summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2017-11-20 10:33:36 +0100
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2017-11-22 11:45:12 +0000
commitbe59a35641616a4cf23c4a13fa0632624b021c1b (patch)
tree9da183258bdf9cc413f7562079d25ace6955467f /chromium/chrome/browser
parentd702e4b6a64574e97fc7df8fe3238cde70242080 (diff)
BASELINE: Update Chromium to 62.0.3202.101
Change-Id: I2d5eca8117600df6d331f6166ab24d943d9814ac Reviewed-by: Alexandru Croitor <alexandru.croitor@qt.io>
Diffstat (limited to 'chromium/chrome/browser')
-rw-r--r--chromium/chrome/browser/BUILD.gn230
-rw-r--r--chromium/chrome/browser/android/vr_shell/BUILD.gn9
-rw-r--r--chromium/chrome/browser/browser_resources.grd38
-rw-r--r--chromium/chrome/browser/chrome_content_browser_manifest_overlay.json18
-rw-r--r--chromium/chrome/browser/chrome_content_gpu_manifest_overlay.json3
-rw-r--r--chromium/chrome/browser/chrome_content_renderer_manifest_overlay.json10
-rw-r--r--chromium/chrome/browser/chrome_content_utility_manifest_overlay.json1
-rw-r--r--chromium/chrome/browser/chrome_notification_types.h19
-rw-r--r--chromium/chrome/browser/chromeos/BUILD.gn119
-rw-r--r--chromium/chrome/browser/chromeos/prefs/ash_pref_connector_manifest.json (renamed from chromium/chrome/browser/prefs/forwarder_manifest.json)8
-rw-r--r--chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc49
-rw-r--r--chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.h8
-rw-r--r--chromium/chrome/browser/devtools/device/adb/adb_client_socket_browsertest.cc3
-rw-r--r--chromium/chrome/browser/devtools/device/android_device_manager.cc23
-rw-r--r--chromium/chrome/browser/devtools/device/android_device_manager.h15
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_device_discovery.cc8
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_device_discovery.h2
-rw-r--r--chromium/chrome/browser/devtools/device/port_forwarding_browsertest.cc1
-rw-r--r--chromium/chrome/browser/devtools/device/port_forwarding_controller.cc7
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc72
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_helper.cc2
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_system_indexer.cc3
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc5
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_watcher.cc4
-rw-r--r--chromium/chrome/browser/devtools/devtools_network_transaction.cc10
-rw-r--r--chromium/chrome/browser/devtools/devtools_network_transaction.h3
-rw-r--r--chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc100
-rw-r--r--chromium/chrome/browser/devtools/devtools_targets_ui.cc4
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings.cc98
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings.h2
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc161
-rw-r--r--chromium/chrome/browser/devtools/devtools_window.cc106
-rw-r--r--chromium/chrome/browser/devtools/devtools_window.h13
-rw-r--r--chromium/chrome/browser/devtools/global_confirm_info_bar.cc28
-rw-r--r--chromium/chrome/browser/devtools/global_confirm_info_bar.h7
-rw-r--r--chromium/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc161
-rw-r--r--chromium/chrome/browser/devtools/remote_debugging_server.cc10
-rw-r--r--chromium/chrome/browser/devtools/serialize_host_descriptions_unittest.cc24
-rw-r--r--chromium/chrome/browser/engagement/BUILD.gn3
-rw-r--r--chromium/chrome/browser/extensions/BUILD.gn64
-rw-r--r--chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc19
-rw-r--r--chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h7
-rw-r--r--chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc30
-rw-r--r--chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h11
-rw-r--r--chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc13
-rw-r--r--chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api_unittest.cc65
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc33
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h14
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/OWNERS6
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc30
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.h7
-rw-r--r--chromium/chrome/browser/extensions/api/browser/browser_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc46
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h5
-rw-r--r--chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc52
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h6
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc25
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc390
-rw-r--r--chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h17
-rw-r--r--chromium/chrome/browser/extensions/api/debugger/debugger_api.cc24
-rw-r--r--chromium/chrome/browser/extensions/api/debugger/debugger_api.h1
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/desktop_capture/OWNERS2
-rw-r--r--chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc35
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h6
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc23
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc165
-rw-r--r--chromium/chrome/browser/extensions/api/dial/dial_api.cc29
-rw-r--r--chromium/chrome/browser/extensions/api/dial/dial_api.h3
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc186
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h41
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc25
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc441
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h159
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api_chromeos_unittest.cc394
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_private_apitest.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc119
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h67
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.cc203
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.h144
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager_chromeos_unittest.cc160
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.cc33
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.h50
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.cc61
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.h38
-rw-r--r--chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc15
-rw-r--r--chromium/chrome/browser/extensions/api/file_system/file_entry_picker.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/history/history_apitest.cc21
-rw-r--r--chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/identity/OWNERS3
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_api.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_api.h17
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_apitest.cc225
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc67
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h6
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc28
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h3
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc36
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc43
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h18
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc83
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation.cc173
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation.h88
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc20
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc17
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_nonchromeos.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc124
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h9
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc27
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc12
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc122
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h52
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc92
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.h71
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc15
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc41
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc86
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h15
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc95
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc47
-rw-r--r--chromium/chrome/browser/extensions/api/launcher_page/OWNERS2
-rw-r--r--chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h2
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_api_unittest.cc83
-rw-r--r--chromium/chrome/browser/extensions/api/mdns/mdns_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc29
-rw-r--r--chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc151
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h54
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc309
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/extension_message_port.h115
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/message_property_provider.cc111
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/message_property_provider.h63
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/message_service.cc998
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/message_service.h327
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_port.cc13
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_port.h17
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc80
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h26
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/music_manager_private/device_id.h10
-rw-r--r--chromium/chrome/browser/extensions/api/music_manager_private/device_id_linux.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/music_manager_private/device_id_mac.cc11
-rw-r--r--chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc11
-rw-r--r--chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc24
-rw-r--r--chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto.cc11
-rw-r--r--chromium/chrome/browser/extensions/api/notifications/notifications_api.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc48
-rw-r--r--chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc64
-rw-r--r--chromium/chrome/browser/extensions/api/page_capture/page_capture_api.h4
-rw-r--r--chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc93
-rw-r--r--chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h85
-rw-r--r--chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc169
-rw-r--r--chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.h65
-rw-r--r--chromium/chrome/browser/extensions/api/preference/preference_api.cc18
-rw-r--r--chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/preference/preferences_private_apitest.cc29
-rw-r--r--chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc89
-rw-r--r--chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/OWNERS1
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc123
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/socket/socket_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h2
-rw-r--r--chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_api.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_test.cc89
-rw-r--r--chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc66
-rw-r--r--chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h12
-rw-r--r--chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS3
-rw-r--r--chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc24
-rw-r--r--chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc21
-rw-r--r--chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h3
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc42
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc118
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc66
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc5
-rw-r--r--chromium/chrome/browser/media/media_engagement_score_details.mojom3
-rw-r--r--chromium/chrome/browser/media/router/BUILD.gn10
-rw-r--r--chromium/chrome/browser/media/router/discovery/BUILD.gn4
-rw-r--r--chromium/chrome/browser/metrics/BUILD.gn14
-rw-r--r--chromium/chrome/browser/printing/background_printing_manager.cc3
-rw-r--r--chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc62
-rw-r--r--chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h18
-rw-r--r--chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc198
-rw-r--r--chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc4
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc2
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc3
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_url_fetcher_unittest.cc3
-rw-r--r--chromium/chrome/browser/printing/pdf_to_emf_converter.cc124
-rw-r--r--chromium/chrome/browser/printing/print_browsertest.cc1
-rw-r--r--chromium/chrome/browser/printing/print_dialog_cloud.cc2
-rw-r--r--chromium/chrome/browser/printing/print_job.cc2
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller.cc5
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller.h9
-rw-r--r--chromium/chrome/browser/printing/print_view_manager.cc5
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_base.cc28
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_base.h6
-rw-r--r--chromium/chrome/browser/printing/printing_init.cc28
-rw-r--r--chromium/chrome/browser/printing/printing_init.h19
-rw-r--r--chromium/chrome/browser/printing/printing_message_filter.cc32
-rw-r--r--chromium/chrome/browser/printing/printing_message_filter.h3
-rw-r--r--chromium/chrome/browser/printing/pwg_raster_converter.cc36
-rw-r--r--chromium/chrome/browser/profiling_host/BUILD.gn29
-rw-r--r--chromium/chrome/browser/resources/BUILD.gn24
-rw-r--r--chromium/chrome/browser/resources/OWNERS1
-rw-r--r--chromium/chrome/browser/resources/app_list/OWNERS2
-rw-r--r--chromium/chrome/browser/resources/app_list/start_page.css2
-rw-r--r--chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd8
-rw-r--r--chromium/chrome/browser/resources/chromeos/compiled_resources2.gyp203
-rw-r--r--chromium/chrome/browser/resources/chromeos/input_method/google_xkb_manifest.json3
-rw-r--r--chromium/chrome/browser/resources/components.css4
-rw-r--r--chromium/chrome/browser/resources/components.html12
-rw-r--r--chromium/chrome/browser/resources/components.js11
-rw-r--r--chromium/chrome/browser/resources/domain_reliability_internals.html3
-rw-r--r--chromium/chrome/browser/resources/engagement/site_engagement.html9
-rw-r--r--chromium/chrome/browser/resources/engagement/site_engagement.js410
-rw-r--r--chromium/chrome/browser/resources/extensions/OWNERS1
-rw-r--r--chromium/chrome/browser/resources/extensions/extension_options_overlay.html3
-rw-r--r--chromium/chrome/browser/resources/extensions/extensions.css2
-rw-r--r--chromium/chrome/browser/resources/extensions/extensions.html2
-rw-r--r--chromium/chrome/browser/resources/gaia_auth_host/authenticator.js7
-rw-r--r--chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js7
-rw-r--r--chromium/chrome/browser/resources/hangout_services/manifest.json2
-rw-r--r--chromium/chrome/browser/resources/hangout_services/thunk.js26
-rw-r--r--chromium/chrome/browser/resources/help/OWNERS6
-rw-r--r--chromium/chrome/browser/resources/help/channel_change_page.css33
-rw-r--r--chromium/chrome/browser/resources/help/channel_change_page.html52
-rw-r--r--chromium/chrome/browser/resources/help/channel_change_page.js261
-rw-r--r--chromium/chrome/browser/resources/help/compiled_resources2.gyp103
-rw-r--r--chromium/chrome/browser/resources/help/help.css7
-rw-r--r--chromium/chrome/browser/resources/help/help.html54
-rw-r--r--chromium/chrome/browser/resources/help/help.js51
-rw-r--r--chromium/chrome/browser/resources/help/help_content.css170
-rw-r--r--chromium/chrome/browser/resources/help/help_content.html134
-rw-r--r--chromium/chrome/browser/resources/help/help_page.html10
-rw-r--r--chromium/chrome/browser/resources/help/help_page.js785
-rw-r--r--chromium/chrome/browser/resources/identity_scope_approval_dialog/OWNERS3
-rw-r--r--chromium/chrome/browser/resources/inspect/inspect.css3
-rw-r--r--chromium/chrome/browser/resources/local_ntp/googlemic_clr_24px.svg7
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.css84
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.html51
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.js183
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_iframe.css2
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_single.css66
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_single.js16
-rw-r--r--chromium/chrome/browser/resources/local_ntp/voice.css431
-rw-r--r--chromium/chrome/browser/resources/local_ntp/voice.js1561
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/BUILD.gn18
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/README.md110
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/actions.js5
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/api_listener.js83
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/app.html7
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/app.js46
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/bookmarks.html2
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/command_manager.html15
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/command_manager.js53
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/compiled_resources2.gyp5
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/constants.js46
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/dialog_focus_manager.js14
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/dnd_chip.html18
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/dnd_manager.js481
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/edit_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/edit_dialog.js4
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/folder_node.html15
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/folder_node.js51
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/item.html40
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/item.js59
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/list.html4
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/list.js70
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/mouse_focus_behavior.js24
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/reducers.js109
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/router.js4
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/store.js4
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/store_client.js6
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/timer_proxy.js58
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/toast_manager.js4
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/toolbar.html24
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/toolbar.js2
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/types.js6
-rw-r--r--chromium/chrome/browser/resources/md_bookmarks/util.js34
-rw-r--r--chromium/chrome/browser/resources/md_downloads/.eslintrc.js13
-rw-r--r--chromium/chrome/browser/resources/md_downloads/BUILD.gn18
-rw-r--r--chromium/chrome/browser/resources/md_downloads/OWNERS2
-rw-r--r--chromium/chrome/browser/resources/md_downloads/action_service.html2
-rw-r--r--chromium/chrome/browser/resources/md_downloads/action_service.js134
-rw-r--r--chromium/chrome/browser/resources/md_downloads/action_service_unittest.gtestjs40
-rw-r--r--chromium/chrome/browser/resources/md_downloads/browser_proxy.html2
-rw-r--r--chromium/chrome/browser/resources/md_downloads/browser_proxy.js95
-rw-r--r--chromium/chrome/browser/resources/md_downloads/compiled_resources2.gyp13
-rw-r--r--chromium/chrome/browser/resources/md_downloads/constants.js4
-rw-r--r--chromium/chrome/browser/resources/md_downloads/externs.js1
-rw-r--r--chromium/chrome/browser/resources/md_downloads/item.html2
-rw-r--r--chromium/chrome/browser/resources/md_downloads/item.js45
-rw-r--r--chromium/chrome/browser/resources/md_downloads/manager.html1
-rw-r--r--chromium/chrome/browser/resources/md_downloads/manager.js43
-rw-r--r--chromium/chrome/browser/resources/md_downloads/toolbar.html10
-rw-r--r--chromium/chrome/browser/resources/md_downloads/toolbar.js16
-rw-r--r--chromium/chrome/browser/resources/md_extensions/.eslintrc.js13
-rw-r--r--chromium/chrome/browser/resources/md_extensions/OWNERS2
-rw-r--r--chromium/chrome/browser/resources/md_extensions/animation_helper.html8
-rw-r--r--chromium/chrome/browser/resources/md_extensions/animation_helper.js96
-rw-r--r--chromium/chrome/browser/resources/md_extensions/code_section.html3
-rw-r--r--chromium/chrome/browser/resources/md_extensions/code_section.js10
-rw-r--r--chromium/chrome/browser/resources/md_extensions/compiled_resources2.gyp38
-rw-r--r--chromium/chrome/browser/resources/md_extensions/detail_view.html134
-rw-r--r--chromium/chrome/browser/resources/md_extensions/detail_view.js41
-rw-r--r--chromium/chrome/browser/resources/md_extensions/drop_overlay.html3
-rw-r--r--chromium/chrome/browser/resources/md_extensions/drop_overlay.js10
-rw-r--r--chromium/chrome/browser/resources/md_extensions/error_page.html22
-rw-r--r--chromium/chrome/browser/resources/md_extensions/error_page.js36
-rw-r--r--chromium/chrome/browser/resources/md_extensions/extensions.js2
-rw-r--r--chromium/chrome/browser/resources/md_extensions/item.html35
-rw-r--r--chromium/chrome/browser/resources/md_extensions/item.js31
-rw-r--r--chromium/chrome/browser/resources/md_extensions/item_list.html12
-rw-r--r--chromium/chrome/browser/resources/md_extensions/item_list.js35
-rw-r--r--chromium/chrome/browser/resources/md_extensions/item_util.js38
-rw-r--r--chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.html5
-rw-r--r--chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.js14
-rw-r--r--chromium/chrome/browser/resources/md_extensions/load_error.html9
-rw-r--r--chromium/chrome/browser/resources/md_extensions/load_error.js6
-rw-r--r--chromium/chrome/browser/resources/md_extensions/manager.html48
-rw-r--r--chromium/chrome/browser/resources/md_extensions/manager.js236
-rw-r--r--chromium/chrome/browser/resources/md_extensions/navigation_helper.js97
-rw-r--r--chromium/chrome/browser/resources/md_extensions/options_dialog.html13
-rw-r--r--chromium/chrome/browser/resources/md_extensions/options_dialog.js41
-rw-r--r--chromium/chrome/browser/resources/md_extensions/pack_dialog.html23
-rw-r--r--chromium/chrome/browser/resources/md_extensions/pack_dialog.js64
-rw-r--r--chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.html33
-rw-r--r--chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.js72
-rw-r--r--chromium/chrome/browser/resources/md_extensions/service.html1
-rw-r--r--chromium/chrome/browser/resources/md_extensions/service.js23
-rw-r--r--chromium/chrome/browser/resources/md_extensions/shortcut_input.html17
-rw-r--r--chromium/chrome/browser/resources/md_extensions/shortcut_input.js4
-rw-r--r--chromium/chrome/browser/resources/md_extensions/sidebar.html4
-rw-r--r--chromium/chrome/browser/resources/md_extensions/sidebar.js45
-rw-r--r--chromium/chrome/browser/resources/md_extensions/toolbar.html16
-rw-r--r--chromium/chrome/browser/resources/md_extensions/toolbar.js4
-rw-r--r--chromium/chrome/browser/resources/md_extensions/view_manager.html26
-rw-r--r--chromium/chrome/browser/resources/md_extensions/view_manager.js126
-rw-r--r--chromium/chrome/browser/resources/md_history/BUILD.gn49
-rw-r--r--chromium/chrome/browser/resources/md_history/OWNERS1
-rw-r--r--chromium/chrome/browser/resources/md_history/app.js4
-rw-r--r--chromium/chrome/browser/resources/md_history/externs.js2
-rw-r--r--chromium/chrome/browser/resources/md_history/history.js2
-rw-r--r--chromium/chrome/browser/resources/md_history/history_item.html3
-rw-r--r--chromium/chrome/browser/resources/md_history/history_item.js4
-rw-r--r--chromium/chrome/browser/resources/md_history/history_list.html8
-rw-r--r--chromium/chrome/browser/resources/md_history/history_list.js28
-rw-r--r--chromium/chrome/browser/resources/md_history/lazy_load.html19
-rw-r--r--chromium/chrome/browser/resources/md_history/query_manager.js17
-rw-r--r--chromium/chrome/browser/resources/md_history/side_bar.html2
-rw-r--r--chromium/chrome/browser/resources/md_history/synced_device_card.html3
-rw-r--r--chromium/chrome/browser/resources/md_history/synced_device_manager.js10
-rw-r--r--chromium/chrome/browser/resources/md_policy/md_policy.html10
-rw-r--r--chromium/chrome/browser/resources/md_policy/policy_resources.grd21
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/control_bar.html3
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/control_bar.js8
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/create_profile.html7
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/create_profile.js4
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/error_dialog.html5
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/import_supervised_user.html11
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.html3
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/supervised_user_learn_more.html3
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/user_manager.html13
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/user_manager_pages.html7
-rw-r--r--chromium/chrome/browser/resources/md_user_manager/user_manager_tutorial.html3
-rw-r--r--chromium/chrome/browser/resources/media/media_engagement.html4
-rw-r--r--chromium/chrome/browser/resources/media/media_engagement.js5
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css3
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html8
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js154
-rw-r--r--chromium/chrome/browser/resources/memory_internals.html28
-rw-r--r--chromium/chrome/browser/resources/memory_internals.js80
-rw-r--r--chromium/chrome/browser/resources/net_internals/browser_bridge.js28
-rw-r--r--chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html96
-rw-r--r--chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js315
-rw-r--r--chromium/chrome/browser/resources/net_internals/hsts_view.html51
-rw-r--r--chromium/chrome/browser/resources/net_internals/hsts_view.js199
-rw-r--r--chromium/chrome/browser/resources/net_internals/import_view.html2
-rw-r--r--chromium/chrome/browser/resources/net_internals/index.html2
-rw-r--r--chromium/chrome/browser/resources/net_internals/index.js2
-rw-r--r--chromium/chrome/browser/resources/net_internals/main.css2
-rw-r--r--chromium/chrome/browser/resources/net_internals/main.js2
-rw-r--r--chromium/chrome/browser/resources/net_internals/quic_view.html2
-rw-r--r--chromium/chrome/browser/resources/ntp4/OWNERS1
-rw-r--r--chromium/chrome/browser/resources/ntp4/apps_page.css11
-rw-r--r--chromium/chrome/browser/resources/ntp4/apps_page.js45
-rw-r--r--chromium/chrome/browser/resources/ntp4/new_tab.css4
-rw-r--r--chromium/chrome/browser/resources/ntp4/new_tab.html15
-rw-r--r--chromium/chrome/browser/resources/ntp4/new_tab.js15
-rw-r--r--chromium/chrome/browser/resources/ntp4/page_list_view.js5
-rw-r--r--chromium/chrome/browser/resources/offline_pages/offline_internals.html21
-rw-r--r--chromium/chrome/browser/resources/offline_pages/offline_internals.js61
-rw-r--r--chromium/chrome/browser/resources/offline_pages/offline_internals_browser_proxy.js6
-rw-r--r--chromium/chrome/browser/resources/options/2x/yellow_gear.pngbin2745 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/options/OWNERS5
-rw-r--r--chromium/chrome/browser/resources/options/alert_overlay.css7
-rw-r--r--chromium/chrome/browser/resources/options/alert_overlay.html13
-rw-r--r--chromium/chrome/browser/resources/options/alert_overlay.js147
-rw-r--r--chromium/chrome/browser/resources/options/autofill_edit_address_overlay.html42
-rw-r--r--chromium/chrome/browser/resources/options/autofill_edit_address_overlay.js350
-rw-r--r--chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.html35
-rw-r--r--chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.js223
-rw-r--r--chromium/chrome/browser/resources/options/autofill_edit_overlay.css76
-rw-r--r--chromium/chrome/browser/resources/options/autofill_options.css68
-rw-r--r--chromium/chrome/browser/resources/options/autofill_options.html33
-rw-r--r--chromium/chrome/browser/resources/options/autofill_options.js218
-rw-r--r--chromium/chrome/browser/resources/options/autofill_options_list.js285
-rw-r--r--chromium/chrome/browser/resources/options/automatic_settings_reset_banner.css82
-rw-r--r--chromium/chrome/browser/resources/options/automatic_settings_reset_banner.html19
-rw-r--r--chromium/chrome/browser/resources/options/automatic_settings_reset_banner.js132
-rw-r--r--chromium/chrome/browser/resources/options/browser_options.css492
-rw-r--r--chromium/chrome/browser/resources/options/browser_options.html1149
-rw-r--r--chromium/chrome/browser/resources/options/browser_options.js2487
-rw-r--r--chromium/chrome/browser/resources/options/browser_options_profile_list.js141
-rw-r--r--chromium/chrome/browser/resources/options/browser_options_startup_page_list.js321
-rw-r--r--chromium/chrome/browser/resources/options/certificate_backup_overlay.html40
-rw-r--r--chromium/chrome/browser/resources/options/certificate_backup_overlay.js114
-rw-r--r--chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.html41
-rw-r--r--chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.js162
-rw-r--r--chromium/chrome/browser/resources/options/certificate_import_error_overlay.html16
-rw-r--r--chromium/chrome/browser/resources/options/certificate_import_error_overlay.js65
-rw-r--r--chromium/chrome/browser/resources/options/certificate_manager.css32
-rw-r--r--chromium/chrome/browser/resources/options/certificate_manager.html143
-rw-r--r--chromium/chrome/browser/resources/options/certificate_manager.js264
-rw-r--r--chromium/chrome/browser/resources/options/certificate_restore_overlay.html21
-rw-r--r--chromium/chrome/browser/resources/options/certificate_restore_overlay.js99
-rw-r--r--chromium/chrome/browser/resources/options/certificate_tree.css17
-rw-r--r--chromium/chrome/browser/resources/options/certificate_tree.js177
-rw-r--r--chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.html13
-rw-r--r--chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.js45
-rw-r--r--chromium/chrome/browser/resources/options/clear_browser_data_overlay.css86
-rw-r--r--chromium/chrome/browser/resources/options/clear_browser_data_overlay.html138
-rw-r--r--chromium/chrome/browser/resources/options/clear_browser_data_overlay.js341
-rw-r--r--chromium/chrome/browser/resources/options/compiled_resources2.gyp101
-rw-r--r--chromium/chrome/browser/resources/options/confirm_dialog.js134
-rw-r--r--chromium/chrome/browser/resources/options/content_settings.css117
-rw-r--r--chromium/chrome/browser/resources/options/content_settings.html649
-rw-r--r--chromium/chrome/browser/resources/options/content_settings.js286
-rw-r--r--chromium/chrome/browser/resources/options/content_settings_exceptions_area.html155
-rw-r--r--chromium/chrome/browser/resources/options/content_settings_exceptions_area.js734
-rw-r--r--chromium/chrome/browser/resources/options/content_settings_ui.js66
-rw-r--r--chromium/chrome/browser/resources/options/controlled_setting.js226
-rw-r--r--chromium/chrome/browser/resources/options/cookies_list.js961
-rw-r--r--chromium/chrome/browser/resources/options/cookies_view.css200
-rw-r--r--chromium/chrome/browser/resources/options/cookies_view.html29
-rw-r--r--chromium/chrome/browser/resources/options/cookies_view.js147
-rw-r--r--chromium/chrome/browser/resources/options/deletable_item_list.js214
-rw-r--r--chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.css7
-rw-r--r--chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.html23
-rw-r--r--chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.css7
-rw-r--r--chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.html17
-rw-r--r--chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.js193
-rw-r--r--chromium/chrome/browser/resources/options/editable_text_field.js372
-rw-r--r--chromium/chrome/browser/resources/options/factory_reset_overlay.css7
-rw-r--r--chromium/chrome/browser/resources/options/factory_reset_overlay.html15
-rw-r--r--chromium/chrome/browser/resources/options/factory_reset_overlay.js47
-rw-r--r--chromium/chrome/browser/resources/options/font_settings.css62
-rw-r--r--chromium/chrome/browser/resources/options/font_settings.html104
-rw-r--r--chromium/chrome/browser/resources/options/font_settings.js252
-rw-r--r--chromium/chrome/browser/resources/options/geolocation_options.js33
-rw-r--r--chromium/chrome/browser/resources/options/googleg.svg7
-rw-r--r--chromium/chrome/browser/resources/options/handler_options.css55
-rw-r--r--chromium/chrome/browser/resources/options/handler_options.html44
-rw-r--r--chromium/chrome/browser/resources/options/handler_options.js97
-rw-r--r--chromium/chrome/browser/resources/options/handler_options_list.js268
-rw-r--r--chromium/chrome/browser/resources/options/home_page_overlay.html45
-rw-r--r--chromium/chrome/browser/resources/options/home_page_overlay.js154
-rw-r--r--chromium/chrome/browser/resources/options/hotword_confirm_dialog.js81
-rw-r--r--chromium/chrome/browser/resources/options/hotword_confirm_overlay.css7
-rw-r--r--chromium/chrome/browser/resources/options/hotword_confirm_overlay.html32
-rw-r--r--chromium/chrome/browser/resources/options/hotword_search_setting_indicator.css12
-rw-r--r--chromium/chrome/browser/resources/options/hotword_search_setting_indicator.js122
-rw-r--r--chromium/chrome/browser/resources/options/i18n_setup.html6
-rw-r--r--chromium/chrome/browser/resources/options/import_data_overlay.css36
-rw-r--r--chromium/chrome/browser/resources/options/import_data_overlay.html120
-rw-r--r--chromium/chrome/browser/resources/options/import_data_overlay.js269
-rw-r--r--chromium/chrome/browser/resources/options/info.svg4
-rw-r--r--chromium/chrome/browser/resources/options/inline_editable_list.js774
-rw-r--r--chromium/chrome/browser/resources/options/language_add_language_overlay.html17
-rw-r--r--chromium/chrome/browser/resources/options/language_add_language_overlay.js75
-rw-r--r--chromium/chrome/browser/resources/options/language_dictionary_overlay.css47
-rw-r--r--chromium/chrome/browser/resources/options/language_dictionary_overlay.html21
-rw-r--r--chromium/chrome/browser/resources/options/language_dictionary_overlay.js117
-rw-r--r--chromium/chrome/browser/resources/options/language_dictionary_overlay_word_list.js267
-rw-r--r--chromium/chrome/browser/resources/options/language_list.js444
-rw-r--r--chromium/chrome/browser/resources/options/language_options.css192
-rw-r--r--chromium/chrome/browser/resources/options/language_options.html142
-rw-r--r--chromium/chrome/browser/resources/options/language_options.js1446
-rw-r--r--chromium/chrome/browser/resources/options/manage_profile_overlay.css163
-rw-r--r--chromium/chrome/browser/resources/options/manage_profile_overlay.html141
-rw-r--r--chromium/chrome/browser/resources/options/manage_profile_overlay.js917
-rw-r--r--chromium/chrome/browser/resources/options/options.html218
-rw-r--r--chromium/chrome/browser/resources/options/options.js316
-rw-r--r--chromium/chrome/browser/resources/options/options_bundle.js130
-rw-r--r--chromium/chrome/browser/resources/options/options_focus_manager.js34
-rw-r--r--chromium/chrome/browser/resources/options/options_page.css451
-rw-r--r--chromium/chrome/browser/resources/options/options_page.js94
-rw-r--r--chromium/chrome/browser/resources/options/options_polymer.html11
-rw-r--r--chromium/chrome/browser/resources/options/password_manager.css33
-rw-r--r--chromium/chrome/browser/resources/options/password_manager.html67
-rw-r--r--chromium/chrome/browser/resources/options/password_manager.js285
-rw-r--r--chromium/chrome/browser/resources/options/password_manager_list.css95
-rw-r--r--chromium/chrome/browser/resources/options/password_manager_list.js552
-rw-r--r--chromium/chrome/browser/resources/options/pref_ui.js639
-rw-r--r--chromium/chrome/browser/resources/options/preferences.js338
-rw-r--r--chromium/chrome/browser/resources/options/profiles_icon_grid.js67
-rw-r--r--chromium/chrome/browser/resources/options/reset_profile_settings_overlay.css65
-rw-r--r--chromium/chrome/browser/resources/options/reset_profile_settings_overlay.html45
-rw-r--r--chromium/chrome/browser/resources/options/reset_profile_settings_overlay.js156
-rw-r--r--chromium/chrome/browser/resources/options/search_box.html11
-rw-r--r--chromium/chrome/browser/resources/options/search_engine_manager.css89
-rw-r--r--chromium/chrome/browser/resources/options/search_engine_manager.html27
-rw-r--r--chromium/chrome/browser/resources/options/search_engine_manager.js133
-rw-r--r--chromium/chrome/browser/resources/options/search_engine_manager_engine_list.js379
-rw-r--r--chromium/chrome/browser/resources/options/search_page.css80
-rw-r--r--chromium/chrome/browser/resources/options/search_page.html12
-rw-r--r--chromium/chrome/browser/resources/options/search_page.js710
-rw-r--r--chromium/chrome/browser/resources/options/secondary_user_banner.html10
-rw-r--r--chromium/chrome/browser/resources/options/settings_dialog.js71
-rw-r--r--chromium/chrome/browser/resources/options/spelling_confirm_overlay.css7
-rw-r--r--chromium/chrome/browser/resources/options/spelling_confirm_overlay.html19
-rw-r--r--chromium/chrome/browser/resources/options/startup_overlay.css45
-rw-r--r--chromium/chrome/browser/resources/options/startup_overlay.html24
-rw-r--r--chromium/chrome/browser/resources/options/startup_overlay.js166
-rw-r--r--chromium/chrome/browser/resources/options/startup_section.html45
-rw-r--r--chromium/chrome/browser/resources/options/subpages_tab_controls.css70
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_create_confirm.css46
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_create_confirm.html14
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_create_confirm.js128
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_import.css84
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_import.html40
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_import.js252
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_learn_more.css41
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_learn_more.html17
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_learn_more.js40
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_list.js120
-rw-r--r--chromium/chrome/browser/resources/options/supervised_user_list_data.js150
-rw-r--r--chromium/chrome/browser/resources/options/sync_section.html74
-rw-r--r--chromium/chrome/browser/resources/options/sync_setup_overlay.css215
-rw-r--r--chromium/chrome/browser/resources/options/sync_setup_overlay.html246
-rw-r--r--chromium/chrome/browser/resources/options/sync_setup_overlay.js833
-rw-r--r--chromium/chrome/browser/resources/options/yellow_gear.pngbin1116 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/options_resources.grd163
-rw-r--r--chromium/chrome/browser/resources/pdf/browser_api.js9
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html7
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js4
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html6
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js4
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js11
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf.js33
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_scripting_api.js4
-rw-r--r--chromium/chrome/browser/resources/pdf/toolbar_manager.js4
-rw-r--r--chromium/chrome/browser/resources/pdf/viewport.js40
-rw-r--r--chromium/chrome/browser/resources/pdf/zoom_manager.js19
-rw-r--r--chromium/chrome/browser/resources/plugin_metadata/plugins_chromeos.json28
-rw-r--r--chromium/chrome/browser/resources/plugin_metadata/plugins_linux.json32
-rw-r--r--chromium/chrome/browser/resources/plugin_metadata/plugins_mac.json32
-rw-r--r--chromium/chrome/browser/resources/plugin_metadata/plugins_win.json32
-rw-r--r--chromium/chrome/browser/resources/policy.css145
-rw-r--r--chromium/chrome/browser/resources/policy.html10
-rw-r--r--chromium/chrome/browser/resources/policy.js573
-rw-r--r--chromium/chrome/browser/resources/policy_base.js581
-rw-r--r--chromium/chrome/browser/resources/policy_common.css142
-rwxr-xr-xchromium/chrome/browser/resources/polymer_css_build_gn.py41
-rw-r--r--chromium/chrome/browser/resources/print_preview/common/overlay.js6
-rw-r--r--chromium/chrome/browser/resources/print_preview/common/search_box.css4
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/app_state.js21
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/destination_store.js72
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/print_ticket_store.js9
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/ticket_items/scaling.js8
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js6
-rw-r--r--chromium/chrome/browser/resources/print_preview/metrics.js33
-rw-r--r--chromium/chrome/browser/resources/print_preview/native_layer.js446
-rw-r--r--chromium/chrome/browser/resources/print_preview/no_destinations_promo.css20
-rw-r--r--chromium/chrome/browser/resources/print_preview/no_destinations_promo.html31
-rw-r--r--chromium/chrome/browser/resources/print_preview/previewarea/preview_area.css4
-rw-r--r--chromium/chrome/browser/resources/print_preview/previewarea/preview_area.js25
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_header.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview.css11
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview.html4
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview.js70
-rw-r--r--chromium/chrome/browser/resources/print_preview/search/destination_list.css9
-rw-r--r--chromium/chrome/browser/resources/print_preview/search/destination_list.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/search/destination_search.css8
-rw-r--r--chromium/chrome/browser/resources/print_preview/search/destination_search.js31
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/advanced_options_settings.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.css2
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js12
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.html1
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/copies_settings.js8
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/more_settings.js8
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/other_options_settings.css8
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/other_options_settings.html8
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/other_options_settings.js8
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/page_settings.css5
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/page_settings.html4
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/page_settings.js10
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/scaling_settings.css7
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/scaling_settings.html10
-rw-r--r--chromium/chrome/browser/resources/print_preview/settings/scaling_settings.js222
-rw-r--r--chromium/chrome/browser/resources/safe_browsing/download_file_types.asciipb3
-rw-r--r--chromium/chrome/browser/resources/set_as_default_browser.css4
-rw-r--r--chromium/chrome/browser/resources/set_as_default_browser.html2
-rw-r--r--chromium/chrome/browser/resources/settings/BUILD.gn49
-rw-r--r--chromium/chrome/browser/resources/settings/OWNERS2
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html10
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html162
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/about_page.html4
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/about_page.js12
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js8
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js4
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js8
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.js6
-rw-r--r--chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html6
-rw-r--r--chromium/chrome/browser/resources/settings/animation/animation.js4
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js21
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js5
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html71
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js30
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/fonts_browser_proxy.js5
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/home_url_input.js4
-rw-r--r--chromium/chrome/browser/resources/settings/basic_page/basic_page.html6
-rw-r--r--chromium/chrome/browser/resources/settings/basic_page/basic_page.js20
-rw-r--r--chromium/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp1
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.html140
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.js395
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html5
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js14
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.html13
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js95
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp15
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.html55
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js80
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.html30
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js96
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.html29
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.js27
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.html37
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js156
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.html105
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js190
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.html1
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.js38
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.html33
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js51
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.html44
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js67
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.html61
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js162
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.html1
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.js271
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.html29
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.js36
-rw-r--r--chromium/chrome/browser/resources/settings/certificate_manager_page/compiled_resources2.gyp118
-rw-r--r--chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.html3
-rw-r--r--chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.js43
-rw-r--r--chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html54
-rw-r--r--chromium/chrome/browser/resources/settings/change_password_page/change_password_page.js39
-rw-r--r--chromium/chrome/browser/resources/settings/change_password_page/compiled_resources2.gyp26
-rw-r--r--chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html38
-rw-r--r--chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js50
-rw-r--r--chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_proxy.js28
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_browser_proxy.js15
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html40
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js41
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.html261
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.js258
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/compiled_resources2.gyp3
-rw-r--r--chromium/chrome/browser/resources/settings/controls/controlled_radio_button.js1
-rw-r--r--chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js4
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_checkbox.html13
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_checkbox.js45
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.js4
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_idle_load.js8
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_toggle_button.html24
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_toggle_button.js40
-rw-r--r--chromium/chrome/browser/resources/settings/date_time_page/date_time_page.html82
-rw-r--r--chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js57
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/device_page_browser_proxy.js1
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/display.html41
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/display.js2
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/keyboard.html26
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/layout_behavior.js4
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/pointers.html45
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/power.html19
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/power.js9
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/storage.js4
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/stylus.html36
-rw-r--r--chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html20
-rw-r--r--chromium/chrome/browser/resources/settings/downloads_page/downloads_page.js8
-rw-r--r--chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html39
-rw-r--r--chromium/chrome/browser/resources/settings/i18n_setup.html2
-rw-r--r--chromium/chrome/browser/resources/settings/images/settings_icon_arrow_back.svg1
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp46
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_config.html3
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html39
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js24
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html10
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js18
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_page.js4
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_shared_css.html4
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html2
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js8
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_apnlist.html43
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_apnlist.js269
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_ip_config.html27
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_ip_config.js212
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_nameservers.html43
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_nameservers.js212
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_property_list.html71
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_property_list.js214
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy.html232
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy.js497
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.html37
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js46
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.html49
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.js55
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html103
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.js132
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_siminfo.html24
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_siminfo.js47
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_summary.js8
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js37
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html18
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html26
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.js8
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp1
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js4
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/languages.js36
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/languages_page.html23
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/languages_page.js36
-rw-r--r--chromium/chrome/browser/resources/settings/lazy_load.html31
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp4
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html68
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.js60
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html18
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.js8
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_url_entry.html5
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html108
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js64
-rw-r--r--chromium/chrome/browser/resources/settings/page_visibility.js29
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js20
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html13
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js8
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp9
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js4
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.html7
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.js67
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.html45
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.js19
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html39
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js37
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_shared_css.html6
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.html2
-rw-r--r--chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.js85
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/change_picture.html1
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js10
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js8
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html8
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/import_data_dialog.js33
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/lock_screen.html52
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/lock_screen.js16
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/lock_state_behavior.js4
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/manage_profile.js8
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.js12
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/people_page.html42
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/people_page.js12
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js4
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js8
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/sync_page.js4
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/user_list.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/user_list.js12
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/users_page.html46
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/users_page.js8
-rw-r--r--chromium/chrome/browser/resources/settings/prefs/prefs.js4
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cloud_printers.html10
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cloud_printers.js2
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html26
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js4
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_util.html14
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html24
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers.js2
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html4
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/printing_page.html9
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/printing_page.js6
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html242
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js21
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html6
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html8
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js12
-rw-r--r--chromium/chrome/browser/resources/settings/route.js38
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/omnibox_extension_entry.html6
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html6
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js8
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.html16
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.js8
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js8
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.html8
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.js3
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html26
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.js80
-rw-r--r--chromium/chrome/browser/resources/settings/search_page/search_page.html48
-rw-r--r--chromium/chrome/browser/resources/settings/search_page/search_page.js35
-rw-r--r--chromium/chrome/browser/resources/settings/search_settings.js26
-rw-r--r--chromium/chrome/browser/resources/settings/settings_icons_css.html3
-rw-r--r--chromium/chrome/browser/resources/settings/settings_main/settings_main.html6
-rw-r--r--chromium/chrome/browser/resources/settings/settings_main/settings_main.js20
-rw-r--r--chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html14
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js36
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.html4
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_section.html5
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_section.js58
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html4
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_subpage_search.html12
-rw-r--r--chromium/chrome/browser/resources/settings/settings_resources.grd146
-rw-r--r--chromium/chrome/browser/resources/settings/settings_shared_css.html58
-rw-r--r--chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html2
-rw-r--r--chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js26
-rw-r--r--chromium/chrome/browser/resources/settings/settings_vars_css.html61
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html9
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.js10
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/category_default_setting.html4
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/category_default_setting.js45
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/constants.js17
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js8
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html20
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js8
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/media_picker.js4
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/pdf_documents.html10
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/protocol_handlers.html8
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_data.html65
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_data.js34
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.html1
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details.html77
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details.js171
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html24
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details_permission.js196
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_list.html12
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_list.js17
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_settings_behavior.js2
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js90
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/usb_devices.html2
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/usb_devices.js4
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html25
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js20
-rw-r--r--chromium/chrome/browser/resources/settings/system_page/system_page.html32
-rw-r--r--chromium/chrome/browser/resources/settings/system_page/system_page.js4
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html2
-rw-r--r--chromium/chrome/browser/resources/snippets_internals.css6
-rw-r--r--chromium/chrome/browser/resources/snippets_internals.html62
-rw-r--r--chromium/chrome/browser/resources/snippets_internals.js34
-rw-r--r--chromium/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.asciipb5
-rw-r--r--chromium/chrome/browser/resources/uber/OWNERS2
-rw-r--r--chromium/chrome/browser/resources/uber/uber_frame.css2
-rwxr-xr-xchromium/chrome/browser/resources/unpack_pak.py2
-rw-r--r--chromium/chrome/browser/resources/vulcanize.gni24
-rwxr-xr-xchromium/chrome/browser/resources/vulcanize_gn.py210
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome.html3
-rw-r--r--chromium/chrome/browser/resources/welcome/win10/inline.html3
-rw-r--r--chromium/chrome/browser/resources/welcome/win10/sectioned.html3
-rw-r--r--chromium/chrome/browser/safe_browsing/BUILD.gn55
-rw-r--r--chromium/chrome/browser/search/BUILD.gn14
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_factory.cc2
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc2
-rw-r--r--chromium/chrome/browser/ui/BUILD.gn241
-rw-r--r--chromium/chrome/browser/ui/cocoa/notifications/BUILD.gn7
-rw-r--r--chromium/chrome/browser/ui/libgtkui/BUILD.gn9
-rw-r--r--chromium/chrome/browser/ui/webui/OWNERS12
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_login_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/browsing_history_handler.cc186
-rw-r--r--chromium/chrome/browser/ui/webui/browsing_history_handler.h26
-rw-r--r--chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc27
-rw-r--r--chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.cc90
-rw-r--r--chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h21
-rw-r--r--chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/certificates_handler.cc (renamed from chromium/chrome/browser/ui/webui/settings/certificates_handler.cc)77
-rw-r--r--chromium/chrome/browser/ui/webui/certificates_handler.h (renamed from chromium/chrome/browser/ui/webui/settings/certificates_handler.h)32
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc44
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.cc68
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h22
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.cc66
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.h15
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc172
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h21
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/choose_mobile_network_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.h2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/image_source.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/DEPS6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc141
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h80
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc69
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h24
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc61
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h22
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc83
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h16
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.h7
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc168
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h7
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.cc157
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.h22
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/sim_unlock_ui.cc21
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc54
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.h38
-rw-r--r--chromium/chrome/browser/ui/webui/components_ui.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/cookies_tree_model_util.h4
-rw-r--r--chromium/chrome/browser/ui/webui/devtools_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc34
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extension_settings_handler.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/help/help_handler.cc766
-rw-r--r--chromium/chrome/browser/ui/webui/help/help_handler.h136
-rw-r--r--chromium/chrome/browser/ui/webui/help/help_utils_chromeos.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/help/help_utils_chromeos.h9
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater.h20
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc49
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h10
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc39
-rw-r--r--chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc25
-rw-r--r--chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/md_downloads/OWNERS1
-rw-r--r--chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc22
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc149
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_ui.h43
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc174
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/memory_internals_ui.cc245
-rw-r--r--chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h28
-rw-r--r--chromium/chrome/browser/ui/webui/net_export_ui.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc120
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/OWNERS1
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc74
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.h46
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc31
-rw-r--r--chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/options/DEPS4
-rw-r--r--chromium/chrome/browser/ui/webui/options/OWNERS8
-rw-r--r--chromium/chrome/browser/ui/webui/options/autofill_options_handler.cc507
-rw-r--r--chromium/chrome/browser/ui/webui/options/autofill_options_handler.h114
-rw-r--r--chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.cc71
-rw-r--r--chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.h34
-rw-r--r--chromium/chrome/browser/ui/webui/options/browser_options_handler.cc2347
-rw-r--r--chromium/chrome/browser/ui/webui/options/browser_options_handler.h464
-rw-r--r--chromium/chrome/browser/ui/webui/options/certificate_manager_handler.cc1239
-rw-r--r--chromium/chrome/browser/ui/webui/options/certificate_manager_handler.h194
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/DEPS3
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/OWNERS6
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc182
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h42
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.cc104
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h40
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc461
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.h145
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc427
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h81
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.cc278
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h86
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.cc77
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.h47
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.cc581
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.h63
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.cc211
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.h62
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc253
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.h60
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.cc208
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h22
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.cc191
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.h47
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.cc157
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.h72
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.cc87
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.h47
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/power_handler.cc173
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/power_handler.h54
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.cc76
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.h33
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.cc46
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.h38
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.cc457
-rw-r--r--chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.h130
-rw-r--r--chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.cc441
-rw-r--r--chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.h108
-rw-r--r--chromium/chrome/browser/ui/webui/options/content_settings_handler.cc1492
-rw-r--r--chromium/chrome/browser/ui/webui/options/content_settings_handler.h285
-rw-r--r--chromium/chrome/browser/ui/webui/options/cookies_view_handler.cc297
-rw-r--r--chromium/chrome/browser/ui/webui/options/cookies_view_handler.h81
-rw-r--r--chromium/chrome/browser/ui/webui/options/core_options_handler.cc664
-rw-r--r--chromium/chrome/browser/ui/webui/options/core_options_handler.h191
-rw-r--r--chromium/chrome/browser/ui/webui/options/create_profile_handler.cc483
-rw-r--r--chromium/chrome/browser/ui/webui/options/create_profile_handler.h171
-rw-r--r--chromium/chrome/browser/ui/webui/options/easy_unlock_handler.cc110
-rw-r--r--chromium/chrome/browser/ui/webui/options/easy_unlock_handler.h43
-rw-r--r--chromium/chrome/browser/ui/webui/options/font_settings_handler.cc279
-rw-r--r--chromium/chrome/browser/ui/webui/options/font_settings_handler.h91
-rw-r--r--chromium/chrome/browser/ui/webui/options/geolocation_options_handler.cc40
-rw-r--r--chromium/chrome/browser/ui/webui/options/geolocation_options_handler.h31
-rw-r--r--chromium/chrome/browser/ui/webui/options/handler_options_handler.cc224
-rw-r--r--chromium/chrome/browser/ui/webui/options/handler_options_handler.h90
-rw-r--r--chromium/chrome/browser/ui/webui/options/help_overlay_handler.cc34
-rw-r--r--chromium/chrome/browser/ui/webui/options/help_overlay_handler.h32
-rw-r--r--chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.cc71
-rw-r--r--chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.h48
-rw-r--r--chromium/chrome/browser/ui/webui/options/import_data_handler.cc272
-rw-r--r--chromium/chrome/browser/ui/webui/options/import_data_handler.h75
-rw-r--r--chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.cc134
-rw-r--r--chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.h61
-rw-r--r--chromium/chrome/browser/ui/webui/options/language_options_handler.cc131
-rw-r--r--chromium/chrome/browser/ui/webui/options/language_options_handler.h52
-rw-r--r--chromium/chrome/browser/ui/webui/options/language_options_handler_common.cc302
-rw-r--r--chromium/chrome/browser/ui/webui/options/language_options_handler_common.h96
-rw-r--r--chromium/chrome/browser/ui/webui/options/manage_profile_handler.cc547
-rw-r--r--chromium/chrome/browser/ui/webui/options/manage_profile_handler.h144
-rw-r--r--chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.cc181
-rw-r--r--chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.h59
-rw-r--r--chromium/chrome/browser/ui/webui/options/options_ui.cc662
-rw-r--r--chromium/chrome/browser/ui/webui/options/options_ui.h164
-rw-r--r--chromium/chrome/browser/ui/webui/options/password_manager_handler.cc398
-rw-r--r--chromium/chrome/browser/ui/webui/options/password_manager_handler.h138
-rw-r--r--chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.cc130
-rw-r--r--chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.h62
-rw-r--r--chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.cc269
-rw-r--r--chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.h91
-rw-r--r--chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.cc329
-rw-r--r--chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.h90
-rw-r--r--chromium/chrome/browser/ui/webui/options/startup_pages_handler.cc272
-rw-r--r--chromium/chrome/browser/ui/webui/options/startup_pages_handler.h95
-rw-r--r--chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.cc168
-rw-r--r--chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.h49
-rw-r--r--chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.cc304
-rw-r--r--chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.h118
-rw-r--r--chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.cc42
-rw-r--r--chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.h33
-rw-r--r--chromium/chrome/browser/ui/webui/options/sync_setup_handler.cc955
-rw-r--r--chromium/chrome/browser/ui/webui/options/sync_setup_handler.h175
-rw-r--r--chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/policy_material_design_ui.cc102
-rw-r--r--chromium/chrome/browser/ui/webui/policy_material_design_ui.h25
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc183
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_handler.cc112
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_handler.h29
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc29
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h13
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc83
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc536
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h172
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_win_unittest.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/printer_handler.h22
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc274
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h121
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/sticky_settings.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/sticky_settings.h9
-rw-r--r--chromium/chrome/browser/ui/webui/profile_helper.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc36
-rw-r--r--chromium/chrome/browser/ui/webui/settings/about_handler.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/settings/about_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/appearance_handler.cc55
-rw-r--r--chromium/chrome/browser/ui/webui/settings/appearance_handler.h6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/change_password_handler.cc56
-rw-r--r--chromium/chrome/browser/ui/webui/settings/change_password_handler.h50
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc81
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc35
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc303
-rw-r--r--chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h127
-rw-r--r--chromium/chrome/browser/ui/webui/settings/downloads_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc464
-rw-r--r--chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc41
-rw-r--r--chromium/chrome/browser/ui/webui/settings/md_settings_ui.h19
-rw-r--r--chromium/chrome/browser/ui/webui/settings/md_settings_ui_browsertest.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/md_settings_ui_unittest.cc20
-rw-r--r--chromium/chrome/browser/ui/webui/settings/people_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc17
-rw-r--r--chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc129
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc201
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler.h25
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc495
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_ui.h10
-rw-r--r--chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc59
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/signin_internals_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/site_settings_helper.cc220
-rw-r--r--chromium/chrome/browser/ui/webui/site_settings_helper.h54
-rw-r--r--chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc136
-rw-r--r--chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc156
-rw-r--r--chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h26
-rw-r--r--chromium/chrome/browser/ui/webui/snippets_internals_ui.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/sync_internals_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h16
-rw-r--r--chromium/chrome/browser/ui/webui/web_ui_test_handler.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc40
-rw-r--r--chromium/chrome/browser/ui/webui/welcome_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/welcome_win10_handler.cc5
-rw-r--r--chromium/chrome/browser/vr/BUILD.gn31
1216 files changed, 21119 insertions, 71762 deletions
diff --git a/chromium/chrome/browser/BUILD.gn b/chromium/chrome/browser/BUILD.gn
index 6cc5deab9c0..27e5f84cb1f 100644
--- a/chromium/chrome/browser/BUILD.gn
+++ b/chromium/chrome/browser/BUILD.gn
@@ -20,7 +20,6 @@ import("//ppapi/features/features.gni")
import("//printing/features/features.gni")
import("//rlz/features/features.gni")
import("//sandbox/features.gni")
-import("//services/service_manager/public/service_manifest.gni")
import("//third_party/protobuf/proto_library.gni")
import("//ui/base/ui_features.gni")
@@ -71,6 +70,8 @@ split_static_library("browser") {
sources = [
"about_flags.cc",
"about_flags.h",
+ "accessibility/accessibility_permission_context.cc",
+ "accessibility/accessibility_permission_context.h",
"after_startup_task_utils.cc",
"after_startup_task_utils.h",
"app_controller_mac.h",
@@ -83,6 +84,8 @@ split_static_library("browser") {
"autocomplete/chrome_autocomplete_provider_client.h",
"autocomplete/chrome_autocomplete_scheme_classifier.cc",
"autocomplete/chrome_autocomplete_scheme_classifier.h",
+ "autocomplete/contextual_suggestions_service_factory.cc",
+ "autocomplete/contextual_suggestions_service_factory.h",
"autocomplete/in_memory_url_index_factory.cc",
"autocomplete/in_memory_url_index_factory.h",
"autocomplete/shortcuts_backend_factory.cc",
@@ -232,6 +235,10 @@ split_static_library("browser") {
"chrome_notification_types.h",
"chrome_quota_permission_context.cc",
"chrome_quota_permission_context.h",
+ "chrome_service.cc",
+ "chrome_service.h",
+ "client_hints/client_hints_observer.cc",
+ "client_hints/client_hints_observer.h",
"command_observer.h",
"command_updater.cc",
"command_updater.h",
@@ -424,8 +431,8 @@ split_static_library("browser") {
"favicon/favicon_utils.h",
"favicon/large_icon_service_factory.cc",
"favicon/large_icon_service_factory.h",
- "feature_engagement_tracker/feature_engagement_tracker_factory.cc",
- "feature_engagement_tracker/feature_engagement_tracker_factory.h",
+ "feature_engagement/tracker_factory.cc",
+ "feature_engagement/tracker_factory.h",
"file_select_helper.cc",
"file_select_helper.h",
"file_select_helper_mac.mm",
@@ -443,6 +450,8 @@ split_static_library("browser") {
"gcm/instance_id/instance_id_profile_service.h",
"gcm/instance_id/instance_id_profile_service_factory.cc",
"gcm/instance_id/instance_id_profile_service_factory.h",
+ "generic_sensor/sensor_permission_context.cc",
+ "generic_sensor/sensor_permission_context.h",
"geolocation/chrome_access_token_store.cc",
"geolocation/chrome_access_token_store.h",
"geolocation/geolocation_permission_context.cc",
@@ -477,9 +486,6 @@ split_static_library("browser") {
"gpu/three_d_api_observer.h",
"hang_monitor/hang_crash_dump_win.cc",
"hang_monitor/hang_crash_dump_win.h",
- "history/browsing_history_service.cc",
- "history/browsing_history_service.h",
- "history/browsing_history_service_handler.h",
"history/chrome_history_backend_client.cc",
"history/chrome_history_backend_client.h",
"history/chrome_history_client.cc",
@@ -490,6 +496,8 @@ split_static_library("browser") {
"history/history_tab_helper.h",
"history/history_utils.cc",
"history/history_utils.h",
+ "history/profile_based_browsing_history_driver.cc",
+ "history/profile_based_browsing_history_driver.h",
"history/top_sites_factory.cc",
"history/top_sites_factory.h",
"history/web_history_service_factory.cc",
@@ -519,12 +527,16 @@ split_static_library("browser") {
"install_verification/win/module_list.h",
"install_verification/win/module_verification_common.cc",
"install_verification/win/module_verification_common.h",
+ "installable/installable_data.h",
"installable/installable_logging.cc",
"installable/installable_logging.h",
"installable/installable_manager.cc",
"installable/installable_manager.h",
"installable/installable_metrics.cc",
"installable/installable_metrics.h",
+ "installable/installable_params.h",
+ "installable/installable_task_queue.cc",
+ "installable/installable_task_queue.h",
"internal_auth.cc",
"internal_auth.h",
"interstitials/chrome_controller_client.cc",
@@ -537,6 +549,8 @@ split_static_library("browser") {
"invalidation/profile_invalidation_provider_factory.h",
"io_thread.cc",
"io_thread.h",
+ "language/chrome_language_detection_client.cc",
+ "language/chrome_language_detection_client.h",
"language/url_language_histogram_factory.cc",
"language/url_language_histogram_factory.h",
"lifetime/application_lifetime.cc",
@@ -703,6 +717,8 @@ split_static_library("browser") {
"net/chrome_url_request_context_getter.h",
"net/crl_set_fetcher.cc",
"net/crl_set_fetcher.h",
+ "net/default_network_context_params.cc",
+ "net/default_network_context_params.h",
"net/dns_probe_runner.cc",
"net/dns_probe_runner.h",
"net/dns_probe_service.cc",
@@ -732,6 +748,10 @@ split_static_library("browser") {
"net/predictor_tab_helper.h",
"net/probe_message.cc",
"net/probe_message.h",
+ "net/profile_network_context_service.cc",
+ "net/profile_network_context_service.h",
+ "net/profile_network_context_service_factory.cc",
+ "net/profile_network_context_service_factory.h",
"net/proxy_service_factory.cc",
"net/proxy_service_factory.h",
"net/quota_policy_channel_id_store.cc",
@@ -765,8 +785,6 @@ split_static_library("browser") {
"notifications/alert_dispatcher_mac.h",
"notifications/desktop_notification_profile_util.cc",
"notifications/desktop_notification_profile_util.h",
- "notifications/login_state_notification_blocker_chromeos.cc",
- "notifications/login_state_notification_blocker_chromeos.h",
"notifications/message_center_display_service.cc",
"notifications/message_center_display_service.h",
"notifications/native_notification_display_service.cc",
@@ -807,6 +825,8 @@ split_static_library("browser") {
"ntp_snippets/content_suggestions_notifier_service_factory.h",
"ntp_snippets/content_suggestions_service_factory.cc",
"ntp_snippets/content_suggestions_service_factory.h",
+ "ntp_snippets/contextual_content_suggestions_service_factory.cc",
+ "ntp_snippets/contextual_content_suggestions_service_factory.h",
"ntp_snippets/download_suggestions_provider.cc",
"ntp_snippets/download_suggestions_provider.h",
"ntp_snippets/ntp_snippets_metrics.cc",
@@ -881,6 +901,8 @@ split_static_library("browser") {
"page_load_metrics/observers/tab_restore_page_load_metrics_observer.h",
"page_load_metrics/observers/ukm_page_load_metrics_observer.cc",
"page_load_metrics/observers/ukm_page_load_metrics_observer.h",
+ "page_load_metrics/observers/use_counter_page_load_metrics_observer.cc",
+ "page_load_metrics/observers/use_counter_page_load_metrics_observer.h",
"page_load_metrics/page_load_metrics_embedder_interface.h",
"page_load_metrics/page_load_metrics_initialize.cc",
"page_load_metrics/page_load_metrics_initialize.h",
@@ -942,6 +964,10 @@ split_static_library("browser") {
"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/chrome_browser_policy_connector.cc",
"policy/chrome_browser_policy_connector.h",
"policy/cloud/cloud_policy_invalidator.cc",
@@ -1099,8 +1125,6 @@ split_static_library("browser") {
"profiles/incognito_helpers.h",
"profiles/incognito_mode_policy_handler.cc",
"profiles/incognito_mode_policy_handler.h",
- "profiles/net_http_session_params_observer.cc",
- "profiles/net_http_session_params_observer.h",
"profiles/off_the_record_profile_impl.cc",
"profiles/off_the_record_profile_impl.h",
"profiles/off_the_record_profile_io_data.cc",
@@ -1215,6 +1239,8 @@ split_static_library("browser") {
"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",
"sessions/chrome_serialized_navigation_driver.cc",
"sessions/chrome_serialized_navigation_driver.h",
"sessions/chrome_tab_restore_service_client.cc",
@@ -1307,6 +1333,8 @@ split_static_library("browser") {
"ssl/insecure_sensitive_input_driver.h",
"ssl/insecure_sensitive_input_driver_factory.cc",
"ssl/insecure_sensitive_input_driver_factory.h",
+ "ssl/mitm_software_blocking_page.cc",
+ "ssl/mitm_software_blocking_page.h",
"ssl/security_state_tab_helper.cc",
"ssl/security_state_tab_helper.h",
"ssl/ssl_blocking_page.cc",
@@ -1415,6 +1443,7 @@ split_static_library("browser") {
"usb/web_usb_histograms.h",
"usb/web_usb_permission_provider.cc",
"usb/web_usb_permission_provider.h",
+ "vr/ui_suppressed_element.h",
"vr/vr_tab_helper.cc",
"vr/vr_tab_helper.h",
"web_data_service_factory.cc",
@@ -1451,6 +1480,20 @@ split_static_library("browser") {
"win/titlebar_config.h",
]
+ if (is_ios) {
+ sources -= [
+ "ssl/mitm_software_blocking_page.cc",
+ "ssl/mitm_software_blocking_page.h",
+ ]
+ }
+
+ if (!is_android) {
+ sources += [
+ "embedded_ui_service_info_factory.cc",
+ "embedded_ui_service_info_factory.h",
+ ]
+ }
+
configs += [
"//build/config/compiler:wexit_time_destructors",
"//build/config:precompiled_headers",
@@ -1485,6 +1528,7 @@ split_static_library("browser") {
"//chrome/browser/devtools",
"//chrome/browser/media:mojo_bindings",
"//chrome/browser/media/router",
+ "//chrome/browser/metrics:expired_histograms_array",
"//chrome/browser/metrics/variations:chrome_ui_string_overrider_factory",
"//chrome/browser/net:probe_message_proto",
"//chrome/browser/profiling_host",
@@ -1522,14 +1566,13 @@ split_static_library("browser") {
"//components/device_event_log",
"//components/dom_distiller/content/browser",
"//components/domain_reliability",
- "//components/doodle",
"//components/download/content/factory",
"//components/download/public",
"//components/error_page/common",
"//components/favicon/content",
"//components/favicon/core",
"//components/favicon_base",
- "//components/feature_engagement_tracker",
+ "//components/feature_engagement",
"//components/flags_ui",
"//components/gcm_driver",
"//components/google/core/browser",
@@ -1542,6 +1585,7 @@ split_static_library("browser") {
"//components/keyed_service/content",
"//components/language/core/browser",
"//components/metrics:call_stacks",
+ "//components/metrics:component_metrics",
"//components/metrics:gpu",
"//components/metrics:net",
"//components/metrics:profiler",
@@ -1549,7 +1593,6 @@ split_static_library("browser") {
"//components/metrics:ui",
"//components/metrics/proto:proto",
"//components/metrics_services_manager",
- "//components/mime_util",
"//components/navigation_interception",
"//components/navigation_metrics",
"//components/net_log",
@@ -1644,6 +1687,7 @@ split_static_library("browser") {
"//crypto:platform",
"//device/base",
"//device/bluetooth:mojo",
+ "//device/hid",
"//device/usb/mojo",
"//device/usb/public/interfaces",
"//device/vr/features",
@@ -1682,9 +1726,10 @@ split_static_library("browser") {
"//sql",
"//storage/browser",
"//storage/common",
+ "//third_party/WebKit/common:blink_common",
"//third_party/WebKit/public:features",
- "//third_party/WebKit/public:image_resources",
"//third_party/WebKit/public:resources",
+ "//third_party/WebKit/public:scaled_resources",
"//third_party/cacheinvalidation",
"//third_party/icu",
"//third_party/leveldatabase",
@@ -1695,6 +1740,7 @@ split_static_library("browser") {
"//third_party/smhasher:cityhash",
"//third_party/webrtc/modules/desktop_capture",
"//third_party/webrtc_overrides",
+ "//third_party/webrtc_overrides:init_webrtc",
"//third_party/widevine/cdm:headers",
"//third_party/zlib",
"//third_party/zlib:minizip",
@@ -1751,8 +1797,6 @@ split_static_library("browser") {
sources += [
"crash_upload_list/crash_upload_list_crashpad.cc",
"crash_upload_list/crash_upload_list_crashpad.h",
- "media_galleries/fileapi/file_path_watcher_util.cc",
- "media_galleries/fileapi/file_path_watcher_util.h",
"media_galleries/fileapi/iapps_data_provider.cc",
"media_galleries/fileapi/iapps_data_provider.h",
"media_galleries/fileapi/itunes_data_provider.cc",
@@ -2151,6 +2195,7 @@ split_static_library("browser") {
]
deps += [
"//components/pdf/browser",
+ "//media:media_features",
"//ppapi/features",
"//ppapi/proxy:ipc",
"//services/device/public/interfaces",
@@ -2160,26 +2205,18 @@ split_static_library("browser") {
if (enable_offline_pages) {
sources += [
- "android/offline_pages/downloads/offline_page_download_bridge.cc",
- "android/offline_pages/downloads/offline_page_download_bridge.h",
- "android/offline_pages/downloads/offline_page_infobar_delegate.cc",
- "android/offline_pages/downloads/offline_page_infobar_delegate.h",
- "android/offline_pages/downloads/offline_page_notification_bridge.cc",
- "android/offline_pages/downloads/offline_page_notification_bridge.h",
- "android/offline_pages/downloads/resource_throttle.cc",
- "android/offline_pages/downloads/resource_throttle.h",
- "android/offline_pages/prefetch/prefetch_background_task.cc",
- "android/offline_pages/prefetch/prefetch_background_task.h",
"offline_pages/background_loader_offliner.cc",
"offline_pages/background_loader_offliner.h",
+ "offline_pages/downloads/resource_throttle.cc",
+ "offline_pages/downloads/resource_throttle.h",
"offline_pages/offline_page_bookmark_observer.cc",
"offline_pages/offline_page_bookmark_observer.h",
"offline_pages/offline_page_info_handler.cc",
"offline_pages/offline_page_info_handler.h",
"offline_pages/offline_page_mhtml_archiver.cc",
"offline_pages/offline_page_mhtml_archiver.h",
- "offline_pages/offline_page_model_factory.cc",
"offline_pages/offline_page_model_factory.h",
+ "offline_pages/offline_page_origin_utils.h",
"offline_pages/offline_page_request_interceptor.cc",
"offline_pages/offline_page_request_interceptor.h",
"offline_pages/offline_page_request_job.cc",
@@ -2196,6 +2233,11 @@ split_static_library("browser") {
"offline_pages/prefetch/offline_metrics_collector_impl.h",
"offline_pages/prefetch/offline_prefetch_download_client.cc",
"offline_pages/prefetch/offline_prefetch_download_client.h",
+ "offline_pages/prefetch/prefetch_background_task.h",
+ "offline_pages/prefetch/prefetch_background_task_handler_impl.cc",
+ "offline_pages/prefetch/prefetch_background_task_handler_impl.h",
+ "offline_pages/prefetch/prefetch_configuration_impl.cc",
+ "offline_pages/prefetch/prefetch_configuration_impl.h",
"offline_pages/prefetch/prefetch_importer_impl.cc",
"offline_pages/prefetch/prefetch_importer_impl.h",
"offline_pages/prefetch/prefetch_instance_id_proxy.cc",
@@ -2215,13 +2257,25 @@ split_static_library("browser") {
sources += [
"offline_pages/android/background_scheduler_bridge.cc",
"offline_pages/android/background_scheduler_bridge.h",
+ "offline_pages/android/cct_origin_observer.cc",
+ "offline_pages/android/cct_origin_observer.h",
"offline_pages/android/cct_request_observer.cc",
"offline_pages/android/cct_request_observer.h",
+ "offline_pages/android/downloads/offline_page_download_bridge.cc",
+ "offline_pages/android/downloads/offline_page_download_bridge.h",
+ "offline_pages/android/downloads/offline_page_infobar_delegate.cc",
+ "offline_pages/android/downloads/offline_page_infobar_delegate.h",
+ "offline_pages/android/downloads/offline_page_notification_bridge.cc",
+ "offline_pages/android/downloads/offline_page_notification_bridge.h",
"offline_pages/android/load_termination_listener_impl.cc",
"offline_pages/android/load_termination_listener_impl.h",
"offline_pages/android/offline_page_bridge.cc",
"offline_pages/android/offline_page_bridge.h",
+ "offline_pages/android/offline_page_model_factory.cc",
+ "offline_pages/android/offline_page_origin_utils_android.cc",
"offline_pages/android/offline_page_utils_android.cc",
+ "offline_pages/android/prefetch_background_task_android.cc",
+ "offline_pages/android/prefetch_background_task_android.h",
"offline_pages/android/prerendering_offliner.cc",
"offline_pages/android/prerendering_offliner.h",
"offline_pages/android/request_coordinator_factory.cc",
@@ -2229,24 +2283,28 @@ split_static_library("browser") {
}
deps += [
"//components/offline_pages/content/background_loader",
+ "//components/offline_pages/content/renovations",
"//components/offline_pages/core",
"//components/offline_pages/core/background:background_offliner",
"//components/offline_pages/core/downloads:offline_pages_ui_adapter",
"//components/offline_pages/core/prefetch",
"//components/offline_pages/core/recent_tabs",
+ "//components/offline_pages/core/renovations",
"//components/offline_pages/core/request_header:request_header",
]
- }
- # Used to build test harness locally. The harness is used manually to
- # produce multiple offline pages to evaluate quality of the snapshots.
- if (enable_offline_pages_harness) {
- sources += [
- "android/offline_pages/evaluation/evaluation_test_scheduler.cc",
- "android/offline_pages/evaluation/evaluation_test_scheduler.h",
- "android/offline_pages/evaluation/offline_page_evaluation_bridge.cc",
- "android/offline_pages/evaluation/offline_page_evaluation_bridge.h",
- ]
+ # Used to build test harness locally. The harness is used manually to
+ # produce multiple offline pages to evaluate quality of the snapshots.
+ # This will only be built iff. |enable_offline_pages_harness| is set while
+ # |enable_offline_pages| and |is_android| are both true.
+ if (enable_offline_pages_harness && is_android) {
+ sources += [
+ "offline_pages/android/evaluation/evaluation_test_scheduler.cc",
+ "offline_pages/android/evaluation/evaluation_test_scheduler.h",
+ "offline_pages/android/evaluation/offline_page_evaluation_bridge.cc",
+ "offline_pages/android/evaluation/offline_page_evaluation_bridge.h",
+ ]
+ }
}
if (enable_hotwording) {
@@ -2285,6 +2343,8 @@ split_static_library("browser") {
"download/notification/download_notification.h",
"download/notification/download_notification_manager.cc",
"download/notification/download_notification_manager.h",
+ "feedback/feedback_util_chromeos.cc",
+ "feedback/feedback_util_chromeos.h",
"media/chromeos_login_media_access_handler.cc",
"media/chromeos_login_media_access_handler.h",
"media/public_session_media_access_handler.cc",
@@ -2310,10 +2370,6 @@ split_static_library("browser") {
"metrics/perf/windowed_incognito_observer.h",
"policy/default_geolocation_policy_handler.cc",
"policy/default_geolocation_policy_handler.h",
- "prefs/active_profile_pref_service.cc",
- "prefs/active_profile_pref_service.h",
- "task_manager/providers/arc/arc_process_filter.cc",
- "task_manager/providers/arc/arc_process_filter.h",
"task_manager/providers/arc/arc_process_task.cc",
"task_manager/providers/arc/arc_process_task.h",
"task_manager/providers/arc/arc_process_task_provider.cc",
@@ -2385,8 +2441,6 @@ split_static_library("browser") {
sources += [
"media/webrtc/desktop_media_list_ash.cc",
"media/webrtc/desktop_media_list_ash.h",
- "renderer_context_menu/open_with_menu_factory_ash.cc",
- "renderer_context_menu/open_with_menu_factory_ash.h",
"signin/signin_error_notifier_ash.cc",
"signin/signin_error_notifier_ash.h",
"signin/signin_error_notifier_factory_ash.cc",
@@ -2455,6 +2509,8 @@ split_static_library("browser") {
"printing/print_view_manager_common.h",
"printing/printer_query.cc",
"printing/printer_query.h",
+ "printing/printing_init.cc",
+ "printing/printing_init.h",
"printing/printing_message_filter.cc",
"printing/printing_message_filter.h",
]
@@ -2505,6 +2561,7 @@ split_static_library("browser") {
"service_process/service_process_control.h",
"service_process/service_process_control_mac.mm",
]
+ deps += [ "//chrome/common:service_process_mojom" ]
} else {
# Partial-only printing support.
sources += [
@@ -2565,8 +2622,12 @@ split_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/upgrade_metrics_provider.cc",
+ "metrics/upgrade_metrics_provider.h",
"net/disk_cache_dir_policy_handler.cc",
"net/disk_cache_dir_policy_handler.h",
+ "notifications/screen_lock_notification_blocker.cc",
+ "notifications/screen_lock_notification_blocker.h",
"platform_util.cc",
"policy/cloud/user_policy_signin_service.cc",
"policy/cloud/user_policy_signin_service.h",
@@ -2605,8 +2666,6 @@ split_static_library("browser") {
"after_startup_task_utils_android.cc",
"android/accessibility/font_size_prefs_android.cc",
"android/accessibility/font_size_prefs_android.h",
- "android/activity_type_ids.cc",
- "android/activity_type_ids.h",
"android/android_theme_resources.h",
"android/app_hooks.cc",
"android/app_hooks.h",
@@ -2633,8 +2692,6 @@ split_static_library("browser") {
"android/browsing_data/browsing_data_counter_bridge.h",
"android/browsing_data/url_filter_bridge.cc",
"android/browsing_data/url_filter_bridge.h",
- "android/chrome_application.cc",
- "android/chrome_application.h",
"android/chrome_backup_agent.cc",
"android/chrome_backup_agent.h",
"android/chrome_backup_watcher.cc",
@@ -2684,6 +2741,7 @@ split_static_library("browser") {
"android/compositor/scene_layer/toolbar_scene_layer.h",
"android/compositor/tab_content_manager.cc",
"android/compositor/tab_content_manager.h",
+ "android/content/content_utils.cc",
"android/contextualsearch/contextual_search_context.cc",
"android/contextualsearch/contextual_search_context.h",
"android/contextualsearch/contextual_search_delegate.cc",
@@ -2755,7 +2813,7 @@ split_static_library("browser") {
"android/download/ui/thumbnail_provider.h",
"android/favicon_helper.cc",
"android/favicon_helper.h",
- "android/feature_engagement_tracker/feature_engagement_tracker_factory_android.cc",
+ "android/feature_engagement/tracker_factory_android.cc",
"android/feature_utilities.cc",
"android/feature_utilities.h",
"android/feedback/connectivity_checker.cc",
@@ -2807,8 +2865,6 @@ split_static_library("browser") {
"android/location_settings_impl.h",
"android/logo_bridge.cc",
"android/logo_bridge.h",
- "android/logo_service.cc",
- "android/logo_service.h",
"android/metrics/launch_metrics.cc",
"android/metrics/uma_session_stats.cc",
"android/metrics/uma_session_stats.h",
@@ -2819,8 +2875,10 @@ split_static_library("browser") {
"android/mojo/chrome_interface_registrar_android.h",
"android/net/external_estimate_provider_android.cc",
"android/net/external_estimate_provider_android.h",
- "android/ntp/content_suggestions_notification_helper.cc",
- "android/ntp/content_suggestions_notification_helper.h",
+ "android/ntp/android_content_suggestions_notifier.cc",
+ "android/ntp/android_content_suggestions_notifier.h",
+ "android/ntp/content_suggestions_notifier.cc",
+ "android/ntp/content_suggestions_notifier.h",
"android/ntp/content_suggestions_notifier_service.cc",
"android/ntp/content_suggestions_notifier_service.h",
"android/ntp/most_visited_sites_bridge.cc",
@@ -2844,6 +2902,7 @@ split_static_library("browser") {
"android/password_ui_view_android.cc",
"android/password_ui_view_android.h",
"android/payments/service_worker_payment_app_bridge.cc",
+ "android/photo_picker_sandbox_bridge.cc",
"android/physical_web/eddystone_encoder_bridge.cc",
"android/physical_web/eddystone_encoder_bridge.h",
"android/physical_web/physical_web_data_source_android.cc",
@@ -2860,6 +2919,7 @@ split_static_library("browser") {
"android/preferences/preferences_launcher.h",
"android/preferences/website_preference_bridge.cc",
"android/profiles/profile_downloader_android.cc",
+ "android/profiles/profile_manager_utils.cc",
"android/provider/blocking_ui_thread_async_request.cc",
"android/provider/blocking_ui_thread_async_request.h",
"android/provider/bookmark_model_observer_task.cc",
@@ -2974,6 +3034,8 @@ split_static_library("browser") {
"lifetime/application_lifetime_android.h",
"media/android/cdm/media_drm_credential_manager.cc",
"media/android/cdm/media_drm_credential_manager.h",
+ "media/android/cdm/media_drm_license_manager.cc",
+ "media/android/cdm/media_drm_license_manager.h",
"media/android/cdm/media_drm_storage_factory.cc",
"media/android/cdm/media_drm_storage_factory.h",
"media/android/remote/record_cast_action.cc",
@@ -3077,6 +3139,7 @@ split_static_library("browser") {
"//components/toolbar",
"//components/web_contents_delegate_android",
"//rlz:rlz_utils",
+ "//sandbox",
"//sandbox:sandbox_features",
"//third_party/android_opengl/etc1",
"//third_party/android_tools:cpu_features",
@@ -3086,9 +3149,6 @@ split_static_library("browser") {
]
deps -= [ "//components/storage_monitor" ]
- if (use_seccomp_bpf) {
- deps += [ "//sandbox/linux:seccomp_bpf" ]
- }
if (enable_supervised_users) {
sources += [
@@ -3126,8 +3186,6 @@ split_static_library("browser") {
"cryptauth/chrome_cryptauth_service_factory.h",
"custom_handlers/register_protocol_handler_permission_request.cc",
"custom_handlers/register_protocol_handler_permission_request.h",
- "custom_home_pages_table_model.cc",
- "custom_home_pages_table_model.h",
"diagnostics/diagnostics_controller.cc",
"diagnostics/diagnostics_controller.h",
"diagnostics/diagnostics_metrics.cc",
@@ -3158,6 +3216,10 @@ split_static_library("browser") {
"feedback/feedback_dialog_utils.h",
"feedback/feedback_profile_observer.cc",
"feedback/feedback_profile_observer.h",
+ "feedback/feedback_uploader_chrome.cc",
+ "feedback/feedback_uploader_chrome.h",
+ "feedback/feedback_uploader_factory_chrome.cc",
+ "feedback/feedback_uploader_factory_chrome.h",
"feedback/show_feedback_page.cc",
"feedback/system_logs/about_system_logs_fetcher.cc",
"feedback/system_logs/about_system_logs_fetcher.h",
@@ -3295,6 +3357,10 @@ split_static_library("browser") {
"metrics/first_web_contents_profiler.h",
"metrics/tab_reactivation_tracker.cc",
"metrics/tab_reactivation_tracker.h",
+ "metrics/tab_stats_data_store.cc",
+ "metrics/tab_stats_data_store.h",
+ "metrics/tab_stats_tracker.cc",
+ "metrics/tab_stats_tracker.h",
"metrics/tab_usage_recorder.cc",
"metrics/tab_usage_recorder.h",
"net/firefox_proxy_settings.cc",
@@ -3321,8 +3387,6 @@ split_static_library("browser") {
"notifications/notifier_source.h",
"notifications/profile_notification.cc",
"notifications/profile_notification.h",
- "notifications/screen_lock_notification_blocker.cc",
- "notifications/screen_lock_notification_blocker.h",
"notifications/system_component_notifier_source_chromeos.cc",
"notifications/system_component_notifier_source_chromeos.h",
"notifications/web_page_notifier_source.cc",
@@ -3331,6 +3395,8 @@ split_static_library("browser") {
"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",
"pdf/pdf_extension_util.cc",
"pdf/pdf_extension_util.h",
"policy/local_sync_policy_handler.cc",
@@ -3363,8 +3429,6 @@ split_static_library("browser") {
"profiles/profile_shortcut_manager.h",
"profiles/profile_window.cc",
"profiles/profile_window.h",
- "renderer_context_menu/open_with_menu_factory.cc",
- "renderer_context_menu/open_with_menu_factory.h",
"renderer_context_menu/render_view_context_menu.cc",
"renderer_context_menu/render_view_context_menu.h",
"renderer_context_menu/spelling_bubble_model.cc",
@@ -3427,6 +3491,10 @@ split_static_library("browser") {
"task_manager/providers/child_process_task.h",
"task_manager/providers/child_process_task_provider.cc",
"task_manager/providers/child_process_task_provider.h",
+ "task_manager/providers/fallback_task_provider.cc",
+ "task_manager/providers/fallback_task_provider.h",
+ "task_manager/providers/render_process_host_task_provider.cc",
+ "task_manager/providers/render_process_host_task_provider.h",
"task_manager/providers/task.cc",
"task_manager/providers/task.h",
"task_manager/providers/task_provider.cc",
@@ -3521,7 +3589,7 @@ split_static_library("browser") {
]
}
- if (enable_pepper_cdms) {
+ if (enable_library_cdms) {
sources += [
"component_updater/widevine_cdm_component_installer.cc",
"component_updater/widevine_cdm_component_installer.h",
@@ -3664,10 +3732,16 @@ split_static_library("browser") {
if ((is_linux && !is_chromeos) || is_win) {
sources += [
- "feature_engagement_tracker/new_tab/new_tab_tracker.cc",
- "feature_engagement_tracker/new_tab/new_tab_tracker.h",
- "feature_engagement_tracker/new_tab/new_tab_tracker_factory.cc",
- "feature_engagement_tracker/new_tab/new_tab_tracker_factory.h",
+ "feature_engagement/feature_tracker.cc",
+ "feature_engagement/feature_tracker.h",
+ "feature_engagement/new_tab/new_tab_tracker.cc",
+ "feature_engagement/new_tab/new_tab_tracker.h",
+ "feature_engagement/new_tab/new_tab_tracker_factory.cc",
+ "feature_engagement/new_tab/new_tab_tracker_factory.h",
+ "feature_engagement/session_duration_updater.cc",
+ "feature_engagement/session_duration_updater.h",
+ "feature_engagement/session_duration_updater_factory.cc",
+ "feature_engagement/session_duration_updater_factory.h",
]
}
@@ -3955,7 +4029,6 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/ApplicationLifetime.java",
"../android/java/src/org/chromium/chrome/browser/BackgroundSyncLauncher.java",
"../android/java/src/org/chromium/chrome/browser/BluetoothChooserDialog.java",
- "../android/java/src/org/chromium/chrome/browser/ChromeApplication.java",
"../android/java/src/org/chromium/chrome/browser/ChromeBackupAgent.java",
"../android/java/src/org/chromium/chrome/browser/ChromeBackupWatcher.java",
"../android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java",
@@ -4000,6 +4073,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java",
"../android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java",
"../android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ToolbarSceneLayer.java",
+ "../android/java/src/org/chromium/chrome/browser/content/ContentUtils.java",
"../android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java",
"../android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuParams.java",
"../android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchContext.java",
@@ -4030,7 +4104,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/engagement/SiteEngagementService.java",
"../android/java/src/org/chromium/chrome/browser/favicon/FaviconHelper.java",
"../android/java/src/org/chromium/chrome/browser/favicon/LargeIconBridge.java",
- "../android/java/src/org/chromium/chrome/browser/feature_engagement_tracker/FeatureEngagementTrackerFactory.java",
+ "../android/java/src/org/chromium/chrome/browser/feature_engagement/TrackerFactory.java",
"../android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java",
"../android/java/src/org/chromium/chrome/browser/feedback/ScreenshotTask.java",
"../android/java/src/org/chromium/chrome/browser/findinpage/FindInPageBridge.java",
@@ -4078,7 +4152,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/notifications/ActionInfo.java",
"../android/java/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridge.java",
"../android/java/src/org/chromium/chrome/browser/notifications/NotificationSettingsBridge.java",
- "../android/java/src/org/chromium/chrome/browser/ntp/ContentSuggestionsNotificationHelper.java",
+ "../android/java/src/org/chromium/chrome/browser/ntp/ContentSuggestionsNotifier.java",
"../android/java/src/org/chromium/chrome/browser/ntp/ForeignSessionHelper.java",
"../android/java/src/org/chromium/chrome/browser/ntp/LogoBridge.java",
"../android/java/src/org/chromium/chrome/browser/ntp/RecentTabsPagePrefs.java",
@@ -4087,6 +4161,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetsLauncher.java",
"../android/java/src/org/chromium/chrome/browser/offlinepages/BackgroundSchedulerBridge.java",
"../android/java/src/org/chromium/chrome/browser/offlinepages/CCTRequestStatus.java",
+ "../android/java/src/org/chromium/chrome/browser/offlinepages/CctOfflinePageModelObserver.java",
"../android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridge.java",
"../android/java/src/org/chromium/chrome/browser/offlinepages/SavePageRequest.java",
"../android/java/src/org/chromium/chrome/browser/offlinepages/downloads/OfflinePageDownloadBridge.java",
@@ -4113,6 +4188,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/payments/SslValidityChecker.java",
"../android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogController.java",
"../android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogDelegate.java",
+ "../android/java/src/org/chromium/chrome/browser/photo_picker/DecoderService.java",
"../android/java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebBroadcastService.java",
"../android/java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java",
"../android/java/src/org/chromium/chrome/browser/policy/PolicyAuditor.java",
@@ -4126,6 +4202,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/prerender/ExternalPrerenderHandler.java",
"../android/java/src/org/chromium/chrome/browser/profiles/Profile.java",
"../android/java/src/org/chromium/chrome/browser/profiles/ProfileDownloader.java",
+ "../android/java/src/org/chromium/chrome/browser/profiles/ProfileManagerUtils.java",
"../android/java/src/org/chromium/chrome/browser/provider/ChromeBrowserProvider.java",
"../android/java/src/org/chromium/chrome/browser/push_messaging/PushMessagingServiceObserver.java",
"../android/java/src/org/chromium/chrome/browser/rappor/RapporServiceBridge.java",
@@ -4158,6 +4235,7 @@ if (is_android) {
"../android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java",
"../android/java/src/org/chromium/chrome/browser/webapps/AddToHomescreenManager.java",
"../android/java/src/org/chromium/chrome/browser/webapps/ChromeWebApkHost.java",
+ "../android/java/src/org/chromium/chrome/browser/webapps/WebApkInstallService.java",
"../android/java/src/org/chromium/chrome/browser/webapps/WebApkInstaller.java",
"../android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateDataFetcher.java",
"../android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java",
@@ -4245,9 +4323,6 @@ grit("resources") {
if (enable_hangout_services_extension) {
defines += [ "enable_hangout_services_extension" ]
}
- if (enable_oop_heap_profiling) {
- defines += [ "enable_oop_heap_profiling" ]
- }
output_dir = "$root_gen_dir/chrome"
outputs = [
@@ -4352,12 +4427,12 @@ static_library("test_support") {
"net/dns_probe_test_util.h",
"net/url_request_mock_util.cc",
"net/url_request_mock_util.h",
+ "notifications/notification_display_service_tester.cc",
+ "notifications/notification_display_service_tester.h",
"notifications/notification_test_util.cc",
"notifications/notification_test_util.h",
"notifications/stub_notification_display_service.cc",
"notifications/stub_notification_display_service.h",
- "notifications/stub_notification_platform_bridge.cc",
- "notifications/stub_notification_platform_bridge.h",
"permissions/mock_permission_request.cc",
"permissions/mock_permission_request.h",
"policy/test/local_policy_test_server.cc",
@@ -4562,7 +4637,7 @@ static_library("test_support") {
]
}
- if (enable_pepper_cdms) {
+ if (enable_library_cdms) {
sources += [
"media/pepper_cdm_test_helper.cc",
"media/pepper_cdm_test_helper.h",
@@ -4625,8 +4700,3 @@ if (enable_rlz_support) {
]
}
}
-
-service_manifest("preferences_forwarder_manifest") {
- name = "preferences_forwarder"
- source = "prefs/forwarder_manifest.json"
-}
diff --git a/chromium/chrome/browser/android/vr_shell/BUILD.gn b/chromium/chrome/browser/android/vr_shell/BUILD.gn
index d4130c2dcba..136ba649fa8 100644
--- a/chromium/chrome/browser/android/vr_shell/BUILD.gn
+++ b/chromium/chrome/browser/android/vr_shell/BUILD.gn
@@ -15,9 +15,11 @@ static_library("vr_android") {
sources = [
"android_ui_gesture_target.cc",
"android_ui_gesture_target.h",
- "elbow_model.cc",
- "elbow_model.h",
+ "android_vsync_helper.cc",
+ "android_vsync_helper.h",
"gl_browser_interface.h",
+ "gvr_util.cc",
+ "gvr_util.h",
"mailbox_to_surface_bridge.cc",
"mailbox_to_surface_bridge.h",
"vr_compositor.cc",
@@ -50,7 +52,6 @@ static_library("vr_android") {
"//cc",
"//chrome/browser/vr:vr_common",
"//components/rappor",
- "//content/public/android:jni",
"//content/public/browser",
"//content/public/common",
"//device/gamepad",
@@ -78,6 +79,8 @@ static_library("vr_android") {
generate_jni("vr_shell_jni_headers") {
sources = [
+ "//chrome/android/java/src/org/chromium/chrome/browser/vr_shell/AndroidUiGestureTarget.java",
+ "//chrome/android/java/src/org/chromium/chrome/browser/vr_shell/AndroidVSyncHelper.java",
"//chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrCoreInfo.java",
"//chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrShellDelegate.java",
"//chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrShellImpl.java",
diff --git a/chromium/chrome/browser/browser_resources.grd b/chromium/chrome/browser/browser_resources.grd
index 0cc04985b9d..8fdd51acda4 100644
--- a/chromium/chrome/browser/browser_resources.grd
+++ b/chromium/chrome/browser/browser_resources.grd
@@ -20,13 +20,6 @@
<if expr="chromeos">
<structure name="IDR_FIRST_RUN_HTML" file="resources\chromeos\first_run\first_run.html" flattenhtml="true" type="chrome_html"/>
<structure name="IDR_FIRST_RUN_JS" file="resources\chromeos\first_run\first_run.js" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_CSS" file="resources\help\help.css" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_HTML" file="resources\help\help.html" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_CONTENT_CSS" file="resources\help\help_content.css" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_CONTENT_HTML" file="resources\help\help_content.html" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_PAGE_HTML" file="resources\help\help_page.html" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_CHANNEL_CHANGE_PAGE_CSS" file="resources\help\channel_change_page.css" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_HELP_CHANNEL_CHANGE_PAGE_HTML" file="resources\help\channel_change_page.html" flattenhtml="true" type="chrome_html" />
</if>
<if expr="not is_android">
<structure name="IDR_INCOGNITO_TAB_HTML" file="resources\ntp4\incognito_tab.html" flattenhtml="true" type="chrome_html" />
@@ -158,6 +151,8 @@
<include name="IDR_MD_DOWNLOADS_DOWNLOADS_HTML" file="resources\md_downloads\downloads.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_MD_DOWNLOADS_ACTION_SERVICE_HTML" file="resources\md_downloads\action_service.html" type="BINDATA" />
<include name="IDR_MD_DOWNLOADS_ACTION_SERVICE_JS" file="resources\md_downloads\action_service.js" type="BINDATA" />
+ <include name="IDR_MD_DOWNLOADS_BROWSER_PROXY_HTML" file="resources\md_downloads\browser_proxy.html" type="BINDATA" />
+ <include name="IDR_MD_DOWNLOADS_BROWSER_PROXY_JS" file="resources\md_downloads\browser_proxy.js" type="BINDATA" />
<include name="IDR_MD_DOWNLOADS_CONSTANTS_HTML" file="resources\md_downloads\constants.html" type="BINDATA" />
<include name="IDR_MD_DOWNLOADS_CONSTANTS_JS" file="resources\md_downloads\constants.js" type="BINDATA" />
<include name="IDR_MD_DOWNLOADS_DOWNLOADS_JS" file="resources\md_downloads\downloads.js" type="BINDATA" />
@@ -181,8 +176,6 @@
<include name="IDR_EXTENSIONS_SHORTCUT_UTIL_HTML" file="resources\extensions\shortcut_util.html" type="BINDATA" />
<include name="IDR_EXTENSIONS_SHORTCUT_UTIL_JS" file="resources\extensions\shortcut_util.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_EXTENSIONS_JS" file="resources\md_extensions\extensions.js" type="BINDATA" />
- <include name="IDR_MD_EXTENSIONS_ANIMATION_HELPER_HTML" file="resources\md_extensions\animation_helper.html" type="BINDATA" />
- <include name="IDR_MD_EXTENSIONS_ANIMATION_HELPER_JS" file="resources\md_extensions\animation_helper.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_CODE_SECTION_HTML" file="resources\md_extensions\code_section.html" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_CODE_SECTION_JS" file="resources\md_extensions\code_section.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_DETAIL_VIEW_HTML" file="resources\md_extensions\detail_view.html" type="BINDATA" />
@@ -210,6 +203,8 @@
<include name="IDR_MD_EXTENSIONS_OPTIONS_DIALOG_JS" file="resources\md_extensions\options_dialog.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_PACK_DIALOG_HTML" file="resources\md_extensions\pack_dialog.html" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_PACK_DIALOG_JS" file="resources\md_extensions\pack_dialog.js" type="BINDATA" />
+ <include name="IDR_MD_EXTENSIONS_PACK_DIALOG_ALERT_HTML" file="resources\md_extensions\pack_dialog_alert.html" type="BINDATA" />
+ <include name="IDR_MD_EXTENSIONS_PACK_DIALOG_ALERT_JS" file="resources\md_extensions\pack_dialog_alert.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_SERVICE_HTML" file="resources\md_extensions\service.html" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_SERVICE_JS" file="resources\md_extensions\service.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_SHORTCUT_INPUT_HTML" file="resources\md_extensions\shortcut_input.html" type="BINDATA" />
@@ -219,6 +214,8 @@
<include name="IDR_MD_EXTENSIONS_TOOLBAR_HTML" file="resources\md_extensions\toolbar.html" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_TOOLBAR_JS" file="resources\md_extensions\toolbar.js" type="BINDATA" />
<include name="IDR_MD_EXTENSIONS_STRINGS_HTML" file="resources\md_extensions\strings.html" type="BINDATA" />
+ <include name="IDR_MD_EXTENSIONS_VIEW_MANAGER_HTML" file="resources\md_extensions\view_manager.html" type="BINDATA" />
+ <include name="IDR_MD_EXTENSIONS_VIEW_MANAGER_JS" file="resources\md_extensions\view_manager.js" type="BINDATA" />
</if>
<include name="IDR_FEEDBACK_MANIFEST" file="resources\feedback\manifest.json" type="BINDATA" />
<if expr="not is_android">
@@ -247,11 +244,6 @@
<include name="IDR_HOTWORD_MANIFEST" file="resources\hotword\manifest.json" type="BINDATA" />
<include name="IDR_HOTWORD_AUDIO_VERIFICATION_MANIFEST" file="resources\hotword_audio_verification\manifest.json" type="BINDATA" />
</if>
- <if expr="chromeos">
- <include name="IDR_HELP_JS" file="resources\help\help.js" flattenhtml="true" type="BINDATA" />
- <include name="IDR_HELP_PAGE_JS" file="resources\help\help_page.js" flattenhtml="true" type="BINDATA" />
- <include name="IDR_CHANNEL_CHANGE_PAGE_JS" file="resources\help\channel_change_page.js" flattenhtml="true" type="BINDATA" />
- </if>
<if expr="not is_android and not is_ios">
<!-- MD Bookmarks. -->
@@ -386,6 +378,8 @@
<include name="IDR_LOCAL_NTP_HTML" file="resources\local_ntp\local_ntp.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_CSS" file="resources\local_ntp\local_ntp.css" flattenhtml="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_JS" file="resources\local_ntp\local_ntp.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_LOCAL_NTP_VOICE_CSS" file="resources\local_ntp\voice.css" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_LOCAL_NTP_VOICE_JS" file="resources\local_ntp\voice.js" flattenhtml="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_MOST_VISITED_IFRAME_CSS" file="resources\local_ntp\most_visited_iframe.css" type="BINDATA" />
@@ -406,10 +400,8 @@
<include name="IDR_ORIGIN_MOJO_JS" file="${root_gen_dir}\url\mojo\origin.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip"/>
<include name="IDR_COMPONENTS_HTML" file="resources\components.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_COMPONENTS_JS" file="resources\components.js" type="BINDATA" />
- <if expr="enable_oop_heap_profiling">
- <include name="IDR_MEMORY_INTERNALS_HTML" file="resources/memory_internals.html" flattenhtml="true" type="BINDATA" />
- <include name="IDR_MEMORY_INTERNALS_JS" file="resources/memory_internals.js" type="BINDATA" />
- </if>
+ <include name="IDR_MEMORY_INTERNALS_HTML" file="resources\memory_internals.html" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_MEMORY_INTERNALS_JS" file="resources\memory_internals.js" type="BINDATA" />
<if expr="enable_plugins">
<include name="IDR_PDF_MANIFEST" file="resources\pdf\manifest.json" type="BINDATA" />
</if>
@@ -436,7 +428,9 @@
</else>
</if>
<include name="IDR_POLICY_HTML" file="resources\policy.html" flattenhtml="true" allowexternalscript="true" type="BINDATA"/>
+ <include name="IDR_POLICY_BASE_JS" file="resources\policy_base.js" type="BINDATA"/>
<include name="IDR_POLICY_JS" file="resources\policy.js" type="BINDATA"/>
+ <include name="IDR_POLICY_COMMON_CSS" file="resources\policy_common.css" type="BINDATA"/>
<if expr="enable_print_preview">
<include name="IDR_PRINT_PREVIEW_HTML" file="resources\print_preview\print_preview.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_PRINT_PREVIEW_JS" file="resources\print_preview\print_preview.js" flattenhtml="true" type="BINDATA" />
@@ -460,7 +454,7 @@
</if>
<include name="IDR_PROFILER_HTML" file="resources\profiler\profiler.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
<include name="IDR_PROFILER_JS" file="resources\profiler\profiler.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_SITE_ENGAGEMENT_HTML" file="resources\engagement\site_engagement.html" flattenhtml="true" type="BINDATA" compress="gzip" />
+ <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_MOJO_JS" file="${root_gen_dir}\chrome\browser\engagement\site_engagement_details.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip" />
<include name="IDR_URL_MOJO_JS" file="${root_gen_dir}\url\mojo\url.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip" />
@@ -517,8 +511,12 @@
<include name="IDR_MERGE_SESSION_LOAD_HTML" file="resources\chromeos\merge_session_load.html" flattenhtml="true" type="BINDATA" />
<include name="IDR_OS_CREDITS_HTML" file="resources\chromeos\about_os_credits.html" flattenhtml="true" type="BINDATA" />
<include name="IDR_PROXY_SETTINGS_HTML" file="resources\chromeos\proxy_settings.html" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_INTERNET_DETAIL_DIALOG_HTML" file="resources\chromeos\internet_detail_dialog.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
+ <include name="IDR_INTERNET_DETAIL_DIALOG_JS" file="resources\chromeos\internet_detail_dialog.js" type="chrome_html" />
<include name="IDR_CERT_MANAGER_DIALOG_HTML" file="resources\chromeos\certificate_manager_dialog.html" flattenhtml="true" type="BINDATA" />
<include name="IDR_BLUETOOTH_PAIR_DEVICE_HTML" file="resources\chromeos\bluetooth_pair_device.html" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_BLUETOOTH_DIALOG_HOST_HTML" file="resources\chromeos\bluetooth_dialog_host.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
+ <include name="IDR_BLUETOOTH_DIALOG_HOST_JS" file="resources\chromeos\bluetooth_dialog_host.js" type="chrome_html" />
<include name="IDR_SIM_UNLOCK_HTML" file="resources\chromeos\sim_unlock.html" flattenhtml="true" type="BINDATA" />
<include name="IDR_SLOW_HTML" file="resources\chromeos\slow.html" flattenhtml="true" type="BINDATA" />
<include name="IDR_SLOW_JS" file="resources\chromeos\slow.js" type="BINDATA" />
@@ -671,7 +669,7 @@
<include name="IDR_WELCOME_WIN10_PIN_LARGE_WEBP" file="resources\welcome\win10\pin-large.webp" type="BINDATA" />
<include name="IDR_WELCOME_WIN10_PIN_SMALL_WEBP" file="resources\welcome\win10\pin-small.webp" type="BINDATA" />
</if>
- <if expr="not is_android and not is_ios">
+ <if expr="not is_ios">
<include name="IDR_SSL_ERROR_ASSISTANT_PB" file="${root_gen_dir}/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.pb" use_base_dir="false" type="BINDATA" />
</if>
<if expr="is_android or is_linux">
diff --git a/chromium/chrome/browser/chrome_content_browser_manifest_overlay.json b/chromium/chrome/browser/chrome_content_browser_manifest_overlay.json
index 92120fdb3aa..e659aec2f7d 100644
--- a/chromium/chrome/browser/chrome_content_browser_manifest_overlay.json
+++ b/chromium/chrome/browser/chrome_content_browser_manifest_overlay.json
@@ -17,27 +17,35 @@
"safe_browsing::mojom::SafeBrowsing",
"spellcheck::mojom::SpellCheckHost",
"spellcheck::mojom::SpellCheckPanelHost",
- "startup_metric_utils::mojom::StartupMetricHost",
"translate::mojom::ContentTranslateDriver"
- ],
+ ],
"url_keyed_metrics": [
"ukm::mojom::UkmRecorderInterface"
],
"gpu": [
"metrics::mojom::CallStackProfileCollector"
],
- "ime:ime_driver": []
+ "ime:ime_driver": [],
+ "memlog_client": [
+ "profiling::mojom::MemlogClient"
+ ]
},
"requires": {
"accessibility_autoclick": [ "ash:autoclick" ],
"ash": [ "ash", "display" ],
// Only used in classic ash case.
+ "ash_pref_connector": [ "pref_connector" ],
+ // Only used in classic ash case.
"chrome": [ "input_device_controller" ],
+ "content_browser": [ "memlog_client" ],
"device": [ "device:fingerprint" ],
"identity": [ "identity_manager" ],
+ // Only used in classic ash case.
+ "local_state": [ "pref_client" ],
"nacl_broker": [ "browser" ],
"nacl_loader": [ "browser" ],
- "preferences_forwarder": [ "pref_client" ],
+ "profile_import": [ "import" ],
+ "profiling": [ "memlog" ],
"preferences": [ "pref_client", "pref_control" ],
"ui": [
"display_controller",
@@ -54,7 +62,9 @@
"autofill::mojom::PasswordManagerDriver",
"blink::mojom::BudgetService",
"blink::mojom::InstalledAppProvider",
+ "blink::mojom::MediaDownloadInProductHelp",
"blink::mojom::ShareService",
+ "blink::mojom::TextSuggestionHost",
"bluetooth::mojom::AdapterFactory",
"chrome::mojom::OpenSearchDocumentDescriptionHandler",
"chrome::mojom::PrerenderCanceler",
diff --git a/chromium/chrome/browser/chrome_content_gpu_manifest_overlay.json b/chromium/chrome/browser/chrome_content_gpu_manifest_overlay.json
index 6f9513d7d58..b3823374219 100644
--- a/chromium/chrome/browser/chrome_content_gpu_manifest_overlay.json
+++ b/chromium/chrome/browser/chrome_content_gpu_manifest_overlay.json
@@ -8,7 +8,8 @@
"arc::mojom::VideoDecodeClient",
"arc::mojom::VideoEncodeAccelerator",
"arc::mojom::VideoEncodeClient",
- "chrome::mojom::ResourceUsageReporter"
+ "chrome::mojom::ResourceUsageReporter",
+ "profiling::mojom::MemlogClient"
]
}
}
diff --git a/chromium/chrome/browser/chrome_content_renderer_manifest_overlay.json b/chromium/chrome/browser/chrome_content_renderer_manifest_overlay.json
index 128cd092733..d26bc66362b 100644
--- a/chromium/chrome/browser/chrome_content_renderer_manifest_overlay.json
+++ b/chromium/chrome/browser/chrome_content_renderer_manifest_overlay.json
@@ -5,8 +5,13 @@
"provides": {
"browser": [
"chrome::mojom::ResourceUsageReporter",
- "spellcheck::mojom::SpellChecker"
+ "chrome::mojom::SearchBouncer",
+ "spellcheck::mojom::SpellChecker",
+ "profiling::mojom::MemlogClient"
]
+ },
+ "requires": {
+ "chrome": [ "renderer" ]
}
},
"navigation:frame": {
@@ -18,7 +23,10 @@
"blink::mojom::document_metadata::CopylessPaste",
"chrome::mojom::ImageContextMenuRenderer",
"chrome::mojom::InsecureContentRenderer",
+ "chrome::mojom::PhishingDetector",
"chrome::mojom::ThumbnailCapturer",
+ "chrome::mojom::WebUITester",
+ "chrome::mojom::ChromeRenderFrame",
"contextual_search::mojom::OverlayPageNotifierService",
"dom_distiller::mojom::DistillerPageNotifierService",
"spellcheck::mojom::SpellCheckPanel"
diff --git a/chromium/chrome/browser/chrome_content_utility_manifest_overlay.json b/chromium/chrome/browser/chrome_content_utility_manifest_overlay.json
index df19464de55..07008f85cdd 100644
--- a/chromium/chrome/browser/chrome_content_utility_manifest_overlay.json
+++ b/chromium/chrome/browser/chrome_content_utility_manifest_overlay.json
@@ -18,6 +18,7 @@
"extensions::mojom::WiFiCredentialsGetter",
"net::interfaces::ProxyResolverFactory",
"payments::mojom::PaymentManifestParser",
+ "profiling::mojom::MemlogClient",
"safe_json::mojom::SafeJsonParser"
]
}
diff --git a/chromium/chrome/browser/chrome_notification_types.h b/chromium/chrome/browser/chrome_notification_types.h
index 666b99ba54e..d62cafd4497 100644
--- a/chromium/chrome/browser/chrome_notification_types.h
+++ b/chromium/chrome/browser/chrome_notification_types.h
@@ -116,13 +116,6 @@ enum NotificationType {
// Details<InfoBar::RemovedDetails>.
NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED,
-#if BUILDFLAG(ENABLE_EXTENSIONS)
- // This notification is sent when extensions::TabHelper::SetExtensionApp is
- // invoked. The source is the extensions::TabHelper SetExtensionApp was
- // invoked on.
- NOTIFICATION_TAB_CONTENTS_APPLICATION_EXTENSION_CHANGED,
-#endif
-
// Tabs --------------------------------------------------------------------
// Sent when a tab is added to a WebContentsDelegate. The source is the
@@ -240,11 +233,6 @@ enum NotificationType {
// Non-history storage services --------------------------------------------
- // A safe browsing database update completed. Source is the
- // SafeBrowsingService and the details are a bool indicating whether the
- // update was successful.
- NOTIFICATION_SAFE_BROWSING_UPDATE_COMPLETE,
-
// Autocomplete ------------------------------------------------------------
// Sent by the autocomplete controller when done. The source is the
@@ -275,13 +263,6 @@ enum NotificationType {
// content::WebContents object, the details are None.
NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
- // Sync --------------------------------------------------------------------
-
- // The session service has been saved. This notification type is only sent
- // if there were new SessionService commands to save, and not for no-op save
- // operations.
- NOTIFICATION_SESSION_SERVICE_SAVED,
-
// Cookies -----------------------------------------------------------------
#if BUILDFLAG(ENABLE_EXTENSIONS)
diff --git a/chromium/chrome/browser/chromeos/BUILD.gn b/chromium/chrome/browser/chromeos/BUILD.gn
index 1dbe39bbcc0..5861060d88f 100644
--- a/chromium/chrome/browser/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/chromeos/BUILD.gn
@@ -7,10 +7,12 @@ import("//build/config/ui.gni")
import("//extensions/features/features.gni")
import("//media/media_options.gni")
import("//printing/features/features.gni")
+import("//services/service_manager/public/service_manifest.gni")
import("//third_party/protobuf/proto_library.gni")
import("//ui/ozone/ozone.gni")
assert(is_chromeos)
+assert(use_ozone)
source_set("chromeos") {
assert(enable_extensions, "ChromeOS Chrome has to be built with extensions")
@@ -39,6 +41,7 @@ source_set("chromeos") {
deps = [
# TODO(tbarzic): Cleanup this list.
":attestation_proto",
+ ":device_policy_remover_generated",
"//apps",
"//ash",
"//ash:ash_with_content",
@@ -90,7 +93,6 @@ source_set("chromeos") {
"//components/metrics:serialization",
"//components/metrics/leak_detector",
"//components/metrics/proto",
- "//components/mime_util",
"//components/onc",
"//components/ownership",
"//components/pairing",
@@ -103,6 +105,7 @@ source_set("chromeos") {
"//components/proxy_config",
"//components/quirks",
"//components/rappor",
+ "//components/renderer_context_menu",
"//components/safe_browsing:csd_proto",
"//components/safe_browsing_db:metadata_proto",
"//components/safe_json",
@@ -139,6 +142,7 @@ source_set("chromeos") {
"//extensions/browser",
"//extensions/browser/kiosk",
"//gpu",
+ "//gpu/ipc/host:host",
"//mash/public/interfaces",
"//media",
"//media/mojo/interfaces",
@@ -146,6 +150,7 @@ source_set("chromeos") {
"//net",
"//ppapi/proxy:ipc", # For PpapiMsg_LoadPlugin
"//services/device/public/interfaces",
+ "//services/preferences/public/interfaces",
"//services/service_manager/public/cpp",
"//services/service_manager/runner/common",
"//services/ui/public/interfaces/display",
@@ -158,6 +163,7 @@ source_set("chromeos") {
"//skia",
"//storage/browser",
"//storage/common",
+ "//third_party/WebKit/common:blink_common",
"//third_party/adobe/flash:flapper_version_h",
"//third_party/cacheinvalidation",
"//third_party/icu",
@@ -187,6 +193,7 @@ source_set("chromeos") {
"//ui/keyboard",
"//ui/keyboard:mojom",
"//ui/message_center",
+ "//ui/ozone",
"//ui/shell_dialogs",
"//ui/snapshot",
"//ui/surface",
@@ -323,6 +330,8 @@ source_set("chromeos") {
"arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.h",
"arc/boot_phase_monitor/arc_instance_throttle.cc",
"arc/boot_phase_monitor/arc_instance_throttle.h",
+ "arc/cast_receiver/arc_cast_receiver_service.cc",
+ "arc/cast_receiver/arc_cast_receiver_service.h",
"arc/downloads_watcher/arc_downloads_watcher_service.cc",
"arc/downloads_watcher/arc_downloads_watcher_service.h",
"arc/enterprise/arc_enterprise_reporting_service.cc",
@@ -353,6 +362,8 @@ source_set("chromeos") {
"arc/fileapi/arc_documents_provider_util.h",
"arc/fileapi/arc_documents_provider_watcher_manager.cc",
"arc/fileapi/arc_documents_provider_watcher_manager.h",
+ "arc/fileapi/arc_file_system_bridge.cc",
+ "arc/fileapi/arc_file_system_bridge.h",
"arc/fileapi/arc_file_system_mounter.cc",
"arc/fileapi/arc_file_system_mounter.h",
"arc/fileapi/arc_file_system_operation_runner.cc",
@@ -361,18 +372,26 @@ source_set("chromeos") {
"arc/fileapi/arc_file_system_operation_runner_util.h",
"arc/fileapi/arc_media_view_util.cc",
"arc/fileapi/arc_media_view_util.h",
+ "arc/fileapi/chrome_content_provider_url_util.cc",
+ "arc/fileapi/chrome_content_provider_url_util.h",
+ "arc/fileapi/file_stream_forwarder.cc",
+ "arc/fileapi/file_stream_forwarder.h",
"arc/intent_helper/arc_external_protocol_dialog.cc",
"arc/intent_helper/arc_external_protocol_dialog.h",
"arc/intent_helper/arc_navigation_throttle.cc",
"arc/intent_helper/arc_navigation_throttle.h",
"arc/intent_helper/arc_settings_service.cc",
"arc/intent_helper/arc_settings_service.h",
+ "arc/intent_helper/open_with_menu.cc",
+ "arc/intent_helper/open_with_menu.h",
"arc/kiosk/arc_kiosk_bridge.cc",
"arc/kiosk/arc_kiosk_bridge.h",
"arc/notification/arc_boot_error_notification.cc",
"arc/notification/arc_boot_error_notification.h",
"arc/notification/arc_provision_notification_service.cc",
"arc/notification/arc_provision_notification_service.h",
+ "arc/oemcrypto/arc_oemcrypto_bridge.cc",
+ "arc/oemcrypto/arc_oemcrypto_bridge.h",
"arc/optin/arc_optin_preference_handler.cc",
"arc/optin/arc_optin_preference_handler.h",
"arc/optin/arc_optin_preference_handler_observer.h",
@@ -471,8 +490,6 @@ source_set("chromeos") {
"dbus/screen_lock_service_provider.h",
"device/input_service_proxy.cc",
"device/input_service_proxy.h",
- "device_uma.cc",
- "device_uma.h",
"display/display_configuration_observer.cc",
"display/display_configuration_observer.h",
"display/display_preferences.cc",
@@ -525,10 +542,6 @@ source_set("chromeos") {
"events/event_rewriter_delegate_impl.h",
"events/keyboard_driven_event_rewriter.cc",
"events/keyboard_driven_event_rewriter.h",
- "events/system_key_event_listener.cc",
- "events/system_key_event_listener.h",
- "events/xinput_hierarchy_changed_event_listener.cc",
- "events/xinput_hierarchy_changed_event_listener.h",
"extensions/active_tab_permission_granter_delegate_chromeos.cc",
"extensions/active_tab_permission_granter_delegate_chromeos.h",
"extensions/default_app_order.cc",
@@ -573,8 +586,6 @@ source_set("chromeos") {
"external_metrics.h",
"external_protocol_dialog.cc",
"external_protocol_dialog.h",
- "feedback_util.cc",
- "feedback_util.h",
"file_manager/app_id.h",
"file_manager/arc_file_tasks.cc",
"file_manager/arc_file_tasks.h",
@@ -780,6 +791,8 @@ source_set("chromeos") {
"input_method/mode_indicator_controller.h",
"language_preferences.cc",
"language_preferences.h",
+ "launchable.cc",
+ "launchable.h",
"launcher_search_provider/error_reporter.cc",
"launcher_search_provider/error_reporter.h",
"launcher_search_provider/launcher_search_provider_service.cc",
@@ -1237,8 +1250,11 @@ source_set("chromeos") {
"policy/device_local_account_policy_store.h",
"policy/device_network_configuration_updater.cc",
"policy/device_network_configuration_updater.h",
+ "policy/device_off_hours_controller.cc",
+ "policy/device_off_hours_controller.h",
"policy/device_policy_decoder_chromeos.cc",
"policy/device_policy_decoder_chromeos.h",
+ "policy/device_policy_remover.h",
"policy/device_status_collector.cc",
"policy/device_status_collector.h",
"policy/display_rotation_default_handler.cc",
@@ -1335,6 +1351,8 @@ source_set("chromeos") {
"power/renderer_freezer.h",
"preferences.cc",
"preferences.h",
+ "prefs/pref_connector_service.cc",
+ "prefs/pref_connector_service.h",
"printing/combining_printer_detector.cc",
"printing/combining_printer_detector.h",
"printing/cups_print_job.cc",
@@ -1449,7 +1467,6 @@ source_set("chromeos") {
"system/input_device_settings.cc",
"system/input_device_settings.h",
"system/input_device_settings_impl_ozone.cc",
- "system/input_device_settings_impl_x11.cc",
"system/pointer_device_observer.cc",
"system/pointer_device_observer.h",
"system/system_clock.cc",
@@ -1478,7 +1495,6 @@ source_set("chromeos") {
"system_logs/single_log_file_log_source.h",
"system_logs/touch_log_source.h",
"system_logs/touch_log_source_ozone.cc",
- "system_logs/touch_log_source_x11.cc",
"tether/fake_tether_service.cc",
"tether/fake_tether_service.h",
"tether/tether_service.cc",
@@ -1582,34 +1598,6 @@ source_set("chromeos") {
"extensions/wallpaper_private_api.cc",
"extensions/wallpaper_private_api.h",
]
- if (use_x11 || ozone_platform_x11) {
- deps += [ "//ui/base/x" ]
- }
- if (use_x11) {
- configs += [ "//build/config/linux:x11" ]
- deps += [
- "//ui/events/devices",
- "//ui/events/devices/x11",
- "//ui/gfx/x",
- ]
- sources -= [
- "system/input_device_settings_impl_ozone.cc",
- "system_logs/touch_log_source_ozone.cc",
- ]
- } else {
- assert(use_ozone, "Either use_x11 or use_ozone has to be specified.")
- deps += [ "//ui/ozone" ]
- sources -= [
- "device_uma.cc",
- "device_uma.h",
- "events/system_key_event_listener.cc",
- "events/system_key_event_listener.h",
- "events/xinput_hierarchy_changed_event_listener.cc",
- "events/xinput_hierarchy_changed_event_listener.h",
- "system/input_device_settings_impl_x11.cc",
- "system_logs/touch_log_source_x11.cc",
- ]
- }
if (use_cups) {
sources += [
@@ -1694,7 +1682,6 @@ source_set("unit_tests") {
"../metrics/leak_detector/leak_detector_controller_unittest.cc",
"../metrics/perf/cpu_identity_unittest.cc",
"../metrics/perf/random_selector_unittest.cc",
- "../notifications/login_state_notification_blocker_chromeos_unittest.cc",
"../policy/default_geolocation_policy_handler_unittest.cc",
"../ui/browser_finder_chromeos_unittest.cc",
"accessibility/magnification_manager_unittest.cc",
@@ -1706,6 +1693,7 @@ source_set("unit_tests") {
"arc/arc_support_host_unittest.cc",
"arc/arc_util_unittest.cc",
"arc/bluetooth/arc_bluetooth_bridge_unittest.cc",
+ "arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc",
"arc/downloads_watcher/arc_downloads_watcher_service_unittest.cc",
"arc/extensions/arc_support_message_host_unittest.cc",
"arc/fileapi/arc_content_file_system_async_file_util_unittest.cc",
@@ -1714,13 +1702,17 @@ source_set("unit_tests") {
"arc/fileapi/arc_documents_provider_root_unittest.cc",
"arc/fileapi/arc_documents_provider_util_unittest.cc",
"arc/fileapi/arc_file_system_operation_runner_unittest.cc",
+ "arc/fileapi/chrome_content_provider_url_util_unittest.cc",
+ "arc/fileapi/file_stream_forwarder_unittest.cc",
"arc/intent_helper/arc_external_protocol_dialog_unittest.cc",
"arc/intent_helper/arc_navigation_throttle_unittest.cc",
+ "arc/intent_helper/open_with_menu_unittest.cc",
"arc/kiosk/arc_kiosk_bridge_unittest.cc",
"arc/notification/arc_provision_notification_service_unittest.cc",
"arc/optin/arc_terms_of_service_default_negotiator_unittest.cc",
"arc/policy/arc_policy_bridge_unittest.cc",
"arc/process/arc_process_unittest.cc",
+ "arc/tts/arc_tts_service_unittest.cc",
"attestation/attestation_ca_client_unittest.cc",
"attestation/attestation_policy_observer_unittest.cc",
"attestation/fake_certificate.cc",
@@ -1896,6 +1888,7 @@ source_set("unit_tests") {
"printing/combining_printer_detector_unittest.cc",
"printing/cups_printers_manager_unittest.cc",
"printing/printer_event_tracker_unittest.cc",
+ "printing/printers_sync_bridge_unittest.cc",
"printing/specifics_translation_unittest.cc",
"printing/synced_printers_manager_unittest.cc",
"profiles/profile_list_chromeos_unittest.cc",
@@ -1908,8 +1901,6 @@ source_set("unit_tests") {
"settings/device_settings_provider_unittest.cc",
"settings/device_settings_service_unittest.cc",
"settings/install_attributes_unittest.cc",
- "settings/scoped_cros_settings_test_helper.cc",
- "settings/scoped_cros_settings_test_helper.h",
"settings/session_manager_operation_unittest.cc",
"settings/shutdown_policy_handler_unittest.cc",
"settings/stub_cros_settings_provider_unittest.cc",
@@ -2034,3 +2025,47 @@ proto_library("attestation_proto") {
"attestation/attestation_key_payload.proto",
]
}
+
+service_manifest("ash_pref_connector_manifest") {
+ name = "ash_pref_connector"
+ source = "prefs/ash_pref_connector_manifest.json"
+}
+
+device_policy_remover_path = "$target_gen_dir/device_policy_remover.cc"
+
+action("device_policy_remover_generate") {
+ script = "policy/tools/generate_device_policy_remover.py"
+ descriptor_pool_path = "//third_party/protobuf/python"
+ symbol_database_path = "$root_build_dir/pyproto"
+ chrome_device_policy_pb2_path =
+ "$root_build_dir/pyproto/chrome/browser/chromeos/policy/proto"
+
+ outputs = [
+ device_policy_remover_path,
+ ]
+
+ args = [
+ # generated file name
+ rebase_path(device_policy_remover_path),
+
+ # directories for PATH variable to compile generated file
+ rebase_path(descriptor_pool_path),
+ rebase_path(symbol_database_path),
+ rebase_path(chrome_device_policy_pb2_path),
+ ]
+
+ public_deps = [
+ ":device_policy_proto",
+ "//third_party/protobuf:py_proto",
+ ]
+}
+
+static_library("device_policy_remover_generated") {
+ sources = [
+ device_policy_remover_path,
+ ]
+
+ public_deps = [
+ ":device_policy_remover_generate",
+ ]
+}
diff --git a/chromium/chrome/browser/prefs/forwarder_manifest.json b/chromium/chrome/browser/chromeos/prefs/ash_pref_connector_manifest.json
index 93a1576a31b..e1c86f75c12 100644
--- a/chromium/chrome/browser/prefs/forwarder_manifest.json
+++ b/chromium/chrome/browser/chromeos/prefs/ash_pref_connector_manifest.json
@@ -1,11 +1,11 @@
{
- "name": "preferences_forwarder",
- "display_name": "Preferences Forwarder",
+ "name": "ash_pref_connector",
+ "display_name": "Ash Pref Connector",
"interface_provider_specs": {
"service_manager:connector": {
"provides": {
- "pref_client": [
- "prefs::mojom::PrefStoreConnector"
+ "pref_connector": [
+ "ash::mojom::PrefConnector"
]
},
"requires": {
diff --git a/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc b/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
index 75b04a7bff9..8d5bc7caef0 100644
--- a/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
+++ b/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
@@ -17,6 +17,7 @@
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/browser/subresource_filter/chrome_subresource_filter_client.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/browser_window.h"
@@ -108,6 +109,15 @@ bool GetExtensionInfo(content::WebContents* wc,
return false;
}
+void ToggleAdBlocking(bool enabled, content::DevToolsAgentHost* agent_host) {
+ if (content::WebContents* web_contents = agent_host->GetWebContents()) {
+ if (auto* client =
+ ChromeSubresourceFilterClient::FromWebContents(web_contents)) {
+ client->ToggleForceActivationInCurrentWebContents(enabled);
+ }
+ }
+}
+
} // namespace
// static
@@ -275,6 +285,27 @@ ChromeDevToolsManagerDelegate::SetWindowBounds(int id,
}
std::unique_ptr<base::DictionaryValue>
+ChromeDevToolsManagerDelegate::SetAdBlockingEnabled(
+ content::DevToolsAgentHost* agent_host,
+ int id,
+ base::DictionaryValue* params) {
+ if (!page_enable_)
+ return DevToolsProtocol::CreateErrorResponse(id, "Page domain is disabled");
+ bool enabled = false;
+ params->GetBoolean("enabled", &enabled);
+ ToggleAdBlocking(enabled, agent_host);
+ return DevToolsProtocol::CreateSuccessResponse(id, nullptr);
+}
+
+void ChromeDevToolsManagerDelegate::TogglePageEnable(
+ bool enable,
+ content::DevToolsAgentHost* agent_host) {
+ page_enable_ = enable;
+ if (!page_enable_)
+ ToggleAdBlocking(false /* enable */, agent_host);
+}
+
+std::unique_ptr<base::DictionaryValue>
ChromeDevToolsManagerDelegate::HandleBrowserCommand(
int id,
std::string method,
@@ -327,9 +358,19 @@ base::DictionaryValue* ChromeDevToolsManagerDelegate::HandleCommand(
if (!DevToolsProtocol::ParseCommand(command_dict, &id, &method, &params))
return nullptr;
- if (agent_host->GetType() == DevToolsAgentHost::kTypeBrowser &&
- method.find("Browser.") == 0)
- return HandleBrowserCommand(id, method, params).release();
+ // Do not actually handle the enable/disable commands, just keep track of the
+ // enable state.
+ if (method == chrome::devtools::Page::enable::kName)
+ TogglePageEnable(true /* enable */, agent_host);
+ if (method == chrome::devtools::Page::disable::kName)
+ TogglePageEnable(false /* enable */, agent_host);
+
+ auto* result = HandleBrowserCommand(id, method, params).release();
+ if (result)
+ return result;
+
+ if (method == chrome::devtools::Page::setAdBlockingEnabled::kName)
+ return SetAdBlockingEnabled(agent_host, id, params).release();
if (method == chrome::devtools::Target::setRemoteLocations::kName)
return SetRemoteLocations(agent_host, id, params).release();
@@ -392,6 +433,8 @@ void ChromeDevToolsManagerDelegate::DevToolsAgentHostAttached(
void ChromeDevToolsManagerDelegate::DevToolsAgentHostDetached(
content::DevToolsAgentHost* agent_host) {
network_protocol_handler_->DevToolsAgentStateChanged(agent_host, false);
+ ToggleAdBlocking(false /* enable */, agent_host);
+
// This class is created lazily, so it may not know about some attached hosts.
if (host_data_.find(agent_host) != host_data_.end()) {
host_data_.erase(agent_host);
diff --git a/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.h b/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.h
index 3042a2216a0..a9290d5c042 100644
--- a/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.h
+++ b/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.h
@@ -74,6 +74,12 @@ class ChromeDevToolsManagerDelegate :
static std::unique_ptr<base::DictionaryValue> SetWindowBounds(
int id,
base::DictionaryValue* params);
+ std::unique_ptr<base::DictionaryValue> SetAdBlockingEnabled(
+ content::DevToolsAgentHost* agent_host,
+ int id,
+ base::DictionaryValue* params);
+
+ void TogglePageEnable(bool enable, content::DevToolsAgentHost* agent_host);
std::unique_ptr<DevToolsNetworkProtocolHandler> network_protocol_handler_;
std::map<content::DevToolsAgentHost*, std::unique_ptr<HostData>> host_data_;
@@ -83,6 +89,8 @@ class ChromeDevToolsManagerDelegate :
content::DevToolsAgentHost::List remote_agent_hosts_;
RemoteLocations remote_locations_;
+ bool page_enable_ = false;
+
DISALLOW_COPY_AND_ASSIGN(ChromeDevToolsManagerDelegate);
};
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 3da5dc89d18..44db9942b7b 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,6 +3,7 @@
// found in the LICENSE file.
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.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"
@@ -41,7 +42,7 @@ class AdbClientSocketTest : public InProcessBrowserTest,
const DevToolsAndroidBridge::RemoteDevices& devices) override {
devices_ = devices;
android_bridge_->RemoveDeviceListListener(this);
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
void CheckDevices() {
diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.cc b/chromium/chrome/browser/devtools/device/android_device_manager.cc
index c1c22e2b9f8..8ecf2c114e1 100644
--- a/chromium/chrome/browser/devtools/device/android_device_manager.cc
+++ b/chromium/chrome/browser/devtools/device/android_device_manager.cc
@@ -331,13 +331,6 @@ class DevicesRequest : public base::RefCountedThreadSafe<DevicesRequest> {
std::unique_ptr<DeviceDescriptors> descriptors_;
};
-void ReleaseDeviceAndProvider(
- AndroidDeviceManager::DeviceProvider* provider,
- const std::string& serial) {
- provider->ReleaseDevice(serial);
- provider->Release();
-}
-
} // namespace
AndroidDeviceManager::BrowserInfo::BrowserInfo()
@@ -451,20 +444,16 @@ AndroidDeviceManager::Device::Device(
scoped_refptr<base::SingleThreadTaskRunner> device_task_runner,
scoped_refptr<DeviceProvider> provider,
const std::string& serial)
- : task_runner_(device_task_runner),
+ : RefCountedDeleteOnSequence<Device>(base::ThreadTaskRunnerHandle::Get()),
+ task_runner_(device_task_runner),
provider_(provider),
serial_(serial),
- weak_factory_(this) {
-}
+ weak_factory_(this) {}
AndroidDeviceManager::Device::~Device() {
- DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- provider_->AddRef();
- DeviceProvider* raw_ptr = provider_.get();
- provider_ = nullptr;
- task_runner_->PostTask(FROM_HERE,
- base::BindOnce(&ReleaseDeviceAndProvider,
- base::Unretained(raw_ptr), serial_));
+ task_runner_->PostTask(
+ FROM_HERE, base::BindOnce(&DeviceProvider::ReleaseDevice,
+ std::move(provider_), std::move(serial_)));
}
AndroidDeviceManager::HandlerThread*
diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.h b/chromium/chrome/browser/devtools/device/android_device_manager.h
index 61e33b03ca0..c5a4a572971 100644
--- a/chromium/chrome/browser/devtools/device/android_device_manager.h
+++ b/chromium/chrome/browser/devtools/device/android_device_manager.h
@@ -9,6 +9,7 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
+#include "base/memory/ref_counted_delete_on_sequence.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/single_thread_task_runner.h"
@@ -107,7 +108,7 @@ class AndroidDeviceManager {
class DeviceProvider;
- class Device : public base::RefCountedThreadSafe<Device> {
+ class Device final : public base::RefCountedDeleteOnSequence<Device> {
public:
void QueryDeviceInfo(const DeviceInfoCallback& callback);
@@ -127,24 +128,22 @@ class AndroidDeviceManager {
const std::string& path,
AndroidWebSocket::Delegate* delegate);
- std::string serial() { return serial_; }
+ const std::string& serial() { return serial_; }
private:
- friend class base::RefCountedThreadSafe<Device>;
+ friend class base::RefCountedDeleteOnSequence<Device>;
+ friend class base::DeleteHelper<Device>;
friend class AndroidDeviceManager;
friend class AndroidWebSocket;
Device(scoped_refptr<base::SingleThreadTaskRunner> device_task_runner,
scoped_refptr<DeviceProvider> provider,
const std::string& serial);
-
- virtual ~Device();
+ ~Device();
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
scoped_refptr<DeviceProvider> provider_;
- std::string serial_;
-
- SEQUENCE_CHECKER(sequence_checker_);
+ const std::string serial_;
base::WeakPtrFactory<Device> weak_factory_;
diff --git a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
index fb9901e38d8..f073b0117ad 100644
--- a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
+++ b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
@@ -463,6 +463,9 @@ void DevToolsDeviceDiscovery::DiscoveryRequest::ReceivedVersion(
else
browser->version_ = browser_name;
}
+ browser->browser_target_id_ = GetTargetPath(dict);
+ if (browser->browser_target_id_.empty())
+ browser->browser_target_id_ = kBrowserTargetSocket;
std::string package;
if (dict->GetString("Android-Package", &package)) {
browser->display_name_ =
@@ -602,10 +605,9 @@ DevToolsDeviceDiscovery::CreateBrowserAgentHost(
scoped_refptr<AndroidDeviceManager::Device> device,
scoped_refptr<RemoteBrowser> browser) {
return AgentHostDelegate::GetOrCreateAgentHost(
- device,
- browser->browser_id_,
+ device, browser->browser_id_,
"adb:" + browser->serial() + ":" + browser->socket(),
- kBrowserTargetSocket, DevToolsAgentHost::kTypeBrowser, nullptr);
+ browser->browser_target_id(), DevToolsAgentHost::kTypeBrowser, nullptr);
}
void DevToolsDeviceDiscovery::RequestDeviceList() {
diff --git a/chromium/chrome/browser/devtools/device/devtools_device_discovery.h b/chromium/chrome/browser/devtools/device/devtools_device_discovery.h
index 6a2e66dc617..c3a6e5863c0 100644
--- a/chromium/chrome/browser/devtools/device/devtools_device_discovery.h
+++ b/chromium/chrome/browser/devtools/device/devtools_device_discovery.h
@@ -53,6 +53,7 @@ class DevToolsDeviceDiscovery {
const std::string& display_name() { return display_name_; }
const std::string& user() { return user_; }
const std::string& version() { return version_; }
+ const std::string& browser_target_id() { return browser_target_id_; }
const RemotePages& pages() { return pages_; }
bool IsChrome();
@@ -76,6 +77,7 @@ class DevToolsDeviceDiscovery {
std::string user_;
AndroidDeviceManager::BrowserInfo::Type type_;
std::string version_;
+ std::string browser_target_id_;
RemotePages pages_;
DISALLOW_COPY_AND_ASSIGN(RemoteBrowser);
diff --git a/chromium/chrome/browser/devtools/device/port_forwarding_browsertest.cc b/chromium/chrome/browser/devtools/device/port_forwarding_browsertest.cc
index be48dc9de1c..02b5e6c2b99 100644
--- a/chromium/chrome/browser/devtools/device/port_forwarding_browsertest.cc
+++ b/chromium/chrome/browser/devtools/device/port_forwarding_browsertest.cc
@@ -7,6 +7,7 @@
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/devtools/device/devtools_android_bridge.h"
diff --git a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
index d4ae31f5cbc..550bc24ac45 100644
--- a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
+++ b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
@@ -46,8 +46,6 @@ enum {
namespace tethering = ::chrome::devtools::Tethering;
-static const char kDevToolsRemoteBrowserTarget[] = "/devtools/browser";
-
class SocketTunnel {
public:
static void StartTunnel(const std::string& host,
@@ -259,9 +257,8 @@ PortForwardingController::Connection::Connection(
forwarding_map_(forwarding_map) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
(*registry_)[device_->serial()] = this;
- web_socket_.reset(
- device_->CreateWebSocket(browser->socket(),
- kDevToolsRemoteBrowserTarget, this));
+ web_socket_.reset(device_->CreateWebSocket(
+ browser->socket(), browser->browser_target_id(), this));
}
PortForwardingController::Connection::~Connection() {
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 dec93dfb8bc..b385608e426 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
@@ -12,6 +12,7 @@
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -144,12 +145,11 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
}
void SetConfiguration(int configuration_value,
- const ResultCallback& callback) override {
+ ResultCallback callback) override {
NOTIMPLEMENTED();
}
- void ClaimInterface(int interface_number,
- const ResultCallback& callback) override {
+ void ClaimInterface(int interface_number, ResultCallback callback) override {
bool success = false;
if (device_->claimed_interfaces_.find(interface_number) ==
device_->claimed_interfaces_.end()) {
@@ -158,11 +158,11 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, success));
+ FROM_HERE, base::BindOnce(std::move(callback), success));
}
void ReleaseInterface(int interface_number,
- const ResultCallback& callback) override {
+ ResultCallback callback) override {
bool success = false;
if (device_->claimed_interfaces_.find(interface_number) ==
device_->claimed_interfaces_.end())
@@ -170,20 +170,18 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
device_->claimed_interfaces_.erase(interface_number);
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, success));
+ FROM_HERE, base::BindOnce(std::move(callback), success));
}
void SetInterfaceAlternateSetting(int interface_number,
int alternate_setting,
- const ResultCallback& callback) override {
+ ResultCallback callback) override {
NOTIMPLEMENTED();
}
- void ResetDevice(const ResultCallback& callback) override {
- NOTIMPLEMENTED();
- }
+ void ResetDevice(ResultCallback callback) override { NOTIMPLEMENTED(); }
- void ClearHalt(uint8_t endpoint, const ResultCallback& callback) override {
+ void ClearHalt(uint8_t endpoint, ResultCallback callback) override {
NOTIMPLEMENTED();
}
@@ -197,14 +195,14 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
scoped_refptr<net::IOBuffer> buffer,
size_t length,
unsigned int timeout,
- const TransferCallback& callback) override {}
+ TransferCallback callback) override {}
void GenericTransfer(UsbTransferDirection direction,
uint8_t endpoint,
scoped_refptr<net::IOBuffer> buffer,
size_t length,
unsigned int timeout,
- const TransferCallback& callback) override {
+ TransferCallback callback) override {
if (direction == device::UsbTransferDirection::OUTBOUND) {
if (remaining_body_length_ == 0) {
std::vector<uint32_t> header(6);
@@ -231,10 +229,10 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
? UsbTransferStatus::TRANSFER_ERROR
: UsbTransferStatus::COMPLETED;
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, status, nullptr, 0));
+ FROM_HERE, base::BindOnce(std::move(callback), status, nullptr, 0));
ProcessQueries();
} else if (direction == device::UsbTransferDirection::INBOUND) {
- queries_.push(Query(callback, buffer, length));
+ queries_.push(Query(std::move(callback), buffer, length));
ProcessQueries();
}
}
@@ -340,17 +338,20 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
void ProcessQueries() {
if (queries_.empty())
return;
- Query query = queries_.front();
if (broken_) {
+ Query query = std::move(queries_.front());
+ queries_.pop();
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
- base::BindOnce(query.callback, UsbTransferStatus::TRANSFER_ERROR,
- nullptr, 0));
+ base::BindOnce(std::move(query.callback),
+ UsbTransferStatus::TRANSFER_ERROR, nullptr, 0));
+ return;
}
- if (query.size > output_buffer_.size())
+ if (queries_.front().size > output_buffer_.size())
return;
+ Query query = std::move(queries_.front());
queries_.pop();
std::copy(output_buffer_.begin(),
output_buffer_.begin() + query.size,
@@ -358,22 +359,21 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
output_buffer_.erase(output_buffer_.begin(),
output_buffer_.begin() + query.size);
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(query.callback, UsbTransferStatus::COMPLETED,
- query.buffer, query.size));
+ FROM_HERE,
+ base::BindOnce(std::move(query.callback), UsbTransferStatus::COMPLETED,
+ query.buffer, query.size));
}
- void IsochronousTransferIn(
- uint8_t endpoint_number,
- const std::vector<uint32_t>& packet_lengths,
- unsigned int timeout,
- const IsochronousTransferCallback& callback) override {}
+ void IsochronousTransferIn(uint8_t endpoint_number,
+ const std::vector<uint32_t>& packet_lengths,
+ unsigned int timeout,
+ IsochronousTransferCallback callback) override {}
- void IsochronousTransferOut(
- uint8_t endpoint_number,
- scoped_refptr<net::IOBuffer> buffer,
- const std::vector<uint32_t>& packet_lengths,
- unsigned int timeout,
- const IsochronousTransferCallback& callback) override {}
+ void IsochronousTransferOut(uint8_t endpoint_number,
+ scoped_refptr<net::IOBuffer> buffer,
+ const std::vector<uint32_t>& packet_lengths,
+ unsigned int timeout,
+ IsochronousTransferCallback callback) override {}
protected:
virtual ~MockUsbDeviceHandle() {}
@@ -386,7 +386,7 @@ class MockUsbDeviceHandle : public UsbDeviceHandle {
Query(TransferCallback callback,
scoped_refptr<net::IOBuffer> buffer,
int size)
- : callback(callback), buffer(buffer), size(size) {}
+ : callback(std::move(callback)), buffer(buffer), size(size) {}
};
scoped_refptr<MockUsbDevice<T> > device_;
@@ -424,7 +424,7 @@ class MockUsbDevice : public UsbDevice {
ActiveConfigurationChanged(1);
}
- void Open(const OpenCallback& callback) override {
+ void Open(OpenCallback callback) override {
// While most operating systems allow multiple applications to open a
// device simultaneously so that they may claim separate interfaces DevTools
// will always be trying to claim the same interface and so multiple
@@ -433,7 +433,7 @@ class MockUsbDevice : public UsbDevice {
open_ = true;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
- base::BindOnce(callback,
+ base::BindOnce(std::move(callback),
make_scoped_refptr(new MockUsbDeviceHandle<T>(this))));
}
@@ -625,7 +625,7 @@ class MockCountListener : public DevToolsAndroidBridge::DeviceCountListener {
Shutdown();
}
- void Shutdown() { base::MessageLoop::current()->QuitWhenIdle(); }
+ void Shutdown() { base::RunLoop::QuitCurrentWhenIdleDeprecated(); }
DevToolsAndroidBridge* adb_bridge_;
int invoked_;
diff --git a/chromium/chrome/browser/devtools/devtools_file_helper.cc b/chromium/chrome/browser/devtools/devtools_file_helper.cc
index 7fd7f1cc788..18869314f5b 100644
--- a/chromium/chrome/browser/devtools/devtools_file_helper.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_helper.cc
@@ -72,7 +72,7 @@ class SelectFileDialog : public ui::SelectFileDialog::Listener,
canceled_callback_(canceled_callback),
web_contents_(web_contents) {
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_contents));
+ this, std::make_unique<ChromeSelectFilePolicy>(web_contents));
}
void Show(ui::SelectFileDialog::Type type,
diff --git a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
index 87efb803918..576a620649d 100644
--- a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
@@ -34,12 +34,13 @@ using base::TimeDelta;
using base::TimeTicks;
using content::BrowserThread;
using std::map;
-using std::set;
using std::string;
using std::vector;
namespace {
+using std::set;
+
base::SequencedTaskRunner* impl_task_runner() {
constexpr base::TaskTraits kBlockingTraits = {base::MayBlock(),
base::TaskPriority::BACKGROUND};
diff --git a/chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc b/chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc
index 350b15e3782..029c360f206 100644
--- a/chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/files/file_util.h"
-#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "chrome/browser/devtools/devtools_file_system_indexer.h"
@@ -18,7 +17,7 @@ class DevToolsFileSystemIndexerTest : public testing::Test {
public:
void SetDone() {
indexing_done_ = true;
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
void SearchCallback(const std::vector<std::string>& results) {
@@ -27,7 +26,7 @@ class DevToolsFileSystemIndexerTest : public testing::Test {
search_results_.insert(
base::FilePath::FromUTF8Unsafe(result).BaseName().AsUTF8Unsafe());
}
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
protected:
diff --git a/chromium/chrome/browser/devtools/devtools_file_watcher.cc b/chromium/chrome/browser/devtools/devtools_file_watcher.cc
index 3c43d13520a..2195fc7aed8 100644
--- a/chromium/chrome/browser/devtools/devtools_file_watcher.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_watcher.cc
@@ -22,8 +22,8 @@
using content::BrowserThread;
-static int kFirstThrottleTimeout = 10;
-static int kDefaultThrottleTimeout = 200;
+static constexpr int kFirstThrottleTimeout = 10;
+static constexpr int kDefaultThrottleTimeout = 200;
// DevToolsFileWatcher::SharedFileWatcher --------------------------------------
diff --git a/chromium/chrome/browser/devtools/devtools_network_transaction.cc b/chromium/chrome/browser/devtools/devtools_network_transaction.cc
index a4d1626d155..6508896a4f2 100644
--- a/chromium/chrome/browser/devtools/devtools_network_transaction.cc
+++ b/chromium/chrome/browser/devtools/devtools_network_transaction.cc
@@ -285,6 +285,16 @@ void DevToolsNetworkTransaction::SetBeforeNetworkStartCallback(
network_transaction_->SetBeforeNetworkStartCallback(callback);
}
+void DevToolsNetworkTransaction::SetRequestHeadersCallback(
+ net::RequestHeadersCallback callback) {
+ network_transaction_->SetRequestHeadersCallback(std::move(callback));
+}
+
+void DevToolsNetworkTransaction::SetResponseHeadersCallback(
+ net::ResponseHeadersCallback callback) {
+ network_transaction_->SetResponseHeadersCallback(std::move(callback));
+}
+
void DevToolsNetworkTransaction::SetBeforeHeadersSentCallback(
const BeforeHeadersSentCallback& callback) {
network_transaction_->SetBeforeHeadersSentCallback(callback);
diff --git a/chromium/chrome/browser/devtools/devtools_network_transaction.h b/chromium/chrome/browser/devtools/devtools_network_transaction.h
index aa2db08719a..f52ca9fd888 100644
--- a/chromium/chrome/browser/devtools/devtools_network_transaction.h
+++ b/chromium/chrome/browser/devtools/devtools_network_transaction.h
@@ -88,6 +88,9 @@ class DevToolsNetworkTransaction
const BeforeNetworkStartCallback& callback) override;
void SetBeforeHeadersSentCallback(
const BeforeHeadersSentCallback& callback) override;
+ void SetRequestHeadersCallback(net::RequestHeadersCallback callback) override;
+ void SetResponseHeadersCallback(
+ net::ResponseHeadersCallback callback) override;
int ResumeNetworkStart() override;
void GetConnectionAttempts(net::ConnectionAttempts* out) const override;
diff --git a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
index 55fb4266ab9..95c216e5e72 100644
--- a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
+++ b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
@@ -18,6 +18,7 @@
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
+#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -49,6 +50,10 @@
#include "chrome/test/base/ui_test_utils.h"
#include "components/app_modal/javascript_app_modal_dialog.h"
#include "components/app_modal/native_app_modal_dialog.h"
+#include "components/autofill/content/browser/content_autofill_driver.h"
+#include "components/autofill/content/browser/content_autofill_driver_factory.h"
+#include "components/autofill/core/browser/autofill_manager.h"
+#include "components/autofill/core/browser/autofill_manager_test_delegate.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/content_browser_client.h"
@@ -79,6 +84,7 @@
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/test/url_request/url_request_mock_http_job.h"
#include "net/url_request/url_request_context.h"
+#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_http_job.h"
#include "third_party/WebKit/public/platform/WebInputEvent.h"
@@ -128,6 +134,8 @@ const char kReloadSharedWorkerTestWorker[] =
"files/workers/debug_shared_worker_initialization.js";
const char kEmulateNetworkConditionsPage[] =
"files/devtools/emulate_network_conditions.html";
+const char kDispatchKeyEventShowsAutoFill[] =
+ "files/devtools/dispatch_key_event_shows_auto_fill.html";
template <typename... T>
void DispatchOnTestSuiteSkipCheck(DevToolsWindow* window,
@@ -453,7 +461,7 @@ class DevToolsBeforeUnloadTest: public DevToolsSanityTest {
void TimeoutCallback(const std::string& timeout_message) {
ADD_FAILURE() << timeout_message;
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
// Base class for DevTools tests that test devtools functionality for
@@ -629,7 +637,7 @@ class DevToolsExtensionTest : public DevToolsSanityTest,
const content::NotificationDetails& details) override {
DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD,
type);
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
std::vector<std::unique_ptr<extensions::TestExtensionDir>>
@@ -1497,8 +1505,8 @@ IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
// Whitelist the script we stuff into the 'blob:' URL:
.Set("content_security_policy",
"script-src 'self' "
- "'sha256-95xJWHeV+"
- "1zjAKQufDVW0misgmR4gCjgpipP2LJ5iis='; "
+ "'sha256-uv9gxBEOFchPzak3TK6O39RdKxJeZvfha9zOHGam"
+ "TB4='; "
"object-src 'none'")
.Set("manifest_version", 2)
.Set("devtools_page", "devtools.html")
@@ -1531,7 +1539,6 @@ IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
"var xhr = new XMLHttpRequest();\n"
"xhr.open('GET', blob_url, true);\n"
"xhr.onload = function (e) {\n"
- " domAutomationController.setAutomationId(0);\n"
" domAutomationController.send(xhr.response);\n"
"};\n"
"xhr.send(null);\n");
@@ -1540,7 +1547,6 @@ IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
"var payload = `"
"<html><body>iframe blob contents"
"<script>"
- " domAutomationController.setAutomationId(0);"
" domAutomationController.send(document.body.innerText);\n"
"</script></body></html>"
"`;"
@@ -1696,6 +1702,47 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDispatchKeyEventDoesNotCrash) {
RunTest("testDispatchKeyEventDoesNotCrash", "about:blank");
}
+class AutofillManagerTestDelegateDevtoolsImpl
+ : public autofill::AutofillManagerTestDelegate {
+ public:
+ explicit AutofillManagerTestDelegateDevtoolsImpl(
+ WebContents* inspectedContents)
+ : inspected_contents_(inspectedContents) {}
+ ~AutofillManagerTestDelegateDevtoolsImpl() override {}
+
+ void DidPreviewFormData() override {}
+
+ void DidFillFormData() override {}
+
+ void DidShowSuggestions() override {
+ ASSERT_TRUE(content::ExecuteScript(inspected_contents_,
+ "console.log('didShowSuggestions');"));
+ }
+
+ void OnTextFieldChanged() override {}
+
+ private:
+ WebContents* inspected_contents_;
+
+ DISALLOW_COPY_AND_ASSIGN(AutofillManagerTestDelegateDevtoolsImpl);
+};
+
+IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDispatchKeyEventShowsAutoFill) {
+ OpenDevToolsWindow(kDispatchKeyEventShowsAutoFill, false);
+
+ autofill::ContentAutofillDriver* autofill_driver =
+ autofill::ContentAutofillDriverFactory::FromWebContents(GetInspectedTab())
+ ->DriverForFrame(GetInspectedTab()->GetMainFrame());
+ autofill::AutofillManager* autofill_manager =
+ autofill_driver->autofill_manager();
+ AutofillManagerTestDelegateDevtoolsImpl autoFillTestDelegate(
+ GetInspectedTab());
+ autofill_manager->SetTestDelegate(&autoFillTestDelegate);
+
+ RunTestFunction(window_, "testDispatchKeyEventShowsAutoFill");
+ CloseDevToolsWindow();
+}
+
// Tests that settings are stored in profile correctly.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSettings) {
OpenDevToolsWindow("about:blank", true);
@@ -1995,6 +2042,10 @@ IN_PROC_BROWSER_TEST_F(DevToolsNetInfoTest, EmulateNetworkConditions) {
RunTest("testEmulateNetworkConditions", kEmulateNetworkConditionsPage);
}
+IN_PROC_BROWSER_TEST_F(DevToolsNetInfoTest, OfflineNetworkConditions) {
+ RunTest("testOfflineNetworkConditions", kEmulateNetworkConditionsPage);
+}
+
class StaticURLDataSource : public content::URLDataSource {
public:
StaticURLDataSource(const std::string& source, const std::string& content)
@@ -2066,3 +2117,40 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DevToolsWindowTesting::CloseDevToolsWindowSync(window);
content::WebUIControllerFactory::UnregisterFactoryForTesting(&test_factory);
}
+
+void AddHSTSHost(scoped_refptr<net::URLRequestContextGetter> context,
+ std::string host) {
+ net::TransportSecurityState* transport_security_state =
+ context->GetURLRequestContext()->transport_security_state();
+ base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
+ bool include_subdomains = false;
+ transport_security_state->AddHSTS(host, expiry, include_subdomains);
+}
+
+IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestRawHeadersWithRedirectAndHSTS) {
+ net::EmbeddedTestServer https_test_server(
+ net::EmbeddedTestServer::TYPE_HTTPS);
+ https_test_server.SetSSLConfig(
+ net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
+ https_test_server.ServeFilesFromSourceDirectory("chrome/test/data");
+ ASSERT_TRUE(https_test_server.Start());
+ GURL https_url = https_test_server.GetURL("localhost", "/devtools/image.png");
+ BrowserThread::PostTask(
+ BrowserThread::IO, FROM_HERE,
+ base::BindOnce(
+ AddHSTSHost,
+ base::RetainedRef(browser()->profile()->GetRequestContext()),
+ https_url.host()));
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ OpenDevToolsWindow(std::string(), false);
+ GURL::Replacements replace_scheme;
+ replace_scheme.SetSchemeStr("http");
+ GURL http_url = https_url.ReplaceComponents(replace_scheme);
+ GURL redirect_url =
+ embedded_test_server()->GetURL("/server-redirect?" + http_url.spec());
+
+ DispatchOnTestSuite(window_, "testRawHeadersWithHSTS",
+ redirect_url.spec().c_str());
+ CloseDevToolsWindow();
+}
diff --git a/chromium/chrome/browser/devtools/devtools_targets_ui.cc b/chromium/chrome/browser/devtools/devtools_targets_ui.cc
index ccd72ed9de3..ee8beab57bd 100644
--- a/chromium/chrome/browser/devtools/devtools_targets_ui.cc
+++ b/chromium/chrome/browser/devtools/devtools_targets_ui.cc
@@ -241,8 +241,8 @@ void LocalTargetsUIHandler::SendTargets(
targets_.clear();
for (const scoped_refptr<DevToolsAgentHost>& host : targets) {
targets_[host->GetId()] = host;
- hosts.push_back(
- {host->GetId(), host->GetParentId(), *Serialize(host.get())});
+ hosts.push_back({host->GetId(), host->GetParentId(),
+ std::move(*Serialize(host.get()))});
}
SendSerializedTargets(
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings.cc b/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
index 75f335352c4..a1dd70e2acd 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -226,6 +226,7 @@ class DefaultBindingsDelegate : public DevToolsUIBindings::Delegate {
void ReadyForTest() override {}
InfoBarService* GetInfoBarService() override;
void RenderProcessGone(bool crashed) override {}
+ void ShowCertificateViewer(const std::string& cert_chain) override{};
content::WebContents* web_contents_;
DISALLOW_COPY_AND_ASSIGN(DefaultBindingsDelegate);
@@ -313,12 +314,11 @@ int ResponseWriter::Finish(int net_error,
return net::OK;
}
-GURL SanitizeFrontendURL(
- const GURL& url,
- const std::string& scheme,
- const std::string& host,
- const std::string& path,
- bool allow_query);
+GURL SanitizeFrontendURL(const GURL& url,
+ const std::string& scheme,
+ const std::string& host,
+ const std::string& path,
+ bool allow_query_and_fragment);
std::string SanitizeRevision(const std::string& revision) {
for (size_t i = 0; i < revision.length(); i++) {
@@ -390,7 +390,7 @@ std::string SanitizeFrontendQueryParam(
// Convert boolean flags to true.
if (key == "can_dock" || key == "debugFrontend" || key == "experiments" ||
key == "isSharedWorker" || key == "v8only" || key == "remoteFrontend" ||
- key == "nodeFrontend")
+ key == "nodeFrontend" || key == "hasOtherClients")
return "true";
// Pass connection endpoints as is.
@@ -413,14 +413,14 @@ std::string SanitizeFrontendQueryParam(
return std::string();
}
-GURL SanitizeFrontendURL(
- const GURL& url,
- const std::string& scheme,
- const std::string& host,
- const std::string& path,
- bool allow_query) {
+GURL SanitizeFrontendURL(const GURL& url,
+ const std::string& scheme,
+ const std::string& host,
+ const std::string& path,
+ bool allow_query_and_fragment) {
std::vector<std::string> query_parts;
- if (allow_query) {
+ std::string fragment;
+ if (allow_query_and_fragment) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
@@ -429,11 +429,14 @@ GURL SanitizeFrontendURL(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
+ if (url.has_ref())
+ fragment = '#' + url.ref();
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
- std::string constructed = base::StringPrintf("%s://%s%s%s",
- scheme.c_str(), host.c_str(), path.c_str(), query.c_str());
+ std::string constructed =
+ base::StringPrintf("%s://%s%s%s%s", scheme.c_str(), host.c_str(),
+ path.c_str(), query.c_str(), fragment.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
@@ -660,6 +663,13 @@ void DevToolsUIBindings::SendMessageAck(int request_id,
&id_value, arg, nullptr);
}
+void DevToolsUIBindings::InnerAttach() {
+ DCHECK(agent_host_.get());
+ // Note: we could use ForceAttachClient here to disconnect other clients
+ // if any problems arise.
+ agent_host_->AttachClient(this);
+}
+
// DevToolsEmbedderMessageDispatcher::Delegate implementation -----------------
void DevToolsUIBindings::ActivateWindow() {
@@ -721,7 +731,7 @@ void DevToolsUIBindings::LoadNetworkResource(const DispatchCallback& callback,
destination: WEBSITE
}
policy {
- cookies_allowed: true
+ cookies_allowed: YES
cookies_store: "user"
setting:
"It's not possible to disable this feature from settings."
@@ -864,49 +874,7 @@ void DevToolsUIBindings::SetEyeDropperActive(bool active) {
}
void DevToolsUIBindings::ShowCertificateViewer(const std::string& cert_chain) {
- std::unique_ptr<base::Value> value =
- base::JSONReader::Read(cert_chain);
- if (!value || value->GetType() != base::Value::Type::LIST) {
- NOTREACHED();
- return;
- }
-
- std::unique_ptr<base::ListValue> list =
- base::ListValue::From(std::move(value));
- std::vector<std::string> decoded;
- for (size_t i = 0; i < list->GetSize(); ++i) {
- base::Value* item;
- if (!list->Get(i, &item) || item->GetType() != base::Value::Type::STRING) {
- NOTREACHED();
- return;
- }
- std::string temp;
- if (!item->GetAsString(&temp)) {
- NOTREACHED();
- return;
- }
- if (!base::Base64Decode(temp, &temp)) {
- NOTREACHED();
- return;
- }
- decoded.push_back(temp);
- }
-
- std::vector<base::StringPiece> cert_string_piece;
- for (const auto& str : decoded)
- cert_string_piece.push_back(str);
- scoped_refptr<net::X509Certificate> cert =
- net::X509Certificate::CreateFromDERCertChain(cert_string_piece);
- if (!cert) {
- NOTREACHED();
- return;
- }
-
- if (!agent_host_ || !agent_host_->GetWebContents())
- return;
- content::WebContents* inspected_wc = agent_host_->GetWebContents();
- web_contents_->GetDelegate()->ShowCertificateViewerInDevTools(
- inspected_wc, cert.get());
+ delegate_->ShowCertificateViewer(cert_chain);
}
void DevToolsUIBindings::ZoomIn() {
@@ -1067,7 +1035,7 @@ void DevToolsUIBindings::SetPreference(const std::string& name,
const std::string& value) {
DictionaryPrefUpdate update(profile_->GetPrefs(),
prefs::kDevToolsPreferences);
- update.Get()->SetStringWithoutPathExpansion(name, value);
+ update.Get()->SetKey(name, base::Value(value));
}
void DevToolsUIBindings::RemovePreference(const std::string& name) {
@@ -1085,7 +1053,7 @@ void DevToolsUIBindings::ClearPreferences() {
void DevToolsUIBindings::Reattach(const DispatchCallback& callback) {
if (agent_host_.get()) {
agent_host_->DetachClient(this);
- agent_host_->AttachClient(this);
+ InnerAttach();
}
callback.Run(nullptr);
}
@@ -1338,9 +1306,7 @@ void DevToolsUIBindings::AttachTo(
if (agent_host_.get())
Detach();
agent_host_ = agent_host;
- // DevToolsUIBindings terminates existing debugging connections and starts
- // debugging.
- agent_host_->ForceAttachClient(this);
+ InnerAttach();
}
void DevToolsUIBindings::Reload() {
@@ -1417,7 +1383,7 @@ void DevToolsUIBindings::DocumentAvailableInMainFrame() {
return;
reloading_ = false;
if (agent_host_.get())
- agent_host_->AttachClient(this);
+ InnerAttach();
}
void DevToolsUIBindings::DocumentOnLoadCompletedInMainFrame() {
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings.h b/chromium/chrome/browser/devtools/devtools_ui_bindings.h
index 4dd51b7de47..e85da2a351c 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings.h
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings.h
@@ -65,6 +65,7 @@ class DevToolsUIBindings : public DevToolsEmbedderMessageDispatcher::Delegate,
virtual void ReadyForTest() = 0;
virtual InfoBarService* GetInfoBarService() = 0;
virtual void RenderProcessGone(bool crashed) = 0;
+ virtual void ShowCertificateViewer(const std::string& cert_chain) = 0;
};
explicit DevToolsUIBindings(content::WebContents* web_contents);
@@ -166,6 +167,7 @@ class DevToolsUIBindings : public DevToolsEmbedderMessageDispatcher::Delegate,
void SendMessageAck(int request_id,
const base::Value* arg1);
+ void InnerAttach();
// DevToolsAndroidBridge::DeviceCountListener override:
void DeviceCountChanged(int count) override;
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc b/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
index f1754a328e2..486d99ac298 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
@@ -10,88 +10,85 @@ class DevToolsUIBindingsTest : public testing::Test {
TEST_F(DevToolsUIBindingsTest, SanitizeFrontendURL) {
std::vector<std::pair<std::string, std::string>> tests = {
- {"random-string",
- "chrome-devtools://devtools/"},
- {"http://valid.url/but/wrong",
- "chrome-devtools://devtools/but/wrong"},
- {"chrome-devtools://wrong-domain/",
- "chrome-devtools://devtools/"},
- {"chrome-devtools://devtools/bundled/devtools.html",
- "chrome-devtools://devtools/bundled/devtools.html"},
- {"chrome-devtools://devtools:1234/bundled/devtools.html#hash",
- "chrome-devtools://devtools/bundled/devtools.html"},
- {"chrome-devtools://devtools/some/random/path",
- "chrome-devtools://devtools/some/random/path"},
- {"chrome-devtools://devtools/bundled/devtools.html?experiments=true",
- "chrome-devtools://devtools/bundled/devtools.html?experiments=true"},
- {"chrome-devtools://devtools/bundled/devtools.html"
- "?some-flag=flag&v8only=true&experiments=false&debugFrontend=a"
- "&another-flag=another-flag&can_dock=false&isSharedWorker=notreally"
- "&remoteFrontend=sure",
- "chrome-devtools://devtools/bundled/devtools.html"
- "?v8only=true&experiments=true&debugFrontend=true"
- "&can_dock=true&isSharedWorker=true&remoteFrontend=true"},
- {"chrome-devtools://devtools/?ws=any-value-is-fine",
- "chrome-devtools://devtools/?ws=any-value-is-fine"},
- {"chrome-devtools://devtools/"
- "?service-backend=ws://localhost:9222/services",
- "chrome-devtools://devtools/"
- "?service-backend=ws://localhost:9222/services"},
- {"chrome-devtools://devtools/?dockSide=undocked",
- "chrome-devtools://devtools/?dockSide=undocked"},
- {"chrome-devtools://devtools/?dockSide=dock-to-bottom",
- "chrome-devtools://devtools/"},
- {"chrome-devtools://devtools/?dockSide=bottom",
- "chrome-devtools://devtools/"},
- {"chrome-devtools://devtools/?remoteBase="
- "http://example.com:1234/remote-base#hash",
- "chrome-devtools://devtools/?remoteBase="
- "https://chrome-devtools-frontend.appspot.com/"
- "serve_file//"},
- {"chrome-devtools://devtools/?ws=1%26evil%3dtrue",
- "chrome-devtools://devtools/?ws=1%26evil%3dtrue"},
- {"chrome-devtools://devtools/?remoteBase="
- "https://chrome-devtools-frontend.appspot.com/some/path/"
- "@123719741873/more/path.html",
- "chrome-devtools://devtools/?remoteBase="
- "https://chrome-devtools-frontend.appspot.com/serve_file/path/"},
- {"chrome-devtools://devtools/?remoteBase="
- "https://chrome-devtools-frontend.appspot.com/serve_file/"
- "@123719741873/inspector.html%3FdebugFrontend%3Dfalse",
- "chrome-devtools://devtools/?remoteBase="
- "https://chrome-devtools-frontend.appspot.com/serve_file/"
- "@123719741873/"},
- {"chrome-devtools://devtools/bundled/inspector.html?"
- "&remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/"
- "@b4907cc5d602ff470740b2eb6344b517edecb7b9/&can_dock=true",
- "chrome-devtools://devtools/bundled/inspector.html?"
- "remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/"
- "@b4907cc5d602ff470740b2eb6344b517edecb7b9/&can_dock=true"},
- {"chrome-devtools://devtools/?remoteFrontendUrl="
- "https://chrome-devtools-frontend.appspot.com/serve_rev/"
- "@12345/inspector.html%3FdebugFrontend%3Dfalse",
- "chrome-devtools://devtools/?remoteFrontendUrl="
- "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
- "%2F%4012345%2Finspector.html%3FdebugFrontend%3Dtrue"},
- {"chrome-devtools://devtools/?remoteFrontendUrl="
- "https://chrome-devtools-frontend.appspot.com/serve_rev/"
- "@12345/inspector.html%22></iframe>something",
- "chrome-devtools://devtools/?remoteFrontendUrl="
- "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
- "%2F%4012345%2Finspector.html"},
- {"chrome-devtools://devtools/?remoteFrontendUrl="
- "http://domain:1234/path/rev/a/filename.html%3Fparam%3Dvalue#hash",
- "chrome-devtools://devtools/?remoteFrontendUrl="
- "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
- "%2Frev%2Finspector.html"},
- {"chrome-devtools://devtools/?experiments=whatever&remoteFrontendUrl="
- "https://chrome-devtools-frontend.appspot.com/serve_rev/"
- "@12345/devtools.html%3Fws%3Danyvalue%26experiments%3Dlikely"
- "&unencoded=value&debugFrontend=true",
- "chrome-devtools://devtools/?experiments=true&remoteFrontendUrl="
- "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
- "%2F%4012345%2Fdevtools.html%3Fws%3Danyvalue%26experiments%3Dtrue"
- "&debugFrontend=true"},
+ {"random-string", "chrome-devtools://devtools/"},
+ {"http://valid.url/but/wrong", "chrome-devtools://devtools/but/wrong"},
+ {"chrome-devtools://wrong-domain/", "chrome-devtools://devtools/"},
+ {"chrome-devtools://devtools/bundled/devtools.html",
+ "chrome-devtools://devtools/bundled/devtools.html"},
+ {"chrome-devtools://devtools:1234/bundled/devtools.html#hash",
+ "chrome-devtools://devtools/bundled/devtools.html#hash"},
+ {"chrome-devtools://devtools/some/random/path",
+ "chrome-devtools://devtools/some/random/path"},
+ {"chrome-devtools://devtools/bundled/devtools.html?experiments=true",
+ "chrome-devtools://devtools/bundled/devtools.html?experiments=true"},
+ {"chrome-devtools://devtools/bundled/devtools.html"
+ "?some-flag=flag&v8only=true&experiments=false&debugFrontend=a"
+ "&another-flag=another-flag&can_dock=false&isSharedWorker=notreally"
+ "&remoteFrontend=sure",
+ "chrome-devtools://devtools/bundled/devtools.html"
+ "?v8only=true&experiments=true&debugFrontend=true"
+ "&can_dock=true&isSharedWorker=true&remoteFrontend=true"},
+ {"chrome-devtools://devtools/?ws=any-value-is-fine",
+ "chrome-devtools://devtools/?ws=any-value-is-fine"},
+ {"chrome-devtools://devtools/"
+ "?service-backend=ws://localhost:9222/services",
+ "chrome-devtools://devtools/"
+ "?service-backend=ws://localhost:9222/services"},
+ {"chrome-devtools://devtools/?dockSide=undocked",
+ "chrome-devtools://devtools/?dockSide=undocked"},
+ {"chrome-devtools://devtools/?dockSide=dock-to-bottom",
+ "chrome-devtools://devtools/"},
+ {"chrome-devtools://devtools/?dockSide=bottom",
+ "chrome-devtools://devtools/"},
+ {"chrome-devtools://devtools/?remoteBase="
+ "http://example.com:1234/remote-base#hash",
+ "chrome-devtools://devtools/?remoteBase="
+ "https://chrome-devtools-frontend.appspot.com/"
+ "serve_file//#hash"},
+ {"chrome-devtools://devtools/?ws=1%26evil%3dtrue",
+ "chrome-devtools://devtools/?ws=1%26evil%3dtrue"},
+ {"chrome-devtools://devtools/?remoteBase="
+ "https://chrome-devtools-frontend.appspot.com/some/path/"
+ "@123719741873/more/path.html",
+ "chrome-devtools://devtools/?remoteBase="
+ "https://chrome-devtools-frontend.appspot.com/serve_file/path/"},
+ {"chrome-devtools://devtools/?remoteBase="
+ "https://chrome-devtools-frontend.appspot.com/serve_file/"
+ "@123719741873/inspector.html%3FdebugFrontend%3Dfalse",
+ "chrome-devtools://devtools/?remoteBase="
+ "https://chrome-devtools-frontend.appspot.com/serve_file/"
+ "@123719741873/"},
+ {"chrome-devtools://devtools/bundled/inspector.html?"
+ "&remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/"
+ "@b4907cc5d602ff470740b2eb6344b517edecb7b9/&can_dock=true",
+ "chrome-devtools://devtools/bundled/inspector.html?"
+ "remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/"
+ "@b4907cc5d602ff470740b2eb6344b517edecb7b9/&can_dock=true"},
+ {"chrome-devtools://devtools/?remoteFrontendUrl="
+ "https://chrome-devtools-frontend.appspot.com/serve_rev/"
+ "@12345/inspector.html%3FdebugFrontend%3Dfalse",
+ "chrome-devtools://devtools/?remoteFrontendUrl="
+ "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
+ "%2F%4012345%2Finspector.html%3FdebugFrontend%3Dtrue"},
+ {"chrome-devtools://devtools/?remoteFrontendUrl="
+ "https://chrome-devtools-frontend.appspot.com/serve_rev/"
+ "@12345/inspector.html%22></iframe>something",
+ "chrome-devtools://devtools/?remoteFrontendUrl="
+ "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
+ "%2F%4012345%2Finspector.html"},
+ {"chrome-devtools://devtools/?remoteFrontendUrl="
+ "http://domain:1234/path/rev/a/filename.html%3Fparam%3Dvalue#hash",
+ "chrome-devtools://devtools/?remoteFrontendUrl="
+ "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
+ "%2Frev%2Finspector.html#hash"},
+ {"chrome-devtools://devtools/?experiments=whatever&remoteFrontendUrl="
+ "https://chrome-devtools-frontend.appspot.com/serve_rev/"
+ "@12345/devtools.html%3Fws%3Danyvalue%26experiments%3Dlikely"
+ "&unencoded=value&debugFrontend=true",
+ "chrome-devtools://devtools/?experiments=true&remoteFrontendUrl="
+ "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
+ "%2F%4012345%2Fdevtools.html%3Fws%3Danyvalue%26experiments%3Dtrue"
+ "&debugFrontend=true"},
};
for (const auto& pair : tests) {
diff --git a/chromium/chrome/browser/devtools/devtools_window.cc b/chromium/chrome/browser/devtools/devtools_window.cc
index dc0dfd6e4dd..003280aa489 100644
--- a/chromium/chrome/browser/devtools/devtools_window.cc
+++ b/chromium/chrome/browser/devtools/devtools_window.cc
@@ -7,6 +7,7 @@
#include <algorithm>
#include <utility>
+#include "base/base64.h"
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
@@ -459,7 +460,9 @@ void DevToolsWindow::OpenDevToolsWindowForWorker(
const scoped_refptr<DevToolsAgentHost>& worker_agent) {
DevToolsWindow* window = FindDevToolsWindow(worker_agent.get());
if (!window) {
- window = DevToolsWindow::CreateDevToolsWindowForWorker(profile);
+ base::RecordAction(base::UserMetricsAction("DevTools_InspectWorker"));
+ window = Create(profile, nullptr, kFrontendWorker, std::string(), false, "",
+ "", worker_agent->IsAttached());
if (!window)
return;
window->bindings_->AttachTo(worker_agent);
@@ -468,14 +471,6 @@ void DevToolsWindow::OpenDevToolsWindowForWorker(
}
// static
-DevToolsWindow* DevToolsWindow::CreateDevToolsWindowForWorker(
- Profile* profile) {
- base::RecordAction(base::UserMetricsAction("DevTools_InspectWorker"));
- return Create(profile, nullptr, kFrontendWorker, std::string(), false, "",
- "");
-}
-
-// static
void DevToolsWindow::OpenDevToolsWindow(
content::WebContents* inspected_web_contents) {
ToggleDevToolsWindow(
@@ -539,7 +534,7 @@ void DevToolsWindow::OpenDevToolsWindowForFrame(
if (!window) {
window = DevToolsWindow::Create(profile, nullptr, kFrontendDefault,
std::string(), false, std::string(),
- std::string());
+ std::string(), agent_host->IsAttached());
if (!window)
return;
window->bindings_->AttachTo(agent_host);
@@ -573,7 +568,7 @@ void DevToolsWindow::OpenExternalFrontend(
if (!window) {
window = Create(profile, nullptr, frontend_type,
DevToolsUI::GetProxyURL(frontend_url).spec(), false,
- std::string(), std::string());
+ std::string(), std::string(), agent_host->IsAttached());
if (!window)
return;
window->bindings_->AttachTo(agent_host);
@@ -594,7 +589,7 @@ void DevToolsWindow::OpenNodeFrontendWindow(Profile* profile) {
DevToolsWindow* window =
Create(profile, nullptr, kFrontendNode, std::string(), false,
- std::string(), std::string());
+ std::string(), std::string(), false);
if (!window)
return;
window->bindings_->AttachTo(DevToolsAgentHost::CreateForDiscovery());
@@ -631,7 +626,7 @@ void DevToolsWindow::ToggleDevToolsWindow(
break;
}
window = Create(profile, inspected_web_contents, kFrontendDefault,
- std::string(), true, settings, panel);
+ std::string(), true, settings, panel, agent->IsAttached());
if (!window)
return;
window->bindings_->AttachTo(agent.get());
@@ -885,7 +880,8 @@ DevToolsWindow* DevToolsWindow::Create(
const std::string& frontend_url,
bool can_dock,
const std::string& settings,
- const std::string& panel) {
+ const std::string& panel,
+ bool has_other_clients) {
if (profile->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled) ||
base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode))
return nullptr;
@@ -902,8 +898,8 @@ DevToolsWindow* DevToolsWindow::Create(
}
// Create WebContents with devtools.
- GURL url(
- GetDevToolsURL(profile, frontend_type, frontend_url, can_dock, panel));
+ GURL url(GetDevToolsURL(profile, frontend_type, frontend_url, can_dock, panel,
+ has_other_clients));
std::unique_ptr<WebContents> main_web_contents(
WebContents::Create(WebContents::CreateParams(profile)));
main_web_contents->GetController().LoadURL(
@@ -924,7 +920,8 @@ GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
FrontendType frontend_type,
const std::string& frontend_url,
bool can_dock,
- const std::string& panel) {
+ const std::string& panel,
+ bool has_other_clients) {
std::string url(!frontend_url.empty() ? frontend_url
: chrome::kChromeUIDevToolsURL);
std::string url_string(url +
@@ -953,6 +950,8 @@ GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
url_string += "&can_dock=true";
if (panel.size())
url_string += "&panel=" + panel;
+ if (has_other_clients)
+ url_string += "&hasOtherClients=true";
return DevToolsUIBindings::SanitizeFrontendURL(GURL(url_string));
}
@@ -990,25 +989,16 @@ WebContents* DevToolsWindow::OpenURLFromTab(
DCHECK(source == main_web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
WebContents* inspected_web_contents = GetInspectedWebContents();
- return inspected_web_contents ?
- inspected_web_contents->OpenURL(params) : NULL;
+ if (!inspected_web_contents)
+ return nullptr;
+ content::OpenURLParams modified = params;
+ modified.referrer = content::Referrer();
+ return inspected_web_contents->OpenURL(modified);
}
bindings_->Reload();
return main_web_contents_;
}
-void DevToolsWindow::ShowCertificateViewer(
- scoped_refptr<net::X509Certificate> certificate) {
- WebContents* inspected_contents = is_docked_ ?
- GetInspectedWebContents() : main_web_contents_;
- Browser* browser = NULL;
- int tab = 0;
- if (!FindInspectedBrowserAndTabIndex(inspected_contents, &browser, &tab))
- return;
- gfx::NativeWindow parent = browser->window()->GetNativeWindow();
- ::ShowCertificateViewer(inspected_contents, parent, certificate.get());
-}
-
void DevToolsWindow::ActivateContents(WebContents* contents) {
if (is_docked_) {
WebContents* inspected_tab = GetInspectedWebContents();
@@ -1154,12 +1144,6 @@ bool DevToolsWindow::PreHandleGestureEvent(
return blink::WebInputEvent::IsPinchGestureEventType(event.GetType());
}
-void DevToolsWindow::ShowCertificateViewerInDevTools(
- content::WebContents* web_contents,
- scoped_refptr<net::X509Certificate> certificate) {
- ShowCertificateViewer(certificate);
-}
-
void DevToolsWindow::ActivateWindow() {
if (life_stage_ != kLoadCompleted)
return;
@@ -1297,6 +1281,54 @@ void DevToolsWindow::RenderProcessGone(bool crashed) {
}
}
+void DevToolsWindow::ShowCertificateViewer(const std::string& cert_chain) {
+ std::unique_ptr<base::Value> value = base::JSONReader::Read(cert_chain);
+ if (!value || value->GetType() != base::Value::Type::LIST) {
+ NOTREACHED();
+ return;
+ }
+
+ std::unique_ptr<base::ListValue> list =
+ base::ListValue::From(std::move(value));
+ std::vector<std::string> decoded;
+ for (size_t i = 0; i < list->GetSize(); ++i) {
+ base::Value* item;
+ if (!list->Get(i, &item) || item->GetType() != base::Value::Type::STRING) {
+ NOTREACHED();
+ return;
+ }
+ std::string temp;
+ if (!item->GetAsString(&temp)) {
+ NOTREACHED();
+ return;
+ }
+ if (!base::Base64Decode(temp, &temp)) {
+ NOTREACHED();
+ return;
+ }
+ decoded.push_back(temp);
+ }
+
+ std::vector<base::StringPiece> cert_string_piece;
+ for (const auto& str : decoded)
+ cert_string_piece.push_back(str);
+ scoped_refptr<net::X509Certificate> cert =
+ net::X509Certificate::CreateFromDERCertChain(cert_string_piece);
+ if (!cert) {
+ NOTREACHED();
+ return;
+ }
+
+ WebContents* inspected_contents =
+ is_docked_ ? GetInspectedWebContents() : main_web_contents_;
+ Browser* browser = NULL;
+ int tab = 0;
+ if (!FindInspectedBrowserAndTabIndex(inspected_contents, &browser, &tab))
+ return;
+ gfx::NativeWindow parent = browser->window()->GetNativeWindow();
+ ::ShowCertificateViewer(inspected_contents, parent, cert.get());
+}
+
void DevToolsWindow::OnLoadCompleted() {
// First seed inspected tab id for extension APIs.
WebContents* inspected_web_contents = GetInspectedWebContents();
diff --git a/chromium/chrome/browser/devtools/devtools_window.h b/chromium/chrome/browser/devtools/devtools_window.h
index ca3e0ef4e42..8ee560a0bc1 100644
--- a/chromium/chrome/browser/devtools/devtools_window.h
+++ b/chromium/chrome/browser/devtools/devtools_window.h
@@ -127,8 +127,6 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate,
content::WebContents* source,
const content::OpenURLParams& params) override;
- void ShowCertificateViewer(scoped_refptr<net::X509Certificate> certificate);
-
// BeforeUnload interception ////////////////////////////////////////////////
// In order to preserve any edits the user may have made in devtools, the
@@ -266,14 +264,15 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate,
const std::string& frontend_url,
bool can_dock,
const std::string& settings,
- const std::string& panel);
+ const std::string& panel,
+ bool has_other_clients);
static GURL GetDevToolsURL(Profile* profile,
FrontendType frontend_type,
const std::string& frontend_url,
bool can_dock,
- const std::string& panel);
+ const std::string& panel,
+ bool has_other_clients);
- static DevToolsWindow* CreateDevToolsWindowForWorker(Profile* profile);
static void ToggleDevToolsWindow(
content::WebContents* web_contents,
bool force_open,
@@ -315,9 +314,6 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate,
const content::FileChooserParams& params) override;
bool PreHandleGestureEvent(content::WebContents* source,
const blink::WebGestureEvent& event) override;
- void ShowCertificateViewerInDevTools(
- content::WebContents* web_contents,
- scoped_refptr<net::X509Certificate> certificate) override;
// content::DevToolsUIBindings::Delegate overrides
void ActivateWindow() override;
@@ -335,6 +331,7 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate,
void ReadyForTest() override;
InfoBarService* GetInfoBarService() override;
void RenderProcessGone(bool crashed) override;
+ void ShowCertificateViewer(const std::string& cert_viewer) override;
void ColorPickedInEyeDropper(int r, int g, int b, int a);
void CreateDevToolsBrowser();
diff --git a/chromium/chrome/browser/devtools/global_confirm_info_bar.cc b/chromium/chrome/browser/devtools/global_confirm_info_bar.cc
index a1851f9f2df..ef435c0adc5 100644
--- a/chromium/chrome/browser/devtools/global_confirm_info_bar.cc
+++ b/chromium/chrome/browser/devtools/global_confirm_info_bar.cc
@@ -8,6 +8,7 @@
#include "base/macros.h"
#include "base/stl_util.h"
+#include "base/threading/sequenced_task_runner_handle.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "components/infobars/core/infobar.h"
@@ -34,7 +35,6 @@ class GlobalConfirmInfoBar::DelegateProxy : public ConfirmInfoBarDelegate {
base::string16 GetLinkText() const override;
GURL GetLinkURL() const override;
bool LinkClicked(WindowOpenDisposition disposition) override;
- bool EqualsDelegate(infobars::InfoBarDelegate* delegate) const override;
void InfoBarDismissed() override;
infobars::InfoBar* info_bar_;
@@ -120,11 +120,6 @@ bool GlobalConfirmInfoBar::DelegateProxy::LinkClicked(
global_info_bar_->delegate_->LinkClicked(disposition) : false;
}
-bool GlobalConfirmInfoBar::DelegateProxy::EqualsDelegate(
- infobars::InfoBarDelegate* delegate) const {
- return delegate == this;
-}
-
void GlobalConfirmInfoBar::DelegateProxy::InfoBarDismissed() {
base::WeakPtr<GlobalConfirmInfoBar> info_bar = global_info_bar_;
// See comments in GlobalConfirmInfoBar::DelegateProxy::Accept().
@@ -159,6 +154,7 @@ GlobalConfirmInfoBar::GlobalConfirmInfoBar(
std::unique_ptr<ConfirmInfoBarDelegate> delegate)
: delegate_(std::move(delegate)),
browser_tab_strip_tracker_(this, nullptr, nullptr),
+ is_closing_(false),
weak_factory_(this) {
browser_tab_strip_tracker_.Init();
}
@@ -217,8 +213,26 @@ void GlobalConfirmInfoBar::MaybeAddInfoBar(content::WebContents* web_contents) {
infobars::InfoBar* added_bar = infobar_service->AddInfoBar(
infobar_service->CreateConfirmInfoBar(std::move(proxy)));
+ // If AddInfoBar() fails, either infobars are globally disabled, or something
+ // strange has gone wrong and we can't show the infobar on every tab. In
+ // either case, it doesn't make sense to keep the global object open,
+ // especially since some callers expect it to delete itself when a user acts
+ // on the underlying infobars.
+ //
+ // Asynchronously delete the global object because the BrowserTabStripTracker
+ // doesn't support being deleted while iterating over the existing tabs.
+ if (!added_bar) {
+ if (!is_closing_) {
+ is_closing_ = true;
+
+ base::SequencedTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE,
+ base::Bind(&GlobalConfirmInfoBar::Close, weak_factory_.GetWeakPtr()));
+ }
+ return;
+ }
+
proxy_ptr->info_bar_ = added_bar;
- DCHECK(added_bar);
proxies_[infobar_service] = proxy_ptr;
infobar_service->AddObserver(this);
}
diff --git a/chromium/chrome/browser/devtools/global_confirm_info_bar.h b/chromium/chrome/browser/devtools/global_confirm_info_bar.h
index 06e27f3a7eb..7843f269827 100644
--- a/chromium/chrome/browser/devtools/global_confirm_info_bar.h
+++ b/chromium/chrome/browser/devtools/global_confirm_info_bar.h
@@ -6,6 +6,7 @@
#define CHROME_BROWSER_DEVTOOLS_GLOBAL_CONFIRM_INFO_BAR_H_
#include <map>
+#include <memory>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
@@ -27,6 +28,8 @@ class GlobalConfirmInfoBar : public TabStripModelObserver,
public:
static base::WeakPtr<GlobalConfirmInfoBar> Show(
std::unique_ptr<ConfirmInfoBarDelegate> delegate);
+
+ // Closes all the infobars.
void Close();
// infobars::InfoBarManager::Observer:
@@ -55,6 +58,10 @@ class GlobalConfirmInfoBar : public TabStripModelObserver,
std::map<infobars::InfoBarManager*, DelegateProxy*> proxies_;
BrowserTabStripTracker browser_tab_strip_tracker_;
+ // Indicates if the global infobar is currently in the process of shutting
+ // down.
+ bool is_closing_;
+
base::WeakPtrFactory<GlobalConfirmInfoBar> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(GlobalConfirmInfoBar);
diff --git a/chromium/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc b/chromium/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc
new file mode 100644
index 00000000000..13671b8a427
--- /dev/null
+++ b/chromium/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc
@@ -0,0 +1,161 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/devtools/global_confirm_info_bar.h"
+
+#include <utility>
+
+#include "base/command_line.h"
+#include "base/macros.h"
+#include "base/memory/ptr_util.h"
+#include "base/run_loop.h"
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "components/infobars/core/infobar.h"
+#include "components/infobars/core/infobars_switches.h"
+
+namespace {
+
+class TestConfirmInfoBarDelegate : public ConfirmInfoBarDelegate {
+ public:
+ TestConfirmInfoBarDelegate() = default;
+ ~TestConfirmInfoBarDelegate() override = default;
+
+ InfoBarIdentifier GetIdentifier() const override { return TEST_INFOBAR; }
+
+ base::string16 GetMessageText() const override {
+ return base::ASCIIToUTF16("GlobalConfirmInfoBar browser tests delegate.");
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(TestConfirmInfoBarDelegate);
+};
+
+class GlobalConfirmInfoBarTest : public InProcessBrowserTest {
+ public:
+ GlobalConfirmInfoBarTest() = default;
+ ~GlobalConfirmInfoBarTest() override = default;
+
+ protected:
+ InfoBarService* GetInfoBarServiceFromTabIndex(int tab_index) {
+ return InfoBarService::FromWebContents(
+ browser()->tab_strip_model()->GetWebContentsAt(tab_index));
+ }
+
+ // Adds an additional tab.
+ void AddTab() {
+ AddTabAtIndex(0, GURL("chrome://blank/"), ui::PAGE_TRANSITION_LINK);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GlobalConfirmInfoBarTest);
+};
+
+// Subclass for tests that require infobars to be disabled.
+class GlobalConfirmInfoBarWithInfoBarDisabledTest
+ : public GlobalConfirmInfoBarTest {
+ public:
+ GlobalConfirmInfoBarWithInfoBarDisabledTest() = default;
+ ~GlobalConfirmInfoBarWithInfoBarDisabledTest() override = default;
+
+ protected:
+ void SetUpDefaultCommandLine(base::CommandLine* command_line) override {
+ command_line->AppendSwitch(infobars::switches::kDisableInfoBars);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GlobalConfirmInfoBarWithInfoBarDisabledTest);
+};
+
+} // namespace
+
+// Creates a global confirm info bar on a browser with 2 tabs and closes it.
+IN_PROC_BROWSER_TEST_F(GlobalConfirmInfoBarTest, MultipleTabs) {
+ TabStripModel* tab_strip_model = browser()->tab_strip_model();
+
+ AddTab();
+ ASSERT_EQ(2, tab_strip_model->count());
+
+ // Make sure each tab has no info bars.
+ for (int i = 0; i < tab_strip_model->count(); i++)
+ EXPECT_EQ(0u, GetInfoBarServiceFromTabIndex(i)->infobar_count());
+
+ auto delegate = base::MakeUnique<TestConfirmInfoBarDelegate>();
+ TestConfirmInfoBarDelegate* delegate_ptr = delegate.get();
+
+ base::WeakPtr<GlobalConfirmInfoBar> global_confirm_info_bar =
+ GlobalConfirmInfoBar::Show(std::move(delegate));
+
+ // Verify that the info bar is shown on each tab.
+ for (int i = 0; i < tab_strip_model->count(); i++) {
+ InfoBarService* infobar_service = GetInfoBarServiceFromTabIndex(i);
+ ASSERT_EQ(1u, infobar_service->infobar_count());
+ EXPECT_TRUE(infobar_service->infobar_at(0)->delegate()->EqualsDelegate(
+ delegate_ptr));
+ }
+
+ EXPECT_TRUE(global_confirm_info_bar);
+ global_confirm_info_bar->Close();
+
+ EXPECT_FALSE(global_confirm_info_bar);
+ for (int i = 0; i < tab_strip_model->count(); i++)
+ EXPECT_EQ(0u, GetInfoBarServiceFromTabIndex(i)->infobar_count());
+}
+
+IN_PROC_BROWSER_TEST_F(GlobalConfirmInfoBarTest, UserInteraction) {
+ TabStripModel* tab_strip_model = browser()->tab_strip_model();
+
+ AddTab();
+ ASSERT_EQ(2, tab_strip_model->count());
+
+ // Make sure each tab has no info bars.
+ for (int i = 0; i < tab_strip_model->count(); i++)
+ EXPECT_EQ(0u, GetInfoBarServiceFromTabIndex(i)->infobar_count());
+
+ auto delegate = base::MakeUnique<TestConfirmInfoBarDelegate>();
+ TestConfirmInfoBarDelegate* delegate_ptr = delegate.get();
+
+ base::WeakPtr<GlobalConfirmInfoBar> global_confirm_info_bar =
+ GlobalConfirmInfoBar::Show(std::move(delegate));
+
+ // Verify that the info bar is shown on each tab.
+ for (int i = 0; i < tab_strip_model->count(); i++) {
+ InfoBarService* infobar_service = GetInfoBarServiceFromTabIndex(i);
+ ASSERT_EQ(1u, infobar_service->infobar_count());
+ EXPECT_TRUE(infobar_service->infobar_at(0)->delegate()->EqualsDelegate(
+ delegate_ptr));
+ }
+
+ // Close the GlobalConfirmInfoBar by simulating an interaction with the info
+ // bar on one of the tabs. In this case, the first tab is picked.
+ infobars::InfoBar* first_tab_infobar =
+ GetInfoBarServiceFromTabIndex(0)->infobar_at(0);
+ EXPECT_TRUE(
+ first_tab_infobar->delegate()->AsConfirmInfoBarDelegate()->Accept());
+
+ // Usually, clicking the button makes the info bar close itself if Accept()
+ // returns true. In our case, since we interacted with the info bar delegate
+ // directly, the info bar must be removed manually
+ first_tab_infobar->RemoveSelf();
+
+ EXPECT_FALSE(global_confirm_info_bar);
+ for (int i = 0; i < tab_strip_model->count(); i++)
+ EXPECT_EQ(0u, GetInfoBarServiceFromTabIndex(i)->infobar_count());
+}
+
+IN_PROC_BROWSER_TEST_F(GlobalConfirmInfoBarWithInfoBarDisabledTest,
+ InfoBarsDisabled) {
+ ASSERT_EQ(1, browser()->tab_strip_model()->count());
+
+ auto delegate = base::MakeUnique<TestConfirmInfoBarDelegate>();
+ base::WeakPtr<GlobalConfirmInfoBar> global_confirm_info_bar =
+ GlobalConfirmInfoBar::Show(std::move(delegate));
+
+ // In this case, the deletion is done asynchronously.
+ base::RunLoop().RunUntilIdle();
+
+ ASSERT_FALSE(global_confirm_info_bar);
+}
diff --git a/chromium/chrome/browser/devtools/remote_debugging_server.cc b/chromium/chrome/browser/devtools/remote_debugging_server.cc
index 2cc82280262..e07fe4cb62a 100644
--- a/chromium/chrome/browser/devtools/remote_debugging_server.cc
+++ b/chromium/chrome/browser/devtools/remote_debugging_server.cc
@@ -16,9 +16,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
-#include "chrome/common/chrome_content_client.h"
#include "chrome/common/chrome_paths.h"
-#include "components/version_info/version_info.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_socket_factory.h"
#include "net/base/net_errors.h"
@@ -109,12 +107,8 @@ RemoteDebuggingServer::RemoteDebuggingServer(const std::string& ip,
#endif
content::DevToolsAgentHost::StartRemoteDebuggingServer(
- base::MakeUnique<TCPServerSocketFactory>(ip, port),
- std::string(),
- output_dir,
- debug_frontend_dir,
- version_info::GetProductNameAndVersionForUserAgent(),
- ::GetUserAgent());
+ base::MakeUnique<TCPServerSocketFactory>(ip, port), std::string(),
+ output_dir, debug_frontend_dir);
}
RemoteDebuggingServer::~RemoteDebuggingServer() {
diff --git a/chromium/chrome/browser/devtools/serialize_host_descriptions_unittest.cc b/chromium/chrome/browser/devtools/serialize_host_descriptions_unittest.cc
index 856dc1a68ba..5ad3f88df0c 100644
--- a/chromium/chrome/browser/devtools/serialize_host_descriptions_unittest.cc
+++ b/chromium/chrome/browser/devtools/serialize_host_descriptions_unittest.cc
@@ -61,27 +61,31 @@ TEST(SerializeHostDescriptionTest, Empty) {
// Test serializing a forest of stubs (no edges).
TEST(SerializeHostDescriptionTest, Stubs) {
- base::ListValue result = SerializeHostDescriptions(
- {GetNodeWithLabel("1", 1), GetNodeWithLabel("2", 2),
- GetNodeWithLabel("3", 3)},
- "children");
- EXPECT_THAT(result.base::Value::GetList(),
+ std::vector<HostDescriptionNode> nodes;
+ nodes.emplace_back(GetNodeWithLabel("1", 1));
+ nodes.emplace_back(GetNodeWithLabel("2", 2));
+ nodes.emplace_back(GetNodeWithLabel("3", 3));
+ base::ListValue result =
+ SerializeHostDescriptions(std::move(nodes), "children");
+ EXPECT_THAT(result.GetList(),
UnorderedElementsAre(EmptyNode(1), EmptyNode(2), EmptyNode(3)));
}
// Test handling multiple nodes sharing the same name.
TEST(SerializeHostDescriptionTest, SameNames) {
- std::vector<HostDescriptionNode> nodes = {
- GetNodeWithLabel("A", 1), GetNodeWithLabel("A", 2),
- GetNodeWithLabel("A", 3), GetNodeWithLabel("B", 4),
- GetNodeWithLabel("C", 5)};
+ std::vector<HostDescriptionNode> nodes;
+ nodes.emplace_back(GetNodeWithLabel("A", 1));
+ nodes.emplace_back(GetNodeWithLabel("A", 2));
+ nodes.emplace_back(GetNodeWithLabel("A", 3));
+ nodes.emplace_back(GetNodeWithLabel("B", 4));
+ nodes.emplace_back(GetNodeWithLabel("C", 5));
base::ListValue result =
SerializeHostDescriptions(std::move(nodes), "children");
// Only the first node called "A", and both nodes "B" and "C" should be
// returned.
- EXPECT_THAT(result.base::Value::GetList(),
+ EXPECT_THAT(result.GetList(),
UnorderedElementsAre(EmptyNode(1), EmptyNode(4), EmptyNode(5)));
}
diff --git a/chromium/chrome/browser/engagement/BUILD.gn b/chromium/chrome/browser/engagement/BUILD.gn
index 2f45dd439d7..3bca05363d5 100644
--- a/chromium/chrome/browser/engagement/BUILD.gn
+++ b/chromium/chrome/browser/engagement/BUILD.gn
@@ -15,7 +15,4 @@ mojom("mojo_bindings") {
# TODO(crbug.com/714018): Convert the implementation to use OnceCallback.
use_once_callback = false
-
- # TODO(crbug.com/699569): Convert to use the new JS bindings.
- use_new_js_bindings = false
}
diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn
index abcffeacaf0..5e6fcdbf350 100644
--- a/chromium/chrome/browser/extensions/BUILD.gn
+++ b/chromium/chrome/browser/extensions/BUILD.gn
@@ -22,8 +22,6 @@ static_library("extensions") {
"../ui/toolbar/toolbar_actions_model.h",
"../ui/toolbar/toolbar_actions_model_factory.cc",
"../ui/toolbar/toolbar_actions_model_factory.h",
- "../web_applications/update_shortcut_worker_win.cc",
- "../web_applications/update_shortcut_worker_win.h",
"../web_applications/web_app.cc",
"../web_applications/web_app.h",
"../web_applications/web_app_chromeos.cc",
@@ -45,6 +43,8 @@ static_library("extensions") {
"activity_log/activity_log.h",
"activity_log/activity_log_policy.cc",
"activity_log/activity_log_policy.h",
+ "activity_log/activity_log_task_runner.cc",
+ "activity_log/activity_log_task_runner.h",
"activity_log/counting_policy.cc",
"activity_log/counting_policy.h",
"activity_log/database_string_table.cc",
@@ -186,10 +186,8 @@ static_library("extensions") {
"api/extension_action/extension_action_api.h",
"api/extension_action/extension_page_actions_api_constants.cc",
"api/extension_action/extension_page_actions_api_constants.h",
- "api/feedback_private/feedback_private_api.cc",
- "api/feedback_private/feedback_private_api.h",
- "api/feedback_private/feedback_service.cc",
- "api/feedback_private/feedback_service.h",
+ "api/feedback_private/chrome_feedback_private_delegate.cc",
+ "api/feedback_private/chrome_feedback_private_delegate.h",
"api/file_handlers/non_native_file_system_delegate_chromeos.cc",
"api/file_handlers/non_native_file_system_delegate_chromeos.h",
"api/file_system/chrome_file_system_delegate.cc",
@@ -248,6 +246,8 @@ static_library("extensions") {
"api/image_writer_private/removable_storage_provider_chromeos.cc",
"api/image_writer_private/removable_storage_provider_mac.cc",
"api/image_writer_private/removable_storage_provider_win.cc",
+ "api/image_writer_private/unzip_helper.cc",
+ "api/image_writer_private/unzip_helper.h",
"api/image_writer_private/write_from_file_operation.cc",
"api/image_writer_private/write_from_file_operation.h",
"api/image_writer_private/write_from_url_operation.cc",
@@ -266,14 +266,10 @@ static_library("extensions") {
"api/management/chrome_management_api_delegate.h",
"api/media_galleries/media_galleries_api.cc",
"api/media_galleries/media_galleries_api.h",
- "api/messaging/extension_message_port.cc",
- "api/messaging/extension_message_port.h",
+ "api/messaging/chrome_messaging_delegate.cc",
+ "api/messaging/chrome_messaging_delegate.h",
"api/messaging/incognito_connectability.cc",
"api/messaging/incognito_connectability.h",
- "api/messaging/message_property_provider.cc",
- "api/messaging/message_property_provider.h",
- "api/messaging/message_service.cc",
- "api/messaging/message_service.h",
"api/messaging/native_message_port.cc",
"api/messaging/native_message_port.h",
"api/messaging/native_messaging_host_manifest.cc",
@@ -326,10 +322,6 @@ static_library("extensions") {
"api/permissions/permissions_api.h",
"api/permissions/permissions_api_helpers.cc",
"api/permissions/permissions_api_helpers.h",
- "api/preference/chrome_direct_setting.cc",
- "api/preference/chrome_direct_setting.h",
- "api/preference/chrome_direct_setting_api.cc",
- "api/preference/chrome_direct_setting_api.h",
"api/preference/preference_api.cc",
"api/preference/preference_api.h",
"api/preference/preference_api_constants.cc",
@@ -495,10 +487,10 @@ static_library("extensions") {
"chrome_extension_web_contents_observer.h",
"chrome_extensions_browser_client.cc",
"chrome_extensions_browser_client.h",
+ "chrome_extensions_interface_registration.cc",
+ "chrome_extensions_interface_registration.h",
"chrome_kiosk_delegate.h",
"chrome_kiosk_delegate_chromeos.cc",
- "chrome_mojo_service_registration.cc",
- "chrome_mojo_service_registration.h",
"chrome_process_manager_delegate.cc",
"chrome_process_manager_delegate.h",
"chrome_url_request_util.cc",
@@ -555,8 +547,8 @@ static_library("extensions") {
"extension_commands_global_registry.h",
"extension_context_menu_model.cc",
"extension_context_menu_model.h",
- "extension_cookie_monster_delegate.cc",
- "extension_cookie_monster_delegate.h",
+ "extension_cookie_notifier.cc",
+ "extension_cookie_notifier.h",
"extension_creator.cc",
"extension_creator.h",
"extension_creator_filter.cc",
@@ -658,16 +650,10 @@ static_library("extensions") {
"favicon_downloader.h",
"global_shortcut_listener.cc",
"global_shortcut_listener.h",
- "global_shortcut_listener_chromeos.cc",
- "global_shortcut_listener_chromeos.h",
"global_shortcut_listener_mac.h",
"global_shortcut_listener_mac.mm",
- "global_shortcut_listener_ozone.cc",
- "global_shortcut_listener_ozone.h",
"global_shortcut_listener_win.cc",
"global_shortcut_listener_win.h",
- "global_shortcut_listener_x11.cc",
- "global_shortcut_listener_x11.h",
"install_gate.h",
"install_observer.cc",
"install_observer.h",
@@ -886,6 +872,7 @@ static_library("extensions") {
"//extensions/common/api",
"//extensions/features",
"//extensions/strings",
+ "//google_apis",
"//media:media_features",
"//net",
"//ppapi/features",
@@ -898,8 +885,8 @@ static_library("extensions") {
"//sql",
"//storage/browser",
"//storage/common",
- "//third_party/WebKit/public:image_resources",
"//third_party/WebKit/public:resources",
+ "//third_party/WebKit/public:scaled_resources",
"//third_party/cacheinvalidation",
"//third_party/icu",
"//third_party/leveldatabase",
@@ -934,12 +921,6 @@ static_library("extensions") {
"api/enterprise_platform_keys/enterprise_platform_keys_api.h",
"api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc",
"api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h",
- "api/feedback_private/log_source_access_manager.cc",
- "api/feedback_private/log_source_access_manager.h",
- "api/feedback_private/log_source_resource.cc",
- "api/feedback_private/log_source_resource.h",
- "api/feedback_private/single_log_source_factory.cc",
- "api/feedback_private/single_log_source_factory.h",
"api/file_system/consent_provider.cc",
"api/file_system/consent_provider.h",
"api/file_system/request_file_system_notification.cc",
@@ -1019,19 +1000,16 @@ static_library("extensions") {
]
}
- # chromeos uses its own global_shortcut_listener, _x11 is not necessary.
- if (is_chromeos || !use_x11) {
- sources -= [
+ if (use_x11) {
+ sources += [
"global_shortcut_listener_x11.cc",
"global_shortcut_listener_x11.h",
]
- }
-
- if (is_chromeos && use_ozone) {
- sources -= [ "global_shortcut_listener_chromeos.cc" ]
- }
- if (!use_ozone) {
- sources -= [ "global_shortcut_listener_ozone.cc" ]
+ } else if (use_ozone) {
+ sources += [
+ "global_shortcut_listener_ozone.cc",
+ "global_shortcut_listener_ozone.h",
+ ]
}
if (is_linux) {
diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc
index 7a527c1c029..6e28b1f58c2 100644
--- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc
@@ -23,6 +23,7 @@
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
+#include "extensions/common/hashed_extension_id.h"
namespace extensions {
@@ -77,8 +78,10 @@ void ActivityLogAPI::Shutdown() {
// static
bool ActivityLogAPI::IsExtensionWhitelisted(const std::string& extension_id) {
- return FeatureProvider::GetPermissionFeatures()->
- GetFeature("activityLogPrivate")->IsIdInWhitelist(extension_id);
+ // TODO(devlin): Pass in a HashedExtensionId to avoid this conversion.
+ return FeatureProvider::GetPermissionFeatures()
+ ->GetFeature("activityLogPrivate")
+ ->IsIdInWhitelist(HashedExtensionId(extension_id));
}
void ActivityLogAPI::OnListenerAdded(const EventListenerInfo& details) {
diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc
index 9b072fe6f16..0c20f404c84 100644
--- a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc
@@ -22,6 +22,7 @@
#include "content/public/browser/render_process_host.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/extension.h"
+#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.h"
#include "ui/accessibility/ax_node_data.h"
@@ -123,6 +124,24 @@ void AutomationEventRouter::DispatchTreeDestroyedEvent(
EventRouter::Get(browser_context)->BroadcastEvent(std::move(event));
}
+void AutomationEventRouter::DispatchActionResult(const ui::AXActionData& data,
+ bool result) {
+ CHECK(!data.source_extension_id.empty());
+
+ if (listeners_.empty())
+ return;
+
+ std::unique_ptr<base::ListValue> args(
+ api::automation_internal::OnActionResult::Create(
+ data.target_tree_id, data.request_id, result));
+ auto event = base::MakeUnique<Event>(
+ events::AUTOMATION_INTERNAL_ON_ACTION_RESULT,
+ api::automation_internal::OnActionResult::kEventName, std::move(args),
+ active_profile_);
+ EventRouter::Get(active_profile_)
+ ->DispatchEventToExtension(data.source_extension_id, std::move(event));
+}
+
AutomationEventRouter::AutomationListener::AutomationListener() {
}
diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h
index 6edd9ec3281..426d2646568 100644
--- a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h
+++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h
@@ -22,6 +22,10 @@ namespace content {
class BrowserContext;
} // namespace content
+namespace ui {
+struct AXActionData;
+} // namespace ui
+
struct ExtensionMsg_AccessibilityEventParams;
struct ExtensionMsg_AccessibilityLocationChangeParams;
@@ -60,6 +64,9 @@ class AutomationEventRouter : public content::NotificationObserver {
int tree_id,
content::BrowserContext* browser_context);
+ // Notify the source extension of the action of an action result.
+ void DispatchActionResult(const ui::AXActionData& data, bool result);
+
private:
struct AutomationListener {
AutomationListener();
diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc
index 064ed25f1d1..930346a6d2f 100644
--- a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc
+++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc
@@ -333,7 +333,11 @@ ExtensionFunction::ResponseAction
AutomationInternalPerformActionFunction::ConvertToAXActionData(
api::automation_internal::PerformAction::Params* params,
ui::AXActionData* action) {
+ action->target_tree_id = params->args.tree_id;
+ action->source_extension_id = extension_id();
action->target_node_id = params->args.automation_node_id;
+ int* request_id = params->args.request_id.get();
+ action->request_id = request_id ? *request_id : -1;
switch (params->args.action_type) {
case api::automation_internal::ACTION_TYPE_DODEFAULT:
action->action = ui::AX_ACTION_DO_DEFAULT;
@@ -367,6 +371,24 @@ AutomationInternalPerformActionFunction::ConvertToAXActionData(
case api::automation_internal::ACTION_TYPE_MAKEVISIBLE:
action->action = ui::AX_ACTION_SCROLL_TO_MAKE_VISIBLE;
break;
+ case api::automation_internal::ACTION_TYPE_SCROLLBACKWARD:
+ action->action = ui::AX_ACTION_SCROLL_BACKWARD;
+ break;
+ case api::automation_internal::ACTION_TYPE_SCROLLFORWARD:
+ action->action = ui::AX_ACTION_SCROLL_FORWARD;
+ break;
+ case api::automation_internal::ACTION_TYPE_SCROLLUP:
+ action->action = ui::AX_ACTION_SCROLL_UP;
+ break;
+ case api::automation_internal::ACTION_TYPE_SCROLLDOWN:
+ action->action = ui::AX_ACTION_SCROLL_DOWN;
+ break;
+ case api::automation_internal::ACTION_TYPE_SCROLLLEFT:
+ action->action = ui::AX_ACTION_SCROLL_LEFT;
+ break;
+ case api::automation_internal::ACTION_TYPE_SCROLLRIGHT:
+ action->action = ui::AX_ACTION_SCROLL_RIGHT;
+ break;
case api::automation_internal::ACTION_TYPE_SETSELECTION: {
api::automation_internal::SetSelectionParams selection_params;
EXTENSION_FUNCTION_VALIDATE(
@@ -383,10 +405,6 @@ AutomationInternalPerformActionFunction::ConvertToAXActionData(
action->action = ui::AX_ACTION_SHOW_CONTEXT_MENU;
break;
}
- case api::automation_internal::ACTION_TYPE_SETACCESSIBILITYFOCUS: {
- action->action = ui::AX_ACTION_SET_ACCESSIBILITY_FOCUS;
- break;
- }
case api::automation_internal::
ACTION_TYPE_SETSEQUENTIALFOCUSNAVIGATIONSTARTINGPOINT: {
action->action =
@@ -424,8 +442,10 @@ AutomationInternalPerformActionFunction::Run() {
if (delegate) {
#if defined(USE_AURA)
ui::AXActionData data;
- ConvertToAXActionData(params.get(), &data);
+ ExtensionFunction::ResponseAction result =
+ ConvertToAXActionData(params.get(), &data);
delegate->PerformAction(data);
+ return result;
#else
NOTREACHED();
return RespondNow(Error("Unexpected action on desktop automation tree;"
diff --git a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc
index 24052f2ff64..1206ee39eff 100644
--- a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc
@@ -338,6 +338,22 @@ AutotestPrivateSetPrimaryButtonRightFunction::Run() {
return RespondNow(NoArguments());
}
+ExtensionFunction::ResponseAction
+AutotestPrivateSetMouseReverseScrollFunction::Run() {
+ std::unique_ptr<api::autotest_private::SetMouseReverseScroll::Params> params(
+ api::autotest_private::SetMouseReverseScroll::Params::Create(*args_));
+ EXTENSION_FUNCTION_VALIDATE(params.get());
+
+ DVLOG(1) << "AutotestPrivateSetMouseReverseScrollFunction "
+ << params->enabled;
+
+#if defined(OS_CHROMEOS)
+ chromeos::system::InputDeviceSettings::Get()->SetMouseReverseScroll(
+ params->enabled);
+#endif
+ return RespondNow(NoArguments());
+}
+
// static
std::string AutotestPrivateGetVisibleNotificationsFunction::ConvertToString(
message_center::NotificationType type) {
diff --git a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h
index a70c709ca3a..e781e181aa9 100644
--- a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h
+++ b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h
@@ -159,6 +159,17 @@ class AutotestPrivateSetPrimaryButtonRightFunction
ResponseAction Run() override;
};
+class AutotestPrivateSetMouseReverseScrollFunction
+ : public UIThreadExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("autotestPrivate.setMouseReverseScroll",
+ AUTOTESTPRIVATE_SETMOUSEREVERSESCROLL)
+
+ private:
+ ~AutotestPrivateSetMouseReverseScrollFunction() override {}
+ ResponseAction Run() override;
+};
+
class AutotestPrivateGetVisibleNotificationsFunction
: public UIThreadExtensionFunction {
public:
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 7a33bae88a4..e5e469d3dd3 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
@@ -17,7 +17,7 @@
#include "device/bluetooth/test/mock_bluetooth_gatt_service.h"
#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h"
#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h"
-#include "extensions/common/test_util.h"
+#include "extensions/common/extension_builder.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -105,7 +105,7 @@ class BluetoothLowEnergyApiTest : public ExtensionApiTest {
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
- empty_extension_ = extensions::test_util::CreateEmptyExtension();
+ empty_extension_ = extensions::ExtensionBuilder("Test").Build();
SetUpMocks();
}
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 584d9afe48b..53abf8bcdc2 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
@@ -371,9 +371,12 @@ void BookmarkManagerPrivateDragEventRouter::ClearBookmarkNodeData() {
bool ClipboardBookmarkManagerFunction::CopyOrCut(bool cut,
const std::vector<std::string>& id_list) {
BookmarkModel* model = GetBookmarkModel();
- bookmarks::ManagedBookmarkService* managed = GetManagedBookmarkService();
std::vector<const BookmarkNode*> nodes;
- EXTENSION_FUNCTION_VALIDATE(GetNodesFromVector(model, id_list, &nodes));
+ if (!GetNodesFromVector(model, id_list, &nodes)) {
+ error_ = "Could not find bookmark nodes with given ids.";
+ return false;
+ }
+ bookmarks::ManagedBookmarkService* managed = GetManagedBookmarkService();
if (cut && bookmarks::HasDescendantsOf(nodes, managed->managed_node())) {
error_ = bookmark_keys::kModifyManagedError;
return false;
@@ -561,8 +564,8 @@ bool BookmarkManagerPrivateStartDragFunction::RunOnReady() {
BookmarkModel* model =
BookmarkModelFactory::GetForBrowserContext(GetProfile());
std::vector<const BookmarkNode*> nodes;
- EXTENSION_FUNCTION_VALIDATE(
- GetNodesFromVector(model, params->id_list, &nodes));
+ if (!GetNodesFromVector(model, params->id_list, &nodes))
+ return false;
content::WebContents* web_contents = GetAssociatedWebContents();
CHECK(web_contents);
@@ -710,7 +713,7 @@ bool BookmarkManagerPrivateGetMetaInfoFunction::RunOnReady() {
BookmarkNode::MetaInfoMap::const_iterator itr;
base::DictionaryValue& temp = result.as_object->additional_properties;
for (itr = meta_info->begin(); itr != meta_info->end(); itr++) {
- temp.SetStringWithoutPathExpansion(itr->first, itr->second);
+ temp.SetKey(itr->first, base::Value(itr->second));
}
}
results_ = GetMetaInfo::Results::Create(result);
diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api_unittest.cc
new file mode 100644
index 00000000000..d9f6b862e21
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api_unittest.cc
@@ -0,0 +1,65 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h"
+
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/bookmarks/bookmark_model_factory.h"
+#include "chrome/browser/extensions/extension_service_test_base.h"
+#include "chrome/test/base/testing_profile.h"
+#include "components/bookmarks/browser/bookmark_model.h"
+#include "components/bookmarks/test/bookmark_test_helpers.h"
+#include "extensions/browser/api_test_utils.h"
+
+namespace extensions {
+
+class BookmarkManagerPrivateApiUnitTest : public ExtensionServiceTestBase {
+ public:
+ BookmarkManagerPrivateApiUnitTest() {}
+
+ void SetUp() override {
+ ExtensionServiceTestBase::SetUp();
+ InitializeEmptyExtensionService();
+ profile_->CreateBookmarkModel(false);
+ model_ = BookmarkModelFactory::GetForBrowserContext(profile());
+ bookmarks::test::WaitForBookmarkModelToLoad(model_);
+
+ const bookmarks::BookmarkNode* node =
+ model_->AddURL(model_->other_node(), 0, base::ASCIIToUTF16("Goog"),
+ GURL("https://www.google.com"));
+ // Store node->id() as we will delete |node| in RunOnDeletedNode().
+ node_id_ = base::Int64ToString(node->id());
+ }
+
+ std::string node_id() const { return node_id_; }
+
+ private:
+ bookmarks::BookmarkModel* model_ = nullptr;
+ std::string node_id_;
+
+ DISALLOW_COPY_AND_ASSIGN(BookmarkManagerPrivateApiUnitTest);
+};
+
+// Tests that running ExtensionFunction-s on deleted bookmark node gracefully
+// fails.
+// Regression test for https://crbug.com/739260.
+TEST_F(BookmarkManagerPrivateApiUnitTest, RunOnDeletedNode) {
+ // Remove our only bookmark node.
+ scoped_refptr<BookmarksRemoveFunction> remove_function(
+ new BookmarksRemoveFunction());
+ api_test_utils::RunFunction(remove_function.get(),
+ base::StringPrintf("[\"%s\"]", node_id().c_str()),
+ profile());
+
+ // Call bookmarkManagerPrivate.copy() with the removed bookmark node's id.
+ scoped_refptr<BookmarkManagerPrivateCopyFunction> copy_function(
+ new BookmarkManagerPrivateCopyFunction());
+ EXPECT_EQ(
+ "Could not find bookmark nodes with given ids.",
+ api_test_utils::RunFunctionAndReturnError(
+ copy_function.get(),
+ base::StringPrintf("[[\"%s\"]]", node_id().c_str()), profile()));
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc
index 9cf5c20c80a..1b74a4904d8 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc
@@ -159,7 +159,7 @@ void GetMetaInfo(const BookmarkNode& node,
if (meta_info) {
BookmarkNode::MetaInfoMap::const_iterator itr;
for (itr = meta_info->begin(); itr != meta_info->end(); ++itr) {
- value->SetStringWithoutPathExpansion(itr->first, itr->second);
+ value->SetKey(itr->first, base::Value(itr->second));
}
}
id_to_meta_info_map->Set(base::Int64ToString(node.id()), std::move(value));
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
index 5849981245d..6e5dc26dd00 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
@@ -558,21 +558,6 @@ bool BookmarksSearchFunction::RunOnReady() {
return true;
}
-// static
-bool BookmarksRemoveFunction::ExtractIds(const base::ListValue* args,
- std::list<int64_t>* ids,
- bool* invalid_id) {
- std::string id_string;
- if (!args->GetString(0, &id_string))
- return false;
- int64_t id;
- if (base::StringToInt64(id_string, &id))
- ids->push_back(id);
- else
- *invalid_id = true;
- return true;
-}
-
bool BookmarksRemoveFunction::RunOnReady() {
if (!EditBookmarksEnabled())
return false;
@@ -618,14 +603,6 @@ bool BookmarksCreateFunction::RunOnReady() {
return true;
}
-// static
-bool BookmarksMoveFunction::ExtractIds(const base::ListValue* args,
- std::list<int64_t>* ids,
- bool* invalid_id) {
- // For now, Move accepts ID parameters in the same way as an Update.
- return BookmarksUpdateFunction::ExtractIds(args, ids, invalid_id);
-}
-
bool BookmarksMoveFunction::RunOnReady() {
if (!EditBookmarksEnabled())
return false;
@@ -679,14 +656,6 @@ bool BookmarksMoveFunction::RunOnReady() {
return true;
}
-// static
-bool BookmarksUpdateFunction::ExtractIds(const base::ListValue* args,
- std::list<int64_t>* ids,
- bool* invalid_id) {
- // For now, Update accepts ID parameters in the same way as an Remove.
- return BookmarksRemoveFunction::ExtractIds(args, ids, invalid_id);
-}
-
bool BookmarksUpdateFunction::RunOnReady() {
if (!EditBookmarksEnabled())
return false;
@@ -758,7 +727,7 @@ void BookmarksIOFunction::ShowSelectFileDialog(
WebContents* web_contents = GetAssociatedWebContents();
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_contents));
+ this, std::make_unique<ChromeSelectFilePolicy>(web_contents));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.resize(1);
file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html"));
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
index c81641f50fe..f67548f71c8 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
@@ -248,12 +248,6 @@ class BookmarksRemoveFunction : public BookmarksFunction {
public:
DECLARE_EXTENSION_FUNCTION("bookmarks.remove", BOOKMARKS_REMOVE)
- // Returns true on successful parse and sets invalid_id to true if conversion
- // from id string to int64_t failed.
- static bool ExtractIds(const base::ListValue* args,
- std::list<int64_t>* ids,
- bool* invalid_id);
-
protected:
~BookmarksRemoveFunction() override {}
@@ -284,10 +278,6 @@ class BookmarksMoveFunction : public BookmarksFunction {
public:
DECLARE_EXTENSION_FUNCTION("bookmarks.move", BOOKMARKS_MOVE)
- static bool ExtractIds(const base::ListValue* args,
- std::list<int64_t>* ids,
- bool* invalid_id);
-
protected:
~BookmarksMoveFunction() override {}
@@ -299,10 +289,6 @@ class BookmarksUpdateFunction : public BookmarksFunction {
public:
DECLARE_EXTENSION_FUNCTION("bookmarks.update", BOOKMARKS_UPDATE)
- static bool ExtractIds(const base::ListValue* args,
- std::list<int64_t>* ids,
- bool* invalid_id);
-
protected:
~BookmarksUpdateFunction() override {}
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/OWNERS b/chromium/chrome/browser/extensions/api/braille_display_private/OWNERS
index 8049d3c4fd9..47e691696de 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/OWNERS
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/OWNERS
@@ -1,6 +1,4 @@
-dmazzoni@chromium.org
-dtseng@chromium.org
-plundblad@chromium.org
+file://ui/accessibility/OWNERS
# TEAM: chromium-accessibility@chromium.org
-# COMPONENT: UI>Accessibility
+# COMPONENT: UI>Accessibility>ChromeVox
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 ec59bcfe0ef..205b23130c1 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,6 +15,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/macros.h"
+#include "base/task_scheduler/post_task.h"
#include "base/time/time.h"
#include "chrome/browser/extensions/api/braille_display_private/brlapi_connection.h"
#include "chrome/browser/extensions/api/braille_display_private/brlapi_keycode_map.h"
@@ -166,34 +167,41 @@ void BrailleControllerImpl::StartConnecting() {
if (!libbrlapi_loader_.loaded()) {
return;
}
+
+ if (!sequenced_task_runner_) {
+ sequenced_task_runner_ = base::CreateSequencedTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE});
+ }
+
// Only try to connect after we've started to watch the
// socket directory. This is necessary to avoid a race condition
// and because we don't retry to connect after errors that will
// persist until there's a change to the socket directory (i.e.
// ENOENT).
- BrowserThread::PostTaskAndReply(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&BrailleControllerImpl::StartWatchingSocketDirOnFileThread,
+ sequenced_task_runner_->PostTaskAndReply(
+ FROM_HERE,
+ base::BindOnce(&BrailleControllerImpl::StartWatchingSocketDirOnTaskThread,
base::Unretained(this)),
base::BindOnce(&BrailleControllerImpl::TryToConnect,
base::Unretained(this)));
ResetRetryConnectHorizon();
}
-void BrailleControllerImpl::StartWatchingSocketDirOnFileThread() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+void BrailleControllerImpl::StartWatchingSocketDirOnTaskThread() {
+ base::ThreadRestrictions::AssertIOAllowed();
base::FilePath brlapi_dir(BRLAPI_SOCKETPATH);
if (!file_path_watcher_.Watch(
- brlapi_dir, false, base::Bind(
- &BrailleControllerImpl::OnSocketDirChangedOnFileThread,
- base::Unretained(this)))) {
+ brlapi_dir, false,
+ base::Bind(&BrailleControllerImpl::OnSocketDirChangedOnTaskThread,
+ base::Unretained(this)))) {
LOG(WARNING) << "Couldn't watch brlapi directory " << BRLAPI_SOCKETPATH;
}
}
-void BrailleControllerImpl::OnSocketDirChangedOnFileThread(
- const base::FilePath& path, bool error) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+void BrailleControllerImpl::OnSocketDirChangedOnTaskThread(
+ const base::FilePath& path,
+ bool error) {
+ base::ThreadRestrictions::AssertIOAllowed();
if (error) {
LOG(ERROR) << "Error watching brlapi directory: " << path.value();
return;
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 63962e844f5..82fe471bf73 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
@@ -55,8 +55,8 @@ class BrailleControllerImpl : public BrailleController {
// Tries to connect and starts watching for new brlapi servers.
// No-op if already called.
void StartConnecting();
- void StartWatchingSocketDirOnFileThread();
- void OnSocketDirChangedOnFileThread(const base::FilePath& path, bool error);
+ void StartWatchingSocketDirOnTaskThread();
+ void OnSocketDirChangedOnTaskThread(const base::FilePath& path, bool error);
void OnSocketDirChangedOnIOThread();
void TryToConnect();
void ResetRetryConnectHorizon();
@@ -75,11 +75,12 @@ class BrailleControllerImpl : public BrailleController {
bool started_connecting_;
bool connect_scheduled_;
base::Time retry_connect_horizon_;
+ scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_;
// Manipulated on the UI thread.
base::ObserverList<BrailleObserver> observers_;
- // Manipulated on the FILE thread.
+ // Manipulated by the SequencedTaskRunner.
base::FilePathWatcher file_path_watcher_;
friend struct base::DefaultSingletonTraits<BrailleControllerImpl>;
diff --git a/chromium/chrome/browser/extensions/api/browser/browser_apitest.cc b/chromium/chrome/browser/extensions/api/browser/browser_apitest.cc
index d250398d16c..9ca942fa8c8 100644
--- a/chromium/chrome/browser/extensions/api/browser/browser_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/browser/browser_apitest.cc
@@ -10,7 +10,7 @@
#include "chrome/browser/extensions/api/browser/browser_api.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/test/base/in_process_browser_test.h"
-#include "extensions/common/test_util.h"
+#include "extensions/common/extension_builder.h"
namespace extensions {
@@ -28,7 +28,7 @@ IN_PROC_BROWSER_TEST_F(BrowserApiTest, OpenTab) {
scoped_refptr<api::BrowserOpenTabFunction> function =
new api::BrowserOpenTabFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
base::Value* result = utils::RunFunctionAndReturnSingleResult(
function.get(),
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 cf6a8ec8470..c16ed76a1da 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
@@ -20,8 +20,8 @@
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
-#include "components/browsing_data/core/browsing_data_utils.h"
#include "components/browsing_data/core/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_remover.h"
@@ -29,9 +29,10 @@
#include "extensions/common/extension.h"
using content::BrowserThread;
+using browsing_data::ClearBrowsingDataTab;
+using browsing_data::BrowsingDataType;
namespace extension_browsing_data_api_constants {
-
// Parameter name keys.
const char kDataRemovalPermittedKey[] = "dataRemovalPermitted";
const char kDataToRemoveKey[] = "dataToRemove";
@@ -65,8 +66,9 @@ const char kUnprotectedWebKey[] = "unprotectedWeb";
// The placeholder will be filled by the name of the affected data type (e.g.,
// "history").
const char kBadDataTypeDetails[] = "Invalid value for data type '%s'.";
-const char kDeleteProhibitedError[] = "Browsing history and downloads are not "
- "permitted to be removed.";
+const char kDeleteProhibitedError[] =
+ "Browsing history and downloads are not "
+ "permitted to be removed.";
} // namespace extension_browsing_data_api_constants
@@ -123,9 +125,23 @@ bool IsRemovalPermitted(int removal_mask, PrefService* prefs) {
} // namespace
+bool BrowsingDataSettingsFunction::isDataTypeSelected(
+ BrowsingDataType data_type,
+ ClearBrowsingDataTab tab) {
+ std::string pref_name;
+ bool success = GetDeletionPreferenceFromDataType(data_type, tab, &pref_name);
+ return success && prefs_->GetBoolean(pref_name);
+}
+
ExtensionFunction::ResponseAction BrowsingDataSettingsFunction::Run() {
prefs_ = Profile::FromBrowserContext(browser_context())->GetPrefs();
+ ClearBrowsingDataTab tab =
+ base::FeatureList::IsEnabled(features::kTabsInCbd)
+ ? static_cast<ClearBrowsingDataTab>(prefs_->GetInteger(
+ browsing_data::prefs::kLastClearBrowsingDataTab))
+ : ClearBrowsingDataTab::ADVANCED;
+
// Fill origin types.
// The "cookies" and "hosted apps" UI checkboxes both map to
// REMOVE_SITE_DATA in browsing_data_remover.h, the former for the unprotected
@@ -135,15 +151,17 @@ ExtensionFunction::ResponseAction BrowsingDataSettingsFunction::Run() {
new base::DictionaryValue);
origin_types->SetBoolean(
extension_browsing_data_api_constants::kUnprotectedWebKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeleteCookies));
+ isDataTypeSelected(BrowsingDataType::COOKIES, tab));
origin_types->SetBoolean(
extension_browsing_data_api_constants::kProtectedWebKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeleteHostedAppsData));
+ isDataTypeSelected(BrowsingDataType::HOSTED_APPS_DATA, tab));
origin_types->SetBoolean(
extension_browsing_data_api_constants::kExtensionsKey, false);
// Fill deletion time period.
- int period_pref = prefs_->GetInteger(browsing_data::prefs::kDeleteTimePeriod);
+ int period_pref =
+ prefs_->GetInteger(browsing_data::GetTimePeriodPreferenceName(tab));
+
browsing_data::TimePeriod period =
static_cast<browsing_data::TimePeriod>(period_pref);
double since = 0;
@@ -162,8 +180,8 @@ ExtensionFunction::ResponseAction BrowsingDataSettingsFunction::Run() {
std::unique_ptr<base::DictionaryValue> permitted(new base::DictionaryValue);
bool delete_site_data =
- prefs_->GetBoolean(browsing_data::prefs::kDeleteCookies) ||
- prefs_->GetBoolean(browsing_data::prefs::kDeleteHostedAppsData);
+ isDataTypeSelected(BrowsingDataType::COOKIES, tab) ||
+ isDataTypeSelected(BrowsingDataType::HOSTED_APPS_DATA, tab);
SetDetails(selected.get(), permitted.get(),
extension_browsing_data_api_constants::kAppCacheKey,
@@ -200,19 +218,19 @@ ExtensionFunction::ResponseAction BrowsingDataSettingsFunction::Run() {
SetDetails(selected.get(), permitted.get(),
extension_browsing_data_api_constants::kHistoryKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory));
+ isDataTypeSelected(BrowsingDataType::HISTORY, tab));
SetDetails(selected.get(), permitted.get(),
extension_browsing_data_api_constants::kDownloadsKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory));
+ isDataTypeSelected(BrowsingDataType::DOWNLOADS, tab));
SetDetails(selected.get(), permitted.get(),
extension_browsing_data_api_constants::kCacheKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeleteCache));
+ isDataTypeSelected(BrowsingDataType::CACHE, tab));
SetDetails(selected.get(), permitted.get(),
extension_browsing_data_api_constants::kFormDataKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeleteFormData));
+ isDataTypeSelected(BrowsingDataType::FORM_DATA, tab));
SetDetails(selected.get(), permitted.get(),
extension_browsing_data_api_constants::kPasswordsKey,
- prefs_->GetBoolean(browsing_data::prefs::kDeletePasswords));
+ isDataTypeSelected(BrowsingDataType::PASSWORDS, tab));
std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue);
result->Set(extension_browsing_data_api_constants::kOptionsKey,
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 ac01ad0801f..15db8b7d0ed 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
@@ -13,6 +13,7 @@
#include "base/scoped_observer.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
+#include "components/browsing_data/core/browsing_data_utils.h"
#include "content/public/browser/browsing_data_remover.h"
class PluginPrefs;
@@ -74,6 +75,10 @@ class BrowsingDataSettingsFunction : public UIThreadExtensionFunction {
const char* data_type,
bool is_selected);
+ // Returns whether |data_type| is currently selected for deletion on |tab|.
+ bool isDataTypeSelected(browsing_data::BrowsingDataType data_type,
+ browsing_data::ClearBrowsingDataTab tab);
+
PrefService* prefs_ = nullptr;
};
diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
index 22e22849475..8c7a131d0c4 100644
--- a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
@@ -337,13 +337,10 @@ class CastStreamingApiTestWithPixelOutput : public CastStreamingApiTest {
// 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.
-//
-// TODO(miu): Now that this test has been long-stable on Release build bots, it
-// should be enabled for the Debug build bots. http://crbug.com/396413
#if defined(NDEBUG)
#define MAYBE_EndToEnd EndToEnd
#else
-#define MAYBE_EndToEnd DISABLED_EndToEnd
+#define MAYBE_EndToEnd DISABLED_EndToEnd // crbug.com/396413
#endif
IN_PROC_BROWSER_TEST_F(CastStreamingApiTestWithPixelOutput, MAYBE_EndToEnd) {
std::unique_ptr<net::UDPServerSocket> receive_socket(
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 a570d506aeb..58646f752a2 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
@@ -4,16 +4,21 @@
#include "chrome/browser/extensions/api/chrome_extensions_api_client.h"
+#include <utility>
+
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/memory/ptr_util.h"
+#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "chrome/browser/data_use_measurement/data_use_web_contents_observer.h"
#include "chrome/browser/extensions/api/chrome_device_permissions_prompt.h"
#include "chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h"
#include "chrome/browser/extensions/api/declarative_content/default_content_predicate_evaluators.h"
+#include "chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h"
#include "chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h"
#include "chrome/browser/extensions/api/management/chrome_management_api_delegate.h"
+#include "chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h"
#include "chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h"
#include "chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.h"
#include "chrome/browser/extensions/api/storage/managed_value_store_cache.h"
@@ -29,12 +34,15 @@
#include "chrome/browser/guest_view/web_view/chrome_web_view_permission_helper_delegate.h"
#include "chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.h"
#include "components/pdf/browser/pdf_web_contents_helper.h"
+#include "components/signin/core/browser/signin_header_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/api/virtual_keyboard_private/virtual_keyboard_delegate.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 "google_apis/gaia/gaia_urls.h"
#include "printing/features/features.h"
+#include "url/gurl.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/extensions/api/file_handlers/non_native_file_system_delegate_chromeos.h"
@@ -43,13 +51,8 @@
#endif
#if BUILDFLAG(ENABLE_PRINTING)
-#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
-#include "chrome/browser/printing/print_preview_message_handler.h"
-#include "chrome/browser/printing/print_view_manager.h"
-#else
-#include "chrome/browser/printing/print_view_manager_basic.h"
-#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
-#endif // BUILDFLAG(ENABLE_PRINTING)
+#include "chrome/browser/printing/printing_init.h"
+#endif
namespace extensions {
@@ -76,13 +79,8 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers(
content::WebContents* web_contents) const {
favicon::CreateContentFaviconDriverForWebContents(web_contents);
#if BUILDFLAG(ENABLE_PRINTING)
-#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
- printing::PrintViewManager::CreateForWebContents(web_contents);
- printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
-#else
- printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
-#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
-#endif // BUILDFLAG(ENABLE_PRINTING)
+ printing::InitializePrinting(web_contents);
+#endif
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents, std::unique_ptr<pdf::PDFWebContentsHelperClient>(
new ChromePDFWebContentsHelperClient()));
@@ -93,6 +91,17 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers(
web_contents);
}
+bool ChromeExtensionsAPIClient::ShouldHideResponseHeader(
+ const GURL& url,
+ const std::string& header_name) const {
+ // Gaia may send a OAUth2 authorization code in the Dice response header,
+ // which could allow an extension to generate a refresh token for the account.
+ return (
+ (url.host_piece() == GaiaUrls::GetInstance()->gaia_url().host_piece()) &&
+ (base::CompareCaseInsensitiveASCII(header_name,
+ signin::kDiceResponseHeader) == 0));
+}
+
AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate()
const {
return new ChromeAppViewGuestDelegate();
@@ -186,6 +195,21 @@ FileSystemDelegate* ChromeExtensionsAPIClient::GetFileSystemDelegate() {
return file_system_delegate_.get();
}
+MessagingDelegate* ChromeExtensionsAPIClient::GetMessagingDelegate() {
+ if (!messaging_delegate_)
+ messaging_delegate_ = base::MakeUnique<ChromeMessagingDelegate>();
+ return messaging_delegate_.get();
+}
+
+FeedbackPrivateDelegate*
+ChromeExtensionsAPIClient::GetFeedbackPrivateDelegate() {
+ if (!feedback_private_delegate_) {
+ feedback_private_delegate_ =
+ base::MakeUnique<ChromeFeedbackPrivateDelegate>();
+ }
+ return feedback_private_delegate_.get();
+}
+
#if defined(OS_CHROMEOS)
NonNativeFileSystemDelegate*
ChromeExtensionsAPIClient::GetNonNativeFileSystemDelegate() {
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 1b791b9726d..eb300332f5b 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
@@ -30,6 +30,8 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
override;
void AttachWebContentsHelpers(content::WebContents* web_contents) const
override;
+ bool ShouldHideResponseHeader(const GURL& url,
+ const std::string& header_name) const override;
AppViewGuestDelegate* CreateAppViewGuestDelegate() const override;
ExtensionOptionsGuestDelegate* CreateExtensionOptionsGuestDelegate(
ExtensionOptionsGuest* guest) const override;
@@ -56,6 +58,8 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
MetricsPrivateDelegate* GetMetricsPrivateDelegate() override;
NetworkingCastPrivateDelegate* GetNetworkingCastPrivateDelegate() override;
FileSystemDelegate* GetFileSystemDelegate() override;
+ MessagingDelegate* GetMessagingDelegate() override;
+ FeedbackPrivateDelegate* GetFeedbackPrivateDelegate() override;
#if defined(OS_CHROMEOS)
NonNativeFileSystemDelegate* GetNonNativeFileSystemDelegate() override;
@@ -73,6 +77,8 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
std::unique_ptr<NetworkingCastPrivateDelegate>
networking_cast_private_delegate_;
std::unique_ptr<FileSystemDelegate> file_system_delegate_;
+ std::unique_ptr<MessagingDelegate> messaging_delegate_;
+ std::unique_ptr<FeedbackPrivateDelegate> feedback_private_delegate_;
#if defined(OS_CHROMEOS)
std::unique_ptr<NonNativeFileSystemDelegate> non_native_file_system_delegate_;
diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc
new file mode 100644
index 00000000000..8e2738c02a5
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc
@@ -0,0 +1,25 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/chrome_extensions_api_client.h"
+
+#include "google_apis/gaia/gaia_urls.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace extensions {
+
+TEST(TestChromeExtensionsAPIClient, ShouldHideResponseHeader) {
+ ChromeExtensionsAPIClient client;
+ EXPECT_TRUE(client.ShouldHideResponseHeader(
+ GaiaUrls::GetInstance()->gaia_url(), "X-Chrome-ID-Consistency-Response"));
+ EXPECT_TRUE(client.ShouldHideResponseHeader(
+ GaiaUrls::GetInstance()->gaia_url(), "x-cHroMe-iD-CoNsiStenCY-RESPoNSE"));
+ EXPECT_FALSE(client.ShouldHideResponseHeader(
+ GURL("http://www.example.com"), "X-Chrome-ID-Consistency-Response"));
+ EXPECT_FALSE(client.ShouldHideResponseHeader(
+ GaiaUrls::GetInstance()->gaia_url(), "Google-Accounts-SignOut"));
+}
+
+} // namespace extensions
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 18bcd1195a5..f4e45f5c1dd 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
@@ -204,6 +204,9 @@ ContentSettingsContentSettingSetFunction::Run() {
ContentSetting setting;
EXTENSION_FUNCTION_VALIDATE(
content_settings::ContentSettingFromString(setting_str, &setting));
+ // The content settings extensions API does not support setting any content
+ // settings to |CONTENT_SETTING_DEFAULT|.
+ EXTENSION_FUNCTION_VALIDATE(CONTENT_SETTING_DEFAULT != setting);
EXTENSION_FUNCTION_VALIDATE(
content_settings::ContentSettingsRegistry::GetInstance()
->Get(content_type)
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 050dd7edd03..dd3ce91a420 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
@@ -339,6 +339,9 @@ void ContentSettingsStore::SetExtensionContentSettingFromList(
bool result = content_settings::ContentSettingFromString(
content_setting_string, &setting);
DCHECK(result);
+ // The content settings extensions API does not support setting any content
+ // settings to |CONTENT_SETTING_DEFAULT|.
+ DCHECK_NE(CONTENT_SETTING_DEFAULT, setting);
SetExtensionContentSetting(extension_id,
primary_pattern,
diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc b/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc
index 2dcdab13709..14294b8c46a 100644
--- a/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc
@@ -2,17 +2,130 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_action.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
+#include "chrome/browser/extensions/menu_manager.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
+#include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/common/extensions/api/context_menus.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/common/context_menu_params.h"
+#include "content/public/test/browser_test_utils.h"
#include "extensions/test/result_catcher.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "ui/base/models/menu_model.h"
namespace extensions {
+class ExtensionContextMenuApiTest : public ExtensionApiTest {
+ public:
+ ExtensionContextMenuApiTest()
+ : top_level_model_(nullptr), menu_(nullptr), top_level_index_(-1) {}
+
+ void SetUpTestExtension() {
+ extension_ = LoadExtension(
+ test_data_dir_.AppendASCII("context_menus/item_visibility/"));
+ }
+
+ // Sets up the top-level model, which is the list of menu items (both related
+ // and unrelated to extensions) that is passed to UI code to be displayed.
+ bool SetupTopLevelMenuModel() {
+ content::RenderFrameHost* frame =
+ browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame();
+ content::ContextMenuParams params;
+ params.page_url = frame->GetLastCommittedURL();
+
+ // Create context menu.
+ menu_.reset(new TestRenderViewContextMenu(frame, params));
+ menu_->Init();
+
+ // Get menu model.
+ bool valid_setup = menu_->GetMenuModelAndItemIndex(
+ menu_->extension_items().ConvertToExtensionsCustomCommandId(0),
+ &top_level_model_, &top_level_index_);
+
+ EXPECT_GT(top_level_index(), 0);
+
+ return valid_setup;
+ }
+
+ void CallAPI(const std::string& script) { CallAPI(extension_, script); }
+
+ void CallAPI(const Extension* extension, const std::string& script) {
+ content::RenderViewHost* background_page =
+ GetBackgroundPage(extension->id());
+ bool error = false;
+ ASSERT_TRUE(
+ content::ExecuteScriptAndExtractBool(background_page, script, &error));
+ ASSERT_FALSE(error);
+ }
+
+ // Verifies that the UI menu model has the given number of extension menu
+ // items, |num_items|, of a menu model |type|.
+ void VerifyNumExtensionItemsInMenuModel(int num_items,
+ ui::MenuModel::ItemType type) {
+ int num_found = 0;
+ for (int i = 0; i < top_level_model_->GetItemCount(); i++) {
+ int command_id = top_level_model_->GetCommandIdAt(i);
+ if (command_id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
+ command_id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST &&
+ top_level_model_->GetTypeAt(i) == type) {
+ num_found++;
+ }
+ }
+ ASSERT_TRUE(num_found == num_items);
+ }
+
+ // Verifies that the context menu is valid and contains the given number of
+ // menu items, |num_items|.
+ void VerifyNumContextMenuItems(int num_items) {
+ ASSERT_TRUE(menu());
+ EXPECT_EQ(num_items,
+ (int)(menu_->extension_items().extension_item_map_.size()));
+ }
+
+ // Verifies a context menu item's visibility, title, and item type.
+ void VerifyMenuItem(const std::string& title,
+ ui::MenuModel* model,
+ int index,
+ ui::MenuModel::ItemType type,
+ bool visible) {
+ EXPECT_EQ(base::ASCIIToUTF16(title), model->GetLabelAt(index));
+ ASSERT_EQ(type, model->GetTypeAt(index));
+ EXPECT_EQ(visible, model->IsVisibleAt(index));
+ }
+
+ int top_level_index() { return top_level_index_; }
+
+ TestRenderViewContextMenu* menu() { return menu_.get(); }
+
+ const Extension* extension() { return extension_; }
+
+ ui::MenuModel* top_level_model_;
+
+ private:
+ content::RenderViewHost* GetBackgroundPage(const std::string& extension_id) {
+ return process_manager()
+ ->GetBackgroundHostForExtension(extension_id)
+ ->render_view_host();
+ }
+
+ ProcessManager* process_manager() { return ProcessManager::Get(profile()); }
+
+ const Extension* extension_;
+ std::unique_ptr<TestRenderViewContextMenu> menu_;
+ int top_level_index_;
+
+ DISALLOW_COPY_AND_ASSIGN(ExtensionContextMenuApiTest);
+};
+
// Times out on win syzyasan, http://crbug.com/166026
#if defined(SYZYASAN)
#define MAYBE_ContextMenus DISABLED_ContextMenus
@@ -32,7 +145,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContextMenusFromMultipleContexts) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(RunExtensionTest("context_menus/add_from_multiple_contexts"))
<< message_;
- const extensions::Extension* extension = GetSingleLoadedExtension();
+ const Extension* extension = GetSingleLoadedExtension();
ASSERT_TRUE(extension) << message_;
{
@@ -52,4 +165,279 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContextMenusFromMultipleContexts) {
}
}
+// Tests showing a single visible menu item in the top-level menu model, which
+// includes actions like "Back", "View Page Source", "Inspect", etc.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest, ShowOneTopLevelItem) {
+ SetUpTestExtension();
+ CallAPI("create({title: 'item', visible: true});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(1);
+
+ VerifyMenuItem("item", top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_COMMAND, true);
+
+ // There should be no submenu model.
+ EXPECT_FALSE(top_level_model_->GetSubmenuModelAt(top_level_index()));
+}
+
+// Tests hiding a menu item in the top-level menu model, which includes actions
+// like "Back", "View Page Source", "Inspect", etc.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest, HideTopLevelItem) {
+ SetUpTestExtension();
+ CallAPI("create({id: 'item1', title: 'item', visible: true});");
+ CallAPI("update('item1', {visible: false});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(1);
+
+ VerifyMenuItem("item", top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_COMMAND, false);
+
+ // There should be no submenu model.
+ EXPECT_FALSE(top_level_model_->GetSubmenuModelAt(top_level_index()));
+}
+
+// Tests hiding a parent menu item, when it is hidden and so are all of its
+// children.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ HideTopLevelSubmenuItemIfHiddenAndChildrenHidden) {
+ SetUpTestExtension();
+ CallAPI("create({id: 'id', title: 'parent', visible: false});");
+ CallAPI("create({title: 'child1', parentId: 'id', visible: false});");
+ CallAPI("create({title: 'child2', parentId: 'id', visible: false});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(3);
+
+ VerifyMenuItem("parent", top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, false);
+
+ // Since the extension submenu is hidden, the previous separator should not be
+ // in the model.
+ EXPECT_NE(ui::MenuModel::TYPE_SEPARATOR,
+ top_level_model_->GetTypeAt(top_level_index() - 1));
+
+ ui::MenuModel* submodel =
+ top_level_model_->GetSubmenuModelAt(top_level_index());
+ ASSERT_TRUE(submodel);
+ EXPECT_EQ(2, submodel->GetItemCount());
+
+ VerifyMenuItem("child1", submodel, 0, ui::MenuModel::TYPE_COMMAND, false);
+ VerifyMenuItem("child2", submodel, 1, ui::MenuModel::TYPE_COMMAND, false);
+}
+
+// Tests hiding a parent menu item, when it is hidden and some of its children
+// are visible.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ HideTopLevelSubmenuItemIfHiddenAndSomeChildrenVisible) {
+ SetUpTestExtension();
+ CallAPI("create({id: 'id', title: 'parent', visible: false});");
+ CallAPI("create({title: 'child1', parentId: 'id', visible: false});");
+ CallAPI("create({title: 'child2', parentId: 'id', visible: true});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(3);
+
+ VerifyMenuItem("parent", top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, false);
+
+ // Since the extension submenu is hidden, the previous separator should not be
+ // in the model.
+ EXPECT_NE(ui::MenuModel::TYPE_SEPARATOR,
+ top_level_model_->GetTypeAt(top_level_index() - 1));
+
+ ui::MenuModel* submodel =
+ top_level_model_->GetSubmenuModelAt(top_level_index());
+ ASSERT_TRUE(submodel);
+ EXPECT_EQ(2, submodel->GetItemCount());
+
+ // Though the children's internal visibility state remains unchanged, the ui
+ // code will hide the children if the parent is hidden.
+ VerifyMenuItem("child1", submodel, 0, ui::MenuModel::TYPE_COMMAND, false);
+ VerifyMenuItem("child2", submodel, 1, ui::MenuModel::TYPE_COMMAND, true);
+}
+
+// Tests showing a single top-level parent menu item, when it is visible, but
+// all of its child items are hidden. The child items' hidden states are tested
+// too. Recall that a top-level item can be either a parent item specified by
+// the developer or parent item labeled with the extension's name. In this case,
+// we test the former.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ ShowTopLevelItemIfAllItsChildrenAreHidden) {
+ SetUpTestExtension();
+ CallAPI("create({id: 'id', title: 'parent', visible: true});");
+ CallAPI("create({title: 'child1', parentId: 'id', visible: false});");
+ CallAPI("create({title: 'child2', parentId: 'id', visible: false});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(3);
+
+ VerifyMenuItem("parent", top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, true);
+
+ // Since the extension submenu is shown, the previous separator should be in
+ // the model.
+ EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR,
+ top_level_model_->GetTypeAt(top_level_index() - 1));
+
+ ui::MenuModel* submodel =
+ top_level_model_->GetSubmenuModelAt(top_level_index());
+ ASSERT_TRUE(submodel);
+ EXPECT_EQ(2, submodel->GetItemCount());
+
+ VerifyMenuItem("child1", submodel, 0, ui::MenuModel::TYPE_COMMAND, false);
+ VerifyMenuItem("child2", submodel, 1, ui::MenuModel::TYPE_COMMAND, false);
+}
+
+// Tests showing a top-level parent menu item as a submenu, when some of its
+// child items are visibile. The child items' visibilities are tested too.
+// Recall that a top-level item can be either a parent item specified by the
+// developer or parent item labeled with the extension's name. In this case, we
+// test the former.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ ShowTopLevelSubmenuItemIfSomeOfChildrenAreVisible) {
+ SetUpTestExtension();
+ CallAPI("create({id: 'id', title: 'parent', visible: true});");
+ CallAPI("create({title: 'child1', parentId: 'id', visible: true});");
+ CallAPI("create({title: 'child2', parentId: 'id', visible: false});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(3);
+
+ VerifyMenuItem("parent", top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, true);
+
+ // Since the extension submenu is shown, the previous separator should be in
+ // the model.
+ EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR,
+ top_level_model_->GetTypeAt(top_level_index() - 1));
+
+ ui::MenuModel* submodel =
+ top_level_model_->GetSubmenuModelAt(top_level_index());
+ ASSERT_TRUE(submodel);
+ EXPECT_EQ(2, submodel->GetItemCount());
+
+ VerifyMenuItem("child1", submodel, 0, ui::MenuModel::TYPE_COMMAND, true);
+ VerifyMenuItem("child2", submodel, 1, ui::MenuModel::TYPE_COMMAND, false);
+}
+
+// Tests showing a top-level parent menu item, when all of its child items are
+// hidden. Recall that a top-level item can be either a parent item specified by
+// the developer or parent item labeled with the extension's name. In this case,
+// we test the latter. This extension-named top-level item should always be
+// visible.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ ShowExtensionNamedTopLevelItemIfAllChildrenAreHidden) {
+ SetUpTestExtension();
+ CallAPI("create({title: 'item1', visible: false});");
+ CallAPI("create({title: 'item2', visible: false});");
+ CallAPI("create({title: 'item3', visible: false});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(3);
+
+ VerifyMenuItem(extension()->name(), top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, true);
+
+ // Since the extension submenu is shown, the previous separator should be in
+ // the model.
+ EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR,
+ top_level_model_->GetTypeAt(top_level_index() - 1));
+
+ ui::MenuModel* submodel =
+ top_level_model_->GetSubmenuModelAt(top_level_index());
+ ASSERT_TRUE(submodel);
+ EXPECT_EQ(3, submodel->GetItemCount());
+
+ VerifyMenuItem("item1", submodel, 0, ui::MenuModel::TYPE_COMMAND, false);
+ VerifyMenuItem("item2", submodel, 1, ui::MenuModel::TYPE_COMMAND, false);
+ VerifyMenuItem("item3", submodel, 2, ui::MenuModel::TYPE_COMMAND, false);
+}
+
+// Tests showing a top-level parent menu item, when some of its child items are
+// visible. The child items' visibilities are tested as well. Recall that a
+// top-level item can be either a parent item specified by the developer or
+// parent item labeled with the extension's name. In this case, we test the
+// latter.
+//
+// Also, this tests that hiding a parent item should hide its children even if
+// they are set as visible.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ ShowExtensionNamedTopLevelItemIfSomeChildrenAreVisible) {
+ SetUpTestExtension();
+ CallAPI("create({title: 'item1'});");
+ CallAPI("create({title: 'item2'});");
+ CallAPI("create({title: 'item3', id: 'item3', visible: false});");
+ CallAPI("create({title: 'child1', visible: true, parentId: 'item3'});");
+ CallAPI("create({title: 'child2', visible: true, parentId: 'item3'});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumContextMenuItems(5);
+
+ VerifyMenuItem(extension()->name(), top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, true);
+
+ // Since the extension submenu is shown, the previous separator should be in
+ // the model.
+ EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR,
+ top_level_model_->GetTypeAt(top_level_index() - 1));
+
+ ui::MenuModel* submodel =
+ top_level_model_->GetSubmenuModelAt(top_level_index());
+ ASSERT_TRUE(submodel);
+ EXPECT_EQ(3, submodel->GetItemCount());
+
+ VerifyMenuItem("item1", submodel, 0, ui::MenuModel::TYPE_COMMAND, true);
+ VerifyMenuItem("item2", submodel, 1, ui::MenuModel::TYPE_COMMAND, true);
+ VerifyMenuItem("item3", submodel, 2, ui::MenuModel::TYPE_SUBMENU, false);
+
+ ui::MenuModel* item3_submodel = submodel->GetSubmenuModelAt(2);
+ ASSERT_TRUE(item3_submodel);
+ EXPECT_EQ(2, item3_submodel->GetItemCount());
+
+ // Though the children's internal visibility state remains unchanged, the ui
+ // code will hide the children if the parent is hidden.
+ VerifyMenuItem("child1", item3_submodel, 0, ui::MenuModel::TYPE_COMMAND,
+ true);
+ VerifyMenuItem("child2", item3_submodel, 1, ui::MenuModel::TYPE_COMMAND,
+ true);
+}
+
+// Tests that more than one extension named top-level parent menu item can be
+// displayed in the context menu.
+IN_PROC_BROWSER_TEST_F(ExtensionContextMenuApiTest,
+ ShowMultipleExtensionNamedTopLevelItemsWithChidlren) {
+ const Extension* e1 =
+ LoadExtension(test_data_dir_.AppendASCII("context_menus/simple/one"));
+ const Extension* e2 =
+ LoadExtension(test_data_dir_.AppendASCII("context_menus/simple/two"));
+
+ CallAPI(e1, "create({title: 'item1'});");
+ CallAPI(e1, "create({title: 'item2'});");
+ CallAPI(e2, "create({title: 'item1'});");
+ CallAPI(e2, "create({title: 'item2'});");
+
+ ASSERT_TRUE(SetupTopLevelMenuModel());
+
+ VerifyNumExtensionItemsInMenuModel(2, ui::MenuModel::TYPE_SUBMENU);
+
+ // The UI menu model organizes extension menu items alphabetically by
+ // extension name, regardless of installation order. For example, if an
+ // extension named "aaa" was installed after extension "bbb", then extension
+ // "aaa" item would precede "bbb" in the context menu.
+ VerifyMenuItem(e1->name(), top_level_model_, top_level_index(),
+ ui::MenuModel::TYPE_SUBMENU, true);
+ VerifyMenuItem(e2->name(), top_level_model_, top_level_index() + 1,
+ ui::MenuModel::TYPE_SUBMENU, true);
+}
+
} // namespace extensions
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 19b793cd2d0..9b63355c2ed 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
@@ -118,6 +118,11 @@ bool CreateMenuItem(const PropertyWithEnumT& create_properties,
return false;
}
+ // Visibility state.
+ bool visible = true;
+ if (create_properties.visible)
+ visible = *create_properties.visible;
+
// Checked state.
bool checked = false;
if (create_properties.checked.get())
@@ -129,7 +134,7 @@ bool CreateMenuItem(const PropertyWithEnumT& create_properties,
enabled = *create_properties.enabled;
std::unique_ptr<MenuItem> item(
- new MenuItem(item_id, title, checked, enabled, type, contexts));
+ new MenuItem(item_id, title, checked, visible, enabled, type, contexts));
// URL Patterns.
if (!item->PopulateURLPatterns(
@@ -206,7 +211,11 @@ bool UpdateMenuItem(const PropertyWithEnumT& update_properties,
*error = kCheckedError;
return false;
}
- if (checked != item->checked()) {
+ // If the item was not checked and it is updated to be checked, set it to be
+ // checked. If the radio item was unchecked, nothing should happen. The
+ // radio item should remain checked because there should always be one item
+ // checked in the radio list.
+ if (checked && !item->checked()) {
if (!item->SetChecked(checked)) {
*error = kCheckedError;
return false;
@@ -215,6 +224,10 @@ bool UpdateMenuItem(const PropertyWithEnumT& update_properties,
}
}
+ // Visibility state.
+ if (update_properties.visible)
+ item->set_visible(*update_properties.visible);
+
// Enabled.
if (update_properties.enabled.get())
item->set_enabled(*update_properties.enabled);
diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc
index 48e2e90f406..ef11c34e090 100644
--- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc
+++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc
@@ -553,6 +553,19 @@ bool DebuggerFunction::InitClientHost() {
if (!InitAgentHost())
return false;
+ client_host_ = FindClientHost();
+ if (!client_host_) {
+ FormatErrorMessage(keys::kNotAttachedError);
+ return false;
+ }
+
+ return true;
+}
+
+ExtensionDevToolsClientHost* DebuggerFunction::FindClientHost() {
+ if (!agent_host_.get())
+ return nullptr;
+
const std::string& extension_id = extension()->id();
DevToolsAgentHost* agent_host = agent_host_.get();
AttachedClientHosts& hosts = g_attached_client_hosts.Get();
@@ -563,16 +576,9 @@ bool DebuggerFunction::InitClientHost() {
client_host->extension_id() == extension_id;
});
- if (it == hosts.end()) {
- FormatErrorMessage(keys::kNotAttachedError);
- return false;
- }
-
- client_host_ = *it;
- return true;
+ return it == hosts.end() ? nullptr : *it;
}
-
// DebuggerAttachFunction -----------------------------------------------------
DebuggerAttachFunction::DebuggerAttachFunction() {
@@ -597,7 +603,7 @@ bool DebuggerAttachFunction::RunAsync() {
return false;
}
- if (agent_host_->IsAttached()) {
+ if (FindClientHost()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.h b/chromium/chrome/browser/extensions/api/debugger/debugger_api.h
index 8b6a9c4c1bc..4aa46673741 100644
--- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.h
+++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.h
@@ -35,6 +35,7 @@ class DebuggerFunction : public ChromeAsyncExtensionFunction {
bool InitAgentHost();
bool InitClientHost();
+ ExtensionDevToolsClientHost* FindClientHost();
Debuggee debuggee_;
scoped_refptr<content::DevToolsAgentHost> agent_host_;
diff --git a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc
index 10c8a594ee9..8b7df22c693 100644
--- a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc
@@ -659,7 +659,7 @@ TEST_F(WebRequestRulesRegistryTest, GetMatchesDifferentUrls) {
std::unique_ptr<net::URLRequest> http_request(context.CreateRequest(
urls[i], net::DEFAULT_PRIORITY, NULL, TRAFFIC_ANNOTATION_FOR_TESTS));
WebRequestData request_data(http_request.get(), ON_BEFORE_REQUEST);
- http_request->set_first_party_for_cookies(firstPartyUrls[i]);
+ http_request->set_site_for_cookies(firstPartyUrls[i]);
// Now run both rules on the input.
matches = registry->GetMatches(request_data);
SCOPED_TRACE(testing::Message("i = ") << i << ", rule id = "
diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/OWNERS b/chromium/chrome/browser/extensions/api/desktop_capture/OWNERS
index 4a4b9fb224c..c43cfad6ede 100644
--- a/chromium/chrome/browser/extensions/api/desktop_capture/OWNERS
+++ b/chromium/chrome/browser/extensions/api/desktop_capture/OWNERS
@@ -1,5 +1,7 @@
+# Please send the changes to zijiehe@chromium.org first.
sergeyu@chromium.org
wez@chromium.org
+zijiehe@chromium.org
# TEAM: media-capture-and-streams@grotations.appspotmail.com
# COMPONENT: Blink>GetUserMedia>Desktop
diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc
index 1001d5bfb92..d5aecb7e83b 100644
--- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc
@@ -176,8 +176,8 @@ class DesktopCaptureApiTest : public ExtensionApiTest {
} // namespace
// Flaky on Windows: http://crbug.com/301887
-// Fails on Ozone Chrome OS: http://crbug.com/718512
-#if defined(OS_WIN) || (defined(OS_CHROMEOS) && defined(USE_OZONE))
+// Fails on Chrome OS: http://crbug.com/718512
+#if defined(OS_WIN) || defined(OS_CHROMEOS)
#define MAYBE_ChooseDesktopMedia DISABLED_ChooseDesktopMedia
#else
#define MAYBE_ChooseDesktopMedia ChooseDesktopMedia
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 643cd6da1e1..abcb32fa895 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
@@ -69,7 +69,7 @@
#include "extensions/browser/notification_types.h"
#include "extensions/browser/path_util.h"
#include "extensions/browser/warning_service.h"
-#include "extensions/common/constants.h"
+#include "extensions/common/disable_reason.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/install_warning.h"
@@ -77,6 +77,7 @@
#include "extensions/common/manifest_handlers/options_page_info.h"
#include "extensions/common/manifest_url_handlers.h"
#include "extensions/common/permissions/permissions_data.h"
+#include "storage/browser/blob/shareable_file_reference.h"
#include "storage/browser/fileapi/external_mount_points.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_operation.h"
@@ -156,7 +157,7 @@ void PerformVerificationCheck(content::BrowserContext* context) {
for (const scoped_refptr<const Extension>& extension : *extensions) {
if (ui_util::ShouldDisplayInExtensionSettings(extension.get(), context) &&
prefs->HasDisableReason(extension->id(),
- Extension::DISABLE_NOT_VERIFIED)) {
+ disable_reason::DISABLE_NOT_VERIFIED)) {
should_do_verification_check = true;
break;
}
@@ -902,6 +903,7 @@ void DeveloperPrivatePackDirectoryFunction::OnPackSuccess(
PackExtensionJob::StandardSuccessMessage(crx_file, pem_file));
response.status = developer::PACK_STATUS_SUCCESS;
Respond(OneArgument(response.ToValue()));
+ pack_job_.reset();
Release(); // Balanced in Run().
}
@@ -919,6 +921,7 @@ void DeveloperPrivatePackDirectoryFunction::OnPackFailure(
response.status = developer::PACK_STATUS_ERROR;
}
Respond(OneArgument(response.ToValue()));
+ pack_job_.reset();
Release(); // Balanced in Run().
}
@@ -958,8 +961,8 @@ ExtensionFunction::ResponseAction DeveloperPrivatePackDirectoryFunction::Run() {
AddRef(); // Balanced in OnPackSuccess / OnPackFailure.
- // TODO(devlin): Why is PackExtensionJob ref-counted?
- pack_job_ = new PackExtensionJob(this, root_directory, key_file, flags);
+ pack_job_ =
+ base::MakeUnique<PackExtensionJob>(this, root_directory, key_file, flags);
pack_job_->Start();
return RespondLater();
}
@@ -1057,8 +1060,9 @@ bool DeveloperPrivateLoadDirectoryFunction::LoadByFileSystemAPI(
project_base_path_ = project_path;
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
+ base::PostTaskWithTraits(
+ FROM_HERE,
+ {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(
&DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent,
this, project_base_path_));
@@ -1077,7 +1081,6 @@ void DeveloperPrivateLoadDirectoryFunction::Load() {
void DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent(
const base::FilePath& project_path) {
-
// Clear the project directory before copying new files.
base::DeleteFile(project_path, true /*recursive*/);
@@ -1097,16 +1100,16 @@ void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI(
storage::FileSystemURL url = context_->CrackURL(project_url);
context_->operation_runner()->ReadDirectory(
- url, base::Bind(&DeveloperPrivateLoadDirectoryFunction::
- ReadDirectoryByFileSystemAPICb,
- this, project_path, destination_path));
+ url, base::BindRepeating(&DeveloperPrivateLoadDirectoryFunction::
+ ReadDirectoryByFileSystemAPICb,
+ this, project_path, destination_path));
}
void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPICb(
const base::FilePath& project_path,
const base::FilePath& destination_path,
base::File::Error status,
- const storage::FileSystemOperation::FileEntryList& file_list,
+ storage::FileSystemOperation::FileEntryList file_list,
bool has_more) {
if (status != base::File::FILE_OK) {
DLOG(ERROR) << "Error in copying files from sync filesystem.";
@@ -1161,15 +1164,16 @@ void DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback(
base::File::Error result,
const base::File::Info& file_info,
const base::FilePath& src_path,
- const scoped_refptr<storage::ShareableFileReference>& file_ref) {
+ scoped_refptr<storage::ShareableFileReference> file_ref) {
if (result != base::File::FILE_OK) {
SetError("Error in copying files from sync filesystem.");
success_ = false;
return;
}
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
+ base::PostTaskWithTraits(
+ FROM_HERE,
+ {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::CopyFile, this,
src_path, target_path));
}
@@ -1451,7 +1455,8 @@ DeveloperPrivateRepairExtensionFunction::Run() {
return RespondNow(Error(kNoSuchExtensionError));
if (!ExtensionPrefs::Get(browser_context())
- ->HasDisableReason(extension->id(), Extension::DISABLE_CORRUPTED)) {
+ ->HasDisableReason(extension->id(),
+ disable_reason::DISABLE_CORRUPTED)) {
return RespondNow(Error(kCannotRepairHealthyExtension));
}
diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h
index 758015640cf..ac7249690f5 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h
+++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h
@@ -466,7 +466,7 @@ class DeveloperPrivatePackDirectoryFunction
ResponseAction Run() override;
private:
- scoped_refptr<PackExtensionJob> pack_job_;
+ std::unique_ptr<PackExtensionJob> pack_job_;
std::string item_path_str_;
std::string key_path_str_;
};
@@ -509,7 +509,7 @@ class DeveloperPrivateLoadDirectoryFunction
const base::FilePath& project_path,
const base::FilePath& destination_path,
base::File::Error result,
- const storage::FileSystemOperation::FileEntryList& file_list,
+ storage::FileSystemOperation::FileEntryList file_list,
bool has_more);
void SnapshotFileCallback(
@@ -517,7 +517,7 @@ class DeveloperPrivateLoadDirectoryFunction
base::File::Error result,
const base::File::Info& file_info,
const base::FilePath& platform_path,
- const scoped_refptr<storage::ShareableFileReference>& file_ref);
+ scoped_refptr<storage::ShareableFileReference> file_ref);
void CopyFile(const base::FilePath& src_path,
const base::FilePath& dest_path);
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 1006f7da8b7..200720c287d 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
@@ -49,7 +49,6 @@
#include "extensions/common/extension_set.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/manifest_constants.h"
-#include "extensions/common/test_util.h"
#include "extensions/common/value_builder.h"
using testing::Return;
@@ -911,7 +910,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RepairPolicyExtension) {
// Corrupt the extension , still expect repair failure because this is a
// policy extension.
- service()->DisableExtension(extension_id, Extension::DISABLE_CORRUPTED);
+ service()->DisableExtension(extension_id, disable_reason::DISABLE_CORRUPTED);
args = ListBuilder().Append(extension_id).Build();
function = new api::DeveloperPrivateRepairExtensionFunction();
EXPECT_FALSE(RunFunction(function, *args));
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 06a888c9dde..52310814757 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc
+++ b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc
@@ -49,7 +49,7 @@ EntryPicker::EntryPicker(EntryPickerClient* client,
}
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_contents));
+ this, std::make_unique<ChromeSelectFilePolicy>(web_contents));
gfx::NativeWindow owning_window = web_contents ?
platform_util::GetTopLevel(web_contents->GetNativeView()) :
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 3fd732083c1..c2907900851 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
@@ -315,16 +315,16 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper(
int blacklist_text = -1;
switch (extension_prefs_->GetExtensionBlacklistState(extension.id())) {
case BLACKLISTED_MALWARE:
- blacklist_text = IDS_OPTIONS_BLACKLISTED_MALWARE;
+ blacklist_text = IDS_EXTENSIONS_BLACKLISTED_MALWARE;
break;
case BLACKLISTED_SECURITY_VULNERABILITY:
- blacklist_text = IDS_OPTIONS_BLACKLISTED_SECURITY_VULNERABILITY;
+ blacklist_text = IDS_EXTENSIONS_BLACKLISTED_SECURITY_VULNERABILITY;
break;
case BLACKLISTED_CWS_POLICY_VIOLATION:
- blacklist_text = IDS_OPTIONS_BLACKLISTED_CWS_POLICY_VIOLATION;
+ blacklist_text = IDS_EXTENSIONS_BLACKLISTED_CWS_POLICY_VIOLATION;
break;
case BLACKLISTED_POTENTIALLY_UNWANTED:
- blacklist_text = IDS_OPTIONS_BLACKLISTED_POTENTIALLY_UNWANTED;
+ blacklist_text = IDS_EXTENSIONS_BLACKLISTED_POTENTIALLY_UNWANTED;
break;
default:
break;
@@ -343,7 +343,7 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper(
if (is_policy_location) {
info->controlled_info->type = developer::CONTROLLER_TYPE_POLICY;
info->controlled_info->text =
- l10n_util::GetStringUTF8(IDS_OPTIONS_INSTALL_LOCATION_ENTERPRISE);
+ l10n_util::GetStringUTF8(IDS_EXTENSIONS_INSTALL_LOCATION_ENTERPRISE);
} else if (profile->IsChild()) {
info->controlled_info->type = developer::CONTROLLER_TYPE_CHILD_CUSTODIAN;
info->controlled_info->text = l10n_util::GetStringUTF8(
@@ -382,11 +382,12 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper(
// Disable reasons.
int disable_reasons = extension_prefs_->GetDisableReasons(extension.id());
info->disable_reasons.suspicious_install =
- (disable_reasons & Extension::DISABLE_NOT_VERIFIED) != 0;
+ (disable_reasons & disable_reason::DISABLE_NOT_VERIFIED) != 0;
info->disable_reasons.corrupt_install =
- (disable_reasons & Extension::DISABLE_CORRUPTED) != 0;
+ (disable_reasons & disable_reason::DISABLE_CORRUPTED) != 0;
info->disable_reasons.update_required =
- (disable_reasons & Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) != 0;
+ (disable_reasons & disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY) !=
+ 0;
// Error collection.
bool error_console_enabled =
@@ -449,11 +450,11 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper(
// Location text.
int location_text = -1;
if (info->location == developer::LOCATION_UNKNOWN)
- location_text = IDS_OPTIONS_INSTALL_LOCATION_UNKNOWN;
+ location_text = IDS_EXTENSIONS_INSTALL_LOCATION_UNKNOWN;
else if (extension.location() == Manifest::EXTERNAL_REGISTRY)
- location_text = IDS_OPTIONS_INSTALL_LOCATION_3RD_PARTY;
+ location_text = IDS_EXTENSIONS_INSTALL_LOCATION_3RD_PARTY;
else if (extension.is_shared_module())
- location_text = IDS_OPTIONS_INSTALL_LOCATION_SHARED_MODULE;
+ location_text = IDS_EXTENSIONS_INSTALL_LOCATION_SHARED_MODULE;
if (location_text != -1) {
info->location_text.reset(
new std::string(l10n_util::GetStringUTF8(location_text)));
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 e8989acc395..4807c309009 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
@@ -12,6 +12,7 @@
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
+#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
diff --git a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc
index 4ee780d7326..c3345f1e297 100644
--- a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc
@@ -13,9 +13,11 @@
#include "device/base/mock_device_client.h"
#include "device/hid/hid_device_info.h"
#include "device/hid/mock_hid_service.h"
+#include "device/hid/public/interfaces/hid.mojom.h"
#include "device/usb/mock_usb_device.h"
#include "device/usb/mock_usb_service.h"
#include "extensions/browser/api/device_permissions_manager.h"
+#include "extensions/browser/api/hid/hid_device_manager.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/common/extension.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -38,6 +40,11 @@ const uint64_t kTestDeviceIds[] = {1, 2, 3, 4};
const char* kTestDeviceIds[] = {"A", "B", "C", "D"};
#endif
+std::unique_ptr<KeyedService> CreateHidDeviceManager(
+ content::BrowserContext* context) {
+ return base::MakeUnique<HidDeviceManager>(context);
+}
+
} // namespace
class DevicePermissionsManagerTest : public testing::Test {
@@ -55,27 +62,30 @@ class DevicePermissionsManagerTest : public testing::Test {
" },"
" \"permissions\": [ \"hid\", \"usb\" ]"
"}"));
+
+ HidDeviceManager::GetFactoryInstance()->SetTestingFactory(
+ env_->profile(), &CreateHidDeviceManager);
device0_ =
new MockUsbDevice(0, 0, "Test Manufacturer", "Test Product", "ABCDE");
device1_ = new MockUsbDevice(0, 0, "Test Manufacturer", "Test Product", "");
device2_ =
new MockUsbDevice(0, 0, "Test Manufacturer", "Test Product", "12345");
device3_ = new MockUsbDevice(0, 0, "Test Manufacturer", "Test Product", "");
- device4_ =
- new HidDeviceInfo(kTestDeviceIds[0], 0, 0, "Test HID Device", "abcde",
- device::kHIDBusTypeUSB, std::vector<uint8_t>());
+ device4_ = new HidDeviceInfo(
+ kTestDeviceIds[0], 0, 0, "Test HID Device", "abcde",
+ device::mojom::HidBusType::kHIDBusTypeUSB, std::vector<uint8_t>());
device_client_.hid_service()->AddDevice(device4_);
- device5_ =
- new HidDeviceInfo(kTestDeviceIds[1], 0, 0, "Test HID Device", "",
- device::kHIDBusTypeUSB, std::vector<uint8_t>());
+ device5_ = new HidDeviceInfo(kTestDeviceIds[1], 0, 0, "Test HID Device", "",
+ device::mojom::HidBusType::kHIDBusTypeUSB,
+ std::vector<uint8_t>());
device_client_.hid_service()->AddDevice(device5_);
- device6_ =
- new HidDeviceInfo(kTestDeviceIds[2], 0, 0, "Test HID Device", "67890",
- device::kHIDBusTypeUSB, std::vector<uint8_t>());
+ device6_ = new HidDeviceInfo(
+ kTestDeviceIds[2], 0, 0, "Test HID Device", "67890",
+ device::mojom::HidBusType::kHIDBusTypeUSB, std::vector<uint8_t>());
device_client_.hid_service()->AddDevice(device6_);
- device7_ =
- new HidDeviceInfo(kTestDeviceIds[3], 0, 0, "Test HID Device", "",
- device::kHIDBusTypeUSB, std::vector<uint8_t>());
+ device7_ = new HidDeviceInfo(kTestDeviceIds[3], 0, 0, "Test HID Device", "",
+ device::mojom::HidBusType::kHIDBusTypeUSB,
+ std::vector<uint8_t>());
device_client_.hid_service()->AddDevice(device7_);
device_client_.hid_service()->FirstEnumerationComplete();
}
@@ -100,8 +110,8 @@ TEST_F(DevicePermissionsManagerTest, AllowAndClearDevices) {
DevicePermissionsManager::Get(env_->profile());
manager->AllowUsbDevice(extension_->id(), device0_);
manager->AllowUsbDevice(extension_->id(), device1_);
- manager->AllowHidDevice(extension_->id(), device4_);
- manager->AllowHidDevice(extension_->id(), device5_);
+ manager->AllowHidDevice(extension_->id(), *device4_->device());
+ manager->AllowHidDevice(extension_->id(), *device5_->device());
DevicePermissions* device_permissions =
manager->GetForExtension(extension_->id());
@@ -114,13 +124,15 @@ TEST_F(DevicePermissionsManagerTest, AllowAndClearDevices) {
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device2_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device3_).get());
scoped_refptr<DevicePermissionEntry> device4_entry =
- device_permissions->FindHidDeviceEntry(device4_);
+ device_permissions->FindHidDeviceEntry(*device4_->device());
ASSERT_TRUE(device4_entry.get());
scoped_refptr<DevicePermissionEntry> device5_entry =
- device_permissions->FindHidDeviceEntry(device5_);
+ device_permissions->FindHidDeviceEntry(*device5_->device());
ASSERT_TRUE(device5_entry.get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device6_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device7_).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device6_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device7_->device()).get());
EXPECT_EQ(4U, device_permissions->entries().size());
EXPECT_EQ(base::ASCIIToUTF16(
@@ -141,26 +153,34 @@ TEST_F(DevicePermissionsManagerTest, AllowAndClearDevices) {
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device1_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device2_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device3_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device5_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device6_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device7_).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device6_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device7_->device()).get());
EXPECT_EQ(0U, device_permissions->entries().size());
// After clearing device it should be possible to grant permission again.
manager->AllowUsbDevice(extension_->id(), device0_);
manager->AllowUsbDevice(extension_->id(), device1_);
- manager->AllowHidDevice(extension_->id(), device4_);
- manager->AllowHidDevice(extension_->id(), device5_);
+ manager->AllowHidDevice(extension_->id(), *device4_->device());
+ manager->AllowHidDevice(extension_->id(), *device5_->device());
EXPECT_TRUE(device_permissions->FindUsbDeviceEntry(device0_).get());
EXPECT_TRUE(device_permissions->FindUsbDeviceEntry(device1_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device2_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device3_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device5_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device6_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device7_).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device6_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device7_->device()).get());
}
TEST_F(DevicePermissionsManagerTest, DisconnectDevice) {
@@ -168,8 +188,8 @@ TEST_F(DevicePermissionsManagerTest, DisconnectDevice) {
DevicePermissionsManager::Get(env_->profile());
manager->AllowUsbDevice(extension_->id(), device0_);
manager->AllowUsbDevice(extension_->id(), device1_);
- manager->AllowHidDevice(extension_->id(), device4_);
- manager->AllowHidDevice(extension_->id(), device5_);
+ manager->AllowHidDevice(extension_->id(), *device4_->device());
+ manager->AllowHidDevice(extension_->id(), *device5_->device());
DevicePermissions* device_permissions =
manager->GetForExtension(extension_->id());
@@ -177,15 +197,23 @@ TEST_F(DevicePermissionsManagerTest, DisconnectDevice) {
EXPECT_TRUE(device_permissions->FindUsbDeviceEntry(device1_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device2_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device3_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device5_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device6_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device7_).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device6_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device7_->device()).get());
device_client_.usb_service()->RemoveDevice(device0_);
device_client_.usb_service()->RemoveDevice(device1_);
- device_client_.hid_service()->RemoveDevice(device4_->device_id());
- device_client_.hid_service()->RemoveDevice(device5_->device_id());
+
+ // Wait until HidDeviceManager::GetDevicesCallback is run. HidService
+ // won't send notifications to its observers before that.
+ base::RunLoop().RunUntilIdle();
+ device_client_.hid_service()->RemoveDevice(device4_->platform_device_id());
+ device_client_.hid_service()->RemoveDevice(device5_->platform_device_id());
// Device 0 will be accessible when it is reconnected because it can be
// recognized by its serial number.
@@ -197,11 +225,15 @@ TEST_F(DevicePermissionsManagerTest, DisconnectDevice) {
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device2_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device3_).get());
// Device 4 is like device 0, but HID.
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device4_).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
// Device 5 is like device 1, but HID.
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device5_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device6_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device7_).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device6_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device7_->device()).get());
}
TEST_F(DevicePermissionsManagerTest, RevokeAndRegrantAccess) {
@@ -209,8 +241,8 @@ TEST_F(DevicePermissionsManagerTest, RevokeAndRegrantAccess) {
DevicePermissionsManager::Get(env_->profile());
manager->AllowUsbDevice(extension_->id(), device0_);
manager->AllowUsbDevice(extension_->id(), device1_);
- manager->AllowHidDevice(extension_->id(), device4_);
- manager->AllowHidDevice(extension_->id(), device5_);
+ manager->AllowHidDevice(extension_->id(), *device4_->device());
+ manager->AllowHidDevice(extension_->id(), *device5_->device());
DevicePermissions* device_permissions =
manager->GetForExtension(extension_->id());
@@ -221,10 +253,10 @@ TEST_F(DevicePermissionsManagerTest, RevokeAndRegrantAccess) {
device_permissions->FindUsbDeviceEntry(device1_);
ASSERT_TRUE(device1_entry.get());
scoped_refptr<DevicePermissionEntry> device4_entry =
- device_permissions->FindHidDeviceEntry(device4_);
+ device_permissions->FindHidDeviceEntry(*device4_->device());
ASSERT_TRUE(device4_entry.get());
scoped_refptr<DevicePermissionEntry> device5_entry =
- device_permissions->FindHidDeviceEntry(device5_);
+ device_permissions->FindHidDeviceEntry(*device5_->device());
ASSERT_TRUE(device5_entry.get());
manager->RemoveEntry(extension_->id(), device0_entry);
@@ -244,27 +276,35 @@ TEST_F(DevicePermissionsManagerTest, RevokeAndRegrantAccess) {
EXPECT_TRUE(device_permissions->FindUsbDeviceEntry(device1_).get());
manager->RemoveEntry(extension_->id(), device4_entry);
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device5_).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
- manager->AllowHidDevice(extension_->id(), device4_);
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device5_).get());
+ manager->AllowHidDevice(extension_->id(), *device4_->device());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
manager->RemoveEntry(extension_->id(), device5_entry);
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device5_).get());
-
- manager->AllowHidDevice(extension_->id(), device5_);
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device4_).get());
- EXPECT_TRUE(device_permissions->FindHidDeviceEntry(device5_).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
+
+ manager->AllowHidDevice(extension_->id(), *device5_->device());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device4_->device()).get());
+ EXPECT_TRUE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
}
TEST_F(DevicePermissionsManagerTest, UpdateLastUsed) {
DevicePermissionsManager* manager =
DevicePermissionsManager::Get(env_->profile());
manager->AllowUsbDevice(extension_->id(), device0_);
- manager->AllowHidDevice(extension_->id(), device4_);
+ manager->AllowHidDevice(extension_->id(), *device4_->device());
DevicePermissions* device_permissions =
manager->GetForExtension(extension_->id());
@@ -272,7 +312,7 @@ TEST_F(DevicePermissionsManagerTest, UpdateLastUsed) {
device_permissions->FindUsbDeviceEntry(device0_);
EXPECT_TRUE(device0_entry->last_used().is_null());
scoped_refptr<DevicePermissionEntry> device4_entry =
- device_permissions->FindHidDeviceEntry(device4_);
+ device_permissions->FindHidDeviceEntry(*device4_->device());
EXPECT_TRUE(device4_entry->last_used().is_null());
manager->UpdateLastUsed(extension_->id(), device0_entry);
@@ -314,11 +354,14 @@ TEST_F(DevicePermissionsManagerTest, LoadPrefs) {
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device2_).get());
EXPECT_FALSE(device_permissions->FindUsbDeviceEntry(device3_).get());
scoped_refptr<DevicePermissionEntry> device4_entry =
- device_permissions->FindHidDeviceEntry(device4_);
+ device_permissions->FindHidDeviceEntry(*device4_->device());
ASSERT_TRUE(device4_entry.get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device5_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device6_).get());
- EXPECT_FALSE(device_permissions->FindHidDeviceEntry(device7_).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device5_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device6_->device()).get());
+ EXPECT_FALSE(
+ device_permissions->FindHidDeviceEntry(*device7_->device()).get());
EXPECT_EQ(base::ASCIIToUTF16(
"Test Product from Test Manufacturer (serial number ABCDE)"),
diff --git a/chromium/chrome/browser/extensions/api/dial/dial_api.cc b/chromium/chrome/browser/extensions/api/dial/dial_api.cc
index 8987ca358d4..8cb70bf0d54 100644
--- a/chromium/chrome/browser/extensions/api/dial/dial_api.cc
+++ b/chromium/chrome/browser/extensions/api/dial/dial_api.cc
@@ -34,18 +34,19 @@ DialAPI::DialAPI(Profile* profile)
: RefcountedKeyedService(
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)),
profile_(profile),
- dial_registry_(nullptr) {
+ dial_registry_(nullptr),
+ num_on_device_list_listeners_(0) {
EventRouter::Get(profile)->RegisterObserver(
this, api::dial::OnDeviceList::kEventName);
}
DialAPI::~DialAPI() {
- // TODO(zhaobin): Call dial_registry_->UnregisterObserver() instead. In
- // current implementation, UnregistryObserver() does not StopDiscovery() and
- // causes crash in ~DialRegistry(). May keep a listener count and
- // Register/UnregisterObserver as needed.
- if (dial_registry_)
- dial_registry_->StopPeriodicDiscovery();
+ if (!dial_registry_)
+ return;
+
+ // Remove pending listeners from dial registry.
+ for (int i = 0; i < num_on_device_list_listeners_; i++)
+ dial_registry_->OnListenerRemoved();
}
DialRegistry* DialAPI::dial_registry() {
@@ -77,12 +78,14 @@ void DialAPI::OnListenerRemoved(const EventListenerInfo& details) {
void DialAPI::NotifyListenerAddedOnIOThread() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
VLOG(2) << "DIAL device event listener added.";
+ ++num_on_device_list_listeners_;
dial_registry()->OnListenerAdded();
}
void DialAPI::NotifyListenerRemovedOnIOThread() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
VLOG(2) << "DIAL device event listener removed";
+ --num_on_device_list_listeners_;
dial_registry()->OnListenerRemoved();
}
@@ -161,7 +164,17 @@ void DialAPI::SendErrorOnUIThread(const DialRegistry::DialErrorCode code) {
EventRouter::Get(profile_)->BroadcastEvent(std::move(event));
}
-void DialAPI::ShutdownOnUIThread() {}
+void DialAPI::ShutdownOnUIThread() {
+ EventRouter::Get(profile_)->UnregisterObserver(this);
+
+ if (!dial_registry_)
+ return;
+
+ BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
+ base::BindOnce(&DialRegistry::UnregisterObserver,
+ base::Unretained(dial_registry_),
+ base::RetainedRef(this)));
+}
void DialAPI::SetDeviceForTest(
const media_router::DialDeviceData& device_data,
diff --git a/chromium/chrome/browser/extensions/api/dial/dial_api.h b/chromium/chrome/browser/extensions/api/dial/dial_api.h
index e9fb6ccd1a0..ee842663aba 100644
--- a/chromium/chrome/browser/extensions/api/dial/dial_api.h
+++ b/chromium/chrome/browser/extensions/api/dial/dial_api.h
@@ -96,6 +96,9 @@ class DialAPI : public RefcountedKeyedService,
// |dial_registry_|.
media_router::DialRegistry* dial_registry_;
+ // Number of dial.onDeviceList event listeners.
+ int num_on_device_list_listeners_;
+
// Device data for testing.
std::unique_ptr<media_router::DialDeviceData> test_device_data_;
std::unique_ptr<media_router::DialDeviceDescriptionData>
diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
index 7098da6777a..2502d572a81 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
@@ -1017,7 +1017,7 @@ bool DownloadsDownloadFunction::RunAsync() {
destination: OTHER
}
policy {
- cookies_allowed: true
+ cookies_allowed: YES
cookies_store: "user"
setting:
"This feature cannot be disabled in settings, but disabling all "
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 00258b02fbf..282febf7ac6 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -48,6 +48,7 @@
#include "content/public/common/content_features.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/test_download_request_handler.h"
+#include "content/public/test/test_utils.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/notification_types.h"
#include "net/base/data_url.h"
@@ -191,7 +192,7 @@ class DownloadsEventsListener : public content::NotificationObserver {
waiting_for_.get() &&
new_event->Satisfies(*waiting_for_)) {
waiting_ = false;
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
break;
}
@@ -1002,8 +1003,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
// be able to query the file icon.
download_item->Cancel(true);
ASSERT_FALSE(download_item->GetTargetFilePath().empty());
- // Let cleanup complete on the FILE thread.
- content::RunAllPendingInMessageLoop(BrowserThread::FILE);
+ // Let cleanup complete on blocking threads.
+ content::RunAllBlockingPoolTasksUntilIdle();
// Check the path passed to the icon extractor post-cancellation.
EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
download_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc
index 1bcc400de73..6da116e2e22 100644
--- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc
@@ -51,10 +51,10 @@
#include "ui/gfx/range/range.h"
#if defined(OS_CHROMEOS)
-#include "ash/system/devicetype_utils.h"
#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager.h"
#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_tpm_key_manager_factory.h"
#include "components/user_manager/user_manager.h"
+#include "ui/chromeos/devicetype_utils.h"
#endif
using proximity_auth::ScreenlockState;
@@ -138,7 +138,7 @@ ExtensionFunction::ResponseAction EasyUnlockPrivateGetStringsFunction::Run() {
std::unique_ptr<base::DictionaryValue> strings(new base::DictionaryValue);
#if defined(OS_CHROMEOS)
- const base::string16 device_type = ash::GetChromeOSDeviceName();
+ const base::string16 device_type = ui::GetChromeOSDeviceName();
#else
// TODO(isherman): Set an appropriate device name for non-ChromeOS devices.
const base::string16 device_type = base::ASCIIToUTF16("Chromeschnozzle");
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
index 295f79bf3be..4bdd019d398 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
@@ -32,7 +32,7 @@
#include "components/prefs/pref_service.h"
#include "components/signin/core/account_id/account_id.h"
#include "components/signin/core/browser/signin_manager.h"
-#include "extensions/common/test_util.h"
+#include "extensions/common/extension_builder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
@@ -126,7 +126,7 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest {
protected:
EPKChallengeKeyTestBase()
: settings_helper_(false),
- extension_(test_util::CreateEmptyExtension()),
+ extension_(ExtensionBuilder("Test").Build()),
profile_manager_(TestingBrowserProcess::GetGlobal()),
fake_user_manager_(new chromeos::FakeChromeUserManager),
user_manager_enabler_(fake_user_manager_) {
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
index a22d509f38a..fb8b1b6bd60 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
@@ -36,7 +36,6 @@
#include "components/signin/core/account_id/account_id.h"
#include "components/signin/core/browser/signin_manager.h"
#include "extensions/common/extension_builder.h"
-#include "extensions/common/test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
@@ -230,10 +229,10 @@ class EPKPChallengeKeyTestBase : public BrowserWithTestWindowTest {
scoped_refptr<Extension> CreateExtension() {
switch (profile_type_) {
case ProfileType::USER_PROFILE:
- return test_util::CreateEmptyExtension();
+ return ExtensionBuilder("Test").Build();
case ProfileType::SIGNIN_PROFILE:
- return test_util::BuildApp(ExtensionBuilder())
+ return ExtensionBuilder("Test", ExtensionBuilder::Type::PLATFORM_APP)
.SetLocation(Manifest::Location::EXTERNAL_POLICY)
.Build();
}
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 da79d2e5d26..30400437b88 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
@@ -8,6 +8,7 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
+#include "base/run_loop.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
diff --git a/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc b/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc
index 15b8f360e84..6faba7c31d2 100644
--- a/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc
+++ b/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc
@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "base/run_loop.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
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
new file mode 100644
index 00000000000..28a53f9baaa
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc
@@ -0,0 +1,186 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h"
+
+#include <memory>
+#include <string>
+
+#include "base/values.h"
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/feedback/feedback_uploader_chrome.h"
+#include "chrome/browser/feedback/feedback_uploader_factory_chrome.h"
+#include "chrome/browser/feedback/system_logs/chrome_system_logs_fetcher.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/signin/signin_manager_factory.h"
+#include "chrome/browser/ui/simple_message_box.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/feedback/system_logs/system_logs_fetcher.h"
+#include "components/signin/core/browser/signin_manager.h"
+#include "components/strings/grit/components_strings.h"
+#include "content/public/browser/browser_context.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/base/webui/web_ui_util.h"
+
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/chromeos/arc/arc_util.h"
+#include "chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.h"
+#include "chrome/browser/chromeos/system_logs/single_log_file_log_source.h"
+#include "chrome/browser/profiles/profile.h"
+#include "components/feedback/system_logs/system_logs_source.h"
+#endif // defined(OS_CHROMEOS)
+
+namespace extensions {
+
+ChromeFeedbackPrivateDelegate::ChromeFeedbackPrivateDelegate() = default;
+ChromeFeedbackPrivateDelegate::~ChromeFeedbackPrivateDelegate() = default;
+
+std::unique_ptr<base::DictionaryValue>
+ChromeFeedbackPrivateDelegate::GetStrings(
+ content::BrowserContext* browser_context,
+ bool from_crash) const {
+ std::unique_ptr<base::DictionaryValue> dict =
+ 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("additionalInfo", IDS_FEEDBACK_ADDITIONAL_INFO_LABEL);
+ SET_STRING("minimize-btn-label", IDS_FEEDBACK_MINIMIZE_BUTTON_LABEL);
+ SET_STRING("close-btn-label", IDS_FEEDBACK_CLOSE_BUTTON_LABEL);
+ SET_STRING("page-url", IDS_FEEDBACK_REPORT_URL_LABEL);
+ SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL);
+ SET_STRING("user-email", IDS_FEEDBACK_USER_EMAIL_LABEL);
+ SET_STRING("anonymous-user", IDS_FEEDBACK_ANONYMOUS_EMAIL_OPTION);
+#if defined(OS_CHROMEOS)
+ if (arc::IsArcPlayStoreEnabledForProfile(
+ Profile::FromBrowserContext(browser_context))) {
+ SET_STRING("sys-info",
+ IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX_ARC);
+ } else {
+ SET_STRING("sys-info",
+ IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX);
+ }
+#else
+ SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_CHKBOX);
+#endif
+ SET_STRING("attach-file-label", IDS_FEEDBACK_ATTACH_FILE_LABEL);
+ SET_STRING("attach-file-note", IDS_FEEDBACK_ATTACH_FILE_NOTE);
+ SET_STRING("attach-file-to-big", IDS_FEEDBACK_ATTACH_FILE_TO_BIG);
+ SET_STRING("reading-file", IDS_FEEDBACK_READING_FILE);
+ SET_STRING("send-report", IDS_FEEDBACK_SEND_REPORT);
+ SET_STRING("cancel", IDS_CANCEL);
+ SET_STRING("no-description", IDS_FEEDBACK_NO_DESCRIPTION);
+ SET_STRING("privacy-note", IDS_FEEDBACK_PRIVACY_NOTE);
+ SET_STRING("performance-trace",
+ IDS_FEEDBACK_INCLUDE_PERFORMANCE_TRACE_CHECKBOX);
+ // Add the localized strings needed for the "system information" page.
+ SET_STRING("sysinfoPageTitle", IDS_FEEDBACK_SYSINFO_PAGE_TITLE);
+ SET_STRING("sysinfoPageDescription", IDS_ABOUT_SYS_DESC);
+ SET_STRING("sysinfoPageTableTitle", IDS_ABOUT_SYS_TABLE_TITLE);
+ SET_STRING("sysinfoPageExpandAllBtn", IDS_ABOUT_SYS_EXPAND_ALL);
+ SET_STRING("sysinfoPageCollapseAllBtn", IDS_ABOUT_SYS_COLLAPSE_ALL);
+ SET_STRING("sysinfoPageExpandBtn", IDS_ABOUT_SYS_EXPAND);
+ SET_STRING("sysinfoPageCollapseBtn", IDS_ABOUT_SYS_COLLAPSE);
+ SET_STRING("sysinfoPageStatusLoading", IDS_FEEDBACK_SYSINFO_PAGE_LOADING);
+ // And the localized strings needed for the SRT Download Prompt.
+ SET_STRING("srtPromptBody", IDS_FEEDBACK_SRT_PROMPT_BODY);
+ SET_STRING("srtPromptAcceptButton", IDS_FEEDBACK_SRT_PROMPT_ACCEPT_BUTTON);
+ SET_STRING("srtPromptDeclineButton", IDS_FEEDBACK_SRT_PROMPT_DECLINE_BUTTON);
+#undef SET_STRING
+
+ const std::string& app_locale = g_browser_process->GetApplicationLocale();
+ webui::SetLoadTimeDataDefaults(app_locale, dict.get());
+
+ return dict;
+}
+
+system_logs::SystemLogsFetcher*
+ChromeFeedbackPrivateDelegate::CreateSystemLogsFetcher(
+ content::BrowserContext* context) const {
+ return system_logs::BuildChromeSystemLogsFetcher();
+}
+
+#if defined(OS_CHROMEOS)
+std::unique_ptr<system_logs::SystemLogsSource>
+ChromeFeedbackPrivateDelegate::CreateSingleLogSource(
+ api::feedback_private::LogSource source_type) const {
+ using SupportedLogFileSource =
+ system_logs::SingleLogFileLogSource::SupportedSource;
+ using SupportedDebugDaemonSource =
+ system_logs::SingleDebugDaemonLogSource::SupportedSource;
+
+ switch (source_type) {
+ // These map to SupportedLogFileSources.
+ case api::feedback_private::LOG_SOURCE_MESSAGES:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kMessages);
+ case api::feedback_private::LOG_SOURCE_UILATEST:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kUiLatest);
+ case api::feedback_private::LOG_SOURCE_ATRUSLOG:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kAtrusLog);
+ case api::feedback_private::LOG_SOURCE_NETLOG:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kNetLog);
+ case api::feedback_private::LOG_SOURCE_EVENTLOG:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kEventLog);
+ case api::feedback_private::LOG_SOURCE_UPDATEENGINELOG:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kUpdateEngineLog);
+ case api::feedback_private::LOG_SOURCE_POWERDLATEST:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kPowerdLatest);
+ case api::feedback_private::LOG_SOURCE_POWERDPREVIOUS:
+ return std::make_unique<system_logs::SingleLogFileLogSource>(
+ SupportedLogFileSource::kPowerdPrevious);
+
+ // These map to SupportedDebugDaemonSources.
+ case api::feedback_private::LOG_SOURCE_DRMMODETEST:
+ return std::make_unique<system_logs::SingleDebugDaemonLogSource>(
+ SupportedDebugDaemonSource::kModetest);
+ case api::feedback_private::LOG_SOURCE_LSUSB:
+ return std::make_unique<system_logs::SingleDebugDaemonLogSource>(
+ SupportedDebugDaemonSource::kLsusb);
+ case api::feedback_private::LOG_SOURCE_LSPCI:
+ return std::make_unique<system_logs::SingleDebugDaemonLogSource>(
+ SupportedDebugDaemonSource::kLspci);
+ case api::feedback_private::LOG_SOURCE_IFCONFIG:
+ return std::make_unique<system_logs::SingleDebugDaemonLogSource>(
+ SupportedDebugDaemonSource::kIfconfig);
+
+ case api::feedback_private::LOG_SOURCE_NONE:
+ default:
+ NOTREACHED() << "Unknown log source type.";
+ return nullptr;
+ }
+}
+#endif // defined(OS_CHROMEOS)
+
+std::string ChromeFeedbackPrivateDelegate::GetSignedInUserEmail(
+ content::BrowserContext* context) const {
+ SigninManagerBase* signin_manager =
+ SigninManagerFactory::GetForProfile(Profile::FromBrowserContext(context));
+ return signin_manager ? signin_manager->GetAuthenticatedAccountInfo().email
+ : std::string();
+}
+
+void ChromeFeedbackPrivateDelegate::NotifyFeedbackDelayed() const {
+ // Show a message box to indicate that sending the feedback has been delayed
+ // because the user is offline.
+ chrome::ShowWarningMessageBox(
+ nullptr, l10n_util::GetStringUTF16(IDS_FEEDBACK_OFFLINE_DIALOG_TITLE),
+ l10n_util::GetStringUTF16(IDS_FEEDBACK_OFFLINE_DIALOG_TEXT));
+}
+
+feedback::FeedbackUploader*
+ChromeFeedbackPrivateDelegate::GetFeedbackUploaderForContext(
+ content::BrowserContext* context) const {
+ return feedback::FeedbackUploaderFactoryChrome::GetForBrowserContext(context);
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h
new file mode 100644
index 00000000000..88a9788a3ad
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h
@@ -0,0 +1,41 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_CHROME_FEEDBACK_PRIVATE_DELEGATE_H_
+#define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_CHROME_FEEDBACK_PRIVATE_DELEGATE_H_
+
+#include "extensions/browser/api/feedback_private/feedback_private_delegate.h"
+
+#include "base/macros.h"
+
+namespace extensions {
+
+class ChromeFeedbackPrivateDelegate : public FeedbackPrivateDelegate {
+ public:
+ ChromeFeedbackPrivateDelegate();
+ ~ChromeFeedbackPrivateDelegate() override;
+
+ // FeedbackPrivateDelegate:
+ std::unique_ptr<base::DictionaryValue> GetStrings(
+ content::BrowserContext* browser_context,
+ bool from_crash) const override;
+ system_logs::SystemLogsFetcher* CreateSystemLogsFetcher(
+ content::BrowserContext* context) const override;
+#if defined(OS_CHROMEOS)
+ std::unique_ptr<system_logs::SystemLogsSource> CreateSingleLogSource(
+ api::feedback_private::LogSource source_type) const override;
+#endif // defined(OS_CHROMEOS)
+ std::string GetSignedInUserEmail(
+ content::BrowserContext* context) const override;
+ void NotifyFeedbackDelayed() const override;
+ feedback::FeedbackUploader* GetFeedbackUploaderForContext(
+ content::BrowserContext* context) const override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ChromeFeedbackPrivateDelegate);
+};
+
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_CHROME_FEEDBACK_PRIVATE_DELEGATE_H_
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc
index 06edf418bbf..b01ac06fa6e 100644
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc
@@ -4,30 +4,31 @@
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
-#include "chrome/common/extensions/api/feedback_private.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
+#include "extensions/browser/api/feedback_private/feedback_private_api.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_system.h"
+#include "extensions/common/api/feedback_private.h"
using extensions::api::feedback_private::FeedbackFlow;
namespace {
void StopMessageLoopCallback() {
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
} // namespace
@@ -92,7 +93,14 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, ShowFeedback) {
VerifyFeedbackAppLaunch();
}
-IN_PROC_BROWSER_TEST_F(FeedbackTest, ShowLoginFeedback) {
+// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
+// See crbug.com/757243.
+#if defined(ADDRESS_SANITIZER)
+#define MAYBE_ShowLoginFeedback DISABLED_ShowLoginFeedback
+#else
+#define MAYBE_ShowLoginFeedback ShowLoginFeedback
+#endif
+IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ShowLoginFeedback) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
@@ -116,7 +124,14 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, ShowLoginFeedback) {
// Tests that there's an option in the email drop down box with a value
// 'anonymous_user'.
-IN_PROC_BROWSER_TEST_F(FeedbackTest, AnonymousUser) {
+// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
+// See crbug.com/757243.
+#if defined(ADDRESS_SANITIZER)
+#define MAYBE_AnonymousUser DISABLED_AnonymousUser
+#else
+#define MAYBE_AnonymousUser AnonymousUser
+#endif
+IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_AnonymousUser) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc
deleted file mode 100644
index 1ce23f227bd..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc
+++ /dev/null
@@ -1,441 +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 "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
-
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/lazy_instance.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/statistics_recorder.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/extensions/api/feedback_private/feedback_service.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
-#include "chrome/browser/ui/simple_message_box.h"
-#include "chrome/common/extensions/api/feedback_private.h"
-#include "chrome/common/extensions/extension_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/feedback/tracing_manager.h"
-#include "components/signin/core/browser/signin_manager.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/common/browser_side_navigation_policy.h"
-#include "extensions/browser/event_router.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/webui/web_ui_util.h"
-#include "url/url_util.h"
-
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/chromeos/arc/arc_util.h"
-#include "chrome/browser/extensions/api/feedback_private/log_source_access_manager.h"
-#endif // defined(OS_CHROMEOS)
-
-#if defined(OS_WIN)
-#include "base/feature_list.h"
-#include "chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_win.h"
-#endif
-
-using extensions::api::feedback_private::SystemInformation;
-using feedback::FeedbackData;
-
-namespace {
-
-// Getting the filename of a blob prepends a "C:\fakepath" to the filename.
-// This is undesirable, strip it if it exists.
-std::string StripFakepath(const std::string& path) {
- const char kFakePathStr[] = "C:\\fakepath\\";
- if (base::StartsWith(path, kFakePathStr,
- base::CompareCase::INSENSITIVE_ASCII))
- return path.substr(arraysize(kFakePathStr) - 1);
- return path;
-}
-
-#if defined(OS_WIN)
-// Allows enabling/disabling SRT Prompt as a Variations feature.
-constexpr base::Feature kSrtPromptOnFeedbackForm {
- "SrtPromptOnFeedbackForm", base::FEATURE_DISABLED_BY_DEFAULT
-};
-#endif
-
-} // namespace
-
-namespace extensions {
-
-namespace feedback_private = api::feedback_private;
-
-using feedback_private::FeedbackInfo;
-using feedback_private::FeedbackFlow;
-using feedback_private::LogSource;
-using feedback_private::SystemInformation;
-
-using SystemInformationList =
- std::vector<api::feedback_private::SystemInformation>;
-
-static base::LazyInstance<BrowserContextKeyedAPIFactory<FeedbackPrivateAPI>>::
- DestructorAtExit g_factory = LAZY_INSTANCE_INITIALIZER;
-
-// static
-BrowserContextKeyedAPIFactory<FeedbackPrivateAPI>*
-FeedbackPrivateAPI::GetFactoryInstance() {
- return g_factory.Pointer();
-}
-
-FeedbackPrivateAPI::FeedbackPrivateAPI(content::BrowserContext* context)
- : browser_context_(context),
-#if !defined(OS_CHROMEOS)
- service_(new FeedbackService()) {
-#else
- service_(new FeedbackService()),
- log_source_access_manager_(new LogSourceAccessManager(context)){
-#endif // defined(OS_CHROMEOS)
-}
-
-FeedbackPrivateAPI::~FeedbackPrivateAPI() {}
-
-FeedbackService* FeedbackPrivateAPI::GetService() const {
- return service_.get();
-}
-
-#if defined(OS_CHROMEOS)
-LogSourceAccessManager* FeedbackPrivateAPI::GetLogSourceAccessManager() const {
- return log_source_access_manager_.get();
-}
-#endif
-
-void FeedbackPrivateAPI::RequestFeedback(
- const std::string& description_template,
- const std::string& category_tag,
- const std::string& extra_diagnostics,
- const GURL& page_url) {
-#if defined(OS_WIN)
- // Show prompt for Software Removal Tool if the Reporter component has found
- // unwanted software, and the user has never run the cleaner before.
- if (base::FeatureList::IsEnabled(kSrtPromptOnFeedbackForm) &&
- safe_browsing::ReporterFoundUws() &&
- !safe_browsing::UserHasRunCleaner()) {
- RequestFeedbackForFlow(description_template, category_tag,
- extra_diagnostics, page_url,
- FeedbackFlow::FEEDBACK_FLOW_SHOWSRTPROMPT);
- return;
- }
-#endif
- RequestFeedbackForFlow(description_template, category_tag, extra_diagnostics,
- page_url, FeedbackFlow::FEEDBACK_FLOW_REGULAR);
-}
-
-void FeedbackPrivateAPI::RequestFeedbackForFlow(
- const std::string& description_template,
- const std::string& category_tag,
- const std::string& extra_diagnostics,
- const GURL& page_url,
- api::feedback_private::FeedbackFlow flow) {
- if (browser_context_ && EventRouter::Get(browser_context_)) {
- FeedbackInfo info;
- info.description = description_template;
- info.category_tag = base::MakeUnique<std::string>(category_tag);
- info.page_url = base::MakeUnique<std::string>(page_url.spec());
- info.system_information = base::MakeUnique<SystemInformationList>();
-
- // Any extra diagnostics information should be added to the sys info.
- if (!extra_diagnostics.empty()) {
- SystemInformation extra_info;
- extra_info.key = "EXTRA_DIAGNOSTICS";
- extra_info.value = extra_diagnostics;
- info.system_information->emplace_back(std::move(extra_info));
- }
-
- // The manager is only available if tracing is enabled.
- if (TracingManager* manager = TracingManager::Get()) {
- info.trace_id = base::MakeUnique<int>(manager->RequestTrace());
- }
- info.flow = flow;
-#if defined(OS_MACOSX)
- const bool use_system_window_frame = true;
-#else
- const bool use_system_window_frame = false;
-#endif
- info.use_system_window_frame =
- base::MakeUnique<bool>(use_system_window_frame);
-
- std::unique_ptr<base::ListValue> args =
- feedback_private::OnFeedbackRequested::Create(info);
-
- auto event = base::MakeUnique<Event>(
- events::FEEDBACK_PRIVATE_ON_FEEDBACK_REQUESTED,
- feedback_private::OnFeedbackRequested::kEventName, std::move(args),
- browser_context_);
-
- if (content::IsBrowserSideNavigationEnabled()) {
- // LoginFeedbackTest.Basic times out when this flag is enabled if we are
- // using DispatchEventWithLazyListener(). It is a temporary solution to
- // fix the test failure. Please track crbug.com/765289 for further
- // investigation.
- EventRouter::Get(browser_context_)
- ->DispatchEventToExtension(extension_misc::kFeedbackExtensionId,
- std::move(event));
- } else {
- // TODO(weidongg/754329): Using DispatchEventWithLazyListener() is a
- // temporary fix to the bug. Investigate a better solution that applies to
- // all scenarios.
- EventRouter::Get(browser_context_)
- ->DispatchEventWithLazyListener(extension_misc::kFeedbackExtensionId,
- std::move(event));
- }
- }
-}
-
-// static
-base::Closure* FeedbackPrivateGetStringsFunction::test_callback_ = NULL;
-
-ExtensionFunction::ResponseAction FeedbackPrivateGetStringsFunction::Run() {
- auto params = feedback_private::GetStrings::Params::Create(*args_);
- EXTENSION_FUNCTION_VALIDATE(params.get());
-
- std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
-
-#define SET_STRING(id, idr) \
- dict->SetString(id, l10n_util::GetStringUTF16(idr))
- SET_STRING("page-title",
- params->flow == FeedbackFlow::FEEDBACK_FLOW_SADTABCRASH
- ? IDS_FEEDBACK_REPORT_PAGE_TITLE_SAD_TAB_FLOW
- : IDS_FEEDBACK_REPORT_PAGE_TITLE);
- SET_STRING("additionalInfo", IDS_FEEDBACK_ADDITIONAL_INFO_LABEL);
- SET_STRING("minimize-btn-label", IDS_FEEDBACK_MINIMIZE_BUTTON_LABEL);
- SET_STRING("close-btn-label", IDS_FEEDBACK_CLOSE_BUTTON_LABEL);
- SET_STRING("page-url", IDS_FEEDBACK_REPORT_URL_LABEL);
- SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL);
- SET_STRING("user-email", IDS_FEEDBACK_USER_EMAIL_LABEL);
- SET_STRING("anonymous-user", IDS_FEEDBACK_ANONYMOUS_EMAIL_OPTION);
-#if defined(OS_CHROMEOS)
- if (arc::IsArcPlayStoreEnabledForProfile(
- Profile::FromBrowserContext(browser_context()))) {
- SET_STRING("sys-info",
- IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX_ARC);
- } else {
- SET_STRING("sys-info",
- IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX);
- }
-#else
- SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_CHKBOX);
-#endif
- SET_STRING("attach-file-label", IDS_FEEDBACK_ATTACH_FILE_LABEL);
- SET_STRING("attach-file-note", IDS_FEEDBACK_ATTACH_FILE_NOTE);
- SET_STRING("attach-file-to-big", IDS_FEEDBACK_ATTACH_FILE_TO_BIG);
- SET_STRING("reading-file", IDS_FEEDBACK_READING_FILE);
- SET_STRING("send-report", IDS_FEEDBACK_SEND_REPORT);
- SET_STRING("cancel", IDS_CANCEL);
- SET_STRING("no-description", IDS_FEEDBACK_NO_DESCRIPTION);
- SET_STRING("privacy-note", IDS_FEEDBACK_PRIVACY_NOTE);
- SET_STRING("performance-trace",
- IDS_FEEDBACK_INCLUDE_PERFORMANCE_TRACE_CHECKBOX);
- // Add the localized strings needed for the "system information" page.
- SET_STRING("sysinfoPageTitle", IDS_FEEDBACK_SYSINFO_PAGE_TITLE);
- SET_STRING("sysinfoPageDescription", IDS_ABOUT_SYS_DESC);
- SET_STRING("sysinfoPageTableTitle", IDS_ABOUT_SYS_TABLE_TITLE);
- SET_STRING("sysinfoPageExpandAllBtn", IDS_ABOUT_SYS_EXPAND_ALL);
- SET_STRING("sysinfoPageCollapseAllBtn", IDS_ABOUT_SYS_COLLAPSE_ALL);
- SET_STRING("sysinfoPageExpandBtn", IDS_ABOUT_SYS_EXPAND);
- SET_STRING("sysinfoPageCollapseBtn", IDS_ABOUT_SYS_COLLAPSE);
- SET_STRING("sysinfoPageStatusLoading", IDS_FEEDBACK_SYSINFO_PAGE_LOADING);
- // And the localized strings needed for the SRT Download Prompt.
- SET_STRING("srtPromptBody", IDS_FEEDBACK_SRT_PROMPT_BODY);
- SET_STRING("srtPromptAcceptButton", IDS_FEEDBACK_SRT_PROMPT_ACCEPT_BUTTON);
- SET_STRING("srtPromptDeclineButton",
- IDS_FEEDBACK_SRT_PROMPT_DECLINE_BUTTON);
-#undef SET_STRING
-
- const std::string& app_locale = g_browser_process->GetApplicationLocale();
- webui::SetLoadTimeDataDefaults(app_locale, dict.get());
-
-
- if (test_callback_ && !test_callback_->is_null())
- test_callback_->Run();
-
- return RespondNow(OneArgument(std::move(dict)));
-}
-
-ExtensionFunction::ResponseAction FeedbackPrivateGetUserEmailFunction::Run() {
- SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(
- Profile::FromBrowserContext(browser_context()));
- return RespondNow(OneArgument(base::MakeUnique<base::Value>(
- signin_manager ? signin_manager->GetAuthenticatedAccountInfo().email
- : std::string())));
-}
-
-ExtensionFunction::ResponseAction
-FeedbackPrivateGetSystemInformationFunction::Run() {
- FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance()
- ->Get(browser_context())
- ->GetService();
- DCHECK(service);
- service->GetSystemInformation(
- base::Bind(
- &FeedbackPrivateGetSystemInformationFunction::OnCompleted, this));
- return RespondLater();
-}
-
-void FeedbackPrivateGetSystemInformationFunction::OnCompleted(
- std::unique_ptr<system_logs::SystemLogsResponse> sys_info) {
- SystemInformationList sys_info_list;
- if (sys_info) {
- sys_info_list.reserve(sys_info->size());
- for (auto& itr : *sys_info) {
- SystemInformation sys_info_entry;
- sys_info_entry.key = std::move(itr.first);
- sys_info_entry.value = std::move(itr.second);
- sys_info_list.emplace_back(std::move(sys_info_entry));
- }
- }
-
- Respond(ArgumentList(
- feedback_private::GetSystemInformation::Results::Create(sys_info_list)));
-}
-
-ExtensionFunction::ResponseAction FeedbackPrivateReadLogSourceFunction::Run() {
-#if defined(OS_CHROMEOS)
- using Params = feedback_private::ReadLogSource::Params;
- std::unique_ptr<Params> api_params = Params::Create(*args_);
-
- LogSourceAccessManager* log_source_manager =
- FeedbackPrivateAPI::GetFactoryInstance()
- ->Get(browser_context())
- ->GetLogSourceAccessManager();
-
- if (!log_source_manager->FetchFromSource(
- api_params->params, extension_id(),
- base::Bind(&FeedbackPrivateReadLogSourceFunction::OnCompleted,
- this))) {
- return RespondNow(Error("Unable to initiate fetch from log source."));
- }
-
- return RespondLater();
-#else
- NOTREACHED() << "API function is not supported on this platform.";
- return RespondNow(Error("API function is not supported on this platform."));
-#endif // defined(OS_CHROMEOS)
-}
-
-#if defined(OS_CHROMEOS)
-void FeedbackPrivateReadLogSourceFunction::OnCompleted(
- const feedback_private::ReadLogSourceResult& result) {
- Respond(
- ArgumentList(feedback_private::ReadLogSource::Results::Create(result)));
-}
-#endif // defined(OS_CHROMEOS)
-
-bool FeedbackPrivateSendFeedbackFunction::RunAsync() {
- std::unique_ptr<feedback_private::SendFeedback::Params> params(
- feedback_private::SendFeedback::Params::Create(*args_));
- EXTENSION_FUNCTION_VALIDATE(params);
-
- const FeedbackInfo &feedback_info = params->feedback;
-
- // Populate feedback data.
- scoped_refptr<FeedbackData> feedback_data(new FeedbackData());
- feedback_data->set_context(GetProfile());
- feedback_data->set_description(feedback_info.description);
-
- if (feedback_info.product_id)
- feedback_data->set_product_id(*feedback_info.product_id);
- if (feedback_info.category_tag)
- feedback_data->set_category_tag(*feedback_info.category_tag);
- if (feedback_info.page_url)
- feedback_data->set_page_url(*feedback_info.page_url);
- if (feedback_info.email)
- feedback_data->set_user_email(*feedback_info.email);
- if (feedback_info.trace_id)
- feedback_data->set_trace_id(*feedback_info.trace_id);
-
- if (feedback_info.attached_file_blob_uuid &&
- !feedback_info.attached_file_blob_uuid->empty()) {
- feedback_data->set_attached_filename(
- StripFakepath((*feedback_info.attached_file).name));
- feedback_data->set_attached_file_uuid(
- *feedback_info.attached_file_blob_uuid);
- }
-
- if (feedback_info.screenshot_blob_uuid &&
- !feedback_info.screenshot_blob_uuid->empty()) {
- feedback_data->set_screenshot_uuid(*feedback_info.screenshot_blob_uuid);
- }
-
- auto sys_logs = base::MakeUnique<FeedbackData::SystemLogsMap>();
- const SystemInformationList* sys_info =
- feedback_info.system_information.get();
- if (sys_info) {
- for (const SystemInformation& info : *sys_info)
- sys_logs->emplace(info.key, info.value);
- }
-
- feedback_data->SetAndCompressSystemInfo(std::move(sys_logs));
-
- FeedbackService* service =
- FeedbackPrivateAPI::GetFactoryInstance()->Get(GetProfile())->GetService();
- DCHECK(service);
-
- if (feedback_info.send_histograms) {
- auto histograms = base::MakeUnique<std::string>();
- *histograms = base::StatisticsRecorder::ToJSON(std::string());
- if (!histograms->empty())
- feedback_data->SetAndCompressHistograms(std::move(histograms));
- }
-
- service->SendFeedback(
- GetProfile(),
- feedback_data,
- base::Bind(&FeedbackPrivateSendFeedbackFunction::OnCompleted, this));
-
- return true;
-}
-
-void FeedbackPrivateSendFeedbackFunction::OnCompleted(
- bool success) {
- results_ = feedback_private::SendFeedback::Results::Create(
- success ? feedback_private::STATUS_SUCCESS :
- feedback_private::STATUS_DELAYED);
- SendResponse(true);
-
- if (!success) {
- // Sending the feedback has been delayed as the user is offline. Show a
- // message box to indicate that.
- chrome::ShowWarningMessageBox(
- nullptr, l10n_util::GetStringUTF16(IDS_FEEDBACK_OFFLINE_DIALOG_TITLE),
- l10n_util::GetStringUTF16(IDS_FEEDBACK_OFFLINE_DIALOG_TEXT));
- }
-}
-
-AsyncExtensionFunction::ResponseAction
-FeedbackPrivateLogSrtPromptResultFunction::Run() {
- std::unique_ptr<feedback_private::LogSrtPromptResult::Params> params(
- feedback_private::LogSrtPromptResult::Params::Create(*args_));
- EXTENSION_FUNCTION_VALIDATE(params.get());
-
- const feedback_private::SrtPromptResult result = params->result;
-
- switch (result) {
- case feedback_private::SRT_PROMPT_RESULT_ACCEPTED:
- base::RecordAction(base::UserMetricsAction("Feedback.SrtPromptAccepted"));
- break;
- case feedback_private::SRT_PROMPT_RESULT_DECLINED:
- base::RecordAction(base::UserMetricsAction("Feedback.SrtPromptDeclined"));
- break;
- case feedback_private::SRT_PROMPT_RESULT_CLOSED:
- base::RecordAction(base::UserMetricsAction("Feedback.SrtPromptClosed"));
- break;
- default:
- return RespondNow(Error("Invalid arugment."));
- }
- return RespondNow(NoArguments());
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h
deleted file mode 100644
index ef781bdab64..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h
+++ /dev/null
@@ -1,159 +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.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_PRIVATE_API_H_
-#define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_PRIVATE_API_H_
-
-#include <memory>
-
-#include "chrome/browser/extensions/chrome_extension_function.h"
-#include "chrome/common/extensions/api/feedback_private.h"
-#include "components/feedback/system_logs/system_logs_source.h"
-#include "extensions/browser/browser_context_keyed_api_factory.h"
-#include "extensions/browser/extension_function.h"
-#include "ui/gfx/geometry/rect.h"
-
-namespace extensions {
-
-class FeedbackService;
-#if defined(OS_CHROMEOS)
-class LogSourceAccessManager;
-#endif // defined(OS_CHROMEOS)
-
-class FeedbackPrivateAPI : public BrowserContextKeyedAPI {
- public:
- explicit FeedbackPrivateAPI(content::BrowserContext* context);
- ~FeedbackPrivateAPI() override;
-
- FeedbackService* GetService() const;
-
-#if defined(OS_CHROMEOS)
- LogSourceAccessManager* GetLogSourceAccessManager() const;
-#endif // defined(OS_CHROMEOS)
-
- void RequestFeedback(const std::string& description_template,
- const std::string& category_tag,
- const std::string& extra_diagnostics,
- const GURL& page_url);
-
- void RequestFeedbackForFlow(const std::string& description_template,
- const std::string& category_tag,
- const std::string& extra_diagnostics,
- const GURL& page_url,
- api::feedback_private::FeedbackFlow flow);
-
- // BrowserContextKeyedAPI implementation.
- static BrowserContextKeyedAPIFactory<FeedbackPrivateAPI>*
- GetFactoryInstance();
-
- private:
- friend class BrowserContextKeyedAPIFactory<FeedbackPrivateAPI>;
-
- // BrowserContextKeyedAPI implementation.
- static const char* service_name() {
- return "FeedbackPrivateAPI";
- }
-
- static const bool kServiceHasOwnInstanceInIncognito = true;
-
- content::BrowserContext* const browser_context_;
- std::unique_ptr<FeedbackService> service_;
-
-#if defined(OS_CHROMEOS)
- std::unique_ptr<LogSourceAccessManager> log_source_access_manager_;
-#endif // defined(OS_CHROMEOS)
-
- DISALLOW_COPY_AND_ASSIGN(FeedbackPrivateAPI);
-};
-
-// Feedback strings.
-class FeedbackPrivateGetStringsFunction : public UIThreadExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getStrings",
- FEEDBACKPRIVATE_GETSTRINGS)
-
- // Invoke this callback when this function is called - used for testing.
- static void set_test_callback(base::Closure* const callback) {
- test_callback_ = callback;
- }
-
- protected:
- ~FeedbackPrivateGetStringsFunction() override {}
-
- // ExtensionFunction:
- ResponseAction Run() override;
-
- private:
- static base::Closure* test_callback_;
-};
-
-class FeedbackPrivateGetUserEmailFunction : public UIThreadExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getUserEmail",
- FEEDBACKPRIVATE_GETUSEREMAIL);
-
- protected:
- ~FeedbackPrivateGetUserEmailFunction() override {}
- ResponseAction Run() override;
-};
-
-class FeedbackPrivateGetSystemInformationFunction
- : public UIThreadExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getSystemInformation",
- FEEDBACKPRIVATE_GETSYSTEMINFORMATION);
-
- protected:
- ~FeedbackPrivateGetSystemInformationFunction() override {}
- ResponseAction Run() override;
-
- private:
- void OnCompleted(std::unique_ptr<system_logs::SystemLogsResponse> sys_info);
-};
-
-// This function only reads from actual log sources on Chrome OS. On other
-// platforms, it just returns EmptyResponse().
-class FeedbackPrivateReadLogSourceFunction : public UIThreadExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("feedbackPrivate.readLogSource",
- FEEDBACKPRIVATE_READLOGSOURCE);
-
- protected:
- ~FeedbackPrivateReadLogSourceFunction() override {}
- ResponseAction Run() override;
-
-#if defined(OS_CHROMEOS)
- private:
- void OnCompleted(const api::feedback_private::ReadLogSourceResult& result);
-#endif // defined(OS_CHROMEOS)
-};
-
-class FeedbackPrivateSendFeedbackFunction
- : public ChromeAsyncExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("feedbackPrivate.sendFeedback",
- FEEDBACKPRIVATE_SENDFEEDBACK);
-
- protected:
- ~FeedbackPrivateSendFeedbackFunction() override {}
- bool RunAsync() override;
-
- private:
- void OnCompleted(bool success);
-};
-
-class FeedbackPrivateLogSrtPromptResultFunction
- : public UIThreadExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("feedbackPrivate.logSrtPromptResult",
- FEEDBACKPRIVATE_LOGSRTPROMPTRESULT);
-
- protected:
- ~FeedbackPrivateLogSrtPromptResultFunction() override {}
- AsyncExtensionFunction::ResponseAction Run() override;
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_PRIVATE_API_H_
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api_chromeos_unittest.cc
deleted file mode 100644
index ed67e165324..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api_chromeos_unittest.cc
+++ /dev/null
@@ -1,394 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
-
-#include "base/json/json_writer.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/test/simple_test_tick_clock.h"
-#include "base/values.h"
-#include "chrome/browser/extensions/api/feedback_private/log_source_resource.h"
-#include "chrome/browser/extensions/api/feedback_private/single_log_source_factory.h"
-#include "chrome/browser/extensions/extension_api_unittest.h"
-#include "extensions/browser/api_test_utils.h"
-
-namespace extensions {
-
-namespace {
-
-using api::feedback_private::LogSource;
-using api::feedback_private::ReadLogSourceResult;
-using api::feedback_private::ReadLogSourceParams;
-using base::TimeDelta;
-using system_logs::SystemLogsResponse;
-using system_logs::SystemLogsSource;
-
-std::unique_ptr<KeyedService> ApiResourceManagerTestFactory(
- content::BrowserContext* context) {
- return base::MakeUnique<ApiResourceManager<LogSourceResource>>(context);
-}
-
-// Converts |params| to a string containing a JSON dictionary within an argument
-// list.
-std::string ParamsToJSON(const ReadLogSourceParams& params) {
- base::ListValue params_value;
- params_value.Append(params.ToValue());
- std::string params_json_string;
- EXPECT_TRUE(base::JSONWriter::Write(params_value, &params_json_string));
-
- return params_json_string;
-}
-
-// A dummy SystemLogsSource that does not require real system logs to be
-// available during testing.
-class TestSingleLogSource : public SystemLogsSource {
- public:
- explicit TestSingleLogSource(LogSource type)
- : SystemLogsSource(ToString(type)), call_count_(0) {}
-
- ~TestSingleLogSource() override = default;
-
- // Fetch() will return a single different string each time, in the following
- // sequence: "a", " bb", " ccc", until 25 spaces followed by 26 z's. Will
- // never return an empty result.
- void Fetch(const system_logs::SysLogsSourceCallback& callback) override {
- int count_modulus = call_count_ % kNumCharsToIterate;
- std::string result =
- std::string(count_modulus, ' ') +
- std::string(count_modulus + 1, kInitialChar + count_modulus);
- ASSERT_GT(result.size(), 0U);
- ++call_count_;
-
- SystemLogsResponse* result_map = new SystemLogsResponse;
- result_map->emplace("", result);
-
- // Do not directly pass the result to the callback, because that's not how
- // log sources actually work. Instead, simulate the asynchronous operation
- // of a SystemLogsSource by invoking the callback separately.
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, base::Owned(result_map)));
- }
-
- // Instantiates a new instance of this class. Does not retain ownership. Used
- // to create a Callback that can be used to override the default behavior of
- // SingleLogSourceFactory.
- static std::unique_ptr<SystemLogsSource> Create(LogSource type) {
- return base::MakeUnique<TestSingleLogSource>(type);
- }
-
- private:
- // Iterate over the whole lowercase alphabet, starting from 'a'.
- const int kNumCharsToIterate = 26;
- const char kInitialChar = 'a';
-
- // Keep track of how many times Fetch() has been called, in order to determine
- // its behavior each time.
- int call_count_;
-
- DISALLOW_COPY_AND_ASSIGN(TestSingleLogSource);
-};
-
-} // namespace
-
-class FeedbackPrivateApiUnittest : public ExtensionApiUnittest {
- public:
- FeedbackPrivateApiUnittest()
- : create_callback_(base::Bind(&TestSingleLogSource::Create)) {}
- ~FeedbackPrivateApiUnittest() override {}
-
- void SetUp() override {
- ExtensionApiUnittest::SetUp();
-
- // The ApiResourceManager used for LogSourceResource is destroyed every time
- // a unit test finishes, during TearDown(). There is no way to re-create it
- // normally. The below code forces it to be re-created during SetUp(), so
- // that there is always a valid ApiResourceManager<LogSourceResource> when
- // subsequent unit tests are running.
- ApiResourceManager<LogSourceResource>::GetFactoryInstance()
- ->SetTestingFactoryAndUse(profile(), ApiResourceManagerTestFactory);
-
- SingleLogSourceFactory::SetForTesting(&create_callback_);
- }
-
- void TearDown() override {
- SingleLogSourceFactory::SetForTesting(nullptr);
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(nullptr);
-
- FeedbackPrivateAPI::GetFactoryInstance()
- ->Get(profile())
- ->GetLogSourceAccessManager()
- ->SetTickClockForTesting(nullptr);
-
- ExtensionApiUnittest::TearDown();
- }
-
- // Runs the feedbackPrivate.readLogSource() function. See API function
- // definition for argument descriptions.
- //
- // The API function is expected to complete successfully. For running the
- // function with an expectation of an error result, call
- // RunReadLogSourceFunctionWithError().
- //
- // Note that the second argument of the result is a list of strings, but the
- // test class TestSingleLogSource always returns a list containing a single
- // string. To simplify things, the single string result will be returned in
- // |*result_string|, while the reader ID is returned in |*result_reader_id|.
- testing::AssertionResult RunReadLogSourceFunction(
- const ReadLogSourceParams& params,
- int* result_reader_id,
- std::string* result_string) {
- scoped_refptr<FeedbackPrivateReadLogSourceFunction> function =
- new FeedbackPrivateReadLogSourceFunction;
-
- std::unique_ptr<base::Value> result_value =
- RunFunctionAndReturnValue(function.get(), ParamsToJSON(params));
- if (!result_value)
- return testing::AssertionFailure() << "No result";
-
- ReadLogSourceResult result;
- if (!ReadLogSourceResult::Populate(*result_value, &result)) {
- return testing::AssertionFailure()
- << "Unable to parse a valid result from " << *result_value;
- }
-
- if (result.log_lines.size() != 1) {
- return testing::AssertionFailure()
- << "Expected |log_lines| to contain 1 string, actual number: "
- << result.log_lines.size();
- }
-
- *result_reader_id = result.reader_id;
- *result_string = result.log_lines[0];
-
- return testing::AssertionSuccess();
- }
-
- // Similar to RunReadLogSourceFunction(), but expects to return an error.
- // Returns a string containing the error message. Does not return any result
- // from the API function.
- std::string RunReadLogSourceFunctionWithError(
- const ReadLogSourceParams& params) {
- scoped_refptr<FeedbackPrivateReadLogSourceFunction> function =
- new FeedbackPrivateReadLogSourceFunction;
-
- return RunFunctionAndReturnError(function.get(), ParamsToJSON(params));
- }
-
- private:
- // Passed to SingleLogSourceFactory so that the API can create an instance of
- // TestSingleLogSource for testing.
- SingleLogSourceFactory::CreateCallback create_callback_;
-
- DISALLOW_COPY_AND_ASSIGN(FeedbackPrivateApiUnittest);
-};
-
-TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceInvalidId) {
- const TimeDelta timeout(TimeDelta::FromMilliseconds(0));
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(&timeout);
-
- ReadLogSourceParams params;
- params.source = api::feedback_private::LOG_SOURCE_MESSAGES;
- params.incremental = true;
- params.reader_id.reset(new int(9999));
-
- EXPECT_NE("", RunReadLogSourceFunctionWithError(params));
-}
-
-TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceNonIncremental) {
- const TimeDelta timeout(TimeDelta::FromMilliseconds(0));
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(&timeout);
-
- ReadLogSourceParams params;
- params.source = api::feedback_private::LOG_SOURCE_MESSAGES;
- params.incremental = false;
-
- // Test multiple non-incremental reads.
- int result_reader_id = -1;
- std::string result_string;
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(0, result_reader_id);
- EXPECT_EQ("a", result_string);
-
- result_reader_id = -1;
- result_string.clear();
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(0, result_reader_id);
- EXPECT_EQ("a", result_string);
-
- result_reader_id = -1;
- result_string.clear();
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(0, result_reader_id);
- EXPECT_EQ("a", result_string);
-}
-
-TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceIncremental) {
- const TimeDelta timeout(TimeDelta::FromMilliseconds(0));
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(&timeout);
-
- ReadLogSourceParams params;
- params.source = api::feedback_private::LOG_SOURCE_MESSAGES;
- params.incremental = true;
-
- int result_reader_id = 0;
- std::string result_string;
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_GT(result_reader_id, 0);
- EXPECT_EQ("a", result_string);
- params.reader_id.reset(new int(result_reader_id));
-
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(*params.reader_id, result_reader_id);
- EXPECT_EQ(" bb", result_string);
-
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(*params.reader_id, result_reader_id);
- EXPECT_EQ(" ccc", result_string);
-
- // End the incremental read.
- params.incremental = false;
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(0, result_reader_id);
- EXPECT_EQ(" dddd", result_string);
-
- // The log source will no longer be valid if we try to read it.
- params.incremental = true;
- EXPECT_NE("", RunReadLogSourceFunctionWithError(params));
-}
-
-TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceMultipleSources) {
- const TimeDelta timeout(TimeDelta::FromMilliseconds(0));
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(&timeout);
-
- int result_reader_id = 0;
- std::string result_string;
-
- // Attempt to open LOG_SOURCE_MESSAGES twice.
- ReadLogSourceParams params_1st_read;
- params_1st_read.source = api::feedback_private::LOG_SOURCE_MESSAGES;
- params_1st_read.incremental = true;
- EXPECT_TRUE(RunReadLogSourceFunction(params_1st_read, &result_reader_id,
- &result_string));
- EXPECT_GT(result_reader_id, 0);
- // Store the reader ID back into the params to set up for the next call.
- params_1st_read.reader_id = base::MakeUnique<int>(result_reader_id);
-
- // Cannot create a second reader from the same log source.
- ReadLogSourceParams params_1st_read_repeated;
- params_1st_read_repeated.source = api::feedback_private::LOG_SOURCE_MESSAGES;
- params_1st_read_repeated.incremental = true;
- EXPECT_NE("", RunReadLogSourceFunctionWithError(params_1st_read_repeated));
-
- // Attempt to open LOG_SOURCE_UI_LATEST twice.
- ReadLogSourceParams params_2nd_read;
- params_2nd_read.source = api::feedback_private::LOG_SOURCE_UILATEST;
- params_2nd_read.incremental = true;
- result_reader_id = -1;
- EXPECT_TRUE(RunReadLogSourceFunction(params_2nd_read, &result_reader_id,
- &result_string));
- EXPECT_GT(result_reader_id, 0);
- EXPECT_NE(*params_1st_read.reader_id, result_reader_id);
- // Store the reader ID back into the params to set up for the next call.
- params_2nd_read.reader_id = base::MakeUnique<int>(result_reader_id);
-
- // Cannot create a second reader from the same log source.
- ReadLogSourceParams params_2nd_read_repeated;
- params_2nd_read_repeated.source = api::feedback_private::LOG_SOURCE_UILATEST;
- params_2nd_read_repeated.incremental = true;
- EXPECT_NE("", RunReadLogSourceFunctionWithError(params_2nd_read_repeated));
-
- // Close the two open log source readers, and make sure new ones can be
- // opened.
- params_1st_read.incremental = false;
- result_reader_id = -1;
- EXPECT_TRUE(RunReadLogSourceFunction(params_1st_read, &result_reader_id,
- &result_string));
- EXPECT_EQ(0, result_reader_id);
-
- params_2nd_read.incremental = false;
- result_reader_id = -1;
- EXPECT_TRUE(RunReadLogSourceFunction(params_2nd_read, &result_reader_id,
- &result_string));
- EXPECT_EQ(0, result_reader_id);
-
- EXPECT_TRUE(RunReadLogSourceFunction(params_1st_read_repeated,
- &result_reader_id, &result_string));
- EXPECT_GT(result_reader_id, 0);
- const int new_read_result_reader_id = result_reader_id;
-
- EXPECT_TRUE(RunReadLogSourceFunction(params_2nd_read_repeated,
- &result_reader_id, &result_string));
- EXPECT_GT(result_reader_id, 0);
- EXPECT_NE(new_read_result_reader_id, result_reader_id);
-}
-
-TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceWithAccessTimeouts) {
- const TimeDelta timeout(TimeDelta::FromMilliseconds(100));
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(&timeout);
-
- base::SimpleTestTickClock* test_clock = new base::SimpleTestTickClock;
- FeedbackPrivateAPI::GetFactoryInstance()
- ->Get(profile())
- ->GetLogSourceAccessManager()
- ->SetTickClockForTesting(std::unique_ptr<base::TickClock>(test_clock));
-
- ReadLogSourceParams params;
- params.source = api::feedback_private::LOG_SOURCE_MESSAGES;
- params.incremental = true;
- int result_reader_id = 0;
- std::string result_string;
-
- // |test_clock| must start out at something other than 0, which is interpreted
- // as an invalid value.
- test_clock->Advance(TimeDelta::FromMilliseconds(100));
-
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
- EXPECT_EQ(1, result_reader_id);
- params.reader_id.reset(new int(result_reader_id));
-
- // Immediately perform another read. This is not allowed. (empty result)
- EXPECT_FALSE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-
- // Advance to t=120, but it will not be allowed. (empty result)
- test_clock->Advance(TimeDelta::FromMilliseconds(20));
- EXPECT_FALSE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-
- // Advance to t=150, but still not allowed.
- test_clock->Advance(TimeDelta::FromMilliseconds(30));
- EXPECT_FALSE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-
- // Advance to t=199, but still not allowed. (empty result)
- test_clock->Advance(TimeDelta::FromMilliseconds(49));
- EXPECT_FALSE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-
- // Advance to t=210, annd the access is finally allowed.
- test_clock->Advance(TimeDelta::FromMilliseconds(11));
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-
- // Advance to t=309, but it will not be allowed. (empty result)
- test_clock->Advance(TimeDelta::FromMilliseconds(99));
- EXPECT_FALSE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-
- // Another read is finally allowed at t=310.
- test_clock->Advance(TimeDelta::FromMilliseconds(1));
- EXPECT_TRUE(
- RunReadLogSourceFunction(params, &result_reader_id, &result_string));
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_apitest.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_apitest.cc
deleted file mode 100644
index de42a7ec285..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_apitest.cc
+++ /dev/null
@@ -1,22 +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 "base/message_loop/message_loop.h"
-#include "build/build_config.h"
-#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
-#include "chrome/browser/extensions/extension_apitest.h"
-
-namespace extensions {
-
-class FeedbackApiTest: public ExtensionApiTest {
- public:
- FeedbackApiTest() {}
- ~FeedbackApiTest() override {}
-};
-
-IN_PROC_BROWSER_TEST_F(FeedbackApiTest, Basic) {
- EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_;
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc
deleted file mode 100644
index 869afd4cbbc..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc
+++ /dev/null
@@ -1,119 +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 "chrome/browser/extensions/api/feedback_private/feedback_service.h"
-
-#include <utility>
-
-#include "base/callback.h"
-#include "base/memory/weak_ptr.h"
-#include "base/strings/string_number_conversions.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/feedback/system_logs/chrome_system_logs_fetcher.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/chrome_content_client.h"
-#include "content/public/browser/browser_thread.h"
-#include "extensions/browser/blob_reader.h"
-#include "net/base/network_change_notifier.h"
-
-using content::BrowserThread;
-using feedback::FeedbackData;
-
-namespace extensions {
-
-FeedbackService::FeedbackService() {
-}
-
-FeedbackService::~FeedbackService() {
-}
-
-void FeedbackService::SendFeedback(
- Profile* profile,
- scoped_refptr<FeedbackData> feedback_data,
- const SendFeedbackCallback& callback) {
- feedback_data->set_locale(g_browser_process->GetApplicationLocale());
- feedback_data->set_user_agent(GetUserAgent());
-
- if (!feedback_data->attached_file_uuid().empty()) {
- // Self-deleting object.
- BlobReader* attached_file_reader =
- new BlobReader(profile, feedback_data->attached_file_uuid(),
- base::Bind(&FeedbackService::AttachedFileCallback,
- AsWeakPtr(), feedback_data, callback));
- attached_file_reader->Start();
- }
-
- if (!feedback_data->screenshot_uuid().empty()) {
- // Self-deleting object.
- BlobReader* screenshot_reader =
- new BlobReader(profile, feedback_data->screenshot_uuid(),
- base::Bind(&FeedbackService::ScreenshotCallback,
- AsWeakPtr(), feedback_data, callback));
- screenshot_reader->Start();
- }
-
- CompleteSendFeedback(feedback_data, callback);
-}
-
-void FeedbackService::GetSystemInformation(
- const system_logs::SysLogsFetcherCallback& callback) {
- // Self-deleting object.
- system_logs::SystemLogsFetcher* fetcher =
- system_logs::BuildChromeSystemLogsFetcher();
- fetcher->Fetch(callback);
-}
-
-void FeedbackService::AttachedFileCallback(
- scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback,
- std::unique_ptr<std::string> data,
- int64_t /* total_blob_length */) {
- feedback_data->set_attached_file_uuid(std::string());
- if (data)
- feedback_data->AttachAndCompressFileData(std::move(data));
-
- CompleteSendFeedback(feedback_data, callback);
-}
-
-void FeedbackService::ScreenshotCallback(
- scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback,
- std::unique_ptr<std::string> data,
- int64_t /* total_blob_length */) {
- feedback_data->set_screenshot_uuid(std::string());
- if (data)
- feedback_data->set_image(std::move(data));
-
- CompleteSendFeedback(feedback_data, callback);
-}
-
-void FeedbackService::CompleteSendFeedback(
- scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback) {
- // A particular data collection is considered completed if,
- // a.) The blob URL is invalid - this will either happen because we never had
- // a URL and never needed to read this data, or that the data read failed
- // and we set it to invalid in the data read callback.
- // b.) The associated data object exists, meaning that the data has been read
- // and the read callback has updated the associated data on the feedback
- // object.
- const bool attached_file_completed =
- feedback_data->attached_file_uuid().empty();
- const bool screenshot_completed = feedback_data->screenshot_uuid().empty();
-
- if (screenshot_completed && attached_file_completed) {
- // Signal the feedback object that the data from the feedback page has been
- // filled - the object will manage sending of the actual report.
- feedback_data->OnFeedbackPageDataComplete();
-
- // Sending the feedback will be delayed if the user is offline.
- const bool result = !net::NetworkChangeNotifier::IsOffline();
-
- // TODO(rkc): Change this once we have FeedbackData/Util refactored to
- // report the status of the report being sent.
- callback.Run(result);
- }
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h
deleted file mode 100644
index 9e6dfa87944..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h
+++ /dev/null
@@ -1,67 +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.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_SERVICE_H_
-#define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_SERVICE_H_
-
-#include <stdint.h>
-
-#include <vector>
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "components/feedback/feedback_data.h"
-#include "components/feedback/system_logs/system_logs_fetcher.h"
-
-class Profile;
-
-namespace extensions {
-
-// The feedback service provides the ability to gather the various pieces of
-// data needed to send a feedback report and then send the report once all
-// the pieces are available.
-class FeedbackService : public base::SupportsWeakPtr<FeedbackService> {
- public:
- // Callback invoked when the feedback report is ready to be sent.
- // True will be passed to indicate that it is being successfully sent now,
- // and false to indicate that it will be delayed (usually due to being
- // offline).
- using SendFeedbackCallback = base::Callback<void(bool)>;
-
- FeedbackService();
- virtual ~FeedbackService();
-
- // Sends a feedback report.
- void SendFeedback(Profile* profile,
- scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback);
-
- // Start to gather system information.
- // The |callback| will be invoked once the query is completed.
- void GetSystemInformation(
- const system_logs::SysLogsFetcherCallback& callback);
-
- private:
- // Callbacks to receive blob data.
- void AttachedFileCallback(scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback,
- std::unique_ptr<std::string> data,
- int64_t total_blob_length);
- void ScreenshotCallback(scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback,
- std::unique_ptr<std::string> data,
- int64_t total_blob_length);
-
- // Checks if we have read all the blobs we need to; signals the feedback
- // data object once all the requisite data has been populated.
- void CompleteSendFeedback(scoped_refptr<feedback::FeedbackData> feedback_data,
- const SendFeedbackCallback& callback);
-
- DISALLOW_COPY_AND_ASSIGN(FeedbackService);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_SERVICE_H_
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.cc b/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.cc
deleted file mode 100644
index a71167e3525..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.cc
+++ /dev/null
@@ -1,203 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/feedback_private/log_source_access_manager.h"
-
-#include <algorithm>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/string_split.h"
-#include "base/time/default_tick_clock.h"
-#include "chrome/browser/extensions/api/feedback_private/log_source_resource.h"
-#include "chrome/browser/extensions/api/feedback_private/single_log_source_factory.h"
-#include "extensions/browser/api/api_resource_manager.h"
-
-namespace extensions {
-
-namespace {
-
-namespace feedback_private = api::feedback_private;
-
-using SystemLogsResponse = system_logs::SystemLogsResponse;
-
-const int kMaxReadersPerSource = 10;
-
-// The minimum time between consecutive reads of a log source by a particular
-// extension.
-const int kDefaultRateLimitingTimeoutMs = 1000;
-
-// If this is null, then |kDefaultRateLimitingTimeoutMs| is used as the timeout.
-const base::TimeDelta* g_rate_limiting_timeout = nullptr;
-
-base::TimeDelta GetMinTimeBetweenReads() {
- return g_rate_limiting_timeout
- ? *g_rate_limiting_timeout
- : base::TimeDelta::FromMilliseconds(kDefaultRateLimitingTimeoutMs);
-}
-
-// SystemLogsResponse is a map of strings -> strings. The map value has the
-// actual log contents, a string containing all lines, separated by newlines.
-// This function extracts the individual lines and converts them into a vector
-// of strings, each string containing a single line.
-void GetLogLinesFromSystemLogsResponse(const SystemLogsResponse& response,
- std::vector<std::string>* log_lines) {
- for (const std::pair<std::string, std::string>& pair : response) {
- std::vector<std::string> new_lines = base::SplitString(
- pair.second, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
- log_lines->reserve(log_lines->size() + new_lines.size());
- log_lines->insert(log_lines->end(), new_lines.begin(), new_lines.end());
- }
-}
-
-} // namespace
-
-LogSourceAccessManager::LogSourceAccessManager(content::BrowserContext* context)
- : context_(context),
- tick_clock_(new base::DefaultTickClock),
- weak_factory_(this) {}
-
-LogSourceAccessManager::~LogSourceAccessManager() {}
-
-// static
-void LogSourceAccessManager::SetRateLimitingTimeoutForTesting(
- const base::TimeDelta* timeout) {
- g_rate_limiting_timeout = timeout;
-}
-
-bool LogSourceAccessManager::FetchFromSource(
- const feedback_private::ReadLogSourceParams& params,
- const std::string& extension_id,
- const ReadLogSourceCallback& callback) {
- SourceAndExtension key = SourceAndExtension(params.source, extension_id);
- int requested_resource_id = params.reader_id ? *params.reader_id : 0;
- int resource_id =
- requested_resource_id > 0 ? requested_resource_id : CreateResource(key);
- if (resource_id <= 0)
- return false;
-
- ApiResourceManager<LogSourceResource>* resource_manager =
- ApiResourceManager<LogSourceResource>::Get(context_);
- LogSourceResource* resource =
- resource_manager->Get(extension_id, resource_id);
- if (!resource)
- return false;
-
- // Enforce the rules: rate-limit access to the source from the current
- // extension. If not enough time has elapsed since the last access, do not
- // read from the source, but instead return an empty response. From the
- // caller's perspective, there is no new data. There is no need for the caller
- // to keep track of the time since last access.
- if (!UpdateSourceAccessTime(key)) {
- feedback_private::ReadLogSourceResult empty_result;
- callback.Run(empty_result);
- return true;
- }
-
- // If the API call requested a non-incremental access, clean up the
- // SingleLogSource by removing its API resource. Even if the existing source
- // were originally created as incremental, passing in incremental=false on a
- // later access indicates that the source should be closed afterwards.
- bool delete_resource_when_done = !params.incremental;
-
- resource->GetLogSource()->Fetch(base::Bind(
- &LogSourceAccessManager::OnFetchComplete, weak_factory_.GetWeakPtr(), key,
- delete_resource_when_done, callback));
- return true;
-}
-
-void LogSourceAccessManager::OnFetchComplete(
- const SourceAndExtension& key,
- bool delete_resource,
- const ReadLogSourceCallback& callback,
- SystemLogsResponse* response) {
- int resource_id = 0;
- const auto iter = sources_.find(key);
- if (iter != sources_.end())
- resource_id = iter->second;
-
- feedback_private::ReadLogSourceResult result;
- // Always return reader_id=0 if there is a cleanup.
- result.reader_id = delete_resource ? 0 : resource_id;
-
- GetLogLinesFromSystemLogsResponse(*response, &result.log_lines);
- if (delete_resource) {
- // This should also remove the entry from |sources_|.
- ApiResourceManager<LogSourceResource>::Get(context_)->Remove(
- key.extension_id, resource_id);
- }
-
- callback.Run(result);
-}
-
-void LogSourceAccessManager::RemoveSource(const SourceAndExtension& key) {
- sources_.erase(key);
-}
-
-LogSourceAccessManager::SourceAndExtension::SourceAndExtension(
- feedback_private::LogSource source,
- const std::string& extension_id)
- : source(source), extension_id(extension_id) {}
-
-int LogSourceAccessManager::CreateResource(const SourceAndExtension& key) {
- // Enforce the rules: Do not create a new SingleLogSource if there was already
- // one created for |key|.
- if (sources_.find(key) != sources_.end())
- return 0;
-
- // Enforce the rules: Do not create too many SingleLogSource objects to read
- // from a source, even if they are from different extensions.
- if (GetNumActiveResourcesForSource(key.source) >= kMaxReadersPerSource)
- return 0;
-
- std::unique_ptr<LogSourceResource> new_resource =
- base::MakeUnique<LogSourceResource>(
- key.extension_id,
- SingleLogSourceFactory::CreateSingleLogSource(key.source),
- base::Bind(&LogSourceAccessManager::RemoveSource,
- weak_factory_.GetWeakPtr(), key));
-
- int id = ApiResourceManager<LogSourceResource>::Get(context_)->Add(
- new_resource.release());
- sources_[key] = id;
-
- return id;
-}
-
-bool LogSourceAccessManager::UpdateSourceAccessTime(
- const SourceAndExtension& key) {
- base::TimeTicks last = GetLastExtensionAccessTime(key);
- base::TimeTicks now = tick_clock_->NowTicks();
- if (!last.is_null() && now < last + GetMinTimeBetweenReads()) {
- return false;
- }
- last_access_times_[key] = now;
- return true;
-}
-
-base::TimeTicks LogSourceAccessManager::GetLastExtensionAccessTime(
- const SourceAndExtension& key) const {
- const auto iter = last_access_times_.find(key);
- if (iter == last_access_times_.end())
- return base::TimeTicks();
-
- return iter->second;
-}
-
-size_t LogSourceAccessManager::GetNumActiveResourcesForSource(
- feedback_private::LogSource source) const {
- size_t count = 0;
- // The stored entries are sorted first by source type, then by extension ID.
- // We can take advantage of this fact to avoid iterating over all elements.
- // Instead start from the first element that matches |source|, and end at the
- // first element that does not match |source| anymore.
- for (auto iter = sources_.lower_bound(SourceAndExtension(source, ""));
- iter != sources_.end() && iter->first.source == source; ++iter) {
- ++count;
- }
- return count;
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.h b/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.h
deleted file mode 100644
index 9d44b01e746..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager.h
+++ /dev/null
@@ -1,144 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_LOG_SOURCE_ACCESS_MANAGER_H_
-#define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_LOG_SOURCE_ACCESS_MANAGER_H_
-
-#include <map>
-#include <string>
-#include <utility>
-
-#include "base/callback.h"
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/time/tick_clock.h"
-#include "base/time/time.h"
-#include "chrome/common/extensions/api/feedback_private.h"
-#include "components/feedback/system_logs/system_logs_source.h"
-#include "content/public/browser/browser_context.h"
-
-namespace extensions {
-
-// Provides bookkeepping for SingleLogSource usage. It ensures that:
-// - Each extension can have only one SingleLogSource for a particular source.
-// - A source may not be accessed too frequently by an extension.
-class LogSourceAccessManager {
- public:
- using ReadLogSourceCallback =
- base::Callback<void(const api::feedback_private::ReadLogSourceResult&)>;
-
- explicit LogSourceAccessManager(content::BrowserContext* context);
- ~LogSourceAccessManager();
-
- // To override the default rate-limiting mechanism of this function, pass in
- // a TimeDelta representing the desired minimum time between consecutive reads
- // of a source from an extension. Does not take ownership of |timeout|. When
- // done testing, call this function again with |timeout|=nullptr to reset to
- // the default behavior.
- static void SetRateLimitingTimeoutForTesting(const base::TimeDelta* timeout);
-
- // Override the default base::Time clock with a custom clock for testing.
- // Pass in |clock|=nullptr to revert to default behavior.
- void SetTickClockForTesting(std::unique_ptr<base::TickClock> clock) {
- tick_clock_ = std::move(clock);
- }
-
- // Initiates a fetch from a log source, as specified in |params|. See
- // feedback_private.idl for more info about the actual parameters.
- bool FetchFromSource(const api::feedback_private::ReadLogSourceParams& params,
- const std::string& extension_id,
- const ReadLogSourceCallback& callback);
-
- private:
- FRIEND_TEST_ALL_PREFIXES(LogSourceAccessManagerTest,
- MaxNumberOfOpenLogSources);
-
- // Contains a source/extension pair.
- struct SourceAndExtension {
- explicit SourceAndExtension(api::feedback_private::LogSource source,
- const std::string& extension_id);
-
- bool operator<(const SourceAndExtension& other) const {
- return std::make_pair(source, extension_id) <
- std::make_pair(other.source, other.extension_id);
- }
-
- api::feedback_private::LogSource source;
- std::string extension_id;
- };
-
- // Creates a new LogSourceResource for the source and extension indicated by
- // |key|. Stores the new resource in the API Resource Manager and stores the
- // resource ID in |sources_| as a new entry. Returns the nonzero ID of the
- // newly created resource, or 0 if there was already an existing resource for
- // |key|.
- int CreateResource(const SourceAndExtension& key);
-
- // Callback that is passed to the log source from FetchFromSource.
- // Arguments:
- // - key: The source that was read, and the extension requesting the read.
- // - delete_source: Set this if the source indicated by |key| should be
- // removed from both the API Resource Manager and from |sources_|.
- // - response_callback: Callback for sending the response as a
- // ReadLogSourceResult struct.
- void OnFetchComplete(const SourceAndExtension& key,
- bool delete_source,
- const ReadLogSourceCallback& callback,
- system_logs::SystemLogsResponse* response);
-
- // Removes an existing log source indicated by |key| from both the API
- // Resource Manager and |sources_|.
- void RemoveSource(const SourceAndExtension& key);
-
- // Attempts to update the entry for |key| in |last_access_times_| to the
- // current time, to record that the source is being accessed by the extension
- // right now. If less than |min_time_between_reads_| has elapsed since the
- // last successful read, do not update the timestamp in |last_access_times_|,
- // and instead return false. Otherwise returns true.
- //
- // Creates a new entry in |last_access_times_| if it doesn't exist. Will not
- // delete from |last_access_times_|.
- bool UpdateSourceAccessTime(const SourceAndExtension& key);
-
- // Returns the last time that |key.source| was accessed by |key.extension|.
- // If it was never accessed by the extension, returns an empty base::TimeTicks
- // object.
- base::TimeTicks GetLastExtensionAccessTime(
- const SourceAndExtension& key) const;
-
- // Returns the number of entries in |sources_| with source=|source|.
- size_t GetNumActiveResourcesForSource(
- api::feedback_private::LogSource source) const;
-
- // Every SourceAndExtension is linked to a unique SingleLogSource.
- //
- // Keys: SourceAndExtension for which a SingleLogSource has been created
- // and not yet destroyed. (i.e. currently in use).
- // Values: ID of the API Resource containing the SingleLogSource.
- std::map<SourceAndExtension, int> sources_;
-
- // Keeps track of the last time each source was accessed by each extension.
- // Each time FetchFromSource() is called, the timestamp gets updated.
- //
- // This intentionally kept separate from |sources_| because entries can be
- // removed from and re-added to |sources_|, but that should not erase the
- // recorded access times.
- std::map<SourceAndExtension, base::TimeTicks> last_access_times_;
-
- // For fetching browser resources like ApiResourceManager.
- content::BrowserContext* context_;
-
- // Provides a timer clock implementation for keeping track of access times.
- // Can override the default clock for testing.
- std::unique_ptr<base::TickClock> tick_clock_;
-
- base::WeakPtrFactory<LogSourceAccessManager> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(LogSourceAccessManager);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_LOG_SOURCE_ACCESS_MANAGER_H_
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager_chromeos_unittest.cc
deleted file mode 100644
index 9e7f466d15d..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/log_source_access_manager_chromeos_unittest.cc
+++ /dev/null
@@ -1,160 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/feedback_private/log_source_access_manager.h"
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/run_loop.h"
-#include "base/strings/stringprintf.h"
-#include "chrome/browser/extensions/api/feedback_private/log_source_resource.h"
-#include "chrome/browser/extensions/api/feedback_private/single_log_source_factory.h"
-#include "chrome/browser/extensions/extension_api_unittest.h"
-#include "extensions/browser/api/api_resource_manager.h"
-
-namespace extensions {
-
-namespace {
-
-using api::feedback_private::LOG_SOURCE_MESSAGES;
-using api::feedback_private::LOG_SOURCE_UILATEST;
-using api::feedback_private::LogSource;
-using api::feedback_private::ReadLogSourceResult;
-using api::feedback_private::ReadLogSourceParams;
-using system_logs::SystemLogsSource;
-
-std::unique_ptr<KeyedService> ApiResourceManagerTestFactory(
- content::BrowserContext* context) {
- return base::MakeUnique<ApiResourceManager<LogSourceResource>>(context);
-}
-
-// Dummy function used as a callback for FetchFromSource().
-void OnFetchedFromSource(const ReadLogSourceResult& result) {}
-
-// A dummy SystemLogsSource that does not require real system logs to be
-// available during testing. Always returns an empty result.
-class EmptySingleLogSource : public system_logs::SystemLogsSource {
- public:
- explicit EmptySingleLogSource(LogSource type)
- : SystemLogsSource(api::feedback_private::ToString(type)) {}
-
- ~EmptySingleLogSource() override = default;
-
- void Fetch(const system_logs::SysLogsSourceCallback& callback) override {
- system_logs::SystemLogsResponse* result_map =
- new system_logs::SystemLogsResponse;
- result_map->emplace("", "");
-
- // Do not directly pass the result to the callback, because that's not how
- // log sources actually work. Instead, simulate the asynchronous operation
- // of a SystemLogsSource by invoking the callback separately.
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, base::Owned(result_map)));
- }
-
- // Instantiates a new instance of this class. Does not retain ownership. Used
- // to create a Callback that can be used to override the default behavior of
- // SingleLogSourceFactory.
- static std::unique_ptr<SystemLogsSource> Create(LogSource type) {
- return base::MakeUnique<EmptySingleLogSource>(type);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(EmptySingleLogSource);
-};
-
-} // namespace
-
-class LogSourceAccessManagerTest : public ExtensionApiUnittest {
- public:
- LogSourceAccessManagerTest()
- : create_callback_(base::Bind(&EmptySingleLogSource::Create)) {}
- ~LogSourceAccessManagerTest() override {}
-
- void SetUp() override {
- ExtensionApiUnittest::SetUp();
-
- // The ApiResourceManager used for LogSourceResource is destroyed every time
- // a unit test finishes, during TearDown(). There is no way to re-create it
- // normally. The below code forces it to be re-created during SetUp(), so
- // that there is always a valid ApiResourceManager<LogSourceResource> when
- // subsequent unit tests are running.
- ApiResourceManager<LogSourceResource>::GetFactoryInstance()
- ->SetTestingFactoryAndUse(profile(), ApiResourceManagerTestFactory);
-
- SingleLogSourceFactory::SetForTesting(&create_callback_);
- }
-
- void TearDown() override {
- SingleLogSourceFactory::SetForTesting(nullptr);
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(nullptr);
-
- ExtensionApiUnittest::TearDown();
- }
-
- private:
- // Passed to SingleLogSourceFactory so that the API can create an instance of
- // TestSingleLogSource for testing.
- SingleLogSourceFactory::CreateCallback create_callback_;
-
- DISALLOW_COPY_AND_ASSIGN(LogSourceAccessManagerTest);
-};
-
-TEST_F(LogSourceAccessManagerTest, MaxNumberOfOpenLogSources) {
- const base::TimeDelta timeout(base::TimeDelta::FromMilliseconds(0));
- LogSourceAccessManager::SetRateLimitingTimeoutForTesting(&timeout);
-
- LogSourceAccessManager manager(profile());
- LogSourceAccessManager::ReadLogSourceCallback callback =
- base::Bind(&OnFetchedFromSource);
-
- int count = 0;
-
- // Open 10 readers for LOG_SOURCE_MESSAGES.
- ReadLogSourceParams messages_params;
- messages_params.incremental = false;
- messages_params.source = LOG_SOURCE_MESSAGES;
- for (int i = 0; i < 10; ++i, ++count) {
- EXPECT_TRUE(manager.FetchFromSource(
- messages_params, base::StringPrintf("extension %d", count), callback))
- << count;
- }
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_MESSAGES));
- EXPECT_EQ(0U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_UILATEST));
-
- // Open 10 readers for LOG_SOURCE_UILATEST.
- ReadLogSourceParams ui_latest_params;
- ui_latest_params.incremental = false;
- ui_latest_params.source = LOG_SOURCE_UILATEST;
- for (int i = 0; i < 10; ++i, ++count) {
- EXPECT_TRUE(manager.FetchFromSource(
- ui_latest_params, base::StringPrintf("extension %d", count), callback))
- << count;
- }
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_MESSAGES));
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_UILATEST));
-
- // Can't open more readers for LOG_SOURCE_MESSAGES.
- for (int i = 0; i < 10; ++i, ++count) {
- EXPECT_FALSE(manager.FetchFromSource(
- messages_params, base::StringPrintf("extension %d", count), callback))
- << count;
- }
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_MESSAGES));
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_UILATEST));
-
- // Can't open more readers for LOG_SOURCE_UILATEST.
- for (int i = 0; i < 10; ++i, ++count) {
- EXPECT_FALSE(manager.FetchFromSource(
- ui_latest_params, base::StringPrintf("extension %d", count), callback))
- << count;
- }
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_MESSAGES));
- EXPECT_EQ(10U, manager.GetNumActiveResourcesForSource(LOG_SOURCE_UILATEST));
-
- // Wait for all asynchronous operations to complete.
- base::RunLoop().RunUntilIdle();
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.cc b/chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.cc
deleted file mode 100644
index b416a5fbe07..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/feedback_private/log_source_resource.h"
-
-#include "base/lazy_instance.h"
-
-namespace extensions {
-
-// For managing API resources of type LogSourceResource.
-static base::LazyInstance<BrowserContextKeyedAPIFactory<
- ApiResourceManager<LogSourceResource>>>::DestructorAtExit
- g_log_source_resource_factory = LAZY_INSTANCE_INITIALIZER;
-
-// static
-template <>
-BrowserContextKeyedAPIFactory<ApiResourceManager<LogSourceResource>>*
-ApiResourceManager<LogSourceResource>::GetFactoryInstance() {
- return g_log_source_resource_factory.Pointer();
-}
-
-LogSourceResource::LogSourceResource(
- const std::string& extension_id,
- std::unique_ptr<system_logs::SystemLogsSource> source,
- base::Closure unregister_callback)
- : ApiResource(extension_id),
- source_(source.release()),
- unregister_runner_(unregister_callback) {}
-
-LogSourceResource::~LogSourceResource() {}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.h b/chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.h
deleted file mode 100644
index e510360c1a7..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/log_source_resource.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_LOG_SOURCE_RESOURCE_H_
-#define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_LOG_SOURCE_RESOURCE_H_
-
-#include <memory>
-
-#include "base/callback_helpers.h"
-#include "base/macros.h"
-#include "chrome/browser/extensions/api/feedback_private/log_source_access_manager.h"
-#include "components/feedback/system_logs/system_logs_fetcher.h"
-#include "extensions/browser/api/api_resource.h"
-#include "extensions/browser/api/api_resource_manager.h"
-
-namespace extensions {
-
-// Holds a SystemLogsSource object that is used by an extension using the
-// feedbackPrivate API.
-class LogSourceResource : public ApiResource {
- public:
- static const content::BrowserThread::ID kThreadId =
- content::BrowserThread::UI;
-
- LogSourceResource(const std::string& extension_id,
- std::unique_ptr<system_logs::SystemLogsSource> source,
- base::Closure unregister_callback_);
-
- ~LogSourceResource() override;
-
- system_logs::SystemLogsSource* GetLogSource() const { return source_.get(); }
-
- private:
- friend class ApiResourceManager<LogSourceResource>;
- static const char* service_name() { return "LogSourceResource"; }
-
- std::unique_ptr<system_logs::SystemLogsSource> source_;
-
- // This unregisters the LogSourceResource from a LogSourceAccessManager when
- // this resource is cleaned up. Just pass in a base::Closure to the
- // constructor.
- base::ScopedClosureRunner unregister_runner_;
-
- DISALLOW_COPY_AND_ASSIGN(LogSourceResource);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_LOG_SOURCE_RESOURCE_H_
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.cc b/chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.cc
deleted file mode 100644
index f9177c83562..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/feedback_private/single_log_source_factory.h"
-
-#include "base/memory/ptr_util.h"
-#include "chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.h"
-#include "chrome/browser/chromeos/system_logs/single_log_file_log_source.h"
-
-namespace extensions {
-
-namespace {
-
-namespace feedback_private = api::feedback_private;
-
-using system_logs::SingleDebugDaemonLogSource;
-using system_logs::SingleLogFileLogSource;
-using system_logs::SystemLogsSource;
-
-SingleLogSourceFactory::CreateCallback* g_callback = nullptr;
-
-} // namespace
-
-// static
-std::unique_ptr<SystemLogsSource> SingleLogSourceFactory::CreateSingleLogSource(
- feedback_private::LogSource source_type) {
- if (g_callback)
- return g_callback->Run(source_type);
-
- switch (source_type) {
- case feedback_private::LOG_SOURCE_MESSAGES:
- return base::MakeUnique<SingleLogFileLogSource>(
- SingleLogFileLogSource::SupportedSource::kMessages);
- case feedback_private::LOG_SOURCE_UILATEST:
- return base::MakeUnique<SingleLogFileLogSource>(
- SingleLogFileLogSource::SupportedSource::kUiLatest);
- case feedback_private::LOG_SOURCE_DRMMODETEST:
- return base::MakeUnique<SingleDebugDaemonLogSource>(
- SingleDebugDaemonLogSource::SupportedSource::kModetest);
- case feedback_private::LOG_SOURCE_LSUSB:
- return base::MakeUnique<SingleDebugDaemonLogSource>(
- SingleDebugDaemonLogSource::SupportedSource::kLsusb);
- case feedback_private::LOG_SOURCE_ATRUSLOG:
- return base::MakeUnique<SingleLogFileLogSource>(
- SingleLogFileLogSource::SupportedSource::kAtrusLog);
- case feedback_private::LOG_SOURCE_NONE:
- default:
- NOTREACHED() << "Unknown log source type.";
- break;
- }
- return std::unique_ptr<SystemLogsSource>(nullptr);
-}
-
-// static
-void SingleLogSourceFactory::SetForTesting(
- SingleLogSourceFactory::CreateCallback* callback) {
- g_callback = callback;
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.h b/chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.h
deleted file mode 100644
index 5743d1a07bf..00000000000
--- a/chromium/chrome/browser/extensions/api/feedback_private/single_log_source_factory.h
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_SINGLE_LOG_SOURCE_FACTORY_H_
-#define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_SINGLE_LOG_SOURCE_FACTORY_H_
-
-#include <memory>
-
-#include "base/callback.h"
-#include "chrome/common/extensions/api/feedback_private.h"
-#include "components/feedback/system_logs/system_logs_fetcher.h"
-
-namespace extensions {
-
-// Provides a way to override the creation of a new Single*LogSource during
-// testing.
-class SingleLogSourceFactory {
- public:
- using CreateCallback =
- base::Callback<std::unique_ptr<system_logs::SystemLogsSource>(
- api::feedback_private::LogSource)>;
-
- // Returns a Single*LogSource with source type corresponding to |type|. The
- // caller must takeownership of the returned object.
- static std::unique_ptr<system_logs::SystemLogsSource> CreateSingleLogSource(
- api::feedback_private::LogSource type);
-
- // Pass in a callback that gets executed instead of the default behavior of
- // CreateSingleLogSource. Does not take ownership of |callback|. When done
- // testing, call this function again with |callback|=nullptr to restore the
- // default behavior.
- static void SetForTesting(CreateCallback* callback);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_SINGLE_LOG_SOURCE_FACTORY_H_
diff --git a/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc b/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc
index 23782c4dfb9..2c432f5c380 100644
--- a/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc
@@ -20,7 +20,6 @@
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/manifest.h"
-#include "extensions/common/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using extensions::file_system_api::ConsentProvider;
@@ -133,8 +132,8 @@ TEST_F(FileSystemApiConsentProviderTest, ForNonKioskApps) {
// Component apps are not granted unless they are whitelisted.
{
scoped_refptr<Extension> component_extension(
- test_util::BuildApp(
- std::move(ExtensionBuilder().SetLocation(Manifest::COMPONENT)))
+ ExtensionBuilder("Test", ExtensionBuilder::Type::PLATFORM_APP)
+ .SetLocation(Manifest::COMPONENT)
.Build());
TestingConsentProviderDelegate delegate;
ConsentProvider provider(&delegate);
@@ -145,8 +144,8 @@ TEST_F(FileSystemApiConsentProviderTest, ForNonKioskApps) {
// user.
{
scoped_refptr<Extension> whitelisted_component_extension(
- test_util::BuildApp(
- std::move(ExtensionBuilder().SetLocation(Manifest::COMPONENT)))
+ ExtensionBuilder("Test", ExtensionBuilder::Type::PLATFORM_APP)
+ .SetLocation(Manifest::COMPONENT)
.Build());
TestingConsentProviderDelegate delegate;
delegate.SetComponentWhitelist(whitelisted_component_extension->id());
@@ -168,7 +167,7 @@ TEST_F(FileSystemApiConsentProviderTest, ForNonKioskApps) {
// asking for user consent.
{
scoped_refptr<Extension> non_component_extension(
- test_util::CreateEmptyExtension());
+ ExtensionBuilder("Test").Build());
TestingConsentProviderDelegate delegate;
ConsentProvider provider(&delegate);
EXPECT_FALSE(provider.IsGrantable(*non_component_extension));
@@ -180,7 +179,7 @@ TEST_F(FileSystemApiConsentProviderTest, ForKioskApps) {
// instantly without asking for user consent, but with a notification.
{
scoped_refptr<Extension> auto_launch_kiosk_app(
- test_util::BuildApp(ExtensionBuilder())
+ ExtensionBuilder("Test", ExtensionBuilder::Type::PLATFORM_APP)
.MergeManifest(DictionaryBuilder()
.SetBoolean("kiosk_enabled", true)
.SetBoolean("kiosk_only", true)
@@ -210,7 +209,7 @@ TEST_F(FileSystemApiConsentProviderTest, ForKioskApps) {
// Non-component apps in manual-launch kiosk mode will be granted access after
// receiving approval from the user.
scoped_refptr<Extension> manual_launch_kiosk_app(
- test_util::BuildApp(ExtensionBuilder())
+ ExtensionBuilder("Test", ExtensionBuilder::Type::PLATFORM_APP)
.MergeManifest(DictionaryBuilder()
.SetBoolean("kiosk_enabled", true)
.SetBoolean("kiosk_only", true)
diff --git a/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.cc b/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.cc
index c1ab2746fd7..cd5b37650a4 100644
--- a/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.cc
+++ b/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.cc
@@ -33,7 +33,7 @@ FileEntryPicker::FileEntryPicker(
gfx::NativeWindow owning_window =
platform_util::GetTopLevel(web_contents->GetNativeView());
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, base::MakeUnique<ChromeSelectFilePolicy>(web_contents).release());
+ this, std::make_unique<ChromeSelectFilePolicy>(web_contents));
select_file_dialog_->SelectFile(
picker_type, base::string16(), suggested_name, &file_type_info, 0,
base::FilePath::StringType(), owning_window, nullptr);
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 103a946598e..cf7da48046e 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
@@ -152,8 +152,11 @@ class FileSystemApiTestForDrive : public PlatformAppBrowserTest {
drive::DriveIntegrationService* CreateDriveIntegrationService(
Profile* profile) {
// Ignore signin profile.
- if (profile->GetPath() == chromeos::ProfileHelper::GetSigninProfileDir())
+ if (profile->GetPath() == chromeos::ProfileHelper::GetSigninProfileDir() ||
+ profile->GetPath() ==
+ chromeos::ProfileHelper::GetLockScreenAppProfilePath()) {
return nullptr;
+ }
// FileSystemApiTestForDrive doesn't expect that several user profiles could
// exist simultaneously.
diff --git a/chromium/chrome/browser/extensions/api/history/history_apitest.cc b/chromium/chrome/browser/extensions/api/history/history_apitest.cc
index d50197e58a1..d05394636fa 100644
--- a/chromium/chrome/browser/extensions/api/history/history_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/history/history_apitest.cc
@@ -35,13 +35,7 @@ IN_PROC_BROWSER_TEST_F(HistoryApiTest, DISABLED_TimedSearch) {
ASSERT_TRUE(RunExtensionSubtest("history", "timed_search.html")) << message_;
}
-#if defined(OS_WIN)
-// Flaky on Windows: crbug.com/88318
-#define MAYBE_Delete DISABLED_Delete
-#else
-#define MAYBE_Delete Delete
-#endif
-IN_PROC_BROWSER_TEST_F(HistoryApiTest, MAYBE_Delete) {
+IN_PROC_BROWSER_TEST_F(HistoryApiTest, Delete) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("history", "delete.html")) << message_;
}
@@ -54,21 +48,12 @@ IN_PROC_BROWSER_TEST_F(HistoryApiTest, DeleteProhibited) {
message_;
}
-// See crbug.com/79074
-IN_PROC_BROWSER_TEST_F(HistoryApiTest, DISABLED_GetVisits) {
+IN_PROC_BROWSER_TEST_F(HistoryApiTest, GetVisits) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("history", "get_visits.html")) << message_;
}
-#if defined(OS_WIN)
-// Searching for a URL right after adding it fails on win XP.
-// Fix this as part of crbug/76170.
-#define MAYBE_SearchAfterAdd DISABLED_SearchAfterAdd
-#else
-#define MAYBE_SearchAfterAdd SearchAfterAdd
-#endif
-
-IN_PROC_BROWSER_TEST_F(HistoryApiTest, MAYBE_SearchAfterAdd) {
+IN_PROC_BROWSER_TEST_F(HistoryApiTest, SearchAfterAdd) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionSubtest("history", "search_after_add.html"))
<< message_;
diff --git a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc
index 501102604e7..05389bdd8bd 100644
--- a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc
@@ -30,7 +30,7 @@
#include "ui/base/webui/web_ui_util.h"
#if defined(OS_CHROMEOS)
-#include "ash/system/devicetype_utils.h"
+#include "ui/chromeos/devicetype_utils.h"
#endif
namespace extensions {
@@ -348,7 +348,7 @@ ExtensionFunction::ResponseAction HotwordPrivateStopTrainingFunction::Run() {
ExtensionFunction::ResponseAction
HotwordPrivateGetLocalizedStringsFunction::Run() {
#if defined(OS_CHROMEOS)
- base::string16 device_type = ash::GetChromeOSDeviceName();
+ base::string16 device_type = ui::GetChromeOSDeviceName();
#else
base::string16 product_name =
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME);
diff --git a/chromium/chrome/browser/extensions/api/identity/OWNERS b/chromium/chrome/browser/extensions/api/identity/OWNERS
index bc8f8b8796d..5e319b181d7 100644
--- a/chromium/chrome/browser/extensions/api/identity/OWNERS
+++ b/chromium/chrome/browser/extensions/api/identity/OWNERS
@@ -1 +1,4 @@
+msarda@chromium.org
+
+# Original author, very slow on reviews as no longer working on Chromium.
courage@chromium.org
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api.cc b/chromium/chrome/browser/extensions/api/identity/identity_api.cc
index ace8a51465f..48193405b88 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_api.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_api.cc
@@ -36,8 +36,6 @@
#include "components/signin/core/browser/account_tracker_service.h"
#include "components/signin/core/browser/profile_oauth2_token_service.h"
#include "components/signin/core/browser/signin_manager.h"
-#include "components/signin/core/common/profile_management_switches.h"
-#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_function_dispatcher.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_l10n_util.h"
@@ -184,9 +182,21 @@ void IdentityAPI::OnAccountSignInChanged(const gaia::AccountIds& ids,
api::identity::OnSignInChanged::kEventName, std::move(args),
browser_context_));
+ if (on_signin_changed_callback_for_testing_)
+ on_signin_changed_callback_for_testing_.Run(event.get());
+
EventRouter::Get(browser_context_)->BroadcastEvent(std::move(event));
}
+void IdentityAPI::SetAccountStateForTesting(const std::string& account_id,
+ bool signed_in) {
+ gaia::AccountIds ids;
+ ids.account_key = account_id;
+ ids.email = account_id;
+ ids.gaia = account_id;
+ account_tracker_.SetAccountStateForTest(ids, signed_in);
+}
+
template <>
void BrowserContextKeyedAPIFactory<IdentityAPI>::DeclareFactoryDependencies() {
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api.h b/chromium/chrome/browser/extensions/api/identity/identity_api.h
index 8050cb6c965..544ff271aaa 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_api.h
+++ b/chromium/chrome/browser/extensions/api/identity/identity_api.h
@@ -28,6 +28,7 @@
#include "chrome/browser/extensions/chrome_extension_function.h"
#include "components/signin/core/browser/profile_identity_provider.h"
#include "extensions/browser/browser_context_keyed_api_factory.h"
+#include "extensions/browser/event_router.h"
#include "google_apis/gaia/account_tracker.h"
#include "google_apis/gaia/oauth2_mint_token_flow.h"
#include "google_apis/gaia/oauth2_token_service.h"
@@ -105,6 +106,20 @@ class IdentityAPI : public BrowserContextKeyedAPI,
get_auth_token_function_ = get_auth_token_function;
}
+ // TODO(blundell): Eliminate this method once this class is no longer using
+ // AccountTracker.
+ // Makes |account_tracker_| aware of this account.
+ void SetAccountStateForTesting(const std::string& account_id, bool signed_in);
+
+ // Callback that is used in testing contexts to test the implementation of
+ // the chrome.identity.onSignInChanged event. Note that the passed-in Event is
+ // valid only for the duration of the callback.
+ using OnSignInChangedCallback = base::RepeatingCallback<void(Event*)>;
+ void set_on_signin_changed_callback_for_testing(
+ const OnSignInChangedCallback& callback) {
+ on_signin_changed_callback_for_testing_ = callback;
+ }
+
private:
friend class BrowserContextKeyedAPIFactory<IdentityAPI>;
@@ -118,6 +133,8 @@ class IdentityAPI : public BrowserContextKeyedAPI,
ProfileIdentityProvider profile_identity_provider_;
gaia::AccountTracker account_tracker_;
+ OnSignInChangedCallback on_signin_changed_callback_for_testing_;
+
// May be null.
IdentityGetAuthTokenFunction* get_auth_token_function_;
};
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
index 8b2e28e7f6b..07d9e82c4ab 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -61,8 +61,8 @@
#include "content/public/browser/notification_source.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/api_test_utils.h"
+#include "extensions/common/extension_builder.h"
#include "extensions/common/manifest_handlers/oauth2_manifest_handler.h"
-#include "extensions/common/test_util.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "google_apis/gaia/oauth2_mint_token_flow.h"
#include "google_apis/gaia/oauth2_token_service.h"
@@ -101,7 +101,7 @@ class AsyncExtensionBrowserTest : public ExtensionBrowserTest {
if (!function->extension()) {
scoped_refptr<Extension> empty_extension(
- test_util::CreateEmptyExtension());
+ ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
}
@@ -445,7 +445,8 @@ class IdentityTestWithSignin : public AsyncExtensionBrowserTest {
SignIn(account_key, account_key);
}
- void SignIn(const std::string& email, const std::string& gaia) {
+ // Returns the account ID of the created account.
+ std::string SignIn(const std::string& email, const std::string& gaia) {
AccountTrackerService* account_tracker =
AccountTrackerServiceFactory::GetForProfile(profile());
std::string account_id = account_tracker->SeedAccountInfo(gaia, email);
@@ -456,6 +457,8 @@ class IdentityTestWithSignin : public AsyncExtensionBrowserTest {
signin_manager_->SignIn(gaia, email, "password");
#endif
token_service_->UpdateCredentials(account_id, "refresh_token");
+
+ return account_id;
}
void AddAccount(const std::string& email, const std::string& gaia) {
@@ -490,7 +493,8 @@ class IdentityGetAccountsFunctionTest : public IdentityTestWithSignin {
const std::vector<std::string>& accounts) {
scoped_refptr<IdentityGetAccountsFunction> func(
new IdentityGetAccountsFunction);
- func->set_extension(test_util::CreateEmptyExtension(kExtensionId).get());
+ func->set_extension(
+ ExtensionBuilder("Test").SetID(kExtensionId).Build().get());
if (!utils::RunFunction(
func.get(), std::string("[]"), browser(), utils::NONE)) {
return GenerateFailureResult(accounts, NULL)
@@ -559,13 +563,25 @@ class IdentityGetAccountsFunctionTest : public IdentityTestWithSignin {
};
IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest, MultiAccountOn) {
- EXPECT_TRUE(switches::IsExtensionsMultiAccount());
+ EXPECT_TRUE(signin::IsExtensionsMultiAccount());
}
IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest, NoneSignedIn) {
EXPECT_TRUE(ExpectGetAccounts(std::vector<std::string>()));
}
+IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest, NoPrimaryAccount) {
+ AddAccount("secondary@example.com", "2");
+ EXPECT_TRUE(ExpectGetAccounts(std::vector<std::string>()));
+}
+
+IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest,
+ PrimaryAccountHasNoRefreshToken) {
+ std::string primary_account_id = SignIn("primary@example.com", "1");
+ token_service_->RevokeCredentials(primary_account_id);
+ EXPECT_TRUE(ExpectGetAccounts(std::vector<std::string>()));
+}
+
IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest,
PrimaryAccountSignedIn) {
SignIn("primary@example.com", "1");
@@ -593,7 +609,7 @@ class IdentityOldProfilesGetAccountsFunctionTest
IN_PROC_BROWSER_TEST_F(IdentityOldProfilesGetAccountsFunctionTest,
MultiAccountOff) {
- EXPECT_FALSE(switches::IsExtensionsMultiAccount());
+ EXPECT_FALSE(signin::IsExtensionsMultiAccount());
}
IN_PROC_BROWSER_TEST_F(IdentityOldProfilesGetAccountsFunctionTest,
@@ -610,7 +626,8 @@ class IdentityGetProfileUserInfoFunctionTest : public IdentityTestWithSignin {
std::unique_ptr<api::identity::ProfileUserInfo> RunGetProfileUserInfo() {
scoped_refptr<IdentityGetProfileUserInfoFunction> func(
new IdentityGetProfileUserInfoFunction);
- func->set_extension(test_util::CreateEmptyExtension(kExtensionId).get());
+ func->set_extension(
+ ExtensionBuilder("Test").SetID(kExtensionId).Build().get());
std::unique_ptr<base::Value> value(
utils::RunFunctionAndReturnSingleResult(func.get(), "[]", browser()));
return api::identity::ProfileUserInfo::FromValue(*value);
@@ -1819,7 +1836,8 @@ class RemoveCachedAuthTokenFunctionTest : public ExtensionBrowserTest {
bool InvalidateDefaultToken() {
scoped_refptr<IdentityRemoveCachedAuthTokenFunction> func(
new IdentityRemoveCachedAuthTokenFunction);
- func->set_extension(test_util::CreateEmptyExtension(kExtensionId).get());
+ func->set_extension(
+ ExtensionBuilder("Test").SetID(kExtensionId).Build().get());
return utils::RunFunction(
func.get(),
std::string("[{\"token\": \"") + kAccessToken + "\"}]",
@@ -1897,7 +1915,7 @@ IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, UserCloseWindow) {
scoped_refptr<IdentityLaunchWebAuthFlowFunction> function(
new IdentityLaunchWebAuthFlowFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
WaitForGURLAndCloseWindow popup_observer(auth_url);
@@ -1921,7 +1939,7 @@ IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, InteractionRequired) {
scoped_refptr<IdentityLaunchWebAuthFlowFunction> function(
new IdentityLaunchWebAuthFlowFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
std::string args = "[{\"interactive\": false, \"url\": \"" +
@@ -1941,7 +1959,7 @@ IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, LoadFailed) {
scoped_refptr<IdentityLaunchWebAuthFlowFunction> function(
new IdentityLaunchWebAuthFlowFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
std::string args = "[{\"interactive\": true, \"url\": \"" +
@@ -1955,7 +1973,7 @@ IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, LoadFailed) {
IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, NonInteractiveSuccess) {
scoped_refptr<IdentityLaunchWebAuthFlowFunction> function(
new IdentityLaunchWebAuthFlowFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
function->InitFinalRedirectURLPrefixForTest("abcdefghij");
@@ -1975,7 +1993,7 @@ IN_PROC_BROWSER_TEST_F(
LaunchWebAuthFlowFunctionTest, InteractiveFirstNavigationSuccess) {
scoped_refptr<IdentityLaunchWebAuthFlowFunction> function(
new IdentityLaunchWebAuthFlowFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
function->InitFinalRedirectURLPrefixForTest("abcdefghij");
@@ -2001,7 +2019,7 @@ IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest,
scoped_refptr<IdentityLaunchWebAuthFlowFunction> function(
new IdentityLaunchWebAuthFlowFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
function->set_extension(empty_extension.get());
function->InitFinalRedirectURLPrefixForTest("abcdefghij");
@@ -2016,6 +2034,185 @@ IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest,
url);
}
+class OnSignInChangedEventTest : public IdentityTestWithSignin {
+ protected:
+ void SetUpOnMainThread() override {
+ // TODO(blundell): Ideally we would test fully end-to-end by injecting a
+ // JavaScript extension listener and having that listener do the
+ // verification, but it's not clear how to set that up.
+ id_api()->set_on_signin_changed_callback_for_testing(
+ base::Bind(&OnSignInChangedEventTest::OnSignInEventChanged,
+ base::Unretained(this)));
+ IdentityTestWithSignin::SetUpOnMainThread();
+ }
+
+ IdentityAPI* id_api() {
+ return IdentityAPI::GetFactoryInstance()->Get(browser()->profile());
+ }
+
+ // Adds an event that is expected to fire. Events are checked in the order of
+ // addition, i.e., the first event added is expected to be the first event to
+ // fire.
+ void AddExpectedEvent(std::unique_ptr<base::ListValue> args) {
+ expected_events_.push_back(
+ base::MakeUnique<Event>(events::IDENTITY_ON_SIGN_IN_CHANGED,
+ api::identity::OnSignInChanged::kEventName,
+ std::move(args), browser()->profile()));
+ }
+
+ bool HasExpectedEvent() { return expected_events_.size(); }
+
+ private:
+ void OnSignInEventChanged(Event* event) {
+ if (!HasExpectedEvent())
+ return;
+
+ // Check that |event| matches the first event expected to fire.
+ const auto& expected_event = expected_events_[0];
+ EXPECT_EQ(expected_event->histogram_value, event->histogram_value);
+ EXPECT_EQ(expected_event->event_name, event->event_name);
+ EXPECT_EQ(*(expected_event->event_args.get()), *(event->event_args.get()));
+
+ // Erase that first element whether it matched or not, since it's no longer
+ // expected.
+ expected_events_.erase(expected_events_.begin());
+ }
+
+ std::vector<std::unique_ptr<Event>> expected_events_;
+};
+
+// Test that an event is fired when the primary account signs in.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, FireOnPrimaryAccountSignIn) {
+ id_api()->SetAccountStateForTesting("primary", false);
+
+ api::identity::AccountInfo account_info;
+ account_info.id = "primary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
+
+ // Sign in and verify that the callback fires.
+ SignIn("primary", "primary");
+
+ EXPECT_FALSE(HasExpectedEvent());
+}
+
+#if !defined(OS_CHROMEOS)
+// Test that an event is fired when the primary account signs out.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, FireOnPrimaryAccountSignOut) {
+ id_api()->SetAccountStateForTesting("primary", true);
+
+ api::identity::AccountInfo account_info;
+ account_info.id = "primary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
+
+ // Sign out and verify that the callback fires.
+ signin_manager_->ForceSignOut();
+
+ EXPECT_FALSE(HasExpectedEvent());
+}
+#endif // !defined(OS_CHROMEOS)
+
+// Test that an event is fired when the primary account has a refresh token
+// revoked.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
+ FireOnPrimaryAccountRefreshTokenRevoked) {
+ id_api()->SetAccountStateForTesting("primary", true);
+
+ api::identity::AccountInfo account_info;
+ account_info.id = "primary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
+
+ // Revoke the refresh token and verify that the callback fires.
+ token_service_->RevokeCredentials("primary");
+
+ EXPECT_FALSE(HasExpectedEvent());
+}
+
+// Test that an event is fired when the primary account has a refresh token
+// newly available.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
+ FireOnPrimaryAccountRefreshTokenAvailable) {
+ id_api()->SetAccountStateForTesting("primary", false);
+
+ SignIn("primary", "primary");
+ token_service_->RevokeCredentials("primary");
+
+ api::identity::AccountInfo account_info;
+ account_info.id = "primary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
+
+ // Make the primary account's refresh token available and check that the
+ // callback fires.
+ token_service_->UpdateCredentials("primary", "refresh_token");
+ EXPECT_FALSE(HasExpectedEvent());
+}
+
+// Test that an event is fired for changes to a secondary account when there is
+// a primary account available.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
+ FireForSecondaryAccountWhenPrimaryAccountExists) {
+ id_api()->SetAccountStateForTesting("primary", false);
+ id_api()->SetAccountStateForTesting("secondary", false);
+
+ SignIn("primary", "primary");
+
+ api::identity::AccountInfo account_info;
+ account_info.id = "secondary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
+
+ // Make a secondary account's refresh token available and check that the
+ // callback fires.
+ token_service_->UpdateCredentials("secondary", "refresh_token");
+ EXPECT_FALSE(HasExpectedEvent());
+
+ // Revoke the secondary account's refresh token and check that the callback
+ // fires.
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
+
+ token_service_->RevokeCredentials("secondary");
+ EXPECT_FALSE(HasExpectedEvent());
+}
+
+// Test that an event is not fired for changes to a secondary account when
+// there is no primary account available.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
+ DontFireForSecondaryAccountWhenNoPrimaryAccountExists) {
+ // Add an expected event to be able to verify that no event is fired.
+ api::identity::AccountInfo account_info;
+ account_info.id = "secondary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
+
+ // Check not firing on addition of secondary account.
+ AddAccount("secondary", "secondary");
+ EXPECT_TRUE(HasExpectedEvent());
+
+ // Check not firing on token revocation of secondary account.
+ token_service_->RevokeCredentials("primary");
+ EXPECT_TRUE(HasExpectedEvent());
+}
+
+#if !defined(OS_CHROMEOS)
+// Test that signout events are fired for all known accounts when the primary
+// account signs out, firing first for the primary account and then for any
+// secondary accounts.
+IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
+ FireForAllAccountsOnPrimaryAccountSignOut) {
+ id_api()->SetAccountStateForTesting("primary", true);
+ id_api()->SetAccountStateForTesting("secondary", true);
+
+ api::identity::AccountInfo account_info;
+ account_info.id = "primary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
+
+ account_info.id = "secondary";
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
+
+ // Sign out and verify that both events fire.
+ signin_manager_->ForceSignOut();
+
+ EXPECT_FALSE(HasExpectedEvent());
+}
+#endif // !defined(OS_CHROMEOS)
+
} // namespace extensions
// Tests the chrome.identity API implemented by custom JS bindings .
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
index 3b1213187a4..e9cf6e09a40 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
@@ -7,14 +7,12 @@
#include "chrome/browser/extensions/api/identity/identity_api.h"
#include "chrome/browser/extensions/api/identity/identity_constants.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/signin/account_tracker_service_factory.h"
-#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/extensions/api/identity.h"
-#include "components/signin/core/browser/account_tracker_service.h"
-#include "components/signin/core/browser/profile_oauth2_token_service.h"
-#include "components/signin/core/browser/signin_manager.h"
#include "components/signin/core/common/profile_management_switches.h"
+#include "content/public/common/service_manager_connection.h"
+#include "services/identity/public/interfaces/account.mojom.h"
+#include "services/identity/public/interfaces/constants.mojom.h"
+#include "services/service_manager/public/cpp/connector.h"
namespace extensions {
@@ -29,48 +27,39 @@ ExtensionFunction::ResponseAction IdentityGetAccountsFunction::Run() {
return RespondNow(Error(identity_constants::kOffTheRecord));
}
- ProfileOAuth2TokenService* token_service =
- ProfileOAuth2TokenServiceFactory::GetForProfile(GetProfile());
- AccountTrackerService* account_tracker =
- AccountTrackerServiceFactory::GetForProfile(GetProfile());
+ content::BrowserContext::GetConnectorFor(GetProfile())
+ ->BindInterface(identity::mojom::kServiceName,
+ mojo::MakeRequest(&identity_manager_));
- std::unique_ptr<base::ListValue> infos(new base::ListValue());
- std::string primary_account =
- SigninManagerFactory::GetForProfile(GetProfile())
- ->GetAuthenticatedAccountId();
-
- // If there is no primary account, short-circuit out.
- if (primary_account.empty() ||
- !token_service->RefreshTokenIsAvailable(primary_account))
- return RespondNow(OneArgument(std::move(infos)));
+ identity_manager_->GetAccounts(
+ base::Bind(&IdentityGetAccountsFunction::OnGotAccounts, this));
- // Set the primary account as the first entry.
- std::string primary_gaia_id =
- account_tracker->GetAccountInfo(primary_account).gaia;
- api::identity::AccountInfo primary_account_info;
- primary_account_info.id = primary_gaia_id;
- infos->Append(primary_account_info.ToValue());
+ return RespondLater();
+}
- // If extensions are not multi-account, ignore any other accounts.
- if (!switches::IsExtensionsMultiAccount())
- return RespondNow(OneArgument(std::move(infos)));
+void IdentityGetAccountsFunction::OnGotAccounts(
+ std::vector<identity::mojom::AccountPtr> accounts) {
+ std::unique_ptr<base::ListValue> infos(new base::ListValue());
- // Otherwise, add the other accounts.
- std::vector<std::string> accounts = token_service->GetAccounts();
- for (std::vector<std::string>::const_iterator it = accounts.begin();
- it != accounts.end(); ++it) {
- std::string gaia_id = account_tracker->GetAccountInfo(*it).gaia;
- if (gaia_id.empty())
- continue;
- if (gaia_id == primary_gaia_id)
- continue;
+ // If there is no primary account or the primary account has no refresh token
+ // available, short-circuit out.
+ if (accounts.empty() || !accounts[0]->state.is_primary_account ||
+ !accounts[0]->state.has_refresh_token) {
+ Respond(OneArgument(std::move(infos)));
+ return;
+ }
+ for (const auto& account : accounts) {
api::identity::AccountInfo account_info;
- account_info.id = gaia_id;
+ account_info.id = account->info.gaia;
infos->Append(account_info.ToValue());
+
+ // Stop after the primary account if extensions are not multi-account.
+ if (!signin::IsExtensionsMultiAccount())
+ break;
}
- return RespondNow(OneArgument(std::move(infos)));
+ Respond(OneArgument(std::move(infos)));
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h
index 2b597795798..76c33885f8d 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h
@@ -7,6 +7,7 @@
#include "chrome/browser/extensions/chrome_extension_function.h"
#include "extensions/browser/extension_function_histogram_value.h"
+#include "services/identity/public/interfaces/identity_manager.mojom.h"
namespace extensions {
@@ -20,8 +21,13 @@ class IdentityGetAccountsFunction : public ChromeUIThreadExtensionFunction {
private:
~IdentityGetAccountsFunction() override;
+ // Invoked in response to IdentityManager::GetAccounts().
+ void OnGotAccounts(std::vector<identity::mojom::AccountPtr> accounts);
+
// UIThreadExtensionFunction implementation.
ExtensionFunction::ResponseAction Run() override;
+
+ identity::mojom::IdentityManagerPtr identity_manager_;
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
index 640eb7038b1..32acfe362fd 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
@@ -4,6 +4,11 @@
#include "chrome/browser/extensions/api/identity/identity_get_auth_token_function.h"
+#include <memory>
+#include <set>
+#include <string>
+#include <vector>
+
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
@@ -141,7 +146,7 @@ void IdentityGetAuthTokenFunction::OnReceivedPrimaryAccountInfo(
// Detect and handle the case where the extension is using an account other
// than the primary account.
if (!extension_gaia_id.empty() && extension_gaia_id != primary_gaia_id) {
- if (!switches::IsExtensionsMultiAccount()) {
+ if (!signin::IsExtensionsMultiAccount()) {
// TODO(courage): should this be a different error?
CompleteFunctionWithError(identity_constants::kUserNotSignedIn);
return;
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc
index 6e62c6e6b94..b28d8c9221e 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc
@@ -27,6 +27,7 @@ DestroyPartitionsOperation::DestroyPartitionsOperation(
DestroyPartitionsOperation::~DestroyPartitionsOperation() {}
void DestroyPartitionsOperation::StartImpl() {
+ DCHECK(IsRunningInCorrectSequence());
if (!base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_path_)) {
Error(error::kTempFileError);
return;
@@ -41,8 +42,7 @@ void DestroyPartitionsOperation::StartImpl() {
return;
}
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
+ PostTask(
base::BindOnce(&DestroyPartitionsOperation::Write, this,
base::Bind(&DestroyPartitionsOperation::Finish, this)));
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc
index 491ff820f74..5bc4932bbdd 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc
@@ -24,6 +24,20 @@ TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) {
TestingProfile profile;
MockOperationManager manager(&profile);
+#if !defined(OS_CHROMEOS)
+ auto set_up_utility_client_progress_simulation =
+ [](FakeImageWriterClient* client) {
+ std::vector<int> progress_list{0, 50, 100};
+ bool will_succeed = true;
+ client->SimulateProgressOnWrite(progress_list, will_succeed);
+ client->SimulateProgressOnVerifyWrite(progress_list, will_succeed);
+ };
+ // Sets up client for simulating Operation::Progress() on Operation::Write and
+ // Operation::VerifyWrite.
+ test_utils_.RunOnUtilityClientCreation(
+ base::BindOnce(set_up_utility_client_progress_simulation));
+#endif
+
scoped_refptr<DestroyPartitionsOperation> operation(
new DestroyPartitionsOperation(
manager.AsWeakPtr(),
@@ -47,18 +61,8 @@ TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) {
EXPECT_CALL(manager, OnComplete(kDummyExtensionId)).Times(1);
EXPECT_CALL(manager, OnError(kDummyExtensionId, _, _, _)).Times(0);
- operation->Start();
-
- base::RunLoop().RunUntilIdle();
-
-#if !defined(OS_CHROMEOS)
- test_utils_.GetUtilityClient()->Progress(0);
- test_utils_.GetUtilityClient()->Progress(50);
- test_utils_.GetUtilityClient()->Progress(100);
- test_utils_.GetUtilityClient()->Success();
-
- base::RunLoop().RunUntilIdle();
-#endif
+ operation->PostTask(base::Bind(&Operation::Start, operation));
+ content::RunAllBlockingPoolTasksUntilIdle();
}
} // namespace
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc
index 14aef77a27e..19cfdbeae72 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc
@@ -167,16 +167,15 @@ ImageWriterPrivateListRemovableStorageDevicesFunction::
}
bool ImageWriterPrivateListRemovableStorageDevicesFunction::RunAsync() {
- RemovableStorageProvider::GetAllDevices(
- base::Bind(
+ RemovableStorageProvider::GetAllDevices(base::BindOnce(
&ImageWriterPrivateListRemovableStorageDevicesFunction::OnDeviceListReady,
this));
return true;
}
void ImageWriterPrivateListRemovableStorageDevicesFunction::OnDeviceListReady(
- scoped_refptr<StorageDeviceList> device_list,
- bool success) {
+ scoped_refptr<StorageDeviceList> device_list) {
+ const bool success = device_list.get() != nullptr;
if (success) {
results_ = image_writer_api::ListRemovableStorageDevices::Results::Create(
device_list->data);
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h
index a7abf444f33..68b17d7ac7c 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h
@@ -72,8 +72,7 @@ class ImageWriterPrivateListRemovableStorageDevicesFunction
private:
~ImageWriterPrivateListRemovableStorageDevicesFunction() override;
bool RunAsync() override;
- void OnDeviceListReady(scoped_refptr<StorageDeviceList> device_list,
- bool success);
+ void OnDeviceListReady(scoped_refptr<StorageDeviceList> device_list);
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc
index 6031be47ed7..2c4dc2e4cf4 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc
@@ -67,26 +67,6 @@ class ImageWriterPrivateApiTest : public ExtensionApiTest {
FileSystemChooseEntryFunction::StopSkippingPickerForTest();
}
-#if !defined(OS_CHROMEOS)
- void ImageWriterUtilityClientCall() {
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&FakeImageWriterClient::Progress,
- test_utils_.GetUtilityClient(), 0));
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&FakeImageWriterClient::Progress,
- test_utils_.GetUtilityClient(), 50));
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&FakeImageWriterClient::Progress,
- test_utils_.GetUtilityClient(), 100));
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&FakeImageWriterClient::Success,
- test_utils_.GetUtilityClient()));
- }
-#endif
protected:
base::MessageLoopForUI message_loop_;
@@ -107,12 +87,16 @@ IN_PROC_BROWSER_TEST_F(ImageWriterPrivateApiTest, TestWriteFromFile) {
&selected_image);
#if !defined(OS_CHROMEOS)
- test_utils_.GetUtilityClient()->SetWriteCallback(base::Bind(
- &ImageWriterPrivateApiTest::ImageWriterUtilityClientCall,
- base::Unretained(this)));
- test_utils_.GetUtilityClient()->SetVerifyCallback(base::Bind(
- &ImageWriterPrivateApiTest::ImageWriterUtilityClientCall,
- base::Unretained(this)));
+ auto set_up_utility_client_callbacks = [](FakeImageWriterClient* client) {
+ std::vector<int> progress_list{0, 50, 100};
+ client->SimulateProgressOnWrite(progress_list, true);
+ client->SimulateProgressOnVerifyWrite(progress_list, true);
+ };
+
+ // Sets up client for simulating Operation::Progress() on Operation::Write and
+ // Operation::VerifyWrite.
+ test_utils_.RunOnUtilityClientCreation(
+ base::BindOnce(set_up_utility_client_callbacks));
#endif
ASSERT_TRUE(RunPlatformAppTest("image_writer_private/write_from_file"))
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc
index 3ad3e5d116a..295ade130f3 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc
@@ -9,8 +9,7 @@
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/optional.h"
-#include "base/single_thread_task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
+#include "base/threading/thread_restrictions.h"
#include "chrome/common/extensions/removable_storage_writer.mojom.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/browser_thread.h"
@@ -18,6 +17,14 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "ui/base/l10n/l10n_util.h"
+namespace extensions {
+namespace image_writer {
+
+namespace {
+ImageWriterUtilityClient::ImageWriterUtilityClientFactory*
+ g_factory_for_testing = nullptr;
+} // namespace
+
class ImageWriterUtilityClient::RemovableStorageWriterClientImpl
: public extensions::mojom::RemovableStorageWriterClient {
public:
@@ -26,7 +33,7 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl
extensions::mojom::RemovableStorageWriterClientPtr* interface)
: binding_(this, mojo::MakeRequest(interface)),
image_writer_utility_client_(owner) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ base::ThreadRestrictions::AssertIOAllowed();
binding_.set_connection_error_handler(
base::BindOnce(&ImageWriterUtilityClient::UtilityProcessError,
@@ -59,12 +66,25 @@ ImageWriterUtilityClient::ImageWriterUtilityClient() = default;
ImageWriterUtilityClient::~ImageWriterUtilityClient() = default;
+// static
+scoped_refptr<ImageWriterUtilityClient> ImageWriterUtilityClient::Create() {
+ if (g_factory_for_testing)
+ return g_factory_for_testing->Run();
+ return make_scoped_refptr(new ImageWriterUtilityClient());
+}
+
+// static
+void ImageWriterUtilityClient::SetFactoryForTesting(
+ ImageWriterUtilityClientFactory* factory) {
+ g_factory_for_testing = factory;
+}
+
void ImageWriterUtilityClient::Write(const ProgressCallback& progress_callback,
const SuccessCallback& success_callback,
const ErrorCallback& error_callback,
const base::FilePath& source,
const base::FilePath& target) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!removable_storage_writer_client_);
progress_callback_ = progress_callback;
@@ -86,7 +106,7 @@ void ImageWriterUtilityClient::Verify(const ProgressCallback& progress_callback,
const ErrorCallback& error_callback,
const base::FilePath& source,
const base::FilePath& target) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!removable_storage_writer_client_);
progress_callback_ = progress_callback;
@@ -104,22 +124,22 @@ void ImageWriterUtilityClient::Verify(const ProgressCallback& progress_callback,
}
void ImageWriterUtilityClient::Cancel(const CancelCallback& cancel_callback) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(cancel_callback);
ResetRequest();
- base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, cancel_callback);
+ base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, cancel_callback);
}
void ImageWriterUtilityClient::Shutdown() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ResetRequest();
utility_process_mojo_client_.reset();
}
void ImageWriterUtilityClient::StartUtilityProcessIfNeeded() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (utility_process_mojo_client_)
return;
@@ -140,7 +160,7 @@ void ImageWriterUtilityClient::StartUtilityProcessIfNeeded() {
}
void ImageWriterUtilityClient::UtilityProcessError() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
OperationFailed("Utility process crashed or failed.");
utility_process_mojo_client_.reset();
@@ -173,3 +193,6 @@ void ImageWriterUtilityClient::ResetRequest() {
success_callback_.Reset();
error_callback_.Reset();
}
+
+} // namespace image_writer
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h
index 0df6304205c..183c07357d6 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h
@@ -11,10 +11,13 @@
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
-#include "base/single_thread_task_runner.h"
+#include "base/sequence_checker.h"
#include "chrome/common/extensions/removable_storage_writer.mojom.h"
#include "content/public/browser/utility_process_mojo_client.h"
+namespace extensions {
+namespace image_writer {
+
// Writes a disk image to a device inside the utility process. This
// class lives on the FILE thread.
class ImageWriterUtilityClient
@@ -24,8 +27,12 @@ class ImageWriterUtilityClient
typedef base::Callback<void()> SuccessCallback;
typedef base::Callback<void(int64_t)> ProgressCallback;
typedef base::Callback<void(const std::string&)> ErrorCallback;
+ using ImageWriterUtilityClientFactory =
+ base::Callback<scoped_refptr<ImageWriterUtilityClient>()>;
- ImageWriterUtilityClient();
+ static scoped_refptr<ImageWriterUtilityClient> Create();
+
+ static void SetFactoryForTesting(ImageWriterUtilityClientFactory* factory);
// Starts the write operation.
// |progress_callback|: Called periodically with the count of bytes processed.
@@ -61,7 +68,9 @@ class ImageWriterUtilityClient
protected:
friend class base::RefCountedThreadSafe<ImageWriterUtilityClient>;
+ friend class ImageWriterUtilityClientTest;
+ ImageWriterUtilityClient();
virtual ~ImageWriterUtilityClient();
private:
@@ -87,7 +96,12 @@ class ImageWriterUtilityClient
std::unique_ptr<RemovableStorageWriterClientImpl>
removable_storage_writer_client_;
+ SEQUENCE_CHECKER(sequence_checker_);
+
DISALLOW_COPY_AND_ASSIGN(ImageWriterUtilityClient);
};
+} // namespace image_writer
+} // namespace extensions
+
#endif // CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_IMAGE_WRITER_UTILITY_CLIENT_H_
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 b81800d5ecb..dc42c2d9e7f 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
@@ -11,13 +11,20 @@
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/run_loop.h"
+#include "base/sequenced_task_runner.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_restrictions.h"
+#include "chrome/browser/extensions/api/image_writer_private/operation.h"
#include "chrome/common/extensions/removable_storage_writer.mojom.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/browser_thread.h"
+namespace extensions {
+namespace image_writer {
+
+namespace {
constexpr int64_t kTestFileSize = 1 << 15; // 32 kB
+} // namespace
class ImageWriterUtilityClientTest : public InProcessBrowserTest {
public:
@@ -62,10 +69,9 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
verify_ = (option == VERIFY);
cancel_ = (option == CANCEL);
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::Bind(&ImageWriterUtilityClientTest::StartWriteTest,
- base::Unretained(this)));
+ CreateTaskRunner()->PostTask(
+ FROM_HERE, base::Bind(&ImageWriterUtilityClientTest::StartWriteTest,
+ base::Unretained(this)));
run_loop.Run();
EXPECT_TRUE(quit_called_);
@@ -77,11 +83,10 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
ASSERT_NE(option, WRITE); // Verify tests do not WRITE.
cancel_ = (option == CANCEL);
-
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::Bind(&ImageWriterUtilityClientTest::StartVerifyTest,
- base::Unretained(this)));
+ CreateTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&ImageWriterUtilityClientTest::StartVerifyTest,
+ base::Unretained(this)));
run_loop.Run();
EXPECT_TRUE(quit_called_);
@@ -93,7 +98,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
private:
void StartWriteTest() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (!image_writer_utility_client_)
image_writer_utility_client_ = new ImageWriterUtilityClient();
@@ -111,7 +116,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
}
void Progress(int64_t progress) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
progress_ = progress;
if (!cancel_)
@@ -122,7 +127,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
}
void Success() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
EXPECT_EQ(kTestFileSize, progress_);
EXPECT_FALSE(cancel_);
@@ -133,14 +138,13 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
return;
}
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::Bind(&ImageWriterUtilityClientTest::Shutdown,
- base::Unretained(this)));
+ GetTaskRunner()->PostTask(
+ FROM_HERE, base::Bind(&ImageWriterUtilityClientTest::Shutdown,
+ base::Unretained(this)));
}
void StartVerifyTest() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (!image_writer_utility_client_)
image_writer_utility_client_ = new ImageWriterUtilityClient();
@@ -158,33 +162,31 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
}
void Failure(const std::string& error) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
EXPECT_FALSE(error.empty());
success_ = false;
error_ = error;
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::Bind(&ImageWriterUtilityClientTest::Shutdown,
- base::Unretained(this)));
+ GetTaskRunner()->PostTask(
+ FROM_HERE, base::Bind(&ImageWriterUtilityClientTest::Shutdown,
+ base::Unretained(this)));
}
void Verified() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
EXPECT_EQ(kTestFileSize, progress_);
EXPECT_FALSE(cancel_);
success_ = !cancel_;
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::Bind(&ImageWriterUtilityClientTest::Shutdown,
- base::Unretained(this)));
+ GetTaskRunner()->PostTask(
+ FROM_HERE, base::Bind(&ImageWriterUtilityClientTest::Shutdown,
+ base::Unretained(this)));
}
void Cancelled() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
EXPECT_TRUE(cancel_);
success_ = cancel_;
@@ -195,7 +197,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
}
void Shutdown() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
image_writer_utility_client_->Shutdown();
@@ -209,6 +211,24 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
EXPECT_TRUE(base::WriteFile(path, fill.data(), kTestFileSize));
}
+ base::SequencedTaskRunner* CreateTaskRunner() {
+ DCHECK(!task_runner_.get());
+ task_runner_ = base::CreateSequencedTaskRunnerWithTraits(
+ Operation::blocking_task_traits());
+ return task_runner_.get();
+ }
+
+ base::SequencedTaskRunner* GetTaskRunner() {
+ DCHECK(task_runner_.get())
+ << "Called GetTaskRunner before creating TaskRunner.";
+ return task_runner_.get();
+ }
+
+ bool IsRunningInCorrectSequence() const {
+ base::ThreadRestrictions::AssertIOAllowed();
+ return task_runner_->RunsTasksInCurrentSequence();
+ }
+
base::ScopedTempDir temp_dir_;
base::FilePath test_device_;
base::FilePath device_;
@@ -217,12 +237,14 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
base::Closure quit_closure_;
bool quit_called_ = false;
+ // Lives on |task_runner_|.
scoped_refptr<ImageWriterUtilityClient> image_writer_utility_client_;
int64_t progress_ = 0;
bool success_ = false;
bool verify_ = false;
bool cancel_ = false;
std::string error_;
+ scoped_refptr<base::SequencedTaskRunner> task_runner_;
DISALLOW_COPY_AND_ASSIGN(ImageWriterUtilityClientTest);
};
@@ -318,3 +340,6 @@ IN_PROC_BROWSER_TEST_F(ImageWriterUtilityClientTest, VerifyCancel) {
EXPECT_TRUE(success());
EXPECT_TRUE(error().empty());
}
+
+} // namespace image_writer
+} // namespace extensions
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 e1a0dc19278..0fedb395491 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc
@@ -8,24 +8,23 @@
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
+#include "base/task_scheduler/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
#include "chrome/browser/extensions/api/image_writer_private/operation_manager.h"
+#include "chrome/browser/extensions/api/image_writer_private/unzip_helper.h"
#include "content/public/browser/browser_thread.h"
-#include "third_party/zlib/google/zip_reader.h"
namespace extensions {
namespace image_writer {
using content::BrowserThread;
+namespace {
+
const int kMD5BufferSize = 1024;
-#if !defined(OS_CHROMEOS)
-static base::LazyInstance<scoped_refptr<ImageWriterUtilityClient>>::
- DestructorAtExit g_utility_client = LAZY_INSTANCE_INITIALIZER;
-#endif
+} // namespace
Operation::Operation(base::WeakPtr<OperationManager> manager,
const ExtensionId& extension_id,
@@ -40,14 +39,15 @@ Operation::Operation(base::WeakPtr<OperationManager> manager,
#endif
stage_(image_writer_api::STAGE_UNKNOWN),
progress_(0),
- zip_reader_(new zip::ZipReader),
- download_folder_(download_folder) {
+ download_folder_(download_folder),
+ task_runner_(
+ base::CreateSequencedTaskRunnerWithTraits(blocking_task_traits())) {
}
Operation::~Operation() {}
void Operation::Cancel() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
stage_ = image_writer_api::STAGE_NONE;
@@ -55,6 +55,7 @@ void Operation::Cancel() {
}
void Operation::Abort() {
+ DCHECK(IsRunningInCorrectSequence());
Error(error::kAborted);
}
@@ -66,15 +67,12 @@ image_writer_api::Stage Operation::GetStage() {
return stage_;
}
-#if !defined(OS_CHROMEOS)
-// static
-void Operation::SetUtilityClientForTesting(
- scoped_refptr<ImageWriterUtilityClient> client) {
- g_utility_client.Get() = client;
+void Operation::PostTask(base::OnceClosure task) {
+ task_runner_->PostTask(FROM_HERE, std::move(task));
}
-#endif
void Operation::Start() {
+ DCHECK(IsRunningInCorrectSequence());
#if defined(OS_CHROMEOS)
if (download_folder_.empty() ||
!temp_dir_.CreateUniqueTempDirUnderPath(download_folder_)) {
@@ -86,62 +84,40 @@ void Operation::Start() {
}
AddCleanUpFunction(
- base::Bind(base::IgnoreResult(&base::ScopedTempDir::Delete),
- base::Unretained(&temp_dir_)));
+ base::BindOnce(base::IgnoreResult(&base::ScopedTempDir::Delete),
+ base::Unretained(&temp_dir_)));
StartImpl();
}
+void Operation::OnUnzipOpenComplete(const base::FilePath& image_path) {
+ DCHECK(IsRunningInCorrectSequence());
+ image_path_ = image_path;
+}
+
void Operation::Unzip(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
if (image_path_.Extension() != FILE_PATH_LITERAL(".zip")) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
+ PostTask(continuation);
return;
}
SetStage(image_writer_api::STAGE_UNZIP);
- if (!(zip_reader_->Open(image_path_) && zip_reader_->AdvanceToNextEntry() &&
- zip_reader_->OpenCurrentEntryInZip())) {
- Error(error::kUnzipGenericError);
- return;
- }
-
- if (zip_reader_->HasMore()) {
- Error(error::kUnzipInvalidArchive);
- return;
- }
-
- // Create a new target to unzip to. The original file is opened by the
- // zip_reader_.
- zip::ZipReader::EntryInfo* entry_info = zip_reader_->current_entry_info();
- if (entry_info) {
- image_path_ =
- temp_dir_.GetPath().Append(entry_info->file_path().BaseName());
- } else {
- Error(error::kTempDirError);
- return;
- }
-
- zip_reader_->ExtractCurrentEntryToFilePathAsync(
- image_path_,
+ auto unzip_helper = make_scoped_refptr(new UnzipHelper(
+ task_runner(), base::Bind(&Operation::OnUnzipOpenComplete, this),
base::Bind(&Operation::CompleteAndContinue, this, continuation),
base::Bind(&Operation::OnUnzipFailure, this),
- base::Bind(&Operation::OnUnzipProgress,
- this,
- zip_reader_->current_entry_info()->original_size()));
+ base::Bind(&Operation::OnUnzipProgress, this)));
+ unzip_helper->Unzip(image_path_, temp_dir_.GetPath());
}
void Operation::Finish() {
- if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::Finish, this));
- return;
- }
+ DCHECK(IsRunningInCorrectSequence());
CleanUp();
@@ -151,12 +127,7 @@ void Operation::Finish() {
}
void Operation::Error(const std::string& error_message) {
- if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::Error, this, error_message));
- return;
- }
+ DCHECK(IsRunningInCorrectSequence());
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
@@ -167,12 +138,7 @@ void Operation::Error(const std::string& error_message) {
}
void Operation::SetProgress(int progress) {
- if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::SetProgress, this, progress));
- return;
- }
+ DCHECK(IsRunningInCorrectSequence());
if (progress <= progress_) {
return;
@@ -191,15 +157,10 @@ void Operation::SetProgress(int progress) {
}
void Operation::SetStage(image_writer_api::Stage stage) {
- if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::SetStage, this, stage));
- return;
- }
+ DCHECK(IsRunningInCorrectSequence());
- if (IsCancelled()) {
+ if (IsCancelled())
return;
- }
stage_ = stage;
progress_ = 0;
@@ -211,42 +172,38 @@ void Operation::SetStage(image_writer_api::Stage stage) {
}
bool Operation::IsCancelled() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
return stage_ == image_writer_api::STAGE_NONE;
}
-void Operation::AddCleanUpFunction(const base::Closure& callback) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
- cleanup_functions_.push_back(callback);
+void Operation::AddCleanUpFunction(base::OnceClosure callback) {
+ DCHECK(IsRunningInCorrectSequence());
+ cleanup_functions_.push_back(std::move(callback));
}
void Operation::CompleteAndContinue(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
SetProgress(kProgressComplete);
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
+ PostTask(continuation);
}
#if !defined(OS_CHROMEOS)
void Operation::StartUtilityClient() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
- if (g_utility_client.Get().get()) {
- image_writer_client_ = g_utility_client.Get();
- return;
- }
+ DCHECK(IsRunningInCorrectSequence());
if (!image_writer_client_.get()) {
- image_writer_client_ = new ImageWriterUtilityClient();
- AddCleanUpFunction(base::Bind(&Operation::StopUtilityClient, this));
+ image_writer_client_ = ImageWriterUtilityClient::Create();
+ AddCleanUpFunction(base::BindOnce(&Operation::StopUtilityClient, this));
}
}
void Operation::StopUtilityClient() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
image_writer_client_->Shutdown();
}
void Operation::WriteImageProgress(int64_t total_bytes, int64_t curr_bytes) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
@@ -264,7 +221,8 @@ void Operation::GetMD5SumOfFile(
int64_t file_size,
int progress_offset,
int progress_scale,
- const base::Callback<void(const std::string&)>& callback) {
+ base::OnceCallback<void(const std::string&)> callback) {
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
@@ -285,10 +243,14 @@ void Operation::GetMD5SumOfFile(
}
}
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::MD5Chunk, this, Passed(std::move(file)), 0,
- file_size, progress_offset, progress_scale, callback));
+ PostTask(base::BindOnce(&Operation::MD5Chunk, this, Passed(std::move(file)),
+ 0, file_size, progress_offset, progress_scale,
+ std::move(callback)));
+}
+
+bool Operation::IsRunningInCorrectSequence() const {
+ base::ThreadRestrictions::AssertIOAllowed();
+ return task_runner_->RunsTasksInCurrentSequence();
}
void Operation::MD5Chunk(
@@ -297,7 +259,8 @@ void Operation::MD5Chunk(
int64_t bytes_total,
int progress_offset,
int progress_scale,
- const base::Callback<void(const std::string&)>& callback) {
+ base::OnceCallback<void(const std::string&)> callback) {
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled())
return;
@@ -311,7 +274,7 @@ void Operation::MD5Chunk(
// Nothing to read, we are done.
base::MD5Digest digest;
base::MD5Final(&digest, &md5_context_);
- callback.Run(base::MD5DigestToBase16(digest));
+ std::move(callback).Run(base::MD5DigestToBase16(digest));
} else {
int len = file.Read(bytes_processed, buffer.get(), read_size);
@@ -323,11 +286,10 @@ void Operation::MD5Chunk(
progress_offset;
SetProgress(percent_curr);
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::MD5Chunk, this, Passed(std::move(file)),
- bytes_processed + len, bytes_total, progress_offset,
- progress_scale, callback));
+ PostTask(base::BindOnce(&Operation::MD5Chunk, this,
+ Passed(std::move(file)), bytes_processed + len,
+ bytes_total, progress_offset, progress_scale,
+ std::move(callback)));
// Skip closing the file.
return;
} else {
@@ -337,25 +299,22 @@ void Operation::MD5Chunk(
}
}
-void Operation::OnUnzipFailure() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
- Error(error::kUnzipGenericError);
+void Operation::OnUnzipFailure(const std::string& error) {
+ DCHECK(IsRunningInCorrectSequence());
+ Error(error);
}
void Operation::OnUnzipProgress(int64_t total_bytes, int64_t progress_bytes) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
int progress_percent = kProgressComplete * progress_bytes / total_bytes;
SetProgress(progress_percent);
}
void Operation::CleanUp() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
- for (std::vector<base::Closure>::iterator it = cleanup_functions_.begin();
- it != cleanup_functions_.end();
- ++it) {
- it->Run();
- }
+ DCHECK(IsRunningInCorrectSequence());
+ for (base::OnceClosure& cleanup_function : cleanup_functions_)
+ std::move(cleanup_function).Run();
cleanup_functions_.clear();
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h
index b6d49387369..52efeef18c4 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h
@@ -15,7 +15,8 @@
#include "base/md5.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/weak_ptr.h"
-#include "base/task/cancelable_task_tracker.h"
+#include "base/sequenced_task_runner.h"
+#include "base/task_scheduler/task_traits.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h"
#include "chrome/common/extensions/api/image_writer_private.h"
@@ -27,10 +28,6 @@ namespace base {
class FilePath;
} // namespace base
-namespace zip {
-class ZipReader;
-}
-
namespace extensions {
namespace image_writer {
@@ -44,19 +41,20 @@ class OperationManager;
// then the Cancel method will stop it. The operation will call back to the
// OperationManager periodically or on any significant event.
//
-// Each stage of the operation is generally divided into three phases: Start,
-// Run, Complete. Start and Complete run on the UI thread and are responsible
-// for advancing to the next stage and other UI interaction. The Run phase does
-// the work on the FILE thread and calls SendProgress or Error as appropriate.
+// Each stage of the operation is generally divided into multiple phases with
+// Start() being the first phase and Complete() being the last. All phases
+// except Complete() run on blocking thread and Complete() runs on the UI
+// thread.
//
// TODO(haven): This class is current refcounted because it is owned by the
-// OperationManager on the UI thread but needs to do work on the FILE thread.
+// OperationManager on the UI thread but needs to do work on blocking threads.
// There is probably a better way to organize this so that it can be represented
// by a WeakPtr, but those are not thread-safe. Additionally, if destruction is
// done on the UI thread then that causes problems if any of the fields were
-// allocated/accessed on the FILE thread. http://crbug.com/344713
+// allocated/accessed on the blocking thread. http://crbug.com/344713
class Operation : public base::RefCountedThreadSafe<Operation> {
public:
+ // TODO(lazyboy): Turn these into base::OnceCallback. http://crbug.com/749865.
typedef base::Callback<void(bool, const std::string&)> StartWriteCallback;
typedef base::Callback<void(bool, const std::string&)> CancelWriteCallback;
@@ -80,17 +78,16 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
int GetProgress();
image_writer_api::Stage GetStage();
-#if !defined(OS_CHROMEOS)
- // Set an ImageWriterClient to use. Should be called only when testing. This
- // does not set up automatic shutdown of the client and it must be shutdown
- // manually.
- static void SetUtilityClientForTesting(
- scoped_refptr<ImageWriterUtilityClient> client);
-#endif
+ // Posts |task| to Operation's |task_runner_|.
+ void PostTask(base::OnceClosure task);
protected:
virtual ~Operation();
+ scoped_refptr<base::SequencedTaskRunner> task_runner() {
+ return task_runner_;
+ }
+
// This function should be overriden by subclasses to set up the work of the
// operation. It will be called from Start().
virtual void StartImpl() = 0;
@@ -111,7 +108,7 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
// Generates an error.
// |error_message| is used to create an OnWriteError event which is
// sent to the extension
- virtual void Error(const std::string& error_message);
+ void Error(const std::string& error_message);
// Set |progress_| and send an event. Progress should be in the interval
// [0,100]
@@ -125,8 +122,8 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
// Adds a callback that will be called during clean-up, whether the operation
// is aborted, encounters and error, or finishes successfully. These
- // functions will be run on the FILE thread.
- void AddCleanUpFunction(const base::Closure& callback);
+ // functions will be run on |task_runner_|.
+ void AddCleanUpFunction(base::OnceClosure callback);
// Completes the current operation (progress set to 100) and runs the
// continuation.
@@ -138,12 +135,13 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
// a scale of 50 means it will increment from 0 to 50 over the course of the
// sum. |progress_offset| is an percentage that will be added to the progress
// of the MD5 sum before updating |progress_| but after scaling.
- void GetMD5SumOfFile(
- const base::FilePath& file,
- int64_t file_size,
- int progress_offset,
- int progress_scale,
- const base::Callback<void(const std::string&)>& callback);
+ void GetMD5SumOfFile(const base::FilePath& file,
+ int64_t file_size,
+ int progress_offset,
+ int progress_scale,
+ base::OnceCallback<void(const std::string&)> callback);
+
+ bool IsRunningInCorrectSequence() const;
base::WeakPtr<OperationManager> manager_;
const ExtensionId extension_id_;
@@ -156,6 +154,9 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
private:
friend class base::RefCountedThreadSafe<Operation>;
+ friend class OperationForTest;
+ friend class ImageWriterUtilityClientTest;
+ friend class WriteFromUrlOperationForTest;
#if !defined(OS_CHROMEOS)
// Ensures the client is started. This may be called many times but will only
@@ -198,11 +199,12 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
int64_t bytes_total,
int progress_offset,
int progress_scale,
- const base::Callback<void(const std::string&)>& callback);
+ const base::OnceCallback<void(const std::string&)> callback);
- // Callbacks for zip::ZipReader.
- void OnUnzipFailure();
+ // Callbacks for UnzipHelper.
+ void OnUnzipOpenComplete(const base::FilePath& image_path);
void OnUnzipProgress(int64_t total_bytes, int64_t progress_bytes);
+ void OnUnzipFailure(const std::string& error);
// Runs all cleanup functions.
void CleanUp();
@@ -216,18 +218,28 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
// memory here. This requires that we only do one MD5 sum at a time.
base::MD5Context md5_context_;
- // Zip reader for unzip operations. The reason for using a pointer is that we
- // don't want to include zip_reader.h here which can mangle definitions in
- // jni.h when included in the same file. See crbug.com/554199.
- std::unique_ptr<zip::ZipReader> zip_reader_;
-
- // CleanUp operations that must be run. All these functions are run on the
- // FILE thread.
- std::vector<base::Closure> cleanup_functions_;
+ // Cleanup operations that must be run. All these functions are run on
+ // |task_runner_|.
+ std::vector<base::OnceClosure> cleanup_functions_;
+
+ static constexpr base::TaskTraits blocking_task_traits() {
+ return {
+ // Requires I/O.
+ base::MayBlock(),
+ // Apps (e.g. Chromebook Recovery Utility) present UI feedback based on
+ // an operation, but it's not on critical path.
+ base::TaskPriority::USER_VISIBLE,
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN,
+ };
+ }
// The download folder on Chrome OS.
const base::FilePath download_folder_;
+ // Sequenced task runner where all I/O operation will be performed.
+ // Most of the methods of this class run in this task runner.
+ scoped_refptr<base::SequencedTaskRunner> task_runner_;
+
DISALLOW_COPY_AND_ASSIGN(Operation);
};
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 79ad1bea323..56b833274df 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
@@ -35,7 +35,7 @@ void ClearImageBurner() {
} // namespace
void Operation::Write(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
SetStage(image_writer_api::STAGE_WRITE);
// Note this has to be run on the FILE thread to avoid concurrent access.
@@ -47,7 +47,7 @@ void Operation::Write(const base::Closure& continuation) {
}
void Operation::VerifyWrite(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
// No verification is available in Chrome OS currently.
continuation.Run();
@@ -66,7 +66,7 @@ void Operation::UnmountVolumesCallback(const base::Closure& continuation,
if (!success) {
LOG(ERROR) << "Volume unmounting failed.";
- Error(error::kUnmountVolumesError);
+ PostTask(base::Bind(&Operation::Error, this, error::kUnmountVolumesError));
return;
}
@@ -77,7 +77,7 @@ void Operation::UnmountVolumesCallback(const base::Closure& continuation,
if (iter == disks.end()) {
LOG(ERROR) << "Disk not found in disk list after unmounting volumes.";
- Error(error::kUnmountVolumesError);
+ PostTask(base::Bind(&Operation::Error, this, error::kUnmountVolumesError));
return;
}
@@ -106,11 +106,12 @@ void Operation::OnBurnFinished(const base::Closure& continuation,
bool success,
const std::string& error) {
if (success) {
- SetProgress(kProgressComplete);
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
+ PostTask(base::BindOnce(&Operation::SetProgress, this, kProgressComplete));
+ PostTask(continuation);
} else {
DLOG(ERROR) << "Error encountered while burning: " << error;
- Error(error::kChromeOSImageBurnerError);
+ PostTask(base::BindOnce(&Operation::Error, this,
+ error::kChromeOSImageBurnerError));
}
}
@@ -118,11 +119,12 @@ void Operation::OnBurnProgress(const std::string& target_path,
int64_t num_bytes_burnt,
int64_t total_size) {
int progress = kProgressComplete * num_bytes_burnt / total_size;
- SetProgress(progress);
+ PostTask(base::BindOnce(&Operation::SetProgress, this, progress));
}
void Operation::OnBurnError() {
- Error(error::kChromeOSImageBurnerError);
+ PostTask(base::BindOnce(&Operation::Error, this,
+ error::kChromeOSImageBurnerError));
}
} // namespace image_writer
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc
index c01110bc14d..0e007816974 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc
@@ -60,8 +60,8 @@ void OperationManager::Shutdown() {
for (OperationMap::iterator iter = operations_.begin();
iter != operations_.end();
iter++) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::Abort, iter->second));
+ scoped_refptr<Operation> operation = iter->second;
+ operation->PostTask(base::BindOnce(&Operation::Abort, operation));
}
}
@@ -92,8 +92,8 @@ void OperationManager::StartWriteFromUrl(
device_path,
GetAssociatedDownloadFolder()));
operations_[extension_id] = operation;
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::Start, operation));
+ operation->PostTask(base::BindOnce(&Operation::Start, operation));
+
callback.Run(true, "");
}
@@ -117,8 +117,7 @@ void OperationManager::StartWriteFromFile(
weak_factory_.GetWeakPtr(), extension_id, path, device_path,
GetAssociatedDownloadFolder()));
operations_[extension_id] = operation;
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::Start, operation));
+ operation->PostTask(base::BindOnce(&Operation::Start, operation));
callback.Run(true, "");
}
@@ -130,8 +129,7 @@ void OperationManager::CancelWrite(
if (existing_operation == NULL) {
callback.Run(false, error::kNoOperationInProgress);
} else {
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
+ existing_operation->PostTask(
base::BindOnce(&Operation::Cancel, existing_operation));
DeleteOperation(extension_id);
callback.Run(true, "");
@@ -152,8 +150,7 @@ void OperationManager::DestroyPartitions(
weak_factory_.GetWeakPtr(), extension_id, device_path,
GetAssociatedDownloadFolder()));
operations_[extension_id] = operation;
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&Operation::Start, operation));
+ operation->PostTask(base::BindOnce(&Operation::Start, operation));
callback.Run(true, "");
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc
index 5580e87281e..d020f25e12b 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc
@@ -104,7 +104,7 @@ TEST_F(ImageWriterOperationManagerTest, WriteFromFile) {
EXPECT_TRUE(cancel_success_);
EXPECT_EQ("", cancel_error_);
- base::RunLoop().RunUntilIdle();
+ content::RunAllBlockingPoolTasksUntilIdle();
}
TEST_F(ImageWriterOperationManagerTest, DestroyPartitions) {
@@ -129,7 +129,7 @@ TEST_F(ImageWriterOperationManagerTest, DestroyPartitions) {
EXPECT_TRUE(cancel_success_);
EXPECT_EQ("", cancel_error_);
- base::RunLoop().RunUntilIdle();
+ content::RunAllBlockingPoolTasksUntilIdle();
}
} // namespace
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_nonchromeos.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_nonchromeos.cc
index bf8fac46e25..dc78b165855 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_nonchromeos.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_nonchromeos.cc
@@ -17,7 +17,7 @@ namespace image_writer {
using content::BrowserThread;
void Operation::Write(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
@@ -38,7 +38,7 @@ void Operation::Write(const base::Closure& continuation) {
}
void Operation::VerifyWrite(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc
index 5d74e69c247..2e8654ee0e4 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc
@@ -29,6 +29,19 @@ using testing::AtLeast;
using testing::Gt;
using testing::Lt;
+#if !defined(OS_CHROMEOS)
+
+void SetUpUtilityClientProgressOnVerifyWrite(
+ const std::vector<int>& progress_list,
+ bool will_succeed,
+ FakeImageWriterClient* client) {
+ client->SimulateProgressOnVerifyWrite(progress_list, will_succeed);
+}
+
+#endif // !defined(OS_CHROMEOS)
+
+} // namespace
+
// This class gives us a generic Operation with the ability to set or inspect
// the current path to the image file.
class OperationForTest : public Operation {
@@ -42,18 +55,23 @@ class OperationForTest : public Operation {
void StartImpl() override {}
// Expose internal stages for testing.
+ // Also wraps Operation's methods to run on correct sequence.
void Unzip(const base::Closure& continuation) {
- Operation::Unzip(continuation);
+ PostTask(base::BindOnce(&Operation::Unzip, this, continuation));
}
void Write(const base::Closure& continuation) {
- Operation::Write(continuation);
+ PostTask(base::BindOnce(&Operation::Write, this, continuation));
}
void VerifyWrite(const base::Closure& continuation) {
- Operation::VerifyWrite(continuation);
+ PostTask(base::BindOnce(&Operation::VerifyWrite, this, continuation));
}
+ void Start() { PostTask(base::BindOnce(&Operation::Start, this)); }
+
+ void Cancel() { PostTask(base::BindOnce(&Operation::Cancel, this)); }
+
// Helpers to set-up state for intermediate stages.
void SetImagePath(const base::FilePath image_path) {
image_path_ = image_path;
@@ -93,7 +111,10 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase {
void TearDown() override {
// Ensure all callbacks have been destroyed and cleanup occurs.
+
+ // Cancel() will ensure we Shutdown() FakeImageWriterClient.
operation_->Cancel();
+ scoped_task_environment_.RunUntilIdle();
ImageWriterUnitTestBase::TearDown();
}
@@ -107,8 +128,6 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase {
scoped_refptr<OperationForTest> operation_;
};
-} // namespace
-
// Unizpping a non-zip should do nothing.
TEST_F(ImageWriterOperationTest, UnzipNonZipFile) {
EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0);
@@ -118,12 +137,9 @@ TEST_F(ImageWriterOperationTest, UnzipNonZipFile) {
EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0);
operation_->Start();
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::Unzip, operation_,
- base::Bind(&base::DoNothing)));
-
- base::RunLoop().RunUntilIdle();
+ base::RunLoop run_loop;
+ operation_->Unzip(run_loop.QuitClosure());
+ run_loop.Run();
}
TEST_F(ImageWriterOperationTest, UnzipZipFile) {
@@ -141,18 +157,26 @@ TEST_F(ImageWriterOperationTest, UnzipZipFile) {
operation_->SetImagePath(zip_file_);
operation_->Start();
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::Unzip, operation_,
- base::Bind(&base::DoNothing)));
-
- base::RunLoop().RunUntilIdle();
+ base::RunLoop run_loop;
+ operation_->Unzip(run_loop.QuitClosure());
+ run_loop.Run();
EXPECT_TRUE(base::ContentsEqual(image_path_, operation_->GetImagePath()));
}
#if defined(OS_LINUX)
TEST_F(ImageWriterOperationTest, WriteImageToDevice) {
+#if !defined(OS_CHROMEOS)
+ auto set_up_utility_client_progress =
+ [](const std::vector<int>& progress_list, bool will_succeed,
+ FakeImageWriterClient* client) {
+ client->SimulateProgressOnWrite(progress_list, will_succeed);
+ };
+ // Sets up client for simulating Operation::Progress() on Operation::Write.
+ std::vector<int> progress_list{0, kTestFileSize / 2, kTestFileSize};
+ test_utils_.RunOnUtilityClientCreation(base::BindOnce(
+ set_up_utility_client_progress, progress_list, true /* will_succeed */));
+#endif
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, _))
@@ -165,29 +189,23 @@ TEST_F(ImageWriterOperationTest, WriteImageToDevice) {
.Times(AtLeast(1));
operation_->Start();
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::Write, operation_,
- base::Bind(&base::DoNothing)));
-
- base::RunLoop().RunUntilIdle();
-
-#if !defined(OS_CHROMEOS)
- test_utils_.GetUtilityClient()->Progress(0);
- test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
- test_utils_.GetUtilityClient()->Progress(kTestFileSize);
- test_utils_.GetUtilityClient()->Success();
-
- base::RunLoop().RunUntilIdle();
-#endif
+ base::RunLoop run_loop;
+ operation_->Write(run_loop.QuitClosure());
+ run_loop.Run();
}
-#endif
+#endif // defined(OS_LINUX)
#if !defined(OS_CHROMEOS)
// Chrome OS doesn't support verification in the ImageBurner, so these two tests
// are skipped.
TEST_F(ImageWriterOperationTest, VerifyFileSuccess) {
+ // Sets up client for simulating Operation::Progress() on
+ // Operation::VerifyWrite.
+ std::vector<int> progress_list{0, kTestFileSize / 2, kTestFileSize};
+ test_utils_.RunOnUtilityClientCreation(
+ base::BindOnce(&SetUpUtilityClientProgressOnVerifyWrite, progress_list,
+ true /* will_succeed */));
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(
manager_,
@@ -206,24 +224,18 @@ TEST_F(ImageWriterOperationTest, VerifyFileSuccess) {
test_utils_.GetDevicePath(), kImagePattern, kTestFileSize);
operation_->Start();
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::VerifyWrite, operation_,
- base::Bind(&base::DoNothing)));
-
- base::RunLoop().RunUntilIdle();
-
-#if !defined(OS_CHROMEOS)
- test_utils_.GetUtilityClient()->Progress(0);
- test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
- test_utils_.GetUtilityClient()->Progress(kTestFileSize);
- test_utils_.GetUtilityClient()->Success();
-#endif
-
- base::RunLoop().RunUntilIdle();
+ base::RunLoop run_loop;
+ operation_->VerifyWrite(run_loop.QuitClosure());
+ run_loop.Run();
}
TEST_F(ImageWriterOperationTest, VerifyFileFailure) {
+ // Sets up client for simulating Operation::Progress() on
+ // Operation::VerifyWrite. Also simulates failure.
+ std::vector<int> progress_list{0, kTestFileSize / 2};
+ test_utils_.RunOnUtilityClientCreation(
+ base::BindOnce(&SetUpUtilityClientProgressOnVerifyWrite, progress_list,
+ false /* will_succeed */));
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _))
@@ -242,20 +254,10 @@ TEST_F(ImageWriterOperationTest, VerifyFileFailure) {
test_utils_.GetDevicePath(), kDevicePattern, kTestFileSize);
operation_->Start();
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::VerifyWrite, operation_,
- base::Bind(&base::DoNothing)));
-
- base::RunLoop().RunUntilIdle();
-
- test_utils_.GetUtilityClient()->Progress(0);
- test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
- test_utils_.GetUtilityClient()->Error(error::kVerificationFailed);
-
- base::RunLoop().RunUntilIdle();
+ operation_->VerifyWrite(base::Bind(&base::DoNothing));
+ content::RunAllBlockingPoolTasksUntilIdle();
}
-#endif
+#endif // !defined(OS_CHROMEOS)
// Tests that on creation the operation_ has the expected state.
TEST_F(ImageWriterOperationTest, Creation) {
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc
index 1b2a3cdbee3..c16b847be5a 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc
@@ -5,6 +5,7 @@
#include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h"
#include "base/lazy_instance.h"
+#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/browser_thread.h"
@@ -19,29 +20,30 @@ static base::LazyInstance<scoped_refptr<StorageDeviceList>>::DestructorAtExit
void RemovableStorageProvider::GetAllDevices(DeviceListReadyCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (g_test_device_list.Get().get() != NULL) {
+ if (g_test_device_list.Get().get() != nullptr) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(callback, g_test_device_list.Get(), true));
+ FROM_HERE,
+ base::BindOnce(std::move(callback), g_test_device_list.Get()));
return;
}
-
- scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList);
-
// We need to do some file i/o to get the device block size
- content::BrowserThread::PostTaskAndReplyWithResult(
- content::BrowserThread::FILE,
+ base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE,
- base::Bind(PopulateDeviceList, device_list),
- base::Bind(callback, device_list));
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
+ base::BindOnce(&RemovableStorageProvider::PopulateDeviceList),
+ std::move(callback));
}
+// static
void RemovableStorageProvider::SetDeviceListForTesting(
scoped_refptr<StorageDeviceList> device_list) {
g_test_device_list.Get() = device_list;
}
+// static
void RemovableStorageProvider::ClearDeviceListForTesting() {
- g_test_device_list.Get() = NULL;
+ g_test_device_list.Get() = nullptr;
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h
index 7c6724242e4..5dd00878cfd 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h
@@ -19,8 +19,8 @@ typedef RefCountedVector<api::image_writer_private::RemovableStorageDevice>
// storage devices
class RemovableStorageProvider {
public:
- typedef base::Callback<void(scoped_refptr<StorageDeviceList>, bool)>
- DeviceListReadyCallback;
+ using DeviceListReadyCallback =
+ base::OnceCallback<void(scoped_refptr<StorageDeviceList>)>;
// Gets the list of all available devices and returns it via callback.
static void GetAllDevices(DeviceListReadyCallback callback);
@@ -34,8 +34,9 @@ class RemovableStorageProvider {
static void ClearDeviceListForTesting();
private:
- // Fills the provided empty device list with the available devices.
- static bool PopulateDeviceList(scoped_refptr<StorageDeviceList> device_list);
+ // Returns available list of devices. If there is an error retrieving devices,
+ // then returns nullptr.
+ static scoped_refptr<StorageDeviceList> PopulateDeviceList();
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc
index 6dfc9f1b87b..c3599770427 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc
@@ -17,10 +17,11 @@ using chromeos::disks::DiskMountManager;
// fixed disk. In fact, some SD cards will present themselves as fixed disks
// (see http://crbug.com/340761). Thus we just expose all USB and SD drives.
// static
-bool RemovableStorageProvider::PopulateDeviceList(
- scoped_refptr<StorageDeviceList> device_list) {
+scoped_refptr<StorageDeviceList>
+RemovableStorageProvider::PopulateDeviceList() {
DiskMountManager* disk_mount_manager = DiskMountManager::GetInstance();
const DiskMountManager::DiskMap& disks = disk_mount_manager->disks();
+ scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList());
for (DiskMountManager::DiskMap::const_iterator iter = disks.begin();
iter != disks.end();
@@ -48,7 +49,7 @@ bool RemovableStorageProvider::PopulateDeviceList(
}
}
- return true;
+ return device_list;
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc
index 098f786b4ac..bbbea6ddf8b 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc
@@ -6,6 +6,7 @@
#include "base/bind.h"
#include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
#include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h"
#include "chromeos/disks/mock_disk_mount_manager.h"
#include "content/public/test/test_browser_thread_bundle.h"
@@ -27,12 +28,16 @@ const char kVendorName[] = "Test Vendor";
const char kProductName[] = "Test Product";
const uint64_t kDeviceSize = 1024 * 1024 * 1024;
const bool kOnRemovableDevice = true;
+const char kDiskFileSystemType[] = "vfat";
const char kUnknownSDDiskModel[] = "SD Card";
const char kUnknownUSBDiskModel[] = "USB Drive";
class RemovableStorageProviderChromeOsUnitTest : public testing::Test {
public:
+ RemovableStorageProviderChromeOsUnitTest()
+ : scoped_task_environment_(
+ base::test::ScopedTaskEnvironment::MainThreadType::UI) {}
void SetUp() override {
disk_mount_manager_mock_ = new MockDiskMountManager();
DiskMountManager::InitializeForTesting(disk_mount_manager_mock_);
@@ -41,7 +46,7 @@ class RemovableStorageProviderChromeOsUnitTest : public testing::Test {
void TearDown() override { DiskMountManager::Shutdown(); }
- void DevicesCallback(scoped_refptr<StorageDeviceList> devices, bool success) {
+ void DevicesCallback(scoped_refptr<StorageDeviceList> devices) {
devices_ = devices;
}
@@ -71,17 +76,10 @@ class RemovableStorageProviderChromeOsUnitTest : public testing::Test {
kMountPath,
chromeos::MOUNT_TYPE_DEVICE,
chromeos::disks::MOUNT_CONDITION_NONE);
- disk_mount_manager_mock_->CreateDiskEntryForMountDevice(mount_info,
- kDeviceId,
- kDeviceName,
- vendor_name,
- product_name,
- device_type,
- kDeviceSize,
- is_parent,
- has_media,
- on_boot_device,
- kOnRemovableDevice);
+ disk_mount_manager_mock_->CreateDiskEntryForMountDevice(
+ mount_info, kDeviceId, kDeviceName, vendor_name, product_name,
+ device_type, kDeviceSize, is_parent, has_media, on_boot_device,
+ kOnRemovableDevice, kDiskFileSystemType);
}
// Checks if the DeviceList has a specific entry.
@@ -109,6 +107,7 @@ class RemovableStorageProviderChromeOsUnitTest : public testing::Test {
EXPECT_EQ(capacity, device->capacity);
}
+ base::test::ScopedTaskEnvironment scoped_task_environment_;
MockDiskMountManager* disk_mount_manager_mock_;
scoped_refptr<StorageDeviceList> devices_;
@@ -132,7 +131,7 @@ TEST_F(RemovableStorageProviderChromeOsUnitTest, GetAllDevices) {
base::Bind(&RemovableStorageProviderChromeOsUnitTest::DevicesCallback,
base::Unretained(this)));
- base::RunLoop().RunUntilIdle();
+ scoped_task_environment_.RunUntilIdle();
ASSERT_EQ(2U, devices_->data.size());
@@ -153,7 +152,7 @@ TEST_F(RemovableStorageProviderChromeOsUnitTest, EmptyProductAndModel) {
base::Bind(&RemovableStorageProviderChromeOsUnitTest::DevicesCallback,
base::Unretained(this)));
- base::RunLoop().RunUntilIdle();
+ scoped_task_environment_.RunUntilIdle();
ASSERT_EQ(2U, devices_->data.size());
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc
index 60921f31f89..389479b1ae2 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc
@@ -42,14 +42,16 @@ static int get_device_blk_size(const std::string& path) {
return blk_size;
}
-bool RemovableStorageProvider::PopulateDeviceList(
- scoped_refptr<StorageDeviceList> device_list) {
+// static
+scoped_refptr<StorageDeviceList>
+RemovableStorageProvider::PopulateDeviceList() {
device::ScopedUdevPtr udev(device::udev_new());
if (!udev) {
DLOG(ERROR) << "Can't create udev";
- return false;
+ return nullptr;
}
+ scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList());
/* Create a list of the devices in the 'block' subsystem. */
device::ScopedUdevEnumeratePtr enumerate(
device::udev_enumerate_new(udev.get()));
@@ -106,7 +108,7 @@ bool RemovableStorageProvider::PopulateDeviceList(
device_list->data.push_back(std::move(device_item));
}
- return true;
+ return device_list;
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc
index ad1f5d3e127..8191b1c31f6 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc
@@ -22,8 +22,8 @@
namespace extensions {
// static
-bool RemovableStorageProvider::PopulateDeviceList(
- scoped_refptr<StorageDeviceList> device_list) {
+scoped_refptr<StorageDeviceList>
+RemovableStorageProvider::PopulateDeviceList() {
base::ThreadRestrictions::AssertIOAllowed();
// Match only writable whole-disks.
CFMutableDictionaryRef matching = IOServiceMatching(kIOMediaClass);
@@ -34,11 +34,12 @@ bool RemovableStorageProvider::PopulateDeviceList(
if (IOServiceGetMatchingServices(
kIOMasterPortDefault, matching, &disk_iterator) != KERN_SUCCESS) {
LOG(ERROR) << "Unable to get disk services.";
- return false;
+ return nullptr;
}
base::mac::ScopedIOObject<io_service_t> iterator_ref(disk_iterator);
io_object_t disk_obj;
+ scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList());
while ((disk_obj = IOIteratorNext(disk_iterator))) {
base::mac::ScopedIOObject<io_object_t> disk_obj_ref(disk_obj);
@@ -100,7 +101,7 @@ bool RemovableStorageProvider::PopulateDeviceList(
device_list->data.push_back(std::move(device));
}
- return true;
+ return device_list;
}
} // namespace extensions
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 a48c2b7ed58..51db3d51b8d 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
@@ -174,8 +174,9 @@ bool AddDeviceInfo(HANDLE interface_enumerator,
} // namespace
-bool RemovableStorageProvider::PopulateDeviceList(
- scoped_refptr<StorageDeviceList> device_list) {
+// static
+scoped_refptr<StorageDeviceList>
+RemovableStorageProvider::PopulateDeviceList() {
HDEVINFO interface_enumerator = SetupDiGetClassDevs(
&DiskClassGuid,
NULL, // Enumerator.
@@ -185,13 +186,14 @@ bool RemovableStorageProvider::PopulateDeviceList(
if (interface_enumerator == INVALID_HANDLE_VALUE) {
DPLOG(ERROR) << "SetupDiGetClassDevs failed.";
- return false;
+ return nullptr;
}
DWORD index = 0;
SP_DEVICE_INTERFACE_DATA interface_data;
interface_data.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);
+ scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList());
while (SetupDiEnumDeviceInterfaces(
interface_enumerator,
NULL, // Device Info data.
@@ -207,11 +209,11 @@ bool RemovableStorageProvider::PopulateDeviceList(
if (error_code != ERROR_NO_MORE_ITEMS) {
PLOG(ERROR) << "SetupDiEnumDeviceInterfaces failed";
SetupDiDestroyDeviceInfoList(interface_enumerator);
- return false;
+ return nullptr;
}
SetupDiDestroyDeviceInfoList(interface_enumerator);
- return true;
+ return device_list;
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc
index 17f9f497029..a19da48acad 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc
@@ -11,6 +11,7 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
+#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
#if defined(OS_CHROMEOS)
#include "chromeos/dbus/dbus_thread_manager.h"
@@ -60,7 +61,6 @@ class ImageWriterFakeImageBurnerClient
} // namespace
#endif
-MockOperationManager::MockOperationManager() : OperationManager(NULL) {}
MockOperationManager::MockOperationManager(content::BrowserContext* context)
: OperationManager(context) {}
MockOperationManager::~MockOperationManager() {}
@@ -77,9 +77,29 @@ void FakeDiskMountManager::UnmountDeviceRecursively(
}
#endif
+SimulateProgressInfo::SimulateProgressInfo(
+ const std::vector<int>& progress_list,
+ bool will_succeed)
+ : progress_list(progress_list), will_succeed(will_succeed) {}
+
+SimulateProgressInfo::~SimulateProgressInfo() {}
+SimulateProgressInfo::SimulateProgressInfo(const SimulateProgressInfo&) =
+ default;
+
FakeImageWriterClient::FakeImageWriterClient() {}
FakeImageWriterClient::~FakeImageWriterClient() {}
+void FakeImageWriterClient::SimulateProgressAndCompletion(
+ const SimulateProgressInfo& info) {
+ for (int progress : info.progress_list)
+ Progress(progress);
+ if (info.will_succeed) {
+ Success();
+ } else {
+ Error(error::kVerificationFailed);
+ }
+}
+
void FakeImageWriterClient::Write(const ProgressCallback& progress_callback,
const SuccessCallback& success_callback,
const ErrorCallback& error_callback,
@@ -89,8 +109,10 @@ void FakeImageWriterClient::Write(const ProgressCallback& progress_callback,
success_callback_ = success_callback;
error_callback_ = error_callback;
- if (!write_callback_.is_null())
- write_callback_.Run();
+ if (simulate_on_write_) {
+ SimulateProgressAndCompletion(*simulate_on_write_);
+ simulate_on_write_.reset();
+ }
}
void FakeImageWriterClient::Verify(const ProgressCallback& progress_callback,
@@ -102,8 +124,10 @@ void FakeImageWriterClient::Verify(const ProgressCallback& progress_callback,
success_callback_ = success_callback;
error_callback_ = error_callback;
- if (!verify_callback_.is_null())
- verify_callback_.Run();
+ if (simulate_on_verify_) {
+ SimulateProgressAndCompletion(*simulate_on_verify_);
+ simulate_on_verify_.reset();
+ }
}
void FakeImageWriterClient::Cancel(const CancelCallback& cancel_callback) {
@@ -117,18 +141,20 @@ void FakeImageWriterClient::Shutdown() {
error_callback_.Reset();
cancel_callback_.Reset();
- write_callback_.Reset();
- verify_callback_.Reset();
+ simulate_on_write_.reset();
+ simulate_on_verify_.reset();
}
-void FakeImageWriterClient::SetWriteCallback(
- const base::Closure& write_callback) {
- write_callback_ = write_callback;
+void FakeImageWriterClient::SimulateProgressOnWrite(
+ const std::vector<int>& progress_list,
+ bool will_succeed) {
+ simulate_on_write_ = SimulateProgressInfo(progress_list, will_succeed);
}
-void FakeImageWriterClient::SetVerifyCallback(
- const base::Closure& verify_callback) {
- verify_callback_ = verify_callback;
+void FakeImageWriterClient::SimulateProgressOnVerifyWrite(
+ const std::vector<int>& progress_list,
+ bool will_succeed) {
+ simulate_on_verify_ = SimulateProgressInfo(progress_list, will_succeed);
}
void FakeImageWriterClient::Progress(int64_t progress) {
@@ -151,11 +177,43 @@ void FakeImageWriterClient::Cancel() {
cancel_callback_.Run();
}
-ImageWriterTestUtils::ImageWriterTestUtils() {
+#if !defined(OS_CHROMEOS)
+scoped_refptr<ImageWriterUtilityClient> CreateFakeImageWriterUtilityClient(
+ ImageWriterTestUtils* utils) {
+ auto* client = new FakeImageWriterClient();
+ utils->OnUtilityClientCreated(client);
+ return make_scoped_refptr(client);
+}
+#endif // !defined(OS_CHROMEOS)
+
+ImageWriterTestUtils::ImageWriterTestUtils()
+#if !defined(OS_CHROMEOS)
+ : utility_client_factory_(
+ base::Bind(&CreateFakeImageWriterUtilityClient, this))
+#endif
+{
}
ImageWriterTestUtils::~ImageWriterTestUtils() {
}
+#if !defined(OS_CHROMEOS)
+void ImageWriterTestUtils::OnUtilityClientCreated(
+ FakeImageWriterClient* client) {
+ DCHECK(!client_.get())
+ << "Single FakeImageWriterClient instance per test case expected.";
+ client_ = client;
+ if (!client_creation_callback_.is_null())
+ std::move(client_creation_callback_).Run(client);
+}
+#endif
+
+#if !defined(OS_CHROMEOS)
+void ImageWriterTestUtils::RunOnUtilityClientCreation(
+ base::OnceCallback<void(FakeImageWriterClient*)> closure) {
+ client_creation_callback_ = std::move(closure);
+}
+#endif
+
void ImageWriterTestUtils::SetUp() {
SetUp(false);
}
@@ -185,24 +243,14 @@ void ImageWriterTestUtils::SetUp(bool is_browser_test) {
// Adds a disk entry for test_device_path_ with the same device and file path.
disk_manager->CreateDiskEntryForMountDevice(
chromeos::disks::DiskMountManager::MountPointInfo(
- test_device_path_.value(),
- "/dummy/mount",
- chromeos::MOUNT_TYPE_DEVICE,
- chromeos::disks::MOUNT_CONDITION_NONE),
- "device_id",
- "device_label",
- "Vendor",
- "Product",
- chromeos::DEVICE_TYPE_USB,
- kTestFileSize,
- true,
- true,
- true,
- false);
+ test_device_path_.value(), "/dummy/mount",
+ chromeos::MOUNT_TYPE_DEVICE, chromeos::disks::MOUNT_CONDITION_NONE),
+ "device_id", "device_label", "Vendor", "Product",
+ chromeos::DEVICE_TYPE_USB, kTestFileSize, true, true, true, false,
+ kTestFileSystemType);
disk_manager->SetupDefaultReplies();
#else
- client_ = new FakeImageWriterClient();
- image_writer::Operation::SetUtilityClientForTesting(client_);
+ ImageWriterUtilityClient::SetFactoryForTesting(&utility_client_factory_);
#endif
}
@@ -213,8 +261,7 @@ void ImageWriterTestUtils::TearDown() {
}
chromeos::disks::DiskMountManager::Shutdown();
#else
- image_writer::Operation::SetUtilityClientForTesting(NULL);
- client_->Shutdown();
+ ImageWriterUtilityClient::SetFactoryForTesting(nullptr);
#endif
}
@@ -230,12 +277,6 @@ const base::FilePath& ImageWriterTestUtils::GetDevicePath() {
return test_device_path_;
}
-#if !defined(OS_CHROMEOS)
-FakeImageWriterClient* ImageWriterTestUtils::GetUtilityClient() {
- return client_.get();
-}
-#endif
-
bool ImageWriterTestUtils::ImageWrittenToDevice() {
std::unique_ptr<char[]> image_buffer(new char[kTestFileSize]);
std::unique_ptr<char[]> device_buffer(new char[kTestFileSize]);
@@ -265,8 +306,9 @@ bool ImageWriterTestUtils::FillFile(const base::FilePath& file,
}
ImageWriterUnitTestBase::ImageWriterUnitTestBase()
- : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
-}
+ : scoped_task_environment_(
+ base::test::ScopedTaskEnvironment::MainThreadType::UI),
+ thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD) {}
ImageWriterUnitTestBase::~ImageWriterUnitTestBase() {
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h
index 2ccac3d7f48..8ad775dbb06 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h
@@ -11,6 +11,7 @@
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h"
#include "chrome/browser/extensions/api/image_writer_private/operation_manager.h"
@@ -35,12 +36,13 @@ const int kTestFileSize = 32 * 1024;
const int kImagePattern = 0x55555555; // 01010101
// Pattern to use in the device file.
const int kDevicePattern = 0xAAAAAAAA; // 10101010
+// Disk file system type
+const char kTestFileSystemType[] = "vfat";
// A mock around the operation manager for tracking callbacks. Note that there
// are non-virtual methods on this class that should not be called in tests.
class MockOperationManager : public OperationManager {
public:
- MockOperationManager();
explicit MockOperationManager(content::BrowserContext* context);
virtual ~MockOperationManager();
@@ -74,6 +76,15 @@ class FakeDiskMountManager : public chromeos::disks::MockDiskMountManager {
};
#endif
+struct SimulateProgressInfo {
+ SimulateProgressInfo(const std::vector<int>& progress_list,
+ bool will_succeed);
+ ~SimulateProgressInfo();
+ SimulateProgressInfo(const SimulateProgressInfo&);
+ std::vector<int> progress_list;
+ bool will_succeed;
+};
+
class FakeImageWriterClient : public ImageWriterUtilityClient {
public:
FakeImageWriterClient();
@@ -94,10 +105,14 @@ class FakeImageWriterClient : public ImageWriterUtilityClient {
void Shutdown() override;
- // Sets a callback for when a Write call is made.
- void SetWriteCallback(const base::Closure& write_callback);
- // Sets a callback for when a Verify call is made.
- void SetVerifyCallback(const base::Closure& verify_callback);
+ // Issues Operation::Progress() calls with items in |progress_list| on
+ // Operation Write(). Sends Operation::Success() iff |will_succeed| is true,
+ // otherwise issues an error.
+ void SimulateProgressOnWrite(const std::vector<int>& progress_list,
+ bool will_succeed);
+ // Same as SimulateProgressOnWrite, but applies to Operation::VerifyWrite().
+ void SimulateProgressOnVerifyWrite(const std::vector<int>& progress_list,
+ bool will_succeed);
// Triggers the progress callback.
void Progress(int64_t progress);
@@ -108,16 +123,19 @@ class FakeImageWriterClient : public ImageWriterUtilityClient {
// Triggers the cancel callback.
void Cancel();
- private:
+ protected:
~FakeImageWriterClient() override;
+ private:
+ void SimulateProgressAndCompletion(const SimulateProgressInfo& info);
+
ProgressCallback progress_callback_;
SuccessCallback success_callback_;
ErrorCallback error_callback_;
CancelCallback cancel_callback_;
- base::Closure write_callback_;
- base::Closure verify_callback_;
+ base::Optional<SimulateProgressInfo> simulate_on_write_;
+ base::Optional<SimulateProgressInfo> simulate_on_verify_;
};
class ImageWriterTestUtils {
@@ -125,6 +143,15 @@ class ImageWriterTestUtils {
ImageWriterTestUtils();
virtual ~ImageWriterTestUtils();
+#if !defined(OS_CHROMEOS)
+ using UtilityClientCreationCallback =
+ base::OnceCallback<void(FakeImageWriterClient*)>;
+ void RunOnUtilityClientCreation(UtilityClientCreationCallback callback);
+
+ // Called when an instance of utility client is created.
+ void OnUtilityClientCreated(FakeImageWriterClient* client);
+#endif
+
// Verifies that the data in image_path was written to the file at
// device_path. This is different from base::ContentsEqual because the device
// may be larger than the image.
@@ -152,10 +179,6 @@ class ImageWriterTestUtils {
const base::FilePath& GetImagePath();
const base::FilePath& GetDevicePath();
-#if !defined(OS_CHROMEOS)
- FakeImageWriterClient* GetUtilityClient();
-#endif
-
protected:
base::ScopedTempDir temp_dir_;
base::FilePath test_image_path_;
@@ -163,6 +186,9 @@ class ImageWriterTestUtils {
#if !defined(OS_CHROMEOS)
scoped_refptr<FakeImageWriterClient> client_;
+ ImageWriterUtilityClient::ImageWriterUtilityClientFactory
+ utility_client_factory_;
+ base::OnceCallback<void(FakeImageWriterClient*)> client_creation_callback_;
#endif
};
@@ -177,6 +203,8 @@ class ImageWriterUnitTestBase : public testing::Test {
ImageWriterTestUtils test_utils_;
+ base::test::ScopedTaskEnvironment scoped_task_environment_;
+
private:
content::TestBrowserThreadBundle thread_bundle_;
};
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc
new file mode 100644
index 00000000000..39f27d646ad
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc
@@ -0,0 +1,92 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/image_writer_private/unzip_helper.h"
+
+#include "base/files/file_util.h"
+#include "base/memory/ptr_util.h"
+#include "base/single_thread_task_runner.h"
+#include "base/task_scheduler/post_task.h"
+#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
+#include "third_party/zlib/google/zip_reader.h"
+
+namespace extensions {
+namespace image_writer {
+
+UnzipHelper::UnzipHelper(
+ scoped_refptr<base::SequencedTaskRunner> owner_task_runner,
+ const base::Callback<void(const base::FilePath&)>& open_callback,
+ const base::Closure& complete_callback,
+ const base::Callback<void(const std::string&)>& failure_callback,
+ const base::Callback<void(int64_t, int64_t)>& progress_callback)
+ : owner_task_runner_(owner_task_runner),
+ open_callback_(open_callback),
+ complete_callback_(complete_callback),
+ failure_callback_(failure_callback),
+ progress_callback_(progress_callback),
+ zip_reader_(base::MakeUnique<zip::ZipReader>()) {}
+
+UnzipHelper::~UnzipHelper() {}
+
+void UnzipHelper::Unzip(const base::FilePath& image_path,
+ const base::FilePath& temp_dir_path) {
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner =
+ base::CreateSingleThreadTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE});
+ task_runner->PostTask(FROM_HERE, base::Bind(&UnzipHelper::UnzipImpl, this,
+ image_path, temp_dir_path));
+}
+
+void UnzipHelper::UnzipImpl(const base::FilePath& image_path,
+ const base::FilePath& temp_dir_path) {
+ if (!zip_reader_->Open(image_path) || !zip_reader_->AdvanceToNextEntry() ||
+ !zip_reader_->OpenCurrentEntryInZip()) {
+ OnError(error::kUnzipGenericError);
+ return;
+ }
+
+ if (zip_reader_->HasMore()) {
+ OnError(error::kUnzipInvalidArchive);
+ return;
+ }
+
+ // Create a new target to unzip to. The original file is opened by
+ // |zip_reader_|.
+ zip::ZipReader::EntryInfo* entry_info = zip_reader_->current_entry_info();
+
+ if (!entry_info) {
+ OnError(error::kTempDirError);
+ return;
+ }
+
+ base::FilePath out_image_path =
+ temp_dir_path.Append(entry_info->file_path().BaseName());
+ OnOpenSuccess(out_image_path);
+
+ zip_reader_->ExtractCurrentEntryToFilePathAsync(
+ out_image_path, base::Bind(&UnzipHelper::OnComplete, this),
+ base::Bind(&UnzipHelper::OnError, this, error::kUnzipGenericError),
+ base::Bind(&UnzipHelper::OnProgress, this, entry_info->original_size()));
+}
+
+void UnzipHelper::OnError(const std::string& error) {
+ owner_task_runner_->PostTask(FROM_HERE, base::Bind(failure_callback_, error));
+}
+
+void UnzipHelper::OnOpenSuccess(const base::FilePath& image_path) {
+ owner_task_runner_->PostTask(FROM_HERE,
+ base::Bind(open_callback_, image_path));
+}
+
+void UnzipHelper::OnComplete() {
+ owner_task_runner_->PostTask(FROM_HERE, complete_callback_);
+}
+
+void UnzipHelper::OnProgress(int64_t total_bytes, int64_t curr_bytes) {
+ owner_task_runner_->PostTask(
+ FROM_HERE, base::Bind(progress_callback_, total_bytes, curr_bytes));
+}
+
+} // namespace image_writer
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.h b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.h
new file mode 100644
index 00000000000..984b037c34a
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.h
@@ -0,0 +1,71 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_UNZIP_HELPER_H_
+#define CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_UNZIP_HELPER_H_
+
+#include "base/memory/ref_counted_memory.h"
+#include "base/sequenced_task_runner.h"
+#include "build/build_config.h"
+
+namespace base {
+class FilePath;
+}
+
+namespace zip {
+class ZipReader;
+}
+
+namespace extensions {
+namespace image_writer {
+
+// A helper to provide Unzip operation.
+// Currently ZipReader requires SingleThreadTaskRunner, this class is
+// responsible for running ZipReader on a SingleThreadTaskRunner. Unzip
+// should be called from sequences (|owner_task_runner_|) and all the
+// callbacks of this class is called on that task runner.
+// TODO(satorux/lazyboy): Make ZipReader Sequence friendly and remove
+// SingleThreadTaskRunner from this class. https://crbug.com/752702.
+class UnzipHelper : public base::RefCountedThreadSafe<UnzipHelper> {
+ public:
+ explicit UnzipHelper(
+ scoped_refptr<base::SequencedTaskRunner> owner_task_runner,
+ const base::Callback<void(const base::FilePath&)>& open_callback,
+ const base::Closure& complete_callback,
+ const base::Callback<void(const std::string&)>& failure_callback,
+ const base::Callback<void(int64_t, int64_t)>& progress_callback);
+
+ void Unzip(const base::FilePath& image_path,
+ const base::FilePath& temp_dir_path);
+
+ private:
+ friend class base::RefCountedThreadSafe<UnzipHelper>;
+ ~UnzipHelper();
+
+ void UnzipImpl(const base::FilePath& image_path,
+ const base::FilePath& temp_dir);
+ void OnError(const std::string& error);
+ void OnOpenSuccess(const base::FilePath& image_path);
+ void OnComplete();
+ void OnProgress(int64_t total_bytes, int64_t curr_bytes);
+
+ scoped_refptr<base::SequencedTaskRunner> owner_task_runner_;
+
+ base::Callback<void(const base::FilePath&)> open_callback_;
+ base::Closure complete_callback_;
+ base::Callback<void(const std::string&)> failure_callback_;
+ base::Callback<void(int64_t, int64_t)> progress_callback_;
+
+ // Zip reader for unzip operations. The reason for using a pointer is that we
+ // don't want to include zip_reader.h here which can mangle definitions in
+ // jni.h when included in the same file. See crbug.com/554199.
+ std::unique_ptr<zip::ZipReader> zip_reader_;
+
+ DISALLOW_COPY_AND_ASSIGN(UnzipHelper);
+};
+
+} // namespace image_writer
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_UNZIP_HELPER_H_
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc
index 4136c1a3a6f..cc9ff46059d 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc
@@ -25,20 +25,19 @@ WriteFromFileOperation::WriteFromFileOperation(
WriteFromFileOperation::~WriteFromFileOperation() {}
void WriteFromFileOperation::StartImpl() {
+ DCHECK(IsRunningInCorrectSequence());
if (!base::PathExists(image_path_) || base::DirectoryExists(image_path_)) {
DLOG(ERROR) << "Source must exist and not be a directory.";
Error(error::kImageInvalid);
return;
}
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(
- &WriteFromFileOperation::Unzip, this,
- base::Bind(
- &WriteFromFileOperation::Write, this,
- base::Bind(&WriteFromFileOperation::VerifyWrite, this,
- base::Bind(&WriteFromFileOperation::Finish, this)))));
+ PostTask(base::BindOnce(
+ &WriteFromFileOperation::Unzip, this,
+ base::Bind(
+ &WriteFromFileOperation::Write, this,
+ base::Bind(&WriteFromFileOperation::VerifyWrite, this,
+ base::Bind(&WriteFromFileOperation::Finish, this)))));
}
} // namespace image_writer
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 3c6fb916d49..2a79bf4506d 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
@@ -16,6 +16,19 @@ using testing::Lt;
using testing::AnyNumber;
using testing::AtLeast;
+namespace {
+
+#if !defined(OS_CHROMEOS)
+void SetUpImageWriteClientProgressSimulation(FakeImageWriterClient* client) {
+ std::vector<int> progress_list{0, 50, 100};
+ bool will_succeed = true;
+ client->SimulateProgressOnWrite(progress_list, will_succeed);
+ client->SimulateProgressOnVerifyWrite(progress_list, will_succeed);
+}
+#endif
+
+} // namespace
+
class ImageWriterFromFileTest : public ImageWriterUnitTestBase {
protected:
ImageWriterFromFileTest()
@@ -42,13 +55,18 @@ TEST_F(ImageWriterFromFileTest, InvalidFile) {
0,
error::kImageInvalid)).Times(1);
- op->Start();
-
- base::RunLoop().RunUntilIdle();
+ op->PostTask(base::BindOnce(&Operation::Start, op));
+ content::RunAllBlockingPoolTasksUntilIdle();
}
// Runs the entire WriteFromFile operation.
TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) {
+#if !defined(OS_CHROMEOS)
+ // Sets up simulating Operation::Progress() and Operation::Success().
+ test_utils_.RunOnUtilityClientCreation(
+ base::BindOnce(&SetUpImageWriteClientProgressSimulation));
+#endif
+
scoped_refptr<WriteFromFileOperation> op =
new WriteFromFileOperation(manager_.AsWeakPtr(),
kDummyExtensionId,
@@ -84,21 +102,8 @@ TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) {
EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(1);
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
- op->Start();
-
- base::RunLoop().RunUntilIdle();
-#if !defined(OS_CHROMEOS)
- test_utils_.GetUtilityClient()->Progress(0);
- test_utils_.GetUtilityClient()->Progress(50);
- test_utils_.GetUtilityClient()->Progress(100);
- test_utils_.GetUtilityClient()->Success();
- base::RunLoop().RunUntilIdle();
- test_utils_.GetUtilityClient()->Progress(0);
- test_utils_.GetUtilityClient()->Progress(50);
- test_utils_.GetUtilityClient()->Progress(100);
- test_utils_.GetUtilityClient()->Success();
- base::RunLoop().RunUntilIdle();
-#endif
+ op->PostTask(base::BindOnce(&Operation::Start, op));
+ content::RunAllBlockingPoolTasksUntilIdle();
}
} // namespace image_writer
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc
index bf67f50f2fc..ca700e12d9c 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc
@@ -33,28 +33,22 @@ WriteFromUrlOperation::~WriteFromUrlOperation() {
}
void WriteFromUrlOperation::StartImpl() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
-
- GetDownloadTarget(base::Bind(
- &WriteFromUrlOperation::Download,
- this,
- base::Bind(
- &WriteFromUrlOperation::VerifyDownload,
- this,
- base::Bind(
- &WriteFromUrlOperation::Unzip,
- this,
- base::Bind(&WriteFromUrlOperation::Write,
- this,
- base::Bind(&WriteFromUrlOperation::VerifyWrite,
- this,
+ DCHECK(IsRunningInCorrectSequence());
+
+ GetDownloadTarget(base::BindOnce(
+ &WriteFromUrlOperation::Download, this,
+ base::BindOnce(
+ &WriteFromUrlOperation::VerifyDownload, this,
+ base::BindOnce(
+ &WriteFromUrlOperation::Unzip, this,
+ base::Bind(&WriteFromUrlOperation::Write, this,
+ base::Bind(&WriteFromUrlOperation::VerifyWrite, this,
base::Bind(&WriteFromUrlOperation::Finish,
this)))))));
}
-void WriteFromUrlOperation::GetDownloadTarget(
- const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+void WriteFromUrlOperation::GetDownloadTarget(base::OnceClosure continuation) {
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
@@ -70,17 +64,17 @@ void WriteFromUrlOperation::GetDownloadTarget(
image_path_ = temp_dir_.GetPath().Append(file_name);
}
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
+ PostTask(std::move(continuation));
}
-void WriteFromUrlOperation::Download(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+void WriteFromUrlOperation::Download(base::OnceClosure continuation) {
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
- download_continuation_ = continuation;
+ download_continuation_ = std::move(continuation);
SetStage(image_writer_api::STAGE_DOWNLOAD);
@@ -102,7 +96,7 @@ void WriteFromUrlOperation::Download(const base::Closure& continuation) {
destination: GOOGLE_OWNED_SERVICE
}
policy {
- cookies_allowed: true
+ cookies_allowed: YES
cookies_store: "user"
setting:
"This feature cannot be disabled by settings, it can only be used "
@@ -117,11 +111,10 @@ void WriteFromUrlOperation::Download(const base::Closure& continuation) {
traffic_annotation);
url_fetcher_->SetRequestContext(request_context_);
- url_fetcher_->SaveResponseToFileAtPath(
- image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE));
+ url_fetcher_->SaveResponseToFileAtPath(image_path_, task_runner());
AddCleanUpFunction(
- base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this));
+ base::BindOnce(&WriteFromUrlOperation::DestroyUrlFetcher, this));
url_fetcher_->Start();
}
@@ -140,7 +133,7 @@ void WriteFromUrlOperation::OnURLFetchDownloadProgress(
int64_t current,
int64_t total,
int64_t current_network_bytes) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
url_fetcher_.reset(NULL);
@@ -152,22 +145,19 @@ void WriteFromUrlOperation::OnURLFetchDownloadProgress(
}
void WriteFromUrlOperation::OnURLFetchComplete(const net::URLFetcher* source) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (source->GetStatus().is_success() && source->GetResponseCode() == 200) {
SetProgress(kProgressComplete);
- download_continuation_.Run();
-
- // Remove the reference to ourselves in this closure.
- download_continuation_ = base::Closure();
+ std::move(download_continuation_).Run();
} else {
Error(error::kDownloadInterrupted);
}
}
-void WriteFromUrlOperation::VerifyDownload(const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+void WriteFromUrlOperation::VerifyDownload(base::OnceClosure continuation) {
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
@@ -175,45 +165,39 @@ void WriteFromUrlOperation::VerifyDownload(const base::Closure& continuation) {
// Skip verify if no hash.
if (hash_.empty()) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
+ PostTask(std::move(continuation));
return;
}
SetStage(image_writer_api::STAGE_VERIFYDOWNLOAD);
- GetMD5SumOfFile(
- image_path_,
- 0,
- 0,
- kProgressComplete,
- base::Bind(
- &WriteFromUrlOperation::VerifyDownloadCompare, this, continuation));
+ GetMD5SumOfFile(image_path_, 0, 0, kProgressComplete,
+ base::BindOnce(&WriteFromUrlOperation::VerifyDownloadCompare,
+ this, std::move(continuation)));
}
void WriteFromUrlOperation::VerifyDownloadCompare(
- const base::Closure& continuation,
+ base::OnceClosure continuation,
const std::string& download_hash) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ DCHECK(IsRunningInCorrectSequence());
if (download_hash != hash_) {
Error(error::kDownloadHashError);
return;
}
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&WriteFromUrlOperation::VerifyDownloadComplete, this,
- continuation));
+ PostTask(base::BindOnce(&WriteFromUrlOperation::VerifyDownloadComplete, this,
+ std::move(continuation)));
}
void WriteFromUrlOperation::VerifyDownloadComplete(
- const base::Closure& continuation) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ base::OnceClosure continuation) {
+ DCHECK(IsRunningInCorrectSequence());
if (IsCancelled()) {
return;
}
SetProgress(kProgressComplete);
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
+ PostTask(std::move(continuation));
}
} // namespace image_writer
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h
index b653bbfb70c..47c98f8e06d 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h
@@ -34,18 +34,21 @@ class WriteFromUrlOperation : public Operation, public net::URLFetcherDelegate {
void StartImpl() override;
protected:
+ friend class OperationForTest;
+ friend class WriteFromUrlOperationForTest;
+
~WriteFromUrlOperation() override;
// Sets the image_path to the correct location to download to.
- void GetDownloadTarget(const base::Closure& continuation);
+ void GetDownloadTarget(base::OnceClosure continuation);
// Downloads the |url| to the currently configured |image_path|. Should not
// be called without calling |GetDownloadTarget| first.
- void Download(const base::Closure& continuation);
+ void Download(base::OnceClosure continuation);
// Verifies the download matches |hash|. If the hash is empty, this stage is
// skipped.
- void VerifyDownload(const base::Closure& continuation);
+ void VerifyDownload(base::OnceClosure continuation);
private:
// Destroys the URLFetcher. The URLFetcher needs to be destroyed on the same
@@ -63,9 +66,9 @@ class WriteFromUrlOperation : public Operation, public net::URLFetcherDelegate {
int64_t current,
int64_t total) override;
- void VerifyDownloadCompare(const base::Closure& continuation,
+ void VerifyDownloadCompare(base::OnceClosure continuation,
const std::string& download_hash);
- void VerifyDownloadComplete(const base::Closure& continuation);
+ void VerifyDownloadComplete(base::OnceClosure continuation);
// Arguments
net::URLRequestContextGetter* request_context_;
@@ -74,7 +77,7 @@ class WriteFromUrlOperation : public Operation, public net::URLFetcherDelegate {
// Local state
std::unique_ptr<net::URLFetcher> url_fetcher_;
- base::Closure download_continuation_;
+ base::OnceClosure download_continuation_;
};
} // namespace image_writer
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 28ca08a3834..30d91fc504f 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
@@ -4,6 +4,7 @@
#include "chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h"
+#include "base/run_loop.h"
#include "base/task_scheduler/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"
@@ -27,17 +28,19 @@ const char kTestImageUrl[] = "http://localhost/test/image.zip";
typedef net::LocalHostTestURLRequestInterceptor GetInterceptor;
+} // namespace
+
// This class gives us a generic Operation with the ability to set or inspect
// the current path to the image file.
-class OperationForTest : public WriteFromUrlOperation {
+class WriteFromUrlOperationForTest : public WriteFromUrlOperation {
public:
- OperationForTest(base::WeakPtr<OperationManager> manager_,
- const ExtensionId& extension_id,
- net::URLRequestContextGetter* request_context,
- GURL url,
- const std::string& hash,
- const std::string& storage_unit_id)
- : WriteFromUrlOperation(manager_,
+ WriteFromUrlOperationForTest(base::WeakPtr<OperationManager> manager,
+ const ExtensionId& extension_id,
+ net::URLRequestContextGetter* request_context,
+ GURL url,
+ const std::string& hash,
+ const std::string& storage_unit_id)
+ : WriteFromUrlOperation(manager,
extension_id,
request_context,
url,
@@ -47,17 +50,29 @@ class OperationForTest : public WriteFromUrlOperation {
void StartImpl() override {}
- // Expose stages for testing.
+ // Following methods let us:
+ // 1. Expose stages for testing.
+ // 2. Make sure Operation methods are invoked on its task runner.
+ void Start() {
+ PostTask(base::BindOnce(&WriteFromUrlOperation::Start, this));
+ }
void GetDownloadTarget(const base::Closure& continuation) {
- WriteFromUrlOperation::GetDownloadTarget(continuation);
+ PostTask(base::BindOnce(&WriteFromUrlOperation::GetDownloadTarget, this,
+ continuation));
}
void Download(const base::Closure& continuation) {
- WriteFromUrlOperation::Download(continuation);
+ PostTask(
+ base::BindOnce(&WriteFromUrlOperation::Download, this, continuation));
}
void VerifyDownload(const base::Closure& continuation) {
- WriteFromUrlOperation::VerifyDownload(continuation);
+ PostTask(base::BindOnce(&WriteFromUrlOperation::VerifyDownload, this,
+ continuation));
+ }
+
+ void Cancel() {
+ PostTask(base::BindOnce(&WriteFromUrlOperation::Cancel, this));
}
// Helpers to set-up state for intermediate stages.
@@ -68,7 +83,7 @@ class OperationForTest : public WriteFromUrlOperation {
base::FilePath GetImagePath() { return image_path_; }
private:
- ~OperationForTest() override {}
+ ~WriteFromUrlOperationForTest() override {}
};
class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
@@ -92,15 +107,14 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
ImageWriterUnitTestBase::TearDown();
}
- scoped_refptr<OperationForTest> CreateOperation(const GURL& url,
- const std::string& hash) {
- scoped_refptr<OperationForTest> operation(
- new OperationForTest(manager_.AsWeakPtr(),
- kDummyExtensionId,
- test_profile_.GetRequestContext(),
- url,
- hash,
- test_utils_.GetDevicePath().AsUTF8Unsafe()));
+ scoped_refptr<WriteFromUrlOperationForTest> CreateOperation(
+ const GURL& url,
+ const std::string& hash) {
+ scoped_refptr<WriteFromUrlOperationForTest> operation(
+ new WriteFromUrlOperationForTest(
+ manager_.AsWeakPtr(), kDummyExtensionId,
+ test_profile_.GetRequestContext(), url, hash,
+ test_utils_.GetDevicePath().AsUTF8Unsafe()));
operation->Start();
return operation;
}
@@ -112,22 +126,27 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
};
TEST_F(ImageWriterWriteFromUrlOperationTest, SelectTargetWithoutExtension) {
- scoped_refptr<OperationForTest> operation =
+ scoped_refptr<WriteFromUrlOperationForTest> operation =
CreateOperation(GURL("http://localhost/foo/bar"), "");
- operation->GetDownloadTarget(base::Bind(&base::DoNothing));
+ base::RunLoop run_loop;
+ operation->GetDownloadTarget(run_loop.QuitClosure());
+ run_loop.Run();
EXPECT_EQ(FILE_PATH_LITERAL("bar"),
operation->GetImagePath().BaseName().value());
operation->Cancel();
+ content::RunAllBlockingPoolTasksUntilIdle();
}
TEST_F(ImageWriterWriteFromUrlOperationTest, SelectTargetWithExtension) {
- scoped_refptr<OperationForTest> operation =
+ scoped_refptr<WriteFromUrlOperationForTest> operation =
CreateOperation(GURL("http://localhost/foo/bar.zip"), "");
- operation->GetDownloadTarget(base::Bind(&base::DoNothing));
+ base::RunLoop run_loop;
+ operation->GetDownloadTarget(run_loop.QuitClosure());
+ run_loop.Run();
EXPECT_EQ(FILE_PATH_LITERAL("bar.zip"),
operation->GetImagePath().BaseName().value());
@@ -140,9 +159,8 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
// message queues while waiting for IO, thus we have to run until the
// operation completes.
base::RunLoop runloop;
- base::Closure quit_closure = runloop.QuitClosure();
base::FilePath download_target_path;
- scoped_refptr<OperationForTest> operation =
+ scoped_refptr<WriteFromUrlOperationForTest> operation =
CreateOperation(GURL(kTestImageUrl), "");
EXPECT_TRUE(base::CreateTemporaryFileInDir(test_utils_.GetTempDir(),
@@ -162,11 +180,9 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
OnProgress(kDummyExtensionId, image_writer_api::STAGE_DOWNLOAD, 100))
.Times(AnyNumber());
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::Download, operation, quit_closure));
-
+ operation->Download(runloop.QuitClosure());
runloop.Run();
+ content::RunAllBlockingPoolTasksUntilIdle();
EXPECT_TRUE(base::ContentsEqual(test_utils_.GetImagePath(),
operation->GetImagePath()));
@@ -183,7 +199,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) {
base::MD5Sum(data_buffer.get(), kTestFileSize, &expected_digest);
std::string expected_hash = base::MD5DigestToBase16(expected_digest);
- scoped_refptr<OperationForTest> operation =
+ scoped_refptr<WriteFromUrlOperationForTest> operation =
CreateOperation(GURL(""), expected_hash);
EXPECT_CALL(
@@ -200,17 +216,14 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) {
100)).Times(AtLeast(1));
operation->SetImagePath(test_utils_.GetImagePath());
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&OperationForTest::VerifyDownload, operation,
- base::Bind(&base::DoNothing)));
-
- base::RunLoop().RunUntilIdle();
+ {
+ base::RunLoop run_loop;
+ operation->VerifyDownload(run_loop.QuitClosure());
+ run_loop.Run();
+ }
operation->Cancel();
}
-} // namespace
-
} // namespace image_writer
} // namespace extensions
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 cbc890742ef..6b60ecd81aa 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
@@ -34,11 +34,10 @@ ImeObserver::ImeObserver(const std::string& extension_id, Profile* profile)
: extension_id_(extension_id), profile_(profile) {}
void ImeObserver::OnActivate(const std::string& component_id) {
- if (extension_id_.empty() ||
- !HasListener(input_ime::OnActivate::kEventName)) {
- LOG(ERROR) << "Can't send onActivate event to \"" << extension_id_ << "\"";
+ // Don't check whether the extension listens on onActivate event here.
+ // Send onActivate event to give the IME a chance to add their listeners.
+ if (extension_id_.empty())
return;
- }
std::unique_ptr<base::ListValue> args(input_ime::OnActivate::Create(
component_id, input_ime::ParseScreenType(GetCurrentScreenType())));
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 2eb23292328..32151e988b1 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
@@ -194,26 +194,33 @@ class ImeObserverChromeOS : public ui::ImeObserver {
extensions::events::HistogramValue histogram_value,
const std::string& event_name,
std::unique_ptr<base::ListValue> args) override {
- if (event_name != input_ime::OnActivate::kEventName) {
- // For suspended IME extension (e.g. XKB extension), don't awake it by IME
- // events except onActivate. The IME extension should be awake by other
- // events (e.g. runtime.onMessage) from its other pages.
- // This is to save memory for steady state Chrome OS on which the users
- // don't want any IME features.
- extensions::ExtensionSystem* extension_system =
- extensions::ExtensionSystem::Get(profile_);
- if (extension_system) {
- const extensions::Extension* extension =
- extension_system->extension_service()->GetExtensionById(
- extension_id_, false /* include_disabled */);
- if (!extension)
- return;
- extensions::ProcessManager* process_manager =
- extensions::ProcessManager::Get(profile_);
- if (extensions::BackgroundInfo::HasBackgroundPage(extension) &&
- !process_manager->GetBackgroundHostForExtension(extension_id_)) {
- return;
- }
+ if (event_name == input_ime::OnActivate::kEventName) {
+ // Send onActivate event regardless of it's listened by the IME.
+ auto event = base::MakeUnique<extensions::Event>(
+ histogram_value, event_name, std::move(args), profile_);
+ extensions::EventRouter::Get(profile_)->DispatchEventWithLazyListener(
+ extension_id_, std::move(event));
+ return;
+ }
+
+ // For suspended IME extension (e.g. XKB extension), don't awake it by IME
+ // events except onActivate. The IME extension should be awake by other
+ // events (e.g. runtime.onMessage) from its other pages.
+ // This is to save memory for steady state Chrome OS on which the users
+ // don't want any IME features.
+ extensions::ExtensionSystem* extension_system =
+ extensions::ExtensionSystem::Get(profile_);
+ if (extension_system) {
+ const extensions::Extension* extension =
+ extension_system->extension_service()->GetExtensionById(
+ extension_id_, false /* include_disabled */);
+ if (!extension)
+ return;
+ extensions::ProcessManager* process_manager =
+ extensions::ProcessManager::Get(profile_);
+ if (extensions::BackgroundInfo::HasBackgroundPage(extension) &&
+ !process_manager->GetBackgroundHostForExtension(extension_id_)) {
+ return;
}
}
diff --git a/chromium/chrome/browser/extensions/api/launcher_page/OWNERS b/chromium/chrome/browser/extensions/api/launcher_page/OWNERS
index 16d36d99416..ed54f09c40c 100644
--- a/chromium/chrome/browser/extensions/api/launcher_page/OWNERS
+++ b/chromium/chrome/browser/extensions/api/launcher_page/OWNERS
@@ -1,2 +1,2 @@
calamity@chromium.org
-mgiuca@chromium.org
+khmel@chromium.org
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 8fd3eff8255..73fd31913c3 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
@@ -36,7 +36,7 @@
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
-#include "extensions/common/constants.h"
+#include "extensions/common/disable_reason.h"
#include "extensions/common/extension.h"
namespace {
@@ -303,7 +303,7 @@ void ChromeManagementAPIDelegate::EnableExtension(
void ChromeManagementAPIDelegate::DisableExtension(
content::BrowserContext* context,
const std::string& extension_id,
- extensions::Extension::DisableReason disable_reason) const {
+ extensions::disable_reason::DisableReason disable_reason) const {
extensions::ExtensionSystem::Get(context)
->extension_service()
->DisableExtension(extension_id, disable_reason);
diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h
index dec94239580..db1ed8157e1 100644
--- a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h
+++ b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h
@@ -53,7 +53,7 @@ class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate {
void DisableExtension(
content::BrowserContext* context,
const std::string& extension_id,
- extensions::Extension::DisableReason disable_reason) const override;
+ extensions::disable_reason::DisableReason disable_reason) const override;
bool UninstallExtension(content::BrowserContext* context,
const std::string& transient_extension_id,
extensions::UninstallReason reason,
diff --git a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc
index 75c9f026141..b6cbae05ebe 100644
--- a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc
@@ -26,7 +26,6 @@
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/notification_types.h"
-#include "extensions/common/test_util.h"
#include "extensions/test/extension_test_message_listener.h"
namespace keys = extension_management_api_constants;
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 59d0593e072..40f4701600e 100644
--- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc
@@ -24,11 +24,12 @@
#include "extensions/browser/extension_system.h"
#include "extensions/browser/management_policy.h"
#include "extensions/browser/test_management_policy.h"
+#include "extensions/common/api/management.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension.h"
+#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/permissions/permission_set.h"
-#include "extensions/common/test_util.h"
namespace extensions {
@@ -107,7 +108,7 @@ void ManagementApiUnitTest::TearDown() {
// Test the basic parts of management.setEnabled.
TEST_F(ManagementApiUnitTest, ManagementSetEnabled) {
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
service()->AddExtension(extension.get());
std::string extension_id = extension->id();
scoped_refptr<ManagementSetEnabledFunction> function(
@@ -149,7 +150,7 @@ TEST_F(ManagementApiUnitTest, ManagementSetEnabled) {
// Tests management.uninstall.
TEST_F(ManagementApiUnitTest, ManagementUninstall) {
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
service()->AddExtension(extension.get());
std::string extension_id = extension->id();
@@ -225,7 +226,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstall) {
// Tests uninstalling a blacklisted extension via management.uninstall.
TEST_F(ManagementApiUnitTest, ManagementUninstallBlacklisted) {
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
service()->AddExtension(extension.get());
std::string id = extension->id();
@@ -244,7 +245,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstallBlacklisted) {
}
TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlacklisted) {
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
service()->AddExtension(extension.get());
std::string id = extension->id();
@@ -277,6 +278,78 @@ TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlacklisted) {
}
}
+TEST_F(ManagementApiUnitTest, ExtensionInfo_MayEnable) {
+ using ExtensionInfo = api::management::ExtensionInfo;
+
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
+ service()->AddExtension(extension.get());
+
+ const std::string args =
+ base::StringPrintf("[\"%s\"]", extension->id().c_str());
+ scoped_refptr<UIThreadExtensionFunction> function;
+
+ // Initially the extension should show as enabled.
+ EXPECT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
+ {
+ function = new ManagementGetFunction();
+ std::unique_ptr<base::Value> value(
+ extension_function_test_utils::RunFunctionAndReturnSingleResult(
+ function.get(), args, browser()));
+ ASSERT_TRUE(value);
+ std::unique_ptr<ExtensionInfo> info = ExtensionInfo::FromValue(*value);
+ ASSERT_TRUE(info);
+ EXPECT_TRUE(info->enabled);
+ // |may_enable| is only returned for extensions which are not enabled.
+ EXPECT_FALSE(info->may_enable.get());
+ }
+
+ // Simulate blacklisting the extension and verify that the extension shows as
+ // disabled with a false value of |may_enable|.
+ ManagementPolicy* policy =
+ ExtensionSystem::Get(profile())->management_policy();
+ policy->UnregisterAllProviders();
+ TestManagementPolicyProvider provider(
+ TestManagementPolicyProvider::PROHIBIT_LOAD);
+ policy->RegisterProvider(&provider);
+ service()->CheckManagementPolicy();
+ EXPECT_TRUE(registry()->disabled_extensions().Contains(extension->id()));
+ {
+ function = new ManagementGetFunction();
+ std::unique_ptr<base::Value> value(
+ extension_function_test_utils::RunFunctionAndReturnSingleResult(
+ function.get(), args, browser()));
+ ASSERT_TRUE(value);
+ std::unique_ptr<ExtensionInfo> info = ExtensionInfo::FromValue(*value);
+ ASSERT_TRUE(info);
+ EXPECT_FALSE(info->enabled);
+ ASSERT_TRUE(info->may_enable.get());
+ EXPECT_FALSE(*(info->may_enable));
+ }
+
+ // Re-enable the extension.
+ policy->UnregisterAllProviders();
+ service()->CheckManagementPolicy();
+ EXPECT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
+
+ // Disable the extension with a normal user action. Verify the extension shows
+ // as disabled with |may_enable| as true.
+ service()->DisableExtension(extension->id(),
+ disable_reason::DISABLE_USER_ACTION);
+ EXPECT_TRUE(registry()->disabled_extensions().Contains(extension->id()));
+ {
+ function = new ManagementGetFunction();
+ std::unique_ptr<base::Value> value(
+ extension_function_test_utils::RunFunctionAndReturnSingleResult(
+ function.get(), args, browser()));
+ ASSERT_TRUE(value);
+ std::unique_ptr<ExtensionInfo> info = ExtensionInfo::FromValue(*value);
+ ASSERT_TRUE(info);
+ EXPECT_FALSE(info->enabled);
+ ASSERT_TRUE(info->may_enable.get());
+ EXPECT_TRUE(*(info->may_enable));
+ }
+}
+
// Tests enabling an extension via management API after it was disabled due to
// permission increase.
TEST_F(ManagementApiUnitTest, SetEnabledAfterIncreasedPermissions) {
diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc b/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc
index 9d210dae43b..b7ac56b46a7 100644
--- a/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc
+++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc
@@ -167,7 +167,7 @@ void MDnsAPI::OnDnsSdEvent(const std::string& service_type,
}
mdns::MDnsService mdns_service;
mdns_service.service_name = service.service_name;
- mdns_service.service_host_port = service.service_host_port;
+ mdns_service.service_host_port = service.service_host_port.ToString();
mdns_service.ip_address = service.ip_address;
mdns_service.service_data = service.service_data;
args.push_back(std::move(mdns_service));
diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc
index 6a6a648c079..a6ada3fa9e3 100644
--- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc
+++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc
@@ -170,24 +170,21 @@ base::ListValue* ConstructFileSystemList(
// Send the file system id so the renderer can create a valid FileSystem
// object.
- file_system_dict_value->SetStringWithoutPathExpansion(
- "fsid", filesystems[i].fsid);
+ file_system_dict_value->SetKey("fsid", base::Value(filesystems[i].fsid));
- file_system_dict_value->SetStringWithoutPathExpansion(
- kNameKey, filesystems[i].name);
- file_system_dict_value->SetStringWithoutPathExpansion(
+ file_system_dict_value->SetKey(kNameKey, base::Value(filesystems[i].name));
+ file_system_dict_value->SetKey(
kGalleryIdKey,
- base::Uint64ToString(filesystems[i].pref_id));
+ base::Value(base::Uint64ToString(filesystems[i].pref_id)));
if (!filesystems[i].transient_device_id.empty()) {
- file_system_dict_value->SetStringWithoutPathExpansion(
- kDeviceIdKey, filesystems[i].transient_device_id);
+ file_system_dict_value->SetKey(
+ kDeviceIdKey, base::Value(filesystems[i].transient_device_id));
}
- file_system_dict_value->SetBooleanWithoutPathExpansion(
- kIsRemovableKey, filesystems[i].removable);
- file_system_dict_value->SetBooleanWithoutPathExpansion(
- kIsMediaDeviceKey, filesystems[i].media_device);
- file_system_dict_value->SetBooleanWithoutPathExpansion(
- kIsAvailableKey, true);
+ file_system_dict_value->SetKey(kIsRemovableKey,
+ base::Value(filesystems[i].removable));
+ file_system_dict_value->SetKey(kIsMediaDeviceKey,
+ base::Value(filesystems[i].media_device));
+ file_system_dict_value->SetKey(kIsAvailableKey, base::Value(true));
list->Append(std::move(file_system_dict_value));
@@ -220,7 +217,7 @@ class SelectDirectoryDialog : public ui::SelectFileDialog::Listener,
: web_contents_(web_contents),
callback_(callback) {
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_contents));
+ this, std::make_unique<ChromeSelectFilePolicy>(web_contents));
}
void Show(const base::FilePath& default_path) {
@@ -586,7 +583,7 @@ void MediaGalleriesAddUserSelectedFolderFunction::ReturnGalleriesAndId(
}
std::unique_ptr<base::DictionaryValue> results(new base::DictionaryValue);
results->SetWithoutPathExpansion("mediaFileSystems", std::move(list));
- results->SetIntegerWithoutPathExpansion("selectedFileSystemIndex", index);
+ results->SetKey("selectedFileSystemIndex", base::Value(index));
SetResult(std::move(results));
SendResponse(true);
}
diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc
index c47f6d8146e..a37f3e39686 100644
--- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc
@@ -11,6 +11,7 @@
#include "base/json/json_writer.h"
#include "base/numerics/safe_conversions.h"
#include "base/path_service.h"
+#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/test_timeouts.h"
diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc
new file mode 100644
index 00000000000..d564de69c3d
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc
@@ -0,0 +1,151 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h"
+
+#include "base/callback.h"
+#include "base/logging.h"
+#include "base/memory/ptr_util.h"
+#include "build/build_config.h"
+#include "chrome/browser/extensions/api/messaging/incognito_connectability.h"
+#include "chrome/browser/extensions/api/messaging/native_message_port.h"
+#include "chrome/browser/extensions/extension_tab_util.h"
+#include "chrome/browser/profiles/profile.h"
+#include "components/prefs/pref_service.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/messaging/extension_message_port.h"
+#include "extensions/browser/api/messaging/native_message_host.h"
+#include "extensions/browser/extension_api_frame_id_map.h"
+#include "extensions/browser/pref_names.h"
+#include "extensions/common/api/messaging/port_id.h"
+#include "extensions/common/extension.h"
+#include "ui/gfx/native_widget_types.h"
+#include "url/gurl.h"
+
+namespace extensions {
+
+ChromeMessagingDelegate::ChromeMessagingDelegate() = default;
+ChromeMessagingDelegate::~ChromeMessagingDelegate() = default;
+
+MessagingDelegate::PolicyPermission
+ChromeMessagingDelegate::IsNativeMessagingHostAllowed(
+ content::BrowserContext* browser_context,
+ const std::string& native_host_name) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ PrefService* pref_service =
+ Profile::FromBrowserContext(browser_context)->GetPrefs();
+
+ PolicyPermission allow_result = PolicyPermission::ALLOW_ALL;
+ if (pref_service->IsManagedPreference(
+ pref_names::kNativeMessagingUserLevelHosts)) {
+ if (!pref_service->GetBoolean(pref_names::kNativeMessagingUserLevelHosts))
+ allow_result = PolicyPermission::ALLOW_SYSTEM_ONLY;
+ }
+
+ // All native messaging hosts are allowed if there is no blacklist.
+ if (!pref_service->IsManagedPreference(pref_names::kNativeMessagingBlacklist))
+ return allow_result;
+ const base::ListValue* blacklist =
+ pref_service->GetList(pref_names::kNativeMessagingBlacklist);
+ if (!blacklist)
+ return allow_result;
+
+ // Check if the name or the wildcard is in the blacklist.
+ base::Value name_value(native_host_name);
+ base::Value wildcard_value("*");
+ if (blacklist->Find(name_value) == blacklist->end() &&
+ blacklist->Find(wildcard_value) == blacklist->end()) {
+ return allow_result;
+ }
+
+ // The native messaging host is blacklisted. Check the whitelist.
+ if (pref_service->IsManagedPreference(
+ pref_names::kNativeMessagingWhitelist)) {
+ const base::ListValue* whitelist =
+ pref_service->GetList(pref_names::kNativeMessagingWhitelist);
+ if (whitelist && whitelist->Find(name_value) != whitelist->end())
+ return allow_result;
+ }
+
+ return PolicyPermission::DISALLOW;
+}
+
+std::unique_ptr<base::DictionaryValue> ChromeMessagingDelegate::MaybeGetTabInfo(
+ content::WebContents* web_contents) {
+ // Add info about the opener's tab (if it was a tab).
+ if (web_contents && ExtensionTabUtil::GetTabId(web_contents) >= 0) {
+ // Only the tab id is useful to platform apps for internal use. The
+ // unnecessary bits will be stripped out in
+ // MessagingBindings::DispatchOnConnect().
+ return ExtensionTabUtil::CreateTabObject(web_contents)->ToValue();
+ }
+ return nullptr;
+}
+
+content::WebContents* ChromeMessagingDelegate::GetWebContentsByTabId(
+ content::BrowserContext* browser_context,
+ int tab_id) {
+ content::WebContents* contents = nullptr;
+ if (!ExtensionTabUtil::GetTabById(tab_id, browser_context,
+ /*incognito_enabled=*/true, nullptr,
+ nullptr, &contents, nullptr)) {
+ return nullptr;
+ }
+ return contents;
+}
+
+std::unique_ptr<MessagePort> ChromeMessagingDelegate::CreateReceiverForTab(
+ base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
+ const std::string& extension_id,
+ const PortId& receiver_port_id,
+ content::WebContents* receiver_contents,
+ int receiver_frame_id) {
+ // Frame ID -1 is every frame in the tab.
+ bool include_child_frames = receiver_frame_id == -1;
+ content::RenderFrameHost* receiver_rfh =
+ include_child_frames ? receiver_contents->GetMainFrame()
+ : ExtensionApiFrameIdMap::GetRenderFrameHostById(
+ receiver_contents, receiver_frame_id);
+ if (!receiver_rfh)
+ return nullptr;
+
+ return base::MakeUnique<ExtensionMessagePort>(
+ channel_delegate, receiver_port_id, extension_id, receiver_rfh,
+ include_child_frames);
+}
+
+std::unique_ptr<MessagePort>
+ChromeMessagingDelegate::CreateReceiverForNativeApp(
+ base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
+ content::RenderFrameHost* source,
+ const std::string& extension_id,
+ const PortId& receiver_port_id,
+ const std::string& native_app_name,
+ bool allow_user_level,
+ std::string* error_out) {
+ DCHECK(error_out);
+ gfx::NativeView native_view = source ? source->GetNativeView() : nullptr;
+ std::unique_ptr<NativeMessageHost> native_host = NativeMessageHost::Create(
+ native_view, extension_id, native_app_name, allow_user_level, error_out);
+ if (!native_host.get())
+ return nullptr;
+ return base::MakeUnique<NativeMessagePort>(channel_delegate, receiver_port_id,
+ std::move(native_host));
+}
+
+void ChromeMessagingDelegate::QueryIncognitoConnectability(
+ content::BrowserContext* context,
+ const Extension* target_extension,
+ content::WebContents* source_contents,
+ const GURL& source_url,
+ const base::Callback<void(bool)>& callback) {
+ DCHECK(context->IsOffTheRecord());
+ IncognitoConnectability::Get(context)->Query(
+ target_extension, source_contents, source_url, callback);
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h
new file mode 100644
index 00000000000..047341694d1
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h
@@ -0,0 +1,54 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_CHROME_MESSAGING_DELEGATE_H_
+#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_CHROME_MESSAGING_DELEGATE_H_
+
+#include "extensions/browser/api/messaging/messaging_delegate.h"
+
+namespace extensions {
+
+// Helper class for Chrome-specific features of the extension messaging API.
+class ChromeMessagingDelegate : public MessagingDelegate {
+ public:
+ ChromeMessagingDelegate();
+ ~ChromeMessagingDelegate() override;
+
+ // MessagingDelegate:
+ PolicyPermission IsNativeMessagingHostAllowed(
+ content::BrowserContext* browser_context,
+ const std::string& native_host_name) override;
+ std::unique_ptr<base::DictionaryValue> MaybeGetTabInfo(
+ content::WebContents* web_contents) override;
+ content::WebContents* GetWebContentsByTabId(
+ content::BrowserContext* browser_context,
+ int tab_id) override;
+ std::unique_ptr<MessagePort> CreateReceiverForTab(
+ base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
+ const std::string& extension_id,
+ const PortId& receiver_port_id,
+ content::WebContents* receiver_contents,
+ int receiver_frame_id) override;
+ std::unique_ptr<MessagePort> CreateReceiverForNativeApp(
+ base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
+ content::RenderFrameHost* source,
+ const std::string& extension_id,
+ const PortId& receiver_port_id,
+ const std::string& native_app_name,
+ bool allow_user_level,
+ std::string* error_out) override;
+ void QueryIncognitoConnectability(
+ content::BrowserContext* context,
+ const Extension* extension,
+ content::WebContents* web_contents,
+ const GURL& url,
+ const base::Callback<void(bool)>& callback) override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ChromeMessagingDelegate);
+};
+
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_CHROME_MESSAGING_DELEGATE_H_
diff --git a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc
deleted file mode 100644
index 7252e2fae25..00000000000
--- a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc
+++ /dev/null
@@ -1,309 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/messaging/extension_message_port.h"
-
-#include "base/memory/ptr_util.h"
-#include "base/scoped_observer.h"
-#include "content/public/browser/interstitial_page.h"
-#include "content/public/browser/navigation_handle.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/render_process_host.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_contents_observer.h"
-#include "extensions/browser/extension_host.h"
-#include "extensions/browser/process_manager.h"
-#include "extensions/browser/process_manager_observer.h"
-#include "extensions/common/extension_messages.h"
-#include "extensions/common/manifest_handlers/background_info.h"
-
-namespace extensions {
-
-const char kReceivingEndDoesntExistError[] =
- "Could not establish connection. Receiving end does not exist.";
-
-// Helper class to detect when frames are destroyed.
-class ExtensionMessagePort::FrameTracker : public content::WebContentsObserver,
- public ProcessManagerObserver {
- public:
- explicit FrameTracker(ExtensionMessagePort* port)
- : pm_observer_(this), port_(port), interstitial_frame_(nullptr) {}
- ~FrameTracker() override {}
-
- void TrackExtensionProcessFrames() {
- pm_observer_.Add(ProcessManager::Get(port_->browser_context_));
- }
-
- void TrackTabFrames(content::WebContents* tab) {
- Observe(tab);
- }
-
- void TrackInterstitialFrame(content::WebContents* tab,
- content::RenderFrameHost* interstitial_frame) {
- // |tab| should never be nullptr, because an interstitial's lifetime is
- // tied to a tab. This is a CHECK, not a DCHECK because we really need an
- // observer subject to detect frame removal (via DidDetachInterstitialPage).
- CHECK(tab);
- DCHECK(interstitial_frame);
- interstitial_frame_ = interstitial_frame;
- Observe(tab);
- }
-
- private:
- // content::WebContentsObserver overrides:
- void RenderFrameDeleted(content::RenderFrameHost* render_frame_host)
- override {
- port_->UnregisterFrame(render_frame_host);
- }
-
- void DidFinishNavigation(
- content::NavigationHandle* navigation_handle) override {
- if (navigation_handle->HasCommitted() &&
- !navigation_handle->IsSameDocument()) {
- port_->UnregisterFrame(navigation_handle->GetRenderFrameHost());
- }
- }
-
- void DidDetachInterstitialPage() override {
- if (interstitial_frame_)
- port_->UnregisterFrame(interstitial_frame_);
- }
-
- // extensions::ProcessManagerObserver overrides:
- void OnExtensionFrameUnregistered(
- const std::string& extension_id,
- content::RenderFrameHost* render_frame_host) override {
- if (extension_id == port_->extension_id_)
- port_->UnregisterFrame(render_frame_host);
- }
-
- ScopedObserver<ProcessManager, ProcessManagerObserver> pm_observer_;
- ExtensionMessagePort* port_; // Owns this FrameTracker.
-
- // Set to the main frame of an interstitial if we are tracking an interstitial
- // page, because RenderFrameDeleted is never triggered for frames in an
- // interstitial (and we only support tracking the interstitial's main frame).
- content::RenderFrameHost* interstitial_frame_;
-
- DISALLOW_COPY_AND_ASSIGN(FrameTracker);
-};
-
-ExtensionMessagePort::ExtensionMessagePort(
- base::WeakPtr<MessageService> message_service,
- const PortId& port_id,
- const std::string& extension_id,
- content::RenderProcessHost* extension_process)
- : weak_message_service_(message_service),
- port_id_(port_id),
- extension_id_(extension_id),
- browser_context_(extension_process->GetBrowserContext()),
- extension_process_(extension_process),
- did_create_port_(false),
- background_host_ptr_(nullptr),
- frame_tracker_(new FrameTracker(this)) {
- auto all_hosts = ProcessManager::Get(browser_context_)
- ->GetRenderFrameHostsForExtension(extension_id);
- for (content::RenderFrameHost* rfh : all_hosts)
- RegisterFrame(rfh);
-
- frame_tracker_->TrackExtensionProcessFrames();
-}
-
-ExtensionMessagePort::ExtensionMessagePort(
- base::WeakPtr<MessageService> message_service,
- const PortId& port_id,
- const std::string& extension_id,
- content::RenderFrameHost* rfh,
- bool include_child_frames)
- : weak_message_service_(message_service),
- port_id_(port_id),
- extension_id_(extension_id),
- browser_context_(rfh->GetProcess()->GetBrowserContext()),
- extension_process_(nullptr),
- did_create_port_(false),
- background_host_ptr_(nullptr),
- frame_tracker_(new FrameTracker(this)) {
- content::WebContents* tab = content::WebContents::FromRenderFrameHost(rfh);
- if (!tab) {
- content::InterstitialPage* interstitial =
- content::InterstitialPage::FromRenderFrameHost(rfh);
- // A RenderFrameHost must be hosted in a WebContents or InterstitialPage.
- CHECK(interstitial);
-
- // Only the main frame of an interstitial is supported, because frames in
- // the interstitial do not trigger RenderFrameCreated / RenderFrameDeleted
- // on WebContentObservers. Consequently, (1) we cannot detect removal of
- // RenderFrameHosts, and (2) even if the RenderFrameDeleted is propagated,
- // then WebContentsObserverSanityChecker triggers a CHECK when it detects
- // frame notifications without a corresponding RenderFrameCreated.
- if (!rfh->GetParent()) {
- // It is safe to pass the interstitial's WebContents here because we only
- // use it to observe DidDetachInterstitialPage.
- frame_tracker_->TrackInterstitialFrame(interstitial->GetWebContents(),
- rfh);
- RegisterFrame(rfh);
- }
- return;
- }
-
- frame_tracker_->TrackTabFrames(tab);
- if (include_child_frames) {
- tab->ForEachFrame(base::Bind(&ExtensionMessagePort::RegisterFrame,
- base::Unretained(this)));
- } else {
- RegisterFrame(rfh);
- }
-}
-
-ExtensionMessagePort::~ExtensionMessagePort() {}
-
-void ExtensionMessagePort::RevalidatePort() {
- // Only opener ports need to be revalidated, because these are created in the
- // renderer before the browser knows about them.
- DCHECK(!extension_process_);
- DCHECK_LE(frames_.size(), 1U);
-
- // If the port is unknown, the renderer will respond by closing the port.
- SendToPort(base::MakeUnique<ExtensionMsg_ValidateMessagePort>(
- MSG_ROUTING_NONE, port_id_));
-}
-
-void ExtensionMessagePort::RemoveCommonFrames(const MessagePort& port) {
- // Avoid overlap in the set of frames to make sure that it does not matter
- // when UnregisterFrame is called.
- for (std::set<content::RenderFrameHost*>::iterator it = frames_.begin();
- it != frames_.end(); ) {
- if (port.HasFrame(*it)) {
- frames_.erase(it++);
- } else {
- ++it;
- }
- }
-}
-
-bool ExtensionMessagePort::HasFrame(content::RenderFrameHost* rfh) const {
- return frames_.find(rfh) != frames_.end();
-}
-
-bool ExtensionMessagePort::IsValidPort() {
- return !frames_.empty();
-}
-
-void ExtensionMessagePort::DispatchOnConnect(
- const std::string& channel_name,
- std::unique_ptr<base::DictionaryValue> source_tab,
- int source_frame_id,
- int guest_process_id,
- int guest_render_frame_routing_id,
- const std::string& source_extension_id,
- const std::string& target_extension_id,
- const GURL& source_url,
- const std::string& tls_channel_id) {
- ExtensionMsg_TabConnectionInfo source;
- if (source_tab)
- source.tab.Swap(source_tab.get());
- source.frame_id = source_frame_id;
-
- ExtensionMsg_ExternalConnectionInfo info;
- info.target_id = target_extension_id;
- info.source_id = source_extension_id;
- info.source_url = source_url;
- info.guest_process_id = guest_process_id;
- info.guest_render_frame_routing_id = guest_render_frame_routing_id;
-
- SendToPort(base::MakeUnique<ExtensionMsg_DispatchOnConnect>(
- MSG_ROUTING_NONE, port_id_, channel_name, source, info, tls_channel_id));
-}
-
-void ExtensionMessagePort::DispatchOnDisconnect(
- const std::string& error_message) {
- SendToPort(base::MakeUnique<ExtensionMsg_DispatchOnDisconnect>(
- MSG_ROUTING_NONE, port_id_, error_message));
-}
-
-void ExtensionMessagePort::DispatchOnMessage(const Message& message) {
- SendToPort(base::MakeUnique<ExtensionMsg_DeliverMessage>(
- MSG_ROUTING_NONE, port_id_, message));
-}
-
-void ExtensionMessagePort::IncrementLazyKeepaliveCount() {
- ProcessManager* pm = ProcessManager::Get(browser_context_);
- ExtensionHost* host = pm->GetBackgroundHostForExtension(extension_id_);
- if (host && BackgroundInfo::HasLazyBackgroundPage(host->extension()))
- pm->IncrementLazyKeepaliveCount(host->extension());
-
- // Keep track of the background host, so when we decrement, we only do so if
- // the host hasn't reloaded.
- background_host_ptr_ = host;
-}
-
-void ExtensionMessagePort::DecrementLazyKeepaliveCount() {
- ProcessManager* pm = ProcessManager::Get(browser_context_);
- ExtensionHost* host = pm->GetBackgroundHostForExtension(extension_id_);
- if (host && host == background_host_ptr_)
- pm->DecrementLazyKeepaliveCount(host->extension());
-}
-
-void ExtensionMessagePort::OpenPort(int process_id, int routing_id) {
- DCHECK(routing_id != MSG_ROUTING_NONE || extension_process_);
-
- did_create_port_ = true;
-}
-
-void ExtensionMessagePort::ClosePort(int process_id, int routing_id) {
- if (routing_id == MSG_ROUTING_NONE) {
- // The only non-frame-specific message is the response to an unhandled
- // onConnect event in the extension process.
- DCHECK(extension_process_);
- frames_.clear();
- CloseChannel();
- return;
- }
-
- content::RenderFrameHost* rfh =
- content::RenderFrameHost::FromID(process_id, routing_id);
- if (rfh)
- UnregisterFrame(rfh);
-}
-
-void ExtensionMessagePort::CloseChannel() {
- std::string error_message = did_create_port_ ? std::string() :
- kReceivingEndDoesntExistError;
- if (weak_message_service_)
- weak_message_service_->CloseChannel(port_id_, error_message);
-}
-
-void ExtensionMessagePort::RegisterFrame(content::RenderFrameHost* rfh) {
- // Only register a RenderFrameHost whose RenderFrame has been created, to
- // ensure that we are notified of frame destruction. Without this check,
- // |frames_| can eventually contain a stale pointer because RenderFrameDeleted
- // is not triggered for |rfh|.
- if (rfh->IsRenderFrameLive())
- frames_.insert(rfh);
-}
-
-void ExtensionMessagePort::UnregisterFrame(content::RenderFrameHost* rfh) {
- if (frames_.erase(rfh) != 0 && frames_.empty())
- CloseChannel();
-}
-
-void ExtensionMessagePort::SendToPort(std::unique_ptr<IPC::Message> msg) {
- DCHECK_GT(frames_.size(), 0UL);
- if (extension_process_) {
- // All extension frames reside in the same process, so we can just send a
- // single IPC message to the extension process as an optimization.
- // The frame tracking is then only used to make sure that the port gets
- // closed when all frames have closed / reloaded.
- msg->set_routing_id(MSG_ROUTING_CONTROL);
- extension_process_->Send(msg.release());
- return;
- }
- for (content::RenderFrameHost* rfh : frames_) {
- IPC::Message* msg_copy = new IPC::Message(*msg);
- msg_copy->set_routing_id(rfh->GetRoutingID());
- rfh->Send(msg_copy);
- }
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h
deleted file mode 100644
index 4c2ba8a831d..00000000000
--- a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h
+++ /dev/null
@@ -1,115 +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_EXTENSIONS_API_MESSAGING_EXTENSION_MESSAGE_PORT_H_
-#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_EXTENSION_MESSAGE_PORT_H_
-
-#include "base/macros.h"
-#include "chrome/browser/extensions/api/messaging/message_service.h"
-#include "extensions/common/api/messaging/port_id.h"
-
-class GURL;
-
-namespace content {
-class BrowserContext;
-class RenderFrameHost;
-class RenderProcessHost;
-} // namespace content
-
-namespace IPC {
-class Message;
-} // namespace IPC
-
-namespace extensions {
-
-// A port that manages communication with an extension.
-// The port's lifetime will end when either all receivers close the port, or
-// when the opener / receiver explicitly closes the channel.
-class ExtensionMessagePort : public MessageService::MessagePort {
- public:
- // Create a port that is tied to frame(s) in a single tab.
- ExtensionMessagePort(base::WeakPtr<MessageService> message_service,
- const PortId& port_id,
- const std::string& extension_id,
- content::RenderFrameHost* rfh,
- bool include_child_frames);
- // Create a port that is tied to all frames of an extension, possibly spanning
- // multiple tabs, including the invisible background page, popups, etc.
- ExtensionMessagePort(base::WeakPtr<MessageService> message_service,
- const PortId& port_id,
- const std::string& extension_id,
- content::RenderProcessHost* extension_process);
- ~ExtensionMessagePort() override;
-
- // Checks whether the frames to which this port is tied at its construction
- // are still aware of this port's existence. Frames that don't know about
- // the port are removed from the set of frames. This should be used for opener
- // ports because the frame may be navigated before the port was initialized.
- void RevalidatePort();
-
- // MessageService::MessagePort:
- void RemoveCommonFrames(const MessagePort& port) override;
- bool HasFrame(content::RenderFrameHost* rfh) const override;
- bool IsValidPort() override;
- void DispatchOnConnect(const std::string& channel_name,
- std::unique_ptr<base::DictionaryValue> source_tab,
- int source_frame_id,
- int guest_process_id,
- int guest_render_frame_routing_id,
- const std::string& source_extension_id,
- const std::string& target_extension_id,
- const GURL& source_url,
- const std::string& tls_channel_id) override;
- void DispatchOnDisconnect(const std::string& error_message) override;
- void DispatchOnMessage(const Message& message) override;
- void IncrementLazyKeepaliveCount() override;
- void DecrementLazyKeepaliveCount() override;
- void OpenPort(int process_id, int routing_id) override;
- void ClosePort(int process_id, int routing_id) override;
-
- private:
- class FrameTracker;
-
- // Registers a frame as a receiver / sender.
- void RegisterFrame(content::RenderFrameHost* rfh);
-
- // Unregisters a frame as a receiver / sender. When there are no registered
- // frames any more, the port closes via CloseChannel().
- void UnregisterFrame(content::RenderFrameHost* rfh);
-
- // Immediately close the port and its associated channel.
- void CloseChannel();
-
- // Send a IPC message to the renderer for all registered frames.
- void SendToPort(std::unique_ptr<IPC::Message> msg);
-
- base::WeakPtr<MessageService> weak_message_service_;
-
- const PortId port_id_;
- std::string extension_id_;
- content::BrowserContext* browser_context_;
- // Only for receivers in an extension process.
- content::RenderProcessHost* extension_process_;
-
- // When the port is used as a sender, this set contains only one element.
- // If used as a receiver, it may contain any number of frames.
- // This set is populated before the first message is sent to the destination,
- // and shrinks over time when the port is rejected by the recipient frame, or
- // when the frame is removed or unloaded.
- std::set<content::RenderFrameHost*> frames_;
-
- // Whether the renderer acknowledged creation of the port. This is used to
- // distinguish abnormal port closure (e.g. no receivers) from explicit port
- // closure (e.g. by the port.disconnect() JavaScript method in the renderer).
- bool did_create_port_;
-
- ExtensionHost* background_host_ptr_; // used in IncrementLazyKeepaliveCount
- std::unique_ptr<FrameTracker> frame_tracker_;
-
- DISALLOW_COPY_AND_ASSIGN(ExtensionMessagePort);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_EXTENSION_MESSAGE_PORT_H_
diff --git a/chromium/chrome/browser/extensions/api/messaging/message_property_provider.cc b/chromium/chrome/browser/extensions/api/messaging/message_property_provider.cc
deleted file mode 100644
index a98f99cc548..00000000000
--- a/chromium/chrome/browser/extensions/api/messaging/message_property_provider.cc
+++ /dev/null
@@ -1,111 +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 "chrome/browser/extensions/api/messaging/message_property_provider.h"
-
-#include <stdint.h>
-
-#include "base/json/json_writer.h"
-#include "base/logging.h"
-#include "base/strings/string_piece.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "base/values.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/storage_partition.h"
-#include "crypto/ec_private_key.h"
-#include "extensions/common/api/runtime.h"
-#include "net/base/completion_callback.h"
-#include "net/cert/asn1_util.h"
-#include "net/cert/jwk_serializer.h"
-#include "net/ssl/channel_id_service.h"
-#include "net/url_request/url_request_context.h"
-#include "net/url_request/url_request_context_getter.h"
-#include "url/gurl.h"
-
-namespace extensions {
-
-MessagePropertyProvider::MessagePropertyProvider() {}
-
-void MessagePropertyProvider::GetChannelID(
- content::BrowserContext* browser_context,
- const GURL& source_url,
- const ChannelIDCallback& reply) {
- if (!source_url.is_valid()) {
- // This isn't a real URL, so there's no sense in looking for a channel ID
- // for it. Dispatch with an empty tls channel ID.
- reply.Run(std::string());
- return;
- }
-
- scoped_refptr<net::URLRequestContextGetter> request_context_getter(
- content::BrowserContext::GetDefaultStoragePartition(browser_context)
- ->GetURLRequestContext());
- content::BrowserThread::PostTask(
- content::BrowserThread::IO, FROM_HERE,
- base::BindOnce(&MessagePropertyProvider::GetChannelIDOnIOThread,
- base::ThreadTaskRunnerHandle::Get(),
- request_context_getter, source_url.host(), reply));
-}
-
-// Helper struct to bind the memory addresses that will be written to by
-// ChannelIDService::GetChannelID to the callback provided to
-// MessagePropertyProvider::GetChannelID.
-struct MessagePropertyProvider::GetChannelIDOutput {
- std::unique_ptr<crypto::ECPrivateKey> channel_id_key;
- net::ChannelIDService::Request request;
-};
-
-// static
-void MessagePropertyProvider::GetChannelIDOnIOThread(
- scoped_refptr<base::TaskRunner> original_task_runner,
- scoped_refptr<net::URLRequestContextGetter> request_context_getter,
- const std::string& host,
- const ChannelIDCallback& reply) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- net::ChannelIDService* channel_id_service =
- request_context_getter->GetURLRequestContext()->
- channel_id_service();
- GetChannelIDOutput* output = new GetChannelIDOutput();
- net::CompletionCallback net_completion_callback =
- base::Bind(&MessagePropertyProvider::GotChannelID,
- original_task_runner,
- base::Owned(output),
- reply);
- int status = channel_id_service->GetChannelID(
- host, &output->channel_id_key, net_completion_callback, &output->request);
- if (status == net::ERR_IO_PENDING)
- return;
- GotChannelID(original_task_runner, output, reply, status);
-}
-
-// static
-void MessagePropertyProvider::GotChannelID(
- scoped_refptr<base::TaskRunner> original_task_runner,
- struct GetChannelIDOutput* output,
- const ChannelIDCallback& reply,
- int status) {
- base::Closure no_tls_channel_id_closure = base::Bind(reply, "");
- if (status != net::OK) {
- original_task_runner->PostTask(FROM_HERE, no_tls_channel_id_closure);
- return;
- }
- std::vector<uint8_t> spki_vector;
- if (!output->channel_id_key->ExportPublicKey(&spki_vector)) {
- original_task_runner->PostTask(FROM_HERE, no_tls_channel_id_closure);
- return;
- }
- base::StringPiece spki(reinterpret_cast<char*>(spki_vector.data()),
- spki_vector.size());
- base::DictionaryValue jwk_value;
- if (!net::JwkSerializer::ConvertSpkiFromDerToJwk(spki, &jwk_value)) {
- original_task_runner->PostTask(FROM_HERE, no_tls_channel_id_closure);
- return;
- }
- std::string jwk_str;
- base::JSONWriter::Write(jwk_value, &jwk_str);
- original_task_runner->PostTask(FROM_HERE, base::BindOnce(reply, jwk_str));
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/message_property_provider.h b/chromium/chrome/browser/extensions/api/messaging/message_property_provider.h
deleted file mode 100644
index 576b1723676..00000000000
--- a/chromium/chrome/browser/extensions/api/messaging/message_property_provider.h
+++ /dev/null
@@ -1,63 +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.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_PROPERTY_PROVIDER_H_
-#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_PROPERTY_PROVIDER_H_
-
-#include <string>
-
-#include "base/callback.h"
-#include "base/macros.h"
-
-class GURL;
-
-namespace base {
-class TaskRunner;
-}
-
-namespace content {
-class BrowserContext;
-}
-
-namespace net {
-class URLRequestContextGetter;
-}
-
-namespace extensions {
-
-// This class provides properties of messages asynchronously.
-class MessagePropertyProvider {
- public:
- MessagePropertyProvider();
-
- typedef base::Callback<void(const std::string&)> ChannelIDCallback;
-
- // Gets the DER-encoded public key of the domain-bound cert,
- // aka TLS channel ID, for the given URL.
- // Runs |reply| on the current message loop.
- void GetChannelID(content::BrowserContext* browser_context,
- const GURL& source_url,
- const ChannelIDCallback& reply);
-
- private:
- struct GetChannelIDOutput;
-
- static void GetChannelIDOnIOThread(
- scoped_refptr<base::TaskRunner> original_task_runner,
- scoped_refptr<net::URLRequestContextGetter> request_context_getter,
- const std::string& host,
- const ChannelIDCallback& reply);
-
- static void GotChannelID(
- scoped_refptr<base::TaskRunner> original_task_runner,
- struct GetChannelIDOutput* output,
- const ChannelIDCallback& reply,
- int status);
-
- DISALLOW_COPY_AND_ASSIGN(MessagePropertyProvider);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_PROPERTY_PROVIDER_H_
diff --git a/chromium/chrome/browser/extensions/api/messaging/message_service.cc b/chromium/chrome/browser/extensions/api/messaging/message_service.cc
deleted file mode 100644
index 9be1a4a3269..00000000000
--- a/chromium/chrome/browser/extensions/api/messaging/message_service.cc
+++ /dev/null
@@ -1,998 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/extensions/api/messaging/message_service.h"
-
-#include <stdint.h>
-#include <limits>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/json/json_writer.h"
-#include "base/lazy_instance.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/histogram_macros.h"
-#include "build/build_config.h"
-#include "chrome/browser/extensions/api/messaging/extension_message_port.h"
-#include "chrome/browser/extensions/api/messaging/incognito_connectability.h"
-#include "chrome/browser/extensions/api/messaging/native_message_port.h"
-#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
-#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/extensions/extension_tab_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/tab_contents/tab_util.h"
-#include "components/guest_view/common/guest_view_constants.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/render_process_host.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/render_widget_host.h"
-#include "content/public/browser/render_widget_host_view.h"
-#include "content/public/browser/site_instance.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/child_process_host.h"
-#include "extensions/browser/event_router.h"
-#include "extensions/browser/extension_api_frame_id_map.h"
-#include "extensions/browser/extension_host.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/browser/extension_system.h"
-#include "extensions/browser/extension_util.h"
-#include "extensions/browser/extension_web_contents_observer.h"
-#include "extensions/browser/extensions_browser_client.h"
-#include "extensions/browser/guest_view/web_view/web_view_guest.h"
-#include "extensions/browser/lazy_background_task_queue.h"
-#include "extensions/browser/pref_names.h"
-#include "extensions/browser/process_manager.h"
-#include "extensions/common/extension.h"
-#include "extensions/common/manifest_constants.h"
-#include "extensions/common/manifest_handlers/background_info.h"
-#include "extensions/common/manifest_handlers/externally_connectable.h"
-#include "extensions/common/manifest_handlers/incognito_info.h"
-#include "extensions/common/permissions/permissions_data.h"
-#include "net/base/completion_callback.h"
-#include "url/gurl.h"
-
-using content::BrowserContext;
-using content::BrowserThread;
-using content::SiteInstance;
-using content::WebContents;
-
-namespace extensions {
-
-MessageService::PolicyPermission MessageService::IsNativeMessagingHostAllowed(
- const PrefService* pref_service,
- const std::string& native_host_name) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- PolicyPermission allow_result = ALLOW_ALL;
- if (pref_service->IsManagedPreference(
- pref_names::kNativeMessagingUserLevelHosts)) {
- if (!pref_service->GetBoolean(pref_names::kNativeMessagingUserLevelHosts))
- allow_result = ALLOW_SYSTEM_ONLY;
- }
-
- // All native messaging hosts are allowed if there is no blacklist.
- if (!pref_service->IsManagedPreference(pref_names::kNativeMessagingBlacklist))
- return allow_result;
- const base::ListValue* blacklist =
- pref_service->GetList(pref_names::kNativeMessagingBlacklist);
- if (!blacklist)
- return allow_result;
-
- // Check if the name or the wildcard is in the blacklist.
- base::Value name_value(native_host_name);
- base::Value wildcard_value("*");
- if (blacklist->Find(name_value) == blacklist->end() &&
- blacklist->Find(wildcard_value) == blacklist->end()) {
- return allow_result;
- }
-
- // The native messaging host is blacklisted. Check the whitelist.
- if (pref_service->IsManagedPreference(
- pref_names::kNativeMessagingWhitelist)) {
- const base::ListValue* whitelist =
- pref_service->GetList(pref_names::kNativeMessagingWhitelist);
- if (whitelist && whitelist->Find(name_value) != whitelist->end())
- return allow_result;
- }
-
- return DISALLOW;
-}
-
-const char kReceivingEndDoesntExistError[] =
- "Could not establish connection. Receiving end does not exist.";
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
-const char kMissingPermissionError[] =
- "Access to native messaging requires nativeMessaging permission.";
-const char kProhibitedByPoliciesError[] =
- "Access to the native messaging host was disabled by the system "
- "administrator.";
-#endif
-
-struct MessageService::MessageChannel {
- std::unique_ptr<MessagePort> opener;
- std::unique_ptr<MessagePort> receiver;
-};
-
-struct MessageService::OpenChannelParams {
- int source_process_id;
- int source_routing_id;
- std::unique_ptr<base::DictionaryValue> source_tab;
- int source_frame_id;
- std::unique_ptr<MessagePort> receiver;
- PortId receiver_port_id;
- std::string source_extension_id;
- std::string target_extension_id;
- GURL source_url;
- std::string channel_name;
- bool include_tls_channel_id;
- std::string tls_channel_id;
- bool include_guest_process_info;
-
- // Takes ownership of receiver.
- OpenChannelParams(int source_process_id,
- int source_routing_id,
- std::unique_ptr<base::DictionaryValue> source_tab,
- int source_frame_id,
- MessagePort* receiver,
- const PortId& receiver_port_id,
- const std::string& source_extension_id,
- const std::string& target_extension_id,
- const GURL& source_url,
- const std::string& channel_name,
- bool include_tls_channel_id,
- bool include_guest_process_info)
- : source_process_id(source_process_id),
- source_routing_id(source_routing_id),
- source_frame_id(source_frame_id),
- receiver(receiver),
- receiver_port_id(receiver_port_id),
- source_extension_id(source_extension_id),
- target_extension_id(target_extension_id),
- source_url(source_url),
- channel_name(channel_name),
- include_tls_channel_id(include_tls_channel_id),
- include_guest_process_info(include_guest_process_info) {
- if (source_tab)
- this->source_tab = std::move(source_tab);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(OpenChannelParams);
-};
-
-namespace {
-
-static content::RenderProcessHost* GetExtensionProcess(
- BrowserContext* context,
- const std::string& extension_id) {
- scoped_refptr<SiteInstance> site_instance =
- ProcessManager::Get(context)->GetSiteInstanceForURL(
- Extension::GetBaseURLFromExtensionId(extension_id));
- return site_instance->HasProcess() ? site_instance->GetProcess() : NULL;
-}
-
-} // namespace
-
-void MessageService::MessagePort::RemoveCommonFrames(const MessagePort& port) {}
-
-bool MessageService::MessagePort::HasFrame(
- content::RenderFrameHost* rfh) const {
- return false;
-}
-
-MessageService::MessageService(BrowserContext* context)
- : lazy_background_task_queue_(
- LazyBackgroundTaskQueue::Get(context)),
- weak_factory_(this) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-}
-
-MessageService::~MessageService() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- channels_.clear();
-}
-
-static base::LazyInstance<
- BrowserContextKeyedAPIFactory<MessageService>>::DestructorAtExit g_factory =
- LAZY_INSTANCE_INITIALIZER;
-
-// static
-BrowserContextKeyedAPIFactory<MessageService>*
-MessageService::GetFactoryInstance() {
- return g_factory.Pointer();
-}
-
-// static
-MessageService* MessageService::Get(BrowserContext* context) {
- return BrowserContextKeyedAPIFactory<MessageService>::Get(context);
-}
-
-void MessageService::OpenChannelToExtension(
- int source_process_id,
- int source_routing_id,
- const PortId& source_port_id,
- const std::string& source_extension_id,
- const std::string& target_extension_id,
- const GURL& source_url,
- const std::string& channel_name,
- bool include_tls_channel_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(source_port_id.is_opener);
-
- content::RenderFrameHost* source =
- content::RenderFrameHost::FromID(source_process_id, source_routing_id);
- if (!source)
- return;
- BrowserContext* context = source->GetProcess()->GetBrowserContext();
-
- ExtensionRegistry* registry = ExtensionRegistry::Get(context);
- const Extension* target_extension =
- registry->enabled_extensions().GetByID(target_extension_id);
- PortId receiver_port_id(source_port_id.context_id, source_port_id.port_number,
- false);
- if (!target_extension) {
- DispatchOnDisconnect(
- source, receiver_port_id, kReceivingEndDoesntExistError);
- return;
- }
-
- bool is_web_connection = false;
-
- if (source_extension_id != target_extension_id) {
- // It's an external connection. Check the externally_connectable manifest
- // key if it's present. If it's not, we allow connection from any extension
- // but not webpages.
- ExternallyConnectableInfo* externally_connectable =
- static_cast<ExternallyConnectableInfo*>(
- target_extension->GetManifestData(
- manifest_keys::kExternallyConnectable));
- bool is_externally_connectable = false;
-
- if (externally_connectable) {
- if (source_extension_id.empty()) {
- // No source extension ID so the source was a web page. Check that the
- // URL matches.
- is_web_connection = true;
- is_externally_connectable =
- externally_connectable->matches.MatchesURL(source_url);
- // Only include the TLS channel ID for externally connected web pages.
- include_tls_channel_id &=
- is_externally_connectable &&
- externally_connectable->accepts_tls_channel_id;
- } else {
- // Source extension ID so the source was an extension. Check that the
- // extension matches.
- is_externally_connectable =
- externally_connectable->IdCanConnect(source_extension_id);
- }
- } else {
- // Default behaviour. Any extension, no webpages.
- is_externally_connectable = !source_extension_id.empty();
- }
-
- if (!is_externally_connectable) {
- // Important: use kReceivingEndDoesntExistError here so that we don't
- // leak information about this extension to callers. This way it's
- // indistinguishable from the extension just not existing.
- DispatchOnDisconnect(
- source, receiver_port_id, kReceivingEndDoesntExistError);
- return;
- }
- }
-
- WebContents* source_contents = tab_util::GetWebContentsByFrameID(
- source_process_id, source_routing_id);
-
- bool include_guest_process_info = false;
-
- // Include info about the opener's tab (if it was a tab).
- std::unique_ptr<base::DictionaryValue> source_tab;
- int source_frame_id = -1;
- if (source_contents && ExtensionTabUtil::GetTabId(source_contents) >= 0) {
- // Only the tab id is useful to platform apps for internal use. The
- // unnecessary bits will be stripped out in
- // MessagingBindings::DispatchOnConnect().
- source_tab.reset(ExtensionTabUtil::CreateTabObject(source_contents)
- ->ToValue()
- .release());
-
- content::RenderFrameHost* rfh =
- content::RenderFrameHost::FromID(source_process_id, source_routing_id);
- if (rfh)
- source_frame_id = ExtensionApiFrameIdMap::GetFrameId(rfh);
- } else {
- // Check to see if it was a WebView making the request.
- // Sending messages from WebViews to extensions breaks webview isolation,
- // so only allow component extensions to receive messages from WebViews.
- bool is_web_view = !!WebViewGuest::FromWebContents(source_contents);
- if (is_web_view && extensions::Manifest::IsComponentLocation(
- target_extension->location())) {
- include_guest_process_info = true;
- }
- }
-
- std::unique_ptr<OpenChannelParams> params(new OpenChannelParams(
- source_process_id, source_routing_id, std::move(source_tab),
- source_frame_id, nullptr, receiver_port_id, source_extension_id,
- target_extension_id, source_url, channel_name, include_tls_channel_id,
- include_guest_process_info));
-
- pending_incognito_channels_[params->receiver_port_id.GetChannelId()] =
- PendingMessagesQueue();
- if (context->IsOffTheRecord() &&
- !util::IsIncognitoEnabled(target_extension_id, context)) {
- // Give the user a chance to accept an incognito connection from the web if
- // they haven't already, with the conditions:
- // - Only for non-split mode incognito. We don't want the complication of
- // spinning up an additional process here which might need to do some
- // setup that we're not expecting.
- // - Only for extensions that can't normally be enabled in incognito, since
- // that surface (e.g. chrome://extensions) should be the only one for
- // enabling in incognito. In practice this means platform apps only.
- if (!is_web_connection || IncognitoInfo::IsSplitMode(target_extension) ||
- util::CanBeIncognitoEnabled(target_extension)) {
- OnOpenChannelAllowed(std::move(params), false);
- return;
- }
-
- // If the target extension isn't even listening for connect/message events,
- // there is no need to go any further and the connection should be
- // rejected without showing a prompt. See http://crbug.com/442497
- EventRouter* event_router = EventRouter::Get(context);
- const char* const events[] = {"runtime.onConnectExternal",
- "runtime.onMessageExternal",
- "extension.onRequestExternal",
- nullptr};
- bool has_event_listener = false;
- for (const char* const* event = events; *event; event++) {
- has_event_listener |=
- event_router->ExtensionHasEventListener(target_extension_id, *event);
- }
- if (!has_event_listener) {
- OnOpenChannelAllowed(std::move(params), false);
- return;
- }
-
- // This check may show a dialog.
- IncognitoConnectability::Get(context)
- ->Query(target_extension, source_contents, source_url,
- base::Bind(&MessageService::OnOpenChannelAllowed,
- weak_factory_.GetWeakPtr(), base::Passed(&params)));
- return;
- }
-
- OnOpenChannelAllowed(std::move(params), true);
-}
-
-void MessageService::OpenChannelToNativeApp(
- int source_process_id,
- int source_routing_id,
- const PortId& source_port_id,
- const std::string& native_app_name) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(source_port_id.is_opener);
-
- content::RenderFrameHost* source =
- content::RenderFrameHost::FromID(source_process_id, source_routing_id);
- if (!source)
- return;
-
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
- content::WebContents* web_contents =
- content::WebContents::FromRenderFrameHost(source);
- ExtensionWebContentsObserver* extension_web_contents_observer =
- web_contents ?
- ExtensionWebContentsObserver::GetForWebContents(web_contents) :
- nullptr;
- const Extension* extension =
- extension_web_contents_observer ?
- extension_web_contents_observer->GetExtensionFromFrame(source, true) :
- nullptr;
-
- bool has_permission = extension &&
- extension->permissions_data()->HasAPIPermission(
- APIPermission::kNativeMessaging);
-
- PortId receiver_port_id(source_port_id.context_id, source_port_id.port_number,
- false);
- if (!has_permission) {
- DispatchOnDisconnect(source, receiver_port_id, kMissingPermissionError);
- return;
- }
-
- PrefService* pref_service =
- Profile::FromBrowserContext(source->GetProcess()->GetBrowserContext())->
- GetPrefs();
-
- // Verify that the host is not blocked by policies.
- PolicyPermission policy_permission =
- IsNativeMessagingHostAllowed(pref_service, native_app_name);
- if (policy_permission == DISALLOW) {
- DispatchOnDisconnect(source, receiver_port_id, kProhibitedByPoliciesError);
- return;
- }
-
- std::unique_ptr<MessageChannel> channel(new MessageChannel());
- channel->opener.reset(
- new ExtensionMessagePort(weak_factory_.GetWeakPtr(), source_port_id,
- extension->id(), source, false));
- if (!channel->opener->IsValidPort())
- return;
- channel->opener->OpenPort(source_process_id, source_routing_id);
-
- // Get handle of the native view and pass it to the native messaging host.
- gfx::NativeView native_view = source ? source->GetNativeView() : nullptr;
-
- std::string error = kReceivingEndDoesntExistError;
- std::unique_ptr<NativeMessageHost> native_host = NativeMessageHost::Create(
- native_view, extension->id(), native_app_name,
- policy_permission == ALLOW_ALL, &error);
-
- // Abandon the channel.
- if (!native_host.get()) {
- DispatchOnDisconnect(source, receiver_port_id, error);
- return;
- }
- channel->receiver.reset(new NativeMessagePort(
- weak_factory_.GetWeakPtr(), receiver_port_id, std::move(native_host)));
-
- // Keep the opener alive until the channel is closed.
- channel->opener->IncrementLazyKeepaliveCount();
-
- AddChannel(std::move(channel), receiver_port_id);
-#else // !(defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX))
- const char kNativeMessagingNotSupportedError[] =
- "Native Messaging is not supported on this platform.";
- DispatchOnDisconnect(
- source, receiver_port_id, kNativeMessagingNotSupportedError);
-#endif // !(defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX))
-}
-
-void MessageService::OpenChannelToTab(int source_process_id,
- int source_routing_id,
- const PortId& source_port_id,
- int tab_id,
- int frame_id,
- const std::string& extension_id,
- const std::string& channel_name) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK_GE(frame_id, -1);
- DCHECK(source_port_id.is_opener);
-
- content::RenderFrameHost* source =
- content::RenderFrameHost::FromID(source_process_id, source_routing_id);
- if (!source)
- return;
- content::BrowserContext* browser_context =
- source->GetProcess()->GetBrowserContext();
-
- WebContents* contents = NULL;
- std::unique_ptr<MessagePort> receiver;
- PortId receiver_port_id(source_port_id.context_id, source_port_id.port_number,
- false);
- if (!ExtensionTabUtil::GetTabById(tab_id, browser_context, true, NULL, NULL,
- &contents, NULL) ||
- contents->GetController().NeedsReload()) {
- // The tab isn't loaded yet. Don't attempt to connect.
- DispatchOnDisconnect(
- source, receiver_port_id, kReceivingEndDoesntExistError);
- return;
- }
-
- // Frame ID -1 is every frame in the tab.
- bool include_child_frames = frame_id == -1;
- content::RenderFrameHost* receiver_rfh =
- include_child_frames
- ? contents->GetMainFrame()
- : ExtensionApiFrameIdMap::GetRenderFrameHostById(contents, frame_id);
- if (!receiver_rfh) {
- DispatchOnDisconnect(
- source, receiver_port_id, kReceivingEndDoesntExistError);
- return;
- }
- receiver.reset(
- new ExtensionMessagePort(weak_factory_.GetWeakPtr(),
- receiver_port_id, extension_id, receiver_rfh,
- include_child_frames));
-
- const Extension* extension = nullptr;
- if (!extension_id.empty()) {
- // Source extension == target extension so the extension must exist, or
- // where did the IPC come from?
- extension = ExtensionRegistry::Get(browser_context)
- ->enabled_extensions()
- .GetByID(extension_id);
- DCHECK(extension);
- }
-
- std::unique_ptr<OpenChannelParams> params(new OpenChannelParams(
- source_process_id, source_routing_id,
- std::unique_ptr<base::DictionaryValue>(), // Source tab doesn't make
- // sense
- // for opening to tabs.
- -1, // If there is no tab, then there is no frame either.
- receiver.release(), receiver_port_id, extension_id, extension_id,
- GURL(), // Source URL doesn't make sense for opening to tabs.
- channel_name,
- false, // Connections to tabs don't get TLS channel IDs.
- false)); // Connections to tabs aren't webview guests.
- OpenChannelImpl(contents->GetBrowserContext(), std::move(params), extension,
- false /* did_enqueue */);
-}
-
-void MessageService::OpenChannelImpl(BrowserContext* browser_context,
- std::unique_ptr<OpenChannelParams> params,
- const Extension* target_extension,
- bool did_enqueue) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK_EQ(target_extension != nullptr, !params->target_extension_id.empty());
-
- content::RenderFrameHost* source =
- content::RenderFrameHost::FromID(params->source_process_id,
- params->source_routing_id);
- if (!source)
- return; // Closed while in flight.
-
- if (!params->receiver || !params->receiver->IsValidPort()) {
- DispatchOnDisconnect(source, params->receiver_port_id,
- kReceivingEndDoesntExistError);
- return;
- }
-
- std::unique_ptr<ExtensionMessagePort> opener(new ExtensionMessagePort(
- weak_factory_.GetWeakPtr(), params->receiver_port_id.GetOppositePortId(),
- params->source_extension_id, source, false));
- if (!opener->IsValidPort())
- return;
- opener->OpenPort(params->source_process_id, params->source_routing_id);
- opener->RevalidatePort();
-
- params->receiver->RemoveCommonFrames(*opener);
- if (!params->receiver->IsValidPort()) {
- opener->DispatchOnDisconnect(kReceivingEndDoesntExistError);
- return;
- }
-
- std::unique_ptr<MessageChannel> channel_ptr =
- base::MakeUnique<MessageChannel>();
- MessageChannel* channel = channel_ptr.get();
- channel->opener = std::move(opener);
- channel->receiver = std::move(params->receiver);
- AddChannel(std::move(channel_ptr), params->receiver_port_id);
-
- int guest_process_id = content::ChildProcessHost::kInvalidUniqueID;
- int guest_render_frame_routing_id = MSG_ROUTING_NONE;
- if (params->include_guest_process_info) {
- guest_process_id = params->source_process_id;
- guest_render_frame_routing_id = params->source_routing_id;
-
- DCHECK(WebViewGuest::FromWebContents(
- WebContents::FromRenderFrameHost(source)));
- }
-
- // Send the connect event to the receiver. Give it the opener's port ID (the
- // opener has the opposite port ID).
- channel->receiver->DispatchOnConnect(
- params->channel_name, std::move(params->source_tab),
- params->source_frame_id, guest_process_id, guest_render_frame_routing_id,
- params->source_extension_id, params->target_extension_id,
- params->source_url, params->tls_channel_id);
-
- // Report the event to the event router, if the target is an extension.
- //
- // First, determine what event this will be (runtime.onConnect vs
- // runtime.onMessage etc), and what the event target is (view vs background
- // page etc).
- //
- // Yes - even though this is opening a channel, they may actually be
- // runtime.onRequest/onMessage events because those single-use events are
- // built using the connect framework (see messaging.js).
- //
- // Likewise, if you're wondering about native messaging events, these are
- // only initiated *by* the extension, so aren't really events, just the
- // endpoint of a communication channel.
- if (target_extension) {
- events::HistogramValue histogram_value = events::UNKNOWN;
- bool is_external =
- params->source_extension_id != params->target_extension_id;
- if (params->channel_name == "chrome.runtime.onRequest") {
- histogram_value = is_external ? events::RUNTIME_ON_REQUEST_EXTERNAL
- : events::RUNTIME_ON_REQUEST;
- } else if (params->channel_name == "chrome.runtime.onMessage") {
- histogram_value = is_external ? events::RUNTIME_ON_MESSAGE_EXTERNAL
- : events::RUNTIME_ON_MESSAGE;
- } else {
- histogram_value = is_external ? events::RUNTIME_ON_CONNECT_EXTERNAL
- : events::RUNTIME_ON_CONNECT;
- }
- EventRouter::Get(browser_context)
- ->ReportEvent(histogram_value, target_extension, did_enqueue);
- }
-
- // Keep both ends of the channel alive until the channel is closed.
- channel->opener->IncrementLazyKeepaliveCount();
- channel->receiver->IncrementLazyKeepaliveCount();
-}
-
-void MessageService::AddChannel(std::unique_ptr<MessageChannel> channel,
- const PortId& receiver_port_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- ChannelId channel_id = receiver_port_id.GetChannelId();
- CHECK(channels_.find(channel_id) == channels_.end());
- channels_[channel_id] = std::move(channel);
- pending_lazy_background_page_channels_.erase(channel_id);
-}
-
-void MessageService::OpenPort(const PortId& port_id,
- int process_id,
- int routing_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(!port_id.is_opener);
-
- ChannelId channel_id = port_id.GetChannelId();
- MessageChannelMap::iterator it = channels_.find(channel_id);
- if (it == channels_.end())
- return;
-
- it->second->receiver->OpenPort(process_id, routing_id);
-}
-
-void MessageService::ClosePort(const PortId& port_id,
- int process_id,
- int routing_id,
- bool force_close) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- ClosePortImpl(port_id, process_id, routing_id, force_close, std::string());
-}
-
-void MessageService::CloseChannel(const PortId& port_id,
- const std::string& error_message) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- ClosePortImpl(port_id, content::ChildProcessHost::kInvalidUniqueID,
- MSG_ROUTING_NONE, true, error_message);
-}
-
-void MessageService::ClosePortImpl(const PortId& port_id,
- int process_id,
- int routing_id,
- bool force_close,
- const std::string& error_message) {
- // Note: The channel might be gone already, if the other side closed first.
- ChannelId channel_id = port_id.GetChannelId();
- MessageChannelMap::iterator it = channels_.find(channel_id);
- if (it == channels_.end()) {
- PendingLazyBackgroundPageChannelMap::iterator pending =
- pending_lazy_background_page_channels_.find(channel_id);
- if (pending != pending_lazy_background_page_channels_.end()) {
- lazy_background_task_queue_->AddPendingTask(
- pending->second.first, pending->second.second,
- base::Bind(&MessageService::PendingLazyBackgroundPageClosePort,
- weak_factory_.GetWeakPtr(), port_id, process_id,
- routing_id, force_close, error_message));
- }
- return;
- }
-
- // The difference between closing a channel and port is that closing a port
- // does not necessarily have to destroy the channel if there are multiple
- // receivers, whereas closing a channel always forces all ports to be closed.
- if (force_close) {
- CloseChannelImpl(it, port_id, error_message, true);
- } else if (port_id.is_opener) {
- it->second->opener->ClosePort(process_id, routing_id);
- } else {
- it->second->receiver->ClosePort(process_id, routing_id);
- }
-}
-
-void MessageService::CloseChannelImpl(MessageChannelMap::iterator channel_iter,
- const PortId& closing_port_id,
- const std::string& error_message,
- bool notify_other_port) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- std::unique_ptr<MessageChannel> channel = std::move(channel_iter->second);
- // Remove from map to make sure that it is impossible for CloseChannelImpl to
- // run twice for the same channel.
- channels_.erase(channel_iter);
-
- // Notify the other side.
- if (notify_other_port) {
- MessagePort* port = closing_port_id.is_opener ? channel->receiver.get()
- : channel->opener.get();
- port->DispatchOnDisconnect(error_message);
- }
-
- // Balance the IncrementLazyKeepaliveCount() in OpenChannelImpl.
- channel->opener->DecrementLazyKeepaliveCount();
- channel->receiver->DecrementLazyKeepaliveCount();
-}
-
-void MessageService::PostMessage(const PortId& source_port_id,
- const Message& message) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- ChannelId channel_id = source_port_id.GetChannelId();
- MessageChannelMap::iterator iter = channels_.find(channel_id);
- if (iter == channels_.end()) {
- // If this channel is pending, queue up the PostMessage to run once
- // the channel opens.
- EnqueuePendingMessage(source_port_id, channel_id, message);
- return;
- }
-
- DispatchMessage(source_port_id, iter->second.get(), message);
-}
-
-void MessageService::EnqueuePendingMessage(const PortId& source_port_id,
- const ChannelId& channel_id,
- const Message& message) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- PendingChannelMap::iterator pending_for_incognito =
- pending_incognito_channels_.find(channel_id);
- if (pending_for_incognito != pending_incognito_channels_.end()) {
- pending_for_incognito->second.push_back(
- PendingMessage(source_port_id, message));
- // A channel should only be holding pending messages because it is in one
- // of these states.
- DCHECK(!base::ContainsKey(pending_tls_channel_id_channels_, channel_id));
- DCHECK(
- !base::ContainsKey(pending_lazy_background_page_channels_, channel_id));
- return;
- }
- PendingChannelMap::iterator pending_for_tls_channel_id =
- pending_tls_channel_id_channels_.find(channel_id);
- if (pending_for_tls_channel_id != pending_tls_channel_id_channels_.end()) {
- pending_for_tls_channel_id->second.push_back(
- PendingMessage(source_port_id, message));
- // A channel should only be holding pending messages because it is in one
- // of these states.
- DCHECK(
- !base::ContainsKey(pending_lazy_background_page_channels_, channel_id));
- return;
- }
- EnqueuePendingMessageForLazyBackgroundLoad(source_port_id,
- channel_id,
- message);
-}
-
-void MessageService::EnqueuePendingMessageForLazyBackgroundLoad(
- const PortId& source_port_id,
- const ChannelId& channel_id,
- const Message& message) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- PendingLazyBackgroundPageChannelMap::iterator pending =
- pending_lazy_background_page_channels_.find(channel_id);
- if (pending != pending_lazy_background_page_channels_.end()) {
- lazy_background_task_queue_->AddPendingTask(
- pending->second.first, pending->second.second,
- base::Bind(&MessageService::PendingLazyBackgroundPagePostMessage,
- weak_factory_.GetWeakPtr(), source_port_id, message));
- }
-}
-
-void MessageService::DispatchMessage(const PortId& source_port_id,
- MessageChannel* channel,
- const Message& message) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- // Figure out which port the ID corresponds to.
- MessagePort* dest_port = source_port_id.is_opener ? channel->receiver.get()
- : channel->opener.get();
-
- dest_port->DispatchOnMessage(message);
-}
-
-bool MessageService::MaybeAddPendingLazyBackgroundPageOpenChannelTask(
- BrowserContext* context,
- const Extension* extension,
- std::unique_ptr<OpenChannelParams>* params,
- const PendingMessagesQueue& pending_messages) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (!BackgroundInfo::HasLazyBackgroundPage(extension))
- return false;
-
- // If the extension uses spanning incognito mode, make sure we're always
- // using the original profile since that is what the extension process
- // will use.
- if (!IncognitoInfo::IsSplitMode(extension))
- context = ExtensionsBrowserClient::Get()->GetOriginalContext(context);
-
- if (!lazy_background_task_queue_->ShouldEnqueueTask(context, extension))
- return false;
-
- ChannelId channel_id = (*params)->receiver_port_id.GetChannelId();
- pending_lazy_background_page_channels_[channel_id] =
- PendingLazyBackgroundPageChannel(context, extension->id());
- int source_id = (*params)->source_process_id;
- lazy_background_task_queue_->AddPendingTask(
- context, extension->id(),
- base::Bind(&MessageService::PendingLazyBackgroundPageOpenChannel,
- weak_factory_.GetWeakPtr(), base::Passed(params), source_id));
-
- for (const PendingMessage& message : pending_messages) {
- EnqueuePendingMessageForLazyBackgroundLoad(message.first, channel_id,
- message.second);
- }
- return true;
-}
-
-void MessageService::OnOpenChannelAllowed(
- std::unique_ptr<OpenChannelParams> params,
- bool allowed) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- ChannelId channel_id = params->receiver_port_id.GetChannelId();
-
- PendingChannelMap::iterator pending_for_incognito =
- pending_incognito_channels_.find(channel_id);
- if (pending_for_incognito == pending_incognito_channels_.end()) {
- NOTREACHED();
- return;
- }
- PendingMessagesQueue pending_messages;
- pending_messages.swap(pending_for_incognito->second);
- pending_incognito_channels_.erase(pending_for_incognito);
-
- // Re-lookup the source process since it may no longer be valid.
- content::RenderFrameHost* source =
- content::RenderFrameHost::FromID(params->source_process_id,
- params->source_routing_id);
- if (!source) {
- return;
- }
-
- if (!allowed) {
- DispatchOnDisconnect(source, params->receiver_port_id,
- kReceivingEndDoesntExistError);
- return;
- }
-
- BrowserContext* context = source->GetProcess()->GetBrowserContext();
-
- // Note: we use the source's profile here. If the source is an incognito
- // process, we will use the incognito EPM to find the right extension process,
- // which depends on whether the extension uses spanning or split mode.
- if (content::RenderProcessHost* extension_process =
- GetExtensionProcess(context, params->target_extension_id)) {
- params->receiver.reset(
- new ExtensionMessagePort(
- weak_factory_.GetWeakPtr(), params->receiver_port_id,
- params->target_extension_id, extension_process));
- } else {
- params->receiver.reset();
- }
-
- // If the target requests the TLS channel id, begin the lookup for it.
- // The target might also be a lazy background page, checked next, but the
- // loading of lazy background pages continues asynchronously, so enqueue
- // messages awaiting TLS channel ID first.
- if (params->include_tls_channel_id) {
- // Transfer pending messages to the next pending channel list.
- pending_tls_channel_id_channels_[channel_id].swap(pending_messages);
- // Capture this reference before params is invalidated by base::Passed().
- const GURL& source_url = params->source_url;
- property_provider_.GetChannelID(
- context, source_url,
- base::Bind(&MessageService::GotChannelID, weak_factory_.GetWeakPtr(),
- base::Passed(&params)));
- return;
- }
-
- ExtensionRegistry* registry = ExtensionRegistry::Get(context);
- const Extension* target_extension =
- registry->enabled_extensions().GetByID(params->target_extension_id);
- if (!target_extension) {
- DispatchOnDisconnect(source, params->receiver_port_id,
- kReceivingEndDoesntExistError);
- return;
- }
-
- // The target might be a lazy background page. In that case, we have to check
- // if it is loaded and ready, and if not, queue up the task and load the
- // page.
- if (!MaybeAddPendingLazyBackgroundPageOpenChannelTask(
- context, target_extension, &params, pending_messages)) {
- OpenChannelImpl(context, std::move(params), target_extension,
- false /* did_enqueue */);
- DispatchPendingMessages(pending_messages, channel_id);
- }
-}
-
-void MessageService::GotChannelID(std::unique_ptr<OpenChannelParams> params,
- const std::string& tls_channel_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- params->tls_channel_id.assign(tls_channel_id);
- ChannelId channel_id = params->receiver_port_id.GetChannelId();
-
- PendingChannelMap::iterator pending_for_tls_channel_id =
- pending_tls_channel_id_channels_.find(channel_id);
- if (pending_for_tls_channel_id == pending_tls_channel_id_channels_.end()) {
- NOTREACHED();
- return;
- }
- PendingMessagesQueue pending_messages;
- pending_messages.swap(pending_for_tls_channel_id->second);
- pending_tls_channel_id_channels_.erase(pending_for_tls_channel_id);
-
- // Re-lookup the source process since it may no longer be valid.
- content::RenderFrameHost* source =
- content::RenderFrameHost::FromID(params->source_process_id,
- params->source_routing_id);
- if (!source) {
- return;
- }
-
- BrowserContext* context = source->GetProcess()->GetBrowserContext();
- ExtensionRegistry* registry = ExtensionRegistry::Get(context);
- const Extension* target_extension =
- registry->enabled_extensions().GetByID(params->target_extension_id);
- if (!target_extension) {
- DispatchOnDisconnect(source, params->receiver_port_id,
- kReceivingEndDoesntExistError);
- return;
- }
-
- if (!MaybeAddPendingLazyBackgroundPageOpenChannelTask(
- context, target_extension, &params, pending_messages)) {
- OpenChannelImpl(context, std::move(params), target_extension,
- false /* did_enqueue */);
- DispatchPendingMessages(pending_messages, channel_id);
- }
-}
-
-void MessageService::PendingLazyBackgroundPageOpenChannel(
- std::unique_ptr<OpenChannelParams> params,
- int source_process_id,
- ExtensionHost* host) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (!host)
- return; // TODO(mpcomplete): notify source of disconnect?
-
- params->receiver.reset(
- new ExtensionMessagePort(
- weak_factory_.GetWeakPtr(), params->receiver_port_id,
- params->target_extension_id, host->render_process_host()));
- OpenChannelImpl(host->browser_context(), std::move(params), host->extension(),
- true /* did_enqueue */);
-}
-
-void MessageService::DispatchOnDisconnect(content::RenderFrameHost* source,
- const PortId& port_id,
- const std::string& error_message) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- ExtensionMessagePort port(weak_factory_.GetWeakPtr(),
- port_id.GetOppositePortId(), "", source, false);
- if (!port.IsValidPort())
- return;
- port.DispatchOnDisconnect(error_message);
-}
-
-void MessageService::DispatchPendingMessages(const PendingMessagesQueue& queue,
- const ChannelId& channel_id) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- MessageChannelMap::iterator channel_iter = channels_.find(channel_id);
- if (channel_iter != channels_.end()) {
- for (const PendingMessage& message : queue) {
- DispatchMessage(message.first, channel_iter->second.get(),
- message.second);
- }
- }
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/message_service.h b/chromium/chrome/browser/extensions/api/messaging/message_service.h
deleted file mode 100644
index e5d5322ba24..00000000000
--- a/chromium/chrome/browser/extensions/api/messaging/message_service.h
+++ /dev/null
@@ -1,327 +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_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
-#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
-
-#include <map>
-#include <memory>
-#include <set>
-#include <string>
-#include <vector>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/values.h"
-#include "chrome/browser/extensions/api/messaging/message_property_provider.h"
-#include "extensions/browser/api/messaging/native_message_host.h"
-#include "extensions/browser/browser_context_keyed_api_factory.h"
-#include "extensions/common/api/messaging/message.h"
-#include "extensions/common/api/messaging/port_id.h"
-#include "extensions/common/extension_id.h"
-
-class GURL;
-
-namespace content {
-class BrowserContext;
-}
-
-namespace extensions {
-class Extension;
-class ExtensionHost;
-class LazyBackgroundTaskQueue;
-
-// This class manages message and event passing between renderer processes.
-// It maintains a list of processes that are listening to events and a set of
-// open channels.
-//
-// Messaging works this way:
-// - An extension-owned script context (like a background page or a content
-// script) adds an event listener to the "onConnect" event.
-// - Another context calls "runtime.connect()" to open a channel to the
-// extension process, or an extension context calls "tabs.connect(tabId)" to
-// open a channel to the content scripts for the given tab. The EMS notifies
-// the target process/tab, which then calls the onConnect event in every
-// context owned by the connecting extension in that process/tab.
-// - Once the channel is established, either side can call postMessage to send
-// a message to the opposite side of the channel, which may have multiple
-// listeners.
-//
-// Terminology:
-// channel: connection between two ports
-// port: One sender or receiver tied to one or more RenderFrameHost instances.
-class MessageService : public BrowserContextKeyedAPI {
- public:
- // A messaging channel. Note that the opening port can be the same as the
- // receiver, if an extension background page wants to talk to its tab (for
- // example).
- struct MessageChannel;
-
- // One side of the communication handled by extensions::MessageService.
- class MessagePort {
- public:
- virtual ~MessagePort() {}
-
- // Called right before a channel is created for this MessagePort and |port|.
- // This allows us to ensure that the ports have no RenderFrameHost instances
- // in common.
- virtual void RemoveCommonFrames(const MessagePort& port);
-
- // Check whether the given RenderFrameHost is associated with this port.
- virtual bool HasFrame(content::RenderFrameHost* rfh) const;
-
- // Called right before a port is connected to a channel. If false, the port
- // is not used and the channel is closed.
- virtual bool IsValidPort() = 0;
-
- // Notify the port that the channel has been opened.
- virtual void DispatchOnConnect(
- const std::string& channel_name,
- std::unique_ptr<base::DictionaryValue> source_tab,
- int source_frame_id,
- int guest_process_id,
- int guest_render_frame_routing_id,
- const std::string& source_extension_id,
- const std::string& target_extension_id,
- const GURL& source_url,
- const std::string& tls_channel_id) {}
-
- // Notify the port that the channel has been closed. If |error_message| is
- // non-empty, it indicates an error occurred while opening the connection.
- virtual void DispatchOnDisconnect(const std::string& error_message) {}
-
- // Dispatch a message to this end of the communication.
- virtual void DispatchOnMessage(const Message& message) = 0;
-
- // Mark the port as opened by the specific frame.
- virtual void OpenPort(int process_id, int routing_id) {}
-
- // Close the port for the given frame.
- virtual void ClosePort(int process_id, int routing_id) {}
-
- // MessagePorts that target extensions will need to adjust their keepalive
- // counts for their lazy background page.
- virtual void IncrementLazyKeepaliveCount() {}
- virtual void DecrementLazyKeepaliveCount() {}
-
- protected:
- MessagePort() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MessagePort);
- };
-
- enum PolicyPermission {
- DISALLOW, // The host is not allowed.
- ALLOW_SYSTEM_ONLY, // Allowed only when installed on system level.
- ALLOW_ALL, // Allowed when installed on system or user level.
- };
-
- static PolicyPermission IsNativeMessagingHostAllowed(
- const PrefService* pref_service,
- const std::string& native_host_name);
-
- explicit MessageService(content::BrowserContext* context);
- ~MessageService() override;
-
- // BrowserContextKeyedAPI implementation.
- static BrowserContextKeyedAPIFactory<MessageService>* GetFactoryInstance();
-
- // Convenience method to get the MessageService for a browser context.
- static MessageService* Get(content::BrowserContext* context);
-
- // Given an extension's ID, opens a channel between the given renderer "port"
- // and every listening context owned by that extension. |channel_name| is
- // an optional identifier for use by extension developers.
- void OpenChannelToExtension(int source_process_id,
- int source_routing_id,
- const PortId& source_port_id,
- const std::string& source_extension_id,
- const std::string& target_extension_id,
- const GURL& source_url,
- const std::string& channel_name,
- bool include_tls_channel_id);
-
- // Same as above, but opens a channel to the tab with the given ID. Messages
- // are restricted to that tab, so if there are multiple tabs in that process,
- // only the targeted tab will receive messages.
- void OpenChannelToTab(int source_process_id,
- int source_routing_id,
- const PortId& source_port_id,
- int tab_id,
- int frame_id,
- const std::string& extension_id,
- const std::string& channel_name);
-
- void OpenChannelToNativeApp(int source_process_id,
- int source_routing_id,
- const PortId& source_port_id,
- const std::string& native_app_name);
-
- // Mark the given port as opened by the frame identified by
- // (process_id, routing_id).
- void OpenPort(const PortId& port_id, int process_id, int routing_id);
-
- // Closes the given port in the given frame. If this was the last frame or if
- // |force_close| is true, then the other side is closed as well.
- void ClosePort(const PortId& port_id,
- int process_id,
- int routing_id,
- bool force_close);
-
- // Closes the message channel associated with the given port, and notifies
- // the other side.
- void CloseChannel(const PortId& port_id, const std::string& error_message);
-
- // Enqueues a message on a pending channel, or sends a message to the given
- // port if the channel isn't pending.
- void PostMessage(const PortId& port_id, const Message& message);
-
- private:
- friend class MockMessageService;
- friend class BrowserContextKeyedAPIFactory<MessageService>;
- struct OpenChannelParams;
-
- // A map of channel ID to its channel object.
- using MessageChannelMap =
- std::map<ChannelId, std::unique_ptr<MessageChannel>>;
-
- using PendingMessage = std::pair<PortId, Message>;
- using PendingMessagesQueue = std::vector<PendingMessage>;
- // A set of channel IDs waiting to complete opening, and any pending messages
- // queued to be sent on those channels.
- using PendingChannelMap = std::map<ChannelId, PendingMessagesQueue>;
-
- // A map of channel ID to information about the extension that is waiting
- // for that channel to open. Used for lazy background pages.
- using PendingLazyBackgroundPageChannel =
- std::pair<content::BrowserContext*, ExtensionId>;
- using PendingLazyBackgroundPageChannelMap =
- std::map<ChannelId, PendingLazyBackgroundPageChannel>;
-
- // Common implementation for opening a channel configured by |params|.
- //
- // |target_extension| will be non-null if |params->target_extension_id| is
- // non-empty, that is, if the target is an extension, it must exist.
- //
- // |did_enqueue| will be true if the channel opening was delayed while
- // waiting for an event page to start, false otherwise.
- void OpenChannelImpl(content::BrowserContext* browser_context,
- std::unique_ptr<OpenChannelParams> params,
- const Extension* target_extension,
- bool did_enqueue);
-
- void ClosePortImpl(const PortId& port_id,
- int process_id,
- int routing_id,
- bool force_close,
- const std::string& error_message);
-
- void CloseChannelImpl(MessageChannelMap::iterator channel_iter,
- const PortId& port_id,
- const std::string& error_message,
- bool notify_other_port);
-
- // Have MessageService take ownership of |channel|, and remove any pending
- // channels with the same id.
- void AddChannel(std::unique_ptr<MessageChannel> channel,
- const PortId& receiver_port_id);
-
- // If the channel is being opened from an incognito tab the user must allow
- // the connection.
- void OnOpenChannelAllowed(std::unique_ptr<OpenChannelParams> params,
- bool allowed);
- void GotChannelID(std::unique_ptr<OpenChannelParams> params,
- const std::string& tls_channel_id);
-
- // Enqueues a message on a pending channel.
- void EnqueuePendingMessage(const PortId& port_id,
- const ChannelId& channel_id,
- const Message& message);
-
- // Enqueues a message on a channel pending on a lazy background page load.
- void EnqueuePendingMessageForLazyBackgroundLoad(const PortId& port_id,
- const ChannelId& channel_id,
- const Message& message);
-
- // Immediately sends a message to the given port.
- void DispatchMessage(const PortId& port_id,
- MessageChannel* channel,
- const Message& message);
-
- // Potentially registers a pending task with the LazyBackgroundTaskQueue
- // to open a channel. Returns true if a task was queued.
- // Takes ownership of |params| if true is returned.
- bool MaybeAddPendingLazyBackgroundPageOpenChannelTask(
- content::BrowserContext* context,
- const Extension* extension,
- std::unique_ptr<OpenChannelParams>* params,
- const PendingMessagesQueue& pending_messages);
-
- // Callbacks for LazyBackgroundTaskQueue tasks. The queue passes in an
- // ExtensionHost to its task callbacks, though some of our callbacks don't
- // use that argument.
- void PendingLazyBackgroundPageOpenChannel(
- std::unique_ptr<OpenChannelParams> params,
- int source_process_id,
- extensions::ExtensionHost* host);
- void PendingLazyBackgroundPageClosePort(const PortId& port_id,
- int process_id,
- int routing_id,
- bool force_close,
- const std::string& error_message,
- extensions::ExtensionHost* host) {
- if (host)
- ClosePortImpl(port_id, process_id, routing_id, force_close,
- error_message);
- }
- void PendingLazyBackgroundPagePostMessage(const PortId& port_id,
- const Message& message,
- extensions::ExtensionHost* host) {
- if (host)
- PostMessage(port_id, message);
- }
-
- // Immediate dispatches a disconnect to |source| for |port_id|. Sets source's
- // runtime.lastMessage to |error_message|, if any.
- void DispatchOnDisconnect(content::RenderFrameHost* source,
- const PortId& port_id,
- const std::string& error_message);
-
- void DispatchPendingMessages(const PendingMessagesQueue& queue,
- const ChannelId& channel_id);
-
- // BrowserContextKeyedAPI implementation.
- static const char* service_name() {
- return "MessageService";
- }
- static const bool kServiceRedirectedInIncognito = true;
- static const bool kServiceIsCreatedWithBrowserContext = false;
- static const bool kServiceIsNULLWhileTesting = true;
-
- MessageChannelMap channels_;
- // A set of channel IDs waiting for TLS channel IDs to complete opening, and
- // any pending messages queued to be sent on those channels. This and the
- // following two maps form a pipeline where messages are queued before the
- // channel they are addressed to is ready.
- PendingChannelMap pending_tls_channel_id_channels_;
- // A set of channel IDs waiting for user permission to cross the border
- // between an incognito page and an app or extension, and any pending messages
- // queued to be sent on those channels.
- PendingChannelMap pending_incognito_channels_;
- PendingLazyBackgroundPageChannelMap pending_lazy_background_page_channels_;
- MessagePropertyProvider property_provider_;
-
- // Weak pointer. Guaranteed to outlive this class.
- LazyBackgroundTaskQueue* lazy_background_task_queue_;
-
- base::WeakPtrFactory<MessageService> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(MessageService);
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc
index 4cdffbc8b64..3c694ff0d7f 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc
@@ -11,6 +11,7 @@
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
#include "content/public/browser/browser_thread.h"
+#include "extensions/common/api/messaging/message.h"
namespace extensions {
@@ -83,10 +84,10 @@ void NativeMessagePort::Core::CloseChannel(const std::string& error_message) {
}
NativeMessagePort::NativeMessagePort(
- base::WeakPtr<MessageService> message_service,
+ base::WeakPtr<ChannelDelegate> channel_delegate,
const PortId& port_id,
std::unique_ptr<NativeMessageHost> native_message_host)
- : weak_message_service_(message_service),
+ : weak_channel_delegate_(channel_delegate),
host_task_runner_(native_message_host->task_runner()),
port_id_(port_id),
weak_factory_(this) {
@@ -116,16 +117,16 @@ void NativeMessagePort::DispatchOnMessage(const Message& message) {
void NativeMessagePort::PostMessageFromNativeHost(const std::string& message) {
DCHECK(thread_checker_.CalledOnValidThread());
- if (weak_message_service_) {
- weak_message_service_->PostMessage(
+ if (weak_channel_delegate_) {
+ weak_channel_delegate_->PostMessage(
port_id_, Message(message, false /* user_gesture */));
}
}
void NativeMessagePort::CloseChannel(const std::string& error_message) {
DCHECK(thread_checker_.CalledOnValidThread());
- if (weak_message_service_) {
- weak_message_service_->CloseChannel(port_id_, error_message);
+ if (weak_channel_delegate_) {
+ weak_channel_delegate_->CloseChannel(port_id_, error_message);
}
}
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_port.h b/chromium/chrome/browser/extensions/api/messaging/native_message_port.h
index ecfa6ac9f1f..1e7684bb304 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_port.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_port.h
@@ -5,22 +5,29 @@
#ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGE_PORT_H_
#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGE_PORT_H_
+#include "base/memory/ref_counted.h"
+#include "base/memory/weak_ptr.h"
#include "base/threading/thread_checker.h"
-#include "chrome/browser/extensions/api/messaging/message_service.h"
+#include "extensions/browser/api/messaging/message_port.h"
#include "extensions/common/api/messaging/port_id.h"
+namespace base {
+class SingleThreadTaskRunner;
+}
+
namespace extensions {
+class NativeMessageHost;
// A port that manages communication with a native application.
// All methods must be called on the UI Thread of the browser process.
-class NativeMessagePort : public MessageService::MessagePort {
+class NativeMessagePort : public MessagePort {
public:
- NativeMessagePort(base::WeakPtr<MessageService> message_service,
+ NativeMessagePort(base::WeakPtr<ChannelDelegate> channel_delegate,
const PortId& port_id,
std::unique_ptr<NativeMessageHost> native_message_host);
~NativeMessagePort() override;
- // MessageService::MessagePort implementation.
+ // MessagePort implementation.
bool IsValidPort() override;
void DispatchOnMessage(const Message& message) override;
@@ -30,7 +37,7 @@ class NativeMessagePort : public MessageService::MessagePort {
void CloseChannel(const std::string& error_message);
base::ThreadChecker thread_checker_;
- base::WeakPtr<MessageService> weak_message_service_;
+ base::WeakPtr<ChannelDelegate> weak_channel_delegate_;
scoped_refptr<base::SingleThreadTaskRunner> host_task_runner_;
const PortId port_id_;
std::unique_ptr<Core> core_;
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc
index 8f9410f00a4..207bae83545 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc
@@ -3,17 +3,9 @@
// found in the LICENSE file.
#include "chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h"
+#include "components/prefs/pref_value_map.h"
-#include <utility>
-
-#include "base/logging.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h"
-#include "chrome/browser/extensions/external_policy_loader.h"
-#include "components/policy/core/browser/policy_error_map.h"
-#include "components/policy/core/common/policy_map.h"
-#include "components/policy/policy_constants.h"
-#include "components/prefs/pref_value_map.h"
-#include "components/strings/grit/components_strings.h"
namespace extensions {
@@ -21,73 +13,25 @@ NativeMessagingHostListPolicyHandler::NativeMessagingHostListPolicyHandler(
const char* policy_name,
const char* pref_path,
bool allow_wildcards)
- : policy::TypeCheckingPolicyHandler(policy_name, base::Value::Type::LIST),
+ : policy::ListPolicyHandler(policy_name, base::Value::Type::STRING),
pref_path_(pref_path),
allow_wildcards_(allow_wildcards) {}
NativeMessagingHostListPolicyHandler::~NativeMessagingHostListPolicyHandler() {}
-bool NativeMessagingHostListPolicyHandler::CheckPolicySettings(
- const policy::PolicyMap& policies,
- policy::PolicyErrorMap* errors) {
- return CheckAndGetList(policies, errors, NULL);
-}
-
-void NativeMessagingHostListPolicyHandler::ApplyPolicySettings(
- const policy::PolicyMap& policies,
- PrefValueMap* prefs) {
- std::unique_ptr<base::ListValue> list;
- policy::PolicyErrorMap errors;
- if (CheckAndGetList(policies, &errors, &list) && list)
- prefs->SetValue(pref_path(), std::move(list));
-}
-
-const char* NativeMessagingHostListPolicyHandler::pref_path() const {
- return pref_path_;
-}
-
-bool NativeMessagingHostListPolicyHandler::CheckAndGetList(
- const policy::PolicyMap& policies,
- policy::PolicyErrorMap* errors,
- std::unique_ptr<base::ListValue>* names) {
- const base::Value* value = NULL;
- if (!CheckAndGetValue(policies, errors, &value))
- return false;
-
- if (!value)
+bool NativeMessagingHostListPolicyHandler::CheckListEntry(
+ const base::Value& value) {
+ const std::string& str = value.GetString();
+ if (allow_wildcards_ && str == "*")
return true;
- const base::ListValue* list_value = NULL;
- if (!value->GetAsList(&list_value)) {
- NOTREACHED();
- return false;
- }
-
- // Filter the list, rejecting any invalid native messaging host names.
- std::unique_ptr<base::ListValue> filtered_list(new base::ListValue());
- for (base::ListValue::const_iterator entry(list_value->begin());
- entry != list_value->end(); ++entry) {
- std::string name;
- if (!entry->GetAsString(&name)) {
- errors->AddError(policy_name(), entry - list_value->begin(),
- IDS_POLICY_TYPE_ERROR,
- base::Value::GetTypeName(base::Value::Type::STRING));
- continue;
- }
- if (!(allow_wildcards_ && name == "*") &&
- !NativeMessagingHostManifest::IsValidName(name)) {
- errors->AddError(policy_name(),
- entry - list_value->begin(),
- IDS_POLICY_VALUE_FORMAT_ERROR);
- continue;
- }
- filtered_list->AppendString(name);
- }
-
- if (names)
- *names = std::move(filtered_list);
+ return NativeMessagingHostManifest::IsValidName(str);
+}
- return true;
+void NativeMessagingHostListPolicyHandler::ApplyList(
+ std::unique_ptr<base::ListValue> filtered_list,
+ PrefValueMap* prefs) {
+ prefs->SetValue(pref_path_, std::move(filtered_list));
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h
index 5257812be8e..456f60a4476 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h
@@ -11,36 +11,26 @@
#include "base/values.h"
#include "components/policy/core/browser/configuration_policy_handler.h"
-namespace policy {
-class PolicyMap;
-class PolicyErrorMap;
-} // namespace policy
-
namespace extensions {
// Implements additional checks for policies that are lists of Native Messaging
// Hosts.
-class NativeMessagingHostListPolicyHandler
- : public policy::TypeCheckingPolicyHandler {
+class NativeMessagingHostListPolicyHandler : public policy::ListPolicyHandler {
public:
NativeMessagingHostListPolicyHandler(const char* policy_name,
const char* pref_path,
bool allow_wildcards);
~NativeMessagingHostListPolicyHandler() override;
- // ConfigurationPolicyHandler methods:
- bool CheckPolicySettings(const policy::PolicyMap& policies,
- policy::PolicyErrorMap* errors) override;
- void ApplyPolicySettings(const policy::PolicyMap& policies,
- PrefValueMap* prefs) override;
-
protected:
- const char* pref_path() const;
+ // ListPolicyHandler methods:
+
+ // Checks whether |value| contains a valid host name (or a wildcard).
+ bool CheckListEntry(const base::Value& value) override;
- // Runs sanity checks on the policy value and returns it in |extension_ids|.
- bool CheckAndGetList(const policy::PolicyMap& policies,
- policy::PolicyErrorMap* errors,
- std::unique_ptr<base::ListValue>* extension_ids);
+ // Sets |prefs| at pref_path() to |filtered_list|.
+ void ApplyList(std::unique_ptr<base::ListValue> filtered_list,
+ PrefValueMap* prefs) override;
private:
const char* pref_path_;
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc
index 806cd753217..91762123572 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc
@@ -81,7 +81,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, ApplyPolicySettings) {
policy::POLICY_SOURCE_CLOUD, policy.CreateDeepCopy(), nullptr);
handler.ApplyPolicySettings(policy_map, &prefs);
EXPECT_TRUE(prefs.GetValue(kTestPref, &value));
- EXPECT_TRUE(base::Value::Equals(&expected, value));
+ EXPECT_EQ(expected, *value);
policy.AppendString("*");
expected.AppendString("*");
@@ -91,7 +91,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, ApplyPolicySettings) {
policy::POLICY_SOURCE_CLOUD, policy.CreateDeepCopy(), nullptr);
handler.ApplyPolicySettings(policy_map, &prefs);
EXPECT_TRUE(prefs.GetValue(kTestPref, &value));
- EXPECT_TRUE(base::Value::Equals(&expected, value));
+ EXPECT_EQ(expected, *value);
policy.AppendString("invalid Name");
policy_map.Set(policy::key::kNativeMessagingBlacklist,
@@ -99,7 +99,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, ApplyPolicySettings) {
policy::POLICY_SOURCE_CLOUD, policy.CreateDeepCopy(), nullptr);
handler.ApplyPolicySettings(policy_map, &prefs);
EXPECT_TRUE(prefs.GetValue(kTestPref, &value));
- EXPECT_TRUE(base::Value::Equals(&expected, value));
+ EXPECT_EQ(expected, *value);
}
} // namespace extensions
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 2527742857c..ec99eaed500 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
@@ -4,6 +4,7 @@
#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
+#include <inttypes.h>
#include <utility>
#include "base/bind.h"
@@ -192,7 +193,7 @@ void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool(
// way the host will be able to create properly focused UI windows.
#if defined(OS_WIN)
command_line.AppendArg(
- base::StringPrintf("--parent-window=%d", window_handle_));
+ base::StringPrintf("--parent-window=%" PRIdPTR, window_handle_));
#endif // !defined(OS_WIN)
base::Process process;
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc
index c2176436493..0a5d0166333 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc
@@ -55,7 +55,7 @@ bool NativeProcessLauncher::LaunchNativeProcess(
base::Process* process,
base::File* read_file,
base::File* write_file) {
- base::FileHandleMappingVector fd_map;
+ base::LaunchOptions options;
int read_pipe_fds[2] = {0};
if (HANDLE_EINTR(pipe(read_pipe_fds)) != 0) {
@@ -64,7 +64,8 @@ bool NativeProcessLauncher::LaunchNativeProcess(
}
base::ScopedFD read_pipe_read_fd(read_pipe_fds[0]);
base::ScopedFD read_pipe_write_fd(read_pipe_fds[1]);
- fd_map.push_back(std::make_pair(read_pipe_write_fd.get(), STDOUT_FILENO));
+ options.fds_to_remap.push_back(
+ std::make_pair(read_pipe_write_fd.get(), STDOUT_FILENO));
int write_pipe_fds[2] = {0};
if (HANDLE_EINTR(pipe(write_pipe_fds)) != 0) {
@@ -73,11 +74,10 @@ bool NativeProcessLauncher::LaunchNativeProcess(
}
base::ScopedFD write_pipe_read_fd(write_pipe_fds[0]);
base::ScopedFD write_pipe_write_fd(write_pipe_fds[1]);
- fd_map.push_back(std::make_pair(write_pipe_read_fd.get(), STDIN_FILENO));
+ options.fds_to_remap.push_back(
+ std::make_pair(write_pipe_read_fd.get(), STDIN_FILENO));
- base::LaunchOptions options;
options.current_directory = command_line.GetProgram().DirName();
- options.fds_to_remap = &fd_map;
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
// Don't use no_new_privs mode, e.g. in case the host needs to use sudo.
diff --git a/chromium/chrome/browser/extensions/api/music_manager_private/device_id.h b/chromium/chrome/browser/extensions/api/music_manager_private/device_id.h
index 21f56fd12d7..7a1cf5dafef 100644
--- a/chromium/chrome/browser/extensions/api/music_manager_private/device_id.h
+++ b/chromium/chrome/browser/extensions/api/music_manager_private/device_id.h
@@ -10,6 +10,7 @@
#include <string>
#include "base/bind.h"
+#include "base/task_scheduler/task_traits.h"
namespace extensions {
namespace api {
@@ -42,6 +43,15 @@ class DeviceId {
// identified as invalid, i.e. not unique. For example, some VM hosts assign a
// new MAC addresses at each reboot.
static bool IsValidMacAddress(const void* bytes, size_t size);
+
+ // The traits of the task that retrieves the device id.
+ //
+ // MayBlock(): Since this requires fetching disk.
+ // TaskPriority: USER_VISIBLE. Though this might be conservative, depending
+ // on how GetDeviceId() is used.
+ static constexpr base::TaskTraits traits() {
+ return {base::MayBlock(), base::TaskPriority::USER_VISIBLE};
+ }
};
} // namespace api
diff --git a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_linux.cc b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_linux.cc
index 0484c0a49da..a7d93cba4fa 100644
--- a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_linux.cc
+++ b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_linux.cc
@@ -20,6 +20,7 @@
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
+#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_thread.h"
@@ -195,10 +196,10 @@ namespace api {
void DeviceId::GetRawDeviceId(const IdCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(GetRawDeviceIdImpl,
- base::Bind(DeviceId::IsValidMacAddress), callback));
+ base::PostTaskWithTraits(
+ FROM_HERE, traits(),
+ base::BindOnce(&GetRawDeviceIdImpl,
+ base::Bind(&DeviceId::IsValidMacAddress), callback));
}
} // namespace api
diff --git a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_mac.cc b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_mac.cc
index f350f26e1ab..2e7e8562bd5 100644
--- a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_mac.cc
+++ b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_mac.cc
@@ -21,6 +21,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
+#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_thread.h"
@@ -243,12 +244,10 @@ namespace api {
void DeviceId::GetRawDeviceId(const IdCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE,
- FROM_HERE,
- base::Bind(GetRawDeviceIdImpl,
- base::Bind(DeviceId::IsValidMacAddress),
- callback));
+ base::PostTaskWithTraits(
+ FROM_HERE, traits(),
+ base::Bind(&GetRawDeviceIdImpl, base::Bind(&DeviceId::IsValidMacAddress),
+ callback));
}
} // namespace api
diff --git a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc
index 6455e9a8f86..da75dc257b1 100644
--- a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc
+++ b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc
@@ -22,6 +22,7 @@
#include "base/scoped_native_library.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
+#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "base/win/windows_version.h"
#include "content/public/browser/browser_thread.h"
@@ -215,12 +216,10 @@ namespace api {
void DeviceId::GetRawDeviceId(const IdCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE,
- FROM_HERE,
- base::Bind(GetMacAddress,
- base::Bind(DeviceId::IsValidMacAddress),
- base::Bind(GetMacAddressCallback, callback)));
+ base::PostTaskWithTraits(
+ FROM_HERE, traits(),
+ base::Bind(&GetMacAddress, base::Bind(&DeviceId::IsValidMacAddress),
+ base::Bind(&GetMacAddressCallback, callback)));
}
} // namespace api
diff --git a/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc
index 7c9675385d1..56cd505bf57 100644
--- a/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc
@@ -6,6 +6,7 @@
#include "base/location.h"
#include "base/macros.h"
+#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
index 918c0f4b162..10c2cab24d8 100644
--- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
@@ -10,6 +10,7 @@
#include "base/command_line.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
+#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/helper.h"
@@ -378,11 +379,10 @@ class NetworkingPrivateChromeOSApiTest : public ExtensionApiTest {
// Add IPConfigs
base::DictionaryValue ipconfig;
- ipconfig.SetStringWithoutPathExpansion(shill::kAddressProperty, "0.0.0.0");
- ipconfig.SetStringWithoutPathExpansion(shill::kGatewayProperty, "0.0.0.1");
- ipconfig.SetIntegerWithoutPathExpansion(shill::kPrefixlenProperty, 0);
- ipconfig.SetStringWithoutPathExpansion(shill::kMethodProperty,
- shill::kTypeIPv4);
+ ipconfig.SetKey(shill::kAddressProperty, base::Value("0.0.0.0"));
+ ipconfig.SetKey(shill::kGatewayProperty, base::Value("0.0.0.1"));
+ ipconfig.SetKey(shill::kPrefixlenProperty, base::Value(0));
+ ipconfig.SetKey(shill::kMethodProperty, base::Value(shill::kTypeIPv4));
ip_config_test->AddIPConfig(kIPConfigPath, ipconfig);
// Add Devices
@@ -424,8 +424,7 @@ class NetworkingPrivateChromeOSApiTest : public ExtensionApiTest {
service_test_->SetServiceProperty(kWifi1ServicePath, shill::kDeviceProperty,
base::Value(kWifiDevicePath));
base::DictionaryValue static_ipconfig;
- static_ipconfig.SetStringWithoutPathExpansion(shill::kAddressProperty,
- "1.2.3.4");
+ static_ipconfig.SetKey(shill::kAddressProperty, base::Value("1.2.3.4"));
service_test_->SetServiceProperty(
kWifi1ServicePath, shill::kStaticIPConfigProperty, static_ipconfig);
base::ListValue frequencies1;
@@ -880,12 +879,13 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, CellularSimPuk) {
IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetGlobalPolicy) {
base::DictionaryValue global_config;
- global_config.SetBooleanWithoutPathExpansion(
+ global_config.SetKey(
::onc::global_network_config::kAllowOnlyPolicyNetworksToAutoconnect,
- true);
- global_config.SetBooleanWithoutPathExpansion(
- ::onc::global_network_config::kAllowOnlyPolicyNetworksToConnect, false);
- global_config.SetBooleanWithoutPathExpansion("SomeNewGlobalPolicy", false);
+ base::Value(true));
+ global_config.SetKey(
+ ::onc::global_network_config::kAllowOnlyPolicyNetworksToConnect,
+ base::Value(false));
+ global_config.SetKey("SomeNewGlobalPolicy", base::Value(false));
chromeos::NetworkHandler::Get()
->managed_network_configuration_handler()
->SetPolicy(::onc::ONC_SOURCE_DEVICE_POLICY,
diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto.cc
index 3c82b8b5e6c..5dca9176640 100644
--- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto.cc
+++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto.cc
@@ -13,6 +13,7 @@
#include "components/cast_certificate/cast_cert_validator.h"
#include "crypto/openssl_util.h"
#include "crypto/rsa_private_key.h"
+#include "net/cert/internal/signature_algorithm.h"
#include "net/cert/pem_tokenizer.h"
#include "third_party/boringssl/src/include/openssl/evp.h"
#include "third_party/boringssl/src/include/openssl/rsa.h"
@@ -92,9 +93,10 @@ bool VerifyCredentialsAtTime(
cast_crypto::CastDeviceCertPolicy unused_policy;
std::unique_ptr<cast_crypto::CertVerificationContext> verification_context;
- if (!cast_crypto::VerifyDeviceCert(certs, time, &verification_context,
- &unused_policy, nullptr,
- cast_crypto::CRLPolicy::CRL_OPTIONAL)) {
+ if (cast_crypto::VerifyDeviceCert(certs, time, &verification_context,
+ &unused_policy, nullptr,
+ cast_crypto::CRLPolicy::CRL_OPTIONAL) !=
+ cast_crypto::CastCertError::OK) {
LOG(ERROR) << kErrorPrefix << "Failed verifying cast device cert";
return false;
}
@@ -112,7 +114,8 @@ bool VerifyCredentialsAtTime(
// Use the public key from verified certificate to verify |signature| over
// |data|.
- if (!verification_context->VerifySignatureOverData(signature, data)) {
+ if (!verification_context->VerifySignatureOverData(
+ signature, data, net::DigestAlgorithm::Sha1)) {
LOG(ERROR) << kErrorPrefix
<< "Failed verifying signature using cast device cert";
return false;
diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc
index 79360590416..4e3a9bf8ed8 100644
--- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc
+++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc
@@ -569,6 +569,11 @@ bool NotificationsCreateFunction::RunNotificationsApi() {
SetResult(base::MakeUnique<base::Value>(notification_id));
+ // TODO(crbug.com/749402): Cap the length of notification Ids to a certain
+ // limit if the histogram indicates that this is safe to do.
+ UMA_HISTOGRAM_COUNTS_1000("Notifications.ExtensionNotificationIdLength",
+ notification_id.size());
+
// TODO(dewittj): Add more human-readable error strings if this fails.
if (!CreateNotification(notification_id, &params_->options))
return false;
@@ -650,8 +655,8 @@ bool NotificationsGetAllFunction::RunNotificationsApi() {
for (std::set<std::string>::iterator iter = notification_ids.begin();
iter != notification_ids.end(); iter++) {
- result->SetBooleanWithoutPathExpansion(
- StripScopeFromIdentifier(extension_->id(), *iter), true);
+ result->SetKey(StripScopeFromIdentifier(extension_->id(), *iter),
+ base::Value(true));
}
SetResult(std::move(result));
diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc
index ec2f3e1d913..fef2b34cbc3 100644
--- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc
@@ -3,6 +3,7 @@
// found in the LICENSE file.
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
@@ -17,10 +18,9 @@
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_common.h"
-#include "chrome/browser/notifications/notification_display_service_factory.h"
+#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/notifications/notifier_state_tracker.h"
#include "chrome/browser/notifications/notifier_state_tracker_factory.h"
-#include "chrome/browser/notifications/stub_notification_display_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/extensions/app_launch_params.h"
#include "chrome/browser/ui/extensions/application_launch.h"
@@ -33,8 +33,8 @@
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/app_window/native_app_window.h"
#include "extensions/browser/notification_types.h"
+#include "extensions/common/extension_builder.h"
#include "extensions/common/features/feature.h"
-#include "extensions/common/test_util.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "ui/message_center/notifier_settings.h"
@@ -92,7 +92,7 @@ class UserGestureCatcher : public content::NotificationObserver {
.ptr()
->user_gesture());
if (waiting_)
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
content::NotificationRegistrar registrar_;
@@ -165,11 +165,6 @@ class NotificationsApiTest : public ExtensionApiTest {
return ExtensionNotificationDisplayHelperFactory::GetForProfile(profile());
}
- StubNotificationDisplayService* GetDisplayService() {
- return reinterpret_cast<StubNotificationDisplayService*>(
- NotificationDisplayServiceFactory::GetForProfile(profile()));
- }
-
NotifierStateTracker* GetNotifierStateTracker() {
return NotifierStateTrackerFactory::GetForProfile(profile());
}
@@ -179,8 +174,13 @@ class NotificationsApiTest : public ExtensionApiTest {
ExtensionApiTest::SetUpOnMainThread();
DCHECK(profile());
- NotificationDisplayServiceFactory::GetInstance()->SetTestingFactory(
- profile(), &StubNotificationDisplayService::FactoryForTests);
+ display_service_tester_ =
+ base::MakeUnique<NotificationDisplayServiceTester>(profile());
+ }
+
+ void TearDownOnMainThread() override {
+ display_service_tester_.reset();
+ ExtensionApiTest::TearDownOnMainThread();
}
// Returns the notification that's being displayed for |extension|, or nullptr
@@ -210,17 +210,17 @@ class NotificationsApiTest : public ExtensionApiTest {
}
void EnableFullscreenNotifications() {
- feature_list_.InitWithFeatures({
- features::kPreferHtmlOverPlugins,
- extensions::kAllowFullscreenAppNotificationsFeature}, {});
+ feature_list_.InitAndEnableFeature(
+ extensions::kAllowFullscreenAppNotificationsFeature);
}
void DisableFullscreenNotifications() {
- feature_list_.InitWithFeatures(
- {features::kPreferHtmlOverPlugins},
- {extensions::kAllowFullscreenAppNotificationsFeature});
+ feature_list_.InitAndDisableFeature(
+ extensions::kAllowFullscreenAppNotificationsFeature);
}
+ std::unique_ptr<NotificationDisplayServiceTester> display_service_tester_;
+
private:
base::test::ScopedFeatureList feature_list_;
};
@@ -256,7 +256,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestByUser) {
ResultCatcher catcher;
const std::string notification_id =
GetNotificationIdFromDelegateId(extension->id() + "-FOO");
- GetDisplayService()->RemoveNotification(
+ display_service_tester_->RemoveNotification(
NotificationCommon::EXTENSION, notification_id, false /* by_user */);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
@@ -265,21 +265,21 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestByUser) {
ResultCatcher catcher;
const std::string notification_id =
GetNotificationIdFromDelegateId(extension->id() + "-BAR");
- GetDisplayService()->RemoveNotification(
+ display_service_tester_->RemoveNotification(
NotificationCommon::EXTENSION, notification_id, true /* by_user */);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
{
ResultCatcher catcher;
- GetDisplayService()->RemoveAllNotifications(NotificationCommon::EXTENSION,
- false /* by_user */);
+ display_service_tester_->RemoveAllNotifications(
+ NotificationCommon::EXTENSION, false /* by_user */);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
{
ResultCatcher catcher;
- GetDisplayService()->RemoveAllNotifications(NotificationCommon::EXTENSION,
- true /* by_user */);
+ display_service_tester_->RemoveAllNotifications(
+ NotificationCommon::EXTENSION, true /* by_user */);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
}
@@ -309,7 +309,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestPartialUpdate) {
IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestGetPermissionLevel) {
scoped_refptr<Extension> empty_extension(
- extensions::test_util::CreateEmptyExtension());
+ extensions::ExtensionBuilder("Test").Build());
// Get permission level for the extension whose notifications are enabled.
{
diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc
index 2d9854e29ab..6fcfcfddccd 100644
--- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc
+++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc
@@ -212,12 +212,11 @@ void OmniboxAPI::OnExtensionLoaded(content::BrowserContext* browser_context,
if (!keyword.empty()) {
// Load the omnibox icon so it will be ready to display in the URL bar.
omnibox_icon_manager_.LoadIcon(profile_, extension);
-
if (url_service_) {
url_service_->Load();
if (url_service_->loaded()) {
url_service_->RegisterOmniboxKeyword(
- extension->id(), extension->name(), keyword,
+ extension->id(), extension->short_name(), keyword,
GetTemplateURLStringForExtension(extension->id()),
ExtensionPrefs::Get(profile_)->GetInstallTime(extension->id()));
} else {
@@ -249,7 +248,7 @@ void OmniboxAPI::OnTemplateURLsLoaded() {
template_url_sub_.reset();
for (const auto* i : pending_extensions_) {
url_service_->RegisterOmniboxKeyword(
- i->id(), i->name(), OmniboxInfo::GetKeyword(i),
+ i->id(), i->short_name(), OmniboxInfo::GetKeyword(i),
GetTemplateURLStringForExtension(i->id()),
ExtensionPrefs::Get(profile_)->GetInstallTime(i->id()));
}
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 7ec0dc27a1b..21e0e4ce9da 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,6 +11,8 @@
#include "base/bind_helpers.h"
#include "base/files/file_util.h"
#include "base/memory/ptr_util.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/threading/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
@@ -47,6 +49,17 @@ const char kTabClosedError[] = "Cannot find the tab for this request.";
const char kUserDenied[] = "User denied request.";
#endif
+constexpr base::TaskTraits kCreateTemporaryFileTaskTraits = {
+ // Requires IO.
+ base::MayBlock(),
+
+ // TaskPriority: Inherit.
+
+ // TaskShutdownBehavior: TemporaryFileCreated*() called from
+ // CreateTemporaryFile() might access global variable, so use
+ // SKIP_ON_SHUTDOWN. See ShareableFileReference::GetOrCreate().
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN};
+
void ClearFileReferenceOnIOThread(
scoped_refptr<storage::ShareableFileReference>) {}
@@ -100,8 +113,8 @@ bool PageCaptureSaveAsMHTMLFunction::RunAsync() {
}
#endif
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
+ base::PostTaskWithTraits(
+ FROM_HERE, kCreateTemporaryFileTaskTraits,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile,
this));
return true;
@@ -133,8 +146,8 @@ bool PageCaptureSaveAsMHTMLFunction::OnMessageReceived(
void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest(
const PermissionIDSet& allowed_permissions) {
if (allowed_permissions.ContainsID(APIPermission::kPageCapture)) {
- BrowserThread::PostTask(
- BrowserThread::FILE, FROM_HERE,
+ base::PostTaskWithTraits(
+ FROM_HERE, kCreateTemporaryFileTaskTraits,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile,
this));
} else {
@@ -144,30 +157,41 @@ void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest(
#endif
void PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ base::ThreadRestrictions::AssertIOAllowed();
bool success = base::CreateTemporaryFile(&mhtml_path_);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
- base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreated,
+ base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO,
this, success));
}
-void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreated(bool success) {
- if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
- if (success) {
- // Setup a ShareableFileReference so the temporary file gets deleted
- // once it is no longer used.
- mhtml_file_ = ShareableFileReference::GetOrCreate(
- mhtml_path_, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
- BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get());
- }
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreated,
- this, success));
- return;
+void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO(bool success) {
+ DCHECK_CURRENTLY_ON(BrowserThread::IO);
+ if (success) {
+ // Setup a ShareableFileReference so the temporary file gets deleted
+ // once it is no longer used.
+ mhtml_file_ = ShareableFileReference::GetOrCreate(
+ mhtml_path_, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
+ base::CreateSequencedTaskRunnerWithTraits(
+ {// Requires IO.
+ base::MayBlock(),
+
+ // TaskPriority: Inherit.
+
+ // Because we are using DELETE_ON_FINAL_RELEASE here, the
+ // storage::ScopedFile inside ShareableFileReference requires
+ // a shutdown blocking task runner to ensure that its deletion
+ // task runs.
+ base::TaskShutdownBehavior::BLOCK_SHUTDOWN})
+ .get());
}
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnUI,
+ this, success));
+}
+void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnUI(bool success) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!success) {
ReturnFailure(kTemporaryFileError);
diff --git a/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.h b/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.h
index 1f4f76d7d96..68ff9cb2645 100644
--- a/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.h
+++ b/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.h
@@ -50,8 +50,10 @@ class PageCaptureSaveAsMHTMLFunction : public ChromeAsyncExtensionFunction {
// Called on the file thread.
void CreateTemporaryFile();
+ void TemporaryFileCreatedOnIO(bool success);
+ void TemporaryFileCreatedOnUI(bool success);
+
// Called on the UI thread.
- void TemporaryFileCreated(bool success);
void ReturnFailure(const std::string& error);
void ReturnSuccess(int64_t file_size);
diff --git a/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc b/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
index c393e2e4564..10671beb8e2 100644
--- a/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
@@ -58,7 +58,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest, SaveAsMHTML) {
// Make sure the MHTML data gets written to the temporary file.
ASSERT_FALSE(delegate.temp_file_.empty());
// Flush the message loops to make sure the delete happens.
- content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
+ content::RunAllBlockingPoolTasksUntilIdle();
content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
// Make sure the temporary file is destroyed once the javascript side reads
// the contents.
@@ -76,7 +76,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest,
ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);
ASSERT_TRUE(RunExtensionTest("page_capture")) << message_;
ASSERT_FALSE(delegate.temp_file_.empty());
- content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
+ content::RunAllBlockingPoolTasksUntilIdle();
content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
base::ThreadRestrictions::ScopedAllowIO allow_io;
ASSERT_FALSE(base::PathExists(delegate.temp_file_));
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 cada03f3bce..4372d80fa7b 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
@@ -57,9 +57,9 @@ struct PublicKeyInfo {
void BuildWebCryptoRSAAlgorithmDictionary(const PublicKeyInfo& key_info,
base::DictionaryValue* algorithm) {
CHECK_EQ(net::X509Certificate::kPublicKeyTypeRSA, key_info.key_type);
- algorithm->SetStringWithoutPathExpansion("name", kWebCryptoRSASSA_PKCS1_v1_5);
- algorithm->SetIntegerWithoutPathExpansion("modulusLength",
- key_info.key_size_bits);
+ algorithm->SetKey("name", base::Value(kWebCryptoRSASSA_PKCS1_v1_5));
+ algorithm->SetKey("modulusLength",
+ base::Value(static_cast<int>(key_info.key_size_bits)));
// Equals 65537.
const unsigned char defaultPublicExponent[] = {0x01, 0x00, 0x01};
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 5364c9676d1..73d502cf1bb 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
@@ -10,6 +10,7 @@
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
+#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys_service.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h"
@@ -195,8 +196,7 @@ class PlatformKeysTest : public ExtensionApiTest {
{
std::unique_ptr<base::DictionaryValue> cert1_key_permission(
new base::DictionaryValue);
- cert1_key_permission->SetBooleanWithoutPathExpansion(
- "allowCorporateKeyUsage", true);
+ cert1_key_permission->SetKey("allowCorporateKeyUsage", base::Value(true));
key_permissions_policy.SetWithoutPathExpansion(
extension_->id(), std::move(cert1_key_permission));
}
@@ -207,8 +207,8 @@ class PlatformKeysTest : public ExtensionApiTest {
&key_permissions_policy_str);
base::DictionaryValue user_policy;
- user_policy.SetStringWithoutPathExpansion(policy::key::kKeyPermissions,
- key_permissions_policy_str);
+ user_policy.SetKey(policy::key::kKeyPermissions,
+ base::Value(key_permissions_policy_str));
policy_helper_->UpdatePolicy(
user_policy, base::DictionaryValue() /* empty recommended policy */,
diff --git a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc
deleted file mode 100644
index db511d051b8..00000000000
--- a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc
+++ /dev/null
@@ -1,93 +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 "chrome/browser/extensions/api/preference/chrome_direct_setting.h"
-
-#include <utility>
-
-#include "base/containers/hash_tables.h"
-#include "base/lazy_instance.h"
-#include "base/values.h"
-#include "chrome/browser/extensions/api/preference/chrome_direct_setting_api.h"
-#include "chrome/browser/extensions/api/preference/preference_api_constants.h"
-#include "chrome/browser/profiles/profile.h"
-#include "components/prefs/pref_service.h"
-
-namespace extensions {
-namespace chromedirectsetting {
-
-DirectSettingFunctionBase::DirectSettingFunctionBase() {}
-
-DirectSettingFunctionBase::~DirectSettingFunctionBase() {}
-
-PrefService* DirectSettingFunctionBase::GetPrefService() {
- return Profile::FromBrowserContext(browser_context())->GetPrefs();
-}
-
-GetDirectSettingFunction::GetDirectSettingFunction() {}
-
-ExtensionFunction::ResponseAction GetDirectSettingFunction::Run() {
- std::string pref_key;
- EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key));
- EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(browser_context())
- ->IsPreferenceOnWhitelist(pref_key));
-
- const PrefService::Preference* preference =
- GetPrefService()->FindPreference(pref_key.c_str());
- EXTENSION_FUNCTION_VALIDATE(preference);
- const base::Value* value = preference->GetValue();
-
- std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue);
- result->Set(preference_api_constants::kValue, value->CreateDeepCopy());
- return RespondNow(OneArgument(std::move(result)));
-}
-
-GetDirectSettingFunction::~GetDirectSettingFunction() {}
-
-SetDirectSettingFunction::SetDirectSettingFunction() {}
-
-ExtensionFunction::ResponseAction SetDirectSettingFunction::Run() {
- std::string pref_key;
- EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key));
- EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(browser_context())
- ->IsPreferenceOnWhitelist(pref_key));
-
- base::DictionaryValue* details = NULL;
- EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &details));
-
- base::Value* value = NULL;
- EXTENSION_FUNCTION_VALIDATE(
- details->Get(preference_api_constants::kValue, &value));
-
- PrefService* pref_service = GetPrefService();
- const PrefService::Preference* preference =
- pref_service->FindPreference(pref_key.c_str());
- EXTENSION_FUNCTION_VALIDATE(preference);
-
- EXTENSION_FUNCTION_VALIDATE(value->GetType() == preference->GetType());
-
- pref_service->Set(pref_key.c_str(), *value);
-
- return RespondNow(NoArguments());
-}
-
-SetDirectSettingFunction::~SetDirectSettingFunction() {}
-
-ClearDirectSettingFunction::ClearDirectSettingFunction() {}
-
-ExtensionFunction::ResponseAction ClearDirectSettingFunction::Run() {
- std::string pref_key;
- EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key));
- EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(browser_context())
- ->IsPreferenceOnWhitelist(pref_key));
- GetPrefService()->ClearPref(pref_key.c_str());
-
- return RespondNow(NoArguments());
-}
-
-ClearDirectSettingFunction::~ClearDirectSettingFunction() {}
-
-} // namespace chromedirectsetting
-} // namespace extensions
-
diff --git a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h
deleted file mode 100644
index c58cab26e96..00000000000
--- a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h
+++ /dev/null
@@ -1,85 +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.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_PREFERENCE_CHROME_DIRECT_SETTING_H__
-#define CHROME_BROWSER_EXTENSIONS_API_PREFERENCE_CHROME_DIRECT_SETTING_H__
-
-#include "base/lazy_instance.h"
-#include "base/macros.h"
-#include "extensions/browser/extension_function.h"
-
-class PrefService;
-
-namespace extensions {
-namespace chromedirectsetting {
-
-// Base class to host instance method helpers.
-class DirectSettingFunctionBase : public UIThreadExtensionFunction {
- protected:
- DirectSettingFunctionBase();
- ~DirectSettingFunctionBase() override;
-
- // Returns the user pref service.
- PrefService* GetPrefService();
-
- // Returns true if the caller is a component extension.
- bool IsCalledFromComponentExtension();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(DirectSettingFunctionBase);
-};
-
-class GetDirectSettingFunction : public DirectSettingFunctionBase {
- public:
- DECLARE_EXTENSION_FUNCTION("types.private.ChromeDirectSetting.get",
- TYPES_PRIVATE_CHROMEDIRECTSETTING_GET)
-
- GetDirectSettingFunction();
-
- protected:
- // ExtensionFunction:
- ResponseAction Run() override;
-
- private:
- ~GetDirectSettingFunction() override;
- DISALLOW_COPY_AND_ASSIGN(GetDirectSettingFunction);
-};
-
-class SetDirectSettingFunction : public DirectSettingFunctionBase {
- public:
- DECLARE_EXTENSION_FUNCTION("types.private.ChromeDirectSetting.set",
- TYPES_PRIVATE_CHROMEDIRECTSETTING_SET)
-
- SetDirectSettingFunction();
-
- protected:
- // ExtensionFunction:
- ResponseAction Run() override;
-
- private:
- ~SetDirectSettingFunction() override;
- DISALLOW_COPY_AND_ASSIGN(SetDirectSettingFunction);
-};
-
-class ClearDirectSettingFunction : public DirectSettingFunctionBase {
- public:
- DECLARE_EXTENSION_FUNCTION("types.private.ChromeDirectSetting.clear",
- TYPES_PRIVATE_CHROMEDIRECTSETTING_CLEAR)
-
- ClearDirectSettingFunction();
-
- protected:
- // ExtensionFunction:
- ResponseAction Run() override;
-
- private:
- ~ClearDirectSettingFunction() override;
- DISALLOW_COPY_AND_ASSIGN(ClearDirectSettingFunction);
-};
-
-} // namespace chromedirectsetting
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_PREFERENCE_CHROME_DIRECT_SETTING_H__
-
diff --git a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc
deleted file mode 100644
index 5bf1d8f7a02..00000000000
--- a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc
+++ /dev/null
@@ -1,169 +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 "chrome/browser/extensions/api/preference/chrome_direct_setting_api.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/containers/hash_tables.h"
-#include "base/lazy_instance.h"
-#include "base/macros.h"
-#include "base/strings/stringprintf.h"
-#include "chrome/browser/extensions/api/preference/preference_api_constants.h"
-#include "chrome/browser/profiles/profile.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "components/prefs/pref_service.h"
-#include "extensions/browser/extension_registry.h"
-
-namespace extensions {
-namespace chromedirectsetting {
-
-const char kOnPrefChangeFormat[] =
- "types.private.ChromeDirectSetting.%s.onChange";
-
-class PreferenceWhitelist {
- public:
- PreferenceWhitelist() {
- // Note: DO NOT add any setting here that does not have a UI element in
- // chrome://settings unless you write a component extension that is always
- // installed. Otherwise, users may install your extension, the extension may
- // toggle settings, and after the extension has been disabled/uninstalled
- // the toggled setting remains in place. See http://crbug.com/164227#c157 .
- // The following settings need to be checked and probably removed. See
- // http://crbug.com/164227#c157 .
- whitelist_.insert("easy_unlock.proximity_required");
- }
-
- ~PreferenceWhitelist() {}
-
- bool IsPreferenceOnWhitelist(const std::string& pref_key){
- return whitelist_.find(pref_key) != whitelist_.end();
- }
-
- void RegisterEventListeners(
- Profile* profile,
- EventRouter::Observer* observer) {
- for (base::hash_set<std::string>::iterator iter = whitelist_.begin();
- iter != whitelist_.end();
- iter++) {
- std::string event_name = base::StringPrintf(
- kOnPrefChangeFormat,
- (*iter).c_str());
- EventRouter::Get(profile)->RegisterObserver(observer, event_name);
- }
- }
-
- void RegisterPropertyListeners(
- Profile* profile,
- PrefChangeRegistrar* registrar,
- const base::Callback<void(const std::string&)>& callback) {
- for (base::hash_set<std::string>::iterator iter = whitelist_.begin();
- iter != whitelist_.end();
- iter++) {
- const char* pref_key = (*iter).c_str();
- std::string event_name = base::StringPrintf(
- kOnPrefChangeFormat,
- pref_key);
- registrar->Add(pref_key, callback);
- }
- }
-
- private:
- base::hash_set<std::string> whitelist_;
-
- DISALLOW_COPY_AND_ASSIGN(PreferenceWhitelist);
-};
-
-base::LazyInstance<PreferenceWhitelist>::DestructorAtExit preference_whitelist =
- LAZY_INSTANCE_INITIALIZER;
-
-static base::LazyInstance<
- BrowserContextKeyedAPIFactory<ChromeDirectSettingAPI>>::DestructorAtExit
- g_factory = LAZY_INSTANCE_INITIALIZER;
-
-ChromeDirectSettingAPI::ChromeDirectSettingAPI(content::BrowserContext* context)
- : profile_(Profile::FromBrowserContext(context)) {
- preference_whitelist.Get().RegisterEventListeners(profile_, this);
-}
-
-ChromeDirectSettingAPI::~ChromeDirectSettingAPI() {}
-
-// KeyedService implementation.
-void ChromeDirectSettingAPI::Shutdown() {}
-
-// BrowserContextKeyedAPI implementation.
-BrowserContextKeyedAPIFactory<ChromeDirectSettingAPI>*
-ChromeDirectSettingAPI::GetFactoryInstance() {
- return g_factory.Pointer();
-}
-
-// EventRouter::Observer implementation.
-void ChromeDirectSettingAPI::OnListenerAdded(const EventListenerInfo& details) {
- EventRouter::Get(profile_)->UnregisterObserver(this);
- registrar_.Init(profile_->GetPrefs());
- preference_whitelist.Get().RegisterPropertyListeners(
- profile_,
- &registrar_,
- base::Bind(&ChromeDirectSettingAPI::OnPrefChanged,
- base::Unretained(this),
- registrar_.prefs()));
-}
-
-bool ChromeDirectSettingAPI::IsPreferenceOnWhitelist(
- const std::string& pref_key) {
- return preference_whitelist.Get().IsPreferenceOnWhitelist(pref_key);
-}
-
-ChromeDirectSettingAPI* ChromeDirectSettingAPI::Get(
- content::BrowserContext* context) {
- return BrowserContextKeyedAPIFactory<ChromeDirectSettingAPI>::Get(context);
-}
-
-// BrowserContextKeyedAPI implementation.
-const char* ChromeDirectSettingAPI::service_name() {
- return "ChromeDirectSettingAPI";
-}
-
-void ChromeDirectSettingAPI::OnPrefChanged(
- PrefService* pref_service, const std::string& pref_key) {
- std::string event_name = base::StringPrintf(kOnPrefChangeFormat,
- pref_key.c_str());
- EventRouter* router = EventRouter::Get(profile_);
- if (router && router->HasEventListener(event_name)) {
- const PrefService::Preference* preference =
- profile_->GetPrefs()->FindPreference(pref_key.c_str());
- const base::Value* value = preference->GetValue();
-
- std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue);
- result->Set(preference_api_constants::kValue, value->CreateDeepCopy());
- base::ListValue args;
- args.Append(std::move(result));
-
- for (const scoped_refptr<const extensions::Extension>& extension :
- ExtensionRegistry::Get(profile_)->enabled_extensions()) {
- const std::string& extension_id = extension->id();
- if (router->ExtensionHasEventListener(extension_id, event_name)) {
- std::unique_ptr<base::ListValue> args_copy(args.DeepCopy());
- // TODO(kalman): Have a histogram value for each pref type.
- // This isn't so important for the current use case of these
- // histograms, which is to track which event types are waking up event
- // pages, or which are delivered to persistent background pages. Simply
- // "a setting changed" is enough detail for that. However if we try to
- // use these histograms for any fine-grained logic (like removing the
- // string event name altogether), or if we discover this event is
- // firing a lot and want to understand that better, then this will need
- // to change.
- events::HistogramValue histogram_value =
- events::TYPES_PRIVATE_CHROME_DIRECT_SETTING_ON_CHANGE;
- std::unique_ptr<Event> event(
- new Event(histogram_value, event_name, std::move(args_copy)));
- router->DispatchEventToExtension(extension_id, std::move(event));
- }
- }
- }
-}
-
-} // namespace chromedirectsetting
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.h b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.h
deleted file mode 100644
index 226cf99b587..00000000000
--- a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting_api.h
+++ /dev/null
@@ -1,65 +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.
-
-#ifndef CHROME_BROWSER_EXTENSIONS_API_PREFERENCE_CHROME_DIRECT_SETTING_API_H__
-#define CHROME_BROWSER_EXTENSIONS_API_PREFERENCE_CHROME_DIRECT_SETTING_API_H__
-
-#include "base/macros.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "extensions/browser/browser_context_keyed_api_factory.h"
-#include "extensions/browser/event_router.h"
-
-class Profile;
-
-namespace content {
-class BrowserContext;
-}
-
-namespace extensions {
-namespace chromedirectsetting {
-
-class ChromeDirectSettingAPI : public BrowserContextKeyedAPI,
- public EventRouter::Observer {
- public:
- explicit ChromeDirectSettingAPI(content::BrowserContext* context);
-
- ~ChromeDirectSettingAPI() override;
-
- // KeyedService implementation.
- void Shutdown() override;
-
- // BrowserContextKeyedAPI implementation.
- static BrowserContextKeyedAPIFactory<ChromeDirectSettingAPI>*
- GetFactoryInstance();
-
- // EventRouter::Observer implementation.
- void OnListenerAdded(const EventListenerInfo& details) override;
-
- // Returns true if the preference is on the whitelist.
- bool IsPreferenceOnWhitelist(const std::string& pref_key);
-
- // Convenience method to get the ChromeDirectSettingAPI for a profile.
- static ChromeDirectSettingAPI* Get(content::BrowserContext* context);
-
- private:
- friend class BrowserContextKeyedAPIFactory<ChromeDirectSettingAPI>;
-
- // BrowserContextKeyedAPI implementation.
- static const char* service_name();
-
- void OnPrefChanged(PrefService* pref_service, const std::string& pref_key);
-
- static const bool kServiceIsNULLWhileTesting = true;
- static const bool kServiceRedirectedInIncognito = false;
-
- PrefChangeRegistrar registrar_;
- Profile* profile_;
-
- DISALLOW_COPY_AND_ASSIGN(ChromeDirectSettingAPI);
-};
-
-} // namespace chromedirectsetting
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_PREFERENCE_CHROME_DIRECT_SETTING_API_H__
diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.cc b/chromium/chrome/browser/extensions/api/preference/preference_api.cc
index 3895a9392dc..c16442b8097 100644
--- a/chromium/chrome/browser/extensions/api/preference/preference_api.cc
+++ b/chromium/chrome/browser/extensions/api/preference/preference_api.cc
@@ -50,6 +50,10 @@
#include "extensions/common/permissions/permissions_data.h"
#include "media/media_features.h"
+#if defined(OS_CHROMEOS)
+#include "ash/public/cpp/ash_pref_names.h" // nogncheck
+#endif
+
namespace keys = extensions::preference_api_constants;
namespace helpers = extensions::preference_helpers;
@@ -146,25 +150,25 @@ PrefMappingEntry kPrefMapping[] = {
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
#if defined(OS_CHROMEOS)
- {"autoclick", prefs::kAccessibilityAutoclickEnabled,
+ {"autoclick", ash::prefs::kAccessibilityAutoclickEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
- {"highContrast", prefs::kAccessibilityHighContrastEnabled,
+ {"highContrast", ash::prefs::kAccessibilityHighContrastEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
- {"largeCursor", prefs::kAccessibilityLargeCursorEnabled,
+ {"largeCursor", ash::prefs::kAccessibilityLargeCursorEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
- {"screenMagnifier", prefs::kAccessibilityScreenMagnifierEnabled,
+ {"screenMagnifier", ash::prefs::kAccessibilityScreenMagnifierEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
- {"spokenFeedback", prefs::kAccessibilitySpokenFeedbackEnabled,
+ {"spokenFeedback", ash::prefs::kAccessibilitySpokenFeedbackEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
- {"stickyKeys", prefs::kAccessibilityStickyKeysEnabled,
+ {"stickyKeys", ash::prefs::kAccessibilityStickyKeysEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
- {"virtualKeyboard", prefs::kAccessibilityVirtualKeyboardEnabled,
+ {"virtualKeyboard", ash::prefs::kAccessibilityVirtualKeyboardEnabled,
APIPermission::kAccessibilityFeaturesRead,
APIPermission::kAccessibilityFeaturesModify},
#endif
diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc b/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc
index 2c5209a9bb0..2964d6272fc 100644
--- a/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc
@@ -385,7 +385,7 @@ class ControlledPrefsDisableExtension : public ExtensionControlledPrefsTest {
std::string actual = prefs()->pref_service()->GetString(kPref1);
EXPECT_EQ("val1", actual);
prefs()->SetExtensionDisabled(extension1()->id(),
- Extension::DISABLE_USER_ACTION);
+ disable_reason::DISABLE_USER_ACTION);
}
void Verify() override {
std::string actual = prefs()->pref_service()->GetString(kPref1);
@@ -400,7 +400,7 @@ class ControlledPrefsReenableExtension : public ExtensionControlledPrefsTest {
InstallExtensionControlledPref(extension1(), kPref1,
new base::Value("val1"));
prefs()->SetExtensionDisabled(extension1()->id(),
- Extension::DISABLE_USER_ACTION);
+ disable_reason::DISABLE_USER_ACTION);
prefs()->SetExtensionEnabled(extension1()->id());
}
void Verify() override {
diff --git a/chromium/chrome/browser/extensions/api/preference/preferences_private_apitest.cc b/chromium/chrome/browser/extensions/api/preference/preferences_private_apitest.cc
new file mode 100644
index 00000000000..0dd2f8c7dc0
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/preference/preferences_private_apitest.cc
@@ -0,0 +1,29 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/extension_apitest.h"
+#include "extensions/common/switches.h"
+
+namespace extensions {
+
+class PreferencesPrivateApiTest : public ExtensionApiTest {
+ public:
+ PreferencesPrivateApiTest() {}
+ ~PreferencesPrivateApiTest() override {}
+
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ ExtensionApiTest::SetUpCommandLine(command_line);
+ command_line->AppendSwitchASCII(switches::kWhitelistedExtensionID,
+ "cpfhkdbjfdgdebcjlifoldbijinjfifp");
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(PreferencesPrivateApiTest);
+};
+
+IN_PROC_BROWSER_TEST_F(PreferencesPrivateApiTest, TestEasyUnlockEvent) {
+ ASSERT_TRUE(RunExtensionTest("preferences_private")) << message_;
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc
index c912ab1ca81..be4c9da390c 100644
--- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc
@@ -231,42 +231,42 @@ TEST(ExtensionProxyApiHelpers, CreateProxyConfigDict) {
std::unique_ptr<base::DictionaryValue> out_direct(CreateProxyConfigDict(
ProxyPrefs::MODE_DIRECT, false, std::string(), std::string(),
std::string(), std::string(), &error));
- EXPECT_TRUE(base::Value::Equals(exp_direct.get(), out_direct.get()));
+ EXPECT_EQ(*exp_direct, *out_direct);
std::unique_ptr<base::DictionaryValue> exp_auto =
ProxyConfigDictionary::CreateAutoDetect();
std::unique_ptr<base::DictionaryValue> out_auto(CreateProxyConfigDict(
ProxyPrefs::MODE_AUTO_DETECT, false, std::string(), std::string(),
std::string(), std::string(), &error));
- EXPECT_TRUE(base::Value::Equals(exp_auto.get(), out_auto.get()));
+ EXPECT_EQ(*exp_auto, *out_auto);
std::unique_ptr<base::DictionaryValue> exp_pac_url =
ProxyConfigDictionary::CreatePacScript(kSamplePacScriptUrl, false);
std::unique_ptr<base::DictionaryValue> out_pac_url(CreateProxyConfigDict(
ProxyPrefs::MODE_PAC_SCRIPT, false, kSamplePacScriptUrl, std::string(),
std::string(), std::string(), &error));
- EXPECT_TRUE(base::Value::Equals(exp_pac_url.get(), out_pac_url.get()));
+ EXPECT_EQ(*exp_pac_url, *out_pac_url);
std::unique_ptr<base::DictionaryValue> exp_pac_data =
ProxyConfigDictionary::CreatePacScript(kSamplePacScriptAsDataUrl, false);
std::unique_ptr<base::DictionaryValue> out_pac_data(CreateProxyConfigDict(
ProxyPrefs::MODE_PAC_SCRIPT, false, std::string(), kSamplePacScript,
std::string(), std::string(), &error));
- EXPECT_TRUE(base::Value::Equals(exp_pac_data.get(), out_pac_data.get()));
+ EXPECT_EQ(*exp_pac_data, *out_pac_data);
std::unique_ptr<base::DictionaryValue> exp_fixed =
ProxyConfigDictionary::CreateFixedServers("foo:80", "localhost");
std::unique_ptr<base::DictionaryValue> out_fixed(CreateProxyConfigDict(
ProxyPrefs::MODE_FIXED_SERVERS, false, std::string(), std::string(),
"foo:80", "localhost", &error));
- EXPECT_TRUE(base::Value::Equals(exp_fixed.get(), out_fixed.get()));
+ EXPECT_EQ(*exp_fixed, *out_fixed);
std::unique_ptr<base::DictionaryValue> exp_system =
ProxyConfigDictionary::CreateSystem();
std::unique_ptr<base::DictionaryValue> out_system(CreateProxyConfigDict(
ProxyPrefs::MODE_SYSTEM, false, std::string(), std::string(),
std::string(), std::string(), &error));
- EXPECT_TRUE(base::Value::Equals(exp_system.get(), out_system.get()));
+ EXPECT_EQ(*exp_system, *out_system);
// Neither of them should have set an error.
EXPECT_EQ(std::string(), error);
@@ -334,7 +334,7 @@ TEST(ExtensionProxyApiHelpers, CreateProxyRulesDict) {
bypass_list->AppendString("localhost");
expected->Set(keys::kProxyConfigBypassList, std::move(bypass_list));
- EXPECT_TRUE(base::Value::Equals(expected.get(), extension_pref.get()));
+ EXPECT_EQ(*expected, *extension_pref);
}
// Test multiple proxies per scheme -- expect that only the first is returned.
@@ -362,7 +362,7 @@ TEST(ExtensionProxyApiHelpers, CreateProxyRulesDictMultipleProxies) {
bypass_list->AppendString("localhost");
expected->Set(keys::kProxyConfigBypassList, std::move(bypass_list));
- EXPECT_TRUE(base::Value::Equals(expected.get(), extension_pref.get()));
+ EXPECT_EQ(*expected, *extension_pref);
}
// Test if a PAC script URL is specified.
@@ -378,7 +378,7 @@ TEST(ExtensionProxyApiHelpers, CreatePacScriptDictWithUrl) {
expected->SetString(keys::kProxyConfigPacScriptUrl, kSamplePacScriptUrl);
expected->SetBoolean(keys::kProxyConfigPacScriptMandatory, false);
- EXPECT_TRUE(base::Value::Equals(expected.get(), extension_pref.get()));
+ EXPECT_EQ(*expected, *extension_pref);
}
// Test if a PAC script is encoded in a data URL.
@@ -394,7 +394,7 @@ TEST(ExtensionProxyApiHelpers, CreatePacScriptDictWidthData) {
expected->SetString(keys::kProxyConfigPacScriptData, kSamplePacScript);
expected->SetBoolean(keys::kProxyConfigPacScriptMandatory, false);
- EXPECT_TRUE(base::Value::Equals(expected.get(), extension_pref.get()));
+ EXPECT_EQ(*expected, *extension_pref);
}
TEST(ExtensionProxyApiHelpers, TokenizeToStringList) {
@@ -404,7 +404,7 @@ TEST(ExtensionProxyApiHelpers, TokenizeToStringList) {
expected.AppendString("s3");
std::unique_ptr<base::ListValue> out(TokenizeToStringList("s1;s2;s3", ";"));
- EXPECT_TRUE(base::Value::Equals(&expected, out.get()));
+ EXPECT_EQ(expected, *out);
}
} // namespace proxy_api_helpers
diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc
index 7df0ebb87e3..981c9b2d1b2 100644
--- a/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc
@@ -4,6 +4,7 @@
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
@@ -11,6 +12,8 @@
#include "components/prefs/pref_service.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
+#include "extensions/browser/extension_system.h"
+#include "extensions/browser/test_management_policy.h"
#include "extensions/common/extension.h"
#include "extensions/test/result_catcher.h"
@@ -25,6 +28,9 @@ const char kNoPac[] = "";
} // namespace
class ProxySettingsApiTest : public ExtensionApiTest {
+ public:
+ ProxySettingsApiTest() {}
+
protected:
void ValidateSettings(int expected_mode,
const std::string& expected_server,
@@ -84,6 +90,13 @@ class ProxySettingsApiTest : public ExtensionApiTest {
}
return true;
}
+
+ extensions::ManagementPolicy* GetManagementPolicy() {
+ return ExtensionSystem::Get(profile())->management_policy();
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ProxySettingsApiTest);
};
// Tests direct connection settings.
@@ -103,6 +116,82 @@ IN_PROC_BROWSER_TEST_F(ProxySettingsApiTest, ProxyDirectSettings) {
pref_service);
}
+// Tests that proxy settings are changed appropriately when the extension is
+// disabled or enabled.
+IN_PROC_BROWSER_TEST_F(ProxySettingsApiTest, SettingsChangeOnDisableEnable) {
+ ASSERT_TRUE(RunExtensionTestIncognito("proxy/direct")) << message_;
+ const Extension* extension = GetSingleLoadedExtension();
+ ASSERT_TRUE(extension);
+
+ PrefService* pref_service = browser()->profile()->GetPrefs();
+ ValidateSettings(ProxyPrefs::MODE_DIRECT, kNoServer, kNoBypass, kNoPac,
+ pref_service);
+
+ DisableExtension(extension->id());
+ ExpectNoSettings(pref_service);
+
+ EnableExtension(extension->id());
+ ValidateSettings(ProxyPrefs::MODE_DIRECT, kNoServer, kNoBypass, kNoPac,
+ pref_service);
+}
+
+// Tests that proxy settings corresponding to an extension are removed when
+// the extension is uninstalled.
+IN_PROC_BROWSER_TEST_F(ProxySettingsApiTest, SettingsRemovedOnUninstall) {
+ ASSERT_TRUE(RunExtensionTestIncognito("proxy/direct")) << message_;
+ const Extension* extension = GetSingleLoadedExtension();
+ ASSERT_TRUE(extension);
+
+ PrefService* pref_service = browser()->profile()->GetPrefs();
+ ValidateSettings(ProxyPrefs::MODE_DIRECT, kNoServer, kNoBypass, kNoPac,
+ pref_service);
+
+ UninstallExtension(extension->id());
+ ExpectNoSettings(pref_service);
+}
+
+// Tests that proxy settings corresponding to an extension are removed when
+// the extension is blacklisted by management policy. Regression test for
+// crbug.com/709264.
+IN_PROC_BROWSER_TEST_F(ProxySettingsApiTest,
+ PRE_SettingsRemovedOnPolicyBlacklist) {
+ ASSERT_TRUE(RunExtensionTestIncognito("proxy/direct")) << message_;
+ const Extension* extension = GetSingleLoadedExtension();
+ ASSERT_TRUE(extension);
+
+ PrefService* pref_service = browser()->profile()->GetPrefs();
+ ValidateSettings(ProxyPrefs::MODE_DIRECT, kNoServer, kNoBypass, kNoPac,
+ pref_service);
+
+ GetManagementPolicy()->UnregisterAllProviders();
+ extensions::TestManagementPolicyProvider provider(
+ extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
+ GetManagementPolicy()->RegisterProvider(&provider);
+
+ // Run the policy check.
+ extension_service()->CheckManagementPolicy();
+ ExpectNoSettings(pref_service);
+
+ // Remove the extension from policy blacklist. It should get enabled again.
+ GetManagementPolicy()->UnregisterAllProviders();
+ extension_service()->CheckManagementPolicy();
+ ValidateSettings(ProxyPrefs::MODE_DIRECT, kNoServer, kNoBypass, kNoPac,
+ pref_service);
+
+ // Block the extension again for the next test.
+ GetManagementPolicy()->RegisterProvider(&provider);
+ extension_service()->CheckManagementPolicy();
+ ExpectNoSettings(pref_service);
+}
+
+// Tests that proxy settings corresponding to an extension take effect again
+// on browser restart, when the extension is removed from the policy blacklist.
+IN_PROC_BROWSER_TEST_F(ProxySettingsApiTest, SettingsRemovedOnPolicyBlacklist) {
+ PrefService* pref_service = browser()->profile()->GetPrefs();
+ ValidateSettings(ProxyPrefs::MODE_DIRECT, kNoServer, kNoBypass, kNoPac,
+ pref_service);
+}
+
// Tests auto-detect settings.
IN_PROC_BROWSER_TEST_F(ProxySettingsApiTest, ProxyAutoSettings) {
ASSERT_TRUE(RunExtensionTestIncognito("proxy/auto")) << message_;
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 8a6fcc95256..30334b55a15 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
@@ -12,6 +12,7 @@
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
+#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/test/simple_test_tick_clock.h"
diff --git a/chromium/chrome/browser/extensions/api/settings_private/OWNERS b/chromium/chrome/browser/extensions/api/settings_private/OWNERS
index 879a522d857..4207113bb1a 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/OWNERS
+++ b/chromium/chrome/browser/extensions/api/settings_private/OWNERS
@@ -1,5 +1,4 @@
michaelpg@chromium.org
stevenjb@chromium.org
-dbeam@chromium.org
# COMPONENT: UI>Settings
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 0d2f38c086a..012d5eb29e9 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -40,6 +40,7 @@
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
+#include "chrome/browser/chromeos/system/timezone_util.h"
#include "chromeos/settings/cros_settings_names.h"
#include "ui/chromeos/events/pref_names.h"
#endif
@@ -50,13 +51,23 @@ namespace {
bool IsPrivilegedCrosSetting(const std::string& pref_name) {
if (!chromeos::CrosSettings::IsCrosSettings(pref_name))
return false;
- // kSystemTimezone should be changeable by all users.
- if (pref_name == chromeos::kSystemTimezone)
- return false;
- // All other Cros settings are considered privileged and are either policy
+ if (!chromeos::system::PerUserTimezoneEnabled()) {
+ // kSystemTimezone should be changeable by all users.
+ if (pref_name == chromeos::kSystemTimezone)
+ return false;
+ }
+ // Cros settings are considered privileged and are either policy
// controlled or owner controlled.
return true;
}
+
+bool IsCrosSettingReadOnly(const std::string& pref_name) {
+ if (chromeos::system::PerUserTimezoneEnabled()) {
+ // System timezone is never directly changable by user.
+ return pref_name == chromeos::kSystemTimezone;
+ }
+ return false;
+}
#endif
} // namespace
@@ -233,37 +244,37 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_private::PrefType::PREF_TYPE_BOOLEAN;
// Accessibility.
- (*s_whitelist)[::prefs::kAccessibilitySpokenFeedbackEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilitySpokenFeedbackEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityAutoclickEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityAutoclickEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityAutoclickDelayMs] =
+ (*s_whitelist)[ash::prefs::kAccessibilityAutoclickDelayMs] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityCaretHighlightEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityCaretHighlightEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityCursorHighlightEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityCursorHighlightEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kShouldAlwaysShowAccessibilityMenu] =
+ (*s_whitelist)[ash::prefs::kShouldAlwaysShowAccessibilityMenu] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityFocusHighlightEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityFocusHighlightEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityHighContrastEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityHighContrastEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityLargeCursorEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityLargeCursorEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityLargeCursorDipSize] =
+ (*s_whitelist)[ash::prefs::kAccessibilityLargeCursorDipSize] =
settings_private::PrefType::PREF_TYPE_NUMBER;
- (*s_whitelist)[::prefs::kAccessibilityScreenMagnifierEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityScreenMagnifierEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilitySelectToSpeakEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilitySelectToSpeakEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityStickyKeysEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityStickyKeysEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilitySwitchAccessEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityVirtualKeyboardEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityVirtualKeyboardEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kAccessibilityMonoAudioEnabled] =
+ (*s_whitelist)[ash::prefs::kAccessibilityMonoAudioEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
// Android Apps.
@@ -271,6 +282,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_private::PrefType::PREF_TYPE_BOOLEAN;
// Google Assistant.
+ (*s_whitelist)[::prefs::kArcVoiceInteractionValuePropAccepted] =
+ settings_private::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[::prefs::kVoiceInteractionEnabled] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[::prefs::kVoiceInteractionContextEnabled] =
@@ -304,9 +317,13 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
// Timezone settings.
(*s_whitelist)[chromeos::kSystemTimezone] =
- settings_private::PrefType::PREF_TYPE_BOOLEAN;
+ settings_private::PrefType::PREF_TYPE_STRING;
+ (*s_whitelist)[prefs::kUserTimezone] =
+ settings_private::PrefType::PREF_TYPE_STRING;
(*s_whitelist)[::prefs::kResolveTimezoneByGeolocation] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[chromeos::kPerUserTimezoneEnabled] =
+ settings_private::PrefType::PREF_TYPE_BOOLEAN;
// Ash settings.
(*s_whitelist)[::prefs::kEnableStylusTools] =
@@ -339,6 +356,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_private::PrefType::PREF_TYPE_NUMBER;
(*s_whitelist)[::prefs::kPrimaryMouseButtonRight] =
settings_private::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[::prefs::kMouseReverseScroll] =
+ settings_private::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[::prefs::kMouseSensitivity] =
settings_private::PrefType::PREF_TYPE_NUMBER;
(*s_whitelist)[::prefs::kLanguageRemapSearchKeyTo] =
@@ -476,6 +495,21 @@ std::unique_ptr<settings_private::PrefObject> PrefsUtil::GetPref(
}
#if defined(OS_CHROMEOS)
+ // We first check for enterprise-managed, then for primary-user managed.
+ // Otherwise in multiprofile mode enterprise preference for the secondary
+ // user will appear primary-user-controlled, which looks strange, because
+ // primary user preference will be disabled with "enterprise controlled"
+ // status.
+ if (IsPrefEnterpriseManaged(name)) {
+ // Enterprise managed prefs are treated the same as device policy restricted
+ // prefs in the UI.
+ pref_object->controlled_by =
+ settings_private::ControlledBy::CONTROLLED_BY_DEVICE_POLICY;
+ pref_object->enforcement =
+ settings_private::Enforcement::ENFORCEMENT_ENFORCED;
+ return pref_object;
+ }
+
if (IsPrefPrimaryUserControlled(name)) {
pref_object->controlled_by =
settings_private::ControlledBy::CONTROLLED_BY_PRIMARY_USER;
@@ -488,16 +522,6 @@ std::unique_ptr<settings_private::PrefObject> PrefsUtil::GetPref(
.GetUserEmail()));
return pref_object;
}
-
- if (IsPrefEnterpriseManaged(name)) {
- // Enterprise managed prefs are treated the same as device policy restricted
- // prefs in the UI.
- pref_object->controlled_by =
- settings_private::ControlledBy::CONTROLLED_BY_DEVICE_POLICY;
- pref_object->enforcement =
- settings_private::Enforcement::ENFORCEMENT_ENFORCED;
- return pref_object;
- }
#endif
if (pref && pref->IsManaged()) {
@@ -683,16 +707,26 @@ bool PrefsUtil::IsPrefTypeURL(const std::string& pref_name) {
#if defined(OS_CHROMEOS)
bool PrefsUtil::IsPrefEnterpriseManaged(const std::string& pref_name) {
- if (IsPrivilegedCrosSetting(pref_name)) {
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- if (connector->IsEnterpriseManaged())
- return true;
+ policy::BrowserPolicyConnectorChromeOS* connector =
+ g_browser_process->platform_part()->browser_policy_connector_chromeos();
+ if (!connector->IsEnterpriseManaged())
+ return false;
+ if (IsPrivilegedCrosSetting(pref_name))
+ return true;
+ if (chromeos::system::PerUserTimezoneEnabled() &&
+ (pref_name == prefs::kUserTimezone ||
+ pref_name == prefs::kResolveTimezoneByGeolocation)) {
+ return chromeos::system::IsTimezonePrefsManaged(pref_name);
}
return false;
}
bool PrefsUtil::IsPrefOwnerControlled(const std::string& pref_name) {
+ // chromeos::kSystemTimezone is global display-only preference and
+ // it should appear as disabled, but not owned.
+ if (pref_name == chromeos::kSystemTimezone)
+ return false;
+
if (IsPrivilegedCrosSetting(pref_name)) {
if (!chromeos::ProfileHelper::IsOwnerProfile(profile_))
return true;
@@ -701,13 +735,19 @@ bool PrefsUtil::IsPrefOwnerControlled(const std::string& pref_name) {
}
bool PrefsUtil::IsPrefPrimaryUserControlled(const std::string& pref_name) {
- if (pref_name == prefs::kWakeOnWifiDarkConnect) {
+ // chromeos::kSystemTimezone is read-only, but for the non-primary users
+ // it should have "primary user controlled" attribute.
+ if (pref_name == prefs::kWakeOnWifiDarkConnect ||
+ pref_name == prefs::kResolveTimezoneByGeolocation ||
+ pref_name == prefs::kUserTimezone ||
+ pref_name == chromeos::kSystemTimezone) {
user_manager::UserManager* user_manager = user_manager::UserManager::Get();
const user_manager::User* user =
chromeos::ProfileHelper::Get()->GetUserByProfile(profile_);
- if (user &&
- user->GetAccountId() != user_manager->GetPrimaryUser()->GetAccountId())
+ if (user && user->GetAccountId() !=
+ user_manager->GetPrimaryUser()->GetAccountId()) {
return true;
+ }
}
return false;
}
@@ -722,6 +762,11 @@ bool PrefsUtil::IsPrefSupervisorControlled(const std::string& pref_name) {
}
bool PrefsUtil::IsPrefUserModifiable(const std::string& pref_name) {
+#if defined(OS_CHROMEOS)
+ if (IsCrosSettingReadOnly(pref_name))
+ return false;
+#endif
+
const PrefService::Preference* profile_pref =
profile_->GetPrefs()->FindPreference(pref_name);
if (profile_pref)
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 64a62c066a6..8ebc9f6f06b 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
@@ -6,6 +6,8 @@
#include "base/command_line.h"
#include "base/macros.h"
+#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/settings_private/settings_private_delegate.h"
diff --git a/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc b/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc
index 8fb5d4e1ee6..b1710494d53 100644
--- a/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc
@@ -59,7 +59,6 @@ IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPExtension) {
std::unique_ptr<net::SpawnedTestServer> test_server(
new net::SpawnedTestServer(
net::SpawnedTestServer::TYPE_UDP_ECHO,
- net::SpawnedTestServer::kLocalhost,
base::FilePath(FILE_PATH_LITERAL("net/data"))));
EXPECT_TRUE(test_server->Start());
@@ -87,7 +86,6 @@ IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPExtension) {
std::unique_ptr<net::SpawnedTestServer> test_server(
new net::SpawnedTestServer(
net::SpawnedTestServer::TYPE_TCP_ECHO,
- net::SpawnedTestServer::kLocalhost,
base::FilePath(FILE_PATH_LITERAL("net/data"))));
EXPECT_TRUE(test_server->Start());
diff --git a/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc b/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc
index b5bbd061de9..9f0d24a8578 100644
--- a/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc
@@ -150,7 +150,7 @@ TEST_F(PolicyValueStoreTest, DontProvideRecommendedPolicies) {
base::Value* value = NULL;
EXPECT_FALSE(result->settings().Get("may", &value));
EXPECT_TRUE(result->settings().Get("must", &value));
- EXPECT_TRUE(base::Value::Equals(&expected, value));
+ EXPECT_EQ(expected, *value);
}
TEST_F(PolicyValueStoreTest, ReadOnly) {
diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
index 562ab151b6a..2e8594e7c43 100644
--- a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
@@ -1397,7 +1397,7 @@ TEST_F(ExtensionSettingsSyncTest, Dots) {
base::DictionaryValue expected_data;
expected_data.SetWithoutPathExpansion(
"key.with.dot", base::MakeUnique<base::Value>("value"));
- EXPECT_TRUE(base::Value::Equals(&expected_data, &data->settings()));
+ EXPECT_EQ(expected_data, data->settings());
}
// Test dots in keys going to sync.
diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc
index b37e1b1da4c..2238cca632d 100644
--- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc
@@ -322,8 +322,8 @@ IN_PROC_BROWSER_TEST_F(StreamsPrivateApiTest, NavigateCrossSite) {
EXPECT_TRUE(catcher.GetNextResult());
}
-// Flaky on ChromeOS: http://crbug.com/746526.
-#if defined(OS_CHROMEOS)
+// Flaky on Linux and ChromeOS: http://crbug.com/746526.
+#if defined(OS_LINUX)
#define MAYBE_NavigateToAnAttachment DISABLED_NavigateToAnAttachment
#else
#define MAYBE_NavigateToAnAttachment NavigateToAnAttachment
@@ -367,8 +367,8 @@ IN_PROC_BROWSER_TEST_F(StreamsPrivateApiTest, MAYBE_NavigateToAnAttachment) {
EXPECT_TRUE(catcher.GetNextResult());
}
-// Flaky on ChromeOS: http://crbug.com/746526.
-#if defined(OS_CHROMEOS)
+// Flaky on Linux and Win 10: http://crbug.com/746526.
+#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_DirectDownload DISABLED_DirectDownload
#else
#define MAYBE_DirectDownload DirectDownload
diff --git a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc
index eba03820a5d..34c2ace5d41 100644
--- a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc
@@ -71,6 +71,7 @@ class SyncFileSystemTest : public extensions::PlatformAppBrowserTest,
}
void SetUpOnMainThread() override {
+ in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default()));
extensions::PlatformAppBrowserTest::SetUpOnMainThread();
ASSERT_TRUE(base_dir_.CreateUniqueTempDir());
diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc
index bff8d130830..8dbdcf8a265 100644
--- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc
+++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc
@@ -89,7 +89,7 @@ class OffscreenTab::PresentationNavigationPolicy
: public OffscreenTab::NavigationPolicy {
public:
PresentationNavigationPolicy() : first_navigation_started_(false) {}
- ~PresentationNavigationPolicy() = default;
+ ~PresentationNavigationPolicy() override = default;
private:
// OffscreenTab::NavigationPolicy overrides
diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h
index b2a47deb86f..75ad96ed9f8 100644
--- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h
+++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h
@@ -187,7 +187,7 @@ class OffscreenTab : protected content::WebContentsDelegate,
class NavigationPolicy {
public:
NavigationPolicy();
- ~NavigationPolicy();
+ virtual ~NavigationPolicy();
virtual bool DidStartNavigation(
content::NavigationHandle* navigation_handle);
};
diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc
index 1e12aacd479..4933e36328f 100644
--- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc
@@ -66,18 +66,12 @@ class TabCaptureApiPixelTest : public TabCaptureApiTest {
protected:
bool IsTooIntensiveForThisPlatform() const {
- // The tests are too slow to succeed with software GL on the bots.
- if (UsingSoftwareGL())
- return true;
-
#if defined(NDEBUG)
- return false;
+ // The tests are too slow to succeed with software GL on the bots.
+ return UsingSoftwareGL();
#else
- // TODO(miu): Look into enabling these tests for the Debug build bots once
- // they prove to be stable again on the Release bots.
- // http://crbug.com/396413
- return !base::CommandLine::ForCurrentProcess()->HasSwitch(
- "run-tab-capture-api-pixel-tests");
+ // The tests only run on release builds.
+ return true;
#endif
}
};
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
index f88b0deeae9..4330ebfbcd9 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
@@ -1174,9 +1174,17 @@ bool TabsUpdateFunction::RunAsync() {
// Navigate the tab to a new location if the url is different.
bool is_async = false;
- if (params->update_properties.url.get() &&
- !UpdateURL(*params->update_properties.url, tab_id, &is_async)) {
- return false;
+ if (params->update_properties.url.get()) {
+ std::string updated_url = *params->update_properties.url;
+ if (browser->profile()->GetProfileType() == Profile::INCOGNITO_PROFILE &&
+ !chrome::IsURLAllowedInIncognito(GURL(updated_url),
+ browser->profile())) {
+ error_ = ErrorUtils::FormatErrorMessage(
+ keys::kURLsNotAllowedInIncognitoError, updated_url);
+ return false;
+ }
+ if (!UpdateURL(updated_url, tab_id, &is_async))
+ return false;
}
bool active = false;
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc
index 26a3e9c7bea..d06d5513d00 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc
@@ -2,9 +2,10 @@
// 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/tabs/tabs_api.h"
+#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "chrome/browser/extensions/api/tabs/tabs_api.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
@@ -20,7 +21,6 @@
#include "extensions/browser/api_test_utils.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_builder.h"
-#include "extensions/common/test_util.h"
namespace extensions {
@@ -108,7 +108,7 @@ TEST_F(TabsApiUnitTest, QueryWithoutTabsPermission) {
"[{\"title\": \"Sample title\", \"url\": \"*://www.google.com/*\"}]";
// An extension without "tabs" permission will see none of the 3 tabs.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
std::unique_ptr<base::ListValue> tabs_list_without_permission(
RunTabsQueryFunction(browser(), extension.get(), kTitleAndURLQueryInfo));
ASSERT_TRUE(tabs_list_without_permission);
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 d113fba9705..d6a16b00d8a 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc
@@ -54,7 +54,8 @@ bool WillDispatchTabUpdatedEvent(
const base::Value* value = nullptr;
for (const auto& property : changed_property_names) {
if (tab_value->Get(property, &value))
- changed_properties->Set(property, base::MakeUnique<base::Value>(*value));
+ changed_properties->Set(property,
+ base::MakeUnique<base::Value>(value->Clone()));
}
event->event_args->Set(1, std::move(changed_properties));
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc
index f27be745923..ad26ba4b8d9 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc
@@ -15,7 +15,7 @@
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "extensions/browser/api_test_utils.h"
-#include "extensions/common/test_util.h"
+#include "extensions/common/extension_builder.h"
namespace extensions {
@@ -47,7 +47,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetLastFocusedWindow) {
scoped_refptr<extensions::WindowsGetLastFocusedFunction> function =
new extensions::WindowsGetLastFocusedFunction();
scoped_refptr<extensions::Extension> extension(
- extensions::test_util::CreateEmptyExtension());
+ extensions::ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
utils::ToDictionary(utils::RunFunctionAndReturnSingleResult(
@@ -91,7 +91,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryLastFocusedWindowTabs) {
scoped_refptr<extensions::TabsQueryFunction> function =
new extensions::TabsQueryFunction();
scoped_refptr<extensions::Extension> extension(
- extensions::test_util::CreateEmptyExtension());
+ extensions::ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::ListValue> result(
utils::ToList(utils::RunFunctionAndReturnSingleResult(
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc
index 55dd8156623..a761f6b73f6 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc
@@ -12,6 +12,7 @@
#include "apps/test/app_window_waiter.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/strings/pattern.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
@@ -48,8 +49,9 @@
#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
+#include "extensions/common/error_utils.h"
+#include "extensions/common/extension_builder.h"
#include "extensions/common/manifest_constants.h"
-#include "extensions/common/test_util.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
@@ -76,7 +78,7 @@ class ExtensionWindowCreateTest : public InProcessBrowserTest {
// Runs chrome.windows.create(), expecting an error.
std::string RunCreateWindowExpectError(const std::string& args) {
scoped_refptr<WindowsCreateFunction> function(new WindowsCreateFunction);
- function->set_extension(test_util::CreateEmptyExtension().get());
+ function->set_extension(ExtensionBuilder("Test").Build().get());
return api_test_utils::RunFunctionAndReturnError(function.get(), args,
browser()->profile());
}
@@ -118,7 +120,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetWindow) {
// Invalid window ID error.
scoped_refptr<WindowsGetFunction> function = new WindowsGetFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
EXPECT_TRUE(base::MatchPattern(
utils::RunFunctionAndReturnError(
@@ -235,7 +237,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetCurrentWindow) {
// Get the current window using new_browser.
scoped_refptr<WindowsGetCurrentFunction> function =
new WindowsGetCurrentFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
utils::ToDictionary(utils::RunFunctionAndReturnSingleResult(
@@ -288,7 +290,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) {
browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */);
scoped_refptr<WindowsGetAllFunction> function = new WindowsGetAllFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::ListValue> result(
utils::ToList(utils::RunFunctionAndReturnSingleResult(function.get(),
@@ -358,7 +360,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindowsAllTypes) {
DevToolsWindowTesting::Get(devtools)->browser()));
scoped_refptr<WindowsGetAllFunction> function = new WindowsGetAllFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::ListValue> result(
utils::ToList(utils::RunFunctionAndReturnSingleResult(
@@ -416,7 +418,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateNoPermissions) {
// tab data in the function result.
scoped_refptr<TabsUpdateFunction> update_tab_function(
new TabsUpdateFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
update_tab_function->set_extension(empty_extension.get());
// Without a callback the function will not generate a result.
update_tab_function->set_has_callback(true);
@@ -431,7 +433,34 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateNoPermissions) {
}
IN_PROC_BROWSER_TEST_F(ExtensionTabsTest,
- DefaultToIncognitoWhenItIsForced) {
+ DisallowNonIncognitoUrlInIncognitoWindow) {
+ Browser* incognito = CreateIncognitoBrowser();
+
+ scoped_refptr<TabsUpdateFunction> update_tab_function(
+ new TabsUpdateFunction());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
+ update_tab_function->set_extension(extension.get());
+ update_tab_function->set_include_incognito(true);
+
+ static const char kArgsWithNonIncognitoUrl[] =
+ "[null, {\"url\": \"chrome://extensions/configureCommands\"}]";
+ std::string error = extension_function_test_utils::RunFunctionAndReturnError(
+ update_tab_function.get(), kArgsWithNonIncognitoUrl,
+ incognito, // incognito doesn't have any tabs.
+ extension_function_test_utils::NONE);
+ EXPECT_EQ(ErrorUtils::FormatErrorMessage(
+ tabs_constants::kURLsNotAllowedInIncognitoError,
+ "chrome://extensions/configureCommands"),
+ error);
+
+ // Ensure the tab was not updated. It should stay as the new tab page.
+ EXPECT_EQ(1, incognito->tab_strip_model()->count());
+ EXPECT_EQ(GURL(url::kAboutBlankURL), incognito->tab_strip_model()
+ ->GetActiveWebContents()
+ ->GetLastCommittedURL());
+}
+
+IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DefaultToIncognitoWhenItIsForced) {
static const char kArgsWithoutExplicitIncognitoParam[] =
"[{\"url\": \"about:blank\"}]";
// Force Incognito mode.
@@ -441,7 +470,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest,
scoped_refptr<WindowsCreateFunction> function(new WindowsCreateFunction());
function->SetRenderFrameHost(
browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame());
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
utils::ToDictionary(utils::RunFunctionAndReturnSingleResult(
@@ -482,7 +511,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest,
IncognitoModePrefs::FORCED);
// Run without an explicit "incognito" param.
scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
utils::ToDictionary(utils::RunFunctionAndReturnSingleResult(
@@ -521,7 +550,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest,
// Run with an explicit "incognito" param.
scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
EXPECT_TRUE(base::MatchPattern(
utils::RunFunctionAndReturnError(
@@ -550,7 +579,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest,
IncognitoModePrefs::DISABLED);
// Run in normal window.
scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
EXPECT_TRUE(base::MatchPattern(
utils::RunFunctionAndReturnError(function.get(), kArgs, browser()),
@@ -575,7 +604,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryCurrentWindowTabs) {
// Get tabs in the 'current' window called from non-focused browser.
scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction();
- function->set_extension(test_util::CreateEmptyExtension().get());
+ function->set_extension(ExtensionBuilder("Test").Build().get());
std::unique_ptr<base::ListValue> result(
utils::ToList(utils::RunFunctionAndReturnSingleResult(
function.get(), "[{\"currentWindow\":true}]", browser())));
@@ -591,7 +620,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryCurrentWindowTabs) {
// Get tabs NOT in the 'current' window called from non-focused browser.
function = new TabsQueryFunction();
- function->set_extension(test_util::CreateEmptyExtension().get());
+ function->set_extension(ExtensionBuilder("Test").Build().get());
result.reset(utils::ToList(
utils::RunFunctionAndReturnSingleResult(function.get(),
"[{\"currentWindow\":false}]",
@@ -622,7 +651,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryAllTabsWithDevTools) {
// Get tabs in the 'current' window called from non-focused browser.
scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction();
- function->set_extension(test_util::CreateEmptyExtension().get());
+ function->set_extension(ExtensionBuilder("Test").Build().get());
std::unique_ptr<base::ListValue> result(
utils::ToList(utils::RunFunctionAndReturnSingleResult(
function.get(), "[{}]", browser())));
@@ -652,7 +681,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DontCreateTabInClosingPopupWindow) {
scoped_refptr<TabsCreateFunction> create_tab_function(
new TabsCreateFunction());
- create_tab_function->set_extension(test_util::CreateEmptyExtension().get());
+ create_tab_function->set_extension(ExtensionBuilder("Test").Build().get());
// Without a callback the function will not generate a result.
create_tab_function->set_has_callback(true);
@@ -673,7 +702,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, InvalidUpdateWindowState) {
static const char kArgsMinimizedWithFocus[] =
"[%u, {\"state\": \"minimized\", \"focused\": true}]";
scoped_refptr<WindowsUpdateFunction> function = new WindowsUpdateFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
EXPECT_TRUE(base::MatchPattern(
utils::RunFunctionAndReturnError(
@@ -720,7 +749,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateAppWindowSizeConstraint) {
" \"maxWidth\": 400, \"maxHeight\": 400}}");
scoped_refptr<WindowsGetFunction> get_function = new WindowsGetFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension().get());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build().get());
get_function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
utils::ToDictionary(utils::RunFunctionAndReturnSingleResult(
@@ -766,7 +795,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateDevToolsWindow) {
browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */);
scoped_refptr<WindowsGetFunction> get_function = new WindowsGetFunction();
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension().get());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build().get());
get_function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
utils::ToDictionary(utils::RunFunctionAndReturnSingleResult(
@@ -838,7 +867,7 @@ class ExtensionWindowLastFocusedTest : public ExtensionTabsTest {
void OnWidgetActivationChanged(views::Widget* widget,
bool active) override {
if (widget_ == widget && waiting_) {
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
waiting_ = false;
}
}
@@ -853,7 +882,7 @@ class ExtensionWindowLastFocusedTest : public ExtensionTabsTest {
void ExtensionWindowLastFocusedTest::SetUpOnMainThread() {
ExtensionTabsTest::SetUpOnMainThread();
- extension_ = test_util::CreateEmptyExtension();
+ extension_ = ExtensionBuilder("Test").Build();
}
void ExtensionWindowLastFocusedTest::ActivateBrowserWindow(Browser* browser) {
@@ -1057,7 +1086,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowCreateTest, AcceptState) {
#endif
scoped_refptr<WindowsCreateFunction> function(new WindowsCreateFunction());
- scoped_refptr<Extension> extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build());
function->set_extension(extension.get());
std::unique_ptr<base::DictionaryValue> result(
@@ -1184,7 +1213,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTabNoPermission) {
scoped_refptr<TabsDuplicateFunction> duplicate_tab_function(
new TabsDuplicateFunction());
- scoped_refptr<Extension> empty_extension(test_util::CreateEmptyExtension());
+ scoped_refptr<Extension> empty_extension(ExtensionBuilder("Test").Build());
duplicate_tab_function->set_extension(empty_extension.get());
duplicate_tab_function->set_has_callback(true);
@@ -1328,7 +1357,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) {
content::WebContents* web_contents_b = browser()->OpenURL(params);
// Set up query function with an extension.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
auto RunQueryFunction = [this, &extension](const char* query_info) {
scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction();
function->set_extension(extension.get());
@@ -1449,7 +1478,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithId) {
browser()->tab_strip_model()->GetWebContentsAt(1);
// Set up the function with an extension.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction());
discard->set_extension(extension.get());
@@ -1489,7 +1518,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithInvalidId) {
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// Set up the function with an extension.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction());
discard->set_extension(extension.get());
@@ -1523,7 +1552,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithoutId) {
browser()->tab_strip_model()->GetWebContentsAt(1);
// Set up the function with an extension.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction());
discard->set_extension(extension.get());
@@ -1561,7 +1590,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardNoTabProtection) {
base::TimeDelta::FromMinutes(10));
// Set up the function with an extension.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction());
discard->set_extension(extension.get());
@@ -1595,7 +1624,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) {
EXPECT_TRUE(tab_object_a->auto_discardable);
// Set up query and update functions with the extension.
- scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension();
+ scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build();
auto RunQueryFunction = [this, &extension](const char* query_info) {
scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction();
function->set_extension(extension.get());
@@ -1732,7 +1761,7 @@ class ExtensionTabsZoomTest : public ExtensionTabsTest {
void ExtensionTabsZoomTest::SetUpOnMainThread() {
ExtensionTabsTest::SetUpOnMainThread();
- extension_ = test_util::CreateEmptyExtension();
+ extension_ = ExtensionBuilder("Test").Build();
}
bool ExtensionTabsZoomTest::RunSetZoom(int tab_id, double zoom_factor) {
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 c2207fe849f..582571ef429 100644
--- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
@@ -11,6 +11,7 @@
#include "base/json/json_writer.h"
#include "base/memory/ptr_util.h"
#include "base/sys_info.h"
+#include "base/task_scheduler/post_task.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h"
#include "chrome/browser/extensions/extension_service.h"
@@ -140,11 +141,12 @@ TerminalPrivateOpenTerminalProcessFunction::Run() {
if (tab_id < 0)
return RespondNow(Error("Not called from a tab or app window"));
- // Registry lives on FILE thread.
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
+ // Registry lives on its own task runner.
+ chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask(
+ FROM_HERE,
base::BindOnce(
- &TerminalPrivateOpenTerminalProcessFunction::OpenOnFileThread, this,
+ &TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner,
+ this,
base::Bind(&NotifyProcessOutput, browser_context(), extension_id(),
tab_id),
base::Bind(
@@ -153,7 +155,7 @@ TerminalPrivateOpenTerminalProcessFunction::Run() {
return RespondLater();
}
-void TerminalPrivateOpenTerminalProcessFunction::OpenOnFileThread(
+void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner(
const ProcessOutputCallback& output_callback,
const OpenProcessCallback& callback) {
DCHECK(!command_.empty());
@@ -182,15 +184,16 @@ ExtensionFunction::ResponseAction TerminalPrivateSendInputFunction::Run() {
std::unique_ptr<SendInput::Params> params(SendInput::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
- // Registry lives on the FILE thread.
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&TerminalPrivateSendInputFunction::SendInputOnFileThread,
- this, params->pid, params->input));
+ // Registry lives on its own task runner.
+ chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &TerminalPrivateSendInputFunction::SendInputOnRegistryTaskRunner,
+ this, params->pid, params->input));
return RespondLater();
}
-void TerminalPrivateSendInputFunction::SendInputOnFileThread(
+void TerminalPrivateSendInputFunction::SendInputOnRegistryTaskRunner(
int terminal_id,
const std::string& text) {
bool success =
@@ -215,17 +218,16 @@ TerminalPrivateCloseTerminalProcessFunction::Run() {
CloseTerminalProcess::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
- // Registry lives on the FILE thread.
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(
- &TerminalPrivateCloseTerminalProcessFunction::CloseOnFileThread, this,
- params->pid));
+ // Registry lives on its own task runner.
+ chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask(
+ FROM_HERE, base::BindOnce(&TerminalPrivateCloseTerminalProcessFunction::
+ CloseOnRegistryTaskRunner,
+ this, params->pid));
return RespondLater();
}
-void TerminalPrivateCloseTerminalProcessFunction::CloseOnFileThread(
+void TerminalPrivateCloseTerminalProcessFunction::CloseOnRegistryTaskRunner(
int terminal_id) {
bool success =
chromeos::ProcessProxyRegistry::Get()->CloseProcess(terminal_id);
@@ -251,17 +253,17 @@ TerminalPrivateOnTerminalResizeFunction::Run() {
OnTerminalResize::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
- // Registry lives on the FILE thread.
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(
- &TerminalPrivateOnTerminalResizeFunction::OnResizeOnFileThread, this,
- params->pid, params->width, params->height));
+ // Registry lives on its own task runner.
+ chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&TerminalPrivateOnTerminalResizeFunction::
+ OnResizeOnRegistryTaskRunner,
+ this, params->pid, params->width, params->height));
return RespondLater();
}
-void TerminalPrivateOnTerminalResizeFunction::OnResizeOnFileThread(
+void TerminalPrivateOnTerminalResizeFunction::OnResizeOnRegistryTaskRunner(
int terminal_id,
int width,
int height) {
@@ -296,16 +298,18 @@ ExtensionFunction::ResponseAction TerminalPrivateAckOutputFunction::Run() {
if (tab_id != params->tab_id)
return RespondNow(NoArguments());
- // Registry lives on the FILE thread.
- content::BrowserThread::PostTask(
- content::BrowserThread::FILE, FROM_HERE,
- base::BindOnce(&TerminalPrivateAckOutputFunction::AckOutputOnFileThread,
- this, params->pid));
+ // Registry lives on its own task runner.
+ chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &TerminalPrivateAckOutputFunction::AckOutputOnRegistryTaskRunner,
+ this, params->pid));
return RespondNow(NoArguments());
}
-void TerminalPrivateAckOutputFunction::AckOutputOnFileThread(int terminal_id) {
+void TerminalPrivateAckOutputFunction::AckOutputOnRegistryTaskRunner(
+ int terminal_id) {
chromeos::ProcessProxyRegistry::Get()->AckOutput(terminal_id);
}
diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h
index 09982a74805..c6455784059 100644
--- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h
+++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h
@@ -32,8 +32,8 @@ class TerminalPrivateOpenTerminalProcessFunction
const std::string& output)>;
using OpenProcessCallback = base::Callback<void(int terminal_id)>;
- void OpenOnFileThread(const ProcessOutputCallback& output_callback,
- const OpenProcessCallback& callback);
+ void OpenOnRegistryTaskRunner(const ProcessOutputCallback& output_callback,
+ const OpenProcessCallback& callback);
void RespondOnUIThread(int terminal_id);
std::string command_;
@@ -52,7 +52,7 @@ class TerminalPrivateSendInputFunction : public UIThreadExtensionFunction {
ExtensionFunction::ResponseAction Run() override;
private:
- void SendInputOnFileThread(int terminal_id, const std::string& input);
+ void SendInputOnRegistryTaskRunner(int terminal_id, const std::string& input);
void RespondOnUIThread(bool success);
};
@@ -69,7 +69,7 @@ class TerminalPrivateCloseTerminalProcessFunction
ExtensionFunction::ResponseAction Run() override;
private:
- void CloseOnFileThread(int terminal_id);
+ void CloseOnRegistryTaskRunner(int terminal_id);
void RespondOnUIThread(bool success);
};
@@ -86,7 +86,7 @@ class TerminalPrivateOnTerminalResizeFunction
ExtensionFunction::ResponseAction Run() override;
private:
- void OnResizeOnFileThread(int terminal_id, int width, int height);
+ void OnResizeOnRegistryTaskRunner(int terminal_id, int width, int height);
void RespondOnUIThread(bool success);
};
@@ -101,7 +101,7 @@ class TerminalPrivateAckOutputFunction : public UIThreadExtensionFunction {
ExtensionFunction::ResponseAction Run() override;
private:
- void AckOutputOnFileThread(int terminal_id);
+ void AckOutputOnRegistryTaskRunner(int terminal_id);
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc b/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc
index e0f47f99880..7c583c47bfb 100644
--- a/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc
@@ -4,7 +4,6 @@
#include <stddef.h>
-#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/values.h"
#include "build/build_config.h"
@@ -58,7 +57,7 @@ class TopSitesExtensionTest : public InProcessBrowserTest {
private:
void OnTopSitesAvailable(const history::MostVisitedURLList& data) {
if (waiting_) {
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
waiting_ = false;
}
top_sites_inited_ = true;
diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS
index 5af418aa5b6..41986102de4 100644
--- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS
+++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS
@@ -1,4 +1,3 @@
-bshe@chromium.org
-kevers@chromium.org
+file://ui/keyboard/OWNERS
# COMPONENT: UI>Input>VirtualKeyboard
diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
index 3392f302f93..6da975d1720 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
@@ -42,18 +42,6 @@ std::string GenerateFeatureFlag(const std::string& feature, bool enabled) {
return feature + (enabled ? "-enabled" : "-disabled");
}
-keyboard::KeyboardMode getKeyboardModeEnum(keyboard_api::KeyboardMode mode) {
- switch (mode) {
- case keyboard_api::KEYBOARD_MODE_NONE:
- return keyboard::NONE;
- case keyboard_api::KEYBOARD_MODE_FULL_WIDTH:
- return keyboard::FULL_WIDTH;
- case keyboard_api::KEYBOARD_MODE_FLOATING:
- return keyboard::FLOATING;
- }
- return keyboard::NONE;
-}
-
keyboard::KeyboardState getKeyboardStateEnum(
keyboard_api::KeyboardState state) {
switch (state) {
@@ -165,15 +153,9 @@ bool ChromeVirtualKeyboardDelegate::ShowLanguageSettings() {
}
bool ChromeVirtualKeyboardDelegate::SetVirtualKeyboardMode(int mode_enum) {
- keyboard::KeyboardMode keyboard_mode =
- getKeyboardModeEnum(static_cast<keyboard_api::KeyboardMode>(mode_enum));
- keyboard::KeyboardController* controller =
- keyboard::KeyboardController::GetInstance();
- if (!controller)
- return false;
-
- controller->SetKeyboardMode(keyboard_mode);
- return true;
+ // TODO(blakeo): remove this. The virtual keyboard's implementation of mode
+ // was removed, and so this should be removed from the JS API side as well.
+ return false;
}
bool ChromeVirtualKeyboardDelegate::SetRequestedKeyboardState(int state_enum) {
diff --git a/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc b/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc
index 2e51c36d7bf..daa35716969 100644
--- a/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc
@@ -390,17 +390,14 @@ IN_PROC_BROWSER_TEST_F(VpnProviderApiTest, ConfigPersistence) {
EXPECT_FALSE(DoesConfigExist(kTestConfig));
base::DictionaryValue properties;
- properties.SetStringWithoutPathExpansion(shill::kTypeProperty,
- shill::kTypeVPN);
- properties.SetStringWithoutPathExpansion(shill::kNameProperty, kTestConfig);
- properties.SetStringWithoutPathExpansion(shill::kProviderHostProperty,
- extension_id_);
- properties.SetStringWithoutPathExpansion(shill::kObjectPathSuffixProperty,
- GetKey(kTestConfig));
- properties.SetStringWithoutPathExpansion(shill::kProviderTypeProperty,
- shill::kProviderThirdPartyVpn);
- properties.SetStringWithoutPathExpansion(shill::kProfileProperty,
- kNetworkProfilePath);
+ properties.SetKey(shill::kTypeProperty, base::Value(shill::kTypeVPN));
+ properties.SetKey(shill::kNameProperty, base::Value(kTestConfig));
+ properties.SetKey(shill::kProviderHostProperty, base::Value(extension_id_));
+ properties.SetKey(shill::kObjectPathSuffixProperty,
+ base::Value(GetKey(kTestConfig)));
+ properties.SetKey(shill::kProviderTypeProperty,
+ base::Value(shill::kProviderThirdPartyVpn));
+ properties.SetKey(shill::kProfileProperty, base::Value(kNetworkProfilePath));
NetworkHandler::Get()
->network_configuration_handler()
->CreateShillConfiguration(
@@ -451,7 +448,7 @@ IN_PROC_BROWSER_TEST_F(VpnProviderApiTest, CreateDisable) {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile())->extension_service();
extension_service->DisableExtension(extension_id_,
- extensions::Extension::DISABLE_NONE);
+ extensions::disable_reason::DISABLE_NONE);
content::RunAllPendingInMessageLoop();
EXPECT_FALSE(DoesConfigExist(kTestConfig));
EXPECT_FALSE(DBusThreadManager::Get()
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 2cc3ea482ff..861f18cfafd 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
@@ -348,8 +348,7 @@ void WebNavigationTabObserver::DidFailLoad(
content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code,
- const base::string16& error_description,
- bool was_ignored_by_handler) {
+ const base::string16& error_description) {
// When showing replacement content, we might get load signals for frames
// that weren't reguarly loaded.
if (!navigation_state_.IsValidFrame(render_frame_host))
@@ -417,8 +416,10 @@ void WebNavigationTabObserver::DispatchCachedOnBeforeNavigate() {
void WebNavigationTabObserver::HandleCommit(
content::NavigationHandle* navigation_handle) {
- bool is_reference_fragment_navigation = IsReferenceFragmentNavigation(
- navigation_handle->GetRenderFrameHost(), navigation_handle->GetURL());
+ bool is_reference_fragment_navigation =
+ navigation_handle->IsSameDocument() &&
+ IsReferenceFragmentNavigation(navigation_handle->GetRenderFrameHost(),
+ navigation_handle->GetURL());
navigation_state_.StartTrackingDocumentLoad(
navigation_handle->GetRenderFrameHost(), navigation_handle->GetURL(),
diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h
index 35b22af8ce6..1b4b6645194 100644
--- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h
+++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h
@@ -59,8 +59,7 @@ class WebNavigationTabObserver
void DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code,
- const base::string16& error_description,
- bool was_ignored_by_handler) override;
+ const base::string16& error_description) override;
void DidOpenRequestedURL(content::WebContents* new_contents,
content::RenderFrameHost* source_render_frame_host,
const GURL& url,
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 944e035c9cf..6e29c8b0812 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
@@ -50,12 +50,15 @@
#include "extensions/common/api/web_request.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/features/feature.h"
+#include "google_apis/gaia/gaia_urls.h"
#include "net/base/auth.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/request_priority.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/dns/mock_host_resolver.h"
+#include "net/http/http_response_headers.h"
+#include "net/http/http_util.h"
#include "net/log/net_log_with_source.h"
#include "net/log/test_net_log.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
@@ -1485,6 +1488,7 @@ TEST(ExtensionWebRequestHelpersTest, TestCalculateOnHeadersReceivedDelta) {
"Key2: Value2, Bar\r\n"
"Key3: Value3\r\n"
"Key5: Value5, end5\r\n"
+ "X-Chrome-ID-Consistency-Response: Value6\r\n"
"\r\n";
scoped_refptr<net::HttpResponseHeaders> base_headers(
new net::HttpResponseHeaders(
@@ -1497,11 +1501,39 @@ TEST(ExtensionWebRequestHelpersTest, TestCalculateOnHeadersReceivedDelta) {
// Key3 is deleted
new_headers.push_back(ResponseHeader("Key4", "Value4")); // Added
new_headers.push_back(ResponseHeader("Key5", "Value5, end5")); // Unchanged
- GURL effective_new_url;
-
- std::unique_ptr<EventResponseDelta> delta(CalculateOnHeadersReceivedDelta(
- "extid", base::Time::Now(), cancel, effective_new_url, base_headers.get(),
- &new_headers));
+ new_headers.push_back(ResponseHeader("X-Chrome-ID-Consistency-Response",
+ "Value1")); // Modified
+ GURL url;
+
+ // The X-Chrome-ID-Consistency-Response is a protected header, but only for
+ // Gaia URLs. It should be modifiable when sent from anywhere else.
+ // Non-Gaia URL:
+ std::unique_ptr<EventResponseDelta> delta(
+ CalculateOnHeadersReceivedDelta("extid", base::Time::Now(), cancel, url,
+ url, base_headers.get(), &new_headers));
+ ASSERT_TRUE(delta.get());
+ EXPECT_TRUE(delta->cancel);
+ EXPECT_EQ(3u, delta->added_response_headers.size());
+ EXPECT_TRUE(base::ContainsValue(delta->added_response_headers,
+ ResponseHeader("Key2", "Value1")));
+ EXPECT_TRUE(base::ContainsValue(delta->added_response_headers,
+ ResponseHeader("Key4", "Value4")));
+ EXPECT_TRUE(base::ContainsValue(
+ delta->added_response_headers,
+ ResponseHeader("X-Chrome-ID-Consistency-Response", "Value1")));
+ EXPECT_EQ(3u, delta->deleted_response_headers.size());
+ EXPECT_TRUE(base::ContainsValue(delta->deleted_response_headers,
+ ResponseHeader("Key2", "Value2, Bar")));
+ EXPECT_TRUE(base::ContainsValue(delta->deleted_response_headers,
+ ResponseHeader("Key3", "Value3")));
+ EXPECT_TRUE(base::ContainsValue(
+ delta->deleted_response_headers,
+ ResponseHeader("X-Chrome-ID-Consistency-Response", "Value6")));
+
+ // Gaia URL:
+ delta.reset(CalculateOnHeadersReceivedDelta(
+ "extid", base::Time::Now(), cancel, GaiaUrls::GetInstance()->gaia_url(),
+ url, base_headers.get(), &new_headers));
ASSERT_TRUE(delta.get());
EXPECT_TRUE(delta->cancel);
EXPECT_EQ(2u, delta->added_response_headers.size());
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 f5fcff50320..873abeb4a92 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
@@ -30,6 +30,7 @@
#include "chromeos/login/scoped_test_public_session_login_state.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
+#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_frame_host.h"
@@ -45,7 +46,9 @@
#include "extensions/common/features/feature.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
+#include "google_apis/gaia/gaia_switches.h"
#include "net/dns/mock_host_resolver.h"
+#include "net/http/http_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/test_data_directory.h"
@@ -104,6 +107,10 @@ const char kPerformXhrJs[] =
"};\n"
"xhr.send();\n";
+// Header values set by the server and by the extension.
+const char kHeaderValueFromExtension[] = "ValueFromExtension";
+const char kHeaderValueFromServer[] = "ValueFromServer";
+
// Performs an XHR in the given |frame|, replying when complete.
void PerformXhrInFrame(content::RenderFrameHost* frame,
const std::string& host,
@@ -204,6 +211,11 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest {
host_resolver()->AddRule("*", "127.0.0.1");
}
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ ExtensionApiTest::SetUpCommandLine(command_line);
+ command_line->AppendSwitchASCII(switches::kGaiaUrl, "http://gaia.com");
+ }
+
void RunPermissionTest(
const char* extension_directory,
bool load_extension_with_incognito_permission,
@@ -846,6 +858,112 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
GetWebRequestCountFromBackgroundPage(extension, profile()));
}
+// Checks that the Dice response header is protected for Gaia URLs, but not
+// other URLs.
+IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
+ WebRequestDiceHeaderProtection) {
+ // Load an extension that registers a listener for webRequest events, and
+ // wait until it is initialized.
+ ExtensionTestMessageListener listener("ready", false);
+ const Extension* extension =
+ LoadExtension(test_data_dir_.AppendASCII("webrequest_dice_header"));
+ ASSERT_TRUE(extension) << message_;
+ EXPECT_TRUE(listener.WaitUntilSatisfied());
+
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ // Setup a web contents observer to inspect the response headers after the
+ // extension was run.
+ class TestWebContentsObserver : public content::WebContentsObserver {
+ public:
+ explicit TestWebContentsObserver(content::WebContents* contents)
+ : WebContentsObserver(contents) {}
+
+ void DidFinishNavigation(
+ content::NavigationHandle* navigation_handle) override {
+ // Check that the extension cannot add a Dice header.
+ const net::HttpResponseHeaders* headers =
+ navigation_handle->GetResponseHeaders();
+ EXPECT_TRUE(headers->GetNormalizedHeader(
+ "X-Chrome-ID-Consistency-Response", &dice_header_value_));
+ EXPECT_TRUE(
+ headers->GetNormalizedHeader("X-New-Header", &new_header_value_));
+ EXPECT_TRUE(
+ headers->GetNormalizedHeader("X-Control", &control_header_value_));
+ did_finish_navigation_called_ = true;
+ }
+
+ bool did_finish_navigation_called() const {
+ return did_finish_navigation_called_;
+ }
+
+ const std::string& dice_header_value() const { return dice_header_value_; }
+
+ const std::string& new_header_value() const { return new_header_value_; }
+
+ const std::string& control_header_value() const {
+ return control_header_value_;
+ }
+
+ void Clear() {
+ did_finish_navigation_called_ = false;
+ dice_header_value_.clear();
+ new_header_value_.clear();
+ control_header_value_.clear();
+ }
+
+ private:
+ bool did_finish_navigation_called_ = false;
+ std::string dice_header_value_;
+ std::string new_header_value_;
+ std::string control_header_value_;
+ };
+
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ TestWebContentsObserver test_webcontents_observer(web_contents);
+
+ // Navigate to the Gaia URL intercepted by the extension.
+ GURL url =
+ embedded_test_server()->GetURL("gaia.com", "/extensions/dice.html");
+ ui_test_utils::NavigateToURL(browser(), url);
+
+ // Check that the Dice header was not changed by the extension.
+ EXPECT_TRUE(test_webcontents_observer.did_finish_navigation_called());
+ EXPECT_EQ(kHeaderValueFromServer,
+ test_webcontents_observer.dice_header_value());
+ EXPECT_EQ(kHeaderValueFromExtension,
+ test_webcontents_observer.new_header_value());
+ EXPECT_EQ(kHeaderValueFromExtension,
+ test_webcontents_observer.control_header_value());
+
+ // Check that the Dice header cannot be read by the extension.
+ EXPECT_EQ(0, GetCountFromBackgroundPage(extension, profile(),
+ "window.diceResponseHeaderCount"));
+ EXPECT_EQ(1, GetCountFromBackgroundPage(extension, profile(),
+ "window.controlResponseHeaderCount"));
+
+ // Navigate to a non-Gaia URL intercepted by the extension.
+ test_webcontents_observer.Clear();
+ url = embedded_test_server()->GetURL("example.com", "/extensions/dice.html");
+ ui_test_utils::NavigateToURL(browser(), url);
+
+ // Check that the Dice header was changed by the extension.
+ EXPECT_TRUE(test_webcontents_observer.did_finish_navigation_called());
+ EXPECT_EQ(kHeaderValueFromExtension,
+ test_webcontents_observer.dice_header_value());
+ EXPECT_EQ(kHeaderValueFromExtension,
+ test_webcontents_observer.new_header_value());
+ EXPECT_EQ(kHeaderValueFromExtension,
+ test_webcontents_observer.control_header_value());
+
+ // Check that the Dice header can be read by the extension.
+ EXPECT_EQ(1, GetCountFromBackgroundPage(extension, profile(),
+ "window.diceResponseHeaderCount"));
+ EXPECT_EQ(2, GetCountFromBackgroundPage(extension, profile(),
+ "window.controlResponseHeaderCount"));
+}
+
// Test that the webRequest events are dispatched for the WebSocket handshake
// requests.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebSocketRequest) {
diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
index 4501c524845..b68ccc592b8 100644
--- a/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
@@ -4,7 +4,17 @@
#include "extensions/browser/api/web_request/web_request_event_details.h"
+#include "base/message_loop/message_loop.h"
+#include "base/values.h"
+#include "extensions/browser/api/web_request/web_request_api_constants.h"
+#include "extensions/browser/api/web_request/web_request_api_helpers.h"
+#include "google_apis/gaia/gaia_urls.h"
+#include "net/http/http_response_headers.h"
+#include "net/http/http_util.h"
+#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
+#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
namespace extensions {
@@ -64,4 +74,60 @@ TEST(WebRequestEventDetailsTest, WhitelistedCopyForPublicSession) {
EXPECT_EQ(arraysize(safe_attributes) + 1, copy->dict_.size());
}
+TEST(WebRequestEventDetailsTest, SetResponseHeaders) {
+ const int kFilter =
+ extension_web_request_api_helpers::ExtraInfoSpec::RESPONSE_HEADERS;
+ base::MessageLoop message_loop;
+ net::TestURLRequestContext context;
+
+ char headers_string[] =
+ "HTTP/1.0 200 OK\r\n"
+ "Key1: Value1\r\n"
+ "X-Chrome-ID-Consistency-Response: Value2\r\n"
+ "\r\n";
+ scoped_refptr<net::HttpResponseHeaders> headers(
+ new net::HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders(
+ headers_string, sizeof(headers_string))));
+
+ {
+ // Non-Gaia URL.
+ std::unique_ptr<net::URLRequest> request = context.CreateRequest(
+ GURL("http://www.example.com"), net::DEFAULT_PRIORITY, nullptr,
+ TRAFFIC_ANNOTATION_FOR_TESTS);
+ WebRequestEventDetails details(request.get(), kFilter);
+ details.SetResponseHeaders(request.get(), headers.get());
+ std::unique_ptr<base::DictionaryValue> dict =
+ details.GetFilteredDict(kFilter);
+ base::Value* filtered_headers = dict->FindPath({"responseHeaders"});
+ ASSERT_TRUE(filtered_headers);
+ EXPECT_EQ(2u, filtered_headers->GetList().size());
+ EXPECT_EQ("Key1",
+ filtered_headers->GetList()[0].FindPath({"name"})->GetString());
+ EXPECT_EQ("Value1",
+ filtered_headers->GetList()[0].FindPath({"value"})->GetString());
+ EXPECT_EQ("X-Chrome-ID-Consistency-Response",
+ filtered_headers->GetList()[1].FindPath({"name"})->GetString());
+ EXPECT_EQ("Value2",
+ filtered_headers->GetList()[1].FindPath({"value"})->GetString());
+ }
+
+ {
+ // Gaia URL.
+ std::unique_ptr<net::URLRequest> gaia_request = context.CreateRequest(
+ GaiaUrls::GetInstance()->gaia_url(), net::DEFAULT_PRIORITY, nullptr,
+ TRAFFIC_ANNOTATION_FOR_TESTS);
+ WebRequestEventDetails gaia_details(gaia_request.get(), kFilter);
+ gaia_details.SetResponseHeaders(gaia_request.get(), headers.get());
+ std::unique_ptr<base::DictionaryValue> dict =
+ gaia_details.GetFilteredDict(kFilter);
+ base::Value* filtered_headers = dict->FindPath({"responseHeaders"});
+ ASSERT_TRUE(filtered_headers);
+ EXPECT_EQ(1u, filtered_headers->GetList().size());
+ EXPECT_EQ("Key1",
+ filtered_headers->GetList()[0].FindPath({"name"})->GetString());
+ EXPECT_EQ("Value1",
+ filtered_headers->GetList()[0].FindPath({"value"})->GetString());
+ }
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc
index 1670e5593f9..c87e15d2688 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc
@@ -181,10 +181,9 @@ void WebrtcAudioPrivateGetSinksFunction::
GetOutputDeviceDescriptionsOnIOThread() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media::AudioSystem::Get()->GetDeviceDescriptions(
- base::BindOnce(&WebrtcAudioPrivateGetSinksFunction::
- ReceiveOutputDeviceDescriptionsOnIOThread,
- this),
- false);
+ false, base::BindOnce(&WebrtcAudioPrivateGetSinksFunction::
+ ReceiveOutputDeviceDescriptionsOnIOThread,
+ this));
}
void WebrtcAudioPrivateGetSinksFunction::
@@ -237,10 +236,9 @@ void WebrtcAudioPrivateGetAssociatedSinkFunction::
GetInputDeviceDescriptionsOnIOThread() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media::AudioSystem::Get()->GetDeviceDescriptions(
- base::BindOnce(&WebrtcAudioPrivateGetAssociatedSinkFunction::
- ReceiveInputDeviceDescriptionsOnIOThread,
- this),
- true);
+ true, base::BindOnce(&WebrtcAudioPrivateGetAssociatedSinkFunction::
+ ReceiveInputDeviceDescriptionsOnIOThread,
+ this));
}
void WebrtcAudioPrivateGetAssociatedSinkFunction::
diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc
index 9f97850507a..596f5db33e5 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc
@@ -63,14 +63,14 @@ void GetAudioDeviceDescriptions(bool for_input,
AudioDeviceDescriptions* device_descriptions) {
base::RunLoop run_loop;
media::AudioSystem::Get()->GetDeviceDescriptions(
+ for_input,
base::BindOnce(
[](base::Closure finished_callback, AudioDeviceDescriptions* result,
AudioDeviceDescriptions received) {
*result = std::move(received);
finished_callback.Run();
},
- base::Passed(run_loop.QuitClosure()), device_descriptions),
- for_input);
+ base::Passed(run_loop.QuitClosure()), device_descriptions));
run_loop.Run();
}
diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc
index 4c040ef09e0..f5c6b448fca 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc
@@ -24,7 +24,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/browser/api_test_utils.h"
-#include "extensions/common/test_util.h"
+#include "extensions/common/extension_builder.h"
#include "media/base/media_switches.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
@@ -106,7 +106,7 @@ class WebrtcEventLogApiTest : public WebRtcTestBase {
protected:
void SetUp() override {
WebRtcTestBase::SetUp();
- extension_ = extensions::test_util::CreateEmptyExtension();
+ extension_ = extensions::ExtensionBuilder("Test").Build();
}
void SetUpInProcessBrowserTestFixture() override {
diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc
index d6b28a91bdf..d93ec89c88e 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc
@@ -20,7 +20,7 @@
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_utils.h"
-#include "extensions/common/test_util.h"
+#include "extensions/common/extension_builder.h"
#include "third_party/zlib/google/compression_utils.h"
using compression::GzipUncompress;
@@ -69,7 +69,7 @@ class WebrtcLoggingPrivateApiTest : public ExtensionApiTest {
protected:
void SetUp() override {
ExtensionApiTest::SetUp();
- extension_ = extensions::test_util::CreateEmptyExtension();
+ extension_ = extensions::ExtensionBuilder("Test").Build();
}
template<typename T>
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 acccb70a604..b6792c025b7 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
@@ -642,12 +642,12 @@ WebstorePrivateIsPendingCustodianApprovalFunction::Run() {
ExtensionPrefs* extensions_prefs = ExtensionPrefs::Get(browser_context());
if (extensions_prefs->HasDisableReason(
- params->id, Extension::DISABLE_PERMISSIONS_INCREASE)) {
+ params->id, disable_reason::DISABLE_PERMISSIONS_INCREASE)) {
return RespondNow(BuildResponse(true));
}
bool is_pending_approval = extensions_prefs->HasDisableReason(
- params->id, Extension::DISABLE_CUSTODIAN_APPROVAL_REQUIRED);
+ params->id, disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED);
return RespondNow(BuildResponse(is_pending_approval));
}
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 b29f88d3688..45f5cc3b689 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
@@ -8,6 +8,7 @@
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
@@ -58,7 +59,7 @@ class WebstoreInstallListener : public WebstoreInstaller::Delegate {
if (waiting_) {
waiting_ = false;
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
}
@@ -72,7 +73,7 @@ class WebstoreInstallListener : public WebstoreInstaller::Delegate {
if (waiting_) {
waiting_ = false;
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
}
diff --git a/chromium/chrome/browser/media/media_engagement_score_details.mojom b/chromium/chrome/browser/media/media_engagement_score_details.mojom
index e4e0fb9ec11..6daed69a2f0 100644
--- a/chromium/chrome/browser/media/media_engagement_score_details.mojom
+++ b/chromium/chrome/browser/media/media_engagement_score_details.mojom
@@ -16,6 +16,9 @@ struct MediaEngagementScoreDetails {
// Last media playback time in milliseconds since the epoch format.
double last_media_playback_time;
+
+ // Whether the score is considered to be high.
+ bool is_high;
};
interface MediaEngagementScoreDetailsProvider {
diff --git a/chromium/chrome/browser/media/router/BUILD.gn b/chromium/chrome/browser/media/router/BUILD.gn
index 7a7e9dd6588..650d76273d7 100644
--- a/chromium/chrome/browser/media/router/BUILD.gn
+++ b/chromium/chrome/browser/media/router/BUILD.gn
@@ -24,8 +24,6 @@ static_library("router") {
sources = [
"browser_presentation_connection_proxy.cc",
"browser_presentation_connection_proxy.h",
- "create_presentation_connection_request.cc",
- "create_presentation_connection_request.h",
"issue_manager.cc",
"issue_manager.h",
"issues_observer.cc",
@@ -43,16 +41,12 @@ static_library("router") {
"media_routes_observer.h",
"media_sinks_observer.cc",
"media_sinks_observer.h",
- "mojo/media_route_controller.cc",
- "mojo/media_route_controller.h",
"offscreen_presentation_manager.cc",
"offscreen_presentation_manager.h",
"offscreen_presentation_manager_factory.cc",
"offscreen_presentation_manager_factory.h",
"presentation_media_sinks_observer.cc",
"presentation_media_sinks_observer.h",
- "presentation_request.cc",
- "presentation_request.h",
"presentation_service_delegate_impl.cc",
"presentation_service_delegate_impl.h",
"presentation_service_delegate_observers.cc",
@@ -82,8 +76,12 @@ static_library("router") {
"media_router_ui_service.h",
"media_router_ui_service_factory.cc",
"media_router_ui_service_factory.h",
+ "mojo/media_route_controller.cc",
+ "mojo/media_route_controller.h",
"mojo/media_route_provider_util_win.cc",
"mojo/media_route_provider_util_win.h",
+ "mojo/media_router_desktop.cc",
+ "mojo/media_router_desktop.h",
"mojo/media_router_mojo_impl.cc",
"mojo/media_router_mojo_impl.h",
"mojo/media_router_mojo_metrics.cc",
diff --git a/chromium/chrome/browser/media/router/discovery/BUILD.gn b/chromium/chrome/browser/media/router/discovery/BUILD.gn
index 22de620923d..a54986ad192 100644
--- a/chromium/chrome/browser/media/router/discovery/BUILD.gn
+++ b/chromium/chrome/browser/media/router/discovery/BUILD.gn
@@ -39,12 +39,16 @@ static_library("discovery") {
"dial/safe_dial_device_description_parser.h",
"mdns/cast_media_sink_service.cc",
"mdns/cast_media_sink_service.h",
+ "mdns/cast_media_sink_service_impl.cc",
+ "mdns/cast_media_sink_service_impl.h",
"mdns/dns_sd_delegate.cc",
"mdns/dns_sd_delegate.h",
"mdns/dns_sd_device_lister.cc",
"mdns/dns_sd_device_lister.h",
"mdns/dns_sd_registry.cc",
"mdns/dns_sd_registry.h",
+ "media_sink_discovery_metrics.cc",
+ "media_sink_discovery_metrics.h",
"media_sink_service_base.cc",
"media_sink_service_base.h",
]
diff --git a/chromium/chrome/browser/metrics/BUILD.gn b/chromium/chrome/browser/metrics/BUILD.gn
new file mode 100644
index 00000000000..5fea07e070f
--- /dev/null
+++ b/chromium/chrome/browser/metrics/BUILD.gn
@@ -0,0 +1,14 @@
+# 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.
+
+import("//components/metrics/generate_expired_histograms_array.gni")
+
+generate_expired_histograms_array("expired_histograms_array") {
+ inputs = [
+ "//tools/metrics/histograms/histograms.xml",
+ "//tools/metrics/histograms/enums.xml",
+ ]
+ namespace = "chrome_metrics"
+ header_filename = "expired_histograms_array.h"
+}
diff --git a/chromium/chrome/browser/printing/background_printing_manager.cc b/chromium/chrome/browser/printing/background_printing_manager.cc
index fd10907e4f1..d1ca0dcc18e 100644
--- a/chromium/chrome/browser/printing/background_printing_manager.cc
+++ b/chromium/chrome/browser/printing/background_printing_manager.cc
@@ -67,7 +67,8 @@ BackgroundPrintingManager::~BackgroundPrintingManager() {
void BackgroundPrintingManager::OwnPrintPreviewDialog(
WebContents* preview_dialog) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
- DCHECK(PrintPreviewDialogController::IsPrintPreviewDialog(preview_dialog));
+ DCHECK(PrintPreviewDialogController::IsPrintPreviewURL(
+ preview_dialog->GetURL()));
CHECK(!HasPrintPreviewDialog(preview_dialog));
printing_contents_map_[preview_dialog] =
diff --git a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc
index ac18905c7fe..05898e33d74 100644
--- a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc
+++ b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc
@@ -28,15 +28,27 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/service_process/service_process_control.h"
#include "chrome/common/chrome_switches.h"
-#include "chrome/common/cloud_print/cloud_print_proxy_info.h"
#include "chrome/common/pref_names.h"
-#include "chrome/common/service_messages.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
#include "printing/backend/print_backend.h"
using content::BrowserThread;
+namespace {
+
+void ForwardGetPrintersResult(
+ const CloudPrintProxyService::PrintersCallback& callback,
+ const std::vector<std::string>& printers) {
+ UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
+ ServiceProcessControl::SERVICE_PRINTERS_REPLY,
+ ServiceProcessControl::SERVICE_EVENT_MAX);
+ UMA_HISTOGRAM_COUNTS_10000("CloudPrint.AvailablePrinters", printers.size());
+ callback.Run(printers);
+}
+
+} // namespace
+
CloudPrintProxyService::CloudPrintProxyService(Profile* profile)
: profile_(profile),
weak_factory_(this) {
@@ -161,18 +173,25 @@ void CloudPrintProxyService::GetPrinters(const PrintersCallback& callback) {
void CloudPrintProxyService::GetCloudPrintProxyPrinters(
const PrintersCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
+ ServiceProcessControl::SERVICE_PRINTERS_REQUEST,
+ ServiceProcessControl::SERVICE_EVENT_MAX);
ServiceProcessControl* process_control = GetServiceProcessControl();
DCHECK(process_control->IsConnected());
- process_control->GetPrinters(callback);
+ GetCloudPrintProxy().GetPrinters(
+ base::BindOnce(&ForwardGetPrintersResult, callback));
}
void CloudPrintProxyService::RefreshCloudPrintProxyStatus() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
+ ServiceProcessControl::SERVICE_EVENT_INFO_REQUEST,
+ ServiceProcessControl::SERVICE_EVENT_MAX);
ServiceProcessControl* process_control = GetServiceProcessControl();
DCHECK(process_control->IsConnected());
- ServiceProcessControl::CloudPrintProxyInfoCallback callback = base::Bind(
- &CloudPrintProxyService::ProxyInfoCallback, base::Unretained(this));
- process_control->GetCloudPrintProxyInfo(callback);
+ auto callback = base::BindOnce(&CloudPrintProxyService::ProxyInfoCallback,
+ base::Unretained(this));
+ GetCloudPrintProxy().GetCloudPrintProxyInfo(std::move(callback));
}
void CloudPrintProxyService::EnableCloudPrintProxyWithRobot(
@@ -182,9 +201,9 @@ void CloudPrintProxyService::EnableCloudPrintProxyWithRobot(
const base::DictionaryValue* user_preferences) {
ServiceProcessControl* process_control = GetServiceProcessControl();
DCHECK(process_control->IsConnected());
- process_control->Send(
- new ServiceMsg_EnableCloudPrintProxyWithRobot(
- robot_auth_code, robot_email, user_email, *user_preferences));
+ GetCloudPrintProxy().EnableCloudPrintProxyWithRobot(
+ robot_auth_code, robot_email, user_email,
+ user_preferences->CreateDeepCopy());
// Assume the IPC worked.
profile_->GetPrefs()->SetString(prefs::kCloudPrintEmail, user_email);
}
@@ -192,17 +211,20 @@ void CloudPrintProxyService::EnableCloudPrintProxyWithRobot(
void CloudPrintProxyService::DisableCloudPrintProxy() {
ServiceProcessControl* process_control = GetServiceProcessControl();
DCHECK(process_control->IsConnected());
- process_control->Send(new ServiceMsg_DisableCloudPrintProxy);
+ GetCloudPrintProxy().DisableCloudPrintProxy();
// Assume the IPC worked.
profile_->GetPrefs()->SetString(prefs::kCloudPrintEmail, std::string());
}
-void CloudPrintProxyService::ProxyInfoCallback(
- const cloud_print::CloudPrintProxyInfo& proxy_info) {
- proxy_id_ = proxy_info.proxy_id;
- profile_->GetPrefs()->SetString(
- prefs::kCloudPrintEmail,
- proxy_info.enabled ? proxy_info.email : std::string());
+void CloudPrintProxyService::ProxyInfoCallback(bool enabled,
+ const std::string& email,
+ const std::string& proxy_id) {
+ UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
+ ServiceProcessControl::SERVICE_EVENT_INFO_REPLY,
+ ServiceProcessControl::SERVICE_EVENT_MAX);
+ proxy_id_ = proxy_id;
+ profile_->GetPrefs()->SetString(prefs::kCloudPrintEmail,
+ enabled ? email : std::string());
ApplyCloudPrintConnectorPolicy();
}
@@ -214,3 +236,11 @@ bool CloudPrintProxyService::InvokeServiceTask(const base::Closure& task) {
ServiceProcessControl* CloudPrintProxyService::GetServiceProcessControl() {
return ServiceProcessControl::GetInstance();
}
+
+cloud_print::mojom::CloudPrint& CloudPrintProxyService::GetCloudPrintProxy() {
+ if (!cloud_print_proxy_ || cloud_print_proxy_.encountered_error()) {
+ GetServiceProcessControl()->remote_interfaces().GetInterface(
+ &cloud_print_proxy_);
+ }
+ return *cloud_print_proxy_;
+}
diff --git a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h
index ac30e5c20fa..776db58ab21 100644
--- a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h
+++ b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h
@@ -12,6 +12,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
+#include "chrome/common/cloud_print.mojom.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/prefs/pref_change_registrar.h"
@@ -22,10 +23,6 @@ namespace base {
class DictionaryValue;
} // namespace base
-namespace cloud_print {
-struct CloudPrintProxyInfo;
-} // namespace cloud_print
-
// Layer between the browser user interface and the cloud print proxy code
// running in the service process.
class CloudPrintProxyService : public KeyedService {
@@ -73,8 +70,9 @@ class CloudPrintProxyService : public KeyedService {
void DisableCloudPrintProxy();
// Callback that gets the cloud print proxy info.
- void ProxyInfoCallback(
- const cloud_print::CloudPrintProxyInfo& proxy_info);
+ void ProxyInfoCallback(bool enabled,
+ const std::string& email,
+ const std::string& proxy_id);
// Invoke a task that gets run after the service process successfully
// launches. The task typically involves sending an IPC to the service
@@ -85,15 +83,19 @@ class CloudPrintProxyService : public KeyedService {
// not set or the connector is not enabled).
bool ApplyCloudPrintConnectorPolicy();
- Profile* profile_;
- std::string proxy_id_;
+ cloud_print::mojom::CloudPrint& GetCloudPrintProxy();
// Virtual for testing.
virtual ServiceProcessControl* GetServiceProcessControl();
+ Profile* profile_;
+ std::string proxy_id_;
+
// For watching for connector policy changes.
PrefChangeRegistrar pref_change_registrar_;
+ cloud_print::mojom::CloudPrintPtr cloud_print_proxy_;
+
base::WeakPtrFactory<CloudPrintProxyService> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(CloudPrintProxyService);
diff --git a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc
index 1075eacdc1f..6de22a51161 100644
--- a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc
@@ -19,9 +19,9 @@
#include "chrome/browser/service_process/service_process_control.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/common/chrome_switches.h"
+#include "chrome/common/cloud_print.mojom.h"
#include "chrome/common/cloud_print/cloud_print_proxy_info.h"
#include "chrome/common/pref_names.h"
-#include "chrome/common/service_messages.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
@@ -29,6 +29,7 @@
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
+#include "mojo/public/cpp/bindings/binding_set.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -55,27 +56,7 @@ class MockServiceProcessControl : public ServiceProcessControl {
MOCK_METHOD2(Launch, void(const base::Closure&, const base::Closure&));
MOCK_METHOD0(Disconnect, void());
- MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message&));
- MOCK_METHOD1(OnChannelConnected, void(int32_t peer_pid));
- MOCK_METHOD0(OnChannelError, void());
-
- MOCK_METHOD1(Send, bool(IPC::Message*));
-
- typedef enum {
- kServiceStateDisabled,
- kServiceStateEnabled,
- kServiceStateNone
- } ServiceState;
-
- void SetConnectSuccessMockExpectations(ServiceState state, bool post_task);
-
- void SetServiceEnabledExpectations();
- void SetServiceDisabledExpectations();
- void SetWillBeEnabledExpectations();
- void SetWillBeDisabledExpectations();
-
- bool SendEnabledInfo();
- bool SendDisabledInfo();
+ void SetConnectSuccessMockExpectations(bool post_task);
private:
bool connected_;
@@ -98,7 +79,6 @@ void PostTask(const base::Closure& task) {
}
void MockServiceProcessControl::SetConnectSuccessMockExpectations(
- ServiceState service_state,
bool post_task) {
EXPECT_CALL(*this, IsConnected()).WillRepeatedly(ReturnPointee(&connected_));
@@ -110,71 +90,82 @@ void MockServiceProcessControl::SetConnectSuccessMockExpectations(
EXPECT_CALL(*this, Disconnect()).Times(AtMost(1))
.WillRepeatedly(Assign(&connected_, false));
- EXPECT_CALL(*this, Send(_)).Times(0);
-
- if (service_state == kServiceStateEnabled)
- SetServiceEnabledExpectations();
- else if (service_state == kServiceStateDisabled)
- SetServiceDisabledExpectations();
}
-void MockServiceProcessControl::SetServiceEnabledExpectations() {
- EXPECT_CALL(*this, Send(Property(&IPC::Message::type,
- static_cast<int32_t>(
- ServiceMsg_GetCloudPrintProxyInfo::ID))))
- .Times(1)
- .WillOnce(DoAll(DeleteArg<0>(),
- WithoutArgs(Invoke(
- this, &MockServiceProcessControl::SendEnabledInfo))));
-}
+class MockCloudPrintProxy : public cloud_print::mojom::CloudPrint {
+ public:
+ void AddBinding(cloud_print::mojom::CloudPrintRequest request) {
+ bindings_.AddBinding(this, std::move(request));
+ }
-void MockServiceProcessControl::SetServiceDisabledExpectations() {
- EXPECT_CALL(*this, Send(Property(&IPC::Message::type,
- static_cast<int32_t>(
- ServiceMsg_GetCloudPrintProxyInfo::ID))))
- .Times(1)
- .WillOnce(
- DoAll(DeleteArg<0>(),
- WithoutArgs(Invoke(
- this, &MockServiceProcessControl::SendDisabledInfo))));
-}
+ void ReturnDisabledInfo() {
+ cloud_proxy_info_expectation_set_ = true;
+ cloud_proxy_info_.enabled = false;
+ cloud_proxy_info_.email.clear();
+ }
-void MockServiceProcessControl::SetWillBeEnabledExpectations() {
- int32_t message_id = ServiceMsg_EnableCloudPrintProxyWithRobot::ID;
- EXPECT_CALL(
- *this,
- Send(Property(&IPC::Message::type, message_id)))
- .Times(1).WillOnce(DoAll(DeleteArg<0>(), Return(true)));
-}
+ void ReturnEnabledInfo() {
+ cloud_proxy_info_expectation_set_ = true;
+ cloud_proxy_info_.enabled = true;
+ cloud_proxy_info_.email = MockServiceProcessControl::EnabledUserId();
+ }
-void MockServiceProcessControl::SetWillBeDisabledExpectations() {
- EXPECT_CALL(*this, Send(Property(&IPC::Message::type,
- static_cast<int32_t>(
- ServiceMsg_DisableCloudPrintProxy::ID))))
- .Times(1)
- .WillOnce(DoAll(DeleteArg<0>(), Return(true)));
-}
+ bool has_been_enabled() {
+ bindings_.FlushForTesting();
+ return enabled_;
+ }
+ bool has_been_disabled() {
+ bindings_.FlushForTesting();
+ return disabled_;
+ }
-bool MockServiceProcessControl::SendEnabledInfo() {
- info_.enabled = true;
- info_.email = EnabledUserId();
- PostTask(base::Bind(&MockServiceProcessControl::OnCloudPrintProxyInfo,
- base::Unretained(this), info_));
- return true;
-}
+ private:
+ void GetCloudPrintProxyInfo(
+ GetCloudPrintProxyInfoCallback callback) override {
+ EXPECT_TRUE(cloud_proxy_info_expectation_set_);
+ std::move(callback).Run(cloud_proxy_info_.enabled, cloud_proxy_info_.email,
+ cloud_proxy_info_.proxy_id);
+ }
+ void GetPrinters(GetPrintersCallback callback) override { NOTREACHED(); }
+ void DisableCloudPrintProxy() override { disabled_ = true; }
+
+ void EnableCloudPrintProxyWithRobot(
+ const std::string& robot_auth_code,
+ const std::string& robot_email,
+ const std::string& user_email,
+ std::unique_ptr<base::DictionaryValue> user_settings) override {
+ enabled_ = true;
+ }
-bool MockServiceProcessControl::SendDisabledInfo() {
- info_.enabled = false;
- info_.email = std::string();
- PostTask(base::Bind(&MockServiceProcessControl::OnCloudPrintProxyInfo,
- base::Unretained(this), info_));
- return true;
-}
+ mojo::BindingSet<cloud_print::mojom::CloudPrint> bindings_;
+
+ bool cloud_proxy_info_expectation_set_ = false;
+ cloud_print::CloudPrintProxyInfo cloud_proxy_info_;
+
+ bool disabled_ = false;
+ bool enabled_ = false;
+};
class TestCloudPrintProxyService : public CloudPrintProxyService {
public:
explicit TestCloudPrintProxyService(Profile* profile)
- : CloudPrintProxyService(profile) { }
+ : CloudPrintProxyService(profile) {
+ service_manager::InterfaceProvider::TestApi test_api(
+ &process_control_.remote_interfaces());
+ test_api.SetBinderForName(
+ "cloud_print::mojom::CloudPrint",
+ base::Bind(&TestCloudPrintProxyService::HandleCloudPrintProxyRequest,
+ base::Unretained(this)));
+ service_manager::mojom::InterfaceProviderPtr handle;
+ mojo::MakeRequest(&handle);
+ process_control_.SetMojoHandle(std::move(handle));
+ }
+
+ ~TestCloudPrintProxyService() override {
+ service_manager::InterfaceProvider::TestApi test_api(
+ &ServiceProcessControl::GetInstance()->remote_interfaces());
+ test_api.ClearBinderForName("cloud_print::mojom::CloudPrint");
+ }
void Initialize() {
CloudPrintProxyService::Initialize();
@@ -189,10 +180,13 @@ class TestCloudPrintProxyService : public CloudPrintProxyService {
ServiceProcessControl* GetServiceProcessControl() override {
return &process_control_;
}
+
MockServiceProcessControl* GetMockServiceProcessControl() {
return &process_control_;
}
+ MockCloudPrintProxy& GetMockCloudPrintProxy() { return mock_proxy_; }
+
void EnableForUser() {
EnableForUserWithRobot("123", "123@gmail.com",
MockServiceProcessControl::EnabledUserId(),
@@ -200,7 +194,13 @@ class TestCloudPrintProxyService : public CloudPrintProxyService {
}
private:
+ void HandleCloudPrintProxyRequest(mojo::ScopedMessagePipeHandle handle) {
+ mock_proxy_.AddBinding(
+ cloud_print::mojom::CloudPrintRequest(std::move(handle)));
+ }
+
MockServiceProcessControl process_control_;
+ MockCloudPrintProxy mock_proxy_;
};
class CloudPrintProxyPolicyTest : public ::testing::Test {
@@ -221,8 +221,7 @@ class CloudPrintProxyPolicyTest : public ::testing::Test {
TEST_F(CloudPrintProxyPolicyTest, VerifyExpectations) {
MockServiceProcessControl mock_control;
- mock_control.SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateNone, false);
+ mock_control.SetConnectSuccessMockExpectations(false);
EXPECT_FALSE(mock_control.IsConnected());
mock_control.Launch(base::Closure(), base::Closure());
@@ -236,8 +235,9 @@ TEST_F(CloudPrintProxyPolicyTest, VerifyExpectations) {
TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyDisabled) {
TestCloudPrintProxyService service(&profile_);
+ service.GetMockCloudPrintProxy().ReturnDisabledInfo();
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateDisabled, false);
+ false);
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -254,7 +254,8 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyEnabled) {
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateEnabled, false);
+ false);
+ service.GetMockCloudPrintProxy().ReturnEnabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -272,7 +273,8 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithPolicySetProxyDisabled) {
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateDisabled, false);
+ false);
+ service.GetMockCloudPrintProxy().ReturnDisabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -290,8 +292,8 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithPolicySetProxyEnabled) {
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateEnabled, false);
- service.GetMockServiceProcessControl()->SetWillBeDisabledExpectations();
+ false);
+ service.GetMockCloudPrintProxy().ReturnEnabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -303,13 +305,15 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithPolicySetProxyEnabled) {
service.Initialize();
EXPECT_EQ(std::string(), prefs->GetString(prefs::kCloudPrintEmail));
+ EXPECT_TRUE(service.GetMockCloudPrintProxy().has_been_disabled());
}
TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyDisabledThenSetPolicy) {
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateDisabled, false);
+ false);
+ service.GetMockCloudPrintProxy().ReturnDisabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -331,7 +335,8 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyEnabledThenSetPolicy) {
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateEnabled, false);
+ false);
+ service.GetMockCloudPrintProxy().ReturnEnabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -344,11 +349,11 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyEnabledThenSetPolicy) {
EXPECT_EQ(MockServiceProcessControl::EnabledUserId(),
prefs->GetString(prefs::kCloudPrintEmail));
- service.GetMockServiceProcessControl()->SetWillBeDisabledExpectations();
prefs->SetManagedPref(prefs::kCloudPrintProxyEnabled,
base::MakeUnique<base::Value>(false));
EXPECT_EQ(std::string(), prefs->GetString(prefs::kCloudPrintEmail));
+ EXPECT_TRUE(service.GetMockCloudPrintProxy().has_been_disabled());
}
TEST_F(CloudPrintProxyPolicyTest,
@@ -356,7 +361,8 @@ TEST_F(CloudPrintProxyPolicyTest,
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateDisabled, false);
+ false);
+ service.GetMockCloudPrintProxy().ReturnDisabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -377,8 +383,8 @@ TEST_F(CloudPrintProxyPolicyTest,
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateEnabled, false);
- service.GetMockServiceProcessControl()->SetWillBeDisabledExpectations();
+ false);
+ service.GetMockCloudPrintProxy().ReturnEnabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -392,13 +398,15 @@ TEST_F(CloudPrintProxyPolicyTest,
EXPECT_EQ(std::string(), prefs->GetString(prefs::kCloudPrintEmail));
prefs->RemoveManagedPref(prefs::kCloudPrintProxyEnabled);
EXPECT_EQ(std::string(), prefs->GetString(prefs::kCloudPrintEmail));
+ EXPECT_TRUE(service.GetMockCloudPrintProxy().has_been_disabled());
}
TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyDisabledThenEnable) {
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateDisabled, false);
+ false);
+ service.GetMockCloudPrintProxy().ReturnDisabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -409,11 +417,11 @@ TEST_F(CloudPrintProxyPolicyTest, StartWithNoPolicyProxyDisabledThenEnable) {
service.Initialize();
EXPECT_EQ(std::string(), prefs->GetString(prefs::kCloudPrintEmail));
- service.GetMockServiceProcessControl()->SetWillBeEnabledExpectations();
service.EnableForUser();
EXPECT_EQ(MockServiceProcessControl::EnabledUserId(),
prefs->GetString(prefs::kCloudPrintEmail));
+ EXPECT_TRUE(service.GetMockCloudPrintProxy().has_been_enabled());
}
TEST_F(CloudPrintProxyPolicyTest,
@@ -421,8 +429,8 @@ TEST_F(CloudPrintProxyPolicyTest,
TestCloudPrintProxyService service(&profile_);
service.GetMockServiceProcessControl()->SetConnectSuccessMockExpectations(
- MockServiceProcessControl::kServiceStateEnabled, false);
- service.GetMockServiceProcessControl()->SetWillBeDisabledExpectations();
+ false);
+ service.GetMockCloudPrintProxy().ReturnEnabledInfo();
sync_preferences::TestingPrefServiceSyncable* prefs =
profile_.GetTestingPrefService();
@@ -440,9 +448,9 @@ TEST_F(CloudPrintProxyPolicyTest,
prefs->RemoveManagedPref(prefs::kCloudPrintProxyEnabled);
EXPECT_EQ(std::string(), prefs->GetString(prefs::kCloudPrintEmail));
- service.GetMockServiceProcessControl()->SetWillBeEnabledExpectations();
service.EnableForUser();
EXPECT_EQ(MockServiceProcessControl::EnabledUserId(),
prefs->GetString(prefs::kCloudPrintEmail));
+ EXPECT_TRUE(service.GetMockCloudPrintProxy().has_been_enabled());
}
diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
index 16a19621723..520402b6c90 100644
--- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
+++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
@@ -49,7 +49,7 @@ net::NetworkTrafficAnnotationTag GetNetworkTrafficAnnotation(
destination: OTHER
}
policy {
- cookies_allowed: false
+ cookies_allowed: NO
setting: "User triggered requests cannot be disabled."
policy_exception_justification: "Not implemented, it's good to do so."
})");
@@ -68,7 +68,7 @@ net::NetworkTrafficAnnotationTag GetNetworkTrafficAnnotation(
destination: OTHER
}
policy {
- cookies_allowed: false
+ cookies_allowed: NO
setting: "User triggered requests cannot be disabled."
policy_exception_justification: "Not implemented, it's good to do so."
})");
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc b/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc
index 35c78df6432..af7873152bf 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc
@@ -743,7 +743,7 @@ std::unique_ptr<PrivetURLFetcher> PrivetHTTPClientImpl::CreateURLFetcher(
destination: OTHER
}
policy {
- cookies_allowed: false
+ cookies_allowed: NO
setting:
"Users can enable or disable background requests by 'Show "
"notifications when new printers are detected on the network' in "
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc
index 0b396f8cb00..1c7dad8e7e2 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc
@@ -11,7 +11,6 @@
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/scoped_task_environment.h"
@@ -356,7 +355,7 @@ class PrivetHTTPTest : public TestWithParam<const char*> {
callback.Cancel();
}
- void Stop() { base::MessageLoop::current()->QuitWhenIdle(); }
+ void Stop() { base::RunLoop::QuitCurrentWhenIdleDeprecated(); }
protected:
base::test::ScopedTaskEnvironment scoped_task_environment_;
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_url_fetcher_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_url_fetcher_unittest.cc
index ef541ca148d..016fb20da6b 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_url_fetcher_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_url_fetcher_unittest.cc
@@ -7,7 +7,6 @@
#include <memory>
#include "base/location.h"
-#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/scoped_task_environment.h"
@@ -118,7 +117,7 @@ class PrivetURLFetcherTest : public ::testing::Test {
callback.Cancel();
}
- void Stop() { base::MessageLoop::current()->QuitWhenIdle(); }
+ void Stop() { base::RunLoop::QuitCurrentWhenIdleDeprecated(); }
protected:
base::test::ScopedTaskEnvironment scoped_task_environment_;
diff --git a/chromium/chrome/browser/printing/pdf_to_emf_converter.cc b/chromium/chrome/browser/printing/pdf_to_emf_converter.cc
index 4356ae3dec8..b1b023e6018 100644
--- a/chromium/chrome/browser/printing/pdf_to_emf_converter.cc
+++ b/chromium/chrome/browser/printing/pdf_to_emf_converter.cc
@@ -18,6 +18,10 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
+#include "base/memory/ref_counted_delete_on_sequence.h"
+#include "base/sequenced_task_runner.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/common/chrome_utility_printing_messages.h"
#include "chrome/grit/generated_resources.h"
@@ -37,29 +41,60 @@ namespace {
class PdfConverterImpl;
+void CloseFileOnBlockingTaskRunner(base::File temp_file) {
+ base::ThreadRestrictions::AssertIOAllowed();
+ temp_file.Close();
+}
+
// Allows to delete temporary directory after all temporary files created inside
// are closed. Windows cannot delete directory with opened files. Directory is
// used to store PDF and metafiles. PDF should be gone by the time utility
// process exits. Metafiles should be gone when all LazyEmf destroyed.
class RefCountedTempDir
- : public base::RefCountedThreadSafe<RefCountedTempDir,
- BrowserThread::DeleteOnFileThread> {
+ : public base::RefCountedDeleteOnSequence<RefCountedTempDir> {
public:
- RefCountedTempDir() { ignore_result(temp_dir_.CreateUniqueTempDir()); }
+ RefCountedTempDir()
+ : base::RefCountedDeleteOnSequence<RefCountedTempDir>(
+ base::SequencedTaskRunnerHandle::Get()) {
+ ignore_result(temp_dir_.CreateUniqueTempDir());
+ }
+
bool IsValid() const { return temp_dir_.IsValid(); }
const base::FilePath& GetPath() const { return temp_dir_.GetPath(); }
private:
- friend struct BrowserThread::DeleteOnThread<BrowserThread::FILE>;
+ friend class base::RefCountedDeleteOnSequence<RefCountedTempDir>;
friend class base::DeleteHelper<RefCountedTempDir>;
+
~RefCountedTempDir() {}
base::ScopedTempDir temp_dir_;
DISALLOW_COPY_AND_ASSIGN(RefCountedTempDir);
};
-using ScopedTempFile =
- std::unique_ptr<base::File, BrowserThread::DeleteOnFileThread>;
+class TempFile {
+ public:
+ explicit TempFile(base::File file)
+ : file_(std::move(file)),
+ blocking_task_runner_(base::SequencedTaskRunnerHandle::Get()) {
+ base::ThreadRestrictions::AssertIOAllowed();
+ }
+ ~TempFile() {
+ blocking_task_runner_->PostTask(
+ FROM_HERE, base::BindOnce(&CloseFileOnBlockingTaskRunner,
+ base::Passed(std::move(file_))));
+ }
+
+ base::File& file() { return file_; }
+
+ private:
+ base::File file_;
+ const scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
+
+ DISALLOW_COPY_AND_ASSIGN(TempFile);
+};
+
+using ScopedTempFile = std::unique_ptr<TempFile>;
// Wrapper for Emf to keep only file handle in memory, and load actual data only
// on playback. Emf::InitFromFile() can play metafile directly from disk, but it
@@ -98,7 +133,7 @@ class PostScriptMetaFile : public LazyEmf {
: LazyEmf(temp_dir, std::move(file)) {}
~PostScriptMetaFile() override;
- protected:
+ private:
// MetafilePlayer:
bool SafePlayback(HDC hdc) const override;
@@ -106,10 +141,10 @@ class PostScriptMetaFile : public LazyEmf {
};
// Class for converting PDF to another format for printing (Emf, Postscript).
-// Class uses 3 threads: UI, IO and FILE.
+// Class uses UI thread, IO thread and |blocking_task_runner_|.
// Internal workflow is following:
// 1. Create instance on the UI thread. (files_, settings_,)
-// 2. Create pdf file on the FILE thread.
+// 2. Create pdf file on |blocking_task_runner_|.
// 3. Start utility process and start conversion on the IO thread.
// 4. Utility process returns page count.
// 5. For each page:
@@ -141,7 +176,7 @@ class PdfConverterUtilityProcessHostClient
// sync message replies.
bool Send(IPC::Message* msg);
- protected:
+ private:
class GetPageCallbackData {
public:
GetPageCallbackData(int page_number, PdfConverter::GetPageCallback callback)
@@ -178,16 +213,13 @@ class PdfConverterUtilityProcessHostClient
// Helper functions: must be overridden by subclasses
// Set the process name
- virtual base::string16 GetName() const;
+ base::string16 GetName() const;
// Create a metafileplayer subclass file from a temporary file.
- virtual std::unique_ptr<MetafilePlayer> GetFileFromTemp(
- std::unique_ptr<base::File, content::BrowserThread::DeleteOnFileThread>
- temp_file);
+ std::unique_ptr<MetafilePlayer> GetFileFromTemp(ScopedTempFile temp_file);
// Send the messages to Start, GetPage, and Stop.
- virtual void SendStartMessage(IPC::PlatformFileForTransit transit);
- virtual void SendGetPageMessage(int page_number,
- IPC::PlatformFileForTransit transit);
- virtual void SendStopMessage();
+ void SendStartMessage(IPC::PlatformFileForTransit transit);
+ void SendGetPageMessage(int page_number, IPC::PlatformFileForTransit transit);
+ void SendStopMessage();
// Message handlers:
void OnPageCount(int page_count);
@@ -220,13 +252,14 @@ class PdfConverterUtilityProcessHostClient
using GetPageCallbacks = std::queue<GetPageCallbackData>;
GetPageCallbacks get_page_callbacks_;
+ const scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
+
DISALLOW_COPY_AND_ASSIGN(PdfConverterUtilityProcessHostClient);
};
std::unique_ptr<MetafilePlayer>
PdfConverterUtilityProcessHostClient::GetFileFromTemp(
- std::unique_ptr<base::File, content::BrowserThread::DeleteOnFileThread>
- temp_file) {
+ ScopedTempFile temp_file) {
if (settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2 ||
settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3 ||
settings_.mode == PdfRenderSettings::Mode::TEXTONLY) {
@@ -271,7 +304,7 @@ class PdfConverterImpl : public PdfConverter {
ScopedTempFile CreateTempFile(scoped_refptr<RefCountedTempDir>* temp_dir) {
if (!temp_dir->get())
- *temp_dir = new RefCountedTempDir();
+ *temp_dir = base::MakeRefCounted<RefCountedTempDir>();
ScopedTempFile file;
if (!(*temp_dir)->IsValid())
return file;
@@ -281,13 +314,11 @@ ScopedTempFile CreateTempFile(scoped_refptr<RefCountedTempDir>* temp_dir) {
<< (*temp_dir)->GetPath().value();
return file;
}
- file.reset(new base::File(path,
- base::File::FLAG_CREATE_ALWAYS |
- base::File::FLAG_WRITE |
- base::File::FLAG_READ |
- base::File::FLAG_DELETE_ON_CLOSE |
- base::File::FLAG_TEMPORARY));
- if (!file->IsValid()) {
+ file = base::MakeUnique<TempFile>(base::File(
+ path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE |
+ base::File::FLAG_READ | base::File::FLAG_DELETE_ON_CLOSE |
+ base::File::FLAG_TEMPORARY));
+ if (!file->file().IsValid()) {
PLOG(ERROR) << "Failed to create " << path.value();
file.reset();
}
@@ -297,16 +328,14 @@ ScopedTempFile CreateTempFile(scoped_refptr<RefCountedTempDir>* temp_dir) {
ScopedTempFile CreateTempPdfFile(
const scoped_refptr<base::RefCountedMemory>& data,
scoped_refptr<RefCountedTempDir>* temp_dir) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
-
ScopedTempFile pdf_file = CreateTempFile(temp_dir);
- if (!pdf_file ||
- static_cast<int>(data->size()) !=
- pdf_file->WriteAtCurrentPos(data->front_as<char>(), data->size())) {
+ if (!pdf_file || static_cast<int>(data->size()) !=
+ pdf_file->file().WriteAtCurrentPos(
+ data->front_as<char>(), data->size())) {
pdf_file.reset();
return pdf_file;
}
- pdf_file->Seek(base::File::FROM_BEGIN, 0);
+ pdf_file->file().Seek(base::File::FROM_BEGIN, 0);
return pdf_file;
}
@@ -337,12 +366,12 @@ void LazyEmf::Close() const {
}
bool LazyEmf::LoadEmf(Emf* emf) const {
- file_->Seek(base::File::FROM_BEGIN, 0);
- int64_t size = file_->GetLength();
+ file_->file().Seek(base::File::FROM_BEGIN, 0);
+ int64_t size = file_->file().GetLength();
if (size <= 0)
return false;
std::vector<char> data(size);
- if (file_->ReadAtCurrentPos(data.data(), data.size()) != size)
+ if (file_->file().ReadAtCurrentPos(data.data(), data.size()) != size)
return false;
return emf->InitFromData(data.data(), data.size());
}
@@ -384,7 +413,11 @@ bool PostScriptMetaFile::SafePlayback(HDC hdc) const {
PdfConverterUtilityProcessHostClient::PdfConverterUtilityProcessHostClient(
base::WeakPtr<PdfConverterImpl> converter,
const PdfRenderSettings& settings)
- : converter_(converter), settings_(settings) {}
+ : converter_(converter),
+ settings_(settings),
+ blocking_task_runner_(base::CreateSequencedTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
+ base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) {}
PdfConverterUtilityProcessHostClient::~PdfConverterUtilityProcessHostClient() {}
@@ -410,8 +443,8 @@ void PdfConverterUtilityProcessHostClient::Start(
->AsWeakPtr();
utility_process_host_->SetName(GetName());
- BrowserThread::PostTaskAndReplyWithResult(
- BrowserThread::FILE, FROM_HERE,
+ base::PostTaskAndReplyWithResult(
+ blocking_task_runner_.get(), FROM_HERE,
base::Bind(&CreateTempPdfFile, data, &temp_dir_),
base::Bind(&PdfConverterUtilityProcessHostClient::OnTempPdfReady, this));
}
@@ -422,7 +455,7 @@ void PdfConverterUtilityProcessHostClient::OnTempPdfReady(ScopedTempFile pdf) {
return OnFailed();
// Should reply with OnPageCount().
SendStartMessage(
- IPC::GetPlatformFileForTransit(pdf->GetPlatformFile(), false));
+ IPC::GetPlatformFileForTransit(pdf->file().GetPlatformFile(), false));
}
void PdfConverterUtilityProcessHostClient::OnPageCount(int page_count) {
@@ -452,8 +485,9 @@ void PdfConverterUtilityProcessHostClient::GetPage(
if (!utility_process_host_)
return OnFailed();
- BrowserThread::PostTaskAndReplyWithResult(
- BrowserThread::FILE, FROM_HERE, base::Bind(&CreateTempFile, &temp_dir_),
+ base::PostTaskAndReplyWithResult(
+ blocking_task_runner_.get(), FROM_HERE,
+ base::Bind(&CreateTempFile, &temp_dir_),
base::Bind(&PdfConverterUtilityProcessHostClient::OnTempFileReady, this,
&get_page_callbacks_.back()));
}
@@ -464,8 +498,8 @@ void PdfConverterUtilityProcessHostClient::OnTempFileReady(
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!utility_process_host_ || !temp_file)
return OnFailed();
- IPC::PlatformFileForTransit transit =
- IPC::GetPlatformFileForTransit(temp_file->GetPlatformFile(), false);
+ IPC::PlatformFileForTransit transit = IPC::GetPlatformFileForTransit(
+ temp_file->file().GetPlatformFile(), false);
callback_data->set_file(std::move(temp_file));
// Should reply with OnPageDone().
SendGetPageMessage(callback_data->page_number(), transit);
diff --git a/chromium/chrome/browser/printing/print_browsertest.cc b/chromium/chrome/browser/printing/print_browsertest.cc
index 33f98dafd84..036681e9063 100644
--- a/chromium/chrome/browser/printing/print_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_browsertest.cc
@@ -3,6 +3,7 @@
// found in the LICENSE file.
#include "base/auto_reset.h"
+#include "base/run_loop.h"
#include "chrome/browser/printing/print_view_manager_common.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
diff --git a/chromium/chrome/browser/printing/print_dialog_cloud.cc b/chromium/chrome/browser/printing/print_dialog_cloud.cc
index c01239d725d..ff1c8c78502 100644
--- a/chromium/chrome/browser/printing/print_dialog_cloud.cc
+++ b/chromium/chrome/browser/printing/print_dialog_cloud.cc
@@ -71,7 +71,7 @@ void CreateCloudPrintSigninTab(Browser* browser,
bool add_account,
const base::Closure& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (switches::IsAccountConsistencyMirrorEnabled() &&
+ if (signin::IsAccountConsistencyMirrorEnabled() &&
!browser->profile()->IsOffTheRecord()) {
browser->window()->ShowAvatarBubbleFromAvatarButton(
add_account ? BrowserWindow::AVATAR_BUBBLE_MODE_ADD_ACCOUNT
diff --git a/chromium/chrome/browser/printing/print_job.cc b/chromium/chrome/browser/printing/print_job.cc
index d95355508f6..4fc7d84e20c 100644
--- a/chromium/chrome/browser/printing/print_job.cc
+++ b/chromium/chrome/browser/printing/print_job.cc
@@ -477,7 +477,7 @@ void PrintJob::HoldUntilStopIsCalled() {
}
void PrintJob::Quit() {
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
// Takes settings_ ownership and will be deleted in the receiving thread.
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
index 780928be534..ba6ea65f825 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
@@ -241,11 +241,6 @@ void PrintPreviewDialogController::ForEachPreviewDialog(
}
// static
-bool PrintPreviewDialogController::IsPrintPreviewDialog(WebContents* contents) {
- return IsPrintPreviewURL(contents->GetURL());
-}
-
-// static
bool PrintPreviewDialogController::IsPrintPreviewURL(const GURL& url) {
return (url.SchemeIs(content::kChromeUIScheme) &&
url.host_piece() == chrome::kChromeUIPrintHost);
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller.h b/chromium/chrome/browser/printing/print_preview_dialog_controller.h
index 85e9880a444..b5d88214d38 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller.h
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller.h
@@ -42,6 +42,9 @@ class PrintPreviewDialogController
// Call this instead of GetOrCreatePreviewDialog().
static void PrintPreview(content::WebContents* initiator);
+ // Returns true if |url| is a print preview url.
+ static bool IsPrintPreviewURL(const GURL& url);
+
// Get/Create the print preview dialog for |initiator|.
// Exposed for unit tests.
content::WebContents* GetOrCreatePreviewDialog(
@@ -66,12 +69,6 @@ class PrintPreviewDialogController
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
- // Returns true if |contents| is a print preview dialog.
- static bool IsPrintPreviewDialog(content::WebContents* contents);
-
- // Returns true if |url| is a print preview url.
- static bool IsPrintPreviewURL(const GURL& url);
-
// Erase the initiator info associated with |preview_dialog|.
void EraseInitiatorInfo(content::WebContents* preview_dialog);
diff --git a/chromium/chrome/browser/printing/print_view_manager.cc b/chromium/chrome/browser/printing/print_view_manager.cc
index fa54bcc082d..9b81375bc9f 100644
--- a/chromium/chrome/browser/printing/print_view_manager.cc
+++ b/chromium/chrome/browser/printing/print_view_manager.cc
@@ -59,7 +59,7 @@ PrintViewManager::PrintViewManager(content::WebContents* web_contents)
print_preview_state_(NOT_PREVIEWING),
print_preview_rfh_(nullptr),
scripted_print_preview_rph_(nullptr) {
- if (PrintPreviewDialogController::IsPrintPreviewDialog(web_contents)) {
+ if (PrintPreviewDialogController::IsPrintPreviewURL(web_contents->GetURL())) {
EnableInternalPDFPluginForContents(
web_contents->GetRenderProcessHost()->GetID(),
web_contents->GetMainFrame()->GetRoutingID());
@@ -146,7 +146,8 @@ void PrintViewManager::PrintPreviewDone() {
void PrintViewManager::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
- if (PrintPreviewDialogController::IsPrintPreviewDialog(web_contents())) {
+ if (PrintPreviewDialogController::IsPrintPreviewURL(
+ web_contents()->GetURL())) {
EnableInternalPDFPluginForContents(render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID());
}
diff --git a/chromium/chrome/browser/printing/print_view_manager_base.cc b/chromium/chrome/browser/printing/print_view_manager_base.cc
index 9d81a019eac..88cecc9cbd2 100644
--- a/chromium/chrome/browser/printing/print_view_manager_base.cc
+++ b/chromium/chrome/browser/printing/print_view_manager_base.cc
@@ -171,7 +171,7 @@ void PrintViewManagerBase::OnDidPrintPage(
}
std::unique_ptr<PdfMetafileSkia> metafile(
- new PdfMetafileSkia(PDF_SKIA_DOCUMENT_TYPE));
+ new PdfMetafileSkia(SkiaDocumentType::PDF));
if (metafile_must_be_valid) {
if (!metafile->InitFromData(shared_buf->memory(), params.data_size)) {
NOTREACHED() << "Invalid metafile header";
@@ -274,6 +274,19 @@ void PrintViewManagerBase::RenderFrameDeleted(
}
}
+#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+void PrintViewManagerBase::SystemDialogCancelled() {
+ // System dialog was cancelled. Clean up the print job and notify the
+ // BackgroundPrintingManager.
+ ReleasePrinterQuery();
+ TerminatePrintJob(true);
+ content::NotificationService::current()->Notify(
+ chrome::NOTIFICATION_PRINT_JOB_RELEASED,
+ content::Source<content::WebContents>(web_contents()),
+ content::NotificationService::NoDetails());
+}
+#endif
+
bool PrintViewManagerBase::OnMessageReceived(
const IPC::Message& message,
content::RenderFrameHost* render_frame_host) {
@@ -367,7 +380,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
// to actually spool the pages, only to have the renderer generate them. Run
// a message loop until we get our signal that the print job is satisfied.
// PrintJob will send a ALL_PAGES_REQUESTED after having received all the
- // pages it needs. MessageLoop::current()->QuitWhenIdle() will be called as
+ // pages it needs. RunLoop::QuitCurrentWhenIdleDeprecated() will be called as
// soon as print_job_->document()->IsComplete() is true on either
// ALL_PAGES_REQUESTED or in DidPrintPage(). The check is done in
// ShouldQuitFromInnerMessageLoop().
@@ -388,7 +401,7 @@ void PrintViewManagerBase::ShouldQuitFromInnerMessageLoop() {
inside_inner_message_loop_) {
// We are in a message loop created by RenderAllMissingPagesNow. Quit from
// it.
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
inside_inner_message_loop_ = false;
}
}
@@ -495,9 +508,10 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
// memory-bound.
static const int kPrinterSettingsTimeout = 60000;
base::OneShotTimer quit_timer;
- quit_timer.Start(
- FROM_HERE, TimeDelta::FromMilliseconds(kPrinterSettingsTimeout),
- base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle);
+ base::RunLoop run_loop;
+ quit_timer.Start(FROM_HERE,
+ TimeDelta::FromMilliseconds(kPrinterSettingsTimeout),
+ run_loop.QuitWhenIdleClosure());
inside_inner_message_loop_ = true;
@@ -505,7 +519,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
{
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
- base::RunLoop().Run();
+ run_loop.Run();
}
bool success = true;
diff --git a/chromium/chrome/browser/printing/print_view_manager_base.h b/chromium/chrome/browser/printing/print_view_manager_base.h
index c54ba76e5d9..ee19939c134 100644
--- a/chromium/chrome/browser/printing/print_view_manager_base.h
+++ b/chromium/chrome/browser/printing/print_view_manager_base.h
@@ -48,6 +48,12 @@ class PrintViewManagerBase : public content::NotificationObserver,
// Whether printing is enabled or not.
void UpdatePrintingEnabled();
+// Notifies the print view manager that the system dialog has been cancelled
+// after being opened from Print Preview.
+#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+ void SystemDialogCancelled();
+#endif
+
// PrintedPagesSource implementation.
base::string16 RenderSourceName() override;
diff --git a/chromium/chrome/browser/printing/printing_init.cc b/chromium/chrome/browser/printing/printing_init.cc
new file mode 100644
index 00000000000..ceedd62df35
--- /dev/null
+++ b/chromium/chrome/browser/printing/printing_init.cc
@@ -0,0 +1,28 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/printing/printing_init.h"
+
+#include "content/public/browser/web_contents.h"
+#include "printing/features/features.h"
+
+#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
+#include "chrome/browser/printing/print_preview_message_handler.h"
+#include "chrome/browser/printing/print_view_manager.h"
+#else
+#include "chrome/browser/printing/print_view_manager_basic.h"
+#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
+
+namespace printing {
+
+void InitializePrinting(content::WebContents* web_contents) {
+#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
+ printing::PrintViewManager::CreateForWebContents(web_contents);
+ printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
+#else
+ printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
+#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
+}
+
+} // namespace printing
diff --git a/chromium/chrome/browser/printing/printing_init.h b/chromium/chrome/browser/printing/printing_init.h
new file mode 100644
index 00000000000..0660585faee
--- /dev/null
+++ b/chromium/chrome/browser/printing/printing_init.h
@@ -0,0 +1,19 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_PRINTING_PRINTING_INIT_H__
+#define CHROME_BROWSER_PRINTING_PRINTING_INIT_H__
+
+namespace content {
+class WebContents;
+}
+
+namespace printing {
+
+// Initialize printing related classes for web contents.
+void InitializePrinting(content::WebContents* web_contents);
+
+} // namespace printing
+
+#endif // CHROME_BROWSER_PRINTING_PRINTING_INIT_H__
diff --git a/chromium/chrome/browser/printing/printing_message_filter.cc b/chromium/chrome/browser/printing/printing_message_filter.cc
index 8c9c449b8c4..ad72c5fe12d 100644
--- a/chromium/chrome/browser/printing/printing_message_filter.cc
+++ b/chromium/chrome/browser/printing/printing_message_filter.cc
@@ -13,6 +13,7 @@
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/print_job_manager.h"
+#include "chrome/browser/printing/print_view_manager.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
@@ -60,7 +61,7 @@ class ShutdownNotifierFactory
DISALLOW_COPY_AND_ASSIGN(ShutdownNotifierFactory);
};
-#if defined(OS_ANDROID)
+#if defined(OS_ANDROID) || (defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW))
content::WebContents* GetWebContentsForRenderFrame(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -69,6 +70,7 @@ content::WebContents* GetWebContentsForRenderFrame(int render_process_id,
return frame ? content::WebContents::FromRenderFrameHost(frame) : nullptr;
}
+#if defined(OS_ANDROID)
PrintViewManagerBasic* GetPrintManager(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -77,7 +79,18 @@ PrintViewManagerBasic* GetPrintManager(int render_process_id,
return web_contents ? PrintViewManagerBasic::FromWebContents(web_contents)
: nullptr;
}
+#else // defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+PrintViewManager* GetPrintViewManager(int render_process_id,
+ int render_frame_id) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ content::WebContents* web_contents =
+ GetWebContentsForRenderFrame(render_process_id, render_frame_id);
+ return web_contents ? PrintViewManager::FromWebContents(web_contents)
+ : nullptr;
+}
#endif
+#endif // defined(OS_ANDROID) || (defined(OS_WIN) &&
+ // BUILDFLAG(ENABLE_PRINT_PREVIEW))
} // namespace
@@ -309,6 +322,14 @@ void PrintingMessageFilter::OnUpdatePrintSettings(
printer_query, reply_msg));
}
+#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+void PrintingMessageFilter::NotifySystemDialogCancelled(int routing_id) {
+ PrintViewManager* manager =
+ GetPrintViewManager(render_process_id_, routing_id);
+ manager->SystemDialogCancelled();
+}
+#endif
+
void PrintingMessageFilter::OnUpdatePrintSettingsReply(
scoped_refptr<PrinterQuery> printer_query,
IPC::Message* reply_msg) {
@@ -323,6 +344,15 @@ void PrintingMessageFilter::OnUpdatePrintSettingsReply(
}
bool canceled = printer_query.get() &&
(printer_query->last_status() == PrintingContext::CANCEL);
+#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
+ if (canceled) {
+ int routing_id = reply_msg->routing_id();
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::Bind(&PrintingMessageFilter::NotifySystemDialogCancelled, this,
+ routing_id));
+ }
+#endif
PrintHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params,
canceled);
Send(reply_msg);
diff --git a/chromium/chrome/browser/printing/printing_message_filter.h b/chromium/chrome/browser/printing/printing_message_filter.h
index 3402f25e8ab..3b85fffa7a5 100644
--- a/chromium/chrome/browser/printing/printing_message_filter.h
+++ b/chromium/chrome/browser/printing/printing_message_filter.h
@@ -96,6 +96,9 @@ class PrintingMessageFilter : public content::BrowserMessageFilter {
void OnCheckForCancel(int32_t preview_ui_id,
int preview_request_id,
bool* cancel);
+#if defined(OS_WIN)
+ void NotifySystemDialogCancelled(int routing_id);
+#endif
#endif
std::unique_ptr<KeyedServiceShutdownNotifier::Subscription>
diff --git a/chromium/chrome/browser/printing/pwg_raster_converter.cc b/chromium/chrome/browser/printing/pwg_raster_converter.cc
index 5f4509322db..10843be3c2c 100644
--- a/chromium/chrome/browser/printing/pwg_raster_converter.cc
+++ b/chromium/chrome/browser/printing/pwg_raster_converter.cc
@@ -17,7 +17,9 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
-#include "base/single_thread_task_runner.h"
+#include "base/sequenced_task_runner.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/common/chrome_utility_printing_messages.h"
#include "chrome/grit/generated_resources.h"
@@ -44,9 +46,7 @@ class FileHandlers {
public:
FileHandlers() {}
- ~FileHandlers() {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
- }
+ ~FileHandlers() { base::ThreadRestrictions::AssertIOAllowed(); }
void Init(base::RefCountedMemory* data);
bool IsValid();
@@ -82,7 +82,7 @@ class FileHandlers {
};
void FileHandlers::Init(base::RefCountedMemory* data) {
- DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+ base::ThreadRestrictions::AssertIOAllowed();
if (!temp_dir_.CreateUniqueTempDir())
return;
@@ -104,15 +104,15 @@ bool FileHandlers::IsValid() {
}
// Converts PDF into PWG raster.
-// Class uses 3 threads: UI, IO and FILE.
+// Class uses UI thread, IO thread and |blocking_task_runner_|.
// Internal workflow is following:
// 1. Create instance on the UI thread. (files_, settings_,)
-// 2. Create file on the FILE thread.
+// 2. Create file on |blocking_task_runner_|.
// 3. Start utility process and start conversion on the IO thread.
// 4. Run result callback on the UI thread.
// 5. Instance is destroyed from any thread that has the last reference.
-// 6. FileHandlers destroyed on the FILE thread.
-// This step posts |FileHandlers| to be destroyed on the FILE thread.
+// 6. FileHandlers destroyed on |blocking_task_runner_|.
+// This step posts |FileHandlers| to be destroyed on |blocking_task_runner_|.
// All these steps work sequentially, so no data should be accessed
// simultaneously by several threads.
class PwgUtilityProcessHostClient : public content::UtilityProcessHostClient {
@@ -142,10 +142,11 @@ class PwgUtilityProcessHostClient : public content::UtilityProcessHostClient {
void RunCallbackOnUIThread(bool success);
void OnFilesReadyOnUIThread();
- std::unique_ptr<FileHandlers, BrowserThread::DeleteOnFileThread> files_;
PdfRenderSettings settings_;
PwgRasterSettings bitmap_settings_;
PWGRasterConverter::ResultCallback callback_;
+ const scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
+ std::unique_ptr<FileHandlers, base::OnTaskRunnerDeleter> files_;
DISALLOW_COPY_AND_ASSIGN(PwgUtilityProcessHostClient);
};
@@ -153,7 +154,12 @@ class PwgUtilityProcessHostClient : public content::UtilityProcessHostClient {
PwgUtilityProcessHostClient::PwgUtilityProcessHostClient(
const PdfRenderSettings& settings,
const PwgRasterSettings& bitmap_settings)
- : settings_(settings), bitmap_settings_(bitmap_settings) {}
+ : settings_(settings),
+ bitmap_settings_(bitmap_settings),
+ blocking_task_runner_(base::CreateSequencedTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
+ base::TaskShutdownBehavior::BLOCK_SHUTDOWN})),
+ files_(nullptr, base::OnTaskRunnerDeleter(blocking_task_runner_)) {}
PwgUtilityProcessHostClient::~PwgUtilityProcessHostClient() {
}
@@ -167,8 +173,8 @@ void PwgUtilityProcessHostClient::Convert(
CHECK(!files_);
files_.reset(new FileHandlers());
- BrowserThread::PostTaskAndReply(
- BrowserThread::FILE, FROM_HERE,
+ blocking_task_runner_->PostTaskAndReply(
+ FROM_HERE,
base::BindOnce(&FileHandlers::Init, base::Unretained(files_.get()),
base::RetainedRef(data)),
base::BindOnce(&PwgUtilityProcessHostClient::OnFilesReadyOnUIThread,
@@ -276,8 +282,8 @@ void PWGRasterConverterImpl::Start(base::RefCountedMemory* data,
// Rebind cancelable callback to avoid calling callback if
// PWGRasterConverterImpl is destroyed.
callback_.Reset(callback);
- utility_client_ =
- new PwgUtilityProcessHostClient(conversion_settings, bitmap_settings);
+ utility_client_ = base::MakeRefCounted<PwgUtilityProcessHostClient>(
+ conversion_settings, bitmap_settings);
utility_client_->Convert(data, callback_.callback());
}
diff --git a/chromium/chrome/browser/profiling_host/BUILD.gn b/chromium/chrome/browser/profiling_host/BUILD.gn
index 8d5fa33b986..588301f8e21 100644
--- a/chromium/chrome/browser/profiling_host/BUILD.gn
+++ b/chromium/chrome/browser/profiling_host/BUILD.gn
@@ -4,21 +4,18 @@
import("//chrome/common/features.gni")
-if (enable_oop_heap_profiling) {
- static_library("profiling_host") {
- sources = [
- "profiling_process_host.cc",
- "profiling_process_host.h",
- ]
+static_library("profiling_host") {
+ sources = [
+ "chrome_browser_main_extra_parts_profiling.cc",
+ "chrome_browser_main_extra_parts_profiling.h",
+ "profiling_process_host.cc",
+ "profiling_process_host.h",
+ ]
- deps = [
- "//base",
- "//chrome/common",
- "//content/public/common",
- ]
- }
-} else {
- # Dummy group so this target can be unconditionally depended on.
- group("profiling_host") {
- }
+ deps = [
+ "//base",
+ "//base/allocator:features",
+ "//chrome/common",
+ "//content/public/common",
+ ]
}
diff --git a/chromium/chrome/browser/resources/BUILD.gn b/chromium/chrome/browser/resources/BUILD.gn
index 1360570acae..39e356bfb69 100644
--- a/chromium/chrome/browser/resources/BUILD.gn
+++ b/chromium/chrome/browser/resources/BUILD.gn
@@ -37,18 +37,6 @@ grit("password_manager_internals_resources") {
output_dir = "$root_gen_dir/chrome"
}
-grit("policy_resources") {
- source = "md_policy/policy_resources.grd"
- defines = chrome_grit_defines
- outputs = [
- "grit/policy_resources.h",
- "grit/policy_resources_map.cc",
- "grit/policy_resources_map.h",
- "policy_resources.pak",
- ]
- output_dir = "$root_gen_dir/chrome"
-}
-
grit("quota_internals_resources") {
source = "quota_internals_resources.grd"
defines = chrome_grit_defines
@@ -135,18 +123,6 @@ if (!is_android) {
}
}
-if (is_chromeos) {
- grit("options_resources") {
- source = "options_resources.grd"
- defines = chrome_grit_defines
- outputs = [
- "grit/options_resources.h",
- "options_resources.pak",
- ]
- output_dir = "$root_gen_dir/chrome"
- }
-}
-
if (enable_extensions) {
grit("sync_file_system_internals_resources") {
source = "sync_file_system_internals_resources.grd"
diff --git a/chromium/chrome/browser/resources/OWNERS b/chromium/chrome/browser/resources/OWNERS
index f005d384bf2..7dc0fd026a2 100644
--- a/chromium/chrome/browser/resources/OWNERS
+++ b/chromium/chrome/browser/resources/OWNERS
@@ -1,7 +1,6 @@
file://ui/webui/PLATFORM_OWNERS
per-file component_extension_resources.grd=dgozman@chromium.org
-per-file options_resources.grd=file://chrome/browser/resources/options/OWNERS
per-file profile_signin_confirmation*=achuith@chromium.org
per-file snippets_internals*=file://components/ntp_snippets/OWNERS
per-file sync_file_system_internals_resources.*=tzik@chromium.org
diff --git a/chromium/chrome/browser/resources/app_list/OWNERS b/chromium/chrome/browser/resources/app_list/OWNERS
index 16d36d99416..ed54f09c40c 100644
--- a/chromium/chrome/browser/resources/app_list/OWNERS
+++ b/chromium/chrome/browser/resources/app_list/OWNERS
@@ -1,2 +1,2 @@
calamity@chromium.org
-mgiuca@chromium.org
+khmel@chromium.org
diff --git a/chromium/chrome/browser/resources/app_list/start_page.css b/chromium/chrome/browser/resources/app_list/start_page.css
index 8f6edd09c0d..3efaef1955a 100644
--- a/chromium/chrome/browser/resources/app_list/start_page.css
+++ b/chromium/chrome/browser/resources/app_list/start_page.css
@@ -4,11 +4,11 @@
html,
body {
- -webkit-user-select: none;
height: 100%;
margin: 0;
overflow: hidden;
padding: 0;
+ user-select: none;
width: 100%;
}
diff --git a/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd b/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
index 6b81e38dbe5..7a76f8bdf2d 100644
--- a/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
+++ b/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
@@ -770,11 +770,17 @@
Row <ph name="rowIndex">$1</ph> of <ph name="rowTotal">$2</ph>, Column <ph name="colIndex">$3</ph> of <ph name="colTotal">$4</ph>
</message>
<message desc="summarizes a table." name="IDS_CHROMEVOX_TABLE_SUMMARY">
- Table $1, $2 by $3
+ Table <ph name="tableName">$1</ph>, <ph name="tableRows">$2</ph> by <ph name="tableCols">$3</ph>
+ </message>
+ <message desc="summarizes a html data table for braille. If the description for the table (and not the substitutions after the initial description) is longer than 5 characters, try to abbreviate it according to local conventions, and when doing so, if reasonable, use all lowercase and avoid punctuation to keep the number of characters as low as possible." name="IDS_CHROMEVOX_TABLE_SUMMARY_BRL">
+ tbl <ph name="tableName">$1</ph> <ph name="tableRows">$2</ph>x<ph name="tableCols">$3</ph>
</message>
<message desc="summarizes a table cell." name="IDS_CHROMEVOX_CELL_SUMMARY">
row $1 column $2
</message>
+ <message desc="summarizes a table cell for braille; for example, r1c2 means row 1, column 2. Try to localize the 'r' and 'c' to the first letter of something that would be recognizable." name="IDS_CHROMEVOX_CELL_SUMMARY_BRL">
+ r$1c$2
+ </message>
<message desc="Spoken if the user attempts to jump to the next checkbox when none exists." name="IDS_CHROMEVOX_NO_NEXT_CHECKBOX">
No next checkbox.
</message>
diff --git a/chromium/chrome/browser/resources/chromeos/compiled_resources2.gyp b/chromium/chrome/browser/resources/chromeos/compiled_resources2.gyp
index c00877f1a61..e166fcf476d 100644
--- a/chromium/chrome/browser/resources/chromeos/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/chromeos/compiled_resources2.gyp
@@ -4,193 +4,28 @@
{
'targets': [
{
- 'target_name': 'bluetooth_pair_device',
- 'variables': {
- 'extra_inputs': [
- '<!@(python <(CLOSURE_DIR)/build/get_includes.py ../options/options_bundle.js)',
- ],
- 'script_args': ['--custom_sources', '--custom_includes'],
- 'source_files': [
- '<(DEPTH)/third_party/jstemplate/util.js',
- '<(DEPTH)/third_party/jstemplate/jsevalcontext.js',
- '<(DEPTH)/third_party/jstemplate/jstemplate.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js',
- '<(DEPTH)/ui/webui/resources/js/action_link.js',
- '<(DEPTH)/ui/webui/resources/js/cr.js',
- '<(DEPTH)/ui/webui/resources/js/cr/event_target.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/array_data_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/autocomplete_list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/command.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/controlled_indicator.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_outline_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_without_ink.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_controller.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_single_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/grid.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/overlay.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/position_util.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/node_utils.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/repeating_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/touch_handler.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/tree.js',
- '<(DEPTH)/ui/webui/resources/js/event_tracker.js',
- '<(DEPTH)/ui/webui/resources/js/icon.js',
- '<(DEPTH)/ui/webui/resources/js/load_time_data.js',
- '<(DEPTH)/ui/webui/resources/js/parse_html_subset.js',
- '<(DEPTH)/ui/webui/resources/js/promise_resolver.js',
- '<(DEPTH)/ui/webui/resources/js/util.js',
- '../chromeos/keyboard/keyboard_utils.js',
- '<(DEPTH)/ui/webui/resources/js/i18n_behavior.js',
- '<(DEPTH)/ui/webui/resources/js/web_ui_listener_behavior.js',
- '../settings/page_visibility.js',
- '../settings/route.js',
- '../settings/people_page/easy_unlock_browser_proxy.js',
- '../settings/people_page/fingerprint_browser_proxy.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selection-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-multi-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menu-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menubar-behavior-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector_grid.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.js',
- '../settings/people_page/lock_screen_constants.js',
- '<(DEPTH)/third_party/closure_compiler/externs/quick_unlock_private.js',
- '../settings/people_page/lock_state_behavior.js',
- '../settings/people_page/password_prompt_dialog.js',
- '<(DEPTH)/ui/webui/resources/js/assert.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-meta/iron-meta-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-icon/iron-icon-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-control-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-ripple/paper-ripple-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-inky-focus-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-icon-button/paper-icon-button-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js',
- '../settings/people_page/lock_screen.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/management.js',
- '<(DEPTH)/third_party/closure_compiler/externs/metrics_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/networking_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/chrome_send.js',
- '<(DEPTH)/third_party/closure_compiler/externs/web_animations.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_network_icon_externs.js',
- '../options/options_bundle.js',
- # Note: ^ this is just a copy of
- # ../options/compiled_resources2.gyp:options_bundle#source_files. Most
- # of this code is deprecated, but please keep in sync if you really
- # need to change.
- 'bluetooth_pair_device.js',
- ],
- },
+ 'target_name': 'bluetooth_dialog_host',
+ 'dependencies': [
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
+ '<(EXTERNS_GYP):bluetooth',
+ '<(EXTERNS_GYP):bluetooth_private',
+ '<(INTERFACES_GYP):bluetooth_interface',
+ '<(INTERFACES_GYP):bluetooth_private_interface',
+ ],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
- 'target_name': 'certificate_manager_dialog',
- 'variables': {
- 'extra_inputs': [
- '<!@(python <(CLOSURE_DIR)/build/get_includes.py ../options/options_bundle.js)',
- ],
- 'script_args': ['--custom_sources', '--custom_includes'],
- 'source_files': [
- '<(DEPTH)/third_party/jstemplate/util.js',
- '<(DEPTH)/third_party/jstemplate/jsevalcontext.js',
- '<(DEPTH)/third_party/jstemplate/jstemplate.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js',
- '<(DEPTH)/ui/webui/resources/js/action_link.js',
- '<(DEPTH)/ui/webui/resources/js/cr.js',
- '<(DEPTH)/ui/webui/resources/js/cr/event_target.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/array_data_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/autocomplete_list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/command.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/controlled_indicator.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_outline_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_without_ink.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_controller.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_single_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/grid.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/overlay.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/position_util.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/node_utils.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/repeating_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/touch_handler.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/tree.js',
- '<(DEPTH)/ui/webui/resources/js/event_tracker.js',
- '<(DEPTH)/ui/webui/resources/js/icon.js',
- '<(DEPTH)/ui/webui/resources/js/load_time_data.js',
- '<(DEPTH)/ui/webui/resources/js/parse_html_subset.js',
- '<(DEPTH)/ui/webui/resources/js/promise_resolver.js',
- '<(DEPTH)/ui/webui/resources/js/util.js',
- '../chromeos/keyboard/keyboard_utils.js',
- '<(DEPTH)/ui/webui/resources/js/i18n_behavior.js',
- '<(DEPTH)/ui/webui/resources/js/web_ui_listener_behavior.js',
- '../settings/page_visibility.js',
- '../settings/route.js',
- '../settings/people_page/easy_unlock_browser_proxy.js',
- '../settings/people_page/fingerprint_browser_proxy.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selection-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-multi-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menu-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menubar-behavior-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector_grid.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.js',
- '../settings/people_page/lock_screen_constants.js',
- '<(DEPTH)/third_party/closure_compiler/externs/quick_unlock_private.js',
- '../settings/people_page/lock_state_behavior.js',
- '../settings/people_page/password_prompt_dialog.js',
- '<(DEPTH)/ui/webui/resources/js/assert.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-meta/iron-meta-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-icon/iron-icon-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-control-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-ripple/paper-ripple-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-inky-focus-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-icon-button/paper-icon-button-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js',
- '../settings/people_page/lock_screen.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/management.js',
- '<(DEPTH)/third_party/closure_compiler/externs/metrics_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/networking_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/chrome_send.js',
- '<(DEPTH)/third_party/closure_compiler/externs/web_animations.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_network_icon_externs.js',
- '../options/options_bundle.js',
- # Note: ^ this is just a copy of
- # ../options/compiled_resources2.gyp:options_bundle#source_files. Most
- # of this code is deprecated, but please keep in sync if you really
- # need to change.
- 'certificate_manager_dialog.js',
- ],
- },
+ 'target_name': 'internet_detail_dialog',
+ 'dependencies': [
+ '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
+ '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_network_behavior',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
+ '<(EXTERNS_GYP):chrome_send',
+ '<(EXTERNS_GYP):networking_private',
+ '<(INTERFACES_GYP):networking_private_interface',
+ ],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
],
diff --git a/chromium/chrome/browser/resources/chromeos/input_method/google_xkb_manifest.json b/chromium/chrome/browser/resources/chromeos/input_method/google_xkb_manifest.json
index 6034ed5d6dc..ed509c9735b 100644
--- a/chromium/chrome/browser/resources/chromeos/input_method/google_xkb_manifest.json
+++ b/chromium/chrome/browser/resources/chromeos/input_method/google_xkb_manifest.json
@@ -25,8 +25,7 @@
],
"background": {
"page": "background.html",
- // TODO(yhanada): Change to false after fixing crbug.com/761714.
- "persistent": true
+ "persistent": false
},
"content_scripts": [
{
diff --git a/chromium/chrome/browser/resources/components.css b/chromium/chrome/browser/resources/components.css
index c02403c420c..70475b77ad8 100644
--- a/chromium/chrome/browser/resources/components.css
+++ b/chromium/chrome/browser/resources/components.css
@@ -247,3 +247,7 @@ body.show-tmi-mode .show-in-tmi-mode {
button {
font-size: 104%;
}
+
+button[disabled] {
+ color: #999;
+}
diff --git a/chromium/chrome/browser/resources/components.html b/chromium/chrome/browser/resources/components.html
index aef3c973218..205945a39ba 100644
--- a/chromium/chrome/browser/resources/components.html
+++ b/chromium/chrome/browser/resources/components.html
@@ -5,10 +5,6 @@
<title i18n-content="componentsTitle"></title>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<link rel="stylesheet" href="components.css">
-<if expr="chromeos">
- <link rel="stylesheet"
- href="chrome://resources/css/chromeos/ui_account_tweaks.css">
-</if>
</head>
<body>
<div id="body-container" style="visibility:hidden">
@@ -60,8 +56,8 @@
<span jscontent="status" jsvalues=".id: 'status-' + id">
<span>
</div>
- <div class="component-actions" guest-visibility="disabled">
- <button class="button-check-update"
+ <div class="component-actions">
+ <button class="button-check-update" guest-disabled
jsvalues=".id:id" i18n-content="checkUpdate">
</button>
</div>
@@ -73,10 +69,6 @@
<script src="chrome://resources/js/util.js"></script>
<script src="chrome://resources/js/cr.js"></script>
<script src="chrome://components/components.js"></script>
-<if expr="chromeos">
- <script src="chrome://resources/js/chromeos/ui_account_tweaks.js"></script>
-</if>
-
<script src="chrome://resources/js/load_time_data.js"></script>
<script src="chrome://resources/js/jstemplate_compiled.js"></script>
<script src="chrome://components/strings.js"></script>
diff --git a/chromium/chrome/browser/resources/components.js b/chromium/chrome/browser/resources/components.js
index 01925a941a4..f1247bbc0b3 100644
--- a/chromium/chrome/browser/resources/components.js
+++ b/chromium/chrome/browser/resources/components.js
@@ -67,12 +67,11 @@ function returnComponentsData(componentsData) {
};
}
- if (cr.isChromeOS) {
- // Disable some controls for Guest in ChromeOS.
- uiAccountTweaks.UIAccountTweaks.applyGuestSessionVisibility(document);
-
- // Disable some controls for Public session in ChromeOS.
- uiAccountTweaks.UIAccountTweaks.applyPublicSessionVisibility(document);
+ // Disable some controls for Guest mode in ChromeOS.
+ if (cr.isChromeOS && loadTimeData.getBoolean('isGuest')) {
+ document.querySelectorAll('[guest-disabled]').forEach(function(element) {
+ element.disabled = true;
+ });
}
bodyContainer.style.visibility = 'visible';
diff --git a/chromium/chrome/browser/resources/domain_reliability_internals.html b/chromium/chrome/browser/resources/domain_reliability_internals.html
index f23349b71d8..95d6d18901b 100644
--- a/chromium/chrome/browser/resources/domain_reliability_internals.html
+++ b/chromium/chrome/browser/resources/domain_reliability_internals.html
@@ -2,17 +2,14 @@
<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
- <title i18n-content="title"></title>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<link rel="stylesheet" href="domain_reliability_internals.css" />
<script src="chrome://resources/js/cr.js"></script>
<script src="chrome://resources/js/util.js"></script>
<script src="chrome://resources/js/jstemplate_compiled.js"></script>
- <script src="strings.js"></script>
<script src="domain_reliability_internals.js"></script>
</head>
<body>
- <script src="chrome://resources/js/i18n_template.js"></script>
<div id="template">
<div jsdisplay="error">
Error loading Domain Reliability data:
diff --git a/chromium/chrome/browser/resources/engagement/site_engagement.html b/chromium/chrome/browser/resources/engagement/site_engagement.html
index a613730dac0..c5df80fc214 100644
--- a/chromium/chrome/browser/resources/engagement/site_engagement.html
+++ b/chromium/chrome/browser/resources/engagement/site_engagement.html
@@ -3,7 +3,10 @@
<title>Site Engagement</title>
<meta charset="utf-8">
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
+ <script src="chrome://resources/js/mojo_bindings.js"></script>
<script src="chrome://resources/js/util.js"></script>
+ <script src="chrome/browser/engagement/site_engagement_details.mojom.js">
+ </script>
<script src="chrome://site-engagement/site_engagement.js"></script>
<style>
body {
@@ -88,13 +91,13 @@
<th sort-key="origin">
Origin
</th>
- <th sort-key="base_score" sort-reverse>
+ <th sort-key="baseScore" sort-reverse>
Base
</th>
- <th sort-key="bonus_score" sort-reverse>
+ <th sort-key="bonusScore" sort-reverse>
Bonus
</th>
- <th sort-key="total_score" class="sort-column" sort-reverse>
+ <th sort-key="totalScore" class="sort-column" sort-reverse>
Total
</th>
</tr>
diff --git a/chromium/chrome/browser/resources/engagement/site_engagement.js b/chromium/chrome/browser/resources/engagement/site_engagement.js
index c70ff186eec..230f1ea8a59 100644
--- a/chromium/chrome/browser/resources/engagement/site_engagement.js
+++ b/chromium/chrome/browser/resources/engagement/site_engagement.js
@@ -6,218 +6,214 @@
// Allow a function to be provided by tests, which will be called when
// the page has been populated with site engagement details.
+var whenPageIsPopulatedForTest;
+
+var disableAutoupdateForTests;
+var uiHandler;
+
+(function() {
var resolvePageIsPopulated = null;
var pageIsPopulatedPromise = new Promise((resolve, reject) => {
resolvePageIsPopulated = resolve;
});
-function whenPageIsPopulatedForTest() {
+whenPageIsPopulatedForTest = function() {
return pageIsPopulatedPromise;
+};
+
+function initialize() {
+ uiHandler = new mojom.SiteEngagementDetailsProviderPtr;
+ Mojo.bindInterface(
+ mojom.SiteEngagementDetailsProvider.name,
+ mojo.makeRequest(uiHandler).handle);
+
+ var engagementTableBody = $('engagement-table-body');
+ var updateInterval = null;
+ var info = null;
+ var sortKey = 'totalScore';
+ var sortReverse = true;
+
+ // Set table header sort handlers.
+ var engagementTableHeader = $('engagement-table-header');
+ var headers = engagementTableHeader.children;
+ for (var i = 0; i < headers.length; i++) {
+ headers[i].addEventListener('click', (e) => {
+ var newSortKey = e.target.getAttribute('sort-key');
+ if (sortKey == newSortKey) {
+ sortReverse = !sortReverse;
+ } else {
+ sortKey = newSortKey;
+ sortReverse = false;
+ }
+ var oldSortColumn = document.querySelector('.sort-column');
+ oldSortColumn.classList.remove('sort-column');
+ e.target.classList.add('sort-column');
+ if (sortReverse)
+ e.target.setAttribute('sort-reverse', '');
+ else
+ e.target.removeAttribute('sort-reverse');
+ renderTable();
+ });
+ }
+
+ /**
+ * Creates a single row in the engagement table.
+ * @param {SiteEngagementDetails} info The info to create the row from.
+ * @return {HTMLElement}
+ */
+ function createRow(info) {
+ var originCell = createElementWithClassName('td', 'origin-cell');
+ originCell.textContent = info.origin.url;
+
+ var baseScoreInput =
+ createElementWithClassName('input', 'base-score-input');
+ baseScoreInput.addEventListener(
+ 'change', handleBaseScoreChange.bind(undefined, info.origin));
+ baseScoreInput.addEventListener('focus', disableAutoupdate);
+ baseScoreInput.addEventListener('blur', enableAutoupdate);
+ baseScoreInput.value = info.baseScore;
+
+ var baseScoreCell = createElementWithClassName('td', 'base-score-cell');
+ baseScoreCell.appendChild(baseScoreInput);
+
+ var bonusScoreCell = createElementWithClassName('td', 'bonus-score-cell');
+ bonusScoreCell.textContent = info.bonusScore;
+
+ var totalScoreCell = createElementWithClassName('td', 'total-score-cell');
+ totalScoreCell.textContent = info.totalScore;
+
+ var engagementBar = createElementWithClassName('div', 'engagement-bar');
+ engagementBar.style.width = (info.totalScore * 4) + 'px';
+
+ var engagementBarCell =
+ createElementWithClassName('td', 'engagement-bar-cell');
+ engagementBarCell.appendChild(engagementBar);
+
+ var row = document.createElement('tr');
+ row.appendChild(originCell);
+ row.appendChild(baseScoreCell);
+ row.appendChild(bonusScoreCell);
+ row.appendChild(totalScoreCell);
+ row.appendChild(engagementBarCell);
+
+ // Stores correspondent engagementBarCell to change it's length on
+ // scoreChange event.
+ baseScoreInput.barCellRef = engagementBar;
+ return row;
+ }
+
+ function disableAutoupdate() {
+ if (updateInterval)
+ clearInterval(updateInterval);
+ updateInterval = null;
+ }
+ disableAutoupdateForTests = disableAutoupdate;
+
+ function enableAutoupdate() {
+ if (updateInterval)
+ clearInterval(updateInterval);
+ updateInterval = setInterval(updateEngagementTable, 5000);
+ }
+
+ /**
+ * Sets the base engagement score when a score input is changed.
+ * Resets the length of engagement-bar-cell to match the new score.
+ * Also resets the update interval.
+ * @param {string} origin The origin of the engagement score to set.
+ * @param {Event} e
+ */
+ function handleBaseScoreChange(origin, e) {
+ var baseScoreInput = e.target;
+ uiHandler.setSiteEngagementBaseScoreForUrl(origin, baseScoreInput.value);
+ baseScoreInput.barCellRef.style.width = (baseScoreInput.value * 4) + 'px';
+ baseScoreInput.blur();
+ enableAutoupdate();
+ }
+
+ /**
+ * Remove all rows from the engagement table.
+ */
+ function clearTable() {
+ engagementTableBody.innerHTML = '';
+ }
+
+ /**
+ * Sort the engagement info based on |sortKey| and |sortReverse|.
+ */
+ function sortInfo() {
+ info.sort((a, b) => {
+ return (sortReverse ? -1 : 1) * compareTableItem(sortKey, a, b);
+ });
+ }
+
+ /**
+ * Compares two SiteEngagementDetails objects based on |sortKey|.
+ * @param {string} sortKey The name of the property to sort by.
+ * @return {number} A negative number if |a| should be ordered before |b|, a
+ * positive number otherwise.
+ */
+ function compareTableItem(sortKey, a, b) {
+ var val1 = a[sortKey];
+ var val2 = b[sortKey];
+
+ // Compare the hosts of the origin ignoring schemes.
+ if (sortKey == 'origin')
+ return new URL(val1.url).host > new URL(val2.url).host ? 1 : -1;
+
+ if (sortKey == 'baseScore' || sortKey == 'bonusScore' ||
+ sortKey == 'totalScore') {
+ return val1 - val2;
+ }
+
+ assertNotReached('Unsupported sort key: ' + sortKey);
+ return 0;
+ }
+
+ /**
+ * Rounds the supplied value to two decimal places of accuracy.
+ * @param {number} score
+ * @return {number}
+ */
+ function roundScore(score) {
+ return Number(Math.round(score * 100) / 100);
+ }
+
+ /**
+ * Regenerates the engagement table from |info|.
+ */
+ function renderTable() {
+ clearTable();
+ sortInfo();
+
+ info.forEach((info) => {
+ // Round all scores to 2 decimal places.
+ info.baseScore = roundScore(info.baseScore);
+ info.installedBonus = roundScore(info.installedBonus);
+ info.notificationsBonus = roundScore(info.notificationsBonus);
+ info.totalScore = roundScore(info.totalScore);
+
+ // Collate the bonuses into a value for the bonusScore column.
+ info.bonusScore = info.installedBonus + info.notificationsBonus;
+
+ engagementTableBody.appendChild(createRow(info));
+ });
+ }
+
+ /**
+ * Retrieve site engagement info and render the engagement table.
+ */
+ function updateEngagementTable() {
+ // Populate engagement table.
+ uiHandler.getSiteEngagementDetails().then((response) => {
+ info = response.info;
+ renderTable(info);
+ resolvePageIsPopulated();
+ });
+ }
+
+ updateEngagementTable();
+ enableAutoupdate();
}
-define(
- 'main',
- [
- 'chrome/browser/engagement/site_engagement_details.mojom',
- 'content/public/renderer/frame_interfaces',
- ],
- (siteEngagementMojom, frameInterfaces) => {
- return () => {
- var uiHandler =
- new siteEngagementMojom.SiteEngagementDetailsProviderPtr(
- frameInterfaces.getInterface(
- siteEngagementMojom.SiteEngagementDetailsProvider.name));
-
- var engagementTableBody = $('engagement-table-body');
- var updateInterval = null;
- var info = null;
- var sortKey = 'total_score';
- var sortReverse = true;
-
- // Set table header sort handlers.
- var engagementTableHeader = $('engagement-table-header');
- var headers = engagementTableHeader.children;
- for (var i = 0; i < headers.length; i++) {
- headers[i].addEventListener('click', (e) => {
- var newSortKey = e.target.getAttribute('sort-key');
- if (sortKey == newSortKey) {
- sortReverse = !sortReverse;
- } else {
- sortKey = newSortKey;
- sortReverse = false;
- }
- var oldSortColumn = document.querySelector('.sort-column');
- oldSortColumn.classList.remove('sort-column');
- e.target.classList.add('sort-column');
- if (sortReverse)
- e.target.setAttribute('sort-reverse', '');
- else
- e.target.removeAttribute('sort-reverse');
- renderTable();
- });
- }
-
- /**
- * Creates a single row in the engagement table.
- * @param {SiteEngagementDetails} info The info to create the row from.
- * @return {HTMLElement}
- */
- function createRow(info) {
- var originCell = createElementWithClassName('td', 'origin-cell');
- originCell.textContent = info.origin.url;
-
- var baseScoreInput =
- createElementWithClassName('input', 'base-score-input');
- baseScoreInput.addEventListener(
- 'change', handleBaseScoreChange.bind(undefined, info.origin));
- baseScoreInput.addEventListener('focus', disableAutoupdate);
- baseScoreInput.addEventListener('blur', enableAutoupdate);
- baseScoreInput.value = info.base_score;
-
- var baseScoreCell =
- createElementWithClassName('td', 'base-score-cell');
- baseScoreCell.appendChild(baseScoreInput);
-
- var bonusScoreCell =
- createElementWithClassName('td', 'bonus-score-cell');
- bonusScoreCell.textContent = info.bonus_score;
-
- var totalScoreCell =
- createElementWithClassName('td', 'total-score-cell');
- totalScoreCell.textContent = info.total_score;
-
- var engagementBar =
- createElementWithClassName('div', 'engagement-bar');
- engagementBar.style.width = (info.total_score * 4) + 'px';
-
- var engagementBarCell =
- createElementWithClassName('td', 'engagement-bar-cell');
- engagementBarCell.appendChild(engagementBar);
-
- var row = document.createElement('tr');
- row.appendChild(originCell);
- row.appendChild(baseScoreCell);
- row.appendChild(bonusScoreCell);
- row.appendChild(totalScoreCell);
- row.appendChild(engagementBarCell);
-
- // Stores correspondent engagementBarCell to change it's length on
- // scoreChange event.
- baseScoreInput.barCellRef = engagementBar;
- return row;
- }
-
- function disableAutoupdate() {
- if (updateInterval)
- clearInterval(updateInterval);
- updateInterval = null;
- }
-
- function enableAutoupdate() {
- if (updateInterval)
- clearInterval(updateInterval);
- updateInterval = setInterval(updateEngagementTable, 5000);
- }
-
- /**
- * Sets the base engagement score when a score input is changed.
- * Resets the length of engagement-bar-cell to match the new score.
- * Also resets the update interval.
- * @param {string} origin The origin of the engagement score to set.
- * @param {Event} e
- */
- function handleBaseScoreChange(origin, e) {
- var baseScoreInput = e.target;
- uiHandler.setSiteEngagementBaseScoreForUrl(
- origin, baseScoreInput.value);
- baseScoreInput.barCellRef.style.width =
- (baseScoreInput.value * 4) + 'px';
- baseScoreInput.blur();
- enableAutoupdate();
- }
-
- /**
- * Remove all rows from the engagement table.
- */
- function clearTable() {
- engagementTableBody.innerHTML = '';
- }
-
- /**
- * Sort the engagement info based on |sortKey| and |sortReverse|.
- */
- function sortInfo() {
- info.sort((a, b) => {
- return (sortReverse ? -1 : 1) * compareTableItem(sortKey, a, b);
- });
- }
-
- /**
- * Compares two SiteEngagementDetails objects based on |sortKey|.
- * @param {string} sortKey The name of the property to sort by.
- * @return {number} A negative number if |a| should be ordered before |b|, a
- * positive number otherwise.
- */
- function compareTableItem(sortKey, a, b) {
- var val1 = a[sortKey];
- var val2 = b[sortKey];
-
- // Compare the hosts of the origin ignoring schemes.
- if (sortKey == 'origin')
- return new URL(val1.url).host > new URL(val2.url).host ? 1 : -1;
-
- if (sortKey == 'base_score' || sortKey == 'bonus_score' ||
- sortKey == 'total_score') {
- return val1 - val2;
- }
-
- assertNotReached('Unsupported sort key: ' + sortKey);
- return 0;
- }
-
- /**
- * Rounds the supplied value to two decimal places of accuracy.
- * @param {number} score
- * @return {number}
- */
- function roundScore(score) {
- return Number(Math.round(score * 100) / 100);
- }
-
- /**
- * Regenerates the engagement table from |info|.
- */
- function renderTable() {
- clearTable();
- sortInfo();
-
- info.forEach((info) => {
- // Round all scores to 2 decimal places.
- info.base_score = roundScore(info.base_score);
- info.installed_bonus = roundScore(info.installed_bonus);
- info.notifications_bonus = roundScore(info.notifications_bonus);
- info.total_score = roundScore(info.total_score);
-
- // Collate the bonuses into a value for the bonus_score column.
- info.bonus_score = info.installed_bonus + info.notifications_bonus;
-
- engagementTableBody.appendChild(createRow(info));
- });
- }
-
- /**
- * Retrieve site engagement info and render the engagement table.
- */
- function updateEngagementTable() {
- // Populate engagement table.
- uiHandler.getSiteEngagementDetails().then((response) => {
- info = response.info;
- renderTable(info);
- resolvePageIsPopulated();
- });
- }
-
- updateEngagementTable();
- enableAutoupdate();
- };
- });
+document.addEventListener('DOMContentLoaded', initialize);
+})();
diff --git a/chromium/chrome/browser/resources/extensions/OWNERS b/chromium/chrome/browser/resources/extensions/OWNERS
index b4ef9535bac..9f96570c5ab 100644
--- a/chromium/chrome/browser/resources/extensions/OWNERS
+++ b/chromium/chrome/browser/resources/extensions/OWNERS
@@ -1,4 +1,3 @@
-dbeam@chromium.org
finnur@chromium.org
rdevlin.cronin@chromium.org
diff --git a/chromium/chrome/browser/resources/extensions/extension_options_overlay.html b/chromium/chrome/browser/resources/extensions/extension_options_overlay.html
index 2398ac35be6..e5ee0b97885 100644
--- a/chromium/chrome/browser/resources/extensions/extension_options_overlay.html
+++ b/chromium/chrome/browser/resources/extensions/extension_options_overlay.html
@@ -6,8 +6,7 @@ in the LICENSE file.
<div id="extension-options-overlay" class="page">
<div class="close-button"></div>
<div id="extension-options-overlay-header">
- <img id="extension-options-overlay-icon"
- aria-hidden="true"></img>
+ <img id="extension-options-overlay-icon" aria-hidden="true">
<h1 id="extension-options-overlay-title"></h1>
</div>
<div id="extension-options-overlay-guest"></div>
diff --git a/chromium/chrome/browser/resources/extensions/extensions.css b/chromium/chrome/browser/resources/extensions/extensions.css
index a18931e2bbf..fd9e469922b 100644
--- a/chromium/chrome/browser/resources/extensions/extensions.css
+++ b/chromium/chrome/browser/resources/extensions/extensions.css
@@ -189,11 +189,11 @@ html[dir='rtl'] .extension-list-item {
.extension-title {
-webkit-padding-end: 20px;
- -webkit-user-select: text;
color: rgb(48, 57, 66);
display: inline;
font-size: 14px;
font-weight: 500;
+ user-select: text;
}
.inactive-extension .extension-title {
diff --git a/chromium/chrome/browser/resources/extensions/extensions.html b/chromium/chrome/browser/resources/extensions/extensions.html
index 7ed15c83bb5..bcca289b8c7 100644
--- a/chromium/chrome/browser/resources/extensions/extensions.html
+++ b/chromium/chrome/browser/resources/extensions/extensions.html
@@ -162,7 +162,7 @@
$i18n{extensionSettingsReloadUnpacked}
</a>
<a is="action-link" role="button" class="errors-link">
- <img class="extension-error-icon"></img>
+ <img class="extension-error-icon">
<span>$i18n{extensionErrorHeading}</span>
</a>
</div>
diff --git a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
index 2c3f836f88e..878224e9f32 100644
--- a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
+++ b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
@@ -821,7 +821,12 @@ cr.define('cr.login', function() {
'method': 'handshake',
};
- this.webview_.contentWindow.postMessage(msg, currentUrl);
+ // |this.webview_.contentWindow| may be null after network error screen
+ // is shown. See crbug.com/770999.
+ if (this.webview_.contentWindow)
+ this.webview_.contentWindow.postMessage(msg, currentUrl);
+ else
+ console.error('Authenticator: contentWindow is null.');
this.fireReadyEvent_();
// Focus webview after dispatching event when webview is already visible.
diff --git a/chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js b/chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js
index 9212e584129..89907937681 100644
--- a/chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js
+++ b/chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js
@@ -243,7 +243,12 @@ cr.define('cr.login', function() {
* @private
*/
onContentLoad_: function(e) {
- PostMessageChannel.init(this.webview_.contentWindow);
+ // |this.webview_.contentWindow| may be null after network error screen
+ // is shown. See crbug.com/770999.
+ if (this.webview_.contentWindow)
+ PostMessageChannel.init(this.webview_.contentWindow);
+ else
+ console.error('SamlHandler.onContentLoad_: contentWindow is null.');
},
/**
diff --git a/chromium/chrome/browser/resources/hangout_services/manifest.json b/chromium/chrome/browser/resources/hangout_services/manifest.json
index 891af4e1dd4..af76f3d202c 100644
--- a/chromium/chrome/browser/resources/hangout_services/manifest.json
+++ b/chromium/chrome/browser/resources/hangout_services/manifest.json
@@ -5,7 +5,7 @@
"name": "Google Hangouts",
// Note: Always update the version number when this file is updated. Chrome
// triggers extension preferences update on the version increase.
- "version": "1.3.4",
+ "version": "1.3.5",
"manifest_version": 2,
"externally_connectable": {
"matches": [
diff --git a/chromium/chrome/browser/resources/hangout_services/thunk.js b/chromium/chrome/browser/resources/hangout_services/thunk.js
index 43f12df8135..85a7e688a8c 100644
--- a/chromium/chrome/browser/resources/hangout_services/thunk.js
+++ b/chromium/chrome/browser/resources/hangout_services/thunk.js
@@ -12,7 +12,7 @@ chrome.runtime.onMessageExternal.addListener(function(
error['message'] = errorString;
}
- var errorMessage = error || chrome.extension.lastError;
+ var errorMessage = error || chrome.runtime.lastError;
sendResponse({'value': value, 'error': errorMessage});
}
@@ -118,7 +118,7 @@ chrome.runtime.onMessageExternal.addListener(function(
var errorMessage = null;
// If upload fails, report all previous errors.
// Otherwise, throw them away.
- if (chrome.extension.lastError !== undefined) {
+ if (chrome.runtime.lastError !== undefined) {
appendLastErrorMessage(errors);
errorMessage = errors.join('; ');
}
@@ -273,25 +273,27 @@ function onProcessCpu(port) {
if (!tabProcess) {
return;
}
- var pluginProcessCpu = 0, browserProcessCpu = 0, gpuProcessCpu = 0;
+
+ var browserProcessCpu, gpuProcessCpu;
for (var pid in processes) {
var process = processes[pid];
if (process.type == 'browser') {
browserProcessCpu = process.cpu;
} else if (process.type == 'gpu') {
gpuProcessCpu = process.cpu;
- } else if (
- (process.type == 'plugin' || process.type == 'nacl') &&
- process.title.toLowerCase().indexOf('hangouts') > 0) {
- pluginProcessCpu = process.cpu;
}
+ if (!!browserProcessCpu && !!gpuProcessCpu)
+ break;
}
port.postMessage({
+ 'browserCpuUsage': browserProcessCpu || 0,
+ 'gpuCpuUsage': gpuProcessCpu || 0,
'tabCpuUsage': tabProcess.cpu,
- 'browserCpuUsage': browserProcessCpu,
- 'gpuCpuUsage': gpuProcessCpu,
- 'pluginCpuUsage': pluginProcessCpu
+ 'tabNetworkUsage': tabProcess.network,
+ 'tabPrivateMemory': tabProcess.privateMemory,
+ 'tabJsMemoryAllocated': tabProcess.jsMemoryAllocated,
+ 'tabJsMemoryUsed': tabProcess.jsMemoryUsed
});
}
@@ -302,8 +304,8 @@ function onProcessCpu(port) {
}
function appendLastErrorMessage(errors) {
- if (chrome.extension.lastError !== undefined)
- errors.push(chrome.extension.lastError.message);
+ if (chrome.runtime.lastError !== undefined)
+ errors.push(chrome.runtime.lastError.message);
}
chrome.runtime.onConnectExternal.addListener(function(port) {
diff --git a/chromium/chrome/browser/resources/help/OWNERS b/chromium/chrome/browser/resources/help/OWNERS
deleted file mode 100644
index 31563784459..00000000000
--- a/chromium/chrome/browser/resources/help/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-# This UI is deprecated. See chrome/browser/resources/settings/about_page
-# instead.
-
-set noparent
-dbeam@chromium.org
-dpapad@chromium.org
diff --git a/chromium/chrome/browser/resources/help/channel_change_page.css b/chromium/chrome/browser/resources/help/channel_change_page.css
deleted file mode 100644
index 16ca9041357..00000000000
--- a/chromium/chrome/browser/resources/help/channel_change_page.css
+++ /dev/null
@@ -1,33 +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. */
-
-#channel-change-page {
- min-height: 200px;
- width: 500px;
-}
-
-.channel-change-page-channel label {
- margin-left: 10px;
-}
-
-.channel-change-page-channel {
- display: block;
- margin: 0 25px;
-}
-
-.show-when-selected-channel-requires-powerwash,
-.show-when-selected-channel-requires-delayed-update,
-.show-when-selected-channel-good,
-.show-when-selected-channel-unstable {
- display: none !important;
-}
-
-.selected-channel-requires-powerwash
-.show-when-selected-channel-requires-powerwash,
-.selected-channel-requires-delayed-update
-.show-when-selected-channel-requires-delayed-update,
-.selected-channel-good .show-when-selected-channel-good,
-.selected-channel-unstable .show-when-selected-channel-unstable {
- display: block !important;
-}
diff --git a/chromium/chrome/browser/resources/help/channel_change_page.html b/chromium/chrome/browser/resources/help/channel_change_page.html
deleted file mode 100644
index 67b16cf6af5..00000000000
--- a/chromium/chrome/browser/resources/help/channel_change_page.html
+++ /dev/null
@@ -1,52 +0,0 @@
-<div id="channel-change-page" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{channelChangePageTitle}</h1>
- <div class="content-area">
- <div class="channel-change-page-channel radio">
- <input id="channel-change-page-stable-option"
- type="radio" name="channel" value="stable-channel">
- <label for="channel-change-page-stable-option">$i18n{stable}</label>
- </div>
- <div class="channel-change-page-channel radio">
- <input id="channel-change-page-beta-option"
- type="radio" name="channel" value="beta-channel">
- <label for="channel-change-page-beta-option">$i18n{beta}</label>
- </div>
- <div class="channel-change-page-channel radio">
- <input id="channel-change-page-dev-option"
- type="radio" name="channel" value="dev-channel">
- <label for="channel-change-page-dev-option">$i18n{dev}</label>
- </div>
- </div>
- <div class="content-area">
- <div class="show-when-selected-channel-requires-powerwash">
- <h2>$i18n{channelChangePagePowerwashTitle}</h2>
- <div>$i18n{channelChangePagePowerwashMessage}</div>
- </div>
- <div class="show-when-selected-channel-requires-delayed-update">
- <h2>$i18n{channelChangePageDelayedChangeTitle}</h2>
- <div>$i18n{channelChangePageDelayedChangeMessage}</div>
- </div>
- <div class="show-when-selected-channel-unstable">
- <h2>$i18n{channelChangePageUnstableTitle}</h2>
- <div>$i18n{channelChangePageUnstableMessage}</div>
- </div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="channel-change-page-powerwash-button"
- class="show-when-selected-channel-requires-powerwash">
- $i18n{channelChangePagePowerwashButton}
- </button>
- <button id="channel-change-page-change-button"
- class="show-when-selected-channel-requires-delayed-update
- show-when-selected-channel-good
- show-when-selected-channel-unstable">
- $i18n{channelChangePageChangeButton}
- </button>
- <button id="channel-change-page-cancel-button" class="default-button">
- $i18n{channelChangePageCancelButton}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/help/channel_change_page.js b/chromium/chrome/browser/resources/help/channel_change_page.js
deleted file mode 100644
index 3763f6533c7..00000000000
--- a/chromium/chrome/browser/resources/help/channel_change_page.js
+++ /dev/null
@@ -1,261 +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.
-
-cr.define('help', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Encapsulated handling of the channel change overlay.
- */
- function ChannelChangePage() {
- Page.call(this, 'channel-change-page', '', 'channel-change-page');
- }
-
- cr.addSingletonGetter(ChannelChangePage);
-
- ChannelChangePage.prototype = {
- __proto__: Page.prototype,
-
- /**
- * Name of the channel the device is currently on.
- * @private
- */
- currentChannel_: null,
-
- /**
- * Name of the channel the device is supposed to be on.
- * @private
- */
- targetChannel_: null,
-
- /**
- * True iff the device is enterprise-managed.
- * @private
- */
- isEnterpriseManaged_: undefined,
-
- /**
- * List of the channels names, from the least stable to the most stable.
- * @private
- */
- channelList_: ['dev-channel', 'beta-channel', 'stable-channel'],
-
- /**
- * List of the possible ui states.
- * @private
- */
- uiClassTable_: ['selected-channel-requires-powerwash',
- 'selected-channel-requires-delayed-update',
- 'selected-channel-good',
- 'selected-channel-unstable'],
-
- /** override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('channel-change-page-cancel-button').onclick =
- PageManager.closeOverlay.bind(PageManager);
-
- var self = this;
- var options = this.getAllChannelOptions_();
- for (var i = 0; i < options.length; i++) {
- var option = options[i];
- option.onclick = function() {
- self.updateUI_(this.value);
- };
- }
-
- $('channel-change-page-powerwash-button').onclick = function() {
- self.setChannel_(self.getSelectedOption_(), true);
- PageManager.closeOverlay();
- };
-
- $('channel-change-page-change-button').onclick = function() {
- self.setChannel_(self.getSelectedOption_(), false);
- PageManager.closeOverlay();
- };
- },
-
- /** @override */
- didShowPage: function() {
- if (this.targetChannel_ != null)
- this.selectOption_(this.targetChannel_);
- else if (this.currentChannel_ != null)
- this.selectOption_(this.currentChannel_);
- var options = this.getAllChannelOptions_();
- for (var i = 0; i < options.length; i++) {
- var option = options[i];
- if (option.checked)
- option.focus();
- }
- },
-
- /**
- * Returns the list of all radio buttons responsible for channel selection.
- * @return {NodeList} Array of radio buttons
- * @private
- */
- getAllChannelOptions_: function() {
- return this.pageDiv.querySelectorAll('input[type="radio"]');
- },
-
- /**
- * Returns value of the selected option.
- * @return {?string} Selected channel name or null, if neither
- * option is selected.
- * @private
- */
- getSelectedOption_: function() {
- var options = this.getAllChannelOptions_();
- for (var i = 0; i < options.length; i++) {
- var option = options[i];
- if (option.checked)
- return option.value;
- }
- return null;
- },
-
- /**
- * Selects option for a given channel.
- * @param {string} channel Name of channel option that should be selected.
- * @private
- */
- selectOption_: function(channel) {
- var options = this.getAllChannelOptions_();
- for (var i = 0; i < options.length; i++) {
- var option = options[i];
- if (option.value == channel) {
- option.checked = true;
- }
- }
- this.updateUI_(channel);
- },
-
- /**
- * Updates UI according to selected channel.
- * @param {string} selectedChannel Selected channel
- * @private
- */
- updateUI_: function(selectedChannel) {
- var currentStability = this.channelList_.indexOf(this.currentChannel_);
- var newStability = this.channelList_.indexOf(selectedChannel);
-
- var newOverlayClass = null;
-
- if (selectedChannel == this.currentChannel_) {
- if (this.currentChannel_ != this.targetChannel_) {
- // Allow user to switch back to the current channel.
- newOverlayClass = 'selected-channel-good';
- }
- } else if (selectedChannel != this.targetChannel_) {
- // Selected channel isn't equal to the current and target channel.
- if (newStability > currentStability) {
- // More stable channel is selected. For customer devices
- // notify user about powerwash.
- if (this.isEnterpriseManaged_)
- newOverlayClass = 'selected-channel-requires-delayed-update';
- else
- newOverlayClass = 'selected-channel-requires-powerwash';
- } else if (selectedChannel == 'dev-channel') {
- // Warn user about unstable channel.
- newOverlayClass = 'selected-channel-unstable';
- } else {
- // Switching to the less stable channel.
- newOverlayClass = 'selected-channel-good';
- }
- }
-
- // Switch to the new UI state.
- for (var i = 0; i < this.uiClassTable_.length; i++)
- this.pageDiv.classList.remove(this.uiClassTable_[i]);
-
- if (newOverlayClass)
- this.pageDiv.classList.add(newOverlayClass);
- },
-
- /**
- * Sets the device target channel.
- * @param {string} channel The name of the target channel
- * @param {boolean} isPowerwashAllowed True iff powerwash is allowed
- * @private
- */
- setChannel_: function(channel, isPowerwashAllowed) {
- this.targetChannel_ = channel;
- this.updateUI_(channel);
- help.HelpPage.setChannel(channel, isPowerwashAllowed);
- },
-
- /**
- * Updates page UI according to device owhership policy.
- * @param {boolean} isEnterpriseManaged True if the device is
- * enterprise managed
- * @private
- */
- updateIsEnterpriseManaged_: function(isEnterpriseManaged) {
- this.isEnterpriseManaged_ = isEnterpriseManaged;
- },
-
- /**
- * Updates name of the current channel, i.e. the name of the
- * channel the device is currently on.
- * @param {string} channel The name of the current channel
- * @private
- */
- updateCurrentChannel_: function(channel) {
- if (this.channelList_.indexOf(channel) < 0)
- return;
- this.currentChannel_ = channel;
- this.selectOption_(channel);
- },
-
- /**
- * Updates name of the target channel, i.e. the name of the
- * channel the device is supposed to be in case of a pending
- * channel change.
- * @param {string} channel The name of the target channel
- * @private
- */
- updateTargetChannel_: function(channel) {
- if (this.channelList_.indexOf(channel) < 0)
- return;
- this.targetChannel_ = channel;
- },
-
- /**
- * @return {boolean} True if the page is ready and can be
- * displayed, false otherwise
- * @private
- */
- isPageReady_: function() {
- if (typeof this.isEnterpriseManaged_ == 'undefined')
- return false;
- if (!this.currentChannel_ || !this.targetChannel_)
- return false;
- return true;
- },
- };
-
- ChannelChangePage.updateIsEnterpriseManaged = function(isEnterpriseManaged) {
- ChannelChangePage.getInstance().updateIsEnterpriseManaged_(
- isEnterpriseManaged);
- };
-
- ChannelChangePage.updateCurrentChannel = function(channel) {
- ChannelChangePage.getInstance().updateCurrentChannel_(channel);
- };
-
- ChannelChangePage.updateTargetChannel = function(channel) {
- ChannelChangePage.getInstance().updateTargetChannel_(channel);
- };
-
- ChannelChangePage.isPageReady = function() {
- return ChannelChangePage.getInstance().isPageReady_();
- };
-
- // Export
- return {
- ChannelChangePage: ChannelChangePage
- };
-});
diff --git a/chromium/chrome/browser/resources/help/compiled_resources2.gyp b/chromium/chrome/browser/resources/help/compiled_resources2.gyp
deleted file mode 100644
index c0ae4e74deb..00000000000
--- a/chromium/chrome/browser/resources/help/compiled_resources2.gyp
+++ /dev/null
@@ -1,103 +0,0 @@
-# Copyright 2017 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-{
- 'targets': [
- {
- 'target_name': 'help',
- 'variables': {
- 'extra_inputs': [
- '<!@(python <(CLOSURE_DIR)/build/get_includes.py ../options/options_bundle.js)',
- ],
- 'script_args': ['--custom_sources', '--custom_includes'],
- 'source_files': [
- '<(DEPTH)/third_party/jstemplate/util.js',
- '<(DEPTH)/third_party/jstemplate/jsevalcontext.js',
- '<(DEPTH)/third_party/jstemplate/jstemplate.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js',
- '<(DEPTH)/ui/webui/resources/js/action_link.js',
- '<(DEPTH)/ui/webui/resources/js/cr.js',
- '<(DEPTH)/ui/webui/resources/js/cr/event_target.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/array_data_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/autocomplete_list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/command.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/controlled_indicator.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_outline_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_without_ink.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_controller.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_single_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/grid.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/overlay.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/position_util.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/node_utils.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/repeating_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/touch_handler.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/tree.js',
- '<(DEPTH)/ui/webui/resources/js/event_tracker.js',
- '<(DEPTH)/ui/webui/resources/js/icon.js',
- '<(DEPTH)/ui/webui/resources/js/load_time_data.js',
- '<(DEPTH)/ui/webui/resources/js/parse_html_subset.js',
- '<(DEPTH)/ui/webui/resources/js/promise_resolver.js',
- '<(DEPTH)/ui/webui/resources/js/util.js',
- '../chromeos/keyboard/keyboard_utils.js',
- '<(DEPTH)/ui/webui/resources/js/i18n_behavior.js',
- '<(DEPTH)/ui/webui/resources/js/web_ui_listener_behavior.js',
- '../settings/page_visibility.js',
- '../settings/route.js',
- '../settings/people_page/easy_unlock_browser_proxy.js',
- '../settings/people_page/fingerprint_browser_proxy.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selection-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-multi-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menu-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menubar-behavior-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector_grid.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.js',
- '../settings/people_page/lock_screen_constants.js',
- '<(DEPTH)/third_party/closure_compiler/externs/quick_unlock_private.js',
- '../settings/people_page/lock_state_behavior.js',
- '../settings/people_page/password_prompt_dialog.js',
- '<(DEPTH)/ui/webui/resources/js/assert.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-meta/iron-meta-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-icon/iron-icon-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-control-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-ripple/paper-ripple-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-inky-focus-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-icon-button/paper-icon-button-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js',
- '../settings/people_page/lock_screen.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/management.js',
- '<(DEPTH)/third_party/closure_compiler/externs/metrics_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/networking_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/chrome_send.js',
- '<(DEPTH)/third_party/closure_compiler/externs/web_animations.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_network_icon_externs.js',
- '../options/options_bundle.js',
- # Note: ^ this is just a copy of
- # ../options/compiled_resources2.gyp:options_bundle#source_files. Most
- # of this code is deprecated, but please keep in sync if you really
- # need to change.
- 'channel_change_page.js',
- 'help_page.js',
- ],
- },
- 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
- }
- ],
-}
diff --git a/chromium/chrome/browser/resources/help/help.css b/chromium/chrome/browser/resources/help/help.css
deleted file mode 100644
index cf0080090fa..00000000000
--- a/chromium/chrome/browser/resources/help/help.css
+++ /dev/null
@@ -1,7 +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. */
-
-body {
- -webkit-user-select: text;
-}
diff --git a/chromium/chrome/browser/resources/help/help.html b/chromium/chrome/browser/resources/help/help.html
deleted file mode 100644
index 0124090e083..00000000000
--- a/chromium/chrome/browser/resources/help/help.html
+++ /dev/null
@@ -1,54 +0,0 @@
-<!doctype html>
-<html i18n-values="dir:textdirection;lang:language">
-<head>
- <meta charset="utf-8">
- <title>$i18n{aboutTitle}</title>
- <link rel="stylesheet" href="chrome://resources/css/chrome_shared.css">
- <link rel="stylesheet" href="../uber/uber_shared.css">
- <link rel="stylesheet" href="help.css">
- <link rel="stylesheet" href="help_content.css">
-<if expr="chromeos">
- <link rel="stylesheet" href="chrome://resources/css/bubble.css">
- <link rel="stylesheet" href="chrome://resources/css/overlay.css">
- <link rel="stylesheet" href="channel_change_page.css">
-</if>
-
- <script src="chrome://resources/js/action_link.js"></script>
- <script src="chrome://resources/js/cr.js"></script>
- <script src="chrome://resources/js/cr/event_target.js"></script>
- <script src="chrome://resources/js/load_time_data.js"></script>
- <script src="chrome://resources/js/util.js"></script>
- <script src="chrome://resources/js/cr/ui.js"></script>
- <script src="chrome://resources/js/cr/ui/focus_manager.js"></script>
- <script src="chrome://resources/js/cr/ui/focus_outline_manager.js"></script>
- <script src="chrome://resources/js/cr/ui/overlay.js"></script>
- <script src="chrome://resources/js/cr/ui/page_manager/page_manager.js"></script>
- <script src="chrome://resources/js/cr/ui/page_manager/page.js"></script>
-<if expr="chromeos">
- <script src="chrome://resources/js/cr/ui/bubble.js"></script>
- <script src="chrome://resources/js/event_tracker.js"></script>
- <script src="chrome://help-frame/channel_change_page.js"></script>
-</if>
- <script src="chrome://help-frame/help_page.js"></script>
- <script src="chrome://help-frame/help.js"></script>
-</head>
-<body class="uber-frame">
- <header>
- <h1>$i18n{aboutTitle}</h1>
- </header>
-<if expr="chromeos">
- <div id="overlay-container-1" class="overlay transparent" hidden>
- <include src="channel_change_page.html">
- </div>
-</if>
- <div id="mainview-content">
- <div id="page-container">
- <div id="help-page" class="page">
- <include src="help_content.html">
- </div>
- </div>
- </div>
-</body>
-<script src="chrome://help-frame/strings.js"></script>
-<script src="chrome://resources/js/i18n_template.js"></script>
-</html>
diff --git a/chromium/chrome/browser/resources/help/help.js b/chromium/chrome/browser/resources/help/help.js
deleted file mode 100644
index f03dcdee6b6..00000000000
--- a/chromium/chrome/browser/resources/help/help.js
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// <include src="../uber/uber_page_manager_observer.js">
-// <include src="../uber/uber_utils.js">
-
-(function() {
- var HelpPage = help.HelpPage;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * DOMContentLoaded handler, sets up the page.
- */
- function load() {
- PageManager.register(HelpPage.getInstance());
-
- if (help.ChannelChangePage) {
- PageManager.registerOverlay(help.ChannelChangePage.getInstance(),
- HelpPage.getInstance());
- }
- PageManager.addObserver(new uber.PageManagerObserver());
- PageManager.initialize(HelpPage.getInstance());
- uber.onContentFrameLoaded();
-
- var pageName = PageManager.getPageNameFromPath();
- // Still update history so that chrome://help/nonexistant redirects
- // appropriately to chrome://help/. If the URL matches, updateHistory
- // will avoid adding the extra state.
- var updateHistory = true;
- PageManager.showPageByName(pageName, updateHistory, {replaceState: true});
- }
-
- document.addEventListener('DOMContentLoaded', load);
-
- /**
- * Listener for the |beforeunload| event.
- */
- window.onbeforeunload = function() {
- PageManager.willClose();
- };
-
- /**
- * Listener for the |popstate| event.
- * @param {Event} e The |popstate| event.
- */
- window.onpopstate = function(e) {
- var pageName = PageManager.getPageNameFromPath();
- PageManager.setState(pageName, location.hash, e.state);
- };
-})();
diff --git a/chromium/chrome/browser/resources/help/help_content.css b/chromium/chrome/browser/resources/help/help_content.css
deleted file mode 100644
index 3bdd341077d..00000000000
--- a/chromium/chrome/browser/resources/help/help_content.css
+++ /dev/null
@@ -1,170 +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. */
-
-#about-container {
- align-items: center;
- display: flex;
-}
-
-#page-container #about-container {
- margin-top: 10px;
-}
-
-#product-description {
- -webkit-margin-start: 10px;
-}
-
-#version-container {
- margin-top: 30px;
-}
-
-#update-buttons-container {
- margin-top: 5px;
-}
-
-#update-status-container {
- margin-bottom: 12px;
- margin-top: 10px;
-}
-
-#update-status {
- vertical-align: middle;
-}
-
-#update-percentage {
- font-size: 90%;
-}
-
-#get-help,
-#promote {
- -webkit-margin-end: 4px;
-}
-
-#help-container {
- margin-top: 16px;
-}
-
-#product-container {
- line-height: 1.8em;
- margin-top: 200px;
-}
-
-.overlay #product-container {
- margin-top: 30px;
-}
-
-.help-page-icon {
- background-position: center;
- background-repeat: no-repeat;
- display: inline-block;
- height: 18px;
- vertical-align: middle;
- width: 18px;
-}
-
-#update-status-icon.up-to-date {
- background-image: url(../../../../ui/webui/resources/images/check_circle.svg);
- background-size: 18px;
-}
-
-#update-status-icon.working {
- background-image: url(chrome://resources/images/throbber_small.svg);
- background-size: 16px;
-}
-
-#update-status-icon.failed {
- background-image: url(chrome://resources/images/error.svg);
- background-size: 18px;
-}
-
-#update-status-icon.disabled-by-admin {
- background-image: url(../../../../ui/webui/resources/images/business.svg);
- background-size: 18px;
-}
-
-#controlled-feature-icon {
- background-image: url(../../../../ui/webui/resources/images/business.svg);
- background-size: 18px;
-}
-
-#eol-status-icon {
- background-image: url(../../../../ui/webui/resources/images/eol.svg);
- background-size: 18px;
-}
-
-#eol-status-container {
- margin-bottom: 12px;
- margin-top: 10px;
-}
-
-#eol-status-message-container {
- -webkit-margin-start: 8px;
- display: inline-block;
- vertical-align: middle;
-}
-
-#update-status-message-container {
- -webkit-margin-start: 8px;
- display: inline-block;
- vertical-align: middle;
-}
-
-#more-info-expander {
- -webkit-padding-start: 0;
- margin-top: 10px;
-}
-
-#more-info-container.visible {
- margin-bottom: 10px;
-}
-
-#more-info-container {
- height: 0;
- margin-bottom: 0;
- overflow: hidden;
- transition: all 200ms;
-}
-
-#build-date-container.empty {
- visibility: hidden;
-}
-
-#channel-change-confirmation {
- margin-top: 5px;
-}
-
-#change-channel {
- margin-top: 8px;
-}
-
-#channel-change-disallowed-icon,
-.channel-change-error-icon {
- -webkit-margin-start: 4px;
- background-image: url(../../../../ui/webui/resources/images/business.svg);
- background-size: 18px;
-}
-
-.channel-change-error-bubble {
- display: flex;
-}
-
-.channel-change-error-bubble .channel-change-error-icon {
- vertical-align: top;
-}
-
-.channel-change-error-text {
- -webkit-margin-start: 4px;
- display: block;
- vertical-align: top;
- width: 240px;
-}
-
-#regulatory-label-container {
- padding-top: 32px;
-}
-
-#regulatory-label {
- display: block;
- width: 330px;
-}
diff --git a/chromium/chrome/browser/resources/help/help_content.html b/chromium/chrome/browser/resources/help/help_content.html
deleted file mode 100644
index 1c82f60a893..00000000000
--- a/chromium/chrome/browser/resources/help/help_content.html
+++ /dev/null
@@ -1,134 +0,0 @@
- <div class="content-area">
- <div id="about-container">
- <img id="product-logo" srcset="chrome://theme/current-channel-logo@1x 1x,
- chrome://theme/current-channel-logo@2x 2x"
- alt="">
- <div id="product-description">
- <h2>$i18n{aboutProductTitle}</h2>
- <span>$i18n{aboutProductDescription}</span>
- </div>
- </div>
- <div id="help-container">
- <button id="get-help">$i18n{getHelpWithChrome}</button>
-<if expr="_google_chrome">
- <button id="report-issue">$i18n{reportAnIssue}</button>
-</if>
- </div>
- <div id="version-container">
- <div>
- <span dir="ltr">$i18n{browserVersion}</span>
- </div>
-<if expr="chromeos">
- <div>
- <span>$i18n{platform}</span>&nbsp;<span id="os-version"></span>
- </div>
- <div>
- <span>$i18n{arcVersion}</span>&nbsp;<span id="arc-version"></span>
- </div>
- <div>
- <span>$i18n{firmware}</span>&nbsp;<span id="firmware"></span>
- </div>
-</if>
-<if expr="chromeos or _google_chrome or is_linux">
- <div id="update-status-container" hidden>
- <div id="update-status-icon" class="help-page-icon up-to-date"></div>
- <div id="update-status-message-container">
- <div id="update-status-message">$i18n{updateCheckStarted}</div>
-<if expr="is_macosx or is_win">
- <div id="update-obsolete-system-container" hidden>
- <span id="update-obsolete-system">$i18n{updateObsoleteSystem}</span>
- <a i18n-values="href:updateObsoleteSystemURL" target="_blank">
- $i18n{learnMore}
- </a>
- </div>
-</if>
- <div id="allowed-connection-types-message" hidden></div>
- </div>
- </div>
-<if expr="chromeos">
- <div id="eol-status-container" hidden>
- <div id="eol-status-icon" class="help-page-icon"></div>
- <div id="eol-status-message-container">
- <div id="eol-message"></div>
- <div id="eol-learnMore">$i18n{eolLearnMore}</div>
- </div>
- </div>
-</if>
- <div id="update-buttons-container">
- <div id="update-percentage" hidden></div>
-<if expr="is_macosx">
- <button id="promote" hidden>$i18n{promote}</button>
-</if>
- <button id="relaunch" hidden>$i18n{relaunch}</button>
-<if expr="chromeos">
- <button id="relaunch-and-powerwash" hidden>
- $i18n{relaunchAndPowerwash}
- </button>
- <button id="request-update">$i18n{updateButton}</button>
- <div id="controlled-feature-icon" class="help-page-icon" hidden></div>
-</if>
- </div>
-</if>
-<if expr="chromeos">
- <div id="more-info-container">
- <section id="channel-changer-container" hidden>
- <h3>$i18n{channel}</h3>
- <select id="channel-changer">
- <option value="stable-channel">$i18n{stable}</option>
- <option value="beta-channel">$i18n{beta}</option>
- <option value="dev-channel">$i18n{dev}</option>
- </select>
- <div id="channel-change-confirmation" hidden></div>
- </section>
- <section id="channel-change-page-container" hidden>
- <h3>$i18n{channel}</h3>
- <div id="current-channel"></div>
- <div>
- <span id="dev-channel-disclaimer" hidden>
- $i18n{devChannelDisclaimer}
- </span>
- </div>
- <button id="change-channel" disabled>
- $i18n{channelChangeButton}
- </button>
- <div id="channel-change-disallowed-icon"
- class="help-page-icon" hidden>
- </div>
- </section>
- <section>
- <h3 dir="ltr">$i18n{jsEngine}</h3>
- <div>$i18n{jsEngineVersion}</div>
- </section>
- <section>
- <h3>$i18n{userAgent}</h3>
- <div dir="ltr">$i18n{userAgentInfo}</div>
- </section>
- <section>
- <h3>$i18n{commandLine}</h3>
- <div dir="ltr">$i18n{commandLineInfo}</div>
- </section>
- <section id="build-date-container" class="empty">
- <h3>$i18n{buildDate}</h3>
- <div id="build-date"></div>
- </section>
- </div>
- <a is="action-link" id="more-info-expander">$i18n{showMoreInfo}</a>
-</if>
- </div>
- <div id="product-container">
- <div>$i18n{productName}</div>
- <div>$i18n{productCopyright}</div>
- <div id="product-license"></div>
-<if expr="chromeos">
- <div id="product-os-license"></div>
-</if>
-<if expr="_google_chrome">
- <div id="product-tos"></div>
-</if>
- </div>
-<if expr="chromeos">
- <div id="regulatory-label-container" hidden>
- <img id="regulatory-label">
- </div>
-</if>
-</div>
diff --git a/chromium/chrome/browser/resources/help/help_page.html b/chromium/chrome/browser/resources/help/help_page.html
deleted file mode 100644
index 79dcb079461..00000000000
--- a/chromium/chrome/browser/resources/help/help_page.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<div id="help-page" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{aboutTitle}</h1>
- <include src="help_content.html">
- <div class="action-area">
- <div class="button-strip">
- <button id="about-done" class="default-button">$i18n{done}</button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/help/help_page.js b/chromium/chrome/browser/resources/help/help_page.js
deleted file mode 100644
index 977ce38fd76..00000000000
--- a/chromium/chrome/browser/resources/help/help_page.js
+++ /dev/null
@@ -1,785 +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.
-
-cr.define('help', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Encapsulated handling of the About page. Called 'help' internally to avoid
- * confusion with generic AboutUI (about:version, about:sandbox, etc.).
- */
- function HelpPage() {
- var id = loadTimeData.valueExists('aboutOverlayTabTitle') ?
- 'aboutOverlayTabTitle' : 'aboutTitle';
- Page.call(this, 'help', loadTimeData.getString(id), 'help-page');
- }
-
- cr.addSingletonGetter(HelpPage);
-
- HelpPage.prototype = {
- __proto__: Page.prototype,
-
- /**
- * List of the channel names. Should be ordered in increasing level of
- * stability.
- * @private
- */
- channelList_: ['dev-channel', 'beta-channel', 'stable-channel'],
-
- /**
- * Name of the channel the device is currently on.
- * @private
- */
- currentChannel_: null,
-
- /**
- * Name of the channel the device is supposed to be on.
- * @private
- */
- targetChannel_: null,
-
- /**
- * Last status received from the version updater.
- * @private
- */
- status_: null,
-
- /**
- * Last message received from the version updater.
- * @private
- */
- message_: null,
-
- /**
- * True if user is allowed to change channels, false otherwise.
- * @private
- */
- canChangeChannel_: false,
-
- /**
- * True if we have never checked for available updates.
- * @private
- */
- haveNeverCheckedForUpdates_: true,
-
- /**
- * Last EndofLife status received from the version updater.
- * @private
- */
- eolStatus_: null,
-
- /**
- * Last EndofLife message received from the version updater.
- * @private
- */
- eolMessage_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('product-license').innerHTML = loadTimeData.getString('productLicense');
- if (cr.isChromeOS) {
- $('product-os-license').innerHTML =
- loadTimeData.getString('productOsLicense');
- $('eol-learnMore').innerHTML = loadTimeData.getString('eolLearnMore');
- }
-
- var productTOS = $('product-tos');
- if (productTOS)
- productTOS.innerHTML = loadTimeData.getString('productTOS');
-
- $('get-help').onclick = function() {
- chrome.send('openHelpPage');
- };
-// <if expr="_google_chrome">
- $('report-issue').onclick = function() {
- chrome.send('openFeedbackDialog');
- };
-// </if>
-
- this.maybeSetOnClick_($('more-info-expander'),
- this.toggleMoreInfo_.bind(this));
-
- this.maybeSetOnClick_($('promote'), function() {
- chrome.send('promoteUpdater');
- });
- this.maybeSetOnClick_($('relaunch'), function() {
- chrome.send('relaunchNow');
- });
- if (cr.isChromeOS) {
- this.maybeSetOnClick_($('relaunch-and-powerwash'), function() {
- chrome.send('relaunchAndPowerwash');
- });
-
- this.channelTable_ = {
- 'stable-channel': {
- 'name': loadTimeData.getString('stable'),
- 'label': loadTimeData.getString('currentChannelStable'),
- },
- 'beta-channel': {
- 'name': loadTimeData.getString('beta'),
- 'label': loadTimeData.getString('currentChannelBeta')
- },
- 'dev-channel': {
- 'name': loadTimeData.getString('dev'),
- 'label': loadTimeData.getString('currentChannelDev')
- }
- };
- }
- this.maybeSetOnClick_($('about-done'), function() {
- // Event listener for the close button when shown as an overlay.
- PageManager.closeOverlay();
- });
-
- var self = this;
- var channelChanger = $('channel-changer');
- if (channelChanger) {
- channelChanger.onchange = function(event) {
- self.setChannel_(event.target.value, false);
- };
- }
-
- if (cr.isChromeOS) {
- // Add event listener for the check for and apply updates button.
- this.maybeSetOnClick_($('request-update'), function() {
- self.setUpdateStatus_('checking');
- $('request-update').disabled = true;
- chrome.send('requestUpdate');
- });
-
- $('change-channel').onclick = function() {
- PageManager.showPageByName('channel-change-page', false);
- };
-
- var channelChangeDisallowedError = document.createElement('div');
- channelChangeDisallowedError.className = 'channel-change-error-bubble';
-
- var channelChangeDisallowedIcon = document.createElement('div');
- channelChangeDisallowedIcon.className =
- 'help-page-icon channel-change-error-icon';
- channelChangeDisallowedError.appendChild(channelChangeDisallowedIcon);
-
- var channelChangeDisallowedText = document.createElement('div');
- channelChangeDisallowedText.className = 'channel-change-error-text';
- channelChangeDisallowedText.textContent =
- loadTimeData.getString('channelChangeDisallowedMessage');
- channelChangeDisallowedError.appendChild(channelChangeDisallowedText);
-
- $('channel-change-disallowed-icon').onclick = function() {
- PageManager.showBubble(channelChangeDisallowedError,
- $('channel-change-disallowed-icon'),
- $('help-container'),
- cr.ui.ArrowLocation.TOP_END);
- };
-
- // Unhide the regulatory label if/when the image loads.
- $('regulatory-label').onload = function() {
- $('regulatory-label-container').hidden = false;
- };
-
- $('controlled-feature-icon').onclick = function(e) {
- var content = /** @type {HTMLElement} */(
- document.createElement('div'));
- content.textContent =
- loadTimeData.getString('updateDisabledByPolicy');
- var bubble = new cr.ui.AutoCloseBubble;
- bubble.id = 'controlled-feature-bubble';
- bubble.anchorNode = $('controlled-feature-icon');
- bubble.domSibling = $('controlled-feature-icon');
- bubble.arrowLocation = cr.ui.ArrowLocation.TOP_END;
- bubble.content = content;
- bubble.show();
- };
- }
-
- var logo = $('product-logo');
- logo.onclick = function(e) {
- logo.animate({
- transform: ['none', 'rotate(-10turn)'],
- }, /** @type {!KeyframeEffectOptions} */({
- duration: 500,
- easing: 'cubic-bezier(1, 0, 0, 1)',
- }));
- };
-
- // Attempt to update.
- chrome.send('onPageLoaded');
- },
-
- /** @override */
- didClosePage: function() {
- this.setMoreInfoVisible_(false);
- },
-
- /**
- * Sets the visible state of the 'More Info' section.
- * @param {boolean} visible Whether the section should be visible.
- * @private
- */
- setMoreInfoVisible_: function(visible) {
- var moreInfo = $('more-info-container');
- if (!moreInfo || visible == moreInfo.classList.contains('visible'))
- return;
-
- moreInfo.classList.toggle('visible', visible);
- moreInfo.style.height = visible ? moreInfo.scrollHeight + 'px' : '';
- moreInfo.addEventListener('transitionend', function(event) {
- $('more-info-expander').textContent = visible ?
- loadTimeData.getString('hideMoreInfo') :
- loadTimeData.getString('showMoreInfo');
- });
- },
-
- /**
- * Toggles the visible state of the 'More Info' section.
- * @private
- */
- toggleMoreInfo_: function() {
- var moreInfo = $('more-info-container');
- this.setMoreInfoVisible_(!moreInfo.classList.contains('visible'));
- },
-
- /**
- * Assigns |method| to the onclick property of |el| if |el| exists.
- * @param {HTMLElement} el The element on which to set the click handler.
- * @param {Function} method The click handler.
- * @private
- */
- maybeSetOnClick_: function(el, method) {
- if (el)
- el.onclick = method;
- },
-
- /**
- * @param {string} state The state of the update.
- * private
- */
- setUpdateImage_: function(state) {
- $('update-status-icon').className = 'help-page-icon ' + state;
- },
-
- /**
- * @return {boolean} True, if new channel switcher UI is used,
- * false otherwise.
- * @private
- */
- isNewChannelSwitcherUI_: function() {
- return !loadTimeData.valueExists('disableNewChannelSwitcherUI');
- },
-
- /**
- * @return {boolean} True if target and current channels are not null and
- * not equal.
- * @private
- */
- channelsDiffer_: function() {
- var current = this.currentChannel_;
- var target = this.targetChannel_;
- return (current != null && target != null && current != target);
- },
-
- /**
- * @return {boolean} True if target channel is more stable than the current
- * one, and false otherwise.
- * @private
- */
- targetChannelIsMoreStable_: function() {
- var current = this.currentChannel_;
- var target = this.targetChannel_;
- if (current == null || target == null)
- return false;
- var currentIndex = this.channelList_.indexOf(current);
- var targetIndex = this.channelList_.indexOf(target);
- if (currentIndex < 0 || targetIndex < 0)
- return false;
- return currentIndex < targetIndex;
- },
-
- /**
- * @param {string} status The status of the update.
- * @param {string} message Failure message to display.
- * @private
- */
- setUpdateStatus_: function(status, message) {
- var oldStatus = this.status_;
- this.status_ = status;
-
- if (oldStatus != status && oldStatus == 'disabled_by_admin') {
- // If the auto update policy was recently re-enabled, then we'll
- // re-enable the 'request-update' button.
- this.haveNeverCheckedForUpdates_ = true;
- }
-
- if (status == 'checking')
- this.haveNeverCheckedForUpdates_ = false;
- this.message_ = message;
-
- this.updateUI_();
- },
-
- /**
- * @param {string} eolStatus The EndofLife status of the device.
- * @param {string} eolMessage The EndofLife message to display.
- * @private
- */
- updateEolMessage_: function(eolStatus, eolMessage) {
- this.eolStatus_ = eolStatus;
- this.eolMessage_ = eolMessage;
-
- this.updateUI_();
- },
-
- /**
- * Updates UI elements on the page according to current state.
- * @private
- */
- updateUI_: function() {
- var status = this.status_;
- var message = this.message_;
- var channel = this.targetChannel_;
- var eolStatus = this.eolStatus_;
- var eolMessage = this.eolMessage_;
-
- if (this.channelList_.indexOf(channel) >= 0) {
- $('current-channel').textContent = loadTimeData.getStringF(
- 'currentChannel', this.channelTable_[channel].label);
- this.updateChannelChangePageContainerVisibility_();
- if (cr.isChromeOS)
- $('dev-channel-disclaimer').hidden = (channel != 'dev-channel');
- }
-
- if (status == null)
- return;
-
- if (cr.isMac &&
- $('update-status-message') &&
- $('update-status-message').hidden) {
- // Chrome has reached the end of the line on this system. The
- // update-obsolete-system message is displayed. No other auto-update
- // status should be displayed.
- return;
- }
-
- if (status == 'checking') {
- this.setUpdateImage_('working');
- $('update-status-message').innerHTML =
- loadTimeData.getString('updateCheckStarted');
- } else if (status == 'updating') {
- this.setUpdateImage_('working');
- if (this.channelsDiffer_()) {
- $('update-status-message').innerHTML =
- loadTimeData.getStringF('updatingChannelSwitch',
- this.channelTable_[channel].label);
- } else {
- $('update-status-message').innerHTML =
- loadTimeData.getStringF('updating');
- }
- } else if (status == 'nearly_updated') {
- this.setUpdateImage_('up-to-date');
- if (this.channelsDiffer_()) {
- $('update-status-message').innerHTML =
- loadTimeData.getString('successfulChannelSwitch');
- } else {
- $('update-status-message').innerHTML =
- loadTimeData.getString('updateAlmostDone');
- }
- } else if (status == 'updated') {
- this.setUpdateImage_('up-to-date');
- $('update-status-message').innerHTML =
- loadTimeData.getString('upToDate');
- } else if (status == 'failed') {
- this.setUpdateImage_('failed');
- $('update-status-message').innerHTML = message;
- } else if (status == 'disabled_by_admin') {
- // This is the general behavior for non-chromeos.
- this.setUpdateImage_('disabled-by-admin');
- $('update-status-message').innerHTML = message;
- }
-
- // Show EndofLife Strings if applicable
- if (eolStatus == 'device_supported') {
- $('eol-status-container').hidden = true;
- } else if (eolStatus == 'device_endoflife') {
- $('eol-message').innerHTML = eolMessage;
- $('eol-status-container').hidden = false;
- }
-
-
- if (cr.isChromeOS) {
- $('change-channel').disabled = !this.canChangeChannel_ ||
- status == 'nearly_updated';
- $('channel-change-disallowed-icon').hidden = this.canChangeChannel_;
- }
-
- // Following invariant must be established at the end of this function:
- // { ~$('relaunch_and_powerwash').hidden -> $('relaunch').hidden }
- var relaunchAndPowerwashHidden = true;
- if ($('relaunch-and-powerwash')) {
- // It's allowed to do powerwash only for customer devices,
- // when user explicitly decides to update to a more stable
- // channel.
- relaunchAndPowerwashHidden =
- !this.targetChannelIsMoreStable_() || status != 'nearly_updated';
- $('relaunch-and-powerwash').hidden = relaunchAndPowerwashHidden;
- }
-
- if (cr.isChromeOS) {
- // Re-enable the update button if we are in a stale 'updated' status or
- // update has failed, and disable it if there's an update in progress or
- // updates are disabled by policy.
- // In addition, Update button will be disabled when device is in eol
- // status
- $('request-update').disabled =
- !((this.haveNeverCheckedForUpdates_ && status == 'updated') ||
- status == 'failed') || (eolStatus == 'device_endoflife');
- // If updates are disabled by policy, unhide the
- // controlled-feature-icon.
- $('controlled-feature-icon').hidden = (status != 'disabled_by_admin');
- // If updates are no longer disabled by policy and the tooltip bubble
- // is present, we hide it.
- if (status != 'disabled_by_admin' && $('controlled-feature-bubble'))
- $('controlled-feature-bubble').hide();
- }
-
- var container = $('update-status-container');
- if (container) {
- container.hidden = status == 'disabled';
- $('relaunch').hidden =
- (status != 'nearly_updated') || !relaunchAndPowerwashHidden;
-
- if (cr.isChromeOS) {
- // Assume the "updated" status is stale if we haven't checked yet.
- if (status == 'updated' && this.haveNeverCheckedForUpdates_ ||
- status == 'disabled_by_admin' ||
- eolStatus == 'device_endoflife') {
- container.hidden = true;
- }
-
- // Hide the request update button if auto-updating is disabled or
- // a relaunch button is showing.
- $('request-update').hidden = status == 'disabled' ||
- !$('relaunch').hidden || !relaunchAndPowerwashHidden;
- }
-
- if (!cr.isMac)
- $('update-percentage').hidden = status != 'updating';
- }
- },
-
- /**
- * @param {number} progress The percent completion.
- * @private
- */
- setProgress_: function(progress) {
- $('update-percentage').innerHTML = progress + '%';
- },
-
- /**
- * @param {string} message The allowed connection types message.
- * @private
- */
- setAllowedConnectionTypesMsg_: function(message) {
- $('allowed-connection-types-message').innerText = message;
- },
-
- /**
- * @param {boolean} visible Whether to show the message.
- * @private
- */
- showAllowedConnectionTypesMsg_: function(visible) {
- $('allowed-connection-types-message').hidden = !visible;
- },
-
- /**
- * @param {string} state The promote state to set.
- * @private
- */
- setPromotionState_: function(state) {
- if (state == 'hidden') {
- $('promote').hidden = true;
- } else if (state == 'enabled') {
- $('promote').disabled = false;
- $('promote').hidden = false;
- } else if (state == 'disabled') {
- $('promote').disabled = true;
- $('promote').hidden = false;
- }
- },
-
- /**
- * @param {boolean} obsolete Whether the system is obsolete.
- * @private
- */
- setObsoleteSystem_: function(obsolete) {
- if ($('update-obsolete-system-container')) {
- $('update-obsolete-system-container').hidden = !obsolete;
- }
- },
-
- /**
- * @param {boolean} endOfTheLine Whether the train has rolled into
- * the station.
- * @private
- */
- setObsoleteSystemEndOfTheLine_: function(endOfTheLine) {
- if ($('update-obsolete-system-container') &&
- !$('update-obsolete-system-container').hidden &&
- $('update-status-message')) {
- $('update-status-message').hidden = endOfTheLine;
- if (endOfTheLine) {
- this.setUpdateImage_('failed');
- }
- }
- },
-
- /**
- * @param {string} version Version of Chrome OS.
- * @private
- */
- setOSVersion_: function(version) {
- if (!cr.isChromeOS)
- console.error('OS version unsupported on non-CrOS');
-
- $('os-version').parentNode.hidden = (version == '');
- $('os-version').textContent = version;
- },
-
- /**
- * @param {string} version Version of ARC.
- * @private
- */
- setARCVersion_: function(version) {
- if (!cr.isChromeOS)
- console.error('ARC version unsupported on non-CrOS');
-
- $('arc-version').parentNode.hidden = (version == '');
- $('arc-version').textContent = version;
- },
-
- /**
- * @param {string} firmware Firmware on Chrome OS.
- * @private
- */
- setOSFirmware_: function(firmware) {
- if (!cr.isChromeOS)
- console.error('OS firmware unsupported on non-CrOS');
-
- $('firmware').parentNode.hidden = (firmware == '');
- $('firmware').textContent = firmware;
- },
-
- /**
- * Updates page UI according to device owhership policy.
- * @param {boolean} isEnterpriseManaged True if the device is
- * enterprise managed.
- * @private
- */
- updateIsEnterpriseManaged_: function(isEnterpriseManaged) {
- help.ChannelChangePage.updateIsEnterpriseManaged(isEnterpriseManaged);
- this.updateUI_();
- },
-
- /**
- * Updates name of the current channel, i.e. the name of the
- * channel the device is currently on.
- * @param {string} channel The name of the current channel.
- * @private
- */
- updateCurrentChannel_: function(channel) {
- if (this.channelList_.indexOf(channel) < 0)
- return;
- this.currentChannel_ = channel;
- help.ChannelChangePage.updateCurrentChannel(channel);
- this.updateUI_();
- },
-
- /**
- * Updates name of the target channel, i.e. the name of the
- * channel the device is supposed to be.
- * @param {string} channel The name of the target channel.
- * @private
- */
- updateTargetChannel_: function(channel) {
- if (this.channelList_.indexOf(channel) < 0)
- return;
- this.targetChannel_ = channel;
- help.ChannelChangePage.updateTargetChannel(channel);
- this.updateUI_();
- },
-
- /**
- * @param {boolean} enabled True if the release channel can be enabled.
- * @private
- */
- updateEnableReleaseChannel_: function(enabled) {
- this.updateChannelChangerContainerVisibility_(enabled);
- this.canChangeChannel_ = enabled;
- this.updateUI_();
- },
-
- /**
- * Sets the device target channel.
- * @param {string} channel The name of the target channel.
- * @param {boolean} isPowerwashAllowed True iff powerwash is allowed.
- * @private
- */
- setChannel_: function(channel, isPowerwashAllowed) {
- chrome.send('setChannel', [channel, isPowerwashAllowed]);
- $('channel-change-confirmation').hidden = false;
- $('channel-change-confirmation').textContent = loadTimeData.getStringF(
- 'channel-changed', this.channelTable_[channel].name);
- this.updateTargetChannel_(channel);
- },
-
- /**
- * Sets the value of the "Build Date" field of the "More Info" section.
- * @param {string} buildDate The date of the build.
- * @private
- */
- setBuildDate_: function(buildDate) {
- $('build-date-container').classList.remove('empty');
- $('build-date').textContent = buildDate;
- },
-
- /**
- * Updates channel-change-page-container visibility according to
- * internal state.
- * @private
- */
- updateChannelChangePageContainerVisibility_: function() {
- if (!this.isNewChannelSwitcherUI_()) {
- $('channel-change-page-container').hidden = true;
- return;
- }
- $('channel-change-page-container').hidden =
- !help.ChannelChangePage.isPageReady();
- },
-
- /**
- * Updates channel-changer dropdown visibility if |visible| is
- * true and new channel switcher UI is disallowed.
- * @param {boolean} visible True if channel-changer should be
- * displayed, false otherwise.
- * @private
- */
- updateChannelChangerContainerVisibility_: function(visible) {
- if (this.isNewChannelSwitcherUI_()) {
- $('channel-changer').hidden = true;
- return;
- }
- $('channel-changer').hidden = !visible;
- },
-
- /**
- * Sets the regulatory label's source.
- * @param {string} path The path to use for the image.
- * @private
- */
- setRegulatoryLabelPath_: function(path) {
- $('regulatory-label').src = path;
- },
-
- /**
- * Sets the regulatory label's alt text.
- * @param {string} text The text to use for the image.
- * @private
- */
- setRegulatoryLabelText_: function(text) {
- $('regulatory-label').alt = text;
- },
- };
-
- HelpPage.setUpdateStatus = function(status, message) {
- HelpPage.getInstance().setUpdateStatus_(status, message);
- };
-
- HelpPage.setProgress = function(progress) {
- HelpPage.getInstance().setProgress_(progress);
- };
-
- HelpPage.setAndShowAllowedConnectionTypesMsg = function(message) {
- HelpPage.getInstance().setAllowedConnectionTypesMsg_(message);
- HelpPage.getInstance().showAllowedConnectionTypesMsg_(true);
- };
-
- HelpPage.showAllowedConnectionTypesMsg = function(visible) {
- HelpPage.getInstance().showAllowedConnectionTypesMsg_(visible);
- };
-
- HelpPage.setPromotionState = function(state) {
- HelpPage.getInstance().setPromotionState_(state);
- };
-
- HelpPage.setObsoleteSystem = function(obsolete) {
- HelpPage.getInstance().setObsoleteSystem_(obsolete);
- };
-
- HelpPage.setObsoleteSystemEndOfTheLine = function(endOfTheLine) {
- HelpPage.getInstance().setObsoleteSystemEndOfTheLine_(endOfTheLine);
- };
-
- HelpPage.setOSVersion = function(version) {
- HelpPage.getInstance().setOSVersion_(version);
- };
-
- HelpPage.setARCVersion = function(version) {
- HelpPage.getInstance().setARCVersion_(version);
- };
-
- HelpPage.setOSFirmware = function(firmware) {
- HelpPage.getInstance().setOSFirmware_(firmware);
- };
-
- HelpPage.updateIsEnterpriseManaged = function(isEnterpriseManaged) {
- if (!cr.isChromeOS)
- return;
- HelpPage.getInstance().updateIsEnterpriseManaged_(isEnterpriseManaged);
- };
-
- HelpPage.updateCurrentChannel = function(channel) {
- if (!cr.isChromeOS)
- return;
- HelpPage.getInstance().updateCurrentChannel_(channel);
- };
-
- HelpPage.updateTargetChannel = function(channel) {
- if (!cr.isChromeOS)
- return;
- HelpPage.getInstance().updateTargetChannel_(channel);
- };
-
- HelpPage.updateEnableReleaseChannel = function(enabled) {
- HelpPage.getInstance().updateEnableReleaseChannel_(enabled);
- };
-
- HelpPage.setChannel = function(channel, isPowerwashAllowed) {
- HelpPage.getInstance().setChannel_(channel, isPowerwashAllowed);
- };
-
- HelpPage.setBuildDate = function(buildDate) {
- HelpPage.getInstance().setBuildDate_(buildDate);
- };
-
- HelpPage.setRegulatoryLabelPath = function(path) {
- assert(cr.isChromeOS);
- HelpPage.getInstance().setRegulatoryLabelPath_(path);
- };
-
- HelpPage.setRegulatoryLabelText = function(text) {
- assert(cr.isChromeOS);
- HelpPage.getInstance().setRegulatoryLabelText_(text);
- };
-
- HelpPage.updateEolMessage = function(eolStatus, eolMessage) {
- assert(cr.isChromeOS);
- HelpPage.getInstance().updateEolMessage_(eolStatus, eolMessage);
- };
-
- // Export
- return {
- HelpPage: HelpPage
- };
-});
diff --git a/chromium/chrome/browser/resources/identity_scope_approval_dialog/OWNERS b/chromium/chrome/browser/resources/identity_scope_approval_dialog/OWNERS
index bc8f8b8796d..5e319b181d7 100644
--- a/chromium/chrome/browser/resources/identity_scope_approval_dialog/OWNERS
+++ b/chromium/chrome/browser/resources/identity_scope_approval_dialog/OWNERS
@@ -1 +1,4 @@
+msarda@chromium.org
+
+# Original author, very slow on reviews as no longer working on Chromium.
courage@chromium.org
diff --git a/chromium/chrome/browser/resources/inspect/inspect.css b/chromium/chrome/browser/resources/inspect/inspect.css
index 8c3957b7ee6..13875de17a2 100644
--- a/chromium/chrome/browser/resources/inspect/inspect.css
+++ b/chromium/chrome/browser/resources/inspect/inspect.css
@@ -182,8 +182,7 @@ img {
}
.used-for-port-forwarding {
- background-image: -webkit-image-set(url(chrome://theme/IDR_INFO) 1x,
- url(chrome://theme/IDR_INFO@2x) 2x);
+ background-image: url(../../../../ui/webui/resources/images/info.svg);
height: 15px;
margin-left: 20px;
width: 15px;
diff --git a/chromium/chrome/browser/resources/local_ntp/googlemic_clr_24px.svg b/chromium/chrome/browser/resources/local_ntp/googlemic_clr_24px.svg
new file mode 100644
index 00000000000..9e18d9e33fe
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/googlemic_clr_24px.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
+ <path fill="none" d="M0 0h24v24H0z"/>
+ <path fill="#4285F4" d="M12 15c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v7c0 1.66 1.34 3 3 3z"/>
+ <path fill="#34A853" d="M11 18.92h2V22h-2z"/>
+ <path fill="#F4B400" d="M7 12H5c0 1.93.78 3.68 2.05 4.95l1.41-1.41C7.56 14.63 7 13.38 7 12z"/>
+ <path fill="#EA4335" d="M12 17c-1.38 0-2.63-.56-3.54-1.47l-1.41 1.41C8.32 18.21 10.07 19 12.01 19c3.87 0 6.98-3.14 6.98-7h-2c0 2.76-2.23 5-4.99 5z"/>
+</svg>
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.css b/chromium/chrome/browser/resources/local_ntp/local_ntp.css
index 1fa5dbe99ec..ce120114c42 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.css
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.css
@@ -2,6 +2,31 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
+html {
+ --column-count: 2;
+ --content-width: calc(
+ (var(--column-count) * (var(--tile-width) + var(--tile-margin)))
+ /* We add an extra pixel because rounding errors on different zooms can
+ * make the width shorter than it should be. */
+ + 1px);
+ --tile-margin: 16px;
+ --tile-width: 154px;
+}
+
+/* width >= (3 cols * (16px + 154px) - 16px + 200px) */
+@media (min-width: 694px) {
+ html {
+ --column-count: 3;
+ }
+}
+
+/* width >= (4 cols * (16px + 154px) - 16px + 200px) */
+@media (min-width: 864px) {
+ html {
+ --column-count: 4;
+ }
+}
+
/* TODO: Need to discuss with NTP folks before we remove font-family from the
* body tag. */
body {
@@ -14,13 +39,15 @@ body {
}
#ntp-contents {
+ margin: 0 auto;
text-align: -webkit-center;
+ width: var(--content-width);
}
.non-google-page #ntp-contents {
+ left: calc(50% - var(--content-width)/2);
position: absolute;
top: calc(50% - 155px);
- width: 100%;
}
body.hide-fakebox-logo #logo,
@@ -28,20 +55,33 @@ body.hide-fakebox-logo #fakebox {
visibility: hidden;
}
+#search {
+ margin: 0 calc(var(--tile-margin) / 2);
+ width: calc(100% - var(--tile-margin));
+}
+
#logo {
- background-image: url(../../../../ui/webui/resources/images/google_logo.svg);
- background-repeat: no-repeat;
- height: 92px;
+ height: 249px;
margin-bottom: 24px;
- margin-top: 157px;
- width: 272px;
+ position: relative;
}
.non-google-page #logo {
display: none;
}
-body.alternate-logo #logo {
+#logo-default {
+ background-image: url(../../../../ui/webui/resources/images/google_logo.svg);
+ background-repeat: no-repeat;
+ bottom: 0;
+ height: 92px;
+ left: calc(50% - 272px/2);
+ position: absolute;
+ transition: opacity 130ms;
+ width: 272px;
+}
+
+body.alternate-logo #logo-default {
-webkit-mask-image:
url(../../../../ui/webui/resources/images/google_logo.svg);
-webkit-mask-repeat: no-repeat;
@@ -61,8 +101,6 @@ body.alternate-logo #logo {
outline: none;
position: relative;
transition: box-shadow 200ms cubic-bezier(0.4, 0, 0.2, 1);
- /* #fakebox width is set dynamically from JS. */
- width: 300px;
}
.non-google-page #fakebox {
@@ -115,7 +153,7 @@ html[dir=rtl] #fakebox-text {
right: 13px;
}
-#cursor {
+#fakebox-cursor {
background: #333;
bottom: 12px;
left: 13px;
@@ -125,11 +163,27 @@ html[dir=rtl] #fakebox-text {
width: 1px;
}
-html[dir=rtl] #cursor {
+html[dir=rtl] #fakebox-cursor {
left: auto;
right: 13px;
}
+#fakebox-speech {
+ background: url(googlemic_clr_24px.svg) no-repeat center;
+ background-size: 24px 24px;
+ cursor: pointer;
+ height: 21px;
+ padding: 22px 12px 0;
+ position: absolute;
+ right: 0;
+ width: 17px;
+}
+
+html[dir=rtl] #fakebox-speech {
+ left: 0;
+ right: auto;
+}
+
@keyframes blink {
0% {
opacity: 1;
@@ -144,19 +198,19 @@ body.fakebox-focused #fakebox-text {
visibility: hidden;
}
-body.fakebox-drag-focused #cursor {
+body.fakebox-drag-focused #fakebox-cursor {
visibility: inherit;
}
-body.fakebox-focused #cursor {
+body.fakebox-focused #fakebox-cursor {
animation: blink 1.3s step-end infinite;
visibility: inherit;
}
#most-visited {
- -webkit-user-select: none;
margin-top: 64px;
text-align: -webkit-center;
+ user-select: none;
}
/* Non-Google pages have no Fakebox, so don't need top margin. */
@@ -253,7 +307,6 @@ html[dir=rtl] #mv-notice-x {
}
#attribution {
- -webkit-user-select: none;
bottom: 0;
color: #fff;
cursor: default;
@@ -263,6 +316,7 @@ html[dir=rtl] #mv-notice-x {
position: fixed;
right: 8px;
text-align: left;
+ user-select: none;
z-index: -1;
}
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.html b/chromium/chrome/browser/resources/local_ntp/local_ntp.html
index 8ca3d298743..5722d6c1f6c 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.html
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.html
@@ -6,10 +6,13 @@
<head>
<link rel="stylesheet" href="chrome-search://local-ntp/theme.css"></link>
<link rel="stylesheet" href="chrome-search://local-ntp/local-ntp.css"></link>
+ <link rel="stylesheet" href="chrome-search://local-ntp/voice.css"></link>
<script src="chrome-search://local-ntp/config.js"
{{CONFIG_INTEGRITY}}></script>
<script src="chrome-search://local-ntp/local-ntp.js"
{{LOCAL_NTP_INTEGRITY}}></script>
+ <script src="chrome-search://local-ntp/voice.js"
+ {{LOCAL_NTP_VOICE_INTEGRITY}}></script>
<meta charset="utf-8">
<meta name="google" value="notranslate">
</head>
@@ -18,12 +21,19 @@
<div id="one-google" class="hidden"></div>
<div id="ntp-contents">
- <div id="logo" title="Google"></div>
- <div id="fakebox">
- <div id="fakebox-text"></div>
- <input id="fakebox-input" autocomplete="off" tabIndex="-1" type="url"
- aria-hidden="true">
- <div id="cursor"></div>
+ <div id="search">
+ <!-- Container for the logo, whether default or doodle. -->
+ <div id="logo">
+ <!-- The logo that is displayed in the absence of a doodle. -->
+ <div id="logo-default" title="Google"></div>
+ </div>
+ <div id="fakebox">
+ <div id="fakebox-text"></div>
+ <input id="fakebox-input" autocomplete="off" tabIndex="-1" type="url"
+ aria-hidden="true">
+ <div id="fakebox-cursor"></div>
+ <div id="fakebox-speech" tabIndex="0" hidden></div>
+ </div>
</div>
<div id="most-visited">
<!-- The container for the tiles. The MV iframe goes in here. -->
@@ -42,6 +52,35 @@
<div id="attribution"><div id="attribution-text"></div></div>
</div>
+ <div id="voice-overlay" class="overlay-hidden" hidden>
+ <div id="voice-outer" class="outer">
+ <div class="inner-container">
+ <div id="voice-button-container" class="button-container">
+ <!-- The audio level animation. -->
+ <span id="voice-level" class="level"></span>
+ <!-- The microphone button. -->
+ <span id="voice-button" class="button">
+ <!-- The microphone icon (in CSS). -->
+ <div class="microphone">
+ <span class="receiver"></span>
+ <div class="wrapper">
+ <span class="stem"></span>
+ <span class="shell"></span>
+ </div>
+ </div>
+ </span>
+ </div>
+ <div class="text-container">
+ <!-- Low confidence text underneath high confidence text. -->
+ <span id="voice-text-i" class="voice-text"></span>
+ <!-- High confidence text on top of low confidence text. -->
+ <span id="voice-text-f" class="voice-text"></span>
+ </div>
+ </div>
+ </div>
+ <div id="voice-close-button" class="close-button">&times;</div>
+ </div>
+
<div id="one-google-end-of-body"></div>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.js b/chromium/chrome/browser/resources/local_ntp/local_ntp.js
index 3d0970971bb..2c3869364ab 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.js
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.js
@@ -31,24 +31,18 @@ function $(id) {
* Specifications for an NTP design (not comprehensive).
*
* numTitleLines: Number of lines to display in titles.
- * tileWidth: The width of each suggestion tile, in px.
- * tileMargin: Spacing between successive tiles, in px.
* titleColor: The 4-component color of title text.
* titleColorAgainstDark: The 4-component color of title text against a dark
* theme.
*
* @type {{
* numTitleLines: number,
- * tileWidth: number,
- * tileMargin: number,
* titleColor: string,
* titleColorAgainstDark: string,
* }}
*/
var NTP_DESIGN = {
numTitleLines: 1,
- tileWidth: 154,
- tileMargin: 16,
titleColor: [50, 50, 50, 255],
titleColorAgainstDark: [210, 210, 210, 255],
};
@@ -88,6 +82,7 @@ var IDS = {
FAKEBOX: 'fakebox',
FAKEBOX_INPUT: 'fakebox-input',
FAKEBOX_TEXT: 'fakebox-text',
+ FAKEBOX_SPEECH: 'fakebox-speech',
LOGO: 'logo',
NOTIFICATION: 'mv-notice',
NOTIFICATION_CLOSE_BUTTON: 'mv-notice-x',
@@ -119,14 +114,6 @@ var lastBlacklistedTile = null;
/**
- * Current number of tiles columns shown based on the window width, including
- * those that just contain filler.
- * @type {number}
- */
-var numColumnsShown = 0;
-
-
-/**
* The browser embeddedSearch.newTabPage object.
* @type {Object}
*/
@@ -137,27 +124,6 @@ var ntpApiHandle;
var MAX_NUM_TILES_TO_SHOW = 8;
-/** @type {number} @const */
-var MIN_NUM_COLUMNS = 2;
-
-
-/** @type {number} @const */
-var MAX_NUM_COLUMNS = 4;
-
-
-/** @type {number} @const */
-var NUM_ROWS = 2;
-
-
-/**
- * Minimum total padding to give to the left and right of the most visited
- * section. Used to determine how many tiles to show.
- * @type {number}
- * @const
- */
-var MIN_TOTAL_HORIZONTAL_PADDING = 200;
-
-
/**
* Heuristic to determine whether a theme should be considered to be dark, so
* the colors of various UI elements can be adjusted.
@@ -217,11 +183,34 @@ function renderTheme() {
/**
+ * Updates the OneGoogleBar (if it is loaded) based on the current theme.
+ * @private
+ */
+function renderOneGoogleBarTheme() {
+ if (!window.gbar) {
+ return;
+ }
+ try {
+ var oneGoogleBarApi = window.gbar.a;
+ var oneGoogleBarPromise = oneGoogleBarApi.bf();
+ oneGoogleBarPromise.then(function(oneGoogleBar) {
+ var isThemeDark = getIsThemeDark(ntpApiHandle.themeBackgroundInfo);
+ var setForegroundStyle = oneGoogleBar.pc.bind(oneGoogleBar);
+ setForegroundStyle(isThemeDark ? 1 : 0);
+ });
+ } catch (err) {
+ console.log('Failed setting OneGoogleBar theme:\n' + err);
+ }
+}
+
+
+/**
* Callback for embeddedSearch.newTabPage.onthemechange.
* @private
*/
function onThemeChange() {
renderTheme();
+ renderOneGoogleBarTheme();
}
@@ -338,7 +327,7 @@ function reloadTiles() {
for (var i = 0; i < Math.min(MAX_NUM_TILES_TO_SHOW, pages.length); ++i) {
cmds.push({cmd: 'tile', rid: pages[i].rid});
}
- cmds.push({cmd: 'show', maxVisible: numColumnsShown * NUM_ROWS});
+ cmds.push({cmd: 'show'});
$(IDS.TILES_IFRAME).contentWindow.postMessage(cmds, '*');
}
@@ -389,53 +378,6 @@ function onRestoreAll() {
/**
- * Recomputes the number of tile columns, and width of various contents based
- * on the width of the window.
- * @return {boolean} Whether the number of tile columns has changed.
- */
-function updateContentWidth() {
- var tileRequiredWidth = NTP_DESIGN.tileWidth + NTP_DESIGN.tileMargin;
- // If innerWidth is zero, then use the maximum snap size.
- var maxSnapSize = MAX_NUM_COLUMNS * tileRequiredWidth -
- NTP_DESIGN.tileMargin + MIN_TOTAL_HORIZONTAL_PADDING;
- var innerWidth = window.innerWidth || maxSnapSize;
- // Each tile has left and right margins that sum to NTP_DESIGN.tileMargin.
- var availableWidth = innerWidth + NTP_DESIGN.tileMargin -
- MIN_TOTAL_HORIZONTAL_PADDING;
- var newNumColumns = Math.floor(availableWidth / tileRequiredWidth);
- newNumColumns =
- Math.max(MIN_NUM_COLUMNS, Math.min(newNumColumns, MAX_NUM_COLUMNS));
-
- if (numColumnsShown === newNumColumns)
- return false;
-
- numColumnsShown = newNumColumns;
- // We add an extra pixel because rounding errors on different zooms can
- // make the width shorter than it should be.
- var tilesContainerWidth = Math.ceil(numColumnsShown * tileRequiredWidth) + 1;
- $(IDS.TILES).style.width = tilesContainerWidth + 'px';
- // -2 to account for border.
- var fakeboxWidth = (tilesContainerWidth - NTP_DESIGN.tileMargin - 2);
- $(IDS.FAKEBOX).style.width = fakeboxWidth + 'px';
- return true;
-}
-
-
-/**
- * Resizes elements because the number of tile columns may need to change in
- * response to resizing. Also shows or hides extra tiles tiles according to the
- * new width of the page.
- */
-function onResize() {
- if (updateContentWidth()) {
- // If the number of tile columns changes, inform the iframe.
- $(IDS.TILES_IFRAME).contentWindow.postMessage(
- {cmd: 'tilesVisible', maxVisible: numColumnsShown * NUM_ROWS}, '*');
- }
-}
-
-
-/**
* Callback for embeddedSearch.newTabPage.oninputstart. Handles new input by
* disposing the NTP, according to where the input was entered.
*/
@@ -485,7 +427,8 @@ function isFakeboxFocused() {
* @return {boolean} True if the click occurred in an enabled fakebox.
*/
function isFakeboxClick(event) {
- return $(IDS.FAKEBOX).contains(event.target);
+ return $(IDS.FAKEBOX).contains(event.target) &&
+ !$(IDS.FAKEBOX_SPEECH).contains(event.target);
}
@@ -556,9 +499,6 @@ function init() {
$(IDS.NOTIFICATION_CLOSE_BUTTON).addEventListener('click', hideNotification);
- window.addEventListener('resize', onResize);
- updateContentWidth();
-
var embeddedSearchApiHandle = window.chrome.embeddedSearch;
ntpApiHandle = embeddedSearchApiHandle.newTabPage;
@@ -579,6 +519,12 @@ function init() {
$(IDS.FAKEBOX_TEXT).textContent =
configData.translatedStrings.searchboxPlaceholder;
+ if (configData.isVoiceSearchEnabled) {
+ speech.init(
+ configData.googleBaseUrl, configData.translatedStrings,
+ $(IDS.FAKEBOX_SPEECH), searchboxApiHandle);
+ }
+
// Listener for updating the key capture state.
document.body.onmousedown = function(event) {
if (isFakeboxClick(event))
@@ -615,15 +561,13 @@ function init() {
// Update the fakebox style to match the current key capturing state.
setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);
- // Inject the OneGoogleBar loader script. It'll create a global variable
- // named "og" with the following fields:
- // .html - the main bar HTML.
- // .end_of_body_html - HTML to be inserted at the end of the body.
+ // Load the OneGoogleBar script. It'll create a global variable name "og"
+ // which is a dict corresponding to the native OneGoogleBarData type.
var ogScript = document.createElement('script');
ogScript.src = 'chrome-search://local-ntp/one-google.js';
document.body.appendChild(ogScript);
ogScript.onload = function() {
- injectOneGoogleBar(og.html, og.end_of_body_html);
+ injectOneGoogleBar(og);
};
} else {
document.body.classList.add(CLASSES.NON_GOOGLE_PAGE);
@@ -676,37 +620,34 @@ function listen() {
* Injects the One Google Bar into the page. Called asynchronously, so that it
* doesn't block the main page load.
*/
-function injectOneGoogleBar(barHtml, endOfBodyHtml) {
- var inHeadStyle = document.createElement('link');
- inHeadStyle.rel = "stylesheet";
- inHeadStyle.href = 'chrome-search://local-ntp/one-google/in-head.css';
+function injectOneGoogleBar(ogb) {
+ var inHeadStyle = document.createElement('style');
+ inHeadStyle.type = 'text/css';
+ inHeadStyle.appendChild(document.createTextNode(ogb.inHeadStyle));
document.head.appendChild(inHeadStyle);
- inHeadStyle.onload = function() {
- var inHeadScript = document.createElement('script');
- inHeadScript.src = 'chrome-search://local-ntp/one-google/in-head.js';
- document.head.appendChild(inHeadScript);
-
- inHeadScript.onload = function() {
- var ogElem = $('one-google');
- ogElem.innerHTML = barHtml;
- ogElem.classList.remove('hidden');
-
- var afterBarScript = document.createElement('script');
- afterBarScript.src =
- 'chrome-search://local-ntp/one-google/after-bar.js';
- ogElem.parentNode.insertBefore(afterBarScript, ogElem.nextSibling);
-
- afterBarScript.onload = function() {
- $('one-google-end-of-body').innerHTML = endOfBodyHtml;
-
- var endOfBodyScript = document.createElement('script');
- endOfBodyScript.src =
- 'chrome-search://local-ntp/one-google/end-of-body.js';
- document.body.appendChild(endOfBodyScript);
- };
- };
- };
+ var inHeadScript = document.createElement('script');
+ inHeadScript.type = 'text/javascript';
+ inHeadScript.appendChild(document.createTextNode(ogb.inHeadScript));
+ document.head.appendChild(inHeadScript);
+
+ renderOneGoogleBarTheme();
+
+ var ogElem = $('one-google');
+ ogElem.innerHTML = ogb.barHtml;
+ ogElem.classList.remove('hidden');
+
+ var afterBarScript = document.createElement('script');
+ afterBarScript.type = 'text/javascript';
+ afterBarScript.appendChild(document.createTextNode(ogb.afterBarScript));
+ ogElem.parentNode.insertBefore(afterBarScript, ogElem.nextSibling);
+
+ $('one-google-end-of-body').innerHTML = ogb.endOfBodyHtml;
+
+ var endOfBodyScript = document.createElement('script');
+ endOfBodyScript.type = 'text/javascript';
+ endOfBodyScript.appendChild(document.createTextNode(ogb.endOfBodyScript));
+ document.body.appendChild(endOfBodyScript);
}
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_iframe.css b/chromium/chrome/browser/resources/local_ntp/most_visited_iframe.css
index 89efb1e019d..471542c5d9a 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_iframe.css
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_iframe.css
@@ -2,10 +2,10 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
body {
- -webkit-user-select: none;
background: none transparent;
margin: 0;
overflow: hidden;
+ user-select: none;
}
a {
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_single.css b/chromium/chrome/browser/resources/local_ntp/most_visited_single.css
index 85b8c3d7db4..5035a1789e1 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.css
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.css
@@ -2,13 +2,20 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
+html {
+ --tile-height: 128px;
+ --tile-margin: 16px;
+ --tile-width: 154px;
+ --title-height: 32px;
+}
+
body {
- -webkit-user-select: none;
background: none transparent;
color: #323232;
margin: 0;
overflow: hidden;
padding: 0;
+ user-select: none;
}
a {
@@ -24,44 +31,68 @@ a:visited {
}
#most-visited {
- -webkit-user-select: none;
margin: 0;
text-align: -webkit-center;
+ user-select: none;
}
#mv-tiles,
.mv-tiles-old {
- -webkit-user-select: none;
font-size: 0;
/* Two rows of tiles of 128px each, and 16px of spacing between the rows.
* If you change this, also change the corresponding values in
* local_ntp.css. */
- height: calc(2*128px + 16px);
- line-height: calc(128px + 16px);
- margin: 4px 0 8px 0;
+ height: calc(2*var(--tile-height) + var(--tile-margin));
+ line-height: calc(var(--tile-height) + var(--tile-margin));
+ margin: 4px 0 calc(var(--tile-margin) / 2) 0;
opacity: 0;
position: absolute;
/* This align correctly for both LTR and RTL */
text-align: -webkit-auto;
transition: opacity 1s;
+ user-select: none;
}
.mv-tile,
.mv-empty-tile {
border-radius: 2px;
box-sizing: border-box;
- display: inline-block;
+ display: none;
font-family: arial, sans-serif;
font-size: 12px;
- height: 128px;
+ height: var(--tile-height);
line-height: 100%;
- margin: 0 8px;
+ margin: 0 calc(var(--tile-margin) / 2);
opacity: 1;
overflow: hidden;
position: relative;
vertical-align: top;
white-space: nowrap;
- width: 154px;
+ width: var(--tile-width);
+}
+
+/* Minimal layout: 2 columns; only first 4 tiles are visible. */
+.mv-tile:nth-child(-n+4),
+.mv-empty-tile:nth-child(-n+4) {
+ display: inline-block;
+}
+
+/* width >= (3 cols * (16px + 154px))
+ * 3 columns; first 6 tiles are visible. */
+@media (min-width: 510px) {
+ .mv-tile:nth-child(-n+6),
+ .mv-empty-tile:nth-child(-n+6) {
+ display: inline-block;
+ }
+}
+
+/* width >= (4 cols * (16px + 154px))
+ * 4 columns; first 8 tiles are visible. */
+@media (min-width: 680px) {
+ .mv-tile:nth-child(-n+8),
+ .mv-empty-tile:nth-child(-n+8) {
+ display: inline-block;
+ }
}
.mv-tile {
@@ -72,11 +103,6 @@ a:visited {
background: rgb(245,245,245);
}
-.mv-tile.hidden,
-.mv-empty-tile.hidden {
- display: none;
-}
-
.mv-tile {
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.16), 0 0 0 1px rgba(0,0,0,0.08);
cursor: pointer;
@@ -144,11 +170,11 @@ html[dir=rtl] .mv-title[style*='direction: rtl'] {
.mv-thumb {
cursor: pointer;
display: block;
- height: 96px;
+ height: calc(var(--tile-height) - var(--title-height));
overflow: hidden;
position: absolute;
- top: 32px;
- width: 154px;
+ top: var(--title-height);
+ width: var(--tile-width);
}
.mv-thumb img {
@@ -197,10 +223,10 @@ html[dir=rtl] .mv-title[style*='direction: rtl'] {
background-color: rgba(90,90,90,0.7);
content: '';
display: block;
- height: 32px;
+ height: var(--title-height);
position: absolute;
right: 0;
- width: 32px;
+ width: var(--title-height);
}
html[dir=rtl] .mv-x {
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_single.js b/chromium/chrome/browser/resources/local_ntp/most_visited_single.js
index 212538cfcc6..45e98035dc2 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.js
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.js
@@ -178,8 +178,6 @@ var handleCommand = function(data) {
showTiles(data);
} else if (cmd == 'updateTheme') {
updateTheme(data);
- } else if (cmd == 'tilesVisible') {
- hideOverflowTiles(data);
} else {
console.error('Unknown command: ' + JSON.stringify(data));
}
@@ -193,7 +191,6 @@ var handleCommand = function(data) {
var showTiles = function(info) {
logEvent(LOG_TYPE.NTP_ALL_TILES_RECEIVED);
countLoad();
- hideOverflowTiles(info);
};
@@ -241,19 +238,6 @@ var updateTheme = function(info) {
/**
- * Hides extra tiles that don't fit on screen. Called in response to the 'show'
- * and 'tilesVisible' messages from the host page.
- */
-var hideOverflowTiles = function(data) {
- var tileAndEmptyTileList =
- document.querySelectorAll('#mv-tiles .mv-tile,#mv-tiles .mv-empty-tile');
- for (var i = 0; i < tileAndEmptyTileList.length; ++i) {
- tileAndEmptyTileList[i].classList.toggle('hidden', i >= data.maxVisible);
- }
-};
-
-
-/**
* Removes all old instances of #mv-tiles that are pending for deletion.
*/
var removeAllOldTiles = function() {
diff --git a/chromium/chrome/browser/resources/local_ntp/voice.css b/chromium/chrome/browser/resources/local_ntp/voice.css
new file mode 100644
index 00000000000..37f783b1623
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/voice.css
@@ -0,0 +1,431 @@
+/* Copyright 2017 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file. */
+
+/* This template provides the styles used by the Speech feature. There is one UI
+ * used for on the local NTP: the Full Page UI ("overlay") that takes over the
+ * whole page.
+ *
+ * This mode also has a hidden and a visible state to allow for show and hide
+ * animations. As such, there are 2 different UIs, specified by different
+ * modifier classes (the class is applied to the Element with id=voice-overlay):
+ * - Hidden in the Full Page view (parent class: overlay-hidden).
+ * - Visible in the Full Page view (parent class: overlay).
+ *
+ * In addition, speech recognition can be in one of 5 different states that can
+ * manifest in each of the UIs (the corresponding class names are applied to the
+ * element with id=outer):
+ * - Listening for audio (parent class: voice-ml).
+ * - Receiving speech (parent class: voice-rs).
+ * - Error received (parent class: voice-er).
+ * - Inactive (no parent class).
+ *
+ * For details, see go/gws-speech-design and go/local-ntp-voice-search. */
+
+/* Color constants. */
+:root {
+ --dark_grey: #dbdbdb;
+ --dark_red: rgb(205, 0, 0);
+ --grey: #777;
+ --light_grey: #eee;
+ --light_red: rgb(255, 68, 68);
+
+ --active_icon_color: white;
+ --button_shadow: rgba(0, 0, 0, .1);
+ --inactive_icon_color: #999;
+ --listening_icon_color: var(--light_red);
+ --text_link_color: rgb(17, 85, 204);
+}
+
+/* The background element. */
+.overlay,
+.overlay-hidden {
+ background: white;
+ height: 100%;
+ left: 0;
+ opacity: 0;
+ overflow: hidden;
+ position: fixed;
+ text-align: left;
+ top: 0;
+ transition: visibility 0s linear 218ms, opacity 218ms,
+ background-color 218ms;
+ visibility: hidden;
+ width: 100%;
+ z-index: 10000;
+}
+
+/* Full Page visible style for the background element. */
+.overlay {
+ opacity: 1;
+ transition-delay: 0s;
+ visibility: visible;
+}
+
+/* The close 'x' button. */
+.close-button {
+ color: var(--grey);
+ cursor: pointer;
+ font-size: 26px;
+ height: 11px;
+ line-height: 15px;
+ margin: 15px;
+ opacity: .6;
+ padding: 0;
+ position: absolute;
+ right: 0;
+ top: 0;
+ width: 15px;
+}
+
+.close-button:hover {
+ opacity: .8;
+}
+
+.close-button:active {
+ opacity: 1;
+}
+
+/* The vertical positioning container. */
+.outer {
+ display: block;
+ height: 42px;
+ pointer-events: none;
+ position: absolute;
+}
+
+/* Full Page visible and hidden state of the positioning container. */
+.overlay .outer,
+.overlay-hidden .outer {
+ margin: auto;
+ margin-top: 312px;
+ max-width: 572px;
+ min-width: 534px;
+ padding: 0 223px;
+ position: relative;
+ top: 0;
+}
+
+/* Style for the inner container used for horizontal positioning. */
+.inner-container {
+ height: 100%;
+ opacity: .1;
+ pointer-events: none;
+ transition: opacity 318ms ease-in;
+ width: 100%;
+}
+
+.voice-ml .inner-container,
+.voice-rs .inner-container,
+.voice-er .inner-container {
+ opacity: 1;
+ transition: opacity 0s;
+}
+
+/* MICROPHONE BUTTON */
+/* Button with microphone icon in center from which pulses and vibrations
+ * emanate. */
+.button {
+ background-color: white;
+ border: 1px solid var(--light_grey);
+ border-radius: 100%;
+ bottom: 0;
+ box-shadow: 0 2px 5px var(--button_shadow);
+ cursor: pointer;
+ display: inline-block;
+ left: 0;
+ opacity: 0;
+ pointer-events: none;
+ position: absolute;
+ right: 0;
+ top: 0;
+ transition: background-color 218ms, border 218ms, box-shadow 218ms;
+}
+
+/* Button state when speech recognition is inactive. */
+.overlay-hidden .button {
+ opacity: 0;
+ pointer-events: none;
+ position: absolute;
+ transition-delay: 0;
+}
+
+/* Button state when speech recognition is active. */
+.overlay .button {
+ opacity: 1;
+ pointer-events: auto;
+ position: absolute;
+ transition-delay: 0;
+}
+
+/* Button state when speech input is being received by the microphone. */
+.voice-rs .button {
+ background-color: var(--light_red);
+ border: 0;
+ box-shadow: none;
+}
+
+/* Vibrating input volume level. */
+.level {
+ background-color: var(--dark_grey);
+ border-radius: 100%;
+ display: inline-block;
+ height: 301px;
+ left: -69px;
+ opacity: 1;
+ pointer-events: none;
+ position: absolute;
+ top: -69px;
+ transform: scale(.01);
+ transition: opacity 218ms;
+ width: 301px;
+}
+
+/* Container for scaling and positioning of the button. */
+.button-container {
+ float: right;
+ pointer-events: none;
+ position: relative;
+ transition: transform 218ms, opacity 218ms ease-in;
+}
+
+/* Common styles applied to the button-container. */
+.overlay .button-container,
+.overlay-hidden .button-container {
+ height: 165px;
+ right: -70px;
+ top: -70px;
+ width: 165px;
+}
+
+/* Container style when speech recognition is inactive. */
+.overlay-hidden .button-container {
+ transform: scale(.1);
+}
+
+/* Style applied to the button when clicked in the 'receiving audio' state. */
+.voice-rs .button:active {
+ background-color: var(--dark_red);
+}
+
+/* Style applied to the button when clicked. */
+.button:active {
+ background-color: var(--light_grey);
+}
+
+/* TEXT */
+/* Classes:
+ * - voice-text - Text area style class
+ * - voice-text-area - Link style class
+ * - voice-text-2l - 2 line style class
+ * - voice-text-3l - 3 line style class
+ * - voice-text-4l - 4 line style class
+ * - voice-text-5l - 5 line style class */
+
+/* Styles applied to the positioning text-container element. */
+.text-container {
+ pointer-events: none;
+}
+
+/* Full Page UI style for the text-container. */
+.overlay .text-container,
+.overlay-hidden .text-container {
+ position: absolute;
+}
+
+/* This class is used to specify the speech recognition text formatting. */
+.voice-text {
+ font-weight: normal;
+ line-height: 1.2;
+ opacity: 0;
+ pointer-events: none;
+ position: absolute;
+ text-align: left;
+ transition: opacity 100ms ease-in, margin-left 500ms ease-in,
+ top 0s linear 218ms;
+}
+
+/* Recognition results text hidden in the Full Page UI. */
+.overlay-hidden .voice-text {
+ margin-left: 44px;
+}
+
+/* Styles applied to the text output elements. Common style for the text area
+ * class for the full Page UI. To vertically center the text as longer queries
+ * are wrapped, the 'top' position is specified in em here and below. */
+.overlay .voice-text,
+.overlay-hidden .voice-text {
+ font-size: 32px;
+ left: -44px;
+ top: -.2em;
+ width: 460px;
+}
+
+/* Common style for when the text areas are made visible. */
+.overlay .voice-text {
+ margin-left: 0;
+ opacity: 1;
+ transition: opacity 500ms ease-out, margin-left 500ms ease-out;
+}
+
+/* Interim (low confidence) text. */
+#voice-text-i {
+ color: var(--grey);
+}
+
+/* Final (high confidence) text. */
+#voice-text-f {
+ color: black;
+}
+
+/* Text area links. */
+#voice-text-area {
+ color: var(--text_link_color);
+ cursor: pointer;
+ font-size: 18px;
+ font-weight: 500;
+ pointer-events: auto;
+ text-decoration: underline;
+}
+
+/* Range of motion for the typing animation. */
+@keyframes type {
+ from {
+ width: 0;
+ }
+ to {
+ width: 460px;
+ }
+}
+
+/* Style to simulate typing the "Listening..." text. */
+.listening-animation {
+ animation: type 900ms steps(30, end);
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+/* Styles applied to simulate vertical scrolling. Common webkit transition
+ * style for vertical text scrolling. */
+.voice-text-2l.voice-text,
+.voice-text-3l.voice-text,
+.voice-text-4l.voice-text {
+ transition: top 218ms ease-out;
+}
+
+/* When the text height is two lines. */
+.voice-text-2l.voice-text {
+ top: -.6em;
+}
+
+/* When the text height is three lines. */
+.voice-text-3l.voice-text {
+ top: -1.3em;
+}
+
+/* When the text height is four lines. */
+.voice-text-4l.voice-text {
+ top: -1.7em;
+}
+
+/* When the text height is more than five lines, shift the text up. */
+.voice-text-5l.voice-text {
+ top: -2.5em;
+}
+
+/* MICROPHONE ICON */
+/* The microphone icon is made up of 4 parts:
+ * - the audio receiver,
+ * - the shell that surrounds the lower half of the audio receiver,
+ * - the stem that holds up the shell and the audio receiver,
+ * - and a wrapper that positions the shell and stem.
+ *
+ * /===\
+ * | | <==== Audio receiver.
+ * | |
+ * \ \===/ / <== Shell.
+ * \_______/
+ * |
+ * | <====== Stem. */
+
+/* Container element for microphone icon. */
+.microphone {
+ height: 87px;
+ left: 43px;
+ pointer-events: none;
+ position: absolute;
+ top: 47px;
+ width: 42px;
+}
+
+/* Part 1 of CSS-only microphone icon: the audio receiver.
+ * Positioned in the center. */
+.receiver {
+ background-color: var(--inactive_icon_color);
+ border-radius: 30px;
+ height: 46px;
+ left: 25px;
+ pointer-events: none;
+ position: absolute;
+ width: 24px;
+}
+
+/* Part 2 of CSS-only microphone icon: the shell and stem wrapper element.
+ * Positioned below the audio receiver element. */
+.wrapper {
+ bottom: 0;
+ height: 53px;
+ left: 11px;
+ overflow: hidden;
+ pointer-events: none;
+ position: absolute;
+ width: 52px;
+}
+
+/* Part 3 of CSS-only microphone icon: the stem that supports the shell.
+ * Positioned below the audio receiver element and the shell element. */
+.stem {
+ background-color: var(--inactive_icon_color);
+ bottom: 14px;
+ height: 14px;
+ left: 22px;
+ pointer-events: none;
+ position: absolute;
+ width: 9px;
+ z-index: 1; /* z-index is only used to specify position relative to stem. */
+}
+
+/* Part 4 of CSS-only microphone icon: shell that holds the receiver.
+ * Positioned below the audio receiver element and above the stem element. */
+.shell {
+ border: 7px solid var(--inactive_icon_color);
+ border-radius: 28px;
+ bottom: 27px;
+ height: 57px;
+ pointer-events: none;
+ position: absolute;
+ width: 38px;
+ z-index: 0; /* z-index is only used to specify position relative to stem. */
+}
+
+/* The .voice-ml style is applied when the UI is in
+ * the 'listening for audio' state. */
+.voice-ml .receiver,
+.voice-ml .stem {
+ background-color: var(--listening_icon_color);
+}
+
+.voice-ml .shell {
+ border-color: var(--listening_icon_color);
+}
+
+/* The .voice-rs style is applied when the UI is in
+ * the 'receiving speech' state. */
+.voice-rs .receiver,
+.voice-rs .stem {
+ background-color: var(--active_icon_color);
+}
+
+.voice-rs .shell {
+ border-color: var(--active_icon_color);
+}
diff --git a/chromium/chrome/browser/resources/local_ntp/voice.js b/chromium/chrome/browser/resources/local_ntp/voice.js
new file mode 100644
index 00000000000..3e8623c89d5
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/voice.js
@@ -0,0 +1,1561 @@
+// 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.
+
+
+'use strict';
+
+
+/**
+ * Alias for document.getElementById.
+ * @param {string} id The ID of the element to find.
+ * @return {HTMLElement} The found element or null if not found.
+ */
+function $(id) {
+ // eslint-disable-next-line no-restricted-properties
+ return document.getElementById(id);
+}
+
+
+/**
+ * Get the preferred language for UI localization. Represents Chrome's UI
+ * language, which might not coincide with the user's "preferred" language
+ * in the Settings. For more details, see:
+ * - https://developer.mozilla.org/en/docs/Web/API/NavigatorLanguage/language
+ * - https://developer.mozilla.org/en/docs/Web/API/NavigatorLanguage/languages
+ *
+ * The returned value is a language version string as defined in
+ * <a href="http://www.ietf.org/rfc/bcp/bcp47.txt">BCP 47</a>.
+ * Examples: "en", "en-US", "cs-CZ", etc.
+ */
+function getChromeUILanguage() {
+ // In Chrome, |window.navigator.language| is not guaranteed to be equal to
+ // |window.navigator.languages[0]|.
+ return window.navigator.language;
+}
+
+
+/**
+ * Enum for keycodes.
+ * @enum {number}
+ * @const
+ */
+const KEYCODE = {
+ ENTER: 13,
+ ESC: 27,
+ PERIOD: 190
+};
+
+
+/**
+ * The set of possible recognition errors.
+ * @enum {number}
+ * @const
+ */
+const RecognitionError = {
+ NO_SPEECH: 0,
+ ABORTED: 1,
+ AUDIO_CAPTURE: 2,
+ NETWORK: 3,
+ NOT_ALLOWED: 4,
+ SERVICE_NOT_ALLOWED: 5,
+ BAD_GRAMMAR: 6,
+ LANGUAGE_NOT_SUPPORTED: 7,
+ NO_MATCH: 8,
+ OTHER: 9
+};
+
+
+/**
+ * Provides methods for communicating with the <a
+ * href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API">
+ * Web Speech API</a>, error handling and executing search queries.
+ */
+let speech = {};
+
+
+/**
+ * Localized translations for messages used in the Speech UI.
+ * @type {{
+ * audioError: string,
+ * details: string,
+ * languageError: string,
+ * learnMore: string,
+ * listening: string,
+ * networkError: string,
+ * noTranslation: string,
+ * noVoice: string,
+ * permissionError: string,
+ * ready: string,
+ * tryAgain: string,
+ * waiting: string
+ * }}
+ */
+speech.messages = {
+ audioError: '',
+ details: '',
+ languageError: '',
+ learnMore: '',
+ listening: '',
+ networkError: '',
+ noTranslation: '',
+ noVoice: '',
+ permissionError: '',
+ ready: '',
+ tryAgain: '',
+ waiting: ''
+};
+
+
+/**
+ * The set of controller states.
+ * @enum {number}
+ * @private
+ */
+speech.State_ = {
+ // Initial state of the controller. Is never re-entered.
+ // The only state from which the |speech.init()| method can be called.
+ // The UI overlay is hidden, recognition is inactive.
+ UNINITIALIZED: -1,
+ // Represents a ready to be activated state. If voice search is unsuccessful
+ // for any reason, the controller will return to this state
+ // using |speech.reset_()|. The UI overlay is hidden, recognition is inactive.
+ READY: 0,
+ // Indicates that speech recognition has started, but no audio has yet
+ // been captured. The UI overlay is visible, recognition is active.
+ STARTED: 1,
+ // Indicates that audio is being captured by the Web Speech API, but no
+ // speech has yet been recognized. The UI overlay is visible and indicating
+ // that audio is being captured, recognition is active.
+ AUDIO_RECEIVED: 2,
+ // Represents a state where speech has been recognized by the Web Speech API,
+ // but no resulting transcripts have yet been received back. The UI overlay is
+ // visible and indicating that audio is being captured, recognition is active.
+ SPEECH_RECEIVED: 3,
+ // Controller state where speech has been successfully recognized and text
+ // transcripts have been reported back. The UI overlay is visible
+ // and displaying intermediate results, recognition is active.
+ // This state remains until recognition ends successfully or due to an error.
+ RESULT_RECEIVED: 4,
+ // Indicates that speech recognition has failed due to an error
+ // (or a no match error) being received from the Web Speech API.
+ // A timeout may have occurred as well. The UI overlay is visible
+ // and displaying an error message, recognition is inactive.
+ ERROR_RECEIVED: 5,
+ // Represents a state where speech recognition has been stopped
+ // (either on success or failure) and the UI has not yet reset/redirected.
+ // The UI overlay is displaying results or an error message with a timeout,
+ // after which the site will either get redirected to search results
+ // (successful) or back to the NTP by hiding the overlay (unsuccessful).
+ STOPPED: 6
+};
+
+
+/**
+ * Threshold for considering an interim speech transcript result as "confident
+ * enough". The more confident the API is about a transcript, the higher the
+ * confidence (number between 0 and 1).
+ * @private {number}
+ * @const
+ */
+speech.RECOGNITION_CONFIDENCE_THRESHOLD_ = 0.5;
+
+/**
+ * Time in milliseconds to wait before closing the UI after an error has
+ * occured. This is a short timeout used when no click-target is present.
+ * @private {number}
+ * @const
+ */
+speech.ERROR_TIMEOUT_SHORT_MS_ = 3000;
+
+
+/**
+ * Time in milliseconds to wait before closing the UI after an error has
+ * occured. This is a longer timeout used when there is a click-target is
+ * present.
+ * @private {number}
+ * @const
+ */
+speech.ERROR_TIMEOUT_LONG_MS_ = 8000;
+
+
+/**
+ * Time in milliseconds to wait before closing the UI if no interaction has
+ * occured.
+ * @private {number}
+ * @const
+ */
+speech.IDLE_TIMEOUT_MS_ = 8000;
+
+
+/**
+ * Maximum number of characters recognized before force-submitting a query.
+ * Includes characters of non-confident recognition transcripts.
+ * @private {number}
+ * @const
+ */
+speech.QUERY_LENGTH_LIMIT_ = 120;
+
+
+/**
+ * Specifies the current state of the controller.
+ * Note: Different than the UI state.
+ * @private {speech.State_}
+ */
+speech.currentState_ = speech.State_.UNINITIALIZED;
+
+
+/**
+ * The ID for the error timer.
+ * @private {number}
+ */
+speech.errorTimer_;
+
+
+/**
+ * The duration of the timeout for the UI elements during an error state.
+ * Depending on the error state, we have different durations for the timeout.
+ * @private {number}
+ */
+speech.errorTimeoutMs_ = 0;
+
+
+/**
+ * The last high confidence voice transcript received from the Web Speech API.
+ * This is the actual query that could potentially be submitted to Search.
+ * @private {string}
+ */
+speech.finalResult_;
+
+
+/**
+ * Base URL for sending queries to Search. Includes trailing forward slash.
+ * @private {string}
+ */
+speech.googleBaseUrl_;
+
+
+/**
+ * The ID for the idle timer.
+ * @private {number}
+ */
+speech.idleTimer_;
+
+
+/**
+ * The last low confidence voice transcript received from the Web Speech API.
+ * @private {string}
+ */
+speech.interimResult_;
+
+
+/**
+ * The Web Speech API object driving the speech recognition transaction.
+ * @private {!webkitSpeechRecognition}
+ */
+speech.recognition_;
+
+
+/**
+ * Initialize the speech module as part of the local NTP. Adds event handlers
+ * and shows the fakebox speech microphone icon.
+ * @param {!string} googleBaseUrl Base URL for sending queries to Search.
+ * @param {!Object} translatedStrings Dictionary of localized string messages.
+ * @param {!HTMLElement} fakeboxMicrophoneElem Fakebox microphone icon element.
+ * @param {!Object} searchboxApiHandle SearchBox API handle.
+ */
+speech.init = function(
+ googleBaseUrl, translatedStrings, fakeboxMicrophoneElem,
+ searchboxApiHandle) {
+ if (speech.currentState_ != speech.State_.UNINITIALIZED) {
+ throw new Error(
+ 'Trying to re-initialize speech when not in UNINITIALIZED state.');
+ }
+
+ // Initialize event handlers.
+ fakeboxMicrophoneElem.hidden = false;
+ fakeboxMicrophoneElem.title = translatedStrings.fakeboxMicrophoneTooltip;
+ fakeboxMicrophoneElem.onmouseup = function(event) {
+ // If propagated, closes the overlay (click on the background).
+ event.stopPropagation();
+ speech.toggleStartStop();
+ };
+ window.addEventListener('keydown', speech.onKeyDown);
+ if (searchboxApiHandle.onfocuschange) {
+ throw new Error('OnFocusChange handler already set on searchbox.');
+ }
+ searchboxApiHandle.onfocuschange = speech.onOmniboxFocused;
+
+ // Initialize speech internal state.
+ speech.googleBaseUrl_ = googleBaseUrl;
+ speech.messages = {
+ audioError: translatedStrings.audioError,
+ details: translatedStrings.details,
+ languageError: translatedStrings.languageError,
+ learnMore: translatedStrings.learnMore,
+ listening: translatedStrings.listening,
+ networkError: translatedStrings.networkError,
+ noTranslation: translatedStrings.noTranslation,
+ noVoice: translatedStrings.noVoice,
+ permissionError: translatedStrings.permissionError,
+ ready: translatedStrings.ready,
+ tryAgain: translatedStrings.tryAgain,
+ waiting: translatedStrings.waiting,
+ };
+ view.init(speech.onClick_);
+ speech.initWebkitSpeech_();
+ speech.reset_();
+};
+
+
+/**
+ * Resets the internal state of Voice Search and disables the speech
+ * recognition interface. Only used for testing.
+ * @param {HTMLElement} fakeboxMicrophoneElem Fakebox microphone icon element.
+ * @param {!Object} searchboxApiHandle SearchBox API handle.
+ * @private
+ */
+speech.uninit_ = function(fakeboxMicrophoneElem, searchboxApiHandle) {
+ speech.reset_();
+ speech.googleBaseUrl_ = null;
+ speech.messages = {};
+ speech.currentState_ = speech.State_.UNINITIALIZED;
+ fakeboxMicrophoneElem.hidden = true;
+ fakeboxMicrophoneElem.title = '';
+ fakeboxMicrophoneElem.onmouseup = null;
+ window.removeEventListener('keydown', speech.onKeyDown);
+ searchboxApiHandle.onfocuschange = null;
+ speech.recognition_ = null;
+};
+
+
+/**
+ * Initializes and configures the speech recognition API.
+ * @private
+ */
+speech.initWebkitSpeech_ = function() {
+ speech.recognition_ = new webkitSpeechRecognition();
+ speech.recognition_.continuous = false;
+ speech.recognition_.interimResults = true;
+ speech.recognition_.lang = getChromeUILanguage();
+ speech.recognition_.maxAlternatives = 4;
+ speech.recognition_.onaudiostart = speech.handleRecognitionAudioStart_;
+ speech.recognition_.onend = speech.handleRecognitionEnd_;
+ speech.recognition_.onerror = speech.handleRecognitionError_;
+ speech.recognition_.onnomatch = speech.handleRecognitionOnNoMatch_;
+ speech.recognition_.onresult = speech.handleRecognitionResult_;
+ speech.recognition_.onspeechstart = speech.handleRecognitionSpeechStart_;
+};
+
+
+/**
+ * Sets up the necessary states for voice search and then starts the
+ * speech recognition interface.
+ * @private
+ */
+speech.start_ = function() {
+ view.show();
+
+ speech.resetIdleTimer_(speech.IDLE_TIMEOUT_MS_);
+
+ document.addEventListener(
+ 'webkitvisibilitychange', speech.onVisibilityChange_, false);
+
+ if (!speech.isRecognitionInitialized_()) {
+ speech.initWebkitSpeech_();
+ }
+
+ // If |speech.start_()| is called too soon after |speech.stop_()| then the
+ // recognition interface hasn't yet reset and an error occurs. In this case
+ // we need to hard-reset it and reissue the |recognition_.start()| command.
+ // TODO(oskopek): Add tests + possibly fix the root cause.
+ try {
+ speech.recognition_.start();
+ speech.currentState_ = speech.State_.STARTED;
+ } catch (error) {
+ speech.initWebkitSpeech_();
+ try {
+ speech.recognition_.start();
+ speech.currentState_ = speech.State_.STARTED;
+ } catch (error2) {
+ speech.currentState_ = speech.State_.STOPPED;
+ speech.stop_();
+ }
+ }
+};
+
+
+/**
+ * Hides the overlay and resets the speech state.
+ * @private
+ */
+speech.stop_ = function() {
+ speech.currentState_ = speech.State_.STOPPED;
+ view.hide();
+ speech.reset_();
+};
+
+
+/**
+ * Aborts speech recognition and calls |speech.stop_()|.
+ * @private
+ */
+speech.abort_ = function() {
+ speech.recognition_.abort();
+ speech.stop_();
+};
+
+
+/**
+ * Resets the internal state to the READY state.
+ * @private
+ */
+speech.reset_ = function() {
+ window.clearTimeout(speech.idleTimer_);
+ window.clearTimeout(speech.errorTimer_);
+
+ document.removeEventListener(
+ 'webkitvisibilitychange', speech.onVisibilityChange_, false);
+
+ speech.interimResult_ = '';
+ speech.finalResult_ = '';
+ speech.currentState_ = speech.State_.READY;
+};
+
+
+/**
+ * Informs the view that the browser is receiving audio input.
+ * @param {Event=} opt_event Emitted event for audio start.
+ * @private
+ */
+speech.handleRecognitionAudioStart_ = function(opt_event) {
+ speech.resetIdleTimer_(speech.IDLE_TIMEOUT_MS_);
+ speech.currentState_ = speech.State_.AUDIO_RECEIVED;
+ view.setReadyForSpeech();
+};
+
+
+/**
+ * Function is called when the user starts speaking.
+ * @param {Event=} opt_event Emitted event for speech start.
+ * @private
+ */
+speech.handleRecognitionSpeechStart_ = function(opt_event) {
+ speech.resetIdleTimer_(speech.IDLE_TIMEOUT_MS_);
+ speech.currentState_ = speech.State_.SPEECH_RECEIVED;
+ view.setReceivingSpeech();
+};
+
+
+/**
+ * Processes the recognition results arriving from the Web Speech API.
+ * @param {SpeechRecognitionEvent} responseEvent Event coming from the API.
+ * @private
+ */
+speech.handleRecognitionResult_ = function(responseEvent) {
+ speech.resetIdleTimer_(speech.IDLE_TIMEOUT_MS_);
+
+ switch (speech.currentState_) {
+ case speech.State_.RESULT_RECEIVED:
+ case speech.State_.SPEECH_RECEIVED:
+ // Normal, expected states for processing results.
+ break;
+ case speech.State_.AUDIO_RECEIVED:
+ // Network bugginess (the onaudiostart packet was lost).
+ speech.handleRecognitionSpeechStart_();
+ break;
+ case speech.State_.STARTED:
+ // Network bugginess (the onspeechstart packet was lost).
+ speech.handleRecognitionAudioStart_();
+ speech.handleRecognitionSpeechStart_();
+ break;
+ default:
+ // Not expecting results in any other states.
+ return;
+ }
+
+ const results = responseEvent.results;
+ if (results.length == 0) {
+ return;
+ }
+ speech.currentState_ = speech.State_.RESULT_RECEIVED;
+ speech.interimResult_ = '';
+ speech.finalResult_ = '';
+
+ const finalResult = results[responseEvent.resultIndex];
+ // Process final results.
+ if (finalResult.isFinal) {
+ speech.finalResult_ = finalResult[0].transcript;
+ view.updateSpeechResult(speech.finalResult_, speech.finalResult_);
+
+ speech.submitFinalResult_();
+ return;
+ }
+
+ // Process interim results.
+ for (let j = 0; j < results.length; j++) {
+ const result = results[j][0];
+ speech.interimResult_ += result.transcript;
+ if (result.confidence > speech.RECOGNITION_CONFIDENCE_THRESHOLD_) {
+ speech.finalResult_ += result.transcript;
+ }
+ }
+ view.updateSpeechResult(speech.interimResult_, speech.finalResult_);
+
+ // Force-stop long queries.
+ if (speech.interimResult_.length > speech.QUERY_LENGTH_LIMIT_) {
+ if (!!speech.finalResult_) {
+ speech.submitFinalResult_();
+ } else {
+ speech.onErrorReceived_(RecognitionError.NO_MATCH);
+ }
+ }
+};
+
+
+/**
+ * Handles state transition for the controller when an error occurs
+ * during speech recognition.
+ * @param {RecognitionError} error The appropriate error state from
+ * the RecognitionError enum.
+ * @private
+ */
+speech.onErrorReceived_ = function(error) {
+ speech.resetIdleTimer_(speech.IDLE_TIMEOUT_MS_);
+ speech.errorTimeoutMs_ = speech.getRecognitionErrorTimeout_(error);
+ if (error != RecognitionError.ABORTED) {
+ speech.currentState_ = speech.State_.ERROR_RECEIVED;
+ view.showError(error);
+ window.clearTimeout(speech.idleTimer_);
+ speech.resetErrorTimer_(speech.errorTimeoutMs_);
+ }
+};
+
+
+/**
+ * Called when an error from Web Speech API is received.
+ * @param {SpeechRecognitionError} error The error event.
+ * @private
+ */
+speech.handleRecognitionError_ = function(error) {
+ speech.onErrorReceived_(speech.getRecognitionError_(error.error));
+};
+
+
+/**
+ * Stops speech recognition when no matches are found.
+ * @private
+ */
+speech.handleRecognitionOnNoMatch_ = function() {
+ speech.onErrorReceived_(RecognitionError.NO_MATCH);
+};
+
+
+/**
+ * Stops the UI when the Web Speech API reports that it has halted speech
+ * recognition.
+ * @private
+ */
+speech.handleRecognitionEnd_ = function() {
+ window.clearTimeout(speech.idleTimer_);
+ window.clearTimeout(speech.permissionTimer_);
+
+ let error;
+ switch (speech.currentState_) {
+ case speech.State_.STARTED:
+ error = RecognitionError.AUDIO_CAPTURE;
+ break;
+ case speech.State_.AUDIO_RECEIVED:
+ error = RecognitionError.NO_SPEECH;
+ break;
+ case speech.State_.SPEECH_RECEIVED:
+ case speech.State_.RESULT_RECEIVED:
+ error = RecognitionError.NO_MATCH;
+ break;
+ case speech.State_.ERROR_RECEIVED:
+ error = RecognitionError.OTHER;
+ break;
+ default:
+ return;
+ }
+
+ // If error has not yet been displayed.
+ if (speech.currentState_ != speech.State_.ERROR_RECEIVED) {
+ view.showError(error);
+ speech.resetErrorTimer_(speech.ERROR_TIMEOUT_LONG_MS_);
+ }
+ speech.currentState_ = speech.State_.STOPPED;
+};
+
+
+/**
+ * Handles the following keyboard actions.
+ * - <CTRL> + <SHIFT> + <.> starts voice input(<CMD> + <SHIFT> + <.> on mac).
+ * - <ESC> aborts voice input when the recognition interface is active.
+ * - <ENTER> submits the speech query if there is one.
+ * @param {KeyboardEvent} event The keydown event.
+ */
+speech.onKeyDown = function(event) {
+ function isUserAgentMac(userAgent) {
+ return userAgent.includes('Macintosh');
+ }
+
+ if (!speech.isRecognizing_()) {
+ const ctrlKeyPressed = event.ctrlKey ||
+ (isUserAgentMac(window.navigator.userAgent) && event.metaKey);
+ if (speech.currentState_ == speech.State_.READY &&
+ event.keyCode == KEYCODE.PERIOD && event.shiftKey && ctrlKeyPressed) {
+ speech.toggleStartStop();
+ }
+ } else {
+ // Ensures that keyboard events are not propagated during voice input.
+ event.stopPropagation();
+ if (event.keyCode == KEYCODE.ESC) {
+ speech.abort_();
+ } else if (event.keyCode == KEYCODE.ENTER && speech.finalResult_) {
+ speech.submitFinalResult_();
+ }
+ }
+};
+
+
+/**
+ * Stops the recognition interface and closes the UI if no interactions occur
+ * after some time and the interface is still active. This is a safety net in
+ * case the recognition.onend event doesn't fire, as is sometime the case. If
+ * a high confidence transcription was received then show the search results.
+ * @private
+ */
+speech.onIdleTimeout_ = function() {
+ if (!!speech.finalResult_) {
+ speech.submitFinalResult_();
+ return;
+ }
+
+ switch (speech.currentState_) {
+ case speech.State_.STARTED:
+ case speech.State_.AUDIO_RECEIVED:
+ case speech.State_.SPEECH_RECEIVED:
+ case speech.State_.RESULT_RECEIVED:
+ case speech.State_.ERROR_RECEIVED:
+ speech.abort_();
+ break;
+ }
+};
+
+
+/**
+ * Aborts the speech recognition interface when the user switches to a new
+ * tab or window.
+ * @private
+ */
+speech.onVisibilityChange_ = function() {
+ if (speech.isUiDefinitelyHidden_()) {
+ return;
+ }
+
+ if (document.webkitHidden) {
+ speech.abort_();
+ }
+};
+
+
+/**
+ * Aborts the speech session if the UI is showing and omnibox gets focused.
+ */
+speech.onOmniboxFocused = function() {
+ if (!speech.isUiDefinitelyHidden_()) {
+ speech.abort_();
+ }
+};
+
+
+/**
+ * Submits the final spoken speech query to perform a search.
+ * @private
+ */
+speech.submitFinalResult_ = function() {
+ window.clearTimeout(speech.idleTimer_);
+
+ if (!speech.finalResult_) {
+ throw new Error('Submitting empty query.');
+ }
+
+ // Getting |speech.finalResult_| needs to happen before stopping speech.
+ const encodedQuery =
+ encodeURIComponent(speech.finalResult_).replace(/%20/g, '+');
+ const queryUrl = speech.googleBaseUrl_ +
+ // Add the actual query.
+ 'search?q=' + encodedQuery +
+ // Add a parameter to indicate that this request is a voice search.
+ '&gs_ivs=1';
+
+ speech.stop_();
+ window.location.href = queryUrl;
+};
+
+
+/**
+ * Returns the error type based on the error string received from the webkit
+ * speech recognition API.
+ * @param {string} error The error string received from the webkit speech
+ * recognition API.
+ * @return {RecognitionError} The appropriate error state from
+ * the RecognitionError enum.
+ * @private
+ */
+speech.getRecognitionError_ = function(error) {
+ switch (error) {
+ case 'aborted':
+ return RecognitionError.ABORTED;
+ case 'audio-capture':
+ return RecognitionError.AUDIO_CAPTURE;
+ case 'bad-grammar':
+ return RecognitionError.BAD_GRAMMAR;
+ case 'language-not-supported':
+ return RecognitionError.LANGUAGE_NOT_SUPPORTED;
+ case 'network':
+ return RecognitionError.NETWORK;
+ case 'no-speech':
+ return RecognitionError.NO_SPEECH;
+ case 'not-allowed':
+ return RecognitionError.NOT_ALLOWED;
+ case 'service-not-allowed':
+ return RecognitionError.SERVICE_NOT_ALLOWED;
+ default:
+ return RecognitionError.OTHER;
+ }
+};
+
+/**
+ * Returns a timeout based on the error received from the webkit speech
+ * recognition API.
+ * @param {RecognitionError} error An error from the RecognitionError enum.
+ * @return {number} The appropriate timeout duration for displaying the error.
+ * @private
+ */
+speech.getRecognitionErrorTimeout_ = function(error) {
+ switch (error) {
+ case RecognitionError.AUDIO_CAPTURE:
+ case RecognitionError.NO_SPEECH:
+ case RecognitionError.NOT_ALLOWED:
+ case RecognitionError.SERVICE_NOT_ALLOWED:
+ case RecognitionError.NO_MATCH:
+ return speech.ERROR_TIMEOUT_LONG_MS_;
+ default:
+ return speech.ERROR_TIMEOUT_SHORT_MS_;
+ }
+};
+
+
+/**
+ * Resets the idle state timeout.
+ * @param {number} duration The duration after which to close the UI.
+ * @private
+ */
+speech.resetIdleTimer_ = function(duration) {
+ window.clearTimeout(speech.idleTimer_);
+ speech.idleTimer_ = window.setTimeout(speech.onIdleTimeout_, duration);
+};
+
+
+/**
+ * Resets the idle error state timeout.
+ * @param {number} duration The duration after which to close the UI during an
+ * error state.
+ * @private
+ */
+speech.resetErrorTimer_ = function(duration) {
+ window.clearTimeout(speech.errorTimer_);
+ speech.errorTimer_ = window.setTimeout(speech.stop_, duration);
+};
+
+
+/**
+ * Check to see if the speech recognition interface is running.
+ * @return {boolean} True, if the speech recognition interface is running.
+ * @private
+ */
+speech.isRecognizing_ = function() {
+ switch (speech.currentState_) {
+ case speech.State_.STARTED:
+ case speech.State_.AUDIO_RECEIVED:
+ case speech.State_.SPEECH_RECEIVED:
+ case speech.State_.RESULT_RECEIVED:
+ return true;
+ }
+ return false;
+};
+
+
+/**
+ * Check if the controller is in a state where the UI is definitely hidden.
+ * Since we show the UI for a few seconds after we receive an error from the
+ * API, we need a separate definition to |speech.isRecognizing_()| to indicate
+ * when the UI is hidden. <strong>Note:</strong> that if this function
+ * returns false, it might not necessarily mean that the UI is visible.
+ * @return {boolean} True if the UI is hidden.
+ * @private
+ */
+speech.isUiDefinitelyHidden_ = function() {
+ switch (speech.currentState_) {
+ case speech.State_.READY:
+ case speech.State_.UNINITIALIZED:
+ return true;
+ }
+ return false;
+};
+
+
+/**
+ * Check if the Web Speech API is initialized and event functions are set.
+ * @return {boolean} True if recognition is initialized.
+ * @private
+ */
+speech.isRecognitionInitialized_ = function() {
+ // TODO(oskopek): Do handlers of |recognition_| get reset? Verify and test.
+ return !!speech.recognition_;
+};
+
+
+/**
+ * Toggles starting and stopping of speech recognition by the speech tool.
+ */
+speech.toggleStartStop = function() {
+ if (speech.currentState_ == speech.State_.READY) {
+ speech.start_();
+ } else {
+ speech.abort_();
+ }
+};
+
+
+/**
+ * Handles click events during speech recognition.
+ * @param {boolean} shouldSubmit True if a query should be submitted.
+ * @param {boolean} shouldRetry True if the interface should be restarted.
+ * @private
+ */
+speech.onClick_ = function(shouldSubmit, shouldRetry) {
+ if (speech.finalResult_ && shouldSubmit) {
+ speech.submitFinalResult_();
+ } else if (speech.currentState_ == speech.State_.STOPPED && shouldRetry) {
+ speech.restart();
+ } else {
+ speech.abort_();
+ }
+};
+
+/**
+ * Restarts voice recognition. Used for the 'Try again' error link.
+ * @private
+ */
+speech.restart = function() {
+ speech.reset_();
+ speech.toggleStartStop();
+};
+
+
+/* TEXT VIEW */
+/**
+ * Provides methods for styling and animating the text areas
+ * left of the microphone button.
+ */
+let text = {};
+
+
+/**
+ * ID for the link shown in error output.
+ * @const
+ */
+text.ERROR_LINK_ID = 'voice-text-area';
+
+
+/**
+ * Class name for the speech recognition result output area.
+ * @const @private
+ */
+text.TEXT_AREA_CLASS_ = 'voice-text';
+
+/**
+ * Class name for the "Listening..." text animation.
+ * @const @private
+ */
+text.LISTENING_ANIMATION_CLASS_ = 'listening-animation';
+
+
+/**
+ * ID of the final / high confidence speech recognition results element.
+ * @const @private
+ */
+text.FINAL_TEXT_AREA_ID_ = 'voice-text-f';
+
+
+/**
+ * ID of the interim / low confidence speech recognition results element.
+ * @const @private
+ */
+text.INTERIM_TEXT_AREA_ID_ = 'voice-text-i';
+
+
+/**
+ * The line height of the speech recognition results text.
+ * @const @private
+ */
+text.LINE_HEIGHT_ = 1.2;
+
+
+/**
+ * Font size in the full page view in pixels.
+ * @const @private
+ */
+text.FONT_SIZE_ = 32;
+
+
+/**
+ * Delay in milliseconds before showing the initializing message.
+ * @const @private
+ */
+text.INITIALIZING_TIMEOUT_MS_ = 300;
+
+
+/**
+ * Delay in milliseconds before showing the listening message.
+ * @const @private
+ */
+text.LISTENING_TIMEOUT_MS_ = 2000;
+
+
+/**
+ * The final / high confidence speech recognition result element.
+ * @private {Element}
+ */
+text.final_;
+
+
+/**
+ * The interim / low confidence speech recognition result element.
+ * @private {Element}
+ */
+text.interim_;
+
+
+/**
+ * Stores the ID of the initializing message timer.
+ * @private {number}
+ */
+text.initializingTimer_;
+
+
+/**
+ * Stores the ID of the listening message timer.
+ * @private {number}
+ */
+text.listeningTimer_;
+
+
+/**
+ * Base link target for help regarding voice search. To be appended
+ * with a locale string for proper target site localization.
+ * @const @private
+ */
+text.SUPPORT_LINK_BASE_ =
+ 'https://support.google.com/chrome/?p=ui_voice_search&hl=';
+
+
+/**
+ * Finds the text view elements.
+ */
+text.init = function() {
+ text.final_ = $(text.FINAL_TEXT_AREA_ID_);
+ text.interim_ = $(text.INTERIM_TEXT_AREA_ID_);
+ text.clear();
+};
+
+
+/**
+ * Updates the text elements with new recognition results.
+ * @param {string} interimText Low confidence speech recognition result text.
+ * @param {string} opt_finalText High confidence speech recognition result text,
+ * defaults to an empty string.
+ */
+text.updateTextArea = function(interimText, opt_finalText) {
+ const finalText = opt_finalText || '';
+
+ window.clearTimeout(text.initializingTimer_);
+ text.cancelListeningTimeout();
+
+ text.interim_.textContent = interimText;
+ text.final_.textContent = finalText;
+
+ text.interim_.className = text.final_.className = text.getTextClassName_();
+};
+
+
+/**
+ * Sets the text view to the initializing state.
+ */
+text.showInitializingMessage = function() {
+ const displayMessage = function() {
+ if (text.interim_.innerText == '') {
+ text.updateTextArea(speech.messages.waiting);
+ }
+ };
+
+ text.interim_.textContent = '';
+ text.final_.textContent = '';
+
+ // We give the interface some time to get the permission. Once permission
+ // is obtained, the ready message is displayed, in which case the
+ // initializing message won't be shown.
+ text.initializingTimer_ =
+ window.setTimeout(displayMessage, text.INITIALIZING_TIMEOUT_MS_);
+};
+
+
+/**
+ * Sets the text view to the ready state.
+ */
+text.showReadyMessage = function() {
+ window.clearTimeout(text.initializingTimer_);
+ text.updateTextArea(speech.messages.ready);
+ text.startListeningMessageAnimation_();
+};
+
+
+/**
+ * @param {RecognitionError} error The error that occured.
+ */
+text.showErrorMessage = function(error) {
+ text.updateTextArea(text.getErrorMessage_(error));
+
+ const linkElement = text.getErrorLink_(error);
+ // Setting textContent removes all children (no need to clear link elements).
+ if (!!linkElement) {
+ text.interim_.textContent += ' ';
+ text.interim_.appendChild(linkElement);
+ }
+};
+
+
+/**
+ * Returns an error message based on the error.
+ * @param {RecognitionError} error The error that occured.
+ * @private
+ */
+text.getErrorMessage_ = function(error) {
+ switch (error) {
+ case RecognitionError.NO_MATCH:
+ return speech.messages.noTranslation;
+ case RecognitionError.NO_SPEECH:
+ return speech.messages.noVoice;
+ case RecognitionError.AUDIO_CAPTURE:
+ return speech.messages.audioError;
+ case RecognitionError.NETWORK:
+ return speech.messages.networkError;
+ case RecognitionError.NOT_ALLOWED:
+ case RecognitionError.SERVICE_NOT_ALLOWED:
+ return speech.messages.permissionError;
+ case RecognitionError.LANGUAGE_NOT_SUPPORTED:
+ return speech.messages.languageError;
+ default:
+ throw new Error('Illegal RecognitionError value: ' + error);
+ }
+};
+
+
+/**
+ * Returns an error message help link based on the error.
+ * @param {RecognitionError} error The error that occured.
+ * @private
+ */
+text.getErrorLink_ = function(error) {
+ let linkElement = document.createElement('a');
+ linkElement.id = text.ERROR_LINK_ID;
+
+ switch (error) {
+ case RecognitionError.NO_MATCH:
+ linkElement.textContent = speech.messages.tryAgain;
+ linkElement.onclick = speech.restart;
+ return linkElement;
+ case RecognitionError.NO_SPEECH:
+ case RecognitionError.AUDIO_CAPTURE:
+ linkElement.href = text.SUPPORT_LINK_BASE_ + getChromeUILanguage();
+ linkElement.textContent = speech.messages.learnMore;
+ linkElement.target = '_blank';
+ return linkElement;
+ case RecognitionError.NOT_ALLOWED:
+ case RecognitionError.SERVICE_NOT_ALLOWED:
+ linkElement.href = text.SUPPORT_LINK_BASE_ + getChromeUILanguage();
+ linkElement.textContent = speech.messages.details;
+ linkElement.target = '_blank';
+ return linkElement;
+ default:
+ return null;
+ }
+};
+
+
+/**
+ * Clears the text elements.
+ */
+text.clear = function() {
+ text.cancelListeningTimeout();
+ window.clearTimeout(text.initializingTimer_);
+
+ text.interim_.className = text.TEXT_AREA_CLASS_;
+ text.final_.className = text.TEXT_AREA_CLASS_;
+};
+
+
+/**
+ * Cancels listening message display.
+ */
+text.cancelListeningTimeout = function() {
+ window.clearTimeout(text.listeningTimer_);
+};
+
+
+/**
+ * Determines the class name of the text output Elements.
+ * @return {string} The class name.
+ * @private
+ */
+text.getTextClassName_ = function() {
+ // Shift up for every line.
+ const oneLineHeight = text.LINE_HEIGHT_ * text.FONT_SIZE_ + 1;
+ const twoLineHeight = text.LINE_HEIGHT_ * text.FONT_SIZE_ * 2 + 1;
+ const threeLineHeight = text.LINE_HEIGHT_ * text.FONT_SIZE_ * 3 + 1;
+ const fourLineHeight = text.LINE_HEIGHT_ * text.FONT_SIZE_ * 4 + 1;
+
+ const height = text.interim_.scrollHeight;
+ let className = text.TEXT_AREA_CLASS_;
+
+ if (height > fourLineHeight) {
+ className += ' voice-text-5l';
+ } else if (height > threeLineHeight) {
+ className += ' voice-text-4l';
+ } else if (height > twoLineHeight) {
+ className += ' voice-text-3l';
+ } else if (height > oneLineHeight) {
+ className += ' voice-text-2l';
+ }
+ return className;
+};
+
+
+/**
+ * Displays the listening message animation after the ready message has been
+ * shown for |text.LISTENING_TIMEOUT_MS_| milliseconds without further user
+ * action.
+ * @private
+ */
+text.startListeningMessageAnimation_ = function() {
+ const animateListeningText = function() {
+ if (text.interim_.innerText == speech.messages.ready) {
+ text.updateTextArea(speech.messages.listening);
+ text.interim_.classList.add(text.LISTENING_ANIMATION_CLASS_);
+ }
+ };
+
+ text.listeningTimer_ =
+ window.setTimeout(animateListeningText, text.LISTENING_TIMEOUT_MS_);
+};
+/* END TEXT VIEW */
+
+
+/* MICROPHONE VIEW */
+/**
+ * Provides methods for animating the microphone button and icon
+ * on the Voice Search full screen overlay.
+ */
+let microphone = {};
+
+
+/**
+ * ID for the button Element.
+ * @const
+ */
+microphone.RED_BUTTON_ID = 'voice-button';
+
+
+/**
+ * ID for the level animations Element that indicates input volume.
+ * @const @private
+ */
+microphone.LEVEL_ID_ = 'voice-level';
+
+
+/**
+ * ID for the container of the microphone, red button and level animations.
+ * @const @private
+ */
+microphone.CONTAINER_ID_ = 'voice-button-container';
+
+
+/**
+ * The minimum transform scale for the volume rings.
+ * @const @private
+ */
+microphone.LEVEL_SCALE_MINIMUM_ = 0.5;
+
+
+/**
+ * The range of the transform scale for the volume rings.
+ * @const @private
+ */
+microphone.LEVEL_SCALE_RANGE_ = 0.55;
+
+
+/**
+ * The minimum transition time (in milliseconds) for the volume rings.
+ * @const @private
+ */
+microphone.LEVEL_TIME_STEP_MINIMUM_ = 170;
+
+
+/**
+ * The range of the transition time for the volume rings.
+ * @const @private
+ */
+microphone.LEVEL_TIME_STEP_RANGE_ = 10;
+
+
+/**
+ * The button with the microphone icon.
+ * @private {Element}
+ */
+microphone.button_;
+
+
+/**
+ * The voice level element that is displayed when the user starts speaking.
+ * @private {Element}
+ */
+microphone.level_;
+
+
+/**
+ * Variable to indicate whether level animations are underway.
+ * @private {boolean}
+ */
+microphone.isLevelAnimating_ = false;
+
+
+/**
+ * Creates/finds the output elements for the microphone rendering and animation.
+ */
+microphone.init = function() {
+ // Get the button element and microphone container.
+ microphone.button_ = $(microphone.RED_BUTTON_ID);
+
+ // Get the animation elements.
+ microphone.level_ = $(microphone.LEVEL_ID_);
+};
+
+
+/**
+ * Starts the volume circles animations.
+ */
+microphone.startInputAnimation = function() {
+ if (!microphone.isLevelAnimating_) {
+ microphone.isLevelAnimating_ = true;
+ microphone.runLevelAnimation_();
+ }
+};
+
+
+/**
+ * Stops the volume circles animations.
+ */
+microphone.stopInputAnimation = function() {
+ microphone.isLevelAnimating_ = false;
+};
+
+
+/**
+ * Runs the volume level animation.
+ * @private
+ */
+microphone.runLevelAnimation_ = function() {
+ if (!microphone.isLevelAnimating_) {
+ microphone.level_.style.removeProperty('opacity');
+ microphone.level_.style.removeProperty('transition');
+ microphone.level_.style.removeProperty('transform');
+ return;
+ }
+ const scale = microphone.LEVEL_SCALE_MINIMUM_ +
+ Math.random() * microphone.LEVEL_SCALE_RANGE_;
+ const timeStep = Math.round(
+ microphone.LEVEL_TIME_STEP_MINIMUM_ +
+ Math.random() * microphone.LEVEL_TIME_STEP_RANGE_);
+ microphone.level_.style.setProperty(
+ 'transition', 'transform ' + timeStep + 'ms ease-in-out');
+ microphone.level_.style.setProperty('transform', 'scale(' + scale + ')');
+ window.setTimeout(microphone.runLevelAnimation_, timeStep);
+};
+/* END MICROPHONE VIEW */
+
+
+/* VIEW */
+/**
+ * Provides methods for manipulating and animating the Voice Search
+ * full screen overlay.
+ */
+let view = {};
+
+
+/**
+ * Class name of the speech recognition interface on the homepage.
+ * @const @private
+ */
+view.OVERLAY_CLASS_ = 'overlay';
+
+
+/**
+ * Class name of the speech recognition interface when it is hidden on the
+ * homepage.
+ * @const @private
+ */
+view.OVERLAY_HIDDEN_CLASS_ = 'overlay-hidden';
+
+
+/**
+ * ID for the speech output background.
+ * @const @private
+ */
+view.BACKGROUND_ID_ = 'voice-overlay';
+
+
+/**
+ * ID of the close (x) button.
+ * @const @private
+ */
+view.CLOSE_BUTTON_ID_ = 'voice-close-button';
+
+
+/**
+ * ID for the speech output container.
+ * @const @private
+ */
+view.CONTAINER_ID_ = 'voice-outer';
+
+
+/**
+ * Class name used to modify the UI to the 'listening' state.
+ * @const @private
+ */
+view.MICROPHONE_LISTENING_CLASS_ = 'outer voice-ml';
+
+
+/**
+ * Class name used to modify the UI to the 'receiving speech' state.
+ * @const @private
+ */
+view.RECEIVING_SPEECH_CLASS_ = 'outer voice-rs';
+
+
+/**
+ * Class name used to modify the UI to the 'error received' state.
+ * @const @private
+ */
+view.ERROR_RECEIVED_CLASS_ = 'outer voice-er';
+
+
+/**
+ * Class name used to modify the UI to the inactive state.
+ * @const @private
+ */
+view.INACTIVE_CLASS_ = 'outer';
+
+
+/**
+ * Background element and container of all other elements.
+ * @private {Element}
+ */
+view.background_;
+
+
+/**
+ * The container used to position the microphone and text output area.
+ * @private {Element}
+ */
+view.container_;
+
+
+/**
+ * True if the the last error message shown was for the 'no-match' error.
+ * @private {boolean}
+ */
+view.isNoMatchShown_ = false;
+
+
+/**
+ * True if the UI elements are visible.
+ * @private {boolean}
+ */
+view.isVisible_ = false;
+
+
+/**
+ * The function to call when there is a click event.
+ * @private {Function}
+ */
+view.onClick_;
+
+
+/**
+ * Displays the UI.
+ */
+view.show = function() {
+ if (!view.isVisible_) {
+ text.showInitializingMessage();
+ view.showView_();
+ window.addEventListener('mouseup', view.onWindowClick_, false);
+ }
+};
+
+/**
+ * Sets the output area text to listening. This should only be called when
+ * the Web Speech API is receiving audio input (i.e., onaudiostart).
+ */
+view.setReadyForSpeech = function() {
+ if (view.isVisible_) {
+ view.container_.className = view.MICROPHONE_LISTENING_CLASS_;
+ text.showReadyMessage();
+ }
+};
+
+
+/**
+ * Shows the pulsing animation emanating from the microphone. This should only
+ * be called when the Web Speech API is receiving speech input (i.e.,
+ * onspeechstart).
+ */
+view.setReceivingSpeech = function() {
+ if (view.isVisible_) {
+ view.container_.className = view.RECEIVING_SPEECH_CLASS_;
+ microphone.startInputAnimation();
+ text.cancelListeningTimeout();
+ }
+};
+
+
+/**
+ * Updates the speech recognition results output with the latest results.
+ * @param {string} interimResultText Low confidence recognition text (grey).
+ * @param {string} finalResultText High confidence recognition text (black).
+ */
+view.updateSpeechResult = function(interimResultText, finalResultText) {
+ if (view.isVisible_) {
+ view.container_.className = view.RECEIVING_SPEECH_CLASS_;
+ text.updateTextArea(interimResultText, finalResultText);
+ }
+};
+
+
+/**
+ * Hides the UI and stops animations.
+ */
+view.hide = function() {
+ window.removeEventListener('mouseup', view.onWindowClick_, false);
+ view.stopMicrophoneAnimations_();
+ view.hideView_();
+ view.isNoMatchShown_ = false;
+ text.clear();
+};
+
+
+/**
+ * Find the page elements that will be used to render the speech recognition
+ * interface area.
+ * @param {Function} onClick The function to call when there is a click event
+ * in the window.
+ */
+view.init = function(onClick) {
+ view.onClick_ = onClick;
+
+ view.background_ = $(view.BACKGROUND_ID_);
+ view.container_ = $(view.CONTAINER_ID_);
+
+ text.init();
+ microphone.init();
+};
+
+
+/**
+ * Displays an error message and stops animations.
+ * @param {RecognitionError} error The error type.
+ */
+view.showError = function(error) {
+ view.container_.className = view.ERROR_RECEIVED_CLASS_;
+ text.showErrorMessage(error);
+ view.stopMicrophoneAnimations_();
+ view.isNoMatchShown_ = (error == RecognitionError.NO_MATCH);
+};
+
+
+/**
+ * Makes the view visible.
+ * @private
+ */
+view.showView_ = function() {
+ if (!view.isVisible_) {
+ view.background_.hidden = false;
+ view.showFullPage_();
+ view.isVisible_ = true;
+ }
+};
+
+
+/**
+ * Displays the full page view, animating from the hidden state to the visible
+ * state.
+ * @private
+ */
+view.showFullPage_ = function() {
+ view.background_.className = view.OVERLAY_HIDDEN_CLASS_;
+ view.background_.className = view.OVERLAY_CLASS_;
+};
+
+
+/**
+ * Hides the view.
+ * @private
+ */
+view.hideView_ = function() {
+ view.background_.className = view.OVERLAY_HIDDEN_CLASS_;
+ view.container_.className = view.INACTIVE_CLASS_;
+ view.background_.removeAttribute('style');
+ view.background_.hidden = true;
+ view.isVisible_ = false;
+};
+
+
+/**
+ * Stops the animations in the microphone view.
+ * @private
+ */
+view.stopMicrophoneAnimations_ = function() {
+ microphone.stopInputAnimation();
+};
+
+
+/**
+ * Makes sure that a click anywhere closes the UI when it is active.
+ * @param {Event} event The click event.
+ * @private
+ */
+view.onWindowClick_ = function(event) {
+ if (!view.isVisible_) {
+ return;
+ }
+ const targetId = event.target.id;
+ const shouldRetry = (targetId == microphone.RED_BUTTON_ID ||
+ targetId == text.ERROR_LINK_ID) &&
+ view.isNoMatchShown_;
+ const submitQuery =
+ targetId == microphone.RED_BUTTON_ID && !view.isNoMatchShown_;
+ view.onClick_(submitQuery, shouldRetry);
+};
+/* END VIEW */
diff --git a/chromium/chrome/browser/resources/md_bookmarks/BUILD.gn b/chromium/chrome/browser/resources/md_bookmarks/BUILD.gn
index eea759d729c..16e74988bb3 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/BUILD.gn
+++ b/chromium/chrome/browser/resources/md_bookmarks/BUILD.gn
@@ -1,22 +1,12 @@
import("../vulcanize.gni")
-vulcanized_unbuilt = "vulcanized.unbuilt.html"
-
-vulcanize("vulcanize") {
+vulcanize("build") {
host = "bookmarks"
- html_in_file = "bookmarks.html"
- html_out_file = vulcanized_unbuilt
+ html_in_files = [ "bookmarks.html" ]
+ html_out_files = [ "vulcanized.html" ]
input = rebase_path(".", root_build_dir)
- js_out_file = "crisper.js"
+ js_out_files = [ "crisper.js" ]
deps = []
}
-
-polymer_css_build("build") {
- input_files = [ vulcanized_unbuilt ]
- output_files = [ "vulcanized.html" ]
- deps = [
- ":vulcanize",
- ]
-}
diff --git a/chromium/chrome/browser/resources/md_bookmarks/README.md b/chromium/chrome/browser/resources/md_bookmarks/README.md
new file mode 100644
index 00000000000..44f0f1e4718
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_bookmarks/README.md
@@ -0,0 +1,110 @@
+# Material Design Bookmark Manager
+
+The bookmark manager (BMM) is a WebUI surface with a large amount of
+functionality for managing bookmarks across a relatively simple UI. This
+document serves as an overview of the page, both in terms of the page features,
+as well as the code design built up to support it.
+
+## Major features
+
+The following are some of the main features of the BMM which impact the design
+of the code:
+
+* **Real-time updates**: The display updates in real-time in response to any
+ change to the bookmark model, whether from the page itself or from any other
+ part of the browser UI.
+* **Item selection**: It is possible to select items using either the mouse or
+ keyboard, using ctrl/shift in much the same way as with a powerful file
+ browser like Windows Explorer.
+* **Contextual commands**: All viewing/editing commands adapt to the current
+ selection. Most commands have corresponding keyboard shortcuts.
+* **Drag and drop**: It is possible to drag bookmarks to move them between
+ folders. This works within the BMM, as well as between native UI and the BMM,
+ and between two different BMM instances from different Chrome profiles.
+* **Policy support**: Several policies are respected:
+
+ - [EditBookmarksEnabled](https://www.chromium.org/administrators/policy-list-3#EditBookmarksEnabled):
+ Prevents all editing operations
+ - [ManagedBookmarks](https://www.chromium.org/administrators/policy-list-3#ManagedBookmarks):
+ Defines a folder of immutable bookmarks.
+ - [IncognitoModeAvailability](https://www.chromium.org/administrators/policy-list-3#IncognitoModeAvailability):
+ Disables/force-enables opening bookmarks in Incognito
+
+## Data-flow model
+
+[Full design document](https://docs.google.com/document/d/1deh7jm-x95d_nWfvWqZAwwgzR6q_1SXIuRoNnQlqCqA/edit?usp=sharing)
+
+The BMM uses a one-way data flow model that is somewhat different to other
+Polymer WebUI pages. This model is inspired by [Redux](http://redux.js.org/),
+with a simple layer which binds it to Polymer UI components. Designing our data
+flow in this way has a few primary benefits:
+
+* We have a single source of truth for the state of the page
+* We have a well-defined interface for making changes to the state of the page
+* UI components are able to directly read whatever state they need, removing the
+ need for a chain of tedious, highly-coupled Polymer bindings to manage state.
+
+The following is a brief overview of how the data-flow model works. Note that
+this model is only used for front-end Polymer UI, and is entirely separate to
+the backend BookmarkModel in C++.
+
+### Store
+
+`store.js` provides a singleton class (`bookmarks.Store`) which gives access to
+a read-only state tree for the entire page (`store.data`).
+
+Any Polymer UI element which wants to be able to data-bind values from the
+global state should add the behavior `bookmarks.StoreClient` (in
+`store_client.js`). This behavior allows elements to `watch` particular values
+in the store, and be automatically updated when they change.
+
+### Actions
+
+Actions are the only way to modify the state tree. An `Action` is a plain
+Javascript object which describes a modification that should be made to the
+state tree. All `Action` objects are created by functions in `actions.js`.
+
+To actually modify the state, call `Store.dispatch(action)` (or
+`StoreClient.dispatch(action)`). This tells the store to process the action and
+notify UI elements about what has changed.
+
+Changes to the persistent bookmarks backend are made by calling into the
+bookmarks extension API. These then call back to the BMM through
+chrome.bookmarks event listeners, which dispatch actions to change the
+Javascript bookmark model, updating the page.
+
+**Note**: There's also limited support for Actions which are processed
+asynchronously. See `dispatchAsync` for details, but this probably needs more
+work before they are generally useful.
+
+### Reducers
+
+Reducers describe how an action affects the page state. These are **pure
+functions** located in `reducers.js` which take a state and an action, and
+return a new state.
+
+Importantly, reducers must never modify any part of the input state: instead,
+they return new objects for any part of the state tree that has changed. By
+doing this, it is possible for `StoreClient` to quickly check for what has
+changed using `==`, and only notify Polymer about things that have actually
+changed. Plus, these functions are easier to test and debug!
+
+## Context menus and keyboard shortcuts
+
+[Full design document](https://docs.google.com/document/d/1AUWpwaiHgYlnBWeKW8hgScGZvaGa2BImOeV-d4BF8QE/edit?usp=sharing)
+
+Context menus and keyboard shortcuts are controlled by the `CommandManager`,
+located in `command_manager.js`. This includes all logic for commands which
+open/edit bookmarks, including:
+
+* Determining which commands should appear in the context menu (and whether they
+ are enabled or disabled).
+* Triggering commands on keyboard shortcuts
+* Showing appropriate UI (such as confirmation dialogs, toasts) when the command
+ is executed.
+
+An enum of all possible commands is defined in `constants.js`.
+
+<!-- TODO(calamity):
+## Drag and drop
+-->
diff --git a/chromium/chrome/browser/resources/md_bookmarks/actions.js b/chromium/chrome/browser/resources/md_bookmarks/actions.js
index 79807522fb5..8749fdbf598 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/actions.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/actions.js
@@ -193,14 +193,15 @@ cr.define('bookmarks.actions', function() {
/**
* @param {Array<string>} ids
* @param {BookmarksPageState} state
+ * @param {string=} anchor
* @return {!Action}
*/
- function selectAll(ids, state) {
+ function selectAll(ids, state, anchor) {
return {
name: 'select-items',
clear: true,
toggle: false,
- anchor: state.selection.anchor,
+ anchor: anchor ? anchor : state.selection.anchor,
items: ids,
};
}
diff --git a/chromium/chrome/browser/resources/md_bookmarks/api_listener.js b/chromium/chrome/browser/resources/md_bookmarks/api_listener.js
index 1e8852cbe7d..534e8902aec 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/api_listener.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/api_listener.js
@@ -9,8 +9,12 @@
cr.define('bookmarks.ApiListener', function() {
- /** @type {?number} */
- var timerHandle;
+ /** @type {boolean} */
+ var trackUpdates = false;
+ /** @type {!Array<string>} */
+ var updatedItems = [];
+
+ var debouncer;
/**
* Batches UI updates so that no changes will be made to UI until the next
@@ -18,15 +22,43 @@ cr.define('bookmarks.ApiListener', function() {
* can be called in a tight loop by UI actions.
*/
function batchUIUpdates() {
- if (timerHandle)
- clearTimeout(timerHandle);
- else
+ if (!debouncer || debouncer.done()) {
bookmarks.Store.getInstance().beginBatchUpdate();
+ debouncer = new bookmarks.Debouncer(
+ () => bookmarks.Store.getInstance().endBatchUpdate());
+ }
- timerHandle = setTimeout(function() {
- bookmarks.Store.getInstance().endBatchUpdate();
- timerHandle = null;
- });
+ debouncer.resetTimeout();
+ }
+
+ /**
+ * Tracks any items that are created or moved.
+ */
+ function trackUpdatedItems() {
+ trackUpdates = true;
+ }
+
+ function highlightUpdatedItemsImpl() {
+ if (!trackUpdates)
+ return;
+
+ document.dispatchEvent(new CustomEvent('highlight-items', {
+ detail: updatedItems,
+ }));
+ updatedItems = [];
+ trackUpdates = false;
+ }
+
+ /**
+ * Highlights any items that have been updated since |trackUpdatedItems| was
+ * called. Should be called after a user action causes new items to appear in
+ * the main list.
+ */
+ function highlightUpdatedItems() {
+ // Ensure that the items are highlighted after the current batch update (if
+ // there is one) is completed.
+ assert(debouncer);
+ debouncer.promise.then(highlightUpdatedItemsImpl);
}
/** @param {Action} action */
@@ -48,6 +80,8 @@ cr.define('bookmarks.ApiListener', function() {
*/
function onBookmarkCreated(id, treeNode) {
batchUIUpdates();
+ if (trackUpdates)
+ updatedItems.push(id);
dispatch(bookmarks.actions.createBookmark(id, treeNode));
}
@@ -73,6 +107,8 @@ cr.define('bookmarks.ApiListener', function() {
*/
function onBookmarkMoved(id, moveInfo) {
batchUIUpdates();
+ if (trackUpdates)
+ updatedItems.push(id);
dispatch(bookmarks.actions.moveBookmark(
id, moveInfo.parentId, moveInfo.index, moveInfo.oldParentId,
moveInfo.oldIndex));
@@ -116,14 +152,18 @@ cr.define('bookmarks.ApiListener', function() {
dispatch(bookmarks.actions.setCanEditBookmarks(canEdit));
}
+ var listeners = [
+ {api: chrome.bookmarks.onChanged, fn: onBookmarkChanged},
+ {api: chrome.bookmarks.onChildrenReordered, fn: onChildrenReordered},
+ {api: chrome.bookmarks.onCreated, fn: onBookmarkCreated},
+ {api: chrome.bookmarks.onMoved, fn: onBookmarkMoved},
+ {api: chrome.bookmarks.onRemoved, fn: onBookmarkRemoved},
+ {api: chrome.bookmarks.onImportBegan, fn: onImportBegan},
+ {api: chrome.bookmarks.onImportEnded, fn: onImportEnded},
+ ];
+
function init() {
- chrome.bookmarks.onChanged.addListener(onBookmarkChanged);
- chrome.bookmarks.onChildrenReordered.addListener(onChildrenReordered);
- chrome.bookmarks.onCreated.addListener(onBookmarkCreated);
- chrome.bookmarks.onMoved.addListener(onBookmarkMoved);
- chrome.bookmarks.onRemoved.addListener(onBookmarkRemoved);
- chrome.bookmarks.onImportBegan.addListener(onImportBegan);
- chrome.bookmarks.onImportEnded.addListener(onImportEnded);
+ listeners.forEach((listener) => listener.api.addListener(listener.fn));
cr.sendWithPromise('getIncognitoAvailability')
.then(onIncognitoAvailabilityChanged);
@@ -135,7 +175,18 @@ cr.define('bookmarks.ApiListener', function() {
'can-edit-bookmarks-changed', onCanEditBookmarksChanged);
}
+ function destroy() {
+ listeners.forEach((listener) => listener.api.removeListener(listener.fn));
+ cr.removeWebUIListener(
+ 'incognito-availability-changed', onIncognitoAvailabilityChanged);
+ cr.removeWebUIListener(
+ 'can-edit-bookmarks-changed', onCanEditBookmarksChanged);
+ }
+
return {
init: init,
+ destroy: destroy,
+ trackUpdatedItems: trackUpdatedItems,
+ highlightUpdatedItems: highlightUpdatedItems,
};
});
diff --git a/chromium/chrome/browser/resources/md_bookmarks/app.html b/chromium/chrome/browser/resources/md_bookmarks/app.html
index 88676c04b44..b047f366b8d 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/app.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/app.html
@@ -23,7 +23,7 @@
display: flex;
flex-direction: column;
height: 100%;
- line-height: 154%; /* 20px. */
+ line-height: 1.54; /* 20px. */
}
#main-container {
@@ -68,9 +68,10 @@
min-width: 550px;
}
</style>
- <bookmarks-toolbar sidebar-width="[[sidebarWidth_]]"></bookmarks-toolbar>
+ <bookmarks-toolbar sidebar-width="[[sidebarWidth_]]" role="banner">
+ </bookmarks-toolbar>
<div id="main-container">
- <div id="sidebar" role="tree">
+ <div id="sidebar" role="navigation">
<bookmarks-folder-node item-id="0" depth="-1"></bookmarks-folder-node>
</div>
<div id="splitter"></div>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/app.js b/chromium/chrome/browser/resources/md_bookmarks/app.js
index 24b2f1b2806..2622bd0d46e 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/app.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/app.js
@@ -17,10 +17,10 @@ Polymer({
observer: 'searchTermChanged_',
},
- /** @type {ClosedFolderState} */
- closedFoldersState_: {
+ /** @type {FolderOpenState} */
+ folderOpenState_: {
type: Object,
- observer: 'closedFoldersStateChanged_',
+ observer: 'folderOpenStateChanged_',
},
/** @private */
@@ -35,25 +35,26 @@ Polymer({
/** @override */
attached: function() {
- this.watch('searchTerm_', function(store) {
- return store.search.term;
+ this.watch('searchTerm_', function(state) {
+ return state.search.term;
});
- this.watch('closedFoldersState_', function(store) {
- return store.closedFolders;
+ this.watch('folderOpenState_', function(state) {
+ return state.folderOpenState;
});
- chrome.bookmarks.getTree(function(results) {
+ chrome.bookmarks.getTree((results) => {
var nodeMap = bookmarks.util.normalizeNodes(results[0]);
var initialState = bookmarks.util.createEmptyState();
initialState.nodes = nodeMap;
initialState.selectedFolder = nodeMap[ROOT_NODE_ID].children[0];
- var closedFoldersString =
- window.localStorage[LOCAL_STORAGE_CLOSED_FOLDERS_KEY];
- initialState.closedFolders = closedFoldersString ?
- new Set(
- /** @type Array<string> */ (JSON.parse(closedFoldersString))) :
- new Set();
+ var folderStateString =
+ window.localStorage[LOCAL_STORAGE_FOLDER_STATE_KEY];
+ initialState.folderOpenState = folderStateString ?
+ new Map(
+ /** @type Array<Array<boolean|string>> */ (
+ JSON.parse(folderStateString))) :
+ new Map();
bookmarks.Store.getInstance().init(initialState);
bookmarks.ApiListener.init();
@@ -64,7 +65,7 @@ Polymer({
Math.floor(window.performance.now()));
});
- }.bind(this));
+ });
this.boundUpdateSidebarWidth_ = this.updateSidebarWidth_.bind(this);
@@ -77,6 +78,7 @@ Polymer({
detached: function() {
window.removeEventListener('resize', this.boundUpdateSidebarWidth_);
this.dndManager_.destroy();
+ bookmarks.ApiListener.destroy();
},
/**
@@ -96,11 +98,11 @@ Polymer({
this.sidebarWidth_ =
/** @type {string} */ (getComputedStyle(splitterTarget).width);
- splitter.addEventListener('resize', function(e) {
+ splitter.addEventListener('resize', (e) => {
window.localStorage[LOCAL_STORAGE_TREE_WIDTH_KEY] =
splitterTarget.style.width;
this.updateSidebarWidth_();
- }.bind(this));
+ });
splitter.addEventListener('dragmove', this.boundUpdateSidebarWidth_);
window.addEventListener('resize', this.boundUpdateSidebarWidth_);
@@ -117,7 +119,7 @@ Polymer({
if (!this.searchTerm_)
return;
- chrome.bookmarks.search(this.searchTerm_, function(results) {
+ chrome.bookmarks.search(this.searchTerm_, (results) => {
var ids = results.map(function(node) {
return node.id;
});
@@ -127,12 +129,12 @@ Polymer({
loadTimeData.getStringF('searchResults', this.searchTerm_) :
loadTimeData.getString('noSearchResults')
});
- }.bind(this));
+ });
},
/** @private */
- closedFoldersStateChanged_: function() {
- window.localStorage[LOCAL_STORAGE_CLOSED_FOLDERS_KEY] =
- JSON.stringify(Array.from(this.closedFoldersState_));
+ folderOpenStateChanged_: function() {
+ window.localStorage[LOCAL_STORAGE_FOLDER_STATE_KEY] =
+ JSON.stringify(Array.from(this.folderOpenState_));
},
});
diff --git a/chromium/chrome/browser/resources/md_bookmarks/bookmarks.html b/chromium/chrome/browser/resources/md_bookmarks/bookmarks.html
index bc725be992e..6b15d439bb8 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/bookmarks.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/bookmarks.html
@@ -18,7 +18,7 @@
<body>
<bookmarks-app></bookmarks-app>
- <link rel="import" href="chrome://resources/html/load_time_data.html">
+ <script src="chrome://resources/js/load_time_data.js"></script>
<script src="chrome://bookmarks/strings.js"></script>
<link rel="import" href="chrome://bookmarks/app.html">
</body>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/command_manager.html b/chromium/chrome/browser/resources/md_bookmarks/command_manager.html
index 728e5189d80..508b0501a43 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/command_manager.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/command_manager.html
@@ -28,14 +28,13 @@
}
</style>
<template is="cr-lazy-render" id="dropdown">
- <dialog is="cr-action-menu" on-mousedown="onMenuMousedown_" role="menu">
+ <dialog is="cr-action-menu" on-mousedown="onMenuMousedown_">
<template is="dom-repeat" items="[[menuCommands_]]" as="command">
<button class="dropdown-item"
command$="[[command]]"
hidden$="[[!isCommandVisible_(command, menuIds_)]]"
disabled$="[[!isCommandEnabled_(command, menuIds_)]]"
- on-click="onCommandClick_"
- role="menuitem">
+ on-click="onCommandClick_">
<span class="label">
[[getCommandLabel_(command, menuIds_)]]
</span>
@@ -43,7 +42,9 @@
[[getCommandSublabel_(command, menuIds_)]]
</span>
</button>
- <hr hidden$="[[!showDividerAfter_(command, menuIds_)]]"></hr>
+ <hr hidden$="[[!showDividerAfter_(command, menuIds_)]]"
+ aria-hidden="true">
+ </hr>
</template>
</dialog>
</template>
@@ -52,9 +53,9 @@
</template>
<template is="cr-lazy-render" id="openDialog">
<dialog is="cr-dialog">
- <div class="title" slot="title">$i18n{openDialogTitle}</div>
- <div class="body" slot="body"></div>
- <div class="button-container" slot="button-container">
+ <div slot="title">$i18n{openDialogTitle}</div>
+ <div slot="body"></div>
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onOpenCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/command_manager.js b/chromium/chrome/browser/resources/md_bookmarks/command_manager.js
index dee208efa92..486b09231eb 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/command_manager.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/command_manager.js
@@ -66,9 +66,9 @@ cr.define('bookmarks', function() {
document.addEventListener('open-item-menu', this.boundOnOpenItemMenu_);
/** @private {function()} */
- this.boundOnCommandUndo_ = function() {
+ this.boundOnCommandUndo_ = () => {
this.handle(Command.UNDO, new Set());
- }.bind(this);
+ };
document.addEventListener('command-undo', this.boundOnCommandUndo_);
/** @private {function(!Event)} */
@@ -83,8 +83,8 @@ cr.define('bookmarks', function() {
*/
this.menuSource_ = MenuSource.NONE;
- /** @private {Object<Command, cr.ui.KeyboardShortcutList>} */
- this.shortcuts_ = {};
+ /** @private {!Map<Command, cr.ui.KeyboardShortcutList>} */
+ this.shortcuts_ = new Map();
this.addShortcut_(Command.EDIT, 'F2', 'Enter');
this.addShortcut_(Command.DELETE, 'Delete', 'Delete Backspace');
@@ -268,7 +268,7 @@ cr.define('bookmarks', function() {
case Command.COPY_URL:
case Command.COPY:
var idList = Array.from(itemIds);
- chrome.bookmarkManagerPrivate.copy(idList, function() {
+ chrome.bookmarkManagerPrivate.copy(idList, () => {
var labelPromise;
if (command == Command.COPY_URL) {
labelPromise =
@@ -283,12 +283,14 @@ cr.define('bookmarks', function() {
this.showTitleToast_(
labelPromise, state.nodes[idList[0]].title, false);
- }.bind(this));
+ });
break;
case Command.SHOW_IN_FOLDER:
var id = Array.from(itemIds)[0];
this.dispatch(bookmarks.actions.selectFolder(
assert(state.nodes[id].parentId), state.nodes));
+ bookmarks.DialogFocusManager.getInstance().clearFocus();
+ this.fire('highlight-items', [id]);
break;
case Command.DELETE:
var idList = Array.from(this.minimizeDeletionSet_(itemIds));
@@ -303,9 +305,9 @@ cr.define('bookmarks', function() {
'getPluralString', 'toastItemsDeleted', idList.length);
}
- chrome.bookmarkManagerPrivate.removeTrees(idList, function() {
+ chrome.bookmarkManagerPrivate.removeTrees(idList, () => {
this.showTitleToast_(labelPromise, title, true);
- }.bind(this));
+ });
break;
case Command.UNDO:
chrome.bookmarkManagerPrivate.undo();
@@ -345,12 +347,17 @@ cr.define('bookmarks', function() {
case Command.PASTE:
var selectedFolder = state.selectedFolder;
var selectedItems = state.selection.items;
+ bookmarks.ApiListener.trackUpdatedItems();
chrome.bookmarkManagerPrivate.paste(
- selectedFolder, Array.from(selectedItems));
+ selectedFolder, Array.from(selectedItems),
+ bookmarks.ApiListener.highlightUpdatedItems);
break;
default:
assert(false);
}
+
+ bookmarks.util.recordEnumHistogram(
+ 'BookmarkManager.CommandExecuted', command, Command.MAX_VALUE);
},
/**
@@ -360,11 +367,16 @@ cr.define('bookmarks', function() {
* shortcut.
*/
handleKeyEvent: function(e, itemIds) {
- for (var commandName in this.shortcuts_) {
- var shortcut = this.shortcuts_[commandName];
- if (shortcut.matchesEvent(e) && this.canExecute(commandName, itemIds)) {
- this.handle(commandName, itemIds);
-
+ for (var commandTuple of this.shortcuts_) {
+ var command = /** @type {Command} */ (commandTuple[0]);
+ var shortcut =
+ /** @type {cr.ui.KeyboardShortcutList} */ (commandTuple[1]);
+ if (shortcut.matchesEvent(e) && this.canExecute(command, itemIds)) {
+ this.handle(command, itemIds);
+
+ bookmarks.util.recordEnumHistogram(
+ 'BookmarkManager.CommandExecutedFromKeyboard', command,
+ Command.MAX_VALUE);
e.stopPropagation();
e.preventDefault();
return true;
@@ -387,7 +399,7 @@ cr.define('bookmarks', function() {
*/
addShortcut_: function(command, shortcut, macShortcut) {
var shortcut = (cr.isMac && macShortcut) ? macShortcut : shortcut;
- this.shortcuts_[command] = new cr.ui.KeyboardShortcutList(shortcut);
+ this.shortcuts_.set(command, new cr.ui.KeyboardShortcutList(shortcut));
},
/**
@@ -450,7 +462,7 @@ cr.define('bookmarks', function() {
this.confirmOpenCallback_ = openUrlsCallback;
var dialog = this.$.openDialog.get();
- dialog.querySelector('.body').textContent =
+ dialog.querySelector('[slot=body]').textContent =
loadTimeData.getStringF('openDialogBody', urls.length);
bookmarks.DialogFocusManager.getInstance().showDialog(
@@ -579,9 +591,8 @@ cr.define('bookmarks', function() {
if (!this.menuIds_)
return;
- this.hasAnySublabel_ = this.menuCommands_.some(function(command) {
- return this.getCommandSublabel_(command) != '';
- }.bind(this));
+ this.hasAnySublabel_ = this.menuCommands_.some(
+ (command) => this.getCommandSublabel_(command) != '');
},
/**
@@ -638,7 +649,9 @@ cr.define('bookmarks', function() {
*/
onCommandClick_: function(e) {
this.handle(
- e.currentTarget.getAttribute('command'), assert(this.menuIds_));
+ /** @type {Command} */ (
+ Number(e.currentTarget.getAttribute('command'))),
+ assert(this.menuIds_));
this.closeCommandMenu();
},
diff --git a/chromium/chrome/browser/resources/md_bookmarks/compiled_resources2.gyp b/chromium/chrome/browser/resources/md_bookmarks/compiled_resources2.gyp
index 1810e03df48..0ce298c44a6 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/md_bookmarks/compiled_resources2.gyp
@@ -20,6 +20,7 @@
'<(EXTERNS_GYP):chrome_extensions',
'actions',
'store',
+ 'timer_proxy',
'util',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
@@ -49,6 +50,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:command',
'<(EXTERNS_GYP):bookmark_manager_private',
+ 'api_listener',
'dialog_focus_manager',
'edit_dialog',
'store_client',
@@ -82,7 +84,9 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(EXTERNS_GYP):bookmark_manager_private',
'<(EXTERNS_GYP):metrics_private',
+ 'api_listener',
'dnd_chip',
+ 'folder_node',
'store',
'timer_proxy',
'types',
@@ -98,6 +102,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(EXTERNS_GYP):chrome_extensions',
+ 'api_listener',
'dialog_focus_manager',
'types',
],
diff --git a/chromium/chrome/browser/resources/md_bookmarks/constants.js b/chromium/chrome/browser/resources/md_bookmarks/constants.js
index 8ff285b12e4..85a83d391b8 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/constants.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/constants.js
@@ -16,26 +16,31 @@ var DropPosition = {
};
/**
- * @enum {string}
+ * Commands which can be handled by the CommandManager. This enum is also used
+ * for metrics and should be kept in sync with BookmarkManagerCommand in
+ * enums.xml.
+ * @enum {number}
* @const
*/
var Command = {
- EDIT: 'edit',
- COPY_URL: 'copy-url',
- SHOW_IN_FOLDER: 'show-in-folder',
- DELETE: 'delete',
- OPEN_NEW_TAB: 'open-new-tab',
- OPEN_NEW_WINDOW: 'open-new-window',
- OPEN_INCOGNITO: 'open-incognito',
- UNDO: 'undo',
- REDO: 'redo',
+ EDIT: 0,
+ COPY_URL: 1,
+ SHOW_IN_FOLDER: 2,
+ DELETE: 3,
+ OPEN_NEW_TAB: 4,
+ OPEN_NEW_WINDOW: 5,
+ OPEN_INCOGNITO: 6,
+ UNDO: 7,
+ REDO: 8,
// OPEN triggers when you double-click an item.
- OPEN: 'open',
- SELECT_ALL: 'select-all',
- DESELECT_ALL: 'deselect-all',
- COPY: 'copy',
- CUT: 'cut',
- PASTE: 'paste',
+ OPEN: 9,
+ SELECT_ALL: 10,
+ DESELECT_ALL: 11,
+ COPY: 12,
+ CUT: 13,
+ PASTE: 14,
+ // Append new values to the end of the enum.
+ MAX_VALUE: 15,
};
/**
@@ -60,7 +65,7 @@ var IncognitoAvailability = {
};
/** @const */
-var LOCAL_STORAGE_CLOSED_FOLDERS_KEY = 'closedState';
+var LOCAL_STORAGE_FOLDER_STATE_KEY = 'folderOpenState';
/** @const */
var LOCAL_STORAGE_TREE_WIDTH_KEY = 'treeWidth';
@@ -73,3 +78,10 @@ var BOOKMARKS_BAR_ID = '1';
/** @const {number} */
var OPEN_CONFIRMATION_LIMIT = 15;
+
+/**
+ * Folders that are beneath this depth will be closed by default in the folder
+ * tree (where the Bookmarks Bar folder is at depth 0).
+ * @const {number}
+ */
+var FOLDER_OPEN_BY_DEFAULT_DEPTH = 1;
diff --git a/chromium/chrome/browser/resources/md_bookmarks/dialog_focus_manager.js b/chromium/chrome/browser/resources/md_bookmarks/dialog_focus_manager.js
index 98c0fd34e84..68e73b2bda4 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/dialog_focus_manager.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/dialog_focus_manager.js
@@ -51,6 +51,14 @@ cr.define('bookmarks', function() {
return this.dialogs_.size > 0;
},
+ /**
+ * Clears the stored focus element, so that focus does not restore when all
+ * dialogs are closed.
+ */
+ clearFocus: function() {
+ this.previousFocusElement_ = null;
+ },
+
/** @private */
updatePreviousFocus_: function() {
this.previousFocusElement_ = this.getFocusedElement_();
@@ -74,7 +82,7 @@ cr.define('bookmarks', function() {
* @private
*/
getCloseListener_: function(dialog) {
- var closeListener = function(e) {
+ var closeListener = (e) => {
// If the dialog is open, then it got reshown immediately and we
// shouldn't clear it until it is closed again.
if (dialog.open)
@@ -82,11 +90,11 @@ cr.define('bookmarks', function() {
assert(this.dialogs_.delete(dialog));
// Focus the originally focused element if there are no more dialogs.
- if (!this.hasOpenDialog())
+ if (!this.hasOpenDialog() && this.previousFocusElement_)
this.previousFocusElement_.focus();
dialog.removeEventListener('close', closeListener);
- }.bind(this);
+ };
return closeListener;
},
diff --git a/chromium/chrome/browser/resources/md_bookmarks/dnd_chip.html b/chromium/chrome/browser/resources/md_bookmarks/dnd_chip.html
index c0775007678..f9d99859f37 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/dnd_chip.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/dnd_chip.html
@@ -10,7 +10,7 @@
<style include="shared-style">
:host {
--chip-height: 40px;
- --chip-padding-x: 20px;
+ --chip-padding-x: 8px;
--chip-width: 172px;
left: 0;
@@ -29,8 +29,8 @@
.chip-container {
background-color: var(--interactive-color);
border-radius: calc(var(--chip-height) / 2);
- box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.12),
- 0 8px 8px 0 rgba(0, 0, 0, 0.24);
+ box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.12),
+ 0 4px 10px 0 rgba(0, 0, 0, 0.24);
height: var(--chip-height);
left: 0;
padding: 0 var(--chip-padding-x);
@@ -39,13 +39,9 @@
width: calc(var(--chip-width) - var(--chip-padding-x) * 2);
}
- #secondary {
- left: 5px;
- top: 5px;
- }
-
#title {
- -webkit-margin-start: 20px;
+ -webkit-margin-end: 8px;
+ -webkit-margin-start: 12px;
color: white;
flex: 1;
font-weight: 500;
@@ -88,9 +84,7 @@
right: auto;
}
</style>
- <div id="secondary" class="chip-container" hidden$="[[!isMultiItem_]]">
- </div>
- <div id="primary" class="chip-container centered">
+ <div class="chip-container centered">
<div id="icon-wrapper" class="centered">
<div id="icon"></div>
</div>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/dnd_manager.js b/chromium/chrome/browser/resources/md_bookmarks/dnd_manager.js
index c1a73839400..98a4d5ab445 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/dnd_manager.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/dnd_manager.js
@@ -2,7 +2,14 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+
+/** @typedef {?{elements: !Array<BookmarkNode>, sameProfile: boolean}} */
+var NormalizedDragData;
+
cr.define('bookmarks', function() {
+ /** @const {number} */
+ var DRAG_THRESHOLD = 15;
+
/**
* @param {BookmarkElement} element
* @return {boolean}
@@ -28,6 +35,15 @@ cr.define('bookmarks', function() {
}
/**
+ * @param {BookmarkElement} element
+ * @return {boolean}
+ */
+ function isClosedBookmarkFolderNode(element) {
+ return isBookmarkFolderNode(element) &&
+ !(/** @type {BookmarksFolderNodeElement} */ (element).isOpen);
+ }
+
+ /**
* @param {Array<!Element>|undefined} path
* @return {BookmarkElement}
*/
@@ -37,13 +53,28 @@ cr.define('bookmarks', function() {
for (var i = 0; i < path.length; i++) {
if (isBookmarkItem(path[i]) || isBookmarkFolderNode(path[i]) ||
- isBookmarkList(path[i]))
+ isBookmarkList(path[i])) {
return path[i];
+ }
}
return null;
}
/**
+ * @param {Array<!Element>|undefined} path
+ * @return {BookmarkElement}
+ */
+ function getDragElement(path) {
+ var dragElement = getBookmarkElement(path);
+ for (var i = 0; i < path.length; i++) {
+ if (path[i].tagName == 'BUTTON')
+ return null;
+ }
+ return dragElement && dragElement.getAttribute('draggable') ? dragElement :
+ null;
+ }
+
+ /**
* @param {BookmarkElement} bookmarkElement
* @return {BookmarkNode}
*/
@@ -57,14 +88,18 @@ cr.define('bookmarks', function() {
* @constructor
*/
function DragInfo() {
- /** @type {DragData} */
+ /** @type {NormalizedDragData} */
this.dragData = null;
}
DragInfo.prototype = {
/** @param {DragData} newDragData */
- handleChromeDragEnter: function(newDragData) {
- this.dragData = newDragData;
+ setNativeDragData: function(newDragData) {
+ this.dragData = {
+ sameProfile: newDragData.sameProfile,
+ elements:
+ newDragData.elements.map((x) => bookmarks.util.normalizeNode(x))
+ };
},
clearDragData: function() {
@@ -160,9 +195,8 @@ cr.define('bookmarks', function() {
var action = bookmarks.actions.changeFolderOpen(itemId, true);
store.dispatch(action);
} else if (
- overElement && isBookmarkFolderNode(overElement) &&
- bookmarks.util.hasChildFolders(itemId, store.data.nodes) &&
- store.data.closedFolders.has(itemId)) {
+ overElement && isClosedBookmarkFolderNode(overElement) &&
+ bookmarks.util.hasChildFolders(itemId, store.data.nodes)) {
// Since this is a closed folder node that has children, set the auto
// expander to this element.
this.lastTimestamp_ = eventTimestamp;
@@ -260,15 +294,31 @@ cr.define('bookmarks', function() {
// The use of a timeout is in order to reduce flickering as we move
// between valid drop targets.
this.timerProxy.clearTimeout(this.removeDropIndicatorTimeoutId_);
- this.removeDropIndicatorTimeoutId_ =
- this.timerProxy.setTimeout(function() {
- this.removeDropIndicatorStyle();
- }.bind(this), 100);
+ this.removeDropIndicatorTimeoutId_ = this.timerProxy.setTimeout(() => {
+ this.removeDropIndicatorStyle();
+ }, 100);
},
};
/**
* Manages drag and drop events for the bookmarks-app.
+ *
+ * This class manages an internal drag and drop based on mouse events and then
+ * delegates to the native drag and drop in chrome.bookmarkManagerPrivate when
+ * the mouse leaves the web content area. This allows us to render a drag and
+ * drop chip UI for internal drags, while correctly handling and avoiding
+ * conflict with native drags.
+ *
+ * The event flows look like
+ *
+ * mousedown -> mousemove -> mouseup
+ * |
+ * v
+ * dragstart/dragleave (if the drag leaves the browser window)
+ * |
+ * v
+ * external drag -> bookmarkManagerPrivate.onDragEnter -> dragover -> drop
+ *
* @constructor
*/
function DNDManager() {
@@ -297,10 +347,17 @@ cr.define('bookmarks', function() {
this.chip_ = null;
/**
- * The element that initiated a drag.
+ * The element that initiated an internal drag. Not used once native drag
+ * starts.
* @private {BookmarkElement}
*/
- this.dragElement_ = null;
+ this.internalDragElement_ = null;
+
+ /**
+ * Where the internal drag started.
+ * @private {?{x: number, y: number}}
+ */
+ this.mouseDownPos_ = null;
}
DNDManager.prototype = {
@@ -310,20 +367,24 @@ cr.define('bookmarks', function() {
this.autoExpander_ = new AutoExpander();
this.documentListeners_ = {
+ 'mousedown': this.onMousedown_.bind(this),
+ 'mousemove': this.onMouseMove_.bind(this),
+ 'mouseup': this.onMouseUp_.bind(this),
+ 'mouseleave': this.onMouseLeave_.bind(this),
+
'dragstart': this.onDragStart_.bind(this),
'dragenter': this.onDragEnter_.bind(this),
'dragover': this.onDragOver_.bind(this),
'dragleave': this.onDragLeave_.bind(this),
'drop': this.onDrop_.bind(this),
'dragend': this.clearDragData_.bind(this),
- 'mouseup': this.clearDragData_.bind(this),
// TODO(calamity): Add touch support.
};
for (var event in this.documentListeners_)
document.addEventListener(event, this.documentListeners_[event]);
chrome.bookmarkManagerPrivate.onDragEnter.addListener(
- this.dragInfo_.handleChromeDragEnter.bind(this.dragInfo_));
+ this.handleChromeDragEnter_.bind(this));
chrome.bookmarkManagerPrivate.onDragLeave.addListener(
this.clearDragData_.bind(this));
chrome.bookmarkManagerPrivate.onDrop.addListener(
@@ -338,132 +399,177 @@ cr.define('bookmarks', function() {
document.removeEventListener(event, this.documentListeners_[event]);
},
- /** @private */
- onDragLeave_: function() {
- this.dropIndicator_.finish();
- },
+ ////////////////////////////////////////////////////////////////////////////
+ // MouseEvent handlers:
/**
* @private
- * @param {!Event} e
+ * @param {Event} e
*/
- onDrop_: function(e) {
- if (this.dropDestination_) {
- e.preventDefault();
-
- var dropInfo = this.calculateDropInfo_(this.dropDestination_);
- if (dropInfo.index != -1)
- chrome.bookmarkManagerPrivate.drop(dropInfo.parentId, dropInfo.index);
- else
- chrome.bookmarkManagerPrivate.drop(dropInfo.parentId);
- }
+ onMousedown_: function(e) {
+ var dragElement = getDragElement(e.path);
+ if (e.button != 0 || !dragElement)
+ return;
- this.dropDestination_ = null;
- this.dropIndicator_.finish();
+ this.internalDragElement_ = dragElement;
+ this.mouseDownPos_ = {
+ x: e.clientX,
+ y: e.clientY,
+ };
},
/**
- * @param {DropDestination} dropDestination
- * @return {{parentId: string, index: number}}
+ * @private
+ * @param {Event} e
*/
- calculateDropInfo_: function(dropDestination) {
- if (isBookmarkList(dropDestination.element)) {
- return {
- index: 0,
- parentId: bookmarks.Store.getInstance().data.selectedFolder,
- };
+ onMouseMove_: function(e) {
+ // mousemove events still fire when dragged onto the the bookmarks bar.
+ // Once we are outside of the web contents, allow the native drag to
+ // start.
+ if (!this.internalDragElement_ || e.clientX < 0 ||
+ e.clientX > window.innerWidth || e.clientY < 0 ||
+ e.clientY > window.innerHeight) {
+ return;
}
- var node = getBookmarkNode(dropDestination.element);
- var position = dropDestination.position;
- var index = -1;
- var parentId = node.id;
+ this.dropDestination_ = null;
- if (position != DropPosition.ON) {
- var state = bookmarks.Store.getInstance().data;
+ // Prevents a native drag from starting.
+ e.preventDefault();
- // Drops between items in the normal list and the sidebar use the drop
- // destination node's parent.
- parentId = assert(node.parentId);
- index = state.nodes[parentId].children.indexOf(node.id);
+ // On the first mousemove after a mousedown, calculate the items to drag.
+ // This can't be done in mousedown because the user may be shift-clicking
+ // an item.
+ if (!this.dragInfo_.isDragValid()) {
+ // If the mouse hasn't been moved far enough, defer to next mousemove.
+ if (Math.abs(this.mouseDownPos_.x - e.clientX) < DRAG_THRESHOLD &&
+ Math.abs(this.mouseDownPos_.y - e.clientY) < DRAG_THRESHOLD) {
+ return;
+ }
- if (position == DropPosition.BELOW)
- index++;
+ var dragData = this.calculateDragData_();
+ if (!dragData) {
+ this.clearDragData_();
+ return;
+ }
+
+ this.dragInfo_.dragData = dragData;
}
- return {
- index: index,
- parentId: parentId,
- };
+ var state = bookmarks.Store.getInstance().data;
+ var items = this.dragInfo_.dragData.elements;
+ this.dndChip.showForItems(
+ e.clientX, e.clientY, items,
+ this.internalDragElement_ ?
+ state.nodes[this.internalDragElement_.itemId] :
+ items[0]);
+
+ this.onDragOverCommon_(e);
},
- /** @private */
- clearDragData_: function() {
- this.dndChip.hide();
- this.dragElement_ = null;
+ /**
+ * This event fires when the mouse leaves the browser window (not the web
+ * content area).
+ * @private
+ */
+ onMouseLeave_: function() {
+ if (!this.internalDragElement_)
+ return;
- // Defer the clearing of the data so that the bookmark manager API's drop
- // event doesn't clear the drop data before the web drop event has a
- // chance to execute (on Mac).
- this.timerProxy_.setTimeout(function() {
- this.dragInfo_.clearDragData();
- this.dropDestination_ = null;
- this.dropIndicator_.finish();
- }.bind(this), 0);
+ this.startNativeDrag_();
},
/**
* @private
- * @param {Event} e
*/
- onDragStart_: function(e) {
- var dragElement = getBookmarkElement(e.path);
- if (!dragElement)
+ onMouseUp_: function() {
+ if (!this.internalDragElement_)
return;
- var store = bookmarks.Store.getInstance();
- var dragId = dragElement.itemId;
- this.dragElement_ = dragElement;
-
- // Determine the selected bookmarks.
- var state = store.data;
- var draggedNodes = Array.from(state.selection.items);
+ if (this.dropDestination_) {
+ // Complete the drag by moving all dragged items to the drop
+ // destination.
+ var dropInfo = this.calculateDropInfo_(this.dropDestination_);
+ var shouldHighlight = this.shouldHighlight_(this.dropDestination_);
+
+ var movePromises = this.dragInfo_.dragData.elements.map((item) => {
+ return new Promise((resolve) => {
+ chrome.bookmarks.move(item.id, {
+ parentId: dropInfo.parentId,
+ index: dropInfo.index == -1 ? undefined : dropInfo.index
+ }, resolve);
+ });
+ });
- // Change selection to the dragged node if the node is not part of the
- // existing selection.
- if (isBookmarkFolderNode(dragElement) ||
- draggedNodes.indexOf(dragId) == -1) {
- store.dispatch(bookmarks.actions.deselectItems());
- if (!isBookmarkFolderNode(dragElement)) {
- store.dispatch(bookmarks.actions.selectItem(dragId, state, {
- clear: false,
- range: false,
- toggle: false,
- }));
+ if (shouldHighlight) {
+ bookmarks.ApiListener.trackUpdatedItems();
+ Promise.all(movePromises)
+ .then(() => bookmarks.ApiListener.highlightUpdatedItems());
}
- draggedNodes = [dragId];
}
+ this.clearDragData_();
+ },
+
+ ////////////////////////////////////////////////////////////////////////////
+ // DragEvent handlers:
+
+ /**
+ * This should only fire when a mousemove goes from the content area to the
+ * browser chrome.
+ * @private
+ * @param {Event} e
+ */
+ onDragStart_: function(e) {
+ // |e| will be for the originally dragged bookmark item which dragstart
+ // was disabled for due to mousemove's preventDefault.
+ var dragElement = getDragElement(e.path);
+ if (!dragElement)
+ return;
+
+ // Prevent normal drags of all bookmark items.
e.preventDefault();
- // If any node can't be dragged, early return (after preventDefault).
- var anyUnmodifiable = draggedNodes.some(function(itemId) {
- return !bookmarks.util.canEditNode(state, itemId);
- });
- if (anyUnmodifiable)
+ if (!this.startNativeDrag_())
return;
// If we are dragging a single link, we can do the *Link* effect.
// Otherwise, we only allow copy and move.
if (e.dataTransfer) {
+ var draggedNodes = this.dragInfo_.dragData.elements;
e.dataTransfer.effectAllowed =
- draggedNodes.length == 1 && state.nodes[draggedNodes[0]].url ?
- 'copyLink' :
- 'copyMove';
+ draggedNodes.length == 1 && draggedNodes[0].url ? 'copyLink' :
+ 'copyMove';
}
+ },
- // TODO(calamity): account for touch.
- chrome.bookmarkManagerPrivate.startDrag(draggedNodes, false);
+ /** @private */
+ onDragLeave_: function() {
+ this.dropIndicator_.finish();
+ },
+
+ /**
+ * @private
+ * @param {!Event} e
+ */
+ onDrop_: function(e) {
+ if (this.dropDestination_) {
+ e.preventDefault();
+
+ var dropInfo = this.calculateDropInfo_(this.dropDestination_);
+ var index = dropInfo.index != -1 ? dropInfo.index : undefined;
+ var shouldHighlight = this.shouldHighlight_(this.dropDestination_);
+
+ if (shouldHighlight)
+ bookmarks.ApiListener.trackUpdatedItems();
+
+ chrome.bookmarkManagerPrivate.drop(
+ dropInfo.parentId, index,
+ shouldHighlight ? bookmarks.ApiListener.highlightUpdatedItems :
+ undefined);
+ }
+
+ this.clearDragData_();
},
/**
@@ -497,18 +603,78 @@ cr.define('bookmarks', function() {
if (!this.dragInfo_.isDragValid())
return;
+ if (this.onDragOverCommon_(e) && e.dataTransfer) {
+ e.dataTransfer.dropEffect =
+ this.dragInfo_.isSameProfile() ? 'move' : 'copy';
+ }
+ },
+
+ /**
+ * @private
+ * @param {DragData} dragData
+ */
+ handleChromeDragEnter_: function(dragData) {
+ this.dragInfo_.setNativeDragData(dragData);
+ },
+
+ ////////////////////////////////////////////////////////////////////////////
+ // Common drag methods:
+
+ /** @private */
+ clearDragData_: function() {
+ this.dndChip.hide();
+ this.internalDragElement_ = null;
+ this.mouseDownPos_ = null;
+
+ // Defer the clearing of the data so that the bookmark manager API's drop
+ // event doesn't clear the drop data before the web drop event has a
+ // chance to execute (on Mac).
+ this.timerProxy_.setTimeout(() => {
+ this.dragInfo_.clearDragData();
+ this.dropDestination_ = null;
+ this.dropIndicator_.finish();
+ }, 0);
+ },
+
+ /**
+ * Starts a native drag by sending a message to the browser.
+ * @private
+ * @return {boolean}
+ */
+ startNativeDrag_: function() {
+ var state = bookmarks.Store.getInstance().data;
+
+ if (!this.dragInfo_.isDragValid())
+ return false;
+
+ var draggedNodes =
+ this.dragInfo_.dragData.elements.map((item) => item.id);
+
+ // Clear the drag data here so that the chip is hidden. The native drag
+ // will return after the clearing and set up its data.
+ this.clearDragData_();
+
+ // TODO(calamity): account for touch.
+ chrome.bookmarkManagerPrivate.startDrag(draggedNodes, false);
+
+ return true;
+ },
+
+ /**
+ * @private
+ * @param {Event} e
+ * @return {boolean}
+ */
+ onDragOverCommon_: function(e) {
var state = bookmarks.Store.getInstance().data;
- var items = this.dragInfo_.dragData.elements.map(function(x) {
- return bookmarks.util.normalizeNode(x);
- });
- this.dndChip.showForItems(
- e.clientX, e.clientY, items,
- this.dragElement_ ? state.nodes[this.dragElement_.itemId] : items[0]);
+ var items = this.dragInfo_.dragData.elements;
var overElement = getBookmarkElement(e.path);
this.autoExpander_.update(e, overElement);
- if (!overElement)
- return;
+ if (!overElement) {
+ this.dropIndicator_.finish();
+ return false;
+ }
// Now we know that we can drop. Determine if we will drop above, on or
// below based on mouse position etc.
@@ -516,15 +682,91 @@ cr.define('bookmarks', function() {
this.calculateDropDestination_(e.clientY, overElement);
if (!this.dropDestination_) {
this.dropIndicator_.finish();
- return;
+ return false;
}
- if (e.dataTransfer) {
- e.dataTransfer.dropEffect =
- this.dragInfo_.isSameProfile() ? 'move' : 'copy';
+ this.dropIndicator_.update(this.dropDestination_);
+
+ return true;
+ },
+
+ ////////////////////////////////////////////////////////////////////////////
+ // Other methods:
+
+ /**
+ * @param {DropDestination} dropDestination
+ * @return {{parentId: string, index: number}}
+ */
+ calculateDropInfo_: function(dropDestination) {
+ if (isBookmarkList(dropDestination.element)) {
+ return {
+ index: 0,
+ parentId: bookmarks.Store.getInstance().data.selectedFolder,
+ };
}
- this.dropIndicator_.update(this.dropDestination_);
+ var node = getBookmarkNode(dropDestination.element);
+ var position = dropDestination.position;
+ var index = -1;
+ var parentId = node.id;
+
+ if (position != DropPosition.ON) {
+ var state = bookmarks.Store.getInstance().data;
+
+ // Drops between items in the normal list and the sidebar use the drop
+ // destination node's parent.
+ parentId = assert(node.parentId);
+ index = state.nodes[parentId].children.indexOf(node.id);
+
+ if (position == DropPosition.BELOW)
+ index++;
+ }
+
+ return {
+ index: index,
+ parentId: parentId,
+ };
+ },
+
+ /**
+ * Calculates which items should be dragged based on the initial drag item
+ * and the current selection. Dragged items will end up selected.
+ * @private
+ */
+ calculateDragData_: function() {
+ var dragId = this.internalDragElement_.itemId;
+ var store = bookmarks.Store.getInstance();
+ var state = store.data;
+
+ // Determine the selected bookmarks.
+ var draggedNodes = Array.from(state.selection.items);
+
+ // Change selection to the dragged node if the node is not part of the
+ // existing selection.
+ if (isBookmarkFolderNode(this.internalDragElement_) ||
+ draggedNodes.indexOf(dragId) == -1) {
+ store.dispatch(bookmarks.actions.deselectItems());
+ if (!isBookmarkFolderNode(this.internalDragElement_)) {
+ store.dispatch(bookmarks.actions.selectItem(dragId, state, {
+ clear: false,
+ range: false,
+ toggle: false,
+ }));
+ }
+ draggedNodes = [dragId];
+ }
+
+ // If any node can't be dragged, end the drag.
+ var anyUnmodifiable = draggedNodes.some(
+ (itemId) => !bookmarks.util.canEditNode(state, itemId));
+
+ if (anyUnmodifiable)
+ return null;
+
+ return {
+ elements: draggedNodes.map((id) => state.nodes[id]),
+ sameProfile: true,
+ };
},
/**
@@ -629,7 +871,7 @@ cr.define('bookmarks', function() {
// Don't allow dropping below an expanded sidebar folder item since it is
// confusing to the user anyway.
- if (isOverFolderNode && !state.closedFolders.has(overElement.itemId) &&
+ if (isOverFolderNode && !isClosedBookmarkFolderNode(overElement) &&
bookmarks.util.hasChildFolders(overElement.itemId, state.nodes)) {
return validDropPositions;
}
@@ -666,6 +908,15 @@ cr.define('bookmarks', function() {
return !this.dragInfo_.isDraggingChildBookmark(overElement.itemId);
},
+ /**
+ * @param {DropDestination} dropDestination
+ * @private
+ */
+ shouldHighlight_: function(dropDestination) {
+ return isBookmarkItem(dropDestination.element) ||
+ isBookmarkList(dropDestination.element);
+ },
+
/** @param {bookmarks.TimerProxy} timerProxy */
setTimerProxyForTesting: function(timerProxy) {
this.timerProxy_ = timerProxy;
diff --git a/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.html b/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.html
index 8daaaedacfe..c9e6ce563d9 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.html
@@ -11,10 +11,10 @@
<template>
<style include="cr-shared-style"></style>
<dialog is="cr-dialog" id="dialog">
- <div class="title" slot="title">
+ <div slot="title">
[[getDialogTitle_(isFolder_, isEdit_)]]
</div>
- <div class="body" slot="body">
+ <div slot="body">
<paper-input always-float-label id="name"
label="$i18n{editDialogNameInput}"
value="{{titleValue_}}"
@@ -29,7 +29,7 @@
required>
</paper-input>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelButtonTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.js b/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.js
index 582417e708d..d3138fa8b93 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/edit_dialog.js
@@ -127,7 +127,9 @@ Polymer({
chrome.bookmarks.update(this.editItem_.id, edit);
} else {
edit['parentId'] = this.parentId_;
- chrome.bookmarks.create(edit);
+ bookmarks.ApiListener.trackUpdatedItems();
+ chrome.bookmarks.create(
+ edit, bookmarks.ApiListener.highlightUpdatedItems);
}
this.$.dialog.close();
},
diff --git a/chromium/chrome/browser/resources/md_bookmarks/folder_node.html b/chromium/chrome/browser/resources/md_bookmarks/folder_node.html
index e94af3f34da..57a4100e22a 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/folder_node.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/folder_node.html
@@ -80,16 +80,20 @@
<div id="container"
class="v-centered"
- draggable="true"
on-tap="selectFolder_"
+ on-dblclick="toggleFolder_"
on-contextmenu="onContextMenu_"
tabindex$="[[getTabIndex_(isSelectedFolder_)]]"
hidden="[[isRootFolder_(depth)]]"
role="treeitem">
<template is="dom-if" if="[[hasChildFolder_]]">
- <button is="paper-icon-button-light" id="arrow"
- on-tap="toggleFolder_" on-mousedown="preventDefault_" tabindex="-1">
- <iron-icon icon="cr:arrow-drop-down" is-open$="[[!isClosed_]]">
+ <button is="paper-icon-button-light"
+ id="arrow"
+ on-tap="toggleFolder_"
+ on-mousedown="preventDefault_"
+ tabindex="-1"
+ aria-hidden="true">
+ <iron-icon icon="cr:arrow-drop-down" is-open$="[[isOpen]]">
</iron-icon>
</button>
</template>
@@ -102,12 +106,13 @@
</div>
</div>
<div id="descendants" role="group">
- <template is="dom-if" if="[[!isClosed_]]">
+ <template is="dom-if" if="[[isOpen]]">
<template is="dom-repeat"
items="[[item_.children]]"
as="child"
filter="isFolder_">
<bookmarks-folder-node item-id="[[child]]"
+ draggable="true"
depth="[[getChildDepth_(depth)]]">
</bookmarks-folder-node>
</template>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/folder_node.js b/chromium/chrome/browser/resources/md_bookmarks/folder_node.js
index df6ac016a1a..b84e0b4c8f0 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/folder_node.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/folder_node.js
@@ -20,11 +20,16 @@ Polymer({
observer: 'depthChanged_',
},
+ isOpen: {
+ type: Boolean,
+ computed: 'computeIsOpen_(openState_, depth)',
+ },
+
/** @type {BookmarkNode} */
item_: Object,
- /** @private */
- isClosed_: Boolean,
+ /** @private {?boolean} */
+ openState_: Boolean,
/** @private */
selectedFolder_: String,
@@ -52,17 +57,17 @@ Polymer({
},
observers: [
- 'updateAriaExpanded_(hasChildFolder_, isClosed_)',
+ 'updateAriaExpanded_(hasChildFolder_, isOpen)',
],
/** @override */
attached: function() {
- this.watch('item_', function(state) {
- return state.nodes[this.itemId];
- }.bind(this));
- this.watch('isClosed_', function(state) {
- return state.closedFolders.has(this.itemId);
- }.bind(this));
+ this.watch('item_', (state) => state.nodes[this.itemId]);
+ this.watch('openState_', (state) => {
+ return state.folderOpenState.has(this.itemId) ?
+ state.folderOpenState.get(this.itemId) :
+ null;
+ });
this.watch('selectedFolder_', function(state) {
return state.selectedFolder;
});
@@ -145,7 +150,7 @@ Polymer({
// The right arrow opens a folder if closed and goes to the first child
// otherwise.
if (this.hasChildFolder_) {
- if (this.isClosed_) {
+ if (!this.isOpen) {
this.dispatch(
bookmarks.actions.changeFolderOpen(this.item_.id, true));
} else {
@@ -155,7 +160,7 @@ Polymer({
} else if (xDirection == -1) {
// The left arrow closes a folder if open and goes to the parent
// otherwise.
- if (this.hasChildFolder_ && !this.isClosed_) {
+ if (this.hasChildFolder_ && this.isOpen) {
this.dispatch(bookmarks.actions.changeFolderOpen(this.item_.id, false));
} else {
var parentFolderNode = this.getParentFolderNode_();
@@ -170,7 +175,7 @@ Polymer({
return;
// The current node's successor is its first child when open.
- if (!isChildFolderNodeFocused && yDirection == 1 && !this.isClosed_) {
+ if (!isChildFolderNodeFocused && yDirection == 1 && this.isOpen) {
var children = this.getChildFolderNodes_();
if (children.length)
newFocusFolderNode = children[0];
@@ -252,7 +257,7 @@ Polymer({
*/
getLastVisibleDescendant_: function() {
var children = this.getChildFolderNodes_();
- if (this.isClosed_ || children.length == 0)
+ if (!this.isOpen || children.length == 0)
return this;
return children.pop().getLastVisibleDescendant_();
@@ -286,13 +291,13 @@ Polymer({
},
/**
- * Occurs when the drop down arrow is tapped.
+ * Toggles whether the folder is open.
* @private
* @param {!Event} e
*/
toggleFolder_: function(e) {
this.dispatch(
- bookmarks.actions.changeFolderOpen(this.itemId, this.isClosed_));
+ bookmarks.actions.changeFolderOpen(this.itemId, !this.isOpen));
e.stopPropagation();
},
@@ -366,13 +371,23 @@ Polymer({
* Sets the 'aria-expanded' accessibility on nodes which need it. Note that
* aria-expanded="false" is different to having the attribute be undefined.
* @param {boolean} hasChildFolder
- * @param {boolean} isClosed
+ * @param {boolean} isOpen
* @private
*/
- updateAriaExpanded_: function(hasChildFolder, isClosed) {
+ updateAriaExpanded_: function(hasChildFolder, isOpen) {
if (hasChildFolder)
- this.getFocusTarget().setAttribute('aria-expanded', String(!isClosed));
+ this.getFocusTarget().setAttribute('aria-expanded', String(isOpen));
else
this.getFocusTarget().removeAttribute('aria-expanded');
},
+
+ /**
+ * @param {?boolean} openState
+ * @param {number} depth
+ * @return {boolean}
+ */
+ computeIsOpen_: function(openState, depth) {
+ return openState != null ? openState :
+ depth <= FOLDER_OPEN_BY_DEFAULT_DEPTH;
+ },
});
diff --git a/chromium/chrome/browser/resources/md_bookmarks/item.html b/chromium/chrome/browser/resources/md_bookmarks/item.html
index 398affb21b2..30c219c6e3b 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/item.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/item.html
@@ -10,19 +10,15 @@
<template>
<style include="shared-style">
:host {
- display: block;
- flex-direction: row;
- position: relative;
- }
-
- #url {
-webkit-padding-start: 20px;
- -webkit-user-select: none;
align-items: center;
color: inherit;
display: flex;
+ flex-direction: row;
height: 40px;
+ position: relative;
text-decoration: none;
+ user-select: none;
}
:host([is-selected-item_]) {
@@ -46,22 +42,22 @@
-webkit-margin-end: 12px;
}
</style>
- <div id="url">
- <div id="icon"></div>
- <div id="website-title">
- [[item_.title]]
- </div>
- <button is="paper-icon-button-light"
- class="more-vert-button"
- tabindex$="[[ironListTabIndex]]"
- title="$i18n{moreActionsButtonTitle}"
- on-click="onMenuButtonClick_"
- on-dblclick="onMenuButtonDblClick_">
- <div></div>
- <div></div>
- <div></div>
- </button>
+ <div id="icon"></div>
+ <div id="website-title">
+ [[item_.title]]
</div>
+ <button id="menuButton"
+ is="paper-icon-button-light"
+ class="more-vert-button"
+ tabindex$="[[ironListTabIndex]]"
+ title="$i18n{moreActionsButtonTitle}"
+ on-click="onMenuButtonClick_"
+ on-dblclick="onMenuButtonDblClick_"
+ aria-haspopup="menu">
+ <div></div>
+ <div></div>
+ <div></div>
+ </button>
</template>
<script src="chrome://bookmarks/item.js"></script>
<dom-module>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/item.js b/chromium/chrome/browser/resources/md_bookmarks/item.js
index 99e210f01fc..91e3f038970 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/item.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/item.js
@@ -45,16 +45,17 @@ Polymer({
'click': 'onClick_',
'dblclick': 'onDblClick_',
'contextmenu': 'onContextMenu_',
+ 'keydown': 'onKeydown_',
+ 'auxclick': 'onMiddleClick_',
+ 'mousedown': 'cancelMiddleMouseBehavior_',
+ 'mouseup': 'cancelMiddleMouseBehavior_',
},
/** @override */
attached: function() {
- this.watch('item_', function(store) {
- return store.nodes[this.itemId];
- }.bind(this));
- this.watch('isSelectedItem_', function(store) {
- return !!store.selection.items.has(this.itemId);
- }.bind(this));
+ this.watch('item_', (store) => store.nodes[this.itemId]);
+ this.watch(
+ 'isSelectedItem_', (store) => !!store.selection.items.has(this.itemId));
this.updateFromStore();
},
@@ -123,7 +124,10 @@ Polymer({
/** @private */
onItemChanged_: function() {
this.isFolder_ = !this.item_.url;
- this.setAttribute('aria-label', this.item_.title);
+ this.setAttribute(
+ 'aria-label',
+ this.item_.title || this.item_.url ||
+ loadTimeData.getString('folderLabel'));
},
/**
@@ -146,6 +150,17 @@ Polymer({
},
/**
+ * @private
+ * @param {KeyboardEvent} e
+ */
+ onKeydown_: function(e) {
+ if (e.key == 'ArrowLeft')
+ this.focus();
+ else if (e.key == 'ArrowRight')
+ this.$.menuButton.focus();
+ },
+
+ /**
* @param {MouseEvent} e
* @private
*/
@@ -160,6 +175,36 @@ Polymer({
},
/**
+ * @param {MouseEvent} e
+ * @private
+ */
+ onMiddleClick_: function(e) {
+ if (e.button != 1)
+ return;
+
+ this.selectThisItem_();
+ if (this.isFolder_)
+ return;
+
+ var commandManager = bookmarks.CommandManager.getInstance();
+ var itemSet = this.getState().selection.items;
+ var command = e.shiftKey ? Command.OPEN : Command.OPEN_NEW_TAB;
+ if (commandManager.canExecute(command, itemSet))
+ commandManager.handle(command, itemSet);
+ },
+
+ /**
+ * Prevent default middle-mouse behavior. On Windows, this prevents autoscroll
+ * (during mousedown), and on Linux this prevents paste (during mouseup).
+ * @param {MouseEvent} e
+ * @private
+ */
+ cancelMiddleMouseBehavior_: function(e) {
+ if (e.button == 1)
+ e.preventDefault();
+ },
+
+ /**
* @param {string} url
* @private
*/
diff --git a/chromium/chrome/browser/resources/md_bookmarks/list.html b/chromium/chrome/browser/resources/md_bookmarks/list.html
index ae6ee5e1d32..00f86dbff22 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/list.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/list.html
@@ -18,7 +18,7 @@
calc(var(--card-padding-side) - var(--splitter-width));
}
- #bookmarksCard {
+ #list {
@apply(--shadow-elevation-2dp);
background-color: #fff;
margin: 0 auto;
@@ -38,7 +38,7 @@
user-select: none;
}
</style>
- <iron-list items="[[displayedList_]]" id="bookmarksCard"
+ <iron-list id="list" items="[[displayedList_]]"
hidden$="[[isEmptyList_(displayedList_.length)]]" role="list">
<template>
<bookmarks-item item-id="[[item.id]]" draggable="true"
diff --git a/chromium/chrome/browser/resources/md_bookmarks/list.js b/chromium/chrome/browser/resources/md_bookmarks/list.js
index 0b14ed4dd24..823f955e8b1 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/list.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/list.js
@@ -20,7 +20,7 @@ Polymer({
type: Array,
value: function() {
// Use an empty list during initialization so that the databinding to
- // hide #bookmarksCard takes effect.
+ // hide #list takes effect.
return [];
},
},
@@ -50,7 +50,7 @@ Polymer({
},
attached: function() {
- var list = /** @type {IronListElement} */ (this.$.bookmarksCard);
+ var list = /** @type {IronListElement} */ (this.$.list);
list.scrollTarget = this;
this.watch('displayedIds_', function(state) {
@@ -64,8 +64,17 @@ Polymer({
});
this.updateFromStore();
- this.$.bookmarksCard.addEventListener(
+ this.$.list.addEventListener(
'keydown', this.onItemKeydown_.bind(this), true);
+
+ /** @private {function(!Event)} */
+ this.boundOnHighlightItems_ = this.onHighlightItems_.bind(this);
+ document.addEventListener('highlight-items', this.boundOnHighlightItems_);
+ },
+
+ detached: function() {
+ document.removeEventListener(
+ 'highlight-items', this.boundOnHighlightItems_);
},
/** @return {HTMLElement} */
@@ -89,7 +98,7 @@ Polymer({
var splices = Polymer.ArraySplice.calculateSplices(
/** @type {!Array<string>} */ (newValue),
/** @type {!Array<string>} */ (oldValue));
- splices.forEach(function(splice) {
+ splices.forEach((splice) => {
// TODO(calamity): Could use notifySplices to improve performance here.
var additions =
newValue.slice(splice.index, splice.index + splice.addedCount)
@@ -99,7 +108,7 @@ Polymer({
this.splice.apply(this, [
'displayedList_', splice.index, splice.removed.length
].concat(additions));
- }.bind(this));
+ });
}
},
@@ -108,6 +117,20 @@ Polymer({
this.scrollTop = 0;
},
+ /**
+ * Scroll the list so that |itemId| is visible, if it is not already.
+ * @param {string} itemId
+ * @private
+ */
+ scrollToId_: function(itemId) {
+ var index = this.displayedIds_.indexOf(itemId);
+ var list = this.$.list;
+ if (index >= 0 && index < list.firstVisibleIndex ||
+ index > list.lastVisibleIndex) {
+ list.scrollToIndex(index);
+ }
+ },
+
/** @private */
emptyListMessage_: function() {
var emptyListMessage = this.searchTerm_ ? 'noSearchResults' : 'emptyList';
@@ -129,7 +152,7 @@ Polymer({
* @private
*/
getIndexForItemElement_: function(el) {
- return this.$.bookmarksCard.modelForElement(el).index;
+ return this.$.list.modelForElement(el).index;
},
/**
@@ -137,12 +160,35 @@ Polymer({
* @private
*/
onOpenItemMenu_: function(e) {
- var index = this.displayedIds_.indexOf(
- /** @type {BookmarksItemElement} */ (e.path[0]).itemId);
- var list = this.$.bookmarksCard;
// If the item is not visible, scroll to it before rendering the menu.
- if (index < list.firstVisibleIndex || index > list.lastVisibleIndex)
- list.scrollToIndex(index);
+ this.scrollToId_(/** @type {BookmarksItemElement} */ (e.path[0]).itemId);
+ },
+
+ /**
+ * Highlight a list of items by selecting them, scrolling them into view and
+ * focusing the first item.
+ * @param {Event} e
+ * @private
+ */
+ onHighlightItems_: function(e) {
+ // Ensure that we only select items which are actually being displayed.
+ // This should only matter if an unrelated update to the bookmark model
+ // happens with the perfect timing to end up in a tracked batch update.
+ var toHighlight = /** @type {!Array<string>} */
+ (e.detail.filter((item) => this.displayedIds_.indexOf(item) != -1));
+
+ assert(toHighlight.length > 0);
+ var leadId = toHighlight[0];
+ this.dispatch(
+ bookmarks.actions.selectAll(toHighlight, this.getState(), leadId));
+
+ // Allow iron-list time to render additions to the list.
+ this.async(function() {
+ this.scrollToId_(leadId);
+ var leadIndex = this.displayedIds_.indexOf(leadId);
+ assert(leadIndex != -1);
+ this.$.list.focusItem(leadIndex);
+ });
},
/**
@@ -151,7 +197,7 @@ Polymer({
*/
onItemKeydown_: function(e) {
var handled = true;
- var list = this.$.bookmarksCard;
+ var list = this.$.list;
var focusMoved = false;
var focusedIndex =
this.getIndexForItemElement_(/** @type {HTMLElement} */ (e.target));
diff --git a/chromium/chrome/browser/resources/md_bookmarks/mouse_focus_behavior.js b/chromium/chrome/browser/resources/md_bookmarks/mouse_focus_behavior.js
index 85afefe14d9..63755568cee 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/mouse_focus_behavior.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/mouse_focus_behavior.js
@@ -17,14 +17,17 @@ cr.define('bookmarks', function() {
this.boundOnMousedown_ = this.onMousedown_.bind(this);
this.boundOnKeydown = this.onKeydown_.bind(this);
- this.addEventListener('mousedown', this.boundOnMousedown_);
- this.addEventListener('keydown', this.boundOnKeydown, true);
-
+ // These events are added to the document because capture doesn't work
+ // properly when listeners are added to a Polymer element, because the
+ // event is considered AT_TARGET for the element, and is evaluated after
+ // inner captures.
+ document.addEventListener('mousedown', this.boundOnMousedown_, true);
+ document.addEventListener('keydown', this.boundOnKeydown, true);
},
detached: function() {
- this.removeEventListener('mousedown', this.boundOnMousedown_);
- this.removeEventListener('keydown', this.boundOnKeydown, true);
+ document.removeEventListener('mousedown', this.boundOnMousedown_, true);
+ document.removeEventListener('keydown', this.boundOnKeydown, true);
},
/** @private */
@@ -32,13 +35,18 @@ cr.define('bookmarks', function() {
this.setAttribute(HIDE_FOCUS_RING_ATTRIBUTE, '');
},
- /** @private */
- onKeydown_: function() {
- this.removeAttribute(HIDE_FOCUS_RING_ATTRIBUTE);
+ /**
+ * @param {KeyboardEvent} e
+ * @private
+ */
+ onKeydown_: function(e) {
+ if (!['Shift', 'Alt', 'Control', 'Meta'].includes(e.key))
+ this.removeAttribute(HIDE_FOCUS_RING_ATTRIBUTE);
},
};
return {
+ HIDE_FOCUS_RING_ATTRIBUTE: HIDE_FOCUS_RING_ATTRIBUTE,
MouseFocusBehavior: MouseFocusBehavior,
};
});
diff --git a/chromium/chrome/browser/resources/md_bookmarks/reducers.js b/chromium/chrome/browser/resources/md_bookmarks/reducers.js
index 7154b83d59b..2255f7971ef 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/reducers.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/reducers.js
@@ -56,12 +56,12 @@ cr.define('bookmarks', function() {
* @return SelectionState
*/
SelectionState.deselectItems = function(selectionState, deleted) {
- return /** @type {SelectionState} */ Object.assign({}, selectionState, {
+ return /** @type {SelectionState} */ (Object.assign({}, selectionState, {
items: bookmarks.util.removeIdsFromSet(selectionState.items, deleted),
anchor: !selectionState.anchor || deleted.has(selectionState.anchor) ?
null :
selectionState.anchor,
- });
+ }));
};
/**
@@ -278,7 +278,7 @@ cr.define('bookmarks', function() {
Object.assign({}, node, {children: newChildren}));
});
- return bookmarks.util.removeIdsFromMap(newState, action.descendants);
+ return bookmarks.util.removeIdsFromObject(newState, action.descendants);
};
/**
@@ -368,42 +368,63 @@ cr.define('bookmarks', function() {
}
};
- var ClosedFolderState = {};
+ var FolderOpenState = {};
/**
- * @param {ClosedFolderState} closedFolders
+ * @param {FolderOpenState} folderOpenState
* @param {string|undefined} id
* @param {NodeMap} nodes
- * @return {ClosedFolderState}
+ * @return {FolderOpenState}
*/
- ClosedFolderState.openFolderAndAncestors = function(
- closedFolders, id, nodes) {
- var newClosedFolders = new Set(closedFolders);
- var currentId = id;
- while (currentId) {
- if (closedFolders.has(currentId))
- newClosedFolders.delete(currentId);
+ FolderOpenState.openFolderAndAncestors = function(
+ folderOpenState, id, nodes) {
+ var newFolderOpenState =
+ /** @type {FolderOpenState} */ (new Map(folderOpenState));
+ for (var currentId = id; currentId; currentId = nodes[currentId].parentId)
+ newFolderOpenState.set(currentId, true);
+
+ return newFolderOpenState;
+ };
- currentId = nodes[currentId].parentId;
- }
+ /**
+ * @param {FolderOpenState} folderOpenState
+ * @param {Action} action
+ * @return {FolderOpenState}
+ */
+ FolderOpenState.changeFolderOpen = function(folderOpenState, action) {
+ var newFolderOpenState =
+ /** @type {FolderOpenState} */ (new Map(folderOpenState));
+ newFolderOpenState.set(action.id, action.open);
- return newClosedFolders;
+ return newFolderOpenState;
};
/**
- * @param {ClosedFolderState} closedFolders
+ * @param {FolderOpenState} folderOpenState
* @param {Action} action
- * @return {ClosedFolderState}
+ * @param {NodeMap} nodes
+ * @return {FolderOpenState}
*/
- ClosedFolderState.changeFolderOpen = function(closedFolders, action) {
- var closed = !action.open;
- var newClosedFolders = new Set(closedFolders);
- if (closed)
- newClosedFolders.add(action.id);
- else
- newClosedFolders.delete(action.id);
-
- return newClosedFolders;
+ FolderOpenState.updateFolderOpenState = function(
+ folderOpenState, action, nodes) {
+ switch (action.name) {
+ case 'change-folder-open':
+ return FolderOpenState.changeFolderOpen(folderOpenState, action);
+ case 'select-folder':
+ return FolderOpenState.openFolderAndAncestors(
+ folderOpenState, nodes[action.id].parentId, nodes);
+ case 'move-bookmark':
+ if (!nodes[action.id].children)
+ return folderOpenState;
+
+ return FolderOpenState.openFolderAndAncestors(
+ folderOpenState, action.parentId, nodes);
+ case 'remove-bookmark':
+ return bookmarks.util.removeIdsFromMap(
+ folderOpenState, action.descendants);
+ default:
+ return folderOpenState;
+ }
};
var PreferencesState = {};
@@ -429,34 +450,6 @@ cr.define('bookmarks', function() {
};
/**
- * @param {ClosedFolderState} closedFolders
- * @param {Action} action
- * @param {NodeMap} nodes
- * @return {ClosedFolderState}
- */
- ClosedFolderState.updateClosedFolders = function(
- closedFolders, action, nodes) {
- switch (action.name) {
- case 'change-folder-open':
- return ClosedFolderState.changeFolderOpen(closedFolders, action);
- case 'select-folder':
- return ClosedFolderState.openFolderAndAncestors(
- closedFolders, nodes[action.id].parentId, nodes);
- case 'move-bookmark':
- if (!nodes[action.id].children)
- return closedFolders;
-
- return ClosedFolderState.openFolderAndAncestors(
- closedFolders, action.parentId, nodes);
- case 'remove-bookmark':
- return bookmarks.util.removeIdsFromSet(
- closedFolders, action.descendants);
- default:
- return closedFolders;
- }
- };
-
- /**
* Root reducer for the Bookmarks page. This is called by the store in
* response to an action, and the return value is used to update the UI.
* @param {!BookmarksPageState} state
@@ -468,8 +461,8 @@ cr.define('bookmarks', function() {
nodes: NodeState.updateNodes(state.nodes, action),
selectedFolder: SelectedFolderState.updateSelectedFolder(
state.selectedFolder, action, state.nodes),
- closedFolders: ClosedFolderState.updateClosedFolders(
- state.closedFolders, action, state.nodes),
+ folderOpenState: FolderOpenState.updateFolderOpenState(
+ state.folderOpenState, action, state.nodes),
prefs: PreferencesState.updatePrefs(state.prefs, action),
search: SearchState.updateSearch(state.search, action),
selection: SelectionState.updateSelection(state.selection, action),
@@ -478,7 +471,7 @@ cr.define('bookmarks', function() {
return {
reduceAction: reduceAction,
- ClosedFolderState: ClosedFolderState,
+ FolderOpenState: FolderOpenState,
NodeState: NodeState,
PreferencesState: PreferencesState,
SearchState: SearchState,
diff --git a/chromium/chrome/browser/resources/md_bookmarks/router.js b/chromium/chrome/browser/resources/md_bookmarks/router.js
index 431331e62b1..89267f9ef2b 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/router.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/router.js
@@ -63,10 +63,10 @@ Polymer({
this.selectedId_ = selectedId;
// Need to dispatch a deferred action so that during page load
// `this.getState()` will only evaluate after the Store is initialized.
- this.dispatchAsync(function(dispatch) {
+ this.dispatchAsync((dispatch) => {
dispatch(
bookmarks.actions.selectFolder(selectedId, this.getState().nodes));
- }.bind(this));
+ });
}
},
diff --git a/chromium/chrome/browser/resources/md_bookmarks/store.js b/chromium/chrome/browser/resources/md_bookmarks/store.js
index 7cbf93d854a..0b679e2a5c1 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/store.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/store.js
@@ -30,9 +30,9 @@ cr.define('bookmarks', function() {
init: function(initialState) {
this.data_ = initialState;
- this.queuedActions_.forEach(function(action) {
+ this.queuedActions_.forEach((action) => {
this.dispatchInternal_(action);
- }.bind(this));
+ });
this.initialized_ = true;
this.notifyObservers_(this.data_);
diff --git a/chromium/chrome/browser/resources/md_bookmarks/store_client.js b/chromium/chrome/browser/resources/md_bookmarks/store_client.js
index 40b751a90e3..b7149ea2831 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/store_client.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/store_client.js
@@ -79,18 +79,18 @@ cr.define('bookmarks', function() {
/** @param {string} newState */
onStateChanged: function(newState) {
- this.watches_.forEach(function(watch) {
+ this.watches_.forEach((watch) => {
var oldValue = this[watch.localProperty];
var newValue = watch.valueGetter(newState);
// Avoid poking Polymer unless something has actually changed. Reducers
// must return new objects rather than mutating existing objects, so
// any real changes will pass through correctly.
- if (oldValue == newValue || newValue == undefined)
+ if (oldValue === newValue || newValue === undefined)
return;
this[watch.localProperty] = newValue;
- }.bind(this));
+ });
},
updateFromStore: function() {
diff --git a/chromium/chrome/browser/resources/md_bookmarks/timer_proxy.js b/chromium/chrome/browser/resources/md_bookmarks/timer_proxy.js
index de96c7fdb4e..091023fecb5 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/timer_proxy.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/timer_proxy.js
@@ -13,7 +13,7 @@ cr.define('bookmarks', function() {
TimerProxy.prototype = {
/**
- * @param {Function|string} fn
+ * @param {function()|string} fn
* @param {number=} delay
* @return {number}
*/
@@ -27,7 +27,63 @@ cr.define('bookmarks', function() {
},
};
+ /**
+ * A one-shot debouncer which fires the given callback after a delay. The
+ * delay can be refreshed by calling resetTimer. Resetting with no delay moves
+ * the callback to the end of the task queue.
+ * @param {!function()} callback
+ * @constructor
+ */
+ function Debouncer(callback) {
+ /** @private {!function()} */
+ this.callback_ = callback;
+ /** @private {!bookmarks.TimerProxy} */
+ this.timerProxy_ = new TimerProxy();
+ /** @private {?number} */
+ this.timer_ = null;
+ /** @private {!function()} */
+ this.boundTimerCallback_ = this.timerCallback_.bind(this);
+ /** @private {boolean} */
+ this.isDone_ = false;
+ /** @private {!PromiseResolver} */
+ this.promiseResolver_ = new PromiseResolver();
+ }
+
+ Debouncer.prototype = {
+ /**
+ * @param {number=} delay
+ */
+ resetTimeout: function(delay) {
+ if (this.timer_)
+ this.timerProxy_.clearTimeout(this.timer_);
+ this.timer_ =
+ this.timerProxy_.setTimeout(this.boundTimerCallback_, delay);
+ },
+
+ /**
+ * @return {boolean} True if the Debouncer has finished processing.
+ */
+ done: function() {
+ return this.isDone_;
+ },
+
+ /**
+ * @return {Promise} Promise which resolves immediately after the callback.
+ */
+ get promise() {
+ return this.promiseResolver_.promise;
+ },
+
+ /** @private */
+ timerCallback_: function() {
+ this.isDone_ = true;
+ this.callback_.call();
+ this.promiseResolver_.resolve();
+ },
+ };
+
return {
+ Debouncer: Debouncer,
TimerProxy: TimerProxy,
};
});
diff --git a/chromium/chrome/browser/resources/md_bookmarks/toast_manager.js b/chromium/chrome/browser/resources/md_bookmarks/toast_manager.js
index 3692b5f949b..d2da7a5d5f8 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/toast_manager.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/toast_manager.js
@@ -94,10 +94,10 @@ cr.define('bookmarks', function() {
if (this.hideTimeoutId_ != null)
this.timerProxy_.clearTimeout(this.hideTimeoutId_);
- this.hideTimeoutId_ = this.timerProxy_.setTimeout(function() {
+ this.hideTimeoutId_ = this.timerProxy_.setTimeout(() => {
this.hide();
this.hideTimeoutId_ = null;
- }.bind(this), this.duration);
+ }, this.duration);
},
hide: function() {
diff --git a/chromium/chrome/browser/resources/md_bookmarks/toolbar.html b/chromium/chrome/browser/resources/md_bookmarks/toolbar.html
index 94911b0c99c..55fff095c76 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/toolbar.html
+++ b/chromium/chrome/browser/resources/md_bookmarks/toolbar.html
@@ -56,46 +56,42 @@
id="menuButton"
class="more-actions more-vert-button"
title="$i18n{organizeButtonTitle}"
- on-tap="onMenuButtonOpenTap_">
+ on-tap="onMenuButtonOpenTap_"
+ aria-haspopup="menu">
<div></div>
<div></div>
<div></div>
</button>
</cr-toolbar>
<template is="cr-lazy-render" id="dropdown">
- <dialog is="cr-action-menu" role="menu">
+ <dialog is="cr-action-menu">
<button id="sortButton"
class="dropdown-item"
on-tap="onSortTap_"
- disabled="[[!canSortFolder_]]"
- role="menuitem">
+ disabled="[[!canSortFolder_]]">
$i18n{menuSort}
</button>
- <hr>
+ <hr aria-hidden="true">
<button id="addBookmarkButton"
class="dropdown-item"
on-tap="onAddBookmarkTap_"
- disabled="[[!canChangeList_]]"
- role="menuitem">
+ disabled="[[!canChangeList_]]">
$i18n{menuAddBookmark}
</button>
<button class="dropdown-item"
on-tap="onAddFolderTap_"
- disabled="[[!canChangeList_]]"
- role="menuitem">
+ disabled="[[!canChangeList_]]">
$i18n{menuAddFolder}
</button>
- <hr>
+ <hr aria-hidden="true">
<button id="importBookmarkButton"
class="dropdown-item"
on-tap="onImportTap_"
- disabled="[[!globalCanEdit_]]"
- role="menuitem">
+ disabled="[[!globalCanEdit_]]">
$i18n{menuImport}
</button>
<button class="dropdown-item"
- on-tap="onExportTap_"
- role="menuitem">
+ on-tap="onExportTap_">
$i18n{menuExport}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/md_bookmarks/toolbar.js b/chromium/chrome/browser/resources/md_bookmarks/toolbar.js
index 0155ca92180..5923a896234 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/toolbar.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/toolbar.js
@@ -178,7 +178,7 @@ Polymer({
* @private
*/
computeCanSortFolder_: function() {
- return this.canChangeList_ && this.selectedFolderChildren_ > 0;
+ return this.canChangeList_ && this.selectedFolderChildren_ > 1;
},
/**
diff --git a/chromium/chrome/browser/resources/md_bookmarks/types.js b/chromium/chrome/browser/resources/md_bookmarks/types.js
index 6361f9dc7c6..560cf65d61c 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/types.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/types.js
@@ -55,8 +55,8 @@ var SelectionState;
*/
var SearchState;
-/** @typedef {!Set<string>} */
-var ClosedFolderState;
+/** @typedef {!Map<string, boolean>} */
+var FolderOpenState;
/**
* @typedef {{
@@ -70,7 +70,7 @@ var PreferencesState;
* @typedef {{
* nodes: NodeMap,
* selectedFolder: string,
- * closedFolders: ClosedFolderState,
+ * folderOpenState: FolderOpenState,
* prefs: PreferencesState,
* search: SearchState,
* selection: SelectionState,
diff --git a/chromium/chrome/browser/resources/md_bookmarks/util.js b/chromium/chrome/browser/resources/md_bookmarks/util.js
index 3760bdea171..acdd4240e9d 100644
--- a/chromium/chrome/browser/resources/md_bookmarks/util.js
+++ b/chromium/chrome/browser/resources/md_bookmarks/util.js
@@ -22,7 +22,7 @@ cr.define('bookmarks.util', function() {
/**
* @param {BookmarkTreeNode} treeNode
- * @return {BookmarkNode}
+ * @return {!BookmarkNode}
*/
function normalizeNode(treeNode) {
var node = Object.assign({}, treeNode);
@@ -69,7 +69,7 @@ cr.define('bookmarks.util', function() {
return {
nodes: {},
selectedFolder: BOOKMARKS_BAR_ID,
- closedFolders: new Set(),
+ folderOpenState: new Map(),
prefs: {
canEdit: true,
incognitoAvailability: IncognitoAvailability.ENABLED,
@@ -167,15 +167,39 @@ cr.define('bookmarks.util', function() {
}
/**
+ * @param {string} name
+ * @param {number} value
+ * @param {number} maxValue
+ */
+ function recordEnumHistogram(name, value, maxValue) {
+ chrome.send('metricsHandler:recordInHistogram', [name, value, maxValue]);
+ }
+
+ /**
* @param {!Object<string, T>} map
* @param {!Set<string>} ids
* @return {!Object<string, T>}
* @template T
*/
+ function removeIdsFromObject(map, ids) {
+ var newObject = Object.assign({}, map);
+ ids.forEach(function(id) {
+ delete newObject[id];
+ });
+ return newObject;
+ }
+
+
+ /**
+ * @param {!Map<string, T>} map
+ * @param {!Set<string>} ids
+ * @return {!Map<string, T>}
+ * @template T
+ */
function removeIdsFromMap(map, ids) {
- var newMap = Object.assign({}, map);
+ var newMap = new Map(map);
ids.forEach(function(id) {
- delete newMap[id];
+ newMap.delete(id);
});
return newMap;
}
@@ -203,7 +227,9 @@ cr.define('bookmarks.util', function() {
isShowingSearch: isShowingSearch,
normalizeNode: normalizeNode,
normalizeNodes: normalizeNodes,
+ recordEnumHistogram: recordEnumHistogram,
removeIdsFromMap: removeIdsFromMap,
+ removeIdsFromObject: removeIdsFromObject,
removeIdsFromSet: removeIdsFromSet,
};
});
diff --git a/chromium/chrome/browser/resources/md_downloads/.eslintrc.js b/chromium/chrome/browser/resources/md_downloads/.eslintrc.js
new file mode 100644
index 00000000000..847d6e99509
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_downloads/.eslintrc.js
@@ -0,0 +1,13 @@
+// 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.
+
+module.exports = {
+ 'env': {
+ 'browser': true,
+ 'es6': true,
+ },
+ 'rules': {
+ 'no-var': 'error',
+ },
+};
diff --git a/chromium/chrome/browser/resources/md_downloads/BUILD.gn b/chromium/chrome/browser/resources/md_downloads/BUILD.gn
index b0e66aaa26e..1b340e3511c 100644
--- a/chromium/chrome/browser/resources/md_downloads/BUILD.gn
+++ b/chromium/chrome/browser/resources/md_downloads/BUILD.gn
@@ -1,21 +1,11 @@
import("../vulcanize.gni")
-vulcanized_unbuilt = "vulcanized.unbuilt.html"
-
-vulcanize("vulcanize") {
+vulcanize("build") {
deps = []
host = "downloads"
- html_in_file = "downloads.html"
- html_out_file = vulcanized_unbuilt
+ html_in_files = [ "downloads.html" ]
+ html_out_files = [ "vulcanized.html" ]
input = rebase_path(".", root_build_dir)
insert_in_head = "<base href=chrome://downloads>"
- js_out_file = "crisper.js"
-}
-
-polymer_css_build("build") {
- input_files = [ vulcanized_unbuilt ]
- output_files = [ "vulcanized.html" ]
- deps = [
- ":vulcanize",
- ]
+ js_out_files = [ "crisper.js" ]
}
diff --git a/chromium/chrome/browser/resources/md_downloads/OWNERS b/chromium/chrome/browser/resources/md_downloads/OWNERS
index 455bfb52fad..cb00587830d 100644
--- a/chromium/chrome/browser/resources/md_downloads/OWNERS
+++ b/chromium/chrome/browser/resources/md_downloads/OWNERS
@@ -1,3 +1 @@
-dbeam@chromium.org
-
# COMPONENT: UI>Browser>Downloads
diff --git a/chromium/chrome/browser/resources/md_downloads/action_service.html b/chromium/chrome/browser/resources/md_downloads/action_service.html
index 0dce3440a71..7d59ba9e2f0 100644
--- a/chromium/chrome/browser/resources/md_downloads/action_service.html
+++ b/chromium/chrome/browser/resources/md_downloads/action_service.html
@@ -1,4 +1,4 @@
-<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://downloads/i18n_setup.html">
+<link rel="import" href="chrome://downloads/browser_proxy.html">
<script src="chrome://downloads/action_service.js"></script>
diff --git a/chromium/chrome/browser/resources/md_downloads/action_service.js b/chromium/chrome/browser/resources/md_downloads/action_service.js
index 7dec7eec0d7..67e515c6441 100644
--- a/chromium/chrome/browser/resources/md_downloads/action_service.js
+++ b/chromium/chrome/browser/resources/md_downloads/action_service.js
@@ -3,120 +3,55 @@
// found in the LICENSE file.
cr.define('downloads', function() {
- /**
- * @param {string} chromeSendName
- * @return {function(string):void} A chrome.send() callback with curried name.
- */
- function chromeSendWithId(chromeSendName) {
- return function(id) {
- chrome.send(chromeSendName, [id]);
- };
- }
-
- /** @constructor */
- function ActionService() {
- /** @private {Array<string>} */
- this.searchTerms_ = [];
- }
-
- /**
- * @param {string} s
- * @return {string} |s| without whitespace at the beginning or end.
- */
- function trim(s) {
- return s.trim();
- }
-
- /**
- * @param {string|undefined} value
- * @return {boolean} Whether |value| is truthy.
- */
- function truthy(value) {
- return !!value;
- }
+ // TODO(dpapad): Rename to SearchService.
+ class ActionService {
+ constructor() {
+ /** @private {!Array<string>} */
+ this.searchTerms_ = [];
- /**
- * @param {string} searchText Input typed by the user into a search box.
- * @return {Array<string>} A list of terms extracted from |searchText|.
- */
- ActionService.splitTerms = function(searchText) {
- // Split quoted terms (e.g., 'The "lazy" dog' => ['The', 'lazy', 'dog']).
- return searchText.split(/"([^"]*)"/).map(trim).filter(truthy);
- };
+ /** @private {!downloads.BrowserProxy} */
+ this.browserProxy_ = downloads.BrowserProxy.getInstance();
+ }
- ActionService.prototype = {
- /** @param {string} id ID of the download to cancel. */
- cancel: chromeSendWithId('cancel'),
+ /**
+ * @param {string} searchText Input typed by the user into a search box.
+ * @return {Array<string>} A list of terms extracted from |searchText|.
+ */
+ static splitTerms(searchText) {
+ // Split quoted terms (e.g., 'The "lazy" dog' => ['The', 'lazy', 'dog']).
+ return searchText.split(/"([^"]*)"/).map(s => s.trim()).filter(s => !!s);
+ }
/** Instructs the browser to clear all finished downloads. */
- clearAll: function() {
+ clearAll() {
if (loadTimeData.getBoolean('allowDeletingHistory')) {
- chrome.send('clearAll');
+ this.browserProxy_.clearAll();
this.search('');
}
- },
-
- /** @param {string} id ID of the dangerous download to discard. */
- discardDangerous: chromeSendWithId('discardDangerous'),
-
- /** @param {string} url URL of a file to download. */
- download: function(url) {
- var a = document.createElement('a');
- a.href = url;
- a.setAttribute('download', '');
- a.click();
- },
-
- /** @param {string} id ID of the download that the user started dragging. */
- drag: chromeSendWithId('drag'),
+ }
/** Loads more downloads with the current search terms. */
- loadMore: function() {
- chrome.send('getDownloads', this.searchTerms_);
- },
+ loadMore() {
+ this.browserProxy_.getDownloads(this.searchTerms_);
+ }
/**
* @return {boolean} Whether the user is currently searching for downloads
* (i.e. has a non-empty search term).
*/
- isSearching: function() {
+ isSearching() {
return this.searchTerms_.length > 0;
- },
-
- /** Opens the current local destination for downloads. */
- openDownloadsFolder: function() {
- chrome.send('openDownloadsFolderRequiringGesture');
- },
-
- /**
- * @param {string} id ID of the download to run locally on the user's box.
- */
- openFile: chromeSendWithId('openFileRequiringGesture'),
-
- /** @param {string} id ID the of the progressing download to pause. */
- pause: chromeSendWithId('pause'),
-
- /** @param {string} id ID of the finished download to remove. */
- remove: chromeSendWithId('remove'),
-
- /** @param {string} id ID of the paused download to resume. */
- resume: chromeSendWithId('resume'),
-
- /**
- * @param {string} id ID of the dangerous download to save despite
- * warnings.
- */
- saveDangerous: chromeSendWithId('saveDangerousRequiringGesture'),
+ }
/**
* @param {string} searchText What to search for.
* @return {boolean} Whether |searchText| resulted in new search terms.
*/
- search: function(searchText) {
- var searchTerms = ActionService.splitTerms(searchText);
- var sameTerms = searchTerms.length == this.searchTerms_.length;
+ search(searchText) {
+ const searchTerms = ActionService.splitTerms(searchText);
+ let sameTerms = searchTerms.length == this.searchTerms_.length;
- for (var i = 0; sameTerms && i < searchTerms.length; ++i) {
+ for (let i = 0; sameTerms && i < searchTerms.length; ++i) {
if (searchTerms[i] != this.searchTerms_[i])
sameTerms = false;
}
@@ -127,17 +62,8 @@ cr.define('downloads', function() {
this.searchTerms_ = searchTerms;
this.loadMore();
return true;
- },
-
- /**
- * Shows the local folder a finished download resides in.
- * @param {string} id ID of the download to show.
- */
- show: chromeSendWithId('show'),
-
- /** Undo download removal. */
- undo: chrome.send.bind(chrome, 'undo'),
- };
+ }
+ }
cr.addSingletonGetter(ActionService);
diff --git a/chromium/chrome/browser/resources/md_downloads/action_service_unittest.gtestjs b/chromium/chrome/browser/resources/md_downloads/action_service_unittest.gtestjs
index d7670bd870e..bc3524bc5f9 100644
--- a/chromium/chrome/browser/resources/md_downloads/action_service_unittest.gtestjs
+++ b/chromium/chrome/browser/resources/md_downloads/action_service_unittest.gtestjs
@@ -10,24 +10,19 @@ function str(list) {
return JSON.stringify(list);
}
-/**
- * @extends {testing.Test}
- * @constructor
- */
-function ActionServiceUnitTest() {}
-
-ActionServiceUnitTest.prototype = {
- __proto__: testing.Test.prototype,
-
+var ActionServiceUnitTest = class extends testing.Test {
/** @override */
- extraLibraries: [
- '../../../../ui/webui/resources/js/cr.js',
- 'action_service.js',
- ],
-};
+ get extraLibraries() {
+ return [
+ '../../../../ui/webui/resources/js/cr.js',
+ 'browser_proxy.js',
+ 'action_service.js',
+ ];
+ }
+}
TEST_F('ActionServiceUnitTest', 'splitTerms', function() {
- var ActionService = downloads.ActionService;
+ const ActionService = downloads.ActionService;
assertEquals(str([]), str(ActionService.splitTerms('')));
assertEquals(str([]), str(ActionService.splitTerms(' ')));
assertEquals(str(['a']), str(ActionService.splitTerms('a')));
@@ -39,20 +34,11 @@ TEST_F('ActionServiceUnitTest', 'splitTerms', function() {
});
TEST_F('ActionServiceUnitTest', 'searchWithSimilarTerms', function() {
- /**
- * @extends {downloads.ActionService}
- * @constructor
- */
- function TestActionService() {
- downloads.ActionService.call(this);
+ class TestActionService extends downloads.ActionService {
+ loadMore() { /* No chrome.send() for you! */ }
}
- TestActionService.prototype = {
- __proto__: downloads.ActionService.prototype,
- loadMore: function() { /* No chrome.send() for you! */ },
- };
-
- var actionService = new TestActionService();
+ const actionService = new TestActionService();
assertTrue(actionService.search('a'));
assertFalse(actionService.search('a ')); // Same term + space should no-op.
diff --git a/chromium/chrome/browser/resources/md_downloads/browser_proxy.html b/chromium/chrome/browser/resources/md_downloads/browser_proxy.html
new file mode 100644
index 00000000000..245093d8f43
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_downloads/browser_proxy.html
@@ -0,0 +1,2 @@
+<link rel="import" href="chrome://resources/html/cr.html">
+<script src="browser_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/md_downloads/browser_proxy.js b/chromium/chrome/browser/resources/md_downloads/browser_proxy.js
new file mode 100644
index 00000000000..e85d85dc755
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_downloads/browser_proxy.js
@@ -0,0 +1,95 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('downloads', function() {
+ class BrowserProxy {
+ /** @param {string} id ID of the download to cancel. */
+ cancel(id) {
+ chrome.send('cancel', [id]);
+ }
+
+ /** @param {string} id ID of the dangerous download to discard. */
+ discardDangerous(id) {
+ chrome.send('discardDangerous', [id]);
+ }
+
+ /** @param {string} url URL of a file to download. */
+ download(url) {
+ const a = document.createElement('a');
+ a.href = url;
+ a.setAttribute('download', '');
+ a.click();
+ }
+
+ /** @param {string} id ID of the download that the user started dragging. */
+ drag(id) {
+ chrome.send('drag', [id]);
+ }
+
+ /**
+ * Loads more downloads with the current search terms.
+ * @param {!Array<string>} searchTerms
+ */
+ getDownloads(searchTerms) {
+ chrome.send('getDownloads', searchTerms);
+ }
+
+ /** Opens the current local destination for downloads. */
+ openDownloadsFolder() {
+ chrome.send('openDownloadsFolderRequiringGesture');
+ }
+
+ /**
+ * @param {string} id ID of the download to run locally on the user's box.
+ */
+ openFile(id) {
+ chrome.send('openFileRequiringGesture', [id]);
+ }
+
+ /** @param {string} id ID the of the progressing download to pause. */
+ pause(id) {
+ chrome.send('pause', [id]);
+ }
+
+ /** @param {string} id ID of the finished download to remove. */
+ remove(id) {
+ chrome.send('remove', [id]);
+ }
+
+ /** Instructs the browser to clear all finished downloads. */
+ clearAll() {
+ chrome.send('clearAll');
+ }
+
+ /** @param {string} id ID of the paused download to resume. */
+ resume(id) {
+ chrome.send('resume', [id]);
+ }
+
+ /**
+ * @param {string} id ID of the dangerous download to save despite
+ * warnings.
+ */
+ saveDangerous(id) {
+ chrome.send('saveDangerousRequiringGesture', [id]);
+ }
+
+ /**
+ * Shows the local folder a finished download resides in.
+ * @param {string} id ID of the download to show.
+ */
+ show(id) {
+ chrome.send('show', [id]);
+ }
+
+ /** Undo download removal. */
+ undo() {
+ chrome.send('undo');
+ }
+ }
+
+ cr.addSingletonGetter(BrowserProxy);
+
+ return {BrowserProxy: BrowserProxy};
+});
diff --git a/chromium/chrome/browser/resources/md_downloads/compiled_resources2.gyp b/chromium/chrome/browser/resources/md_downloads/compiled_resources2.gyp
index a435a08c6ad..19accde00e5 100644
--- a/chromium/chrome/browser/resources/md_downloads/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/md_downloads/compiled_resources2.gyp
@@ -6,9 +6,16 @@
{
'target_name': 'action_service',
'dependencies': [
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
+ 'browser_proxy',
+ ],
+ 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
+ },
+ {
+ 'target_name': 'browser_proxy',
+ 'dependencies': [
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -37,7 +44,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/compiled_resources2.gyp:paper-inky-focus-behavior-extracted',
'constants',
- 'action_service',
+ 'browser_proxy',
'externs',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
@@ -52,6 +59,7 @@
'<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:command',
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-list/compiled_resources2.gyp:iron-list-extracted',
'action_service',
+ 'browser_proxy',
'item',
'toolbar',
'<(EXTERNS_GYP):chrome_send',
@@ -69,6 +77,7 @@
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-a11y-announcer/compiled_resources2.gyp:iron-a11y-announcer-extracted',
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-menu/compiled_resources2.gyp:paper-menu-extracted',
'action_service',
+ 'browser_proxy',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
diff --git a/chromium/chrome/browser/resources/md_downloads/constants.js b/chromium/chrome/browser/resources/md_downloads/constants.js
index b123be03919..2db3e1169c5 100644
--- a/chromium/chrome/browser/resources/md_downloads/constants.js
+++ b/chromium/chrome/browser/resources/md_downloads/constants.js
@@ -7,7 +7,7 @@ cr.define('downloads', function() {
* Explains why a download is in DANGEROUS state.
* @enum {string}
*/
- var DangerType = {
+ const DangerType = {
NOT_DANGEROUS: 'NOT_DANGEROUS',
DANGEROUS_FILE: 'DANGEROUS_FILE',
DANGEROUS_URL: 'DANGEROUS_URL',
@@ -22,7 +22,7 @@ cr.define('downloads', function() {
* DownloadsDOMHandler::CreateDownloadItemValue
* @enum {string}
*/
- var States = {
+ const States = {
IN_PROGRESS: 'IN_PROGRESS',
CANCELLED: 'CANCELLED',
COMPLETE: 'COMPLETE',
diff --git a/chromium/chrome/browser/resources/md_downloads/externs.js b/chromium/chrome/browser/resources/md_downloads/externs.js
index 51830ff98a9..69865902989 100644
--- a/chromium/chrome/browser/resources/md_downloads/externs.js
+++ b/chromium/chrome/browser/resources/md_downloads/externs.js
@@ -7,6 +7,7 @@
* @externs
*/
+// eslint-disable-next-line no-var
var downloads = {};
/**
diff --git a/chromium/chrome/browser/resources/md_downloads/item.html b/chromium/chrome/browser/resources/md_downloads/item.html
index 84f94d04635..a230d16a3d3 100644
--- a/chromium/chrome/browser/resources/md_downloads/item.html
+++ b/chromium/chrome/browser/resources/md_downloads/item.html
@@ -11,7 +11,7 @@
<link rel="import" href="chrome://resources/polymer/v1_0/paper-progress/paper-progress.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html">
-<link rel="import" href="chrome://downloads/action_service.html">
+<link rel="import" href="chrome://downloads/browser_proxy.html">
<link rel="import" href="chrome://downloads/constants.html">
<link rel="import" href="chrome://downloads/i18n_setup.html">
<link rel="import" href="chrome://downloads/icons.html">
diff --git a/chromium/chrome/browser/resources/md_downloads/item.js b/chromium/chrome/browser/resources/md_downloads/item.js
index 47b216a12b1..d589ab8cadd 100644
--- a/chromium/chrome/browser/resources/md_downloads/item.js
+++ b/chromium/chrome/browser/resources/md_downloads/item.js
@@ -3,7 +3,7 @@
// found in the LICENSE file.
cr.define('downloads', function() {
- var Item = Polymer({
+ const Item = Polymer({
is: 'downloads-item',
properties: {
@@ -74,7 +74,12 @@ cr.define('downloads', function() {
'observeIsDangerous_(isDangerous_, data)',
],
+ /** @private {?downloads.BrowserProxy} */
+ browserProxy_: null,
+
+ /** @override */
ready: function() {
+ this.browserProxy_ = downloads.BrowserProxy.getInstance();
this.content = this.$.content;
},
@@ -89,7 +94,7 @@ cr.define('downloads', function() {
/** @private */
computeClass_: function() {
- var classes = [];
+ const classes = [];
if (this.isActive_)
classes.push('is-active');
@@ -114,8 +119,8 @@ cr.define('downloads', function() {
if (!this.data.by_ext_id || !this.data.by_ext_name)
return '';
- var url = 'chrome://extensions#' + this.data.by_ext_id;
- var name = this.data.by_ext_name;
+ const url = 'chrome://extensions#' + this.data.by_ext_id;
+ const name = this.data.by_ext_name;
return loadTimeData.getStringF('controlledByUrl', url, HTMLEscape(name));
},
@@ -134,11 +139,11 @@ cr.define('downloads', function() {
/** @private */
computeDescription_: function() {
- var data = this.data;
+ const data = this.data;
switch (data.state) {
case downloads.States.DANGEROUS:
- var fileName = data.file_name;
+ const fileName = data.file_name;
switch (data.danger_type) {
case downloads.DangerType.DANGEROUS_FILE:
return loadTimeData.getString('dangerFileDesc');
@@ -201,8 +206,8 @@ cr.define('downloads', function() {
/** @private */
computeRemoveStyle_: function() {
- var canDelete = loadTimeData.getBoolean('allowDeletingHistory');
- var hideRemove = this.isDangerous_ || this.showCancel_ || !canDelete;
+ const canDelete = loadTimeData.getBoolean('allowDeletingHistory');
+ const hideRemove = this.isDangerous_ || this.showCancel_ || !canDelete;
return hideRemove ? 'visibility: hidden' : '';
},
@@ -254,20 +259,20 @@ cr.define('downloads', function() {
this.$.url.removeAttribute('href');
} else {
this.$.url.href = assert(this.data.url);
- var filePath = encodeURIComponent(this.data.file_path);
- var scaleFactor = '?scale=' + window.devicePixelRatio + 'x';
+ const filePath = encodeURIComponent(this.data.file_path);
+ const scaleFactor = '?scale=' + window.devicePixelRatio + 'x';
this.$['file-icon'].src = 'chrome://fileicon/' + filePath + scaleFactor;
}
},
/** @private */
onCancelTap_: function() {
- downloads.ActionService.getInstance().cancel(this.data.id);
+ this.browserProxy_.cancel(this.data.id);
},
/** @private */
onDiscardDangerousTap_: function() {
- downloads.ActionService.getInstance().discardDangerous(this.data.id);
+ this.browserProxy_.discardDangerous(this.data.id);
},
/**
@@ -276,7 +281,7 @@ cr.define('downloads', function() {
*/
onDragStart_: function(e) {
e.preventDefault();
- downloads.ActionService.getInstance().drag(this.data.id);
+ this.browserProxy_.drag(this.data.id);
},
/**
@@ -285,35 +290,35 @@ cr.define('downloads', function() {
*/
onFileLinkTap_: function(e) {
e.preventDefault();
- downloads.ActionService.getInstance().openFile(this.data.id);
+ this.browserProxy_.openFile(this.data.id);
},
/** @private */
onPauseOrResumeTap_: function() {
if (this.isInProgress_)
- downloads.ActionService.getInstance().pause(this.data.id);
+ this.browserProxy_.pause(this.data.id);
else
- downloads.ActionService.getInstance().resume(this.data.id);
+ this.browserProxy_.resume(this.data.id);
},
/** @private */
onRemoveTap_: function() {
- downloads.ActionService.getInstance().remove(this.data.id);
+ this.browserProxy_.remove(this.data.id);
},
/** @private */
onRetryTap_: function() {
- downloads.ActionService.getInstance().download(this.data.url);
+ this.browserProxy_.download(this.data.url);
},
/** @private */
onSaveDangerousTap_: function() {
- downloads.ActionService.getInstance().saveDangerous(this.data.id);
+ this.browserProxy_.saveDangerous(this.data.id);
},
/** @private */
onShowTap_: function() {
- downloads.ActionService.getInstance().show(this.data.id);
+ this.browserProxy_.show(this.data.id);
},
});
diff --git a/chromium/chrome/browser/resources/md_downloads/manager.html b/chromium/chrome/browser/resources/md_downloads/manager.html
index 4733d0ed297..ef562191652 100644
--- a/chromium/chrome/browser/resources/md_downloads/manager.html
+++ b/chromium/chrome/browser/resources/md_downloads/manager.html
@@ -8,6 +8,7 @@
<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-announcer/iron-a11y-announcer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
<link rel="import" href="chrome://downloads/action_service.html">
+<link rel="import" href="chrome://downloads/browser_proxy.html">
<link rel="import" href="chrome://downloads/constants.html">
<link rel="import" href="chrome://downloads/i18n_setup.html">
<link rel="import" href="chrome://downloads/item.html">
diff --git a/chromium/chrome/browser/resources/md_downloads/manager.js b/chromium/chrome/browser/resources/md_downloads/manager.js
index b3ebe46d975..f6471eafbb0 100644
--- a/chromium/chrome/browser/resources/md_downloads/manager.js
+++ b/chromium/chrome/browser/resources/md_downloads/manager.js
@@ -3,7 +3,7 @@
// found in the LICENSE file.
cr.define('downloads', function() {
- var Manager = Polymer({
+ const Manager = Polymer({
is: 'downloads-manager',
properties: {
@@ -55,13 +55,26 @@ cr.define('downloads', function() {
'itemsChanged_(items_.*)',
],
- attached: function() {
- document.documentElement.classList.remove('loading');
- },
+ /** @private {?downloads.BrowserProxy} */
+ browserProxy_: null,
+
+ /** @private {?downloads.ActionService} */
+ actionService_: null,
/** @private {!PromiseResolver} */
loaded_: new PromiseResolver,
+ /** @override */
+ created: function() {
+ this.browserProxy_ = downloads.BrowserProxy.getInstance();
+ this.actionService_ = downloads.ActionService.getInstance();
+ },
+
+ /** @override */
+ attached: function() {
+ document.documentElement.classList.remove('loading');
+ },
+
/** @private */
clearAll_: function() {
this.set('items_', []);
@@ -142,19 +155,19 @@ cr.define('downloads', function() {
*/
onCommand_: function(e) {
if (e.command.id == 'clear-all-command')
- downloads.ActionService.getInstance().clearAll();
+ this.browserProxy_.clearAll();
else if (e.command.id == 'undo-command')
- downloads.ActionService.getInstance().undo();
+ this.browserProxy_.undo();
else if (e.command.id == 'find-command')
this.$.toolbar.onFindCommand();
},
/** @private */
onListScroll_: function() {
- var list = this.$['downloads-list'];
+ const list = this.$['downloads-list'];
if (list.scrollHeight - list.scrollTop - list.offsetHeight <= 100) {
// Approaching the end of the scrollback. Attempt to load more items.
- downloads.ActionService.getInstance().loadMore();
+ this.actionService_.loadMore();
}
this.hasShadow_ = list.scrollTop > 0;
},
@@ -168,13 +181,13 @@ cr.define('downloads', function() {
document.addEventListener('canExecute', this.onCanExecute_.bind(this));
document.addEventListener('command', this.onCommand_.bind(this));
- downloads.ActionService.getInstance().loadMore();
+ this.actionService_.loadMore();
return this.loaded_.promise;
},
/** @private */
onSearchChanged_: function() {
- this.inSearchMode_ = downloads.ActionService.getInstance().isSearching();
+ this.inSearchMode_ = this.actionService_.isSearching();
},
/**
@@ -193,12 +206,12 @@ cr.define('downloads', function() {
* @private
*/
updateHideDates_: function(start, end) {
- for (var i = start; i <= end; ++i) {
- var current = this.items_[i];
+ for (let i = start; i <= end; ++i) {
+ const current = this.items_[i];
if (!current)
continue;
- var prev = this.items_[i - 1];
- var hideDate = !!prev && prev.date_string == current.date_string;
+ const prev = this.items_[i - 1];
+ const hideDate = !!prev && prev.date_string == current.date_string;
this.set('items_.' + i + '.hideDate', hideDate);
}
},
@@ -211,7 +224,7 @@ cr.define('downloads', function() {
updateItem_: function(index, data) {
this.set('items_.' + index, data);
this.updateHideDates_(index, index);
- var list = /** @type {!IronListElement} */ (this.$['downloads-list']);
+ const list = /** @type {!IronListElement} */ (this.$['downloads-list']);
list.updateSizeForItem(index);
},
});
diff --git a/chromium/chrome/browser/resources/md_downloads/toolbar.html b/chromium/chrome/browser/resources/md_downloads/toolbar.html
index 43f9c299d09..e53051b129c 100644
--- a/chromium/chrome/browser/resources/md_downloads/toolbar.html
+++ b/chromium/chrome/browser/resources/md_downloads/toolbar.html
@@ -1,6 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://downloads/action_service.html">
+<link rel="import" href="chrome://downloads/browser_proxy.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
@@ -45,14 +46,11 @@
<iron-icon icon="cr:more-vert"></iron-icon>
</button>
</cr-toolbar>
- <!-- TODO(dbeam): should cr-action-menu be role="menu" by default? -->
- <dialog is="cr-action-menu" id="moreActionsMenu" role="menu">
- <button class="dropdown-item clear-all" on-tap="onClearAllTap_"
- role="menuitem">
+ <dialog is="cr-action-menu" id="moreActionsMenu">
+ <button class="dropdown-item clear-all" on-tap="onClearAllTap_">
$i18n{clearAll}
</div>
- <button class="dropdown-item" on-tap="onOpenDownloadsFolderTap_"
- role="menuitem">
+ <button class="dropdown-item" on-tap="onOpenDownloadsFolderTap_">
$i18n{openDownloadsFolder}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/md_downloads/toolbar.js b/chromium/chrome/browser/resources/md_downloads/toolbar.js
index d533889dca3..a542050d947 100644
--- a/chromium/chrome/browser/resources/md_downloads/toolbar.js
+++ b/chromium/chrome/browser/resources/md_downloads/toolbar.js
@@ -3,7 +3,7 @@
// found in the LICENSE file.
cr.define('downloads', function() {
- var Toolbar = Polymer({
+ const Toolbar = Polymer({
is: 'downloads-toolbar',
properties: {
@@ -20,6 +20,14 @@ cr.define('downloads', function() {
},
},
+ /** @private {?downloads.BrowserProxy} */
+ browserProxy_: null,
+
+ /** @override */
+ ready: function() {
+ this.browserProxy_ = downloads.BrowserProxy.getInstance();
+ },
+
/** @return {boolean} Whether removal can be undone. */
canUndo: function() {
return !this.$.toolbar.getSearchField().isSearchFocused();
@@ -47,7 +55,7 @@ cr.define('downloads', function() {
/** @private */
onClearAllTap_: function() {
assert(this.canClearAll());
- downloads.ActionService.getInstance().clearAll();
+ this.browserProxy_.clearAll();
this.$.moreActionsMenu.close();
},
@@ -61,7 +69,7 @@ cr.define('downloads', function() {
* @private
*/
onSearchChanged_: function(event) {
- var actionService = downloads.ActionService.getInstance();
+ const actionService = downloads.ActionService.getInstance();
if (actionService.search(/** @type {string} */ (event.detail)))
this.spinnerActive = actionService.isSearching();
this.updateClearAll_();
@@ -69,7 +77,7 @@ cr.define('downloads', function() {
/** @private */
onOpenDownloadsFolderTap_: function() {
- downloads.ActionService.getInstance().openDownloadsFolder();
+ this.browserProxy_.openDownloadsFolder();
this.$.moreActionsMenu.close();
},
diff --git a/chromium/chrome/browser/resources/md_extensions/.eslintrc.js b/chromium/chrome/browser/resources/md_extensions/.eslintrc.js
new file mode 100644
index 00000000000..847d6e99509
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_extensions/.eslintrc.js
@@ -0,0 +1,13 @@
+// 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.
+
+module.exports = {
+ 'env': {
+ 'browser': true,
+ 'es6': true,
+ },
+ 'rules': {
+ 'no-var': 'error',
+ },
+};
diff --git a/chromium/chrome/browser/resources/md_extensions/OWNERS b/chromium/chrome/browser/resources/md_extensions/OWNERS
index 9f0111412ab..4efe53bd104 100644
--- a/chromium/chrome/browser/resources/md_extensions/OWNERS
+++ b/chromium/chrome/browser/resources/md_extensions/OWNERS
@@ -1,5 +1,5 @@
rdevlin.cronin@chromium.org
-dbeam@chromium.org
+scottchen@chromium.org
# TEAM: extensions-dev@chromium.org
# COMPONENT: Platform>Extensions
diff --git a/chromium/chrome/browser/resources/md_extensions/animation_helper.html b/chromium/chrome/browser/resources/md_extensions/animation_helper.html
deleted file mode 100644
index 0fd0053b1e3..00000000000
--- a/chromium/chrome/browser/resources/md_extensions/animation_helper.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/hero-animation.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-in-animation.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-out-animation.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/scale-down-animation.html">
-<script src="chrome://extensions/animation_helper.js"></script>
diff --git a/chromium/chrome/browser/resources/md_extensions/animation_helper.js b/chromium/chrome/browser/resources/md_extensions/animation_helper.js
deleted file mode 100644
index 00483b37d41..00000000000
--- a/chromium/chrome/browser/resources/md_extensions/animation_helper.js
+++ /dev/null
@@ -1,96 +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.
-
-cr.exportPath('extensions');
-
-/**
- * The different types of animations this helper supports.
- * @enum {number}
- */
-extensions.Animation = {
- HERO: 0,
- FADE_IN: 1,
- FADE_OUT: 2,
- SCALE_DOWN: 3,
-};
-
-cr.define('extensions', function() {
- 'use strict';
-
- /**
- * A helper object for setting entry/exit animations. Polymer's support of
- * this is pretty limited, since it doesn't allow for things like specifying
- * hero properties or nodes.
- */
- class AnimationHelper {
- /**
- * @param {!HTMLElement} element The parent element to set the animations
- * on. This will be used as the page in to/fromPage.
- * @param {?HTMLElement} node The node to use for scaling and fading
- * animations.
- */
- constructor(element, node) {
- this.element_ = element;
- this.node_ = node;
- element.animationConfig = {};
- }
-
- /**
- * Set the entry animation for the element.
- * @param {!Array<extensions.Animation>} animations
- */
- setEntryAnimations(animations) {
- var configs = [];
- for (let animation of animations) {
- switch (animation) {
- case extensions.Animation.HERO:
- configs.push(
- {name: 'hero-animation', id: 'hero', toPage: this.element_});
- break;
- case extensions.Animation.FADE_IN:
- assert(this.node_);
- configs.push({name: 'fade-in-animation', node: this.node_});
- break;
- default:
- assertNotReached();
- }
- }
- this.element_.animationConfig.entry = configs;
- }
-
- /**
- * Set the exit animation for the element.
- * @param {!Array<extensions.Animation>} animations
- */
- setExitAnimations(animations) {
- var configs = [];
- for (let animation of animations) {
- switch (animation) {
- case extensions.Animation.HERO:
- configs.push(
- {name: 'hero-animation', id: 'hero', fromPage: this.element_});
- break;
- case extensions.Animation.FADE_OUT:
- assert(this.node_);
- configs.push({name: 'fade-out-animation', node: this.node_});
- break;
- case extensions.Animation.SCALE_DOWN:
- assert(this.node_);
- configs.push({
- name: 'scale-down-animation',
- node: this.node_,
- transformOrigin: '50% 50%',
- axis: 'y',
- });
- break;
- default:
- assertNotReached();
- }
- }
- this.element_.animationConfig.exit = configs;
- }
- }
-
- return {AnimationHelper: AnimationHelper};
-});
diff --git a/chromium/chrome/browser/resources/md_extensions/code_section.html b/chromium/chrome/browser/resources/md_extensions/code_section.html
index c8056e3452d..dff22ca8375 100644
--- a/chromium/chrome/browser/resources/md_extensions/code_section.html
+++ b/chromium/chrome/browser/resources/md_extensions/code_section.html
@@ -1,6 +1,7 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<dom-module id="extensions-code-section">
diff --git a/chromium/chrome/browser/resources/md_extensions/code_section.js b/chromium/chrome/browser/resources/md_extensions/code_section.js
index d2f4e8f32eb..1ea32d783d0 100644
--- a/chromium/chrome/browser/resources/md_extensions/code_section.js
+++ b/chromium/chrome/browser/resources/md_extensions/code_section.js
@@ -5,7 +5,7 @@
cr.define('extensions', function() {
'use strict';
- var CodeSection = Polymer({
+ const CodeSection = Polymer({
is: 'extensions-code-section',
properties: {
@@ -49,12 +49,12 @@ cr.define('extensions', function() {
if (!this.code)
return '';
- var lines = [
+ const lines = [
this.code.beforeHighlight, this.code.highlight, this.code.afterHighlight
].join('').match(/\n/g);
- var lineCount = lines ? lines.length : 0;
- var textContent = '';
- for (var i = 1; i <= lineCount; ++i)
+ const lineCount = lines ? lines.length : 0;
+ let textContent = '';
+ for (let i = 1; i <= lineCount; ++i)
textContent += i + '\n';
return textContent;
},
diff --git a/chromium/chrome/browser/resources/md_extensions/compiled_resources2.gyp b/chromium/chrome/browser/resources/md_extensions/compiled_resources2.gyp
index 367d0fb2054..7dc433766ce 100644
--- a/chromium/chrome/browser/resources/md_extensions/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/md_extensions/compiled_resources2.gyp
@@ -4,14 +4,6 @@
{
'targets': [
{
- 'target_name': 'animation_helper',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- ],
- 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
'target_name': 'code_section',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
@@ -26,11 +18,10 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/neon-animation/compiled_resources2.gyp:neon-animatable-behavior-extracted',
'<(EXTERNS_GYP):developer_private',
- 'animation_helper',
'item',
'item_util',
+ 'navigation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -48,11 +39,11 @@
'target_name': 'error_page',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/neon-animation/compiled_resources2.gyp:neon-animatable-behavior-extracted',
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-menu/compiled_resources2.gyp:paper-menu-extracted',
'<(EXTERNS_GYP):developer_private',
- 'animation_helper',
'code_section',
+ 'item_util',
+ 'navigation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -74,6 +65,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(EXTERNS_GYP):developer_private',
'item_util',
+ 'navigation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -83,10 +75,8 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/neon-animation/compiled_resources2.gyp:neon-animatable-behavior-extracted',
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-resizable-behavior/compiled_resources2.gyp:iron-resizable-behavior-extracted',
'<(EXTERNS_GYP):developer_private',
- 'animation_helper',
'item',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
@@ -98,6 +88,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(EXTERNS_GYP):developer_private',
+ 'navigation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -106,9 +97,7 @@
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/neon-animation/compiled_resources2.gyp:neon-animatable-behavior-extracted',
'<(EXTERNS_GYP):developer_private',
- 'animation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -129,15 +118,16 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(EXTERNS_GYP):developer_private',
- 'animation_helper',
'detail_view',
'item',
'item_list',
+ 'item_util',
'load_error',
'keyboard_shortcuts',
'navigation_helper',
'sidebar',
'toolbar',
+ 'view_manager',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -154,7 +144,8 @@
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(EXTERNS_GYP):developer_private',
+ '<(EXTERNS_GYP):developer_private',
+ 'navigation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -163,6 +154,7 @@
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
+ '<(EXTERNS_GYP):developer_private',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -200,6 +192,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
+ 'navigation_helper',
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -212,5 +205,14 @@
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
},
+ {
+ 'target_name': 'view_manager',
+ 'dependencies': [
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
+ '<(EXTERNS_GYP):web_animations',
+ ],
+ 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
+ },
]
}
diff --git a/chromium/chrome/browser/resources/md_extensions/detail_view.html b/chromium/chrome/browser/resources/md_extensions/detail_view.html
index fed3c550838..3a23f8a31c0 100644
--- a/chromium/chrome/browser/resources/md_extensions/detail_view.html
+++ b/chromium/chrome/browser/resources/md_extensions/detail_view.html
@@ -1,6 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_toggle_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_tooltip_icon.html">
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/action_link_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
@@ -8,29 +12,39 @@
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/iron-icons.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable-behavior.html">
-<link rel="import" href="chrome://extensions/animation_helper.html">
<link rel="import" href="chrome://extensions/item_util.html">
+<link rel="import" href="chrome://extensions/navigation_helper.html">
<dom-module id="extensions-detail-view">
<template>
- <style include="iron-flex cr-hidden-style action-link">
+ <style include=
+ "iron-flex cr-hidden-style cr-icons action-link paper-toggle-style">
:host {
- display: flex;
- justify-content: center;
+ --iron-icon-fill-color: var(--paper-grey-600);
+ display: block;
+ height: 100%;
+ overflow: auto;
+ }
+
+ #enable-section {
+ margin-bottom: 8px;
+ }
+
+ #enable-section cr-tooltip-icon {
+ -webkit-margin-end: 20px;
}
#main {
background-color: white;
- height: 100%;
+ margin: auto;
+ min-height: 100%;
width: 640px;
}
#top-bar {
align-items: center;
- color: #5a5a5a;
+ color: var(--paper-grey-700);
display: flex;
font-size: 14px;
height: 40px;
@@ -45,10 +59,6 @@
width: 24px;
}
- a paper-icon-button {
- color: var(--paper-grey-600);
- }
-
#name {
flex-grow: 1;
}
@@ -57,42 +67,38 @@
align-items: center;
display: flex;
justify-content: space-between;
+ width: 100%;
}
.control-line span {
- color: #333;
+ color: var(--paper-grey-900);
}
- #enable-section {
- height: 48px;
- margin-bottom: 8px;
- padding: 0 20px;
+ .section {
+ @apply(--cr-section);
}
- .section {
- border-bottom: 1px solid var(--paper-grey-400);
- padding: 16px 20px;
+ .section.block {
+ display: block;
+ padding-bottom: 16px;
+ padding-top: 16px;
+ }
+
+ .section.continuation {
+ border-top: none;
}
- .section:last-child {
+ .section:first-child {
border: none;
}
.section-title {
- color: #333;
+ color: var(--paper-grey-900);
margin-bottom: 12px;
}
.section-content {
- color: #646464;
- }
-
- #options-section {
- padding: 7px 20px;
- }
-
- #options-section .control-line {
- height: 52px;
+ color: var(--paper-grey-600);
}
.actionable {
@@ -109,42 +115,41 @@
-webkit-padding-start: 20px;
margin: 0;
}
-
- button[is='paper-icon-button-light'].action-arrow {
- background-image: url(chrome://resources/images/arrow_right.svg);
- }
-
- button[is='paper-icon-button-light'].open-in-new {
- background-image: url(chrome://resources/images/open_in_new.svg);
- background-size: contain;
- height: 20px;
- width: 20px;
- }
</style>
<div id="main">
<div id="top-bar">
- <paper-icon-button id="close-button" icon="arrow-back"
- on-tap="onCloseButtonTap_"></paper-icon-button>
+ <button id="close-button" is="paper-icon-button-light"
+ class="icon-arrow-back no-overlap"
+ on-tap="onCloseButtonTap_"></button>
<img alt="" id="icon" src="[[data.iconUrl]]">
<span id="name">[[data.name]]</span>
</div>
- <div class="control-line" id="enable-section">
- <span>[[computeEnabledText_(data.*)]]</span>
- <paper-toggle-button id="enable-toggle"
- checked="[[isEnabled_(data.state)]]"
- on-change="onEnableChange_"
- enabled="[[isEnableToggleEnabled_(data)]]">
- </paper-toggle-button>
+ <div class="section continuation" id="enable-section">
+ <div class="control-line">
+ <span>[[computeEnabledText_(data.*)]]</span>
+ <div class="layout horizontal">
+ <cr-tooltip-icon hidden$="[[!data.controlledInfo]]"
+ tooltip-text="[[data.controlledInfo.text]]"
+ icon-class="[[getIndicatorIcon_(data.controlledInfo.type)]]"
+ icon-aria-label="[[data.controlledInfo.type]]">
+ </cr-tooltip-icon>
+ <paper-toggle-button id="enable-toggle"
+ checked="[[isEnabled_(data.state)]]"
+ on-change="onEnableChange_"
+ disabled="[[!isEnableToggleEnabled_(data.*)]]">
+ </paper-toggle-button>
+ </div>
+ </div>
</div>
- <div class="section">
+ <div class="section continuation block">
<div class="section-title">$i18n{itemDescriptionLabel}</div>
<div class="section-content">[[data.description]]</div>
</div>
- <div class="section">
+ <div class="section block">
<div class="section-title">$i18n{itemVersion}</div>
<div class="section-content">[[data.version]]</div>
</div>
- <div class="section" id="id-section" hidden$="[[!inDevMode]]">
+ <div class="section block" id="id-section" hidden$="[[!inDevMode]]">
<div class="section-title">$i18n{itemIdHeading}</div>
<div class="section-content">[[data.id]]</div>
</div>
@@ -163,7 +168,7 @@
</ul>
</div>
</div>
- <div class="section">
+ <div class="section block">
<div class="section-title">$i18n{itemPermissions}</div>
<div class="section-content">
<span id="no-permissions"
@@ -180,7 +185,7 @@
</div>
<template is="dom-if"
if="[[hasDependentExtensions_(data.dependentExtensions.splices)]]">
- <div class="section">
+ <div class="section block">
<div class="section-title">$i18n{itemDependencies}</div>
<div class="section-content">
<ul id="dependent-extensions-list">
@@ -192,7 +197,7 @@
</div>
</template>
<template is="dom-if" if="[[shouldShowOptionsSection_(data.*)]]">
- <div class="section layout vertical" id="options-section">
+ <div class="section">
<template is="dom-if" if="[[data.incognitoAccess.isEnabled]]">
<div class="control-line">
<span>$i18n{itemAllowIncognito}</span>
@@ -232,17 +237,14 @@
<div class="control-line actionable" id="extensions-options"
on-tap="onOptionsTap_">
<span>$i18n{itemOptions}</span>
- <button class="open-in-new" is="paper-icon-button-light"></button>
- </div>
- </div>
- <div class="section">
- <div class="control-line actionable" id="remove-extension"
- on-tap="onRemoveTap_">
- <span>$i18n{itemRemoveExtension}</span>
- <button class="action-arrow" is="paper-icon-button-light"></button>
+ <button class="icon-external" is="paper-icon-button-light"></button>
</div>
</div>
- <div class="section">
+ <button is="cr-link-row" hidden="[[isControlled_(data.controlledInfo)]]"
+ icon-class="subpage-arrow" id="remove-extension"
+ label="$i18n{itemRemoveExtension}" on-tap="onRemoveTap_">
+ </button>
+ <div class="section block">
<div class="section-title">$i18n{itemSource}</div>
<div class="section-content">
[[computeSourceString_(data.*)]]
diff --git a/chromium/chrome/browser/resources/md_extensions/detail_view.js b/chromium/chrome/browser/resources/md_extensions/detail_view.js
index 31695c4011f..0ea6870e448 100644
--- a/chromium/chrome/browser/resources/md_extensions/detail_view.js
+++ b/chromium/chrome/browser/resources/md_extensions/detail_view.js
@@ -5,10 +5,10 @@
cr.define('extensions', function() {
'use strict';
- var DetailView = Polymer({
+ const DetailView = Polymer({
is: 'extensions-detail-view',
- behaviors: [I18nBehavior, Polymer.NeonAnimatableBehavior],
+ behaviors: [I18nBehavior],
properties: {
/**
@@ -24,15 +24,18 @@ cr.define('extensions', function() {
inDevMode: Boolean,
},
- ready: function() {
- this.sharedElements = {hero: this.$.main};
- /** @type {!extensions.AnimationHelper} */
- this.animationHelper = new extensions.AnimationHelper(this, this.$.main);
- },
-
/** @private */
onCloseButtonTap_: function() {
- this.fire('close');
+ extensions.navigation.navigateTo(
+ {page: Page.LIST, type: extensions.getItemListType(this.data)});
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ isControlled_: function() {
+ return extensions.isControlled(this.data);
},
/**
@@ -175,7 +178,25 @@ cr.define('extensions', function() {
computeSourceString_: function() {
return extensions.getItemSourceString(
extensions.getItemSource(this.data));
- }
+ },
+
+ /**
+ * @param {chrome.developerPrivate.ControllerType} type
+ * @return {string}
+ * @private
+ */
+ getIndicatorIcon_: function(type) {
+ switch (type) {
+ case 'POLICY':
+ return 'cr20:domain';
+ case 'CHILD_CUSTODIAN':
+ return 'cr:account-child-invert';
+ case 'SUPERVISED_USER_CUSTODIAN':
+ return 'cr:supervisor-account';
+ default:
+ return '';
+ }
+ },
});
return {DetailView: DetailView};
diff --git a/chromium/chrome/browser/resources/md_extensions/drop_overlay.html b/chromium/chrome/browser/resources/md_extensions/drop_overlay.html
index ea2646c74d0..5e22a036e60 100644
--- a/chromium/chrome/browser/resources/md_extensions/drop_overlay.html
+++ b/chromium/chrome/browser/resources/md_extensions/drop_overlay.html
@@ -1,8 +1,9 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/drag_wrapper.html">
<link rel="import" href="chrome://resources/html/load_time_data.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/iron-icons.html">
<link rel="import" href="chrome://extensions/drag_and_drop_handler.html">
diff --git a/chromium/chrome/browser/resources/md_extensions/drop_overlay.js b/chromium/chrome/browser/resources/md_extensions/drop_overlay.js
index d862888c2da..feeddba5520 100644
--- a/chromium/chrome/browser/resources/md_extensions/drop_overlay.js
+++ b/chromium/chrome/browser/resources/md_extensions/drop_overlay.js
@@ -9,15 +9,15 @@ Polymer({
is: 'extensions-drop-overlay',
created: function() {
this.hidden = true;
- var dragTarget = document.documentElement;
+ const dragTarget = document.documentElement;
this.dragWrapperHandler_ =
new extensions.DragAndDropHandler(true, dragTarget);
- dragTarget.addEventListener('extension-drag-started', function() {
+ dragTarget.addEventListener('extension-drag-started', () => {
this.hidden = false;
- }.bind(this));
- dragTarget.addEventListener('extension-drag-ended', function() {
+ });
+ dragTarget.addEventListener('extension-drag-ended', () => {
this.hidden = true;
- }.bind(this));
+ });
this.dragWrapper_ =
new cr.ui.DragWrapper(dragTarget, this.dragWrapperHandler_);
},
diff --git a/chromium/chrome/browser/resources/md_extensions/error_page.html b/chromium/chrome/browser/resources/md_extensions/error_page.html
index 742a82408fe..b3103aaa277 100644
--- a/chromium/chrome/browser/resources/md_extensions/error_page.html
+++ b/chromium/chrome/browser/resources/md_extensions/error_page.html
@@ -1,17 +1,19 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/iron-icons.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable-behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
-<link rel="import" href="chrome://extensions/animation_helper.html">
<link rel="import" href="chrome://extensions/code_section.html">
+<link rel="import" href="chrome://extensions/item_util.html">
+<link rel="import" href="chrome://extensions/navigation_helper.html">
<dom-module id="extensions-error-page">
<template>
- <style include="cr-hidden-style">
+ <style include="cr-icons cr-hidden-style">
#main {
background-color: white;
height: 800px;
@@ -61,8 +63,9 @@
</style>
<div id="main">
<div id="heading">
- <paper-icon-button id="close-button" icon="arrow-back"
- on-tap="onCloseButtonTap_"></paper-icon-button>
+ <button id="close-button" is="paper-icon-button-light"
+ class="icon-arrow-back no-overlap" on-tap="onCloseButtonTap_">
+ </button>
<span>$i18n{errorsPageHeading}</span>
</div>
<iron-list id="errors-list" items="[[calculateShownItems_(data.*)]]">
@@ -73,9 +76,8 @@
on-tap="onErrorItemTap_" on-keydown="onErrorItemKeydown_">
<img class$="[[computeErrorIconClass_(item)]]">
<div class="error-message">[[item.message]]</div>
- <paper-icon-button class="delete-button"
- on-tap="onDeleteErrorTap_"
- icon="delete" tabindex$="[[tabIndex]]"></paper-icon-button>
+ <button is="paper-icon-button-light" class="icon-delete-gray"
+ on-tap="onDeleteErrorTap_" tabindex$="[[tabIndex]]"></button>
</div>
</template>
</iron-list>
diff --git a/chromium/chrome/browser/resources/md_extensions/error_page.js b/chromium/chrome/browser/resources/md_extensions/error_page.js
index 2658f9d33f5..01bcf79e3cf 100644
--- a/chromium/chrome/browser/resources/md_extensions/error_page.js
+++ b/chromium/chrome/browser/resources/md_extensions/error_page.js
@@ -3,15 +3,15 @@
// found in the LICENSE file.
/** @typedef {chrome.developerPrivate.ManifestError} */
-var ManifestError;
+let ManifestError;
/** @typedef {chrome.developerPrivate.RuntimeError} */
-var RuntimeError;
+let RuntimeError;
cr.define('extensions', function() {
'use strict';
/** @interface */
- var ErrorPageDelegate = function() {};
+ const ErrorPageDelegate = function() {};
ErrorPageDelegate.prototype = {
/**
@@ -28,11 +28,9 @@ cr.define('extensions', function() {
requestFileSource: assertNotReached,
};
- var ErrorPage = Polymer({
+ const ErrorPage = Polymer({
is: 'extensions-error-page',
- behaviors: [Polymer.NeonAnimatableBehavior],
-
properties: {
/** @type {!chrome.developerPrivate.ExtensionInfo|undefined} */
data: Object,
@@ -49,14 +47,6 @@ cr.define('extensions', function() {
'onSelectedErrorChanged_(selectedError_)',
],
- ready: function() {
- /** @type {!extensions.AnimationHelper} */
- this.animationHelper = new extensions.AnimationHelper(this, this.$.main);
- this.animationHelper.setEntryAnimations([extensions.Animation.FADE_IN]);
- this.animationHelper.setExitAnimations([extensions.Animation.SCALE_DOWN]);
- this.sharedElements = {hero: this.$.main};
- },
-
/**
* Watches for changes to |data| in order to fetch the corresponding
* file source.
@@ -64,7 +54,7 @@ cr.define('extensions', function() {
*/
observeDataChanges_: function() {
assert(this.data);
- var e = this.data.manifestErrors[0] || this.data.runtimeErrors[0];
+ const e = this.data.manifestErrors[0] || this.data.runtimeErrors[0];
if (e)
this.selectedError_ = e;
},
@@ -79,7 +69,11 @@ cr.define('extensions', function() {
/** @private */
onCloseButtonTap_: function() {
- this.fire('close');
+ extensions.navigation.navigateTo({
+ page: Page.LIST,
+ type: extensions.getItemListType(
+ /** @type {!chrome.developerPrivate.ExtensionInfo} */ (this.data))
+ });
},
/**
@@ -110,7 +104,7 @@ cr.define('extensions', function() {
onDeleteErrorTap_: function(event) {
// TODO(devlin): It would be cleaner if we could cast this to a
// PolymerDomRepeatEvent-type thing, but that doesn't exist yet.
- var e = /** @type {!{model:Object}} */ (event);
+ const e = /** @type {!{model:Object}} */ (event);
this.delegate.deleteErrors(this.data.id, [e.model.item.id]);
},
@@ -119,8 +113,8 @@ cr.define('extensions', function() {
* @private
*/
onSelectedErrorChanged_: function() {
- var error = this.selectedError_;
- var args = {
+ const error = this.selectedError_;
+ const args = {
extensionId: error.extensionId,
message: error.message,
};
@@ -138,9 +132,9 @@ cr.define('extensions', function() {
0;
break;
}
- this.delegate.requestFileSource(args).then(function(code) {
+ this.delegate.requestFileSource(args).then(code => {
this.$['code-section'].code = code;
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/md_extensions/extensions.js b/chromium/chrome/browser/resources/md_extensions/extensions.js
index 5b5cfd27e02..a9a62659892 100644
--- a/chromium/chrome/browser/resources/md_extensions/extensions.js
+++ b/chromium/chrome/browser/resources/md_extensions/extensions.js
@@ -4,7 +4,7 @@
(function() {
'use strict';
-var manager = /** @type {extensions.Manager} */ (
+const manager = /** @type {extensions.Manager} */ (
document.querySelector('extensions-manager'));
manager.readyPromiseResolver.promise.then(function() {
extensions.Service.getInstance().managerReady(manager);
diff --git a/chromium/chrome/browser/resources/md_extensions/item.html b/chromium/chrome/browser/resources/md_extensions/item.html
index 0b1ec86fa41..c396d2e4c95 100644
--- a/chromium/chrome/browser/resources/md_extensions/item.html
+++ b/chromium/chrome/browser/resources/md_extensions/item.html
@@ -1,7 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_toggle_style_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
@@ -14,13 +16,14 @@
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/iron-icons.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/communication-icons.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html">
+<link rel="import" href="chrome://extensions/navigation_helper.html">
<dom-module id="extensions-item">
<template>
- <style include="iron-flex cr-hidden-style action-link paper-button-style">
+ <style include="iron-flex cr-hidden-style cr-icons action-link paper-button-style paper-toggle-style">
#icon-wrapper {
align-self: flex-start;
display: flex;
@@ -63,13 +66,12 @@
}
#name-and-version {
- line-height: 15px;
+ @apply(--cr-primary-text);
margin-bottom: 4px;
}
#name {
-webkit-margin-end: 8px;
- color: #333;
}
#description,
@@ -83,15 +85,17 @@
#extension-id,
#inspect-views,
#button-strip {
+ /* TODO(dschuyler): use --cr-secondary-text. */
color: var(--paper-grey-600);
+ font-weight: 400;
}
#button-strip {
-webkit-padding-end: 4px;
- -webkit-padding-start: 20px;
- border-top: 1px solid var(--paper-grey-400);
+ -webkit-padding-start: var(--cr-section-padding);
+ border-top: var(--cr-separator-line);
box-sizing: border-box;
- height: 48px;
+ height: var(--cr-section-min-height);
padding-bottom: 8px;
padding-top: 8px;
}
@@ -143,6 +147,7 @@
}
paper-toggle-button {
+ -webkit-margin-end: 8px; /* Avoid ripple from overlapping container. */
cursor: pointer;
}
@@ -151,10 +156,7 @@
}
#dev-reload-button {
- -webkit-margin-end: 20px;
- height: 20px;
- padding: 0;
- width: 20px;
+ -webkit-margin-end: 12px;
}
#warnings {
@@ -229,7 +231,8 @@
<paper-button id="details-button" on-tap="onDetailsTap_">
$i18n{itemDetails}
</paper-button>
- <paper-button id="remove-button" on-tap="onRemoveTap_">
+ <paper-button id="remove-button" on-tap="onRemoveTap_"
+ hidden="[[isControlled_(data.controlledInfo)]]">
$i18n{itemRemove}
</paper-button>
<paper-button id="errors-button" on-tap="onErrorsTap_"
@@ -238,9 +241,9 @@
</paper-button>
</div>
<template is="dom-if" if="[[!computeDevReloadButtonHidden_(data.*)]]">
- <paper-icon-button id="dev-reload-button"
- on-tap="onReloadTap_" icon="refresh">
- </paper-icon-button>
+ <button id="dev-reload-button" is="paper-icon-button-light"
+ class="icon-refresh no-overlap" on-tap="onReloadTap_">
+ </button>
</template>
<paper-button id="repair-button" class="action-button"
on-tap="onRepairTap_"
@@ -254,7 +257,7 @@
</paper-button>
<paper-toggle-button id="enable-toggle" class="action-button"
checked="[[isEnabled_(data.state)]]" on-change="onEnableChange_"
- enabled="[[isEnableToggleEnabled_(data)]]"
+ disabled="[[!isEnableToggleEnabled_(data.*)]]"
hidden$="[[!showEnableToggle_(data.*)]]">
</paper-toggle-button>
</div>
diff --git a/chromium/chrome/browser/resources/md_extensions/item.js b/chromium/chrome/browser/resources/md_extensions/item.js
index 7e1570b2b9f..eb7c4c4ebbf 100644
--- a/chromium/chrome/browser/resources/md_extensions/item.js
+++ b/chromium/chrome/browser/resources/md_extensions/item.js
@@ -4,7 +4,7 @@
cr.define('extensions', function() {
/** @interface */
- var ItemDelegate = function() {};
+ const ItemDelegate = function() {};
ItemDelegate.prototype = {
/** @param {string} id */
@@ -56,7 +56,7 @@ cr.define('extensions', function() {
showItemOptionsPage: assertNotReached,
};
- var Item = Polymer({
+ const Item = Polymer({
is: 'extensions-item',
behaviors: [I18nBehavior],
@@ -95,7 +95,7 @@ cr.define('extensions', function() {
/** @private */
observeIdVisibility_: function(inDevMode, showingDetails, id) {
Polymer.dom.flush();
- var idElement = this.$$('#extension-id');
+ const idElement = this.$$('#extension-id');
if (idElement) {
assert(this.data);
idElement.innerHTML = this.i18n('itemId', this.data.id);
@@ -125,12 +125,14 @@ cr.define('extensions', function() {
/** @private */
onErrorsTap_: function() {
- this.fire('extension-item-show-errors', {data: this.data});
+ extensions.navigation.navigateTo(
+ {page: Page.ERRORS, extensionId: this.data.id});
},
/** @private */
onDetailsTap_: function() {
- this.fire('extension-item-show-details', {data: this.data});
+ extensions.navigation.navigateTo(
+ {page: Page.DETAILS, extensionId: this.data.id});
},
/**
@@ -143,7 +145,8 @@ cr.define('extensions', function() {
/** @private */
onExtraInspectTap_: function() {
- this.fire('extension-item-show-details', {data: this.data});
+ extensions.navigation.navigateTo(
+ {page: Page.DETAILS, extensionId: this.data.id});
},
/** @private */
@@ -160,6 +163,14 @@ cr.define('extensions', function() {
* @return {boolean}
* @private
*/
+ isControlled_: function() {
+ return extensions.isControlled(this.data);
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
isEnabled_: function() {
return extensions.isEnabled(this.data.state);
},
@@ -196,7 +207,7 @@ cr.define('extensions', function() {
* @private
*/
computeClasses_: function() {
- var classes = this.isEnabled_() ? 'enabled' : 'disabled';
+ let classes = this.isEnabled_() ? 'enabled' : 'disabled';
if (this.inDevMode)
classes += ' dev-mode';
return classes;
@@ -225,7 +236,7 @@ cr.define('extensions', function() {
* @private
*/
computeSourceIndicatorText_: function() {
- var sourceType = extensions.getItemSource(this.data);
+ const sourceType = extensions.getItemSource(this.data);
return sourceType == SourceType.WEBSTORE ?
'' :
extensions.getItemSourceString(sourceType);
@@ -251,7 +262,7 @@ cr.define('extensions', function() {
// need to handle the case gracefully.
if (this.data.views.length == 0)
return '';
- var label = extensions.computeInspectableViewLabel(this.data.views[0]);
+ let label = extensions.computeInspectableViewLabel(this.data.views[0]);
if (this.data.views.length > 1)
label += ',';
return label;
@@ -273,7 +284,7 @@ cr.define('extensions', function() {
// Only display the reload spinner if the extension is unpacked and
// not terminated (since if it's terminated, we'll show a crashed reload
// buton).
- var showIcon =
+ const showIcon =
this.data.location == chrome.developerPrivate.Location.UNPACKED &&
this.data.state != chrome.developerPrivate.ExtensionState.TERMINATED;
return !showIcon;
diff --git a/chromium/chrome/browser/resources/md_extensions/item_list.html b/chromium/chrome/browser/resources/md_extensions/item_list.html
index 14883739fcc..78791afb6da 100644
--- a/chromium/chrome/browser/resources/md_extensions/item_list.html
+++ b/chromium/chrome/browser/resources/md_extensions/item_list.html
@@ -1,10 +1,9 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-resizable-behavior/iron-resizable-behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable-behavior.html">
-<link rel="import" href="chrome://extensions/animation_helper.html">
<link rel="import" href="chrome://extensions/item.html">
<dom-module id="extensions-item-list">
@@ -20,12 +19,11 @@
}
.empty-list-message {
- align-items: center;
color: #6e6e6e;
- display: flex;
- flex: 1;
+ font-size: 123%; /* Should be 16px when 100% is 13px. */
font-weight: 500;
- justify-content: center;
+ margin-top: 80px;
+ text-align: center;
}
.wrapper {
diff --git a/chromium/chrome/browser/resources/md_extensions/item_list.js b/chromium/chrome/browser/resources/md_extensions/item_list.js
index a545b82e4c3..a2a38e15a04 100644
--- a/chromium/chrome/browser/resources/md_extensions/item_list.js
+++ b/chromium/chrome/browser/resources/md_extensions/item_list.js
@@ -3,10 +3,10 @@
// found in the LICENSE file.
cr.define('extensions', function() {
- var ItemList = Polymer({
+ const ItemList = Polymer({
is: 'extensions-item-list',
- behaviors: [Polymer.NeonAnimatableBehavior, Polymer.IronResizableBehavior],
+ behaviors: [Polymer.IronResizableBehavior],
properties: {
/** @type {Array<!chrome.developerPrivate.ExtensionInfo>} */
@@ -31,21 +31,7 @@ cr.define('extensions', function() {
listeners: {
'list.extension-item-size-changed': 'itemSizeChanged_',
- },
-
- ready: function() {
- /** @type {extensions.AnimationHelper} */
- this.animationHelper = new extensions.AnimationHelper(this, this.$.list);
- this.animationHelper.setEntryAnimations([extensions.Animation.FADE_IN]);
- this.animationHelper.setExitAnimations([extensions.Animation.HERO]);
- },
-
- /**
- * Called when a subpage for a given item is about to be shown.
- * @param {string} id
- */
- willShowItemSubpage: function(id) {
- this.sharedElements = {hero: this.$$('#' + id)};
+ 'view-enter-start': 'onViewEnterStart_',
},
/**
@@ -56,15 +42,7 @@ cr.define('extensions', function() {
*/
itemSizeChanged_: function(e) {
this.$.list.updateSizeForItem(e.detail.item);
- },
-
- /**
- * Called right before an item enters the detailed view.
- * @param {CustomEvent} e
- * @private
- */
- showItemDetails_: function(e) {
- this.sharedElements = {hero: e.detail.element};
+ this.fire('resize');
},
/**
@@ -88,6 +66,11 @@ cr.define('extensions', function() {
return !this.shouldShowEmptyItemsMessage_() &&
this.shownItems_.length === 0;
},
+
+ /** @private */
+ onViewEnterStart_: function() {
+ this.fire('resize'); // This is needed to correctly render iron-list.
+ },
});
return {
diff --git a/chromium/chrome/browser/resources/md_extensions/item_util.js b/chromium/chrome/browser/resources/md_extensions/item_util.js
index 608964d1a13..5997a53b00f 100644
--- a/chromium/chrome/browser/resources/md_extensions/item_util.js
+++ b/chromium/chrome/browser/resources/md_extensions/item_util.js
@@ -4,7 +4,7 @@
// Closure compiler won't let this be declared inside cr.define().
/** @enum {string} */
-var SourceType = {
+const SourceType = {
WEBSTORE: 'webstore',
POLICY: 'policy',
SIDELOADED: 'sideloaded',
@@ -30,6 +30,14 @@ cr.define('extensions', function() {
}
/**
+ * @param {!chrome.developerPrivate.ExtensionInfo} extensionInfo
+ * @return {boolean} Whether the extension is controlled.
+ */
+ 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
@@ -98,8 +106,8 @@ cr.define('extensions', function() {
*/
function computeInspectableViewLabel(view) {
// Trim the "chrome-extension://<id>/".
- var url = new URL(view.url);
- var label = view.url;
+ const url = new URL(view.url);
+ let label = view.url;
if (url.protocol == 'chrome-extension:')
label = url.pathname.substring(1);
if (label == '_generated_background_page.html')
@@ -115,9 +123,33 @@ cr.define('extensions', function() {
return label;
}
+ /**
+ * Returns the list type that the item belongs to.
+ * @param {!chrome.developerPrivate.ExtensionInfo} item
+ * @return {extensions.ShowingType}
+ */
+ function getItemListType(item) {
+ const ExtensionType = chrome.developerPrivate.ExtensionType;
+ switch (item.type) {
+ case ExtensionType.HOSTED_APP:
+ case ExtensionType.LEGACY_PACKAGED_APP:
+ case ExtensionType.PLATFORM_APP:
+ return extensions.ShowingType.APPS;
+ case ExtensionType.EXTENSION:
+ case ExtensionType.SHARED_MODULE:
+ return extensions.ShowingType.EXTENSIONS;
+ case ExtensionType.THEME:
+ assertNotReached('Don\'t send themes to the chrome://extensions page');
+ break;
+ }
+ assertNotReached();
+ }
+
return {
+ isControlled: isControlled,
isEnabled: isEnabled,
userCanChangeEnablement: userCanChangeEnablement,
+ getItemListType: getItemListType,
getItemSource: getItemSource,
getItemSourceString: getItemSourceString,
computeInspectableViewLabel: computeInspectableViewLabel
diff --git a/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.html b/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.html
index c4b1e187080..1678a875485 100644
--- a/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.html
+++ b/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.html
@@ -1,11 +1,10 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable-behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html">
-<link rel="import" href="chrome://extensions/animation_helper.html">
<link rel="import" href="chrome://extensions/shortcut_input.html">
<dom-module id="extensions-keyboard-shortcuts">
diff --git a/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.js b/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.js
index 1490eeb7b0d..160e3ce1097 100644
--- a/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.js
+++ b/chromium/chrome/browser/resources/md_extensions/keyboard_shortcuts.js
@@ -6,11 +6,9 @@ cr.define('extensions', function() {
'use strict';
// The UI to display and manage keyboard shortcuts set for extension commands.
- var KeyboardShortcuts = Polymer({
+ const KeyboardShortcuts = Polymer({
is: 'extensions-keyboard-shortcuts',
- behaviors: [Polymer.NeonAnimatableBehavior],
-
properties: {
/** @type {Array<!chrome.developerPrivate.ExtensionInfo>} */
items: Array,
@@ -21,18 +19,10 @@ cr.define('extensions', function() {
*/
CommandScope_: {
type: Object,
- value: chrome.developerPrivate.CommandScope
+ value: chrome.developerPrivate.CommandScope,
},
},
- ready: function() {
- /** @type {!extensions.AnimationHelper} */
- this.animationHelper = new extensions.AnimationHelper(this, this.$.main);
- this.animationHelper.setEntryAnimations([extensions.Animation.FADE_IN]);
- this.animationHelper.setExitAnimations([extensions.Animation.SCALE_DOWN]);
- this.sharedElements = {hero: this.$.main};
- },
-
/**
* @return {!Array<!chrome.developerPrivate.ExtensionInfo>}
* @private
diff --git a/chromium/chrome/browser/resources/md_extensions/load_error.html b/chromium/chrome/browser/resources/md_extensions/load_error.html
index b032246e510..1f3212d870a 100644
--- a/chromium/chrome/browser/resources/md_extensions/load_error.html
+++ b/chromium/chrome/browser/resources/md_extensions/load_error.html
@@ -1,9 +1,10 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://extensions/code_section.html">
@@ -20,8 +21,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{loadErrorHeading}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{loadErrorHeading}</div>
+ <div slot="body">
<div id="info">
<div id="file" class="description-row">
<span class="row-label">$i18n{loadErrorFileLabel}</span>
@@ -36,7 +37,7 @@
could-not-display-code="$i18n{loadErrorCouldNotLoadManifest}">
</extensions-code-section>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="close">
$i18n{loadErrorCancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/md_extensions/load_error.js b/chromium/chrome/browser/resources/md_extensions/load_error.js
index bd440713d39..5d1cc8e98dc 100644
--- a/chromium/chrome/browser/resources/md_extensions/load_error.js
+++ b/chromium/chrome/browser/resources/md_extensions/load_error.js
@@ -16,7 +16,7 @@ cr.define('extensions', function() {
retryLoadUnpacked: assertNotReached,
};
- var LoadError = Polymer({
+ const LoadError = Polymer({
is: 'extensions-load-error',
properties: {
/** @type {extensions.LoadErrorDelegate} */
@@ -47,12 +47,12 @@ cr.define('extensions', function() {
/** @private */
observeLoadErrorChanges_: function() {
assert(this.loadError);
- var source = this.loadError.source;
+ const source = this.loadError.source;
// CodeSection expects a RequestFileSourceResponse, rather than an
// ErrorFileSource. Massage into place.
// TODO(devlin): Make RequestFileSourceResponse use ErrorFileSource.
/** @type {!chrome.developerPrivate.RequestFileSourceResponse} */
- var codeSectionProperties = {
+ const codeSectionProperties = {
beforeHighlight: source ? source.beforeHighlight : '',
highlight: source ? source.highlight : '',
afterHighlight: source ? source.afterHighlight : '',
diff --git a/chromium/chrome/browser/resources/md_extensions/manager.html b/chromium/chrome/browser/resources/md_extensions/manager.html
index b83e72d0a6d..6b401d1dafc 100644
--- a/chromium/chrome/browser/resources/md_extensions/manager.html
+++ b/chromium/chrome/browser/resources/md_extensions/manager.html
@@ -1,18 +1,19 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/cr_drawer/cr_drawer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
+<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/promise_resolver.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-header-panel/paper-header-panel.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animated-pages.html">
<link rel="import" href="chrome://extensions/detail_view.html">
<link rel="import" href="chrome://extensions/drop_overlay.html">
<link rel="import" href="chrome://extensions/error_page.html">
<link rel="import" href="chrome://extensions/item_list.html">
+<link rel="import" href="chrome://extensions/item_util.html">
<link rel="import" href="chrome://extensions/keyboard_shortcuts.html">
<link rel="import" href="chrome://extensions/load_error.html">
<link rel="import" href="chrome://extensions/navigation_helper.html">
@@ -21,6 +22,7 @@
<link rel="import" href="chrome://extensions/service.html">
<link rel="import" href="chrome://extensions/sidebar.html">
<link rel="import" href="chrome://extensions/toolbar.html">
+<link rel="import" href="chrome://extensions/view_manager.html">
<link rel="stylesheet" href="chrome://resources/css/md_colors.css">
<dom-module id="extensions-manager">
@@ -40,27 +42,11 @@
flex-basis: 256px;
}
- #pages {
+ #viewManager {
flex-grow: 1;
overflow-y: auto;
}
- /* Neon-animated pages set the position of the content to be absolute,
- * which is necessary for animations, but breaks sub-page layout. Apply a
- * static position to the selected page. See
- * https://github.com/PolymerElements/neon-animation/issues/101 for
- * conversations.
- * Note: Another proposed solution was
- * neon-animated-pages .iron-selected:not(.neon-animating) {
- * position: relative;
- * }
- * but the below appears to work fine, and is in line with what settings
- * does.
- */
- neon-animated-pages ::content > .iron-selected {
- position: static;
- }
-
extensions-item {
display: inline-block;
}
@@ -78,26 +64,26 @@
</extensions-toolbar>
<dialog id="drawer" is="cr-drawer" heading="$i18n{toolbarTitle}">
<div class="drawer-content">
- <extensions-sidebar></extensions-sidebar>
+ <extensions-sidebar id="sidebar"></extensions-sidebar>
</div>
</dialog>
- <neon-animated-pages id="pages" attr-for-selected="id"
- selected="items-list">
- <extensions-item-list id="items-list" items="[[extensions]]"
+ <extensions-view-manager id="viewManager">
+ <extensions-item-list id="items-list"
+ items="[[itemsList_]]"
delegate="[[delegate]]" in-dev-mode="[[inDevMode]]"
- filter="[[filter]]" hidden$="[[!didInitPage_]]">
+ filter="[[filter]]" hidden$="[[!didInitPage_]]" slot="view">
</extensions-item-list>
<extensions-detail-view id="details-view" delegate="[[delegate]]"
in-dev-mode="[[inDevMode]]" data="[[detailViewItem_]]"
- on-close="onDetailsViewClose_">
+ slot="view">
</extensions-detail-view>
<extensions-keyboard-shortcuts id="keyboard-shortcuts"
- items="[[extensions]]">
+ items="[[extensions]]" slot="view">
</extensions-keyboard-shortcuts>
- <extensions-error-page id="error-page" on-close="onErrorPageClose_"
- data="[[errorPageItem_]]" delegate="[[delegate]]">
+ <extensions-error-page id="error-page"
+ data="[[errorPageItem_]]" delegate="[[delegate]]" slot="view">
</extensions-error-page>
- </neon-animated-pages>
+ </extensions-view-manager>
<extensions-options-dialog id="options-dialog">
</extensions-options-dialog>
<extensions-pack-dialog id="pack-dialog" delegate="[[delegate]]">
@@ -107,4 +93,4 @@
</paper-header-panel>
</template>
<script src="chrome://extensions/manager.js"></script>
-</dom-module>
+</dom-module> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/md_extensions/manager.js b/chromium/chrome/browser/resources/md_extensions/manager.js
index 9b970cfa541..9ac31f6fd5a 100644
--- a/chromium/chrome/browser/resources/md_extensions/manager.js
+++ b/chromium/chrome/browser/resources/md_extensions/manager.js
@@ -11,7 +11,7 @@ cr.define('extensions', function() {
* @param {chrome.developerPrivate.ExtensionInfo} b
* @return {number}
*/
- var compareExtensions = function(a, b) {
+ const compareExtensions = function(a, b) {
function compare(x, y) {
return x < y ? -1 : (x > y ? 1 : 0);
}
@@ -29,7 +29,7 @@ cr.define('extensions', function() {
compare(a.id, b.id);
};
- var Manager = Polymer({
+ const Manager = Polymer({
is: 'extensions-manager',
behaviors: [I18nBehavior],
@@ -72,18 +72,6 @@ cr.define('extensions', function() {
*/
detailViewItem_: Object,
- /**
- * The helper object to maintain page state.
- * @private {!extensions.NavigationHelper}
- */
- navigationHelper_: Object,
-
- /**
- * The current page being shown.
- * @private {!PageState}
- */
- currentPage_: Object,
-
/** @type {!Array<!chrome.developerPrivate.ExtensionInfo>} */
extensions: {
type: Array,
@@ -100,6 +88,14 @@ cr.define('extensions', function() {
},
},
+ /** @private {extensions.ShowingType} */
+ listType_: Number,
+
+ itemsList_: {
+ type: Array,
+ computed: 'computeList_(listType_)',
+ },
+
/**
* Prevents page content from showing before data is first loaded.
* @private
@@ -110,42 +106,24 @@ cr.define('extensions', function() {
},
},
- listeners: {
- 'items-list.extension-item-show-details': 'onShouldShowItemDetails_',
- 'items-list.extension-item-show-errors': 'onShouldShowItemErrors_',
- },
+ /**
+ * The current page being shown. Default to null, and initPage will figure
+ * out the initial page based on url.
+ * @private {?PageState}
+ */
+ currentPage_: null,
created: function() {
this.readyPromiseResolver = new PromiseResolver();
},
ready: function() {
- /** @type {extensions.Sidebar} */
- this.sidebar =
- /** @type {extensions.Sidebar} */ (this.$$('extensions-sidebar'));
this.toolbar =
/** @type {extensions.Toolbar} */ (this.$$('extensions-toolbar'));
- this.listHelper_ = new ListHelper(this);
- this.sidebar.setListDelegate(this.listHelper_);
this.readyPromiseResolver.resolve();
- this.currentPage_ = {page: Page.LIST};
- this.navigationHelper_ =
- new extensions.NavigationHelper(function(newPage) {
- this.changePage(newPage, true);
- }.bind(this));
- this.optionsDialog.addEventListener('close', function() {
- // We update the page when the options dialog closes, but only if we're
- // still on the details page. We could be on a different page if the
- // user hit back while the options dialog was visible; in that case, the
- // new page is already correct.
- if (this.currentPage_.page == Page.DETAILS) {
- // This will update the currentPage_ and the NavigationHelper; since
- // the active page is already the details page, no main page
- // transition occurs.
- this.changePage(
- {page: Page.DETAILS, extensionId: this.currentPage_.extensionId});
- }
- }.bind(this));
+ extensions.navigation.onRouteChanged(newPage => {
+ this.changePage_(newPage);
+ });
},
get keyboardShortcuts() {
@@ -169,20 +147,12 @@ cr.define('extensions', function() {
},
/**
- * Shows the details view for a given item.
- * @param {!chrome.developerPrivate.ExtensionInfo} data
- */
- showItemDetails: function(data) {
- this.changePage({page: Page.DETAILS, extensionId: data.id});
- },
-
- /**
* Initializes the page to reflect what's specified in the url so that if
* the user visits chrome://extensions/?id=..., we land on the proper page.
*/
initPage: function() {
this.didInitPage_ = true;
- this.changePage(this.navigationHelper_.getCurrentPage(), true);
+ this.changePage_(extensions.navigation.getCurrentPage());
},
/**
@@ -199,30 +169,18 @@ cr.define('extensions', function() {
},
/**
- * @param {chrome.developerPrivate.ExtensionType} type The type of item.
+ * @param {chrome.developerPrivate.ExtensionInfo} item
* @return {string} The ID of the list that the item belongs in.
* @private
*/
- getListId_: function(type) {
- var listId;
- var ExtensionType = chrome.developerPrivate.ExtensionType;
- switch (type) {
- case ExtensionType.HOSTED_APP:
- case ExtensionType.LEGACY_PACKAGED_APP:
- case ExtensionType.PLATFORM_APP:
- listId = 'apps';
- break;
- case ExtensionType.EXTENSION:
- case ExtensionType.SHARED_MODULE:
- listId = 'extensions';
- break;
- case ExtensionType.THEME:
- assertNotReached(
- 'Don\'t send themes to the chrome://extensions page');
- break;
- }
- assert(listId);
- return listId;
+ getListId_: function(item) {
+ const type = extensions.getItemListType(item);
+ if (type == extensions.ShowingType.APPS)
+ return 'apps';
+ else if (type == extensions.ShowingType.EXTENSIONS)
+ return 'extensions';
+
+ assertNotReached();
},
/**
@@ -253,10 +211,10 @@ cr.define('extensions', function() {
* the new element is representing.
*/
addItem: function(item) {
- var listId = this.getListId_(item.type);
+ const listId = this.getListId_(item);
// We should never try and add an existing item.
assert(this.getIndexInList_(listId, item.id) == -1);
- var insertBeforeChild = this[listId].findIndex(function(listEl) {
+ let insertBeforeChild = this[listId].findIndex(function(listEl) {
return compareExtensions(listEl, item) > 0;
});
if (insertBeforeChild == -1)
@@ -269,8 +227,8 @@ cr.define('extensions', function() {
* item to update.
*/
updateItem: function(item) {
- var listId = this.getListId_(item.type);
- var index = this.getIndexInList_(listId, item.id);
+ const listId = this.getListId_(item);
+ const index = this.getIndexInList_(listId, item.id);
// We should never try and update a non-existent item.
assert(index >= 0);
this.set([listId, index], item);
@@ -281,11 +239,11 @@ cr.define('extensions', function() {
// that the DOM will have stale data, but there's no point in causing the
// extra work.
if (this.detailViewItem_ && this.detailViewItem_.id == item.id &&
- this.$.pages.selected == Page.DETAILS) {
+ this.currentPage_.page == Page.DETAILS) {
this.detailViewItem_ = item;
} else if (
this.errorPageItem_ && this.errorPageItem_.id == item.id &&
- this.$.pages.selected == Page.ERRORS) {
+ this.currentPage_.page == Page.ERRORS) {
this.errorPageItem_ = item;
}
},
@@ -295,8 +253,8 @@ cr.define('extensions', function() {
* item to remove.
*/
removeItem: function(item) {
- var listId = this.getListId_(item.type);
- var index = this.getIndexInList_(listId, item.id);
+ const listId = this.getListId_(item);
+ const index = this.getIndexInList_(listId, item.id);
// We should never try and remove a non-existent item.
assert(index >= 0);
this.splice(listId, index, 1);
@@ -326,53 +284,33 @@ cr.define('extensions', function() {
/**
* Changes the active page selection.
* @param {PageState} newPage
- * @param {boolean=} isSilent If true, does not notify the navigation helper
- * of the change.
+ * @private
*/
- changePage: function(newPage, isSilent) {
- if (this.currentPage_.page == newPage.page &&
- this.currentPage_.subpage == newPage.subpage &&
- this.currentPage_.extensionId == newPage.extensionId) {
- return;
- }
-
+ changePage_: function(newPage) {
this.$.drawer.closeDrawer();
if (this.optionsDialog.open)
this.optionsDialog.close();
- var fromPage = this.$.pages.selected;
- var toPage = newPage.page;
- var data;
+ const fromPage = this.currentPage_ ? this.currentPage_.page : null;
+ const toPage = newPage.page;
+ let data;
if (newPage.extensionId)
data = assert(this.getData_(newPage.extensionId));
+ if (newPage.hasOwnProperty('type'))
+ this.listType_ = newPage.type;
+
if (toPage == Page.DETAILS)
this.detailViewItem_ = assert(data);
else if (toPage == Page.ERRORS)
this.errorPageItem_ = assert(data);
if (fromPage != toPage) {
- var entry;
- var exit;
- if (fromPage == Page.LIST &&
- (toPage == Page.DETAILS || toPage == Page.ERRORS)) {
- this.$['items-list'].willShowItemSubpage(data.id);
- entry = [extensions.Animation.HERO];
- // The item grid can be larger than the detail view that we're
- // hero'ing into, so we want to also fade out to avoid any jarring.
- exit = [extensions.Animation.HERO, extensions.Animation.FADE_OUT];
- } else if (toPage == Page.LIST) {
- entry = [extensions.Animation.FADE_IN];
- exit = [extensions.Animation.SCALE_DOWN];
- } else {
- assert(toPage == Page.DETAILS || toPage == Page.SHORTCUTS);
- entry = [extensions.Animation.FADE_IN];
- exit = [extensions.Animation.FADE_OUT];
- }
-
- this.getPage_(fromPage).animationHelper.setExitAnimations(exit);
- this.getPage_(toPage).animationHelper.setEntryAnimations(entry);
- this.$.pages.selected = toPage;
+ /** @type {extensions.ViewManager} */ (this.$.viewManager)
+ .switchView(toPage);
+ } else {
+ /** @type {extensions.ViewManager} */ (this.$.viewManager)
+ .animateCurrentView('fade-in');
}
if (newPage.subpage) {
@@ -382,77 +320,31 @@ cr.define('extensions', function() {
}
this.currentPage_ = newPage;
-
- if (!isSilent)
- this.navigationHelper_.updateHistory(newPage);
},
- /**
- * Handles the event for the user clicking on a details button.
- * @param {!CustomEvent} e
- * @private
- */
- onShouldShowItemDetails_: function(e) {
- this.showItemDetails(e.detail.data);
+ /** @private */
+ onPackTap_: function() {
+ this.$['pack-dialog'].show();
},
/**
- * Handles the event for the user clicking on the errors button.
- * @param {!CustomEvent} e
+ * @param {!extensions.ShowingType} listType
* @private
*/
- onShouldShowItemErrors_: function(e) {
- this.changePage({page: Page.ERRORS, id: e.detail.data.id});
- },
-
- /** @private */
- onDetailsViewClose_: function() {
- // Note: we don't reset detailViewItem_ here because doing so just causes
- // extra work for the data-bound details view.
- this.changePage({page: Page.LIST});
- },
-
- /** @private */
- onErrorPageClose_: function() {
- // Note: we don't reset errorPageItem_ here because doing so just causes
- // extra work for the data-bound error page.
- this.changePage({page: Page.LIST});
- },
-
- /** @private */
- onPackTap_: function() {
- this.$['pack-dialog'].show();
- }
- });
-
- /** @implements {extensions.SidebarListDelegate} */
- class ListHelper {
- /** @param {extensions.Manager} manager */
- constructor(manager) {
- this.manager_ = manager;
- }
-
- /** @override */
- showType(type) {
- var items;
- switch (type) {
+ computeList_: function(listType) {
+ // TODO(scottchen): the .slice is required to trigger the binding
+ // correctly, otherwise the list won't rerender. Should investigate
+ // the performance implication, or find better ways to trigger change.
+ switch (listType) {
case extensions.ShowingType.EXTENSIONS:
- items = this.manager_.extensions;
- break;
+ this.linkPaths('itemsList_', 'extensions');
+ return this.extensions;
case extensions.ShowingType.APPS:
- items = this.manager_.apps;
- break;
+ this.linkPaths('itemsList_', 'apps');
+ return this.apps;
}
-
- this.manager_.$ /* hack */['items-list'].set('items', assert(items));
- this.manager_.changePage({page: Page.LIST});
}
-
- /** @override */
- showKeyboardShortcuts() {
- this.manager_.changePage({page: Page.SHORTCUTS});
- }
- }
+ });
return {Manager: Manager};
});
diff --git a/chromium/chrome/browser/resources/md_extensions/navigation_helper.js b/chromium/chrome/browser/resources/md_extensions/navigation_helper.js
index d15ca599647..768b9f1aef0 100644
--- a/chromium/chrome/browser/resources/md_extensions/navigation_helper.js
+++ b/chromium/chrome/browser/resources/md_extensions/navigation_helper.js
@@ -2,12 +2,14 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+cr.exportPath('extensions');
+
/**
* The different pages that can be shown at a time.
* Note: This must remain in sync with the page ids in manager.html!
* @enum {string}
*/
-var Page = {
+const Page = {
LIST: 'items-list',
DETAILS: 'details-view',
SHORTCUTS: 'keyboard-shortcuts',
@@ -15,14 +17,20 @@ var Page = {
};
/** @enum {string} */
-var Dialog = {
+const Dialog = {
OPTIONS: 'options',
};
+/** @enum {number} */
+extensions.ShowingType = {
+ EXTENSIONS: 0,
+ APPS: 1,
+};
+
/** @typedef {{page: Page,
extensionId: (string|undefined),
subpage: (!Dialog|undefined)}} */
-var PageState;
+let PageState;
cr.define('extensions', function() {
'use strict';
@@ -33,19 +41,13 @@ cr.define('extensions', function() {
* page), we use this object to manage the history and url conversions.
*/
class NavigationHelper {
- /**
- * @param {!function(!PageState):void} onHistoryChange A function to call
- * when the page has changed as a result of the user going back or
- * forward in history; called with the new active page.
- */
- constructor(onHistoryChange) {
- this.onHistoryChange_ = onHistoryChange;
- window.addEventListener('popstate', this.onPopState_.bind(this));
- }
+ constructor() {
+ /** @private {!Array<function(!PageState)>} */
+ this.listeners_ = [];
- /** @private */
- onPopState_() {
- this.onHistoryChange_(this.getCurrentPage());
+ window.addEventListener('popstate', () => {
+ this.notifyRouteChanged_(this.getCurrentPage());
+ });
}
/**
@@ -53,8 +55,8 @@ cr.define('extensions', function() {
* URL.
*/
getCurrentPage() {
- var search = new URLSearchParams(location.search);
- var id = search.get('id');
+ const search = new URLSearchParams(location.search);
+ let id = search.get('id');
if (id)
return {page: Page.DETAILS, extensionId: id};
id = search.get('options');
@@ -67,7 +69,44 @@ cr.define('extensions', function() {
if (location.pathname == '/shortcuts')
return {page: Page.SHORTCUTS};
- return {page: Page.LIST};
+ if (location.pathname == '/apps')
+ return {page: Page.LIST, type: extensions.ShowingType.APPS};
+
+ return {page: Page.LIST, type: extensions.ShowingType.EXTENSIONS};
+ }
+
+ /**
+ * Function to add subscribers.
+ * @param {!function(!PageState)} listener
+ */
+ onRouteChanged(listener) {
+ this.listeners_.push(listener);
+ }
+
+ /**
+ * Function to notify subscribers.
+ * @private
+ */
+ notifyRouteChanged_(newPage) {
+ for (const listener of this.listeners_) {
+ listener(newPage);
+ }
+ }
+
+ /**
+ * @param {!PageState} newPage the page to navigate to.
+ */
+ navigateTo(newPage) {
+ let currentPage = this.getCurrentPage();
+ if (currentPage && currentPage.page == newPage.page &&
+ currentPage.type == newPage.type &&
+ currentPage.subpage == newPage.subpage &&
+ currentPage.extensionId == newPage.extensionId) {
+ return;
+ }
+
+ this.updateHistory(newPage);
+ this.notifyRouteChanged_(newPage);
}
/**
@@ -75,10 +114,13 @@ cr.define('extensions', function() {
* @param {!PageState} entry
*/
updateHistory(entry) {
- var path;
+ let path;
switch (entry.page) {
case Page.LIST:
- path = '/';
+ if (entry.type && entry.type == extensions.ShowingType.APPS)
+ path = '/apps';
+ else
+ path = '/';
break;
case Page.DETAILS:
if (entry.subpage) {
@@ -96,10 +138,11 @@ cr.define('extensions', function() {
break;
}
assert(path);
- var state = {url: path};
- var currentPage = this.getCurrentPage();
- var isDialogNavigation = currentPage.page == entry.page &&
- currentPage.extensionId == entry.extensionId;
+ const state = {url: path};
+ const currentPage = this.getCurrentPage();
+ const isDialogNavigation = currentPage.page == entry.page &&
+ currentPage.extensionId == entry.extensionId &&
+ currentPage.type == entry.type;
// Navigating to a dialog doesn't visually change pages; it just opens
// a dialog. As such, we replace state rather than pushing a new state
// on the stack so that hitting the back button doesn't just toggle the
@@ -111,5 +154,9 @@ cr.define('extensions', function() {
}
}
- return {NavigationHelper: NavigationHelper};
+ const navigation = new NavigationHelper();
+
+ return {
+ navigation: navigation,
+ };
});
diff --git a/chromium/chrome/browser/resources/md_extensions/options_dialog.html b/chromium/chrome/browser/resources/md_extensions/options_dialog.html
index c00b200d8ef..e7029bf8c76 100644
--- a/chromium/chrome/browser/resources/md_extensions/options_dialog.html
+++ b/chromium/chrome/browser/resources/md_extensions/options_dialog.html
@@ -1,7 +1,9 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://extensions/navigation_helper.html">
<dom-module id="extensions-options-dialog">
<template>
@@ -26,14 +28,15 @@
}
</style>
- <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
+ <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}"
+ on-close="onClose_">
+ <div slot="title">
<div id="icon-and-name-wrapper">
- <img id="icon" src="[[data_.iconUrl]]"></img>
+ <img id="icon" src="[[data_.iconUrl]]">
<span>[[data_.name]]</span>
</div>
</div>
- <div class="body" slot="body" id="body">
+ <div slot="body" id="body">
</div>
</dialog>
</template>
diff --git a/chromium/chrome/browser/resources/md_extensions/options_dialog.js b/chromium/chrome/browser/resources/md_extensions/options_dialog.js
index 261f00708ca..591c4b7049e 100644
--- a/chromium/chrome/browser/resources/md_extensions/options_dialog.js
+++ b/chromium/chrome/browser/resources/md_extensions/options_dialog.js
@@ -5,14 +5,14 @@
cr.define('extensions', function() {
'use strict';
- var MAX_HEIGHT = 600;
- var MAX_WIDTH = 600;
- var MIN_HEIGHT = 300;
- var MIN_WIDTH = 300;
- var HEADER_EXTRA_SPACING = 50; // 40 from x-button + 10 from img margin.
- var DIALOG_PADDING = 32; // Padding from cr-dialog's .body styling.
+ const MAX_HEIGHT = 600;
+ const MAX_WIDTH = 600;
+ const MIN_HEIGHT = 300;
+ const MIN_WIDTH = 300;
+ const HEADER_EXTRA_SPACING = 50; // 40 from x-button + 10 from img margin.
+ const DIALOG_PADDING = 32; // Padding from cr-dialog's .body styling.
- var OptionsDialog = Polymer({
+ const OptionsDialog = Polymer({
is: 'extensions-options-dialog',
properties: {
/** @private {Object} */
@@ -33,22 +33,23 @@ cr.define('extensions', function() {
this.extensionOptions_ = document.createElement('ExtensionOptions');
this.extensionOptions_.extension = this.data_.id;
this.extensionOptions_.onclose = this.close.bind(this);
- var bounded = function(min, max, val) {
+ const bounded = function(min, max, val) {
return Math.min(Math.max(min, val), max);
};
- var onSizeChanged = function(e) {
- var minHeaderWidth = this.$$('#icon-and-name-wrapper img').offsetWidth +
+ const onSizeChanged = e => {
+ const minHeaderWidth =
+ this.$$('#icon-and-name-wrapper img').offsetWidth +
this.$$('#icon-and-name-wrapper span').offsetWidth +
HEADER_EXTRA_SPACING;
- var minWidth = Math.max(minHeaderWidth, MIN_WIDTH);
+ const minWidth = Math.max(minHeaderWidth, MIN_WIDTH);
this.extensionOptions_.style.height =
bounded(MIN_HEIGHT, MAX_HEIGHT, e.height) + 'px';
this.extensionOptions_.style.width =
bounded(minWidth, MAX_WIDTH, e.width) + 'px';
this.$.dialog.style.width =
(bounded(minWidth, MAX_WIDTH, e.width) + DIALOG_PADDING) + 'px';
- }.bind(this);
+ };
this.extensionOptions_.onpreferredsizechanged = onSizeChanged;
this.$.body.appendChild(this.extensionOptions_);
@@ -59,6 +60,22 @@ cr.define('extensions', function() {
close: function() {
this.$$('dialog').close();
},
+
+ /** @private */
+ onClose_: function() {
+ const currentPage = extensions.navigation.getCurrentPage();
+ // We update the page when the options dialog closes, but only if we're
+ // still on the details page. We could be on a different page if the
+ // user hit back while the options dialog was visible; in that case, the
+ // new page is already correct.
+ if (currentPage && currentPage.page == Page.DETAILS) {
+ // This will update the currentPage_ and the NavigationHelper; since
+ // the active page is already the details page, no main page
+ // transition occurs.
+ extensions.navigation.navigateTo(
+ {page: Page.DETAILS, extensionId: currentPage.extensionId});
+ }
+ },
});
return {OptionsDialog: OptionsDialog};
diff --git a/chromium/chrome/browser/resources/md_extensions/pack_dialog.html b/chromium/chrome/browser/resources/md_extensions/pack_dialog.html
index ad54b3f77e0..c793c6364c8 100644
--- a/chromium/chrome/browser/resources/md_extensions/pack_dialog.html
+++ b/chromium/chrome/browser/resources/md_extensions/pack_dialog.html
@@ -5,8 +5,10 @@
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
+<link rel="import" href="pack_dialog_alert.html">
<dom-module id="extensions-pack-dialog">
<template>
@@ -28,14 +30,13 @@
color: var(--google-blue-500);
}
</style>
-
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{packDialogTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{packDialogTitle}</div>
+ <div slot="body">
<div>$i18n{packDialogContent}</div>
<div class="file-input">
<paper-input id="root-dir" label="$i18n{packDialogExtensionRoot}"
- always-float-label value="[[packDirectory_]]">
+ always-float-label value="{{packDirectory_}}">
</paper-input>
<paper-button id="root-dir-browse" on-tap="onRootBrowse_">
$i18n{packDialogBrowse}
@@ -43,22 +44,28 @@
</div>
<div class="file-input">
<paper-input id="key-file" label="$i18n{packDialogKeyFile}"
- always-float-label value="[[keyFile_]]">
+ always-float-label value="{{keyFile_}}">
</paper-input>
<paper-button id="key-file-browse" on-tap="onKeyBrowse_">
$i18n{packDialogBrowse}
</paper-button>
</div>
</div>
- <div class="button-container" slot="button-container">
- <paper-button class="cancel-button" on-tap="close">
+ <div slot="button-container">
+ <paper-button class="cancel-button" on-tap="onCancelTap_">
$i18n{packDialogCancel}
</paper-button>
- <paper-button class="action-button" on-tap="onConfirmTap_">
+ <paper-button class="action-button" on-tap="onConfirmTap_"
+ disabled="[[!packDirectory_]]">
$i18n{packDialogConfirm}
</paper-button>
</div>
</dialog>
+ <template is="dom-if" if="[[lastResponse_]]" restamp>
+ <extensions-pack-dialog-alert model="[[lastResponse_]]"
+ on-warning-confirmed="onWarningConfirmed_" on-close="resetResponse_">
+ </extensions-pack-dialog-alert>
+ </template>
</template>
<script src="chrome://extensions/pack_dialog.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/md_extensions/pack_dialog.js b/chromium/chrome/browser/resources/md_extensions/pack_dialog.js
index b1524a08689..2f8ac643de5 100644
--- a/chromium/chrome/browser/resources/md_extensions/pack_dialog.js
+++ b/chromium/chrome/browser/resources/md_extensions/pack_dialog.js
@@ -27,51 +27,89 @@ cr.define('extensions', function() {
* Packs the extension into a .crx.
* @param {string} rootPath
* @param {string} keyPath
+ * @param {number=} flag
+ * @param {function(chrome.developerPrivate.PackDirectoryResponse)=} callback
*/
packExtension: assertNotReached,
};
- var PackDialog = Polymer({
+ const PackDialog = Polymer({
is: 'extensions-pack-dialog',
properties: {
/** @type {extensions.PackDialogDelegate} */
delegate: Object,
/** @private */
- packDirectory_: String,
+ packDirectory_: {
+ type: String,
+ value: '', // Initialized to trigger binding when attached.
+ },
/** @private */
keyFile_: String,
- },
- show: function() {
- this.$$('dialog').showModal();
+ /** @private {?chrome.developerPrivate.PackDirectoryResponse} */
+ lastResponse_: Object,
},
- close: function() {
- this.$$('dialog').close();
+ show: function() {
+ this.$.dialog.showModal();
},
/** @private */
onRootBrowse_: function() {
- this.delegate.choosePackRootDirectory().then(function(path) {
+ this.delegate.choosePackRootDirectory().then(path => {
if (path)
this.set('packDirectory_', path);
- }.bind(this));
+ });
},
/** @private */
onKeyBrowse_: function() {
- this.delegate.choosePrivateKeyPath().then(function(path) {
+ this.delegate.choosePrivateKeyPath().then(path => {
if (path)
this.set('keyFile_', path);
- }.bind(this));
+ });
+ },
+
+ /** @private */
+ onCancelTap_: function() {
+ this.$.dialog.cancel();
},
/** @private */
onConfirmTap_: function() {
- this.delegate.packExtension(this.packDirectory_, this.keyFile_);
- this.close();
+ this.delegate.packExtension(
+ this.packDirectory_, this.keyFile_, 0,
+ this.onPackResponse_.bind(this));
+ },
+
+ /**
+ * @param {chrome.developerPrivate.PackDirectoryResponse} response the
+ * response from request to pack an extension.
+ * @private
+ */
+ onPackResponse_: function(response) {
+ if (response.status === chrome.developerPrivate.PackStatus.SUCCESS) {
+ this.$.dialog.close();
+ } else {
+ this.set('lastResponse_', response);
+ }
+ },
+
+ /**
+ * The handler function when user chooses to 'Proceed Anyway' upon
+ * receiving a waring.
+ * @private
+ */
+ onWarningConfirmed_: function() {
+ this.delegate.packExtension(
+ this.lastResponse_.item_path, this.lastResponse_.pem_path,
+ this.lastResponse_.override_flags, this.onPackResponse_.bind(this));
+ },
+
+ resetResponse_: function() {
+ this.lastResponse_ = null;
},
});
diff --git a/chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.html b/chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.html
new file mode 100644
index 00000000000..81810d8bcad
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.html
@@ -0,0 +1,33 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
+<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+
+<dom-module id="extensions-pack-dialog-alert">
+ <template>
+ <style include="cr-shared-style paper-button-style">
+ </style>
+
+ <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
+ <div class="title" slot="title">[[title_]]</div>
+ <div class="body" slot="body">
+ [[model.message]]
+ </div>
+ <div class="button-container" slot="button-container">
+ <paper-button class="cancel-button" on-tap="onCancelTap_"
+ hidden="[[!cancelLabel_]]">
+ [[cancelLabel_]]
+ </paper-button>
+ <paper-button class="action-button" on-tap="onConfirmTap_"
+ hidden="[[!confirmLabel_]]">
+ [[confirmLabel_]]
+ </paper-button>
+ </div>
+ </dialog>
+ </template>
+ <script src="chrome://extensions/pack_dialog_alert.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.js b/chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.js
new file mode 100644
index 00000000000..3afe8734260
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_extensions/pack_dialog_alert.js
@@ -0,0 +1,72 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('extensions', function() {
+ 'use strict';
+
+ const PackDialogAlert = Polymer({
+ is: 'extensions-pack-dialog-alert',
+ properties: {
+ /** @private {chrome.developerPrivate.PackDirectoryResponse} */
+ model: Object,
+
+ /** @private */
+ title_: String,
+
+ /** @private */
+ message_: String,
+
+ /** @private */
+ cancelLabel_: String,
+
+ /** @private */
+ confirmLabel_: String,
+ },
+
+ /** @override */
+ ready: function() {
+ // Initialize button label values for initial html binding.
+ this.cancelLabel_ = null;
+ this.confirmLabel_ = null;
+
+ switch (this.model.status) {
+ case chrome.developerPrivate.PackStatus.WARNING:
+ this.title_ = loadTimeData.getString('packDialogWarningTitle');
+ this.cancelLabel_ = loadTimeData.getString('cancel');
+ this.confirmLabel_ =
+ loadTimeData.getString('packDialogProceedAnyway');
+ break;
+ case chrome.developerPrivate.PackStatus.ERROR:
+ this.title_ = loadTimeData.getString('packDialogErrorTitle');
+ this.cancelLabel_ = loadTimeData.getString('ok');
+ break;
+ // If status were success, this dialog should not be attached at all.
+ case chrome.developerPrivate.PackStatus.SUCCESS:
+ default:
+ assertNotReached();
+ return;
+ }
+ },
+
+ /** @override */
+ attached: function() {
+ this.$.dialog.showModal();
+ },
+
+ /** @private */
+ onCancelTap_: function() {
+ this.$.dialog.cancel();
+ },
+
+ /** @private */
+ onConfirmTap_: function() {
+ // The confirm button should only be available in WARNING state.
+ assert(this.model.status === chrome.developerPrivate.PackStatus.WARNING);
+ this.fire('warning-confirmed');
+ this.$.dialog.close();
+ }
+ });
+
+ return {PackDialogAlert: PackDialogAlert};
+});
diff --git a/chromium/chrome/browser/resources/md_extensions/service.html b/chromium/chrome/browser/resources/md_extensions/service.html
index fe1be3facc3..dd8617e16f9 100644
--- a/chromium/chrome/browser/resources/md_extensions/service.html
+++ b/chromium/chrome/browser/resources/md_extensions/service.html
@@ -2,4 +2,5 @@
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://extensions/service.html">
<link rel="import" href="chrome://extensions/item.html">
+<link rel="import" href="chrome://extensions/navigation_helper.html">
<script src="chrome://extensions/service.js"></script>
diff --git a/chromium/chrome/browser/resources/md_extensions/service.js b/chromium/chrome/browser/resources/md_extensions/service.js
index 3754972ebf0..a7c09cb72bf 100644
--- a/chromium/chrome/browser/resources/md_extensions/service.js
+++ b/chromium/chrome/browser/resources/md_extensions/service.js
@@ -29,7 +29,7 @@ cr.define('extensions', function() {
this.manager_ = manager;
this.manager_.set('delegate', this);
- var keyboardShortcuts = this.manager_.keyboardShortcuts;
+ const keyboardShortcuts = this.manager_.keyboardShortcuts;
keyboardShortcuts.addEventListener(
'shortcut-updated', this.onExtensionCommandUpdated_.bind(this));
keyboardShortcuts.addEventListener(
@@ -43,14 +43,13 @@ cr.define('extensions', function() {
chrome.developerPrivate.onItemStateChanged.addListener(
this.onItemStateChanged_.bind(this));
chrome.developerPrivate.getExtensionsInfo(
- {includeDisabled: true, includeTerminated: true},
- function(extensions) {
+ {includeDisabled: true, includeTerminated: true}, extensions => {
this.extensions_ = extensions;
for (let extension of extensions)
this.manager_.addItem(extension);
this.manager_.initPage();
- }.bind(this));
+ });
chrome.developerPrivate.getProfileConfiguration(
this.onProfileStateChanged_.bind(this));
}
@@ -68,11 +67,11 @@ cr.define('extensions', function() {
* @private
*/
onItemStateChanged_(eventData) {
- var currentIndex = this.extensions_.findIndex(function(extension) {
+ const currentIndex = this.extensions_.findIndex(function(extension) {
return extension.id == eventData.item_id;
});
- var EventType = chrome.developerPrivate.EventType;
+ const EventType = chrome.developerPrivate.EventType;
switch (eventData.event_type) {
case EventType.VIEW_REGISTERED:
case EventType.VIEW_UNREGISTERED:
@@ -181,13 +180,13 @@ cr.define('extensions', function() {
if (this.isDeleting_)
return;
this.isDeleting_ = true;
- chrome.management.uninstall(id, {showConfirmDialog: true}, function() {
+ chrome.management.uninstall(id, {showConfirmDialog: true}, () => {
// The "last error" was almost certainly the user canceling the dialog.
// Do nothing. We only check it so we don't get noisy logs.
/** @suppress {suspiciousCode} */
chrome.runtime.lastError;
this.isDeleting_ = false;
- }.bind(this));
+ });
}
/** @override */
@@ -249,14 +248,14 @@ cr.define('extensions', function() {
/** @override */
showItemOptionsPage(id) {
- var extension = this.extensions_.find(function(e) {
+ const extension = this.extensions_.find(function(e) {
return e.id == id;
});
assert(extension && extension.optionsPage);
if (extension.optionsPage.openInTab) {
chrome.developerPrivate.showOptions(id);
} else {
- this.manager_.changePage(
+ extensions.navigation.navigateTo(
{page: Page.DETAILS, subpage: Dialog.OPTIONS, extensionId: id});
}
}
@@ -292,8 +291,8 @@ cr.define('extensions', function() {
}
/** @override */
- packExtension(rootPath, keyPath) {
- chrome.developerPrivate.packDirectory(rootPath, keyPath);
+ packExtension(rootPath, keyPath, flag, callback) {
+ chrome.developerPrivate.packDirectory(rootPath, keyPath, flag, callback);
}
/** @override */
diff --git a/chromium/chrome/browser/resources/md_extensions/shortcut_input.html b/chromium/chrome/browser/resources/md_extensions/shortcut_input.html
index 381c52b046c..5535af64475 100644
--- a/chromium/chrome/browser/resources/md_extensions/shortcut_input.html
+++ b/chromium/chrome/browser/resources/md_extensions/shortcut_input.html
@@ -1,16 +1,17 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/iron-icons.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
<link rel="import" href="chrome://extensions/shortcut_util.html">
<dom-module id="extensions-shortcut-input">
<template>
- <style include="cr-hidden-style">
+ <style include="cr-icons cr-hidden-style">
#main {
position: relative;
width: 200px;
@@ -29,12 +30,9 @@
}
#clear {
- bottom: 6px;
- height: 16px;
- padding: 0;
+ bottom: -4px;
position: absolute;
- right: 0;
- width: 16px;
+ right: -8px;
}
</style>
@@ -42,9 +40,10 @@
<paper-input id="input" placeholder="$i18n{shortcutTypeAShortcut}"
value="[[computeText_(capturing_, shortcut, pendingShortcut_)]]">
</paper-input>
- <paper-icon-button id="clear" icon="clear" on-tap="onClearTap_"
+ <button id="clear" is="paper-icon-button-light"
+ class="icon-clear no-overlap" on-tap="onClearTap_"
hidden$="[[computeClearHidden_(capturing_, shortcut)]]">
- </paper-icon-button>
+ </button>
</div>
</template>
<script src="chrome://extensions/shortcut_input.js"></script>
diff --git a/chromium/chrome/browser/resources/md_extensions/shortcut_input.js b/chromium/chrome/browser/resources/md_extensions/shortcut_input.js
index aeb278de725..f2a834ece85 100644
--- a/chromium/chrome/browser/resources/md_extensions/shortcut_input.js
+++ b/chromium/chrome/browser/resources/md_extensions/shortcut_input.js
@@ -6,7 +6,7 @@ cr.define('extensions', function() {
'use strict';
// The UI to display and manage keyboard shortcuts set for extension commands.
- var ShortcutInput = Polymer({
+ const ShortcutInput = Polymer({
is: 'extensions-shortcut-input',
behaviors: [I18nBehavior],
@@ -37,7 +37,7 @@ cr.define('extensions', function() {
},
ready: function() {
- var node = this.$['input'];
+ const node = this.$['input'];
node.addEventListener('mouseup', this.startCapture_.bind(this));
node.addEventListener('blur', this.endCapture_.bind(this));
node.addEventListener('focus', this.startCapture_.bind(this));
diff --git a/chromium/chrome/browser/resources/md_extensions/sidebar.html b/chromium/chrome/browser/resources/md_extensions/sidebar.html
index c8dcb011d23..030c5c10243 100644
--- a/chromium/chrome/browser/resources/md_extensions/sidebar.html
+++ b/chromium/chrome/browser/resources/md_extensions/sidebar.html
@@ -1,9 +1,11 @@
-<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-item/paper-item.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-menu/paper-menu.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
+<link rel="import" href="navigation_helper.html">
<dom-module id="extensions-sidebar">
<template>
diff --git a/chromium/chrome/browser/resources/md_extensions/sidebar.js b/chromium/chrome/browser/resources/md_extensions/sidebar.js
index ad6b4011b65..c81d9193804 100644
--- a/chromium/chrome/browser/resources/md_extensions/sidebar.js
+++ b/chromium/chrome/browser/resources/md_extensions/sidebar.js
@@ -1,60 +1,29 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
-cr.exportPath('extensions');
-
-// Declare this here to make closure compiler happy, and us sad.
-/** @enum {number} */
-extensions.ShowingType = {
- EXTENSIONS: 0,
- APPS: 1,
-};
-
cr.define('extensions', function() {
- /** @interface */
- var SidebarListDelegate = function() {};
-
- SidebarListDelegate.prototype = {
- /**
- * Shows the given type of item.
- * @param {extensions.ShowingType} type
- */
- showType: assertNotReached,
-
- /** Shows the keyboard shortcuts page. */
- showKeyboardShortcuts: assertNotReached,
- };
-
- var Sidebar = Polymer({
+ const Sidebar = Polymer({
is: 'extensions-sidebar',
behaviors: [I18nBehavior],
- /** @param {extensions.SidebarListDelegate} listDelegate */
- setListDelegate: function(listDelegate) {
- /** @private {extensions.SidebarListDelegate} */
- this.listDelegate_ = listDelegate;
- },
-
/** @private */
onExtensionsTap_: function() {
- this.listDelegate_.showType(extensions.ShowingType.EXTENSIONS);
+ extensions.navigation.navigateTo(
+ {page: Page.LIST, type: extensions.ShowingType.EXTENSIONS});
},
/** @private */
onAppsTap_: function() {
- this.listDelegate_.showType(extensions.ShowingType.APPS);
+ extensions.navigation.navigateTo(
+ {page: Page.LIST, type: extensions.ShowingType.APPS});
},
/** @private */
onKeyboardShortcutsTap_: function() {
- this.listDelegate_.showKeyboardShortcuts();
+ extensions.navigation.navigateTo({page: Page.SHORTCUTS});
},
});
- return {
- Sidebar: Sidebar,
- SidebarListDelegate: SidebarListDelegate,
- };
+ return {Sidebar: Sidebar};
});
diff --git a/chromium/chrome/browser/resources/md_extensions/toolbar.html b/chromium/chrome/browser/resources/md_extensions/toolbar.html
index 413eab810ce..20d8d952a80 100644
--- a/chromium/chrome/browser/resources/md_extensions/toolbar.html
+++ b/chromium/chrome/browser/resources/md_extensions/toolbar.html
@@ -3,6 +3,8 @@
<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_toggle_style_css.html">
+<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html">
@@ -11,7 +13,7 @@
<dom-module id="extensions-toolbar">
<template>
- <style include="cr-hidden-style paper-button-style">
+ <style include="cr-hidden-style paper-button-style paper-toggle-style">
:host {
--toolbar-width: 580px;
--toolbar-color: var(--md-toolbar-color);
@@ -22,6 +24,18 @@
background: var(--toolbar-color);
}
+ /* This toggle needs special styling because it's on blue background. */
+ cr-toolbar paper-toggle-button {
+ --paper-toggle-button-checked-bar: {
+ @apply(--cr-toggle-bar-size);
+ opacity: 0.5;
+ };
+ --paper-toggle-button-checked-bar-color: white;
+ --paper-toggle-button-checked-button-color: white;
+ --paper-toggle-button-checked-ink-color: white;
+ --paper-toggle-button-unchecked-ink-color: white;
+ }
+
.dev-controls {
background: var(--toolbar-color);
display: flex;
diff --git a/chromium/chrome/browser/resources/md_extensions/toolbar.js b/chromium/chrome/browser/resources/md_extensions/toolbar.js
index 6cb12268aaf..f7e5051491f 100644
--- a/chromium/chrome/browser/resources/md_extensions/toolbar.js
+++ b/chromium/chrome/browser/resources/md_extensions/toolbar.js
@@ -6,7 +6,7 @@ cr.exportPath('extensions');
cr.define('extensions', function() {
/** @interface */
- var ToolbarDelegate = function() {};
+ const ToolbarDelegate = function() {};
ToolbarDelegate.prototype = {
/**
@@ -22,7 +22,7 @@ cr.define('extensions', function() {
updateAllExtensions: assertNotReached,
};
- var Toolbar = Polymer({
+ const Toolbar = Polymer({
is: 'extensions-toolbar',
behaviors: [I18nBehavior],
diff --git a/chromium/chrome/browser/resources/md_extensions/view_manager.html b/chromium/chrome/browser/resources/md_extensions/view_manager.html
new file mode 100644
index 00000000000..75a6207af57
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_extensions/view_manager.html
@@ -0,0 +1,26 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/cr.html">
+
+<dom-module id="extensions-view-manager">
+ <template>
+ <style>
+ :host ::slotted([slot=view]) {
+ bottom: 0;
+ display: none;
+ left: 0;
+ position: absolute;
+ right: 0;
+ top: 0;
+ }
+
+ :host ::slotted(.active),
+ :host ::slotted(.closing) {
+ display: block;
+ }
+ </style>
+ <slot name="view"></slot>
+ </template>
+ <script src="chrome://extensions/view_manager.js"></script>
+</dom-module> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/md_extensions/view_manager.js b/chromium/chrome/browser/resources/md_extensions/view_manager.js
new file mode 100644
index 00000000000..36e5383065f
--- /dev/null
+++ b/chromium/chrome/browser/resources/md_extensions/view_manager.js
@@ -0,0 +1,126 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('extensions', function() {
+ 'use strict';
+
+ /**
+ * TODO(scottchen): shim for not having Animation.finished implemented. Can
+ * replace with Animation.finished if Chrome implements it (see:
+ * crbug.com/257235).
+ * @param {!Animation} animation
+ * @return {!Promise}
+ */
+ function whenFinished(animation) {
+ return new Promise(function(resolve, reject) {
+ animation.addEventListener('finish', resolve);
+ });
+ }
+
+ /** @type {!Map<string, function(!Element): !Promise>} */
+ const viewAnimations = new Map();
+ viewAnimations.set('no-animation', () => Promise.resolve());
+ viewAnimations.set('fade-in', element => {
+ const animation = element.animate(
+ {
+ opacity: [0, 1],
+ },
+ /** @type {!KeyframeEffectOptions} */ ({
+ duration: 180,
+ easing: 'ease-in-out',
+ iterations: 1,
+ }));
+
+ return whenFinished(animation);
+ });
+ viewAnimations.set('fade-out', element => {
+ const animation = element.animate(
+ {
+ opacity: [1, 0],
+ },
+ /** @type {!KeyframeEffectOptions} */ ({
+ duration: 180,
+ easing: 'ease-in-out',
+ iterations: 1,
+ }));
+
+ return whenFinished(animation);
+ });
+
+ const ViewManager = Polymer({
+ is: 'extensions-view-manager',
+
+ /**
+ * @param {!Element} element
+ * @param {string} animation
+ * @return {!Promise}
+ * @private
+ */
+ exit_: function(element, animation) {
+ const animationFunction = extensions.viewAnimations.get(animation);
+ assert(animationFunction);
+
+ element.classList.remove('active');
+ element.classList.add('closing');
+ element.dispatchEvent(new CustomEvent('view-exit-start'));
+ return animationFunction(element).then(function() {
+ element.classList.remove('closing');
+ element.dispatchEvent(new CustomEvent('view-exit-finish'));
+ });
+ },
+
+ /**
+ * @param {!Element} element
+ * @param {!string} animation
+ * @return {!Promise}
+ * @private
+ */
+ enter_: function(element, animation) {
+ const animationFunction = extensions.viewAnimations.get(animation);
+ assert(animationFunction);
+
+ element.classList.add('active');
+ element.dispatchEvent(new CustomEvent('view-enter-start'));
+ return animationFunction(element).then(function() {
+ element.dispatchEvent(new CustomEvent('view-enter-finish'));
+ });
+ },
+
+ /**
+ * @param {string} newViewId
+ * @param {string=} enterAnimation
+ * @param {string=} exitAnimation
+ * @return {!Promise}
+ */
+ switchView: function(newViewId, enterAnimation, exitAnimation) {
+ const previousView = this.querySelector('.active');
+ const newView = assert(this.querySelector('#' + newViewId));
+
+ const promises = [];
+ if (previousView) {
+ promises.push(this.exit_(previousView, exitAnimation || 'fade-out'));
+ promises.push(this.enter_(newView, enterAnimation || 'fade-in'));
+ } else {
+ promises.push(this.enter_(newView, 'no-animation'));
+ }
+
+ return Promise.all(promises);
+ },
+
+ /**
+ * Helper function to only animate the current view.
+ * @param {string} animation
+ * @return {!Promise}
+ */
+ animateCurrentView: function(animation) {
+ const currentView = assert(this.querySelector('.active'));
+ const animationFunction = extensions.viewAnimations.get(animation);
+ assert(animationFunction);
+
+ return animationFunction(currentView);
+ },
+ });
+
+ return {viewAnimations: viewAnimations, ViewManager: ViewManager};
+}); \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/md_history/BUILD.gn b/chromium/chrome/browser/resources/md_history/BUILD.gn
index 6f9eada47d6..2625f114634 100644
--- a/chromium/chrome/browser/resources/md_history/BUILD.gn
+++ b/chromium/chrome/browser/resources/md_history/BUILD.gn
@@ -1,51 +1,26 @@
import("../vulcanize.gni")
-app_unbuilt = "app.vulcanized.unbuilt.html"
-lazy_load_unbuilt = "lazy_load.vulcanized.unbuilt.html"
-
-vulcanize("vulcanize_app") {
+vulcanize("build") {
host = "history"
- html_in_file = "app.html"
- html_out_file = app_unbuilt
+ html_in_files = [
+ "app.html",
+ "lazy_load.html",
+ ]
+ html_out_files = [
+ "app.vulcanized.html",
+ "lazy_load.vulcanized.html",
+ ]
input = rebase_path(".", root_build_dir)
- js_out_file = "app.crisper.js"
-
- excludes = [
- "chrome://resources/html/util.html",
- "chrome://history/constants.html",
+ js_out_files = [
+ "app.crisper.js",
+ "lazy_load.crisper.js",
]
- deps = []
-}
-
-vulcanize("vulcanize_lazy_load") {
- host = "history"
- html_in_file = "lazy_load.html"
- html_out_file = lazy_load_unbuilt
-
- input = rebase_path(".", root_build_dir)
- js_out_file = "lazy_load.crisper.js"
excludes = [
"chrome://resources/html/util.html",
"chrome://history/constants.html",
- "chrome://history/app.html",
]
deps = []
}
-
-polymer_css_build("build") {
- input_files = [
- app_unbuilt,
- lazy_load_unbuilt,
- ]
- output_files = [
- "app.vulcanized.html",
- "lazy_load.vulcanized.html",
- ]
- deps = [
- ":vulcanize_app",
- ":vulcanize_lazy_load",
- ]
-}
diff --git a/chromium/chrome/browser/resources/md_history/OWNERS b/chromium/chrome/browser/resources/md_history/OWNERS
index 68e023a6b9b..c85d9424611 100644
--- a/chromium/chrome/browser/resources/md_history/OWNERS
+++ b/chromium/chrome/browser/resources/md_history/OWNERS
@@ -1,5 +1,4 @@
calamity@chromium.org
-dbeam@chromium.org
tsergeant@chromium.org
# COMPONENT: UI>Browser>History
diff --git a/chromium/chrome/browser/resources/md_history/app.js b/chromium/chrome/browser/resources/md_history/app.js
index 058bd546e37..de2d100abbf 100644
--- a/chromium/chrome/browser/resources/md_history/app.js
+++ b/chromium/chrome/browser/resources/md_history/app.js
@@ -299,9 +299,9 @@ Polymer({
historyViewChanged_: function() {
// This allows the synced-device-manager to render so that it can be set as
// the scroll target.
- requestAnimationFrame(function() {
+ requestAnimationFrame(() => {
this._scrollHandler();
- }.bind(this));
+ });
this.recordHistoryPageView_();
},
diff --git a/chromium/chrome/browser/resources/md_history/externs.js b/chromium/chrome/browser/resources/md_history/externs.js
index 6ba6f5ad8b9..590c127b8e3 100644
--- a/chromium/chrome/browser/resources/md_history/externs.js
+++ b/chromium/chrome/browser/resources/md_history/externs.js
@@ -35,8 +35,6 @@ var HistoryEntry;
* BrowsingHistoryHandler::QueryComplete()
* @typedef {{finished: boolean,
* hasSyncedResults: boolean,
- * queryEndTime: string,
- * queryStartTime: string,
* term: string}}
*/
var HistoryQuery;
diff --git a/chromium/chrome/browser/resources/md_history/history.js b/chromium/chrome/browser/resources/md_history/history.js
index 5f8e6d4dec7..e6c5ff04fea 100644
--- a/chromium/chrome/browser/resources/md_history/history.js
+++ b/chromium/chrome/browser/resources/md_history/history.js
@@ -4,7 +4,7 @@
// Send the history query immediately. This allows the query to process during
// the initial page startup.
-chrome.send('queryHistory', ['', 0, RESULTS_PER_PAGE]);
+chrome.send('queryHistory', ['', RESULTS_PER_PAGE]);
chrome.send('getForeignSessions');
/** @type {Promise} */
diff --git a/chromium/chrome/browser/resources/md_history/history_item.html b/chromium/chrome/browser/resources/md_history/history_item.html
index 982ab92b227..0bb3bbe614c 100644
--- a/chromium/chrome/browser/resources/md_history/history_item.html
+++ b/chromium/chrome/browser/resources/md_history/history_item.html
@@ -1,6 +1,7 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_row.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html">
<link rel="import" href="chrome://resources/html/icon.html">
diff --git a/chromium/chrome/browser/resources/md_history/history_item.js b/chromium/chrome/browser/resources/md_history/history_item.js
index 36692e881e4..4aea6ae9d91 100644
--- a/chromium/chrome/browser/resources/md_history/history_item.js
+++ b/chromium/chrome/browser/resources/md_history/history_item.js
@@ -220,9 +220,9 @@ cr.define('md_history', function() {
*/
onItemMousedown_: function(e) {
this.mouseDown_ = true;
- listenOnce(document, 'mouseup', function() {
+ listenOnce(document, 'mouseup', () => {
this.mouseDown_ = false;
- }.bind(this));
+ });
// Prevent shift clicking a checkbox from selecting text.
if (e.shiftKey)
e.preventDefault();
diff --git a/chromium/chrome/browser/resources/md_history/history_list.html b/chromium/chrome/browser/resources/md_history/history_list.html
index a9c4b6405bf..15d42bbae08 100644
--- a/chromium/chrome/browser/resources/md_history/history_list.html
+++ b/chromium/chrome/browser/resources/md_history/history_list.html
@@ -26,7 +26,7 @@
margin-top: var(--first-card-padding-top);
}
- dialog .body {
+ dialog [slot=body] {
white-space: pre-wrap;
}
</style>
@@ -59,9 +59,9 @@
<template is="cr-lazy-render" id="dialog">
<dialog is="cr-dialog">
- <div class="title" slot="title">$i18n{removeSelected}</div>
- <div class="body" slot="body">$i18n{deleteWarning}</div>
- <div class="button-container" slot="button-container">
+ <div slot="title">$i18n{removeSelected}</div>
+ <div slot="body">$i18n{deleteWarning}</div>
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onDialogCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/md_history/history_list.js b/chromium/chrome/browser/resources/md_history/history_list.js
index 09ac8442c3c..c9a11568cef 100644
--- a/chromium/chrome/browser/resources/md_history/history_list.js
+++ b/chromium/chrome/browser/resources/md_history/history_list.js
@@ -142,9 +142,9 @@ Polymer({
* Deselect each item in |selectedItems|.
*/
unselectAllItems: function() {
- this.selectedItems.forEach(function(index) {
+ this.selectedItems.forEach((index) => {
this.changeSelection_(index, false);
- }.bind(this));
+ });
assert(this.selectedItems.size == 0);
},
@@ -197,17 +197,15 @@ Polymer({
* @private
*/
deleteSelected_: function() {
- var toBeRemoved =
- Array.from(this.selectedItems.values()).map(function(index) {
- return this.get('historyData_.' + index);
- }.bind(this));
+ var toBeRemoved = Array.from(this.selectedItems.values())
+ .map((index) => this.get('historyData_.' + index));
md_history.BrowserService.getInstance()
.deleteItems(toBeRemoved)
- .then(function(items) {
+ .then((items) => {
this.removeItemsByIndex_(Array.from(this.selectedItems));
this.fire('unselect-all');
- }.bind(this));
+ });
},
/**
@@ -223,7 +221,7 @@ Polymer({
// Sort in reverse numerical order.
return b - a;
});
- indices.forEach(function(index) {
+ indices.forEach((index) => {
var item = this.historyData_.splice(index, 1);
splices.push({
index: index,
@@ -232,7 +230,7 @@ Polymer({
object: this.historyData_,
type: 'splice'
});
- }.bind(this));
+ });
this.notifySplices('historyData_', splices);
},
@@ -316,7 +314,7 @@ Polymer({
var target = e.detail.target;
this.actionMenuModel_ = e.detail;
- var menu = /** @type {CrSharedMenuElement} */ this.$.sharedMenu.get();
+ var menu = /** @type {CrActionMenuElement} */ (this.$.sharedMenu.get());
menu.showAt(target);
},
@@ -337,7 +335,7 @@ Polymer({
browserService.recordAction('EntryMenuRemoveFromHistory');
var menu = assert(this.$.sharedMenu.getIfExists());
var itemData = this.actionMenuModel_;
- browserService.deleteItems([itemData.item]).then(function(items) {
+ browserService.deleteItems([itemData.item]).then((items) => {
// This unselect-all resets the toolbar when deleting a selected item
// and clears selection state which can be invalid if items move
// around during deletion.
@@ -359,7 +357,7 @@ Polymer({
'HistoryPage.RemoveEntryPositionSubset', index,
UMA_MAX_SUBSET_BUCKET_VALUE);
}
- }.bind(this));
+ });
this.closeMenu_();
},
@@ -385,9 +383,9 @@ Polymer({
var selected = !this.selectedItems.has(index);
- indices.forEach(function(index) {
+ indices.forEach((index) => {
this.changeSelection_(index, selected);
- }.bind(this));
+ });
this.lastSelectedIndex = index;
},
diff --git a/chromium/chrome/browser/resources/md_history/lazy_load.html b/chromium/chrome/browser/resources/md_history/lazy_load.html
index 666fd68a3ac..011a4357ef2 100644
--- a/chromium/chrome/browser/resources/md_history/lazy_load.html
+++ b/chromium/chrome/browser/resources/md_history/lazy_load.html
@@ -1,7 +1,12 @@
-<link rel="import" href="chrome://history/synced_device_manager.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_drawer/cr_drawer.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar_selection_overlay.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
+<html>
+<head></head>
+<body>
+ <link rel="import" href="chrome://history/synced_device_manager.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_drawer/cr_drawer.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar_selection_overlay.html">
+ <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+ <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
+</body>
+</html>
diff --git a/chromium/chrome/browser/resources/md_history/query_manager.js b/chromium/chrome/browser/resources/md_history/query_manager.js
index 2d41730edc4..de55e2b359b 100644
--- a/chromium/chrome/browser/resources/md_history/query_manager.js
+++ b/chromium/chrome/browser/resources/md_history/query_manager.js
@@ -64,17 +64,14 @@ Polymer({
this.set('queryState.querying', true);
this.set('queryState.incremental', incremental);
- var lastVisitTime = 0;
if (incremental) {
- var lastVisit = this.queryResult.results.slice(-1)[0];
- lastVisitTime = lastVisit ? Math.floor(lastVisit.time) : 0;
+ chrome.send('queryHistoryContinuation');
+ } else {
+ chrome.send('queryHistory', [
+ queryState.searchTerm,
+ RESULTS_PER_PAGE,
+ ]);
}
-
- chrome.send('queryHistory', [
- queryState.searchTerm,
- lastVisitTime,
- RESULTS_PER_PAGE,
- ]);
},
/**
@@ -103,7 +100,7 @@ Polymer({
* @private
*/
onQueryHistory_: function(e) {
- this.queryHistory_(/** @type {boolean} */ e.detail);
+ this.queryHistory_(/** @type {boolean} */ (e.detail));
return false;
},
diff --git a/chromium/chrome/browser/resources/md_history/side_bar.html b/chromium/chrome/browser/resources/md_history/side_bar.html
index d26b03c3434..8ea9c0262e4 100644
--- a/chromium/chrome/browser/resources/md_history/side_bar.html
+++ b/chromium/chrome/browser/resources/md_history/side_bar.html
@@ -39,13 +39,13 @@
}
iron-selector {
- -webkit-user-select: none;
background-color: transparent;
color: var(--sidebar-unselected-color);
display: flex;
flex: 1;
flex-direction: column;
padding-top: 8px;
+ user-select: none;
}
iron-selector > a {
diff --git a/chromium/chrome/browser/resources/md_history/synced_device_card.html b/chromium/chrome/browser/resources/md_history/synced_device_card.html
index 6aa1c745c0e..9e80d9b8083 100644
--- a/chromium/chrome/browser/resources/md_history/synced_device_card.html
+++ b/chromium/chrome/browser/resources/md_history/synced_device_card.html
@@ -1,6 +1,7 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_row.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
diff --git a/chromium/chrome/browser/resources/md_history/synced_device_manager.js b/chromium/chrome/browser/resources/md_history/synced_device_manager.js
index ad4da3d74d9..8ea2b78d7e4 100644
--- a/chromium/chrome/browser/resources/md_history/synced_device_manager.js
+++ b/chromium/chrome/browser/resources/md_history/synced_device_manager.js
@@ -152,7 +152,7 @@ Polymer({
/** @private */
onOpenMenu_: function(e) {
- var menu = /** @type {CrActionMenuElement} */ this.$.menu.get();
+ var menu = /** @type {CrActionMenuElement} */ (this.$.menu.get());
this.actionMenuModel_ = e.detail.tag;
menu.showAt(e.detail.target);
md_history.BrowserService.getInstance().recordHistogram(
@@ -187,9 +187,9 @@ Polymer({
return prev.concat(cur.createFocusRows());
},
[])
- .forEach(function(row) {
+ .forEach((row) => {
this.focusGrid_.addRow(row);
- }.bind(this));
+ });
this.focusGrid_.ensureRowActive(1);
});
},
@@ -277,11 +277,11 @@ Polymer({
}
var devices = [];
- sessionList.forEach(function(session) {
+ sessionList.forEach((session) => {
var device = this.createInternalDevice_(session);
if (device.tabs.length != 0)
devices.push(device);
- }.bind(this));
+ });
this.syncedDevices_ = devices;
},
diff --git a/chromium/chrome/browser/resources/md_policy/md_policy.html b/chromium/chrome/browser/resources/md_policy/md_policy.html
deleted file mode 100644
index 0ed781997cf..00000000000
--- a/chromium/chrome/browser/resources/md_policy/md_policy.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!doctype html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Policies</title>
-</head>
-<body>
- <h1>A Material Design policy page is under construction!</h1>
-</body>
-</html>
diff --git a/chromium/chrome/browser/resources/md_policy/policy_resources.grd b/chromium/chrome/browser/resources/md_policy/policy_resources.grd
deleted file mode 100644
index dc76f527185..00000000000
--- a/chromium/chrome/browser/resources/md_policy/policy_resources.grd
+++ /dev/null
@@ -1,21 +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/policy_resources.h" type="rc_header">
- <emit emit_type='prepend'></emit>
- </output>
- <output filename="grit/policy_resources_map.cc"
- type="resource_file_map_source" />
- <output filename="grit/policy_resources_map.h"
- type="resource_map_header" />
- <output filename="policy_resources.pak" type="data_package" />
- </outputs>
- <release seq="1">
- <structures>
- <!-- TODO(fhorschig): Add upcoming polymer files here. -->
- <structure name="IDR_MD_POLICY_HTML"
- file="md_policy.html"
- type="chrome_html"/>
- </structures>
- </release>
-</grit>
diff --git a/chromium/chrome/browser/resources/md_user_manager/control_bar.html b/chromium/chrome/browser/resources/md_user_manager/control_bar.html
index 8c3319f13b0..279791937af 100644
--- a/chromium/chrome/browser/resources/md_user_manager/control_bar.html
+++ b/chromium/chrome/browser/resources/md_user_manager/control_bar.html
@@ -1,7 +1,8 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/profile_browser_proxy.html">
<link rel="import" href="/shared_styles.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
diff --git a/chromium/chrome/browser/resources/md_user_manager/control_bar.js b/chromium/chrome/browser/resources/md_user_manager/control_bar.js
index 5e22faf8086..b58e581518a 100644
--- a/chromium/chrome/browser/resources/md_user_manager/control_bar.js
+++ b/chromium/chrome/browser/resources/md_user_manager/control_bar.js
@@ -52,14 +52,14 @@ Polymer({
* @private
*/
onLaunchGuestTap_: function(event) {
- this.browserProxy_.areAllProfilesLocked().then(function(allProfilesLocked) {
+ this.browserProxy_.areAllProfilesLocked().then(allProfilesLocked => {
if (!allProfilesLocked || this.isForceSigninEnabled_) {
this.browserProxy_.launchGuestUser();
} else {
document.querySelector('error-dialog')
.show(this.i18n('browseAsGuestAllProfilesLockedError'));
}
- }.bind(this));
+ });
},
/**
@@ -68,7 +68,7 @@ Polymer({
* @private
*/
onAddUserTap_: function(event) {
- this.browserProxy_.areAllProfilesLocked().then(function(allProfilesLocked) {
+ this.browserProxy_.areAllProfilesLocked().then(allProfilesLocked => {
if (!allProfilesLocked || this.isForceSigninEnabled_) {
// Event is caught by user-manager-pages.
this.fire('change-page', {page: 'create-user-page'});
@@ -76,6 +76,6 @@ Polymer({
document.querySelector('error-dialog')
.show(this.i18n('addProfileAllProfilesLockedError'));
}
- }.bind(this));
+ });
}
});
diff --git a/chromium/chrome/browser/resources/md_user_manager/create_profile.html b/chromium/chrome/browser/resources/md_user_manager/create_profile.html
index b098070f5e0..a14ae723f83 100644
--- a/chromium/chrome/browser/resources/md_user_manager/create_profile.html
+++ b/chromium/chrome/browser/resources/md_user_manager/create_profile.html
@@ -1,12 +1,14 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/import_supervised_user.html">
<link rel="import" href="/profile_browser_proxy.html">
<link rel="import" href="/shared_styles.html">
<link rel="import" href="chrome://resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_checkbox_style_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/md_select_css.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
@@ -18,7 +20,8 @@
<dom-module id="create-profile">
<template>
- <style include="shared-styles iron-positioning md-select">
+ <style
+ include="shared-styles iron-positioning md-select paper-checkbox-style">
.container {
color: var(--primary-text-color);
width: var(--page-width);
diff --git a/chromium/chrome/browser/resources/md_user_manager/create_profile.js b/chromium/chrome/browser/resources/md_user_manager/create_profile.js
index 59deaa4b27c..05b9f68b78a 100644
--- a/chromium/chrome/browser/resources/md_user_manager/create_profile.js
+++ b/chromium/chrome/browser/resources/md_user_manager/create_profile.js
@@ -154,9 +154,9 @@ Polymer({
'create-profile-warning', this.handleMessage_.bind(this));
this.addWebUIListener(
'create-profile-error', this.handleMessage_.bind(this));
- this.addWebUIListener('profile-icons-received', function(icons) {
+ this.addWebUIListener('profile-icons-received', icons => {
this.availableIcons_ = icons;
- }.bind(this));
+ });
this.addWebUIListener(
'profile-defaults-received', this.handleProfileDefaults_.bind(this));
this.addWebUIListener(
diff --git a/chromium/chrome/browser/resources/md_user_manager/error_dialog.html b/chromium/chrome/browser/resources/md_user_manager/error_dialog.html
index 6c1bd2904fe..a55ec1bfd70 100644
--- a/chromium/chrome/browser/resources/md_user_manager/error_dialog.html
+++ b/chromium/chrome/browser/resources/md_user_manager/error_dialog.html
@@ -1,6 +1,7 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/shared_styles.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<dom-module id="error-dialog">
<template>
@@ -16,7 +17,7 @@
}
</style>
<dialog is="cr-dialog" id="dialog">
- <div class="body" slot="body">
+ <div slot="body">
<div id="message">[[message_]]</div>
</div>
</dialog>
diff --git a/chromium/chrome/browser/resources/md_user_manager/import_supervised_user.html b/chromium/chrome/browser/resources/md_user_manager/import_supervised_user.html
index 89fc19669b3..b308c932f87 100644
--- a/chromium/chrome/browser/resources/md_user_manager/import_supervised_user.html
+++ b/chromium/chrome/browser/resources/md_user_manager/import_supervised_user.html
@@ -1,8 +1,9 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/shared_styles.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-item/paper-item.html">
@@ -62,13 +63,13 @@
}
</style>
<dialog is="cr-dialog" id="dialog">
- <div class="title" slot="title">$i18n{supervisedUserImportTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{supervisedUserImportTitle}</div>
+ <div slot="body">
<div id="message">$i18n{supervisedUserImportText}</div>
<paper-listbox class="no-padding" selected="{{supervisedUserIndex_}}">
<template is="dom-repeat" items="[[supervisedUsers_]]">
<paper-item disabled="[[item.onCurrentDevice]]">
- <img class="profile-img" src="[[item.iconURL]]"></img>
+ <img class="profile-img" src="[[item.iconURL]]">
<div class="profile-name">[[item.name]]</div>
<div class="on-device" hidden="[[!item.onCurrentDevice]]">
$i18n{supervisedUserAlreadyOnThisDevice}
@@ -77,7 +78,7 @@
</template>
</paper-listbox>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="cancel" class="cancel-button" on-tap="onCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.html b/chromium/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.html
index d132892c1cc..4b50826658d 100644
--- a/chromium/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.html
+++ b/chromium/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.html
@@ -1,7 +1,8 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/icons.html">
<link rel="import" href="/profile_browser_proxy.html">
<link rel="import" href="/shared_styles.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
diff --git a/chromium/chrome/browser/resources/md_user_manager/supervised_user_learn_more.html b/chromium/chrome/browser/resources/md_user_manager/supervised_user_learn_more.html
index eebb7b1e271..2547500b9ab 100644
--- a/chromium/chrome/browser/resources/md_user_manager/supervised_user_learn_more.html
+++ b/chromium/chrome/browser/resources/md_user_manager/supervised_user_learn_more.html
@@ -1,6 +1,7 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/icons.html">
<link rel="import" href="/shared_styles.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
diff --git a/chromium/chrome/browser/resources/md_user_manager/user_manager.html b/chromium/chrome/browser/resources/md_user_manager/user_manager.html
index c838cf33c1e..95537c923d2 100644
--- a/chromium/chrome/browser/resources/md_user_manager/user_manager.html
+++ b/chromium/chrome/browser/resources/md_user_manager/user_manager.html
@@ -56,6 +56,7 @@
* manager. */
#outer-container {
+ -webkit-box-orient: vertical;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
@@ -308,11 +309,23 @@
};
@apply(--action-button);
}
+
+ #user-manager-prompt-message {
+ font-size: 19px;
+ margin-bottom: 45px;
+ text-align: center;
+ }
+
+ #user-manager-prompt-message:empty {
+ display: none;
+ }
+
</style>
</head>
<body>
<user-manager-pages>
<div id="outer-container">
+ <div id="user-manager-prompt-message">$i18n{userManagerPromptMessage}</div>
<user-manager-tutorial></user-manager-tutorial>
<div id="oobe" class="faded">
<div id="inner-container">
diff --git a/chromium/chrome/browser/resources/md_user_manager/user_manager_pages.html b/chromium/chrome/browser/resources/md_user_manager/user_manager_pages.html
index 5ac8b0357f1..10f655aa774 100644
--- a/chromium/chrome/browser/resources/md_user_manager/user_manager_pages.html
+++ b/chromium/chrome/browser/resources/md_user_manager/user_manager_pages.html
@@ -1,7 +1,8 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/create_profile.html">
<link rel="import" href="/supervised_user_create_confirm.html">
<link rel="import" href="/supervised_user_learn_more.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-in-animation.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-out-animation.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html">
@@ -20,7 +21,7 @@
}
/* neon-animated-pages does not automatically hide what's under content */
- neon-animatable:not(.iron-selected) > ::content > * {
+ neon-animatable:not(.iron-selected) ::slotted(*) {
display: none !important;
}
</style>
@@ -37,7 +38,7 @@
</template>
</neon-animatable>
<neon-animatable id="user-pods-page">
- <content></content>
+ <slot></slot>
</neon-animatable>
<neon-animatable id="supervised-learn-more-page">
<template is="dom-if"
diff --git a/chromium/chrome/browser/resources/md_user_manager/user_manager_tutorial.html b/chromium/chrome/browser/resources/md_user_manager/user_manager_tutorial.html
index f07efb98178..56a4543f847 100644
--- a/chromium/chrome/browser/resources/md_user_manager/user_manager_tutorial.html
+++ b/chromium/chrome/browser/resources/md_user_manager/user_manager_tutorial.html
@@ -1,6 +1,7 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="/shared_styles.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="user-manager-tutorial">
diff --git a/chromium/chrome/browser/resources/media/media_engagement.html b/chromium/chrome/browser/resources/media/media_engagement.html
index 77b8ed8573d..d789f520375 100644
--- a/chromium/chrome/browser/resources/media/media_engagement.html
+++ b/chromium/chrome/browser/resources/media/media_engagement.html
@@ -104,6 +104,9 @@
<th sort-key="lastMediaPlaybackTime" sort-reverse>
Last Playback
</th>
+ <th sort-key="isHigh" sort-reverse>
+ Is High
+ </th>
<th sort-key="totalScore" class="sort-column" sort-reverse>
Score
</th>
@@ -119,6 +122,7 @@
<td class="visits-count-cell"></td>
<td class="media-playbacks-count-cell"></td>
<td class="last-playback-time-cell"></td>
+ <td class="is-high-cell"></td>
<td class="total-score-cell"></td>
<td class="engagement-bar-cell">
<div class="engagement-bar"></div>
diff --git a/chromium/chrome/browser/resources/media/media_engagement.js b/chromium/chrome/browser/resources/media/media_engagement.js
index c93a301c940..268f7b1ca2c 100644
--- a/chromium/chrome/browser/resources/media/media_engagement.js
+++ b/chromium/chrome/browser/resources/media/media_engagement.js
@@ -33,8 +33,9 @@ function createRow(rowInfo) {
td[3].textContent = rowInfo.lastMediaPlaybackTime ?
new Date(rowInfo.lastMediaPlaybackTime).toISOString() :
'';
- td[4].textContent = rowInfo.totalScore ? rowInfo.totalScore.toFixed(2) : '0';
- td[5].getElementsByClassName('engagement-bar')[0].style.width =
+ td[4].textContent = rowInfo.isHigh ? 'Yes' : 'No';
+ td[5].textContent = rowInfo.totalScore ? rowInfo.totalScore.toFixed(2) : '0';
+ td[6].getElementsByClassName('engagement-bar')[0].style.width =
(rowInfo.totalScore * 50) + 'px';
return document.importNode(template.content, true);
}
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css b/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css
index ea21fbd46fc..7ae1c39ff5a 100644
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css
+++ b/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css
@@ -138,12 +138,12 @@ paper-item:hover {
}
paper-menu {
- -webkit-user-select: none;
color: rgba(0, 0, 0, 0.87);
overflow-x: hidden;
overflow-y: auto;
padding-bottom: 0;
padding-top: 4px;
+ user-select: none;
}
#search-input-container {
@@ -256,4 +256,3 @@ paper-menu {
white-space: nowrap;
width: 275px;
}
-
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html
index 23deb932789..5df138f4510 100644
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html
+++ b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html
@@ -17,6 +17,7 @@
<div>
<div id="route-time-controls" hidden="[[!routeStatus.canSeek]]">
<paper-slider
+ aria-valuetext$="[[getTimeSliderValueText_(displayedCurrentTime_)]]"
dir="ltr"
id="route-time-slider"
on-change="onSeekComplete_"
@@ -25,10 +26,12 @@
title="[[i18n('seekTitle')]]"
value="[[displayedCurrentTime_]]"></paper-slider>
<div id="timeline">
- <span id="current-time">
+ <span id="current-time"
+ aria-label$="[[getCurrentTimeLabel_(displayedCurrentTime_)]]">
[[getFormattedTime_(displayedCurrentTime_)]]
</span>
- <span id="duration">
+ <span id="duration"
+ aria-label$="[[getDurationLabel_(routeStatus.duration)]]">
[[getFormattedTime_(routeStatus.duration)]]
</span>
</div>
@@ -52,6 +55,7 @@
</span>
<span id="volume-holder">
<paper-slider
+ aria-valuetext$="[[getVolumeSliderValueText_(displayedVolume_)]]"
id="route-volume-slider"
hidden="[[!routeStatus.canSetVolume]]"
disabled="[[!routeStatus.canSetVolume]]"
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js
index 7dde72952df..2ca16a7c75b 100644
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js
+++ b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js
@@ -69,11 +69,29 @@ Polymer({
},
/**
+ * The timestamp for when the controller last submitted a seek request.
+ * @private {number}
+ */
+ lastSeekByUser_: {
+ type: Number,
+ value: 0,
+ },
+
+ /**
+ * The timestamp for when |routeStatus| was last updated.
+ * @private {number}
+ */
+ lastStatusUpdate_: {
+ type: Number,
+ value: 0,
+ },
+
+ /**
* The timestamp for when the controller last submitted a volume change
- * request for the volume slider being dragged.
+ * request.
* @private {boolean}
*/
- lastVolumeChangeByDragging_: {
+ lastVolumeChangeByUser_: {
type: Number,
value: 0,
},
@@ -128,9 +146,34 @@ Polymer({
* @private
*/
canIncrementCurrentTime_: function() {
- return this.routeStatus.playState === media_router.PlayState.PLAYING &&
+ return !this.isSeeking_ &&
+ this.routeStatus.playState === media_router.PlayState.PLAYING &&
(this.routeStatus.duration === 0 ||
- this.routeStatus.currentTime < this.routeStatus.duration);
+ this.displayedCurrentTime_ < this.routeStatus.duration);
+ },
+
+ /**
+ * Creates an accessibility label for the element showing the media's current
+ * time.
+ * @param {number} displayedCurrentTime
+ * @return {string}
+ * @private
+ */
+ getCurrentTimeLabel_: function(displayedCurrentTime) {
+ return `${
+ this.i18n('currentTimeLabel')
+ } ${this.getFormattedTime_(displayedCurrentTime)}`;
+ },
+
+ /**
+ * Creates an accessibility label for the element showing the media's
+ * duration.
+ * @param {number} duration
+ * @return {string}
+ * @private
+ */
+ getDurationLabel_: function(duration) {
+ return `${this.i18n('durationLabel')} ${this.getFormattedTime_(duration)}`;
},
/**
@@ -148,8 +191,9 @@ Polymer({
var hours = Math.floor(timeInSec / 3600);
var minutes = Math.floor(timeInSec / 60) % 60;
var seconds = Math.floor(timeInSec) % 60;
- return ('0' + hours).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' +
- ('0' + seconds).substr(-2);
+ // Show the hours only if it is nonzero.
+ return (hours ? ('0' + hours).substr(-2) + ':' : '') +
+ ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2);
},
/**
@@ -195,6 +239,28 @@ Polymer({
},
/**
+ * @return {string} Text representing the current position on the seek slider.
+ * @private
+ */
+ getTimeSliderValueText_: function(displayedCurrentTime) {
+ if (!this.routeStatus) {
+ return '';
+ }
+ return `${
+ this.getFormattedTime_(displayedCurrentTime)
+ } / ${this.getFormattedTime_(this.routeStatus.duration)}`;
+ },
+
+ /**
+ * @param {number} volume
+ * @return {string} The volume as a percentage.
+ * @private
+ */
+ getVolumeSliderValueText_: function(volume) {
+ return String(Math.round(volume * 100)) + '%';
+ },
+
+ /**
* Checks whether the media is still playing, and if so, sends a media status
* update incrementing the current time and schedules another call for a
* second later.
@@ -202,10 +268,13 @@ Polymer({
*/
maybeIncrementCurrentTime_: function() {
if (this.canIncrementCurrentTime_()) {
- this.routeStatus.currentTime++;
- this.displayedCurrentTime_ = this.routeStatus.currentTime;
+ var updatedCurrentTime = this.routeStatus.currentTime +
+ Math.floor((Date.now() - this.lastStatusUpdate_) / 1000);
+ this.displayedCurrentTime_ = this.routeStatus.duration === 0 ?
+ updatedCurrentTime :
+ Math.min(updatedCurrentTime, this.routeStatus.duration);
if (this.routeStatus.duration === 0 ||
- this.routeStatus.currentTime < this.routeStatus.duration) {
+ this.displayedCurrentTime_ < this.routeStatus.duration) {
this.timeIncrementsTimeoutId_ =
setTimeout(() => this.maybeIncrementCurrentTime_(), 1000);
}
@@ -243,11 +312,12 @@ Polymer({
* @private
*/
onRouteStatusChange_: function(newRouteStatus) {
- if (!this.isSeeking_) {
+ this.lastStatusUpdate_ = Date.now();
+ if (this.shouldAcceptCurrentTimeUpdates_()) {
this.displayedCurrentTime_ = newRouteStatus.currentTime;
}
- if (!this.isVolumeChanging_) {
- this.displayedVolume_ = newRouteStatus.volume;
+ if (this.shouldAcceptVolumeUpdates_()) {
+ this.displayedVolume_ = Math.round(newRouteStatus.volume * 100) / 100;
}
if (newRouteStatus.description !== '') {
this.displayedDescription_ = newRouteStatus.description;
@@ -257,13 +327,10 @@ Polymer({
media_router.browserApi.reportWebUIRouteControllerLoaded(
this.initialLoadTime_ - this.routeDetailsOpenTime);
}
+ this.stopIncrementingCurrentTime_();
if (this.canIncrementCurrentTime_()) {
- if (!this.timeIncrementsTimeoutId_) {
- this.timeIncrementsTimeoutId_ =
- setTimeout(() => this.maybeIncrementCurrentTime_(), 1000);
- }
- } else {
- this.stopIncrementingCurrentTime_();
+ this.timeIncrementsTimeoutId_ =
+ setTimeout(() => this.maybeIncrementCurrentTime_(), 1000);
}
},
@@ -289,9 +356,10 @@ Polymer({
*/
onSeekComplete_: function(e) {
this.stopIncrementingCurrentTime_();
- this.isSeeking_ = false;
this.displayedCurrentTime_ = e.target.value;
media_router.browserApi.seekCurrentMedia(this.displayedCurrentTime_);
+ this.isSeeking_ = false;
+ this.lastSeekByUser_ = Date.now();
},
/**
@@ -311,17 +379,10 @@ Polymer({
* @private
*/
onVolumeChangeComplete_: function(e) {
- this.volumeSliderValue_ = e.target.value;
- media_router.browserApi.setCurrentMediaVolume(this.volumeSliderValue_);
- if (this.isVolumeChanging_) {
- // Wait for 1 second before applying external volume updates, to prevent
- // notifications originating from this controller moving the slider knob
- // around.
- var that = this;
- setTimeout(function() {
- that.isVolumeChanging_ = false;
- }, 1000);
- }
+ this.displayedVolume_ = e.target.value;
+ media_router.browserApi.setCurrentMediaVolume(this.displayedVolume_);
+ this.isVolumeChanging_ = false;
+ this.lastVolumeChangeByUser_ = Date.now();
},
/**
@@ -333,14 +394,14 @@ Polymer({
/** @const */ var currentTime = Date.now();
// We limit the frequency of volume change requests during dragging to
// limit the number of Mojo calls to the component extension.
- if (currentTime - this.lastVolumeChangeByDragging_ < 300) {
+ if (currentTime - this.lastVolumeChangeByUser_ < 300) {
return;
}
- this.lastVolumeChangeByDragging_ = currentTime;
+ this.lastVolumeChangeByUser_ = currentTime;
this.isVolumeChanging_ = true;
var target = /** @type {{immediateValue: number}} */ (e.target);
- this.volumeSliderValue_ = target.immediateValue;
- media_router.browserApi.setCurrentMediaVolume(this.volumeSliderValue_);
+ this.displayedVolume_ = target.immediateValue;
+ media_router.browserApi.setCurrentMediaVolume(this.displayedVolume_);
},
/**
@@ -352,6 +413,31 @@ Polymer({
},
/**
+ * @return {boolean} Whether external current time updates should be reflected
+ * on the seek slider.
+ * @private
+ */
+ shouldAcceptCurrentTimeUpdates_: function() {
+ // Ignore external updates immediately after internal updates, because it's
+ // likely to just be internal updates coming back from the device, and could
+ // make the slider knob jump around.
+ return !this.isSeeking_ && Date.now() - this.lastSeekByUser_ > 1000;
+ },
+
+ /**
+ * @return {boolean} Whether external volume updates should be reflected on
+ * the volume slider.
+ * @private
+ */
+ shouldAcceptVolumeUpdates_: function() {
+ // Ignore external updates immediately after internal updates, because it's
+ // likely to just be internal updates coming back from the device, and could
+ // make the slider knob jump around.
+ return !this.isVolumeChanging_ &&
+ Date.now() - this.lastVolumeChangeByUser_ > 1000;
+ },
+
+ /**
* If it is currently incrementing the current time shown, then stops doing
* so.
* @private
diff --git a/chromium/chrome/browser/resources/memory_internals.html b/chromium/chrome/browser/resources/memory_internals.html
index f6d8665cc74..05ed42211aa 100644
--- a/chromium/chrome/browser/resources/memory_internals.html
+++ b/chromium/chrome/browser/resources/memory_internals.html
@@ -5,15 +5,21 @@
body {
font-family: sans-serif;
}
- .procrow {
- line-height: 250%;
+ th {
+ border-bottom: 1px solid black;
+ padding: 5px;
+ text-align: left;
}
- .button {
- background-color: black;
- color: white;
- cursor: pointer;
- font-weight: bold;
- padding: 10px;
+ td {
+ padding: 5px;
+ }
+ .message {
+ font-style: italic;
+ margin-bottom: 1em;
+ padding: 5px;
+ }
+ .refresh {
+ padding: 5px;
}
</style>
</head><body>
@@ -24,9 +30,9 @@
<h3>Experimental memory internals</h3>
-<div id="proclist">
-loading...
-</div>
+<div class="message" id="message"></div>
+
+<div id="proclist">loading...</div>
</body></html>
diff --git a/chromium/chrome/browser/resources/memory_internals.js b/chromium/chrome/browser/resources/memory_internals.js
index 03050e3d30c..ce94b5adf9e 100644
--- a/chromium/chrome/browser/resources/memory_internals.js
+++ b/chromium/chrome/browser/resources/memory_internals.js
@@ -12,25 +12,69 @@ function dumpProcess(pid) {
chrome.send('dumpProcess', [pid]);
}
-function returnProcessList(processList) {
- var proclist = $('proclist');
- proclist.innerText = '';
- for (let proc of processList) {
- /** @const */ var row = document.createElement('div');
- row.className = 'procrow';
-
- var description = document.createTextNode(proc[1] + ' ');
- row.appendChild(description);
-
- var button = document.createElement('button');
- button.innerText = '[dump]';
- button.className = 'button';
- let proc_id = proc[0];
- button.onclick = () => dumpProcess(proc_id);
- row.appendChild(button);
-
- proclist.appendChild(row);
+function reportProcess(pid) {
+ chrome.send('reportProcess', [pid]);
+}
+
+// celltype should either be "td" or "th". The contents of the |cols| will be
+// added as children of each table cell if they are non-null.
+function addListRow(table, celltype, cols) {
+ let tr = document.createElement('tr');
+ for (let col of cols) {
+ let cell = document.createElement(celltype);
+ if (col)
+ cell.appendChild(col);
+ tr.appendChild(cell);
+ }
+ table.appendChild(tr);
+}
+
+function returnProcessList(data) {
+ $('message').innerText = data['message'];
+
+ let proclist = $('proclist');
+ proclist.innerText = ''; // Clear existing contents.
+
+ let processes = data['processes'];
+ if (processes.length == 0)
+ return; // No processes to dump, don't make the table and refresh button.
+
+ // Add the refresh button.
+ let refreshDiv = document.createElement('div');
+ refreshDiv.className = 'refresh';
+ let refreshButton = document.createElement('button');
+ refreshButton.innerText = '\u21ba Refresh process list';
+ refreshButton.onclick = () => requestProcessList();
+ refreshDiv.appendChild(refreshButton);
+ proclist.appendChild(refreshDiv);
+
+ let table = document.createElement('table');
+
+ // Heading.
+ addListRow(table, 'th', [
+ null, null, document.createTextNode('Process ID'),
+ document.createTextNode('Name')
+ ]);
+
+ for (let proc of processes) {
+ let procId = proc[0];
+
+ let save_button = document.createElement('button');
+ save_button.innerText = '\u21e9 Save dump';
+ save_button.onclick = () => dumpProcess(procId);
+
+ let report_button = document.createElement('button');
+ report_button.innerText = '\uD83D\uDC1E Report';
+ report_button.onclick = () => reportProcess(procId);
+
+ let procIdText = document.createTextNode(procId.toString());
+ let description = document.createTextNode(proc[1]);
+
+ addListRow(
+ table, 'td', [save_button, report_button, procIdText, description]);
}
+
+ proclist.appendChild(table);
}
// Get data and have it displayed upon loading.
diff --git a/chromium/chrome/browser/resources/net_internals/browser_bridge.js b/chromium/chrome/browser/resources/net_internals/browser_bridge.js
index 112a006e710..74b6b7f5817 100644
--- a/chromium/chrome/browser/resources/net_internals/browser_bridge.js
+++ b/chromium/chrome/browser/resources/net_internals/browser_bridge.js
@@ -26,6 +26,7 @@ var BrowserBridge = (function() {
// List of observers for various bits of browser state.
this.connectionTestsObservers_ = [];
this.hstsObservers_ = [];
+ this.expectCTObservers_ = [];
this.constantsObservers_ = [];
this.crosONCFileParseObservers_ = [];
this.storeDebugLogsObservers_ = [];
@@ -172,8 +173,16 @@ var BrowserBridge = (function() {
[domain, sts_include_subdomains, pkp_include_subdomains, pins]);
},
- sendHSTSDelete: function(domain) {
- this.send('hstsDelete', [domain]);
+ sendDomainSecurityPolicyDelete: function(domain) {
+ this.send('domainSecurityPolicyDelete', [domain]);
+ },
+
+ sendExpectCTQuery: function(domain) {
+ this.send('expectCTQuery', [domain]);
+ },
+
+ sendExpectCTAdd: function(domain, report_uri, enforce) {
+ this.send('expectCTAdd', [domain, report_uri, enforce]);
},
sendGetSessionNetworkStats: function() {
@@ -318,6 +327,11 @@ var BrowserBridge = (function() {
this.hstsObservers_[i].onHSTSQueryResult(info);
},
+ receivedExpectCTResult: function(info) {
+ for (var i = 0; i < this.expectCTObservers_.length; i++)
+ this.expectCTObservers_[i].onExpectCTQueryResult(info);
+ },
+
receivedONCFileParse: function(error) {
for (var i = 0; i < this.crosONCFileParseObservers_.length; i++)
this.crosONCFileParseObservers_[i].onONCFileParse(error);
@@ -543,6 +557,16 @@ var BrowserBridge = (function() {
},
/**
+ * Adds a listener for the results of Expect-CT queries. The observer will
+ * be called back with:
+ *
+ * observer.onExpectCTQueryResult(result);
+ */
+ addExpectCTObserver: function(observer) {
+ this.expectCTObservers_.push(observer);
+ },
+
+ /**
* Adds a listener for ONC file parse status. The observer will be called
* back with:
*
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
new file mode 100644
index 00000000000..ec6f6a25aed
--- /dev/null
+++ b/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html
@@ -0,0 +1,96 @@
+<style>
+ #domain-security-policy-view-tab-content tt {
+ word-wrap: break-word;
+ }
+</style>
+
+<!-- HSTS/PKP/Expect-CT tab -->
+<div id=domain-security-policy-view-tab-content class=content-box>
+ <!-- This UI allows a user to query and update the browser's list of
+ HSTS/PKP/Expect-CT domains. -->
+
+ <h3>HSTS/PKP</h3>
+
+ <div class=deindent-header>
+ HSTS is HTTP Strict Transport Security: a way for sites to elect to
+ always use HTTPS. See <a href="https://www.chromium.org/hsts" target=_blank>
+ https://www.chromium.org/hsts</a>. PKP is Public Key Pinning: a way for sites
+ to "pin" themselves to particular public keys that must appear in their
+ certificate chain. See
+ <a href="https://tools.ietf.org/html/rfc7469" target=_blank>https://tools.ietf.org/html/rfc7469</a>.</div>
+
+ <h4>Add HSTS/PKP domain</h4>
+
+ <p>Input a domain name to add it to the HSTS/PKP set:</p>
+ <form id=hsts-view-add-form>
+ Domain: <input type=text id=hsts-view-add-input type="url"
+ placeholder="example.com"><br>
+ <label>Include subdomains for STS: <input type="checkbox" id=hsts-view-check-sts-input></label><br>
+ <label>Include subdomains for PKP: <input type="checkbox" id=hsts-view-check-pkp-input></label><br>
+ <label>Public key fingerprints: <input type=text id=hsts-view-add-pins style="width: 25em; max-width: 100%;"></label><br>
+ <p style="font-size: small; color: #767676; font-style: italic; margin-left: 2em; max-width: 40em; max-width: 100%;">(public key fingerprints are comma separated and consist of the hash function followed by a foreslash and the base64 encoded fingerprint, for example <tt>sha256/7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</tt>)</p>
+ <input type=submit value="Add" id=hsts-view-add-submit>
+ </form>
+
+ <h4>Query HSTS/PKP domain</h4>
+
+ <p>Input a domain name to query the current HSTS/PKP set:</p>
+ <form id=hsts-view-query-form>
+ Domain: <input type=text id=hsts-view-query-input type="url"
+ placeholder="example.com">
+ <input type=submit value="Query" id=hsts-view-query-submit>
+ </form>
+ <div style="margin-top: 1em; margin-left: 2em;" id=hsts-view-query-output></div>
+
+
+ <h3>Expect-CT</h3>
+
+ <div class=deindent-header>
+ Expect-CT allows sites to elect to always require valid Certificate
+ 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>
+
+ <h4>Add Expect-CT domain</h4>
+
+ <p>Input a domain name to add it to the Expect-CT set. Leave Enforce unchecked
+ to configure Expect-CT in report-only mode.</p>
+ <form id=expect-ct-view-add-form>
+ <div><label>Domain: <input type=text id=expect-ct-view-add-input type="url"
+ placeholder="example.com"></label></div>
+ <div><label>Report URI (optional):
+ <input type=text id=expect-ct-view-add-report-uri-input type="url"
+ placeholder="https://reporting.example.com/expect-ct"></label>
+ </div>
+ <div><label>Enforce:
+ <input type="checkbox" id=expect-ct-view-check-enforce-input></label>
+ </div>
+ <input type=submit value="Add" id=expect-ct-view-add-submit>
+ </form>
+
+ <h4>Query Expect-CT domain</h4>
+
+ <p>Input a domain name to query the current Expect-CT set:</p>
+ <form id=expect-ct-view-query-form>
+ <label>Domain: <input type=text id=expect-ct-view-query-input type="url"
+ placeholder="example.com"></label>
+ <input type=submit value="Query" id=expect-ct-view-query-submit>
+ </form>
+ <div style="margin-top: 1em; margin-left: 2em;"
+ id=expect-ct-view-query-output>
+ </div>
+
+ <h3>Delete domain security policies</h3>
+
+ <p>
+ Input a domain name to delete its dynamic domain security policies (HSTS,
+ HPKP, and Expect-CT). (<i>you cannot delete preloaded entries</i>):
+ </p>
+ <form id=domain-security-policy-view-delete-form>
+ <label>Domain: <input type=text id=domain-security-policy-view-delete-input
+ type="url"
+ placeholder="example.com"></label>
+ <input type=submit value="Delete"
+ id=domain-security-policy-view-delete-submit>
+ </form>
+
+</div>
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
new file mode 100644
index 00000000000..b345ad282bb
--- /dev/null
+++ b/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js
@@ -0,0 +1,315 @@
+// 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.
+
+/**
+ * This UI allows a user to query and update the browser's list of per-domain
+ * security policies. These policies include:
+ * - HSTS: HTTPS Strict Transport Security. A way for sites to elect to always
+ * use HTTPS. See http://dev.chromium.org/sts
+ * - PKP: Public Key Pinning. A way for sites to pin themselves to particular
+ * public key fingerprints that must appear in their certificate chains. See
+ * https://tools.ietf.org/html/rfc7469
+ * - Expect-CT. A way for sites to elect to always require valid Certificate
+ * Transparency information to be present. See
+ * https://tools.ietf.org/html/draft-ietf-httpbis-expect-ct-01
+ */
+
+var DomainSecurityPolicyView = (function() {
+ 'use strict';
+
+ // We inherit from DivView.
+ var superClass = DivView;
+
+ /**
+ * @constructor
+ */
+ function DomainSecurityPolicyView() {
+ assertFirstConstructorCall(DomainSecurityPolicyView);
+
+ // Call superclass's constructor.
+ superClass.call(this, DomainSecurityPolicyView.MAIN_BOX_ID);
+
+ this.deleteInput_ = $(DomainSecurityPolicyView.DELETE_INPUT_ID);
+ this.addStsPkpInput_ = $(DomainSecurityPolicyView.ADD_HSTS_PKP_INPUT_ID);
+ this.addStsCheck_ = $(DomainSecurityPolicyView.ADD_STS_CHECK_ID);
+ this.addPkpCheck_ = $(DomainSecurityPolicyView.ADD_PKP_CHECK_ID);
+ this.addPins_ = $(DomainSecurityPolicyView.ADD_PINS_ID);
+ this.queryStsPkpInput_ =
+ $(DomainSecurityPolicyView.QUERY_HSTS_PKP_INPUT_ID);
+ this.queryStsPkpOutputDiv_ =
+ $(DomainSecurityPolicyView.QUERY_HSTS_PKP_OUTPUT_DIV_ID);
+ this.addExpectCTInput_ = $(DomainSecurityPolicyView.ADD_EXPECT_CT_INPUT_ID);
+ this.addExpectCTReportUriInput_ =
+ $(DomainSecurityPolicyView.ADD_EXPECT_CT_REPORT_URI_INPUT_ID);
+ this.addExpectCTEnforceCheck_ =
+ $(DomainSecurityPolicyView.ADD_EXPECT_CT_ENFORCE_CHECK_ID);
+ this.queryExpectCTInput_ =
+ $(DomainSecurityPolicyView.QUERY_EXPECT_CT_INPUT_ID);
+ this.queryExpectCTOutputDiv_ =
+ $(DomainSecurityPolicyView.QUERY_EXPECT_CT_OUTPUT_DIV_ID);
+
+ var form = $(DomainSecurityPolicyView.DELETE_FORM_ID);
+ form.addEventListener('submit', this.onSubmitDelete_.bind(this), false);
+
+ form = $(DomainSecurityPolicyView.ADD_HSTS_PKP_FORM_ID);
+ form.addEventListener('submit', this.onSubmitHSTSPKPAdd_.bind(this), false);
+
+ form = $(DomainSecurityPolicyView.QUERY_HSTS_PKP_FORM_ID);
+ form.addEventListener(
+ 'submit', this.onSubmitHSTSPKPQuery_.bind(this), false);
+
+ var form = $(DomainSecurityPolicyView.ADD_EXPECT_CT_FORM_ID);
+ form.addEventListener(
+ 'submit', this.onSubmitExpectCTAdd_.bind(this), false);
+
+ form = $(DomainSecurityPolicyView.QUERY_EXPECT_CT_FORM_ID);
+ form.addEventListener(
+ 'submit', this.onSubmitExpectCTQuery_.bind(this), false);
+
+ g_browser.addHSTSObserver(this);
+ g_browser.addExpectCTObserver(this);
+ }
+
+ DomainSecurityPolicyView.TAB_ID = 'tab-handle-domain-security-policy';
+ DomainSecurityPolicyView.TAB_NAME = 'Domain Security Policy';
+ // This tab was originally limited to HSTS. Even though it now encompasses
+ // domain security policy more broadly, keep the hash as "#hsts" to preserve
+ // links/documentation that directs users to chrome://net-internals#hsts.
+ DomainSecurityPolicyView.TAB_HASH = '#hsts';
+
+ // IDs for special HTML elements in domain_security_policy_view.html
+ DomainSecurityPolicyView.MAIN_BOX_ID =
+ 'domain-security-policy-view-tab-content';
+ DomainSecurityPolicyView.DELETE_INPUT_ID =
+ 'domain-security-policy-view-delete-input';
+ DomainSecurityPolicyView.DELETE_FORM_ID =
+ 'domain-security-policy-view-delete-form';
+ DomainSecurityPolicyView.DELETE_SUBMIT_ID =
+ 'domain-security-policy-view-delete-submit';
+ // HSTS/PKP form elements
+ DomainSecurityPolicyView.ADD_HSTS_PKP_INPUT_ID = 'hsts-view-add-input';
+ DomainSecurityPolicyView.ADD_STS_CHECK_ID = 'hsts-view-check-sts-input';
+ DomainSecurityPolicyView.ADD_PKP_CHECK_ID = 'hsts-view-check-pkp-input';
+ DomainSecurityPolicyView.ADD_PINS_ID = 'hsts-view-add-pins';
+ DomainSecurityPolicyView.ADD_HSTS_PKP_FORM_ID = 'hsts-view-add-form';
+ DomainSecurityPolicyView.ADD_HSTS_PKP_SUBMIT_ID = 'hsts-view-add-submit';
+ DomainSecurityPolicyView.QUERY_HSTS_PKP_INPUT_ID = 'hsts-view-query-input';
+ DomainSecurityPolicyView.QUERY_HSTS_PKP_OUTPUT_DIV_ID =
+ 'hsts-view-query-output';
+ DomainSecurityPolicyView.QUERY_HSTS_PKP_FORM_ID = 'hsts-view-query-form';
+ DomainSecurityPolicyView.QUERY_HSTS_PKP_SUBMIT_ID = 'hsts-view-query-submit';
+ // Expect-CT form elements
+ DomainSecurityPolicyView.ADD_EXPECT_CT_INPUT_ID = 'expect-ct-view-add-input';
+ DomainSecurityPolicyView.ADD_EXPECT_CT_REPORT_URI_INPUT_ID =
+ 'expect-ct-view-add-report-uri-input';
+ DomainSecurityPolicyView.ADD_EXPECT_CT_ENFORCE_CHECK_ID =
+ 'expect-ct-view-check-enforce-input';
+ DomainSecurityPolicyView.ADD_EXPECT_CT_FORM_ID = 'expect-ct-view-add-form';
+ DomainSecurityPolicyView.ADD_EXPECT_CT_SUBMIT_ID =
+ 'expect-ct-view-add-submit';
+ DomainSecurityPolicyView.QUERY_EXPECT_CT_INPUT_ID =
+ 'expect-ct-view-query-input';
+ DomainSecurityPolicyView.QUERY_EXPECT_CT_FORM_ID =
+ 'expect-ct-view-query-form';
+ DomainSecurityPolicyView.QUERY_EXPECT_CT_SUBMIT_ID =
+ 'expect-ct-view-query-submit';
+ DomainSecurityPolicyView.QUERY_EXPECT_CT_OUTPUT_DIV_ID =
+ 'expect-ct-view-query-output';
+
+ cr.addSingletonGetter(DomainSecurityPolicyView);
+
+ DomainSecurityPolicyView.prototype = {
+ // Inherit the superclass's methods.
+ __proto__: superClass.prototype,
+
+ onSubmitHSTSPKPAdd_: function(event) {
+ g_browser.sendHSTSAdd(
+ this.addStsPkpInput_.value, this.addStsCheck_.checked,
+ this.addPkpCheck_.checked, this.addPins_.value);
+ g_browser.sendHSTSQuery(this.addStsPkpInput_.value);
+ this.queryStsPkpInput_.value = this.addStsPkpInput_.value;
+ this.addStsCheck_.checked = false;
+ this.addPkpCheck_.checked = false;
+ this.addStsPkpInput_.value = '';
+ this.addPins_.value = '';
+ event.preventDefault();
+ },
+
+ onSubmitDelete_: function(event) {
+ g_browser.sendDomainSecurityPolicyDelete(this.deleteInput_.value);
+ this.deleteInput_.value = '';
+ event.preventDefault();
+ },
+
+ onSubmitHSTSPKPQuery_: function(event) {
+ g_browser.sendHSTSQuery(this.queryStsPkpInput_.value);
+ event.preventDefault();
+ },
+
+ onHSTSQueryResult: function(result) {
+ if (result.error != undefined) {
+ this.queryStsPkpOutputDiv_.innerHTML = '';
+ var s = addNode(this.queryStsPkpOutputDiv_, 'span');
+ s.textContent = result.error;
+ s.style.color = '#e00';
+ yellowFade(this.queryStsPkpOutputDiv_);
+ return;
+ }
+
+ if (result.result == false) {
+ this.queryStsPkpOutputDiv_.innerHTML = '<b>Not found</b>';
+ yellowFade(this.queryStsPkpOutputDiv_);
+ return;
+ }
+
+ this.queryStsPkpOutputDiv_.innerHTML = '';
+
+ var s = addNode(this.queryStsPkpOutputDiv_, 'span');
+ s.innerHTML = '<b>Found:</b><br/>';
+
+ var keys = [
+ 'static_sts_domain',
+ 'static_upgrade_mode',
+ 'static_sts_include_subdomains',
+ 'static_sts_observed',
+ 'static_pkp_domain',
+ 'static_pkp_include_subdomains',
+ 'static_pkp_observed',
+ 'static_spki_hashes',
+ 'dynamic_sts_domain',
+ 'dynamic_upgrade_mode',
+ 'dynamic_sts_include_subdomains',
+ 'dynamic_sts_observed',
+ 'dynamic_sts_expiry',
+ 'dynamic_pkp_domain',
+ 'dynamic_pkp_include_subdomains',
+ 'dynamic_pkp_observed',
+ 'dynamic_pkp_expiry',
+ 'dynamic_spki_hashes',
+ ];
+
+ var kStaticHashKeys =
+ ['public_key_hashes', 'preloaded_spki_hashes', 'static_spki_hashes'];
+
+ var staticHashes = [];
+ for (var i = 0; i < kStaticHashKeys.length; ++i) {
+ var staticHashValue = result[kStaticHashKeys[i]];
+ if (staticHashValue != undefined && staticHashValue != '')
+ staticHashes.push(staticHashValue);
+ }
+
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ var value = result[key];
+ addTextNode(this.queryStsPkpOutputDiv_, ' ' + key + ': ');
+
+ // If there are no static_hashes, do not make it seem like there is a
+ // static PKP policy in place.
+ if (staticHashes.length == 0 && key.startsWith('static_pkp_')) {
+ addNode(this.queryStsPkpOutputDiv_, 'br');
+ continue;
+ }
+
+ if (key === 'static_spki_hashes') {
+ addNodeWithText(
+ this.queryStsPkpOutputDiv_, 'tt', staticHashes.join(','));
+ } else if (key.indexOf('_upgrade_mode') >= 0) {
+ addNodeWithText(
+ this.queryStsPkpOutputDiv_, 'tt', modeToString(value));
+ } else {
+ addNodeWithText(
+ this.queryStsPkpOutputDiv_, 'tt',
+ value == undefined ? '' : value);
+ }
+ addNode(this.queryStsPkpOutputDiv_, 'br');
+ }
+
+ yellowFade(this.queryStsPkpOutputDiv_);
+ },
+
+ onSubmitExpectCTAdd_: function(event) {
+ g_browser.sendExpectCTAdd(
+ this.addExpectCTInput_.value, this.addExpectCTReportUriInput_.value,
+ this.addExpectCTEnforceCheck_.checked);
+ g_browser.sendExpectCTQuery(this.addExpectCTInput_.value);
+ this.queryExpectCTInput_.value = this.addExpectCTInput_.value;
+ this.addExpectCTInput_.value = '';
+ this.addExpectCTReportUriInput_.value = '';
+ this.addExpectCTEnforceCheck_.checked = false;
+ event.preventDefault();
+ },
+
+ onSubmitExpectCTQuery_: function(event) {
+ g_browser.sendExpectCTQuery(this.queryExpectCTInput_.value);
+ event.preventDefault();
+ },
+
+ onExpectCTQueryResult: function(result) {
+ if (result.error != undefined) {
+ this.queryExpectCTOutputDiv_.innerHTML = '';
+ var s = addNode(this.queryExpectCTOutputDiv_, 'span');
+ s.textContent = result.error;
+ s.style.color = '#e00';
+ yellowFade(this.queryExpectCTOutputDiv_);
+ return;
+ }
+
+ if (result.result == false) {
+ this.queryExpectCTOutputDiv_.innerHTML = '<b>Not found</b>';
+ yellowFade(this.queryExpectCTOutputDiv_);
+ return;
+ }
+
+ this.queryExpectCTOutputDiv_.innerHTML = '';
+
+ var s = addNode(this.queryExpectCTOutputDiv_, 'span');
+ s.innerHTML = '<b>Found:</b><br/>';
+
+ var keys = [
+ 'dynamic_expect_ct_domain',
+ 'dynamic_expect_ct_observed',
+ 'dynamic_expect_ct_expiry',
+ 'dynamic_expect_ct_enforce',
+ 'dynamic_expect_ct_report_uri',
+ ];
+
+ for (var i in keys) {
+ var key = keys[i];
+ var value = result[key];
+ addTextNode(this.queryExpectCTOutputDiv_, ' ' + key + ': ');
+ addNodeWithText(
+ this.queryExpectCTOutputDiv_, 'tt',
+ value == undefined ? '' : value);
+ addNode(this.queryExpectCTOutputDiv_, 'br');
+ }
+
+ yellowFade(this.queryExpectCTOutputDiv_);
+ }
+
+ };
+
+ function modeToString(m) {
+ // These numbers must match those in
+ // TransportSecurityState::STSState::UpgradeMode.
+ if (m == 0) {
+ return 'FORCE_HTTPS';
+ } else if (m == 1) {
+ return 'DEFAULT';
+ } else {
+ return 'UNKNOWN';
+ }
+ }
+
+ function yellowFade(element) {
+ element.style.transitionProperty = 'background-color';
+ element.style.transitionDuration = '0';
+ element.style.backgroundColor = '#fffccf';
+ setTimeout(function() {
+ element.style.transitionDuration = '1000ms';
+ element.style.backgroundColor = '#fff';
+ }, 0);
+ }
+
+ return DomainSecurityPolicyView;
+})();
diff --git a/chromium/chrome/browser/resources/net_internals/hsts_view.html b/chromium/chrome/browser/resources/net_internals/hsts_view.html
deleted file mode 100644
index cc4f2e54fb6..00000000000
--- a/chromium/chrome/browser/resources/net_internals/hsts_view.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<style>
- #hsts-view-tab-content tt {
- word-wrap: break-word;
- }
-</style>
-
-<!-- HSTS tab -->
-<div id=hsts-view-tab-content class=content-box>
- <div class=deindent-header>
- HSTS is HTTP Strict Transport Security: a way for sites to elect to
- always use HTTPS. See <a href="https://www.chromium.org/hsts" target=_blank>
- https://www.chromium.org/hsts</a>.</div>
-
- <!-- This UI allows a user to query and update the browser's list of
- HSTS domains. -->
-
- <h4>Add domain</h4>
-
- <p>Input a domain name to add it to the HSTS set:</p>
- <form id=hsts-view-add-form>
- Domain: <input type=text id=hsts-view-add-input type="url"
- placeholder="example.com"><br>
- <label>Include subdomains for STS: <input type="checkbox" id=hsts-view-check-sts-input></label><br>
- <label>Include subdomains for PKP: <input type="checkbox" id=hsts-view-check-pkp-input></label><br>
- <label>Public key fingerprints: <input type=text id=hsts-view-add-pins style="width: 25em; max-width: 100%;"></label><br>
- <p style="font-size: small; color: #767676; font-style: italic; margin-left: 2em; max-width: 40em; max-width: 100%;">(public key fingerprints are comma separated and consist of the hash function followed by a foreslash and the base64 encoded fingerprint, for example <tt>sha256/7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</tt>)</p>
- <input type=submit value="Add" id=hsts-view-add-submit>
- </form>
-
- <h4>Delete domain</h4>
-
- <p>
- Input a domain name to delete it from the HSTS set
- (<i>you cannot delete preloaded entries</i>):
- </p>
- <form id=hsts-view-delete-form>
- Domain: <input type=text id=hsts-view-delete-input type="url"
- placeholder="example.com">
- <input type=submit value="Delete" id=hsts-view-delete-submit>
- </form>
-
- <h4>Query domain</h4>
-
- <p>Input a domain name to query the current HSTS set:</p>
- <form id=hsts-view-query-form>
- Domain: <input type=text id=hsts-view-query-input type="url"
- placeholder="example.com">
- <input type=submit value="Query" id=hsts-view-query-submit>
- </form>
- <div style="margin-top: 1em; margin-left: 2em;" id=hsts-view-query-output></div>
-</div>
diff --git a/chromium/chrome/browser/resources/net_internals/hsts_view.js b/chromium/chrome/browser/resources/net_internals/hsts_view.js
deleted file mode 100644
index be6a08db129..00000000000
--- a/chromium/chrome/browser/resources/net_internals/hsts_view.js
+++ /dev/null
@@ -1,199 +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.
-
-/**
- * HSTS is HTTPS Strict Transport Security: a way for sites to elect to always
- * use HTTPS. See http://dev.chromium.org/sts
- *
- * This UI allows a user to query and update the browser's list of HSTS domains.
- * It also allows users to query and update the browser's list of public key
- * pins.
- */
-
-var HSTSView = (function() {
- 'use strict';
-
- // We inherit from DivView.
- var superClass = DivView;
-
- /**
- * @constructor
- */
- function HSTSView() {
- assertFirstConstructorCall(HSTSView);
-
- // Call superclass's constructor.
- superClass.call(this, HSTSView.MAIN_BOX_ID);
-
- this.addInput_ = $(HSTSView.ADD_INPUT_ID);
- this.addStsCheck_ = $(HSTSView.ADD_STS_CHECK_ID);
- this.addPkpCheck_ = $(HSTSView.ADD_PKP_CHECK_ID);
- this.addPins_ = $(HSTSView.ADD_PINS_ID);
- this.deleteInput_ = $(HSTSView.DELETE_INPUT_ID);
- this.queryInput_ = $(HSTSView.QUERY_INPUT_ID);
- this.queryOutputDiv_ = $(HSTSView.QUERY_OUTPUT_DIV_ID);
-
- var form = $(HSTSView.ADD_FORM_ID);
- form.addEventListener('submit', this.onSubmitAdd_.bind(this), false);
-
- form = $(HSTSView.DELETE_FORM_ID);
- form.addEventListener('submit', this.onSubmitDelete_.bind(this), false);
-
- form = $(HSTSView.QUERY_FORM_ID);
- form.addEventListener('submit', this.onSubmitQuery_.bind(this), false);
-
- g_browser.addHSTSObserver(this);
- }
-
- HSTSView.TAB_ID = 'tab-handle-hsts';
- HSTSView.TAB_NAME = 'HSTS';
- HSTSView.TAB_HASH = '#hsts';
-
- // IDs for special HTML elements in hsts_view.html
- HSTSView.MAIN_BOX_ID = 'hsts-view-tab-content';
- HSTSView.ADD_INPUT_ID = 'hsts-view-add-input';
- HSTSView.ADD_STS_CHECK_ID = 'hsts-view-check-sts-input';
- HSTSView.ADD_PKP_CHECK_ID = 'hsts-view-check-pkp-input';
- HSTSView.ADD_PINS_ID = 'hsts-view-add-pins';
- HSTSView.ADD_FORM_ID = 'hsts-view-add-form';
- HSTSView.ADD_SUBMIT_ID = 'hsts-view-add-submit';
- HSTSView.DELETE_INPUT_ID = 'hsts-view-delete-input';
- HSTSView.DELETE_FORM_ID = 'hsts-view-delete-form';
- HSTSView.DELETE_SUBMIT_ID = 'hsts-view-delete-submit';
- HSTSView.QUERY_INPUT_ID = 'hsts-view-query-input';
- HSTSView.QUERY_OUTPUT_DIV_ID = 'hsts-view-query-output';
- HSTSView.QUERY_FORM_ID = 'hsts-view-query-form';
- HSTSView.QUERY_SUBMIT_ID = 'hsts-view-query-submit';
-
- cr.addSingletonGetter(HSTSView);
-
- HSTSView.prototype = {
- // Inherit the superclass's methods.
- __proto__: superClass.prototype,
-
- onSubmitAdd_: function(event) {
- g_browser.sendHSTSAdd(
- this.addInput_.value, this.addStsCheck_.checked,
- this.addPkpCheck_.checked, this.addPins_.value);
- g_browser.sendHSTSQuery(this.addInput_.value);
- this.queryInput_.value = this.addInput_.value;
- this.addStsCheck_.checked = false;
- this.addPkpCheck_.checked = false;
- this.addInput_.value = '';
- this.addPins_.value = '';
- event.preventDefault();
- },
-
- onSubmitDelete_: function(event) {
- g_browser.sendHSTSDelete(this.deleteInput_.value);
- this.deleteInput_.value = '';
- event.preventDefault();
- },
-
- onSubmitQuery_: function(event) {
- g_browser.sendHSTSQuery(this.queryInput_.value);
- event.preventDefault();
- },
-
- onHSTSQueryResult: function(result) {
- if (result.error != undefined) {
- this.queryOutputDiv_.innerHTML = '';
- var s = addNode(this.queryOutputDiv_, 'span');
- s.textContent = result.error;
- s.style.color = '#e00';
- yellowFade(this.queryOutputDiv_);
- return;
- }
-
- if (result.result == false) {
- this.queryOutputDiv_.innerHTML = '<b>Not found</b>';
- yellowFade(this.queryOutputDiv_);
- return;
- }
-
- this.queryOutputDiv_.innerHTML = '';
-
- var s = addNode(this.queryOutputDiv_, 'span');
- s.innerHTML = '<b>Found:</b><br/>';
-
- var keys = [
- 'static_sts_domain',
- 'static_upgrade_mode',
- 'static_sts_include_subdomains',
- 'static_sts_observed',
- 'static_pkp_domain',
- 'static_pkp_include_subdomains',
- 'static_pkp_observed',
- 'static_spki_hashes',
- 'dynamic_sts_domain',
- 'dynamic_upgrade_mode',
- 'dynamic_sts_include_subdomains',
- 'dynamic_sts_observed',
- 'dynamic_pkp_domain',
- 'dynamic_pkp_include_subdomains',
- 'dynamic_pkp_observed',
- 'dynamic_spki_hashes',
- ];
-
- var kStaticHashKeys =
- ['public_key_hashes', 'preloaded_spki_hashes', 'static_spki_hashes'];
-
- var staticHashes = [];
- for (var i = 0; i < kStaticHashKeys.length; ++i) {
- var staticHashValue = result[kStaticHashKeys[i]];
- if (staticHashValue != undefined && staticHashValue != '')
- staticHashes.push(staticHashValue);
- }
-
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- var value = result[key];
- addTextNode(this.queryOutputDiv_, ' ' + key + ': ');
-
- // If there are no static_hashes, do not make it seem like there is a
- // static PKP policy in place.
- if (staticHashes.length == 0 && key.startsWith('static_pkp_')) {
- addNode(this.queryOutputDiv_, 'br');
- continue;
- }
-
- if (key === 'static_spki_hashes') {
- addNodeWithText(this.queryOutputDiv_, 'tt', staticHashes.join(','));
- } else if (key.indexOf('_upgrade_mode') >= 0) {
- addNodeWithText(this.queryOutputDiv_, 'tt', modeToString(value));
- } else {
- addNodeWithText(
- this.queryOutputDiv_, 'tt', value == undefined ? '' : value);
- }
- addNode(this.queryOutputDiv_, 'br');
- }
-
- yellowFade(this.queryOutputDiv_);
- }
- };
-
- function modeToString(m) {
- // These numbers must match those in
- // TransportSecurityState::STSState::UpgradeMode.
- if (m == 0) {
- return 'STRICT';
- } else if (m == 1) {
- return 'OPPORTUNISTIC';
- } else {
- return 'UNKNOWN';
- }
- }
-
- function yellowFade(element) {
- element.style.transitionProperty = 'background-color';
- element.style.transitionDuration = '0';
- element.style.backgroundColor = '#fffccf';
- setTimeout(function() {
- element.style.transitionDuration = '1000ms';
- element.style.backgroundColor = '#fff';
- }, 0);
- }
-
- return HSTSView;
-})();
diff --git a/chromium/chrome/browser/resources/net_internals/import_view.html b/chromium/chrome/browser/resources/net_internals/import_view.html
index 1f91f12e6ed..9c5e704221c 100644
--- a/chromium/chrome/browser/resources/net_internals/import_view.html
+++ b/chromium/chrome/browser/resources/net_internals/import_view.html
@@ -35,7 +35,7 @@
<div id=import-view-tab-content class=content-box>
<div>
<div style='margin-bottom:20px'><b>TIP</b>: Drag-and-drop files into this window.</div>
- <input type=file value="Load log from file" id=import-view-load-log-file accept=".json"></input>
+ <input type=file value="Load log from file" id=import-view-load-log-file accept=".json">
<pre id=import-view-load-status-text></pre>
</div>
diff --git a/chromium/chrome/browser/resources/net_internals/index.html b/chromium/chrome/browser/resources/net_internals/index.html
index 37eb6973e50..3fc6f089d81 100644
--- a/chromium/chrome/browser/resources/net_internals/index.html
+++ b/chromium/chrome/browser/resources/net_internals/index.html
@@ -41,7 +41,7 @@ found in the LICENSE file.
<include src="modules_view.html">
<include src="import_view.html">
<include src="capture_view.html">
- <include src="hsts_view.html">
+ <include src="domain_security_policy_view.html">
<include src="events_view.html">
<include src="timeline_view.html">
<include src="sdch_view.html">
diff --git a/chromium/chrome/browser/resources/net_internals/index.js b/chromium/chrome/browser/resources/net_internals/index.js
index cb8c66bee4b..8fcb840e658 100644
--- a/chromium/chrome/browser/resources/net_internals/index.js
+++ b/chromium/chrome/browser/resources/net_internals/index.js
@@ -10,7 +10,7 @@
// <include src="import_view.js">
// <include src="capture_view.js">
// <include src="http_cache_view.js">
-// <include src="hsts_view.js">
+// <include src="domain_security_policy_view.js">
// <include src="browser_bridge.js">
// <include src="events_tracker.js">
// <include src="source_tracker.js">
diff --git a/chromium/chrome/browser/resources/net_internals/main.css b/chromium/chrome/browser/resources/net_internals/main.css
index 6beb42179b0..28800e299c7 100644
--- a/chromium/chrome/browser/resources/net_internals/main.css
+++ b/chromium/chrome/browser/resources/net_internals/main.css
@@ -19,10 +19,10 @@ ul {
/* This class is used to create the splitter widget in
* ResizbleVerticalSplitView. */
.vertical-splitter {
- -webkit-user-select: none;
border-left: 1px solid #afafaf;
cursor: ew-resize;
position: absolute;
+ user-select: none;
width: 10px;
}
diff --git a/chromium/chrome/browser/resources/net_internals/main.js b/chromium/chrome/browser/resources/net_internals/main.js
index 2ab766d6d75..3036cfb71b1 100644
--- a/chromium/chrome/browser/resources/net_internals/main.js
+++ b/chromium/chrome/browser/resources/net_internals/main.js
@@ -192,7 +192,7 @@ var MainView = (function() {
addTab(SdchView);
addTab(HttpCacheView);
addTab(ModulesView);
- addTab(HSTSView);
+ addTab(DomainSecurityPolicyView);
addTab(BandwidthView);
addTab(PrerenderView);
addTab(CrosView);
diff --git a/chromium/chrome/browser/resources/net_internals/quic_view.html b/chromium/chrome/browser/resources/net_internals/quic_view.html
index 887adb9eb27..bfbe3540272 100644
--- a/chromium/chrome/browser/resources/net_internals/quic_view.html
+++ b/chromium/chrome/browser/resources/net_internals/quic_view.html
@@ -39,7 +39,7 @@
</span>
</td>
</tr><tr>
- <td>Mark QUIC Broken When Network Blacholes</td>
+ <td>Mark QUIC Broken When Network Blackholes</td>
<td>
<span jscontent="!!$this.mark_quic_broken_when_network_blackholes">
</span>
diff --git a/chromium/chrome/browser/resources/ntp4/OWNERS b/chromium/chrome/browser/resources/ntp4/OWNERS
index f4065b6388d..690a9f1a025 100644
--- a/chromium/chrome/browser/resources/ntp4/OWNERS
+++ b/chromium/chrome/browser/resources/ntp4/OWNERS
@@ -1,6 +1,5 @@
estade@chromium.org
rbyers@chromium.org
-dbeam@chromium.org
# TEAM: ntp-dev@chromium.org
# COMPONENT: UI>Browser>NewTabPage
diff --git a/chromium/chrome/browser/resources/ntp4/apps_page.css b/chromium/chrome/browser/resources/ntp4/apps_page.css
index 287304d5699..c64ad4a8740 100644
--- a/chromium/chrome/browser/resources/ntp4/apps_page.css
+++ b/chromium/chrome/browser/resources/ntp4/apps_page.css
@@ -65,6 +65,17 @@
position: absolute;
}
+.app-icon-div .color-stripe {
+ border-bottom-left-radius: 5px 5px;
+ border-bottom-right-radius: 5px 5px;
+ bottom: 0;
+ height: 3px;
+ opacity: 1.0;
+ position: absolute;
+ width: 100%;
+ z-index: 100;
+}
+
.app-context-menu > button:first-child {
font-weight: bold;
}
diff --git a/chromium/chrome/browser/resources/ntp4/apps_page.js b/chromium/chrome/browser/resources/ntp4/apps_page.js
index b7679ce9ef3..7242b5b27a6 100644
--- a/chromium/chrome/browser/resources/ntp4/apps_page.js
+++ b/chromium/chrome/browser/resources/ntp4/apps_page.js
@@ -260,7 +260,12 @@ cr.define('ntp', function() {
this.className = 'app focusable';
- this.appContents_ = $('app-icon-template').cloneNode(true);
+ if (!this.appData_.icon_big_exists && this.appData_.icon_small_exists)
+ this.useSmallIcon_ = true;
+
+ this.appContents_ = (this.useSmallIcon_ ? $('app-small-icon-template') :
+ $('app-large-icon-template'))
+ .cloneNode(true);
this.appContents_.id = '';
this.appendChild(this.appContents_);
@@ -269,8 +274,16 @@ cr.define('ntp', function() {
this.appImg_ = this.appImgContainer_.querySelector('img');
this.setIcon();
- this.addLaunchClickTarget_(this.appImgContainer_);
- this.appImgContainer_.title = this.appData_.full_name;
+ if (this.useSmallIcon_) {
+ this.imgDiv_ =
+ /** @type {HTMLElement} */ (this.querySelector('.app-icon-div'));
+ this.addLaunchClickTarget_(this.imgDiv_);
+ this.imgDiv_.title = this.appData_.full_name;
+ chrome.send('getAppIconDominantColor', [this.id]);
+ } else {
+ this.addLaunchClickTarget_(this.appImgContainer_);
+ this.appImgContainer_.title = this.appData_.full_name;
+ }
// The app's full name is shown in the tooltip, whereas the short name
// is used for the label.
@@ -301,6 +314,14 @@ cr.define('ntp', function() {
},
/**
+ * Sets the color of the favicon dominant color bar.
+ * @param {string} color The css-parsable value for the color.
+ */
+ set stripeColor(color) {
+ this.querySelector('.color-stripe').style.backgroundColor = color;
+ },
+
+ /**
* Removes the app tile from the page. Should be called after the app has
* been uninstalled.
*
@@ -322,7 +343,8 @@ cr.define('ntp', function() {
* to load icons until we have to).
*/
setIcon: function() {
- var src = this.appData_.icon;
+ var src = this.useSmallIcon_ ? this.appData_.icon_small :
+ this.appData_.icon_big;
if (!this.appData_.enabled ||
(!this.appData_.offlineEnabled && !navigator.onLine)) {
src += '?grayscale=true';
@@ -356,7 +378,20 @@ cr.define('ntp', function() {
setBounds: function(size, x, y) {
var imgSize = size * APP_IMG_SIZE_FRACTION;
this.appImgContainer_.style.width = this.appImgContainer_.style.height =
- toCssPx(imgSize);
+ toCssPx(this.useSmallIcon_ ? 16 : imgSize);
+ if (this.useSmallIcon_) {
+ // 3/4 is the ratio of 96px to 128px (the used height and full height
+ // of icons in apps).
+ var iconSize = imgSize * 3 / 4;
+ // The -2 is for the div border to improve the visual alignment for the
+ // icon div.
+ this.imgDiv_.style.width = this.imgDiv_.style.height =
+ toCssPx(iconSize - 2);
+ // Margins set to get the icon placement right and the text to line up.
+ this.imgDiv_.style.marginTop = this.imgDiv_.style.marginBottom =
+ toCssPx((imgSize - iconSize) / 2);
+ }
+
this.style.width = this.style.height = toCssPx(size);
this.style.left = toCssPx(x);
this.style.right = toCssPx(x);
diff --git a/chromium/chrome/browser/resources/ntp4/new_tab.css b/chromium/chrome/browser/resources/ntp4/new_tab.css
index 26dc2828a76..4aa0a18dbe7 100644
--- a/chromium/chrome/browser/resources/ntp4/new_tab.css
+++ b/chromium/chrome/browser/resources/ntp4/new_tab.css
@@ -13,10 +13,10 @@ body {
/* Don't highlight links when they're tapped. Safari has bugs here that
show up as flicker when dragging in some situations */
-webkit-tap-highlight-color: transparent;
- /* Don't allow selecting text - can occur when dragging */
- -webkit-user-select: none;
background-size: auto 100%;
margin: 0;
+ /* Don't allow selecting text - can occur when dragging */
+ user-select: none;
}
/* [hidden] does display:none, but its priority is too low in some cases. */
diff --git a/chromium/chrome/browser/resources/ntp4/new_tab.html b/chromium/chrome/browser/resources/ntp4/new_tab.html
index 1a64328004f..bc44bba405b 100644
--- a/chromium/chrome/browser/resources/ntp4/new_tab.html
+++ b/chromium/chrome/browser/resources/ntp4/new_tab.html
@@ -142,14 +142,25 @@ document.write('<link id="themecss" rel="stylesheet" ' +
</div>
</div>
-<!-- App Contents -->
-<div id="app-icon-template" class="app-contents">
+<!-- App Contents w/ Large Icon -->
+<div id="app-large-icon-template" class="app-contents">
<div class="app-img-container" aria-hidden="true">
<img class="invisible" alt="">
</div>
<span class="title"></span>
</div>
+<!-- App Contents w/ Small Icon -->
+<div id="app-small-icon-template" class="app-contents">
+ <div class="app-icon-div" aria-hidden="true">
+ <div class="app-img-container">
+ <img class="invisible" alt="">
+ </div>
+ <div class="color-stripe"></div>
+ </div>
+ <span class="title"></span>
+</div>
+
</div>
<!-- This is used to measure text in the current locale. It is not visible. -->
diff --git a/chromium/chrome/browser/resources/ntp4/new_tab.js b/chromium/chrome/browser/resources/ntp4/new_tab.js
index 8fdb477f1ff..cecee13c5a3 100644
--- a/chromium/chrome/browser/resources/ntp4/new_tab.js
+++ b/chromium/chrome/browser/resources/ntp4/new_tab.js
@@ -180,7 +180,6 @@ cr.define('ntp', function() {
/**
* Fired as each section of pages becomes ready.
- * @param {Event} e Each page's synthetic DOM event.
*/
document.addEventListener('sectionready', function(e) {
if (--sectionsToWaitFor <= 0) {
@@ -264,6 +263,19 @@ cr.define('ntp', function() {
}
/**
+ * Set the dominant color for a node. This will be called in response to
+ * getFaviconDominantColor. The node represented by |id| better have a setter
+ * for stripeColor.
+ * @param {string} id The ID of a node.
+ * @param {string} color The color represented as a CSS string.
+ */
+ function setFaviconDominantColor(id, color) {
+ var node = $(id);
+ if (node)
+ node.stripeColor = color;
+ }
+
+ /**
* Updates the text displayed in the login container. If there is no text then
* the login container is hidden.
* @param {string} loginHeader The first line of text.
@@ -434,6 +446,7 @@ cr.define('ntp', function() {
saveAppPageName: saveAppPageName,
setAppToBeHighlighted: setAppToBeHighlighted,
setBookmarkBarAttached: setBookmarkBarAttached,
+ setFaviconDominantColor: setFaviconDominantColor,
themeChanged: themeChanged,
updateLogin: updateLogin
};
diff --git a/chromium/chrome/browser/resources/ntp4/page_list_view.js b/chromium/chrome/browser/resources/ntp4/page_list_view.js
index ceb69d59f98..470dbab409f 100644
--- a/chromium/chrome/browser/resources/ntp4/page_list_view.js
+++ b/chromium/chrome/browser/resources/ntp4/page_list_view.js
@@ -19,7 +19,10 @@
* full_name: string,
* full_name_direction: string,
* homepageUrl: string,
- * icon: string,
+ * icon_big: string,
+ * icon_big_exists: boolean,
+ * icon_small: string,
+ * icon_small_exists: boolean,
* id: string,
* is_component: boolean,
* is_webstore: boolean,
diff --git a/chromium/chrome/browser/resources/offline_pages/offline_internals.html b/chromium/chrome/browser/resources/offline_pages/offline_internals.html
index 7220e63acbb..6aae5794445 100644
--- a/chromium/chrome/browser/resources/offline_pages/offline_internals.html
+++ b/chromium/chrome/browser/resources/offline_pages/offline_internals.html
@@ -56,10 +56,21 @@
<th>Namespace</th>
<th>Size (Kb)</th>
<th>Expired</th>
+ <th>Request Origin</th>
</tr>
</thead>
<tbody id="stored-pages"> </tbody>
</table>
+ <template id="stored-pages-table-row">
+ <tr>
+ <td><input type="checkbox" name="stored"></td>
+ <td><a></a></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ </template>
<div id="page-actions-info" class="dump"></div>
<h2>Request Queue</h2>
@@ -74,10 +85,20 @@
<th>URL</th>
<th>Created Timestamp</th>
<th>Status</th>
+ <th>Request Origin</th>
</tr>
</thead>
<tbody id="request-queue"> </tbody>
</table>
+ <template id="request-queue-table-row">
+ <tr>
+ <td><input type="checkbox" name="requests"></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ </template>
<div id="request-queue-actions-info" class="dump"></div>
<input id="url" type="url"
placeholder="http://www.url1.com, http://www.url2.com, ...">
diff --git a/chromium/chrome/browser/resources/offline_pages/offline_internals.js b/chromium/chrome/browser/resources/offline_pages/offline_internals.js
index 5acddb52f5e..dc5894047d6 100644
--- a/chromium/chrome/browser/resources/offline_pages/offline_internals.js
+++ b/chromium/chrome/browser/resources/offline_pages/offline_internals.js
@@ -33,37 +33,22 @@ cr.define('offlineInternals', function() {
var storedPagesTable = $('stored-pages');
storedPagesTable.textContent = '';
+ var template = $('stored-pages-table-row');
+ var td = template.content.querySelectorAll('td');
for (var i = 0; i < pages.length; i++) {
- var row = document.createElement('tr');
-
- var checkboxCell = document.createElement('td');
- var checkbox = document.createElement('input');
- checkbox.setAttribute('type', 'checkbox');
- checkbox.setAttribute('name', 'stored');
+ var checkbox = td[0].querySelector('input');
checkbox.setAttribute('value', pages[i].id);
- checkboxCell.appendChild(checkbox);
- row.appendChild(checkboxCell);
-
- var cell = document.createElement('td');
- var link = document.createElement('a');
+ var link = td[1].querySelector('a');
link.setAttribute('href', pages[i].onlineUrl);
link.textContent = pages[i].onlineUrl;
- cell.appendChild(link);
- row.appendChild(cell);
-
- cell = document.createElement('td');
- cell.textContent = pages[i].namespace;
- row.appendChild(cell);
-
- cell = document.createElement('td');
- cell.textContent = Math.round(pages[i].size / 1024);
- row.appendChild(cell);
- cell = document.createElement('td');
- cell.textContent = pages[i].isExpired;
- row.appendChild(cell);
+ td[2].textContent = pages[i].namespace;
+ td[3].textContent = Math.round(pages[i].size / 1024);
+ td[4].textContent = pages[i].isExpired;
+ td[5].textContent = pages[i].requestOrigin;
+ var row = document.importNode(template.content, true);
storedPagesTable.appendChild(row);
}
offlinePages = pages;
@@ -78,30 +63,18 @@ cr.define('offlineInternals', function() {
var requestQueueTable = $('request-queue');
requestQueueTable.textContent = '';
+ var template = $('request-queue-table-row');
+ var td = template.content.querySelectorAll('td');
for (var i = 0; i < requests.length; i++) {
- var row = document.createElement('tr');
-
- var checkboxCell = document.createElement('td');
- var checkbox = document.createElement('input');
- checkbox.setAttribute('type', 'checkbox');
- checkbox.setAttribute('name', 'requests');
+ var checkbox = td[0].querySelector('input');
checkbox.setAttribute('value', requests[i].id);
- checkboxCell.appendChild(checkbox);
- row.appendChild(checkboxCell);
-
- var cell = document.createElement('td');
- cell.textContent = requests[i].onlineUrl;
- row.appendChild(cell);
-
- cell = document.createElement('td');
- cell.textContent = new Date(requests[i].creationTime);
- row.appendChild(cell);
-
- cell = document.createElement('td');
- cell.textContent = requests[i].status;
- row.appendChild(cell);
+ td[1].textContent = requests[i].onlineUrl;
+ td[2].textContent = new Date(requests[i].creationTime);
+ td[3].textContent = requests[i].status;
+ td[4].textContent = requests[i].requestOrigin;
+ var row = document.importNode(template.content, true);
requestQueueTable.appendChild(row);
}
savePageRequests = requests;
diff --git a/chromium/chrome/browser/resources/offline_pages/offline_internals_browser_proxy.js b/chromium/chrome/browser/resources/offline_pages/offline_internals_browser_proxy.js
index 81d58c117b8..14777fc803d 100644
--- a/chromium/chrome/browser/resources/offline_pages/offline_internals_browser_proxy.js
+++ b/chromium/chrome/browser/resources/offline_pages/offline_internals_browser_proxy.js
@@ -12,7 +12,8 @@
* filePath: string,
* lastAccessTime: number,
* accessCount: number,
- * isExpired: string
+ * isExpired: string,
+ * requestOrigin: string
* }}
*/
var OfflinePage;
@@ -24,7 +25,8 @@ var OfflinePage;
* creationTime: number,
* id: string,
* namespace: string,
- * lastAttempt: number
+ * lastAttempt: number,
+ * requestOrigin: string
* }}
*/
var SavePageRequest;
diff --git a/chromium/chrome/browser/resources/options/2x/yellow_gear.png b/chromium/chrome/browser/resources/options/2x/yellow_gear.png
deleted file mode 100644
index 087c8a329a6..00000000000
--- a/chromium/chrome/browser/resources/options/2x/yellow_gear.png
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/options/OWNERS b/chromium/chrome/browser/resources/options/OWNERS
deleted file mode 100644
index b6bf7d0c8b9..00000000000
--- a/chromium/chrome/browser/resources/options/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# This UI is deprecated. See chrome/browser/resources/settings/ instead.
-set noparent
-
-dbeam@chromium.org
-stevenjb@chromium.org
diff --git a/chromium/chrome/browser/resources/options/alert_overlay.css b/chromium/chrome/browser/resources/options/alert_overlay.css
deleted file mode 100644
index b2d9960a9a1..00000000000
--- a/chromium/chrome/browser/resources/options/alert_overlay.css
+++ /dev/null
@@ -1,7 +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. */
-
-#alertOverlayMessage {
- width: 400px;
-}
diff --git a/chromium/chrome/browser/resources/options/alert_overlay.html b/chromium/chrome/browser/resources/options/alert_overlay.html
deleted file mode 100644
index 2c96ff14f79..00000000000
--- a/chromium/chrome/browser/resources/options/alert_overlay.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<div id="alertOverlay" class="page" hidden>
- <div class="close-button"></div>
- <h1 id="alertOverlayTitle"></h1>
- <div class="content-area">
- <div id="alertOverlayMessage"></div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="alertOverlayCancel" type="reset"></button>
- <button id="alertOverlayOk" class="default-button" type="submit"></button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/alert_overlay.js b/chromium/chrome/browser/resources/options/alert_overlay.js
deleted file mode 100644
index 2206517d080..00000000000
--- a/chromium/chrome/browser/resources/options/alert_overlay.js
+++ /dev/null
@@ -1,147 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * AlertOverlay class
- * Encapsulated handling of a generic alert.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function AlertOverlay() {
- Page.call(this, 'alertOverlay', '', 'alertOverlay');
- }
-
- cr.addSingletonGetter(AlertOverlay);
-
- AlertOverlay.prototype = {
- // Inherit AlertOverlay from Page.
- __proto__: Page.prototype,
-
- /**
- * Whether the page can be shown. Used to make sure the page is only
- * shown via AlertOverlay.Show(), and not via the address bar.
- * @private
- */
- canShow_: false,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- // AlertOverlay is special in that it is not tied to one page or overlay.
- this.alwaysOnTop = true;
-
- var self = this;
- $('alertOverlayOk').onclick = function(event) {
- self.handleOK_();
- };
-
- $('alertOverlayCancel').onclick = function(event) {
- self.handleCancel_();
- };
- },
-
- /**
- * Handle the 'ok' button. Clear the overlay and call the ok callback if
- * available.
- * @private
- */
- handleOK_: function() {
- PageManager.closeOverlay();
- if (this.okCallback != undefined) {
- this.okCallback.call();
- }
- },
-
- /**
- * Handle the 'cancel' button. Clear the overlay and call the cancel
- * callback if available.
- * @private
- */
- handleCancel_: function() {
- PageManager.closeOverlay();
- if (this.cancelCallback != undefined) {
- this.cancelCallback.call();
- }
- },
-
- /**
- * The page is getting hidden. Don't let it be shown again.
- * @override
- */
- willHidePage: function() {
- this.canShow_ = false;
- },
-
- /** @override */
- canShowPage: function() {
- return this.canShow_;
- },
- };
-
- /**
- * Show an alert overlay with the given message, button titles, and
- * callbacks.
- * @param {string} title The alert title to display to the user.
- * @param {string} message The alert message to display to the user.
- * @param {string} okTitle The title of the OK button. If undefined or empty,
- * no button is shown.
- * @param {string} cancelTitle The title of the cancel button. If undefined or
- * empty, no button is shown.
- * @param {function()} okCallback A function to be called when the user
- * presses the ok button. The alert window will be closed automatically.
- * Can be undefined.
- * @param {function()} cancelCallback A function to be called when the user
- * presses the cancel button. The alert window will be closed
- * automatically. Can be undefined.
- */
- AlertOverlay.show = function(
- title, message, okTitle, cancelTitle, okCallback, cancelCallback) {
- if (title != undefined) {
- $('alertOverlayTitle').textContent = title;
- $('alertOverlayTitle').style.display = 'block';
- } else {
- $('alertOverlayTitle').style.display = 'none';
- }
-
- if (message != undefined) {
- $('alertOverlayMessage').textContent = message;
- $('alertOverlayMessage').style.display = 'block';
- } else {
- $('alertOverlayMessage').style.display = 'none';
- }
-
- if (okTitle != undefined && okTitle != '') {
- $('alertOverlayOk').textContent = okTitle;
- $('alertOverlayOk').style.display = 'block';
- } else {
- $('alertOverlayOk').style.display = 'none';
- }
-
- if (cancelTitle != undefined && cancelTitle != '') {
- $('alertOverlayCancel').textContent = cancelTitle;
- $('alertOverlayCancel').style.display = 'inline';
- } else {
- $('alertOverlayCancel').style.display = 'none';
- }
-
- var alertOverlay = AlertOverlay.getInstance();
- alertOverlay.okCallback = okCallback;
- alertOverlay.cancelCallback = cancelCallback;
- alertOverlay.canShow_ = true;
-
- // Intentionally don't show the URL in the location bar as we don't want
- // people trying to navigate here by hand.
- PageManager.showPageByName('alertOverlay', false);
- };
-
- // Export
- return {
- AlertOverlay: AlertOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.html b/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.html
deleted file mode 100644
index 980d9ba82a0..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.html
+++ /dev/null
@@ -1,42 +0,0 @@
-<div id="autofill-edit-address-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1 id="autofill-address-title"></h1>
- <div class="content-area">
- <div id="autofill-edit-address-fields">
- </div>
-
- <div class="settings-row">
- <label>
- <div>$i18n{autofillCountryLabel}</div>
- <select class="country" field="country"></select>
- </label>
- </div>
-
- <div class="input-group settings-row">
- <div>
- <label>
- <div>$i18n{autofillPhoneLabel}</div>
- <input class="short" field="phone"></input>
- </label>
- </div>
-
- <div>
- <label>
- <div>$i18n{autofillEmailLabel}</div>
- <input class="short" field="email"></input>
- </label>
- </div>
- </div>
-
- </div>
-
- <div class="action-area button-strip">
- <button id="autofill-edit-address-cancel-button" type="reset">
- $i18n{cancel}
- </button>
- <button id="autofill-edit-address-apply-button" type="submit"
- class="default-button" disabled>
- $i18n{ok}
- </button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.js b/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.js
deleted file mode 100644
index c9e5440f7fb..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.js
+++ /dev/null
@@ -1,350 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /**
- * AutofillEditAddressOverlay class
- * Encapsulated handling of the 'Add Page' overlay page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function AutofillEditAddressOverlay() {
- Page.call(this, 'autofillEditAddress',
- loadTimeData.getString('autofillEditAddressTitle'),
- 'autofill-edit-address-overlay');
- }
-
- cr.addSingletonGetter(AutofillEditAddressOverlay);
-
- AutofillEditAddressOverlay.prototype = {
- __proto__: Page.prototype,
-
- /**
- * The GUID of the loaded address.
- * @type {string}
- */
- guid_: '',
-
- /**
- * The BCP 47 language code for the layout of input fields.
- * @type {string}
- */
- languageCode_: '',
-
- /**
- * The saved field values for the address. For example, if the user changes
- * from United States to Switzerland, then the State field will be hidden
- * and its value will be stored here. If the user changes back to United
- * States, then the State field will be restored to its previous value, as
- * stored in this object.
- * @type {Object}
- */
- savedFieldValues_: {},
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
- $('autofill-edit-address-cancel-button').onclick = function(event) {
- self.dismissOverlay_();
- };
-
- // TODO(jhawkins): Investigate other possible solutions.
- $('autofill-edit-address-apply-button').onclick = function(event) {
- // Blur active element to ensure that pending changes are committed.
- if (document.activeElement)
- document.activeElement.blur();
- self.saveAddress_();
- self.dismissOverlay_();
- };
-
- this.guid_ = '';
- this.populateCountryList_();
- this.rebuildInputFields_(/** @type {Array<Array<Object>>} */(
- loadTimeData.getValue('autofillDefaultCountryComponents')));
- this.languageCode_ =
- loadTimeData.getString('autofillDefaultCountryLanguageCode');
- this.connectInputEvents_();
- this.setInputFields_({});
- this.getCountrySwitcher_().onchange = function(event) {
- self.countryChanged_();
- };
- },
-
- /**
- * Specifically catch the situations in which the overlay is cancelled
- * externally (e.g. by pressing <Esc>), so that the input fields and
- * GUID can be properly cleared.
- * @override
- */
- handleCancel: function() {
- this.dismissOverlay_();
- },
-
- /**
- * Clears any uncommitted input, resets the stored GUID and dismisses the
- * overlay.
- * @private
- */
- dismissOverlay_: function() {
- this.setInputFields_({});
- this.inputFieldChanged_();
- this.guid_ = '';
- this.languageCode_ = '';
- this.savedInputFields_ = {};
- PageManager.closeOverlay();
- },
-
- /**
- * @return {Element} The element used to switch countries.
- * @private
- */
- getCountrySwitcher_: function() {
- return this.pageDiv.querySelector('[field=country]');
- },
-
- /**
- * Returns all text input elements.
- * @return {!NodeList} The text input elements.
- * @private
- */
- getTextFields_: function() {
- return this.pageDiv.querySelectorAll('textarea[field], input[field]');
- },
-
- /**
- * Creates a map from type => value for all text fields.
- * @return {Object} The mapping from field names to values.
- * @private
- */
- getInputFields_: function() {
- var address = {country: this.getCountrySwitcher_().value};
-
- var fields = this.getTextFields_();
- for (var i = 0; i < fields.length; i++) {
- address[fields[i].getAttribute('field')] = fields[i].value;
- }
-
- return address;
- },
-
- /**
- * Sets the value of each input field according to |address|.
- * @param {Object} address The object with values to use.
- * @private
- */
- setInputFields_: function(address) {
- this.getCountrySwitcher_().value = address.country || '';
-
- var fields = this.getTextFields_();
- for (var i = 0; i < fields.length; i++) {
- fields[i].value = address[fields[i].getAttribute('field')] || '';
- }
- },
-
- /**
- * Aggregates the values in the input fields into an array and sends the
- * array to the Autofill handler.
- * @private
- */
- saveAddress_: function() {
- var inputFields = this.getInputFields_();
- var address = [
- this.guid_,
- inputFields['fullName'] || [],
- inputFields['companyName'] || '',
- inputFields['addrLines'] || '',
- inputFields['dependentLocality'] || '',
- inputFields['city'] || '',
- inputFields['state'] || '',
- inputFields['postalCode'] || '',
- inputFields['sortingCode'] || '',
- inputFields['country'] || loadTimeData.getString('defaultCountryCode'),
- inputFields['phone'] || [],
- inputFields['email'] || [],
- this.languageCode_,
- ];
- chrome.send('setAddress', address);
-
- // If the GUID is empty, this form is being used to add a new address,
- // rather than edit an existing one.
- if (!this.guid_.length) {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_AutofillAddressAdded']);
- }
- },
-
- /**
- * Connects each input field to the inputFieldChanged_() method that enables
- * or disables the 'Ok' button based on whether all the fields are empty or
- * not.
- * @private
- */
- connectInputEvents_: function() {
- var fields = this.getTextFields_();
- for (var i = 0; i < fields.length; i++) {
- fields[i].oninput = this.inputFieldChanged_.bind(this);
- }
- },
-
- /**
- * Disables the 'Ok' button if all of the fields are empty.
- * @private
- */
- inputFieldChanged_: function() {
- var disabled = !this.getCountrySwitcher_().value;
- if (disabled) {
- var fields = this.getTextFields_();
- for (var i = 0; i < fields.length; i++) {
- if (fields[i].value) {
- disabled = false;
- break;
- }
- }
- }
-
- $('autofill-edit-address-apply-button').disabled = disabled;
- },
-
- /**
- * Updates the address fields appropriately for the selected country.
- * @private
- */
- countryChanged_: function() {
- var countryCode = this.getCountrySwitcher_().value;
- if (countryCode)
- chrome.send('loadAddressEditorComponents', [countryCode]);
- else
- this.inputFieldChanged_();
- },
-
- /**
- * Populates the country <select> list.
- * @private
- */
- populateCountryList_: function() {
- var countryList = loadTimeData.getValue('autofillCountrySelectList');
-
- // Add the countries to the country <select>.
- var countrySelect = this.getCountrySwitcher_();
- // Add an empty option.
- countrySelect.appendChild(new Option('', ''));
- for (var i = 0; i < countryList.length; i++) {
- var option = new Option(countryList[i].name,
- countryList[i].value);
- option.disabled = countryList[i].value == 'separator';
- countrySelect.appendChild(option);
- }
- },
-
- /**
- * Called to prepare the overlay when a new address is being added.
- * @private
- */
- prepForNewAddress_: function() {
- // Focus the first element.
- this.pageDiv.querySelector('input').focus();
- },
-
- /**
- * Loads the address data from |address|, sets the input fields based on
- * this data, and stores the GUID and language code of the address.
- * @param {!Object} address Lots of info about an address from the browser.
- * @private
- */
- loadAddress_: function(address) {
- this.rebuildInputFields_(address.components);
- this.setInputFields_(address);
- this.inputFieldChanged_();
- this.connectInputEvents_();
- this.guid_ = address.guid;
- this.languageCode_ = address.languageCode;
- },
-
- /**
- * Takes a snapshot of the input values, clears the input values, loads the
- * address input layout from |input.components|, restores the input values
- * from snapshot, and stores the |input.languageCode| for the address.
- * @param {{languageCode: string, components: Array<Array<Object>>}} input
- * Info about how to layout inputs fields in this dialog.
- * @private
- */
- loadAddressComponents_: function(input) {
- var inputFields = this.getInputFields_();
- for (var fieldName in inputFields) {
- if (inputFields.hasOwnProperty(fieldName))
- this.savedFieldValues_[fieldName] = inputFields[fieldName];
- }
- this.rebuildInputFields_(input.components);
- this.setInputFields_(this.savedFieldValues_);
- this.inputFieldChanged_();
- this.connectInputEvents_();
- this.languageCode_ = input.languageCode;
- },
-
- /**
- * Clears address inputs and rebuilds the input fields according to
- * |components|.
- * @param {Array<Array<Object>>} components A list of information about
- * each input field.
- * @private
- */
- rebuildInputFields_: function(components) {
- var content = $('autofill-edit-address-fields');
- content.innerHTML = '';
-
- var customInputElements = {addrLines: 'textarea'};
-
- for (var i = 0; i < components.length; i++) {
- var row = document.createElement('div');
- row.classList.add('input-group', 'settings-row');
- content.appendChild(row);
-
- for (var j = 0; j < components[i].length; j++) {
- if (components[i][j].field == 'country')
- continue;
-
- var fieldContainer = document.createElement('label');
- row.appendChild(fieldContainer);
-
- var fieldName = document.createElement('div');
- fieldName.textContent = components[i][j].name;
- fieldContainer.appendChild(fieldName);
-
- var input = document.createElement(
- customInputElements[components[i][j].field] || 'input');
- input.setAttribute('field', components[i][j].field);
- input.classList.add(components[i][j].length);
- fieldContainer.appendChild(input);
- }
- }
- },
- };
-
- AutofillEditAddressOverlay.prepForNewAddress = function() {
- AutofillEditAddressOverlay.getInstance().prepForNewAddress_();
- };
-
- AutofillEditAddressOverlay.loadAddress = function(address) {
- AutofillEditAddressOverlay.getInstance().loadAddress_(address);
- };
-
- AutofillEditAddressOverlay.loadAddressComponents = function(input) {
- AutofillEditAddressOverlay.getInstance().loadAddressComponents_(input);
- };
-
- AutofillEditAddressOverlay.setTitle = function(title) {
- $('autofill-address-title').textContent = title;
- };
-
- // Export
- return {
- AutofillEditAddressOverlay: AutofillEditAddressOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.html b/chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.html
deleted file mode 100644
index 9b2c5f8d6d0..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<div id="autofill-edit-credit-card-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1 id="autofill-credit-card-title"></h1>
- <div class="content-area">
- <label class="settings-row">
- <div>$i18n{nameOnCardLabel}</div>
- <input id="name-on-card" type="text">
- </label>
-
- <label class="settings-row">
- <div>$i18n{creditCardNumberLabel}</div>
- <input id="credit-card-number" type="text">
- </label>
-
- <div class="settings-row">
- <div id="creditCardExpirationLabel">
- $i18n{creditCardExpirationDateLabel}
- </div>
- <select id="expiration-month" aria-labelledby="creditCardExpirationLabel">
- </select>
- <select id="expiration-year" aria-labelledby="creditCardExpirationLabel">
- </select>
- </div>
- </div>
-
- <div class="action-area button-strip">
- <button id="autofill-edit-credit-card-cancel-button" type="reset">
- $i18n{cancel}
- </button>
- <button id="autofill-edit-credit-card-apply-button" type="submit"
- class="default-button" disabled>
- $i18n{ok}
- </button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.js b/chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.js
deleted file mode 100644
index 369b7d941ff..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_edit_creditcard_overlay.js
+++ /dev/null
@@ -1,223 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * AutofillEditCreditCardOverlay class
- * Encapsulated handling of the 'Add Page' overlay page.
- * @class
- */
- function AutofillEditCreditCardOverlay() {
- Page.call(this, 'autofillEditCreditCard',
- loadTimeData.getString('autofillEditCreditCardTitle'),
- 'autofill-edit-credit-card-overlay');
- }
-
- cr.addSingletonGetter(AutofillEditCreditCardOverlay);
-
- AutofillEditCreditCardOverlay.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
- $('autofill-edit-credit-card-cancel-button').onclick = function(event) {
- self.dismissOverlay_();
- };
- $('autofill-edit-credit-card-apply-button').onclick = function(event) {
- self.saveCreditCard_();
- self.dismissOverlay_();
- };
-
- self.guid_ = '';
- self.clearInputFields_();
- self.connectInputEvents_();
- self.setDefaultSelectOptions_();
- },
-
- /**
- * Specifically catch the situations in which the overlay is cancelled
- * externally (e.g. by pressing <Esc>), so that the input fields and
- * GUID can be properly cleared.
- * @override
- */
- handleCancel: function() {
- this.dismissOverlay_();
- },
-
- /**
- * Clears any uncommitted input, and dismisses the overlay.
- * @private
- */
- dismissOverlay_: function() {
- this.clearInputFields_();
- this.guid_ = '';
- PageManager.closeOverlay();
- },
-
- /**
- * Aggregates the values in the input fields into an array and sends the
- * array to the Autofill handler.
- * @private
- */
- saveCreditCard_: function() {
- var creditCard = new Array(5);
- creditCard[0] = this.guid_;
- creditCard[1] = $('name-on-card').value;
- creditCard[2] = $('credit-card-number').value;
- creditCard[3] = $('expiration-month').value;
- creditCard[4] = $('expiration-year').value;
- chrome.send('setCreditCard', creditCard);
-
- // If the GUID is empty, this form is being used to add a new card,
- // rather than edit an existing one.
- if (!this.guid_.length) {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_AutofillCreditCardAdded']);
- }
- },
-
- /**
- * Connects each input field to the inputFieldChanged_() method that enables
- * or disables the 'Ok' button based on whether all the fields are empty or
- * not.
- * @private
- */
- connectInputEvents_: function() {
- var ccNumber = $('credit-card-number');
- $('name-on-card').oninput = ccNumber.oninput =
- $('expiration-month').onchange = $('expiration-year').onchange =
- this.inputFieldChanged_.bind(this);
- },
-
- /**
- * Checks the values of each of the input fields and disables the 'Ok'
- * button if all of the fields are empty.
- * @param {Event} opt_event Optional data for the 'input' event.
- * @private
- */
- inputFieldChanged_: function(opt_event) {
- var disabled = !$('name-on-card').value.trim() &&
- !$('credit-card-number').value.trim();
- $('autofill-edit-credit-card-apply-button').disabled = disabled;
- },
-
- /**
- * Sets the default values of the options in the 'Expiration date' select
- * controls.
- * @private
- */
- setDefaultSelectOptions_: function() {
- // Set the 'Expiration month' default options.
- var expirationMonth = $('expiration-month');
- expirationMonth.options.length = 0;
- for (var i = 1; i <= 12; ++i) {
- var text = (i < 10 ? '0' : '') + i;
-
- var option = document.createElement('option');
- option.text = option.value = text;
- expirationMonth.add(option, null);
- }
-
- // Set the 'Expiration year' default options.
- var expirationYear = $('expiration-year');
- expirationYear.options.length = 0;
-
- var date = new Date();
- var year = parseInt(date.getFullYear(), 10);
- for (var i = 0; i < 10; ++i) {
- var text = year + i;
- var option = document.createElement('option');
- option.text = String(text);
- option.value = text;
- expirationYear.add(option, null);
- }
- },
-
- /**
- * Clears the value of each input field.
- * @private
- */
- clearInputFields_: function() {
- $('name-on-card').value = '';
- $('credit-card-number').value = '';
- $('expiration-month').selectedIndex = 0;
- $('expiration-year').selectedIndex = 0;
-
- // Reset the enabled status of the 'Ok' button.
- this.inputFieldChanged_();
- },
-
- /**
- * Sets the value of each input field according to |creditCard|
- * @param {CreditCardData} creditCard
- * @private
- */
- setInputFields_: function(creditCard) {
- $('name-on-card').value = creditCard.nameOnCard;
- $('credit-card-number').value = creditCard.creditCardNumber;
-
- // The options for the year select control may be out-dated at this point,
- // e.g. the user opened the options page before midnight on New Year's Eve
- // and then loaded a credit card profile to edit in the new year, so
- // reload the select options just to be safe.
- this.setDefaultSelectOptions_();
-
- var idx = parseInt(creditCard.expirationMonth, 10);
- $('expiration-month').selectedIndex = idx - 1;
-
- var expYear = creditCard.expirationYear;
- var date = new Date();
- var year = parseInt(date.getFullYear(), 10);
- for (var i = 0; i < 10; ++i) {
- var text = year + i;
- if (expYear == String(text))
- $('expiration-year').selectedIndex = i;
- }
- },
-
- /**
- * Called to prepare the overlay when a new card is being added.
- * @private
- */
- prepForNewCard_: function() {
- // Focus the first element.
- this.pageDiv.querySelector('input').focus();
- },
-
- /**
- * Loads the credit card data from |creditCard|, sets the input fields based
- * on this data and stores the GUID of the credit card.
- * @param {CreditCardData} creditCard
- * @private
- */
- loadCreditCard_: function(creditCard) {
- this.setInputFields_(creditCard);
- this.inputFieldChanged_();
- this.guid_ = creditCard.guid;
- },
- };
-
- AutofillEditCreditCardOverlay.prepForNewCard = function() {
- AutofillEditCreditCardOverlay.getInstance().prepForNewCard_();
- };
-
- AutofillEditCreditCardOverlay.loadCreditCard = function(creditCard) {
- AutofillEditCreditCardOverlay.getInstance().loadCreditCard_(creditCard);
- };
-
- AutofillEditCreditCardOverlay.setTitle = function(title) {
- $('autofill-credit-card-title').textContent = title;
- };
-
- // Export
- return {
- AutofillEditCreditCardOverlay: AutofillEditCreditCardOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/autofill_edit_overlay.css b/chromium/chrome/browser/resources/options/autofill_edit_overlay.css
deleted file mode 100644
index 9f78131956a..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_edit_overlay.css
+++ /dev/null
@@ -1,76 +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. */
-
-#autofill-edit-address-overlay {
- min-width: 55em;
-}
-
-#autofill-edit-credit-card-overlay {
- min-width: 500px;
-}
-
-#autofill-edit-address-overlay .long div[role='listitem'] > div > div,
-#autofill-edit-address-overlay .long input,
-#autofill-edit-address-overlay textarea.long,
-#autofill-edit-address-overlay input.long {
- width: 16em;
-}
-
-#autofill-edit-address-overlay .short div[role='listitem'] > div > div,
-#autofill-edit-address-overlay .short input,
-#autofill-edit-address-overlay textarea.short,
-#autofill-edit-address-overlay input.short {
- width: 14em;
-}
-
-#autofill-edit-address-overlay .country {
- max-width: 450px;
-}
-
-#autofill-edit-address-overlay list {
- -webkit-margin-start: -3px;
- /* Min height is a multiple of the list item height (32px). */
- min-height: 32px;
-}
-
-#autofill-edit-address-overlay list div.static-text {
- -webkit-box-flex: 1;
- -webkit-padding-end: 4px;
- -webkit-padding-start: 4px;
- border: 1px solid darkGray;
- border-radius: 2px;
- /* Border should go "inside" the height. */
- box-sizing: border-box;
- /* Set the line-height and min-height to match the height of an input element,
- * so that even empty cells renderer with the correct height. */
- height: 2em;
- line-height: 2em;
-}
-
-#autofill-edit-address-overlay list:not([has-element-focus]) >
- [selected]:not(:hover) {
- background-color: transparent;
-}
-
-#autofill-edit-address-overlay list:not([has-element-focus]) > *:not(:hover)
- .row-delete-button {
- opacity: 0;
- pointer-events: none;
-}
-
-:-webkit-any(#autofill-edit-credit-card-overlay, #autofill-edit-address-overlay)
- .settings-row label > :-webkit-any(input, select, textarea, list) {
- margin-top: 4px;
-}
-
-.input-group > * {
- -webkit-box-orient: vertical;
- -webkit-margin-end: 2px;
- display: -webkit-inline-box;
- vertical-align: top;
-}
-
-#autofill-edit-credit-card-overlay .content-area > *:first-child {
- margin-top: 0;
-}
diff --git a/chromium/chrome/browser/resources/options/autofill_options.css b/chromium/chrome/browser/resources/options/autofill_options.css
deleted file mode 100644
index dd131a6c52e..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_options.css
+++ /dev/null
@@ -1,68 +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. */
-
-#autofill-options {
- width: 550px;
-}
-
-#autofill-options list {
- height: 192px; /* This is the min-height for lists from WebUI.*/
-}
-
-.autofill-list-item {
- -webkit-padding-start: 8px;
- max-width: 50%;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.autofill-list-item + .deemphasized {
- -webkit-box-flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-#autofill-options > div:last-child {
- margin-top: 15px;
-}
-
-#autofill-options .deemphasized {
- color: #777;
-}
-
-#autofill-options > div.settings-list > div:last-child {
- border-top: 1px solid #d9d9d9;
- padding: 5px 10px;
-}
-
-#autofill-add-address,
-#autofill-add-creditcard {
- margin: 5px 0;
-}
-
-#autofill-options .list-inline-button {
- -webkit-margin-start: 12px;
- margin-top: 0;
- vertical-align: top;
-}
-
-#autofill-options div[role='listitem']:not(:hover):not([selected])
- .hide-until-hover {
- display: none;
-}
-
-#autofill-options div[role='listitem']:-webkit-any(:hover,[selected])
- .hides-on-hover {
- display: none;
-}
-
-.settings-list + .autofill-section-header {
- margin-top: 20px;
-}
-
-#autofill-options .autofill-section-header {
- display: flex;
- justify-content: space-between;
- margin-bottom: 5px;
-} \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/options/autofill_options.html b/chromium/chrome/browser/resources/options/autofill_options.html
deleted file mode 100644
index d820ebee144..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_options.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<div id="autofill-options" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{autofillOptionsPage}</h1>
- <div class="content-area">
- <div class="autofill-section-header">
- <h3>$i18n{autofillAddresses}</h3>
- <button id="autofill-add-address">$i18n{autofillAddAddress}</button>
- </div>
- <div class="settings-list">
- <list id="address-list"></list>
- </div>
- <div class="autofill-section-header">
- <h3>$i18n{autofillCreditCards}</h3>
- <button id="autofill-add-creditcard">
- $i18n{autofillAddCreditCard}
- </button>
- </div>
- <div class="settings-list">
- <list id="creditcard-list"></list>
- </div>
- </div>
-
- <div class="action-area">
- <a id="autofill-help" target="_blank"
- href="$i18nRaw{helpUrl}">$i18n{helpButton}</a>
- <div class="spacer-div"></div>
- <div class="button-strip">
- <button id="autofill-options-confirm" class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/autofill_options.js b/chromium/chrome/browser/resources/options/autofill_options.js
deleted file mode 100644
index 7f300006b80..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_options.js
+++ /dev/null
@@ -1,218 +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.
-
-/**
- * @typedef {{
- * creditCardNumber: string,
- * expirationMonth: string,
- * expirationYear: string,
- * guid: string,
- * nameOnCard: string
- * }}
- * @see chrome/browser/ui/webui/options/autofill_options_handler.cc
- */
-var CreditCardData;
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
- var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /////////////////////////////////////////////////////////////////////////////
- // AutofillOptions class:
-
- /**
- * Encapsulated handling of Autofill options page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function AutofillOptions() {
- Page.call(this, 'autofill',
- loadTimeData.getString('autofillOptionsPageTabTitle'),
- 'autofill-options');
- }
-
- cr.addSingletonGetter(AutofillOptions);
-
- AutofillOptions.prototype = {
- __proto__: Page.prototype,
-
- /**
- * The address list.
- * @type {options.DeletableItemList}
- * @private
- */
- addressList_: null,
-
- /**
- * The credit card list.
- * @type {options.DeletableItemList}
- * @private
- */
- creditCardList_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- this.createAddressList_();
- this.createCreditCardList_();
-
- var self = this;
- $('autofill-add-address').onclick = function(event) {
- self.showAddAddressOverlay_();
- };
- $('autofill-add-creditcard').onclick = function(event) {
- self.showAddCreditCardOverlay_();
- };
- $('autofill-options-confirm').onclick = function(event) {
- PageManager.closeOverlay();
- };
-
- $('autofill-help').onclick = function(event) {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_AutofillShowAbout']);
- return true; // Always follow the href
- };
-
- // TODO(jhawkins): What happens when Autofill is disabled whilst on the
- // Autofill options page?
- },
-
- /**
- * Creates, decorates and initializes the address list.
- * @private
- */
- createAddressList_: function() {
- var addressList = $('address-list');
- options.autofillOptions.AutofillAddressList.decorate(addressList);
- this.addressList_ = assertInstanceof(addressList,
- options.DeletableItemList);
- this.addressList_.autoExpands = true;
- },
-
- /**
- * Creates, decorates and initializes the credit card list.
- * @private
- */
- createCreditCardList_: function() {
- var creditCardList = $('creditcard-list');
- options.autofillOptions.AutofillCreditCardList.decorate(creditCardList);
- this.creditCardList_ = assertInstanceof(creditCardList,
- options.DeletableItemList);
- this.creditCardList_.autoExpands = true;
- },
-
- /**
- * Shows the 'Add address' overlay, specifically by loading the
- * 'Edit address' overlay and modifying the overlay title.
- * @private
- */
- showAddAddressOverlay_: function() {
- var title = loadTimeData.getString('addAddressTitle');
- AutofillEditAddressOverlay.setTitle(title);
- PageManager.showPageByName('autofillEditAddress');
- AutofillEditAddressOverlay.prepForNewAddress();
- },
-
- /**
- * Shows the 'Add credit card' overlay, specifically by loading the
- * 'Edit credit card' overlay and modifying the overlay title.
- * @private
- */
- showAddCreditCardOverlay_: function() {
- var title = loadTimeData.getString('addCreditCardTitle');
- AutofillEditCreditCardOverlay.setTitle(title);
- PageManager.showPageByName('autofillEditCreditCard');
- AutofillEditCreditCardOverlay.prepForNewCard();
- },
-
- /**
- * Updates the data model for the address list with the values from
- * |entries|.
- * @param {!Array} entries The list of addresses.
- */
- setAddressList_: function(entries) {
- this.addressList_.dataModel = new ArrayDataModel(entries);
- },
-
- /**
- * Updates the data model for the credit card list with the values from
- * |entries|.
- * @param {!Array} entries The list of credit cards.
- */
- setCreditCardList_: function(entries) {
- this.creditCardList_.dataModel = new ArrayDataModel(entries);
- },
-
- /**
- * Removes the Autofill address or credit card represented by |guid|.
- * @param {string} guid The GUID of the address to remove.
- * @param {string=} metricsAction The name of the action to log for metrics.
- * @private
- */
- removeData_: function(guid, metricsAction) {
- chrome.send('removeData', [guid]);
- if (metricsAction)
- chrome.send('coreOptionsUserMetricsAction', [metricsAction]);
- },
-
- /**
- * Shows the 'Edit address' overlay, using the data in |address| to fill the
- * input fields. |address| is a list with one item, an associative array
- * that contains the address data.
- * @private
- */
- showEditAddressOverlay_: function(address) {
- var title = loadTimeData.getString('editAddressTitle');
- AutofillEditAddressOverlay.setTitle(title);
- AutofillEditAddressOverlay.loadAddress(address);
- PageManager.showPageByName('autofillEditAddress');
- },
-
- /**
- * Shows the 'Edit credit card' overlay, using the data in |credit_card| to
- * fill the input fields. |creditCard| is a list with one item, an
- * associative array that contains the credit card data.
- * @param {CreditCardData} creditCard
- * @private
- */
- showEditCreditCardOverlay_: function(creditCard) {
- var title = loadTimeData.getString('editCreditCardTitle');
- AutofillEditCreditCardOverlay.setTitle(title);
- AutofillEditCreditCardOverlay.loadCreditCard(creditCard);
- PageManager.showPageByName('autofillEditCreditCard');
- },
- };
-
- AutofillOptions.setAddressList = function(entries) {
- AutofillOptions.getInstance().setAddressList_(entries);
- };
-
- AutofillOptions.setCreditCardList = function(entries) {
- AutofillOptions.getInstance().setCreditCardList_(entries);
- };
-
- AutofillOptions.removeData = function(guid, metricsAction) {
- AutofillOptions.getInstance().removeData_(guid, metricsAction);
- };
-
- AutofillOptions.editAddress = function(address) {
- AutofillOptions.getInstance().showEditAddressOverlay_(address);
- };
-
- /**
- * @param {CreditCardData} creditCard
- */
- AutofillOptions.editCreditCard = function(creditCard) {
- AutofillOptions.getInstance().showEditCreditCardOverlay_(creditCard);
- };
-
- // Export
- return {
- AutofillOptions: AutofillOptions
- };
-
-});
-
diff --git a/chromium/chrome/browser/resources/options/autofill_options_list.js b/chromium/chrome/browser/resources/options/autofill_options_list.js
deleted file mode 100644
index 723c44b551d..00000000000
--- a/chromium/chrome/browser/resources/options/autofill_options_list.js
+++ /dev/null
@@ -1,285 +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.
-
-/**
- * @typedef {{
- * guid: string,
- * label: string,
- * sublabel: string,
- * isLocal: boolean,
- * isCached: boolean
- * }}
- * @see chrome/browser/ui/webui/options/autofill_options_handler.cc
- */
-var AutofillEntityMetadata;
-
-cr.define('options.autofillOptions', function() {
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var DeletableItemList = options.DeletableItemList;
- /** @const */ var InlineEditableItem = options.InlineEditableItem;
- /** @const */ var InlineEditableItemList = options.InlineEditableItemList;
-
- /**
- * @return {!HTMLButtonElement}
- */
- function AutofillEditProfileButton(edit) {
- var editButtonEl = /** @type {HTMLButtonElement} */(
- document.createElement('button'));
- editButtonEl.className =
- 'list-inline-button hide-until-hover custom-appearance';
- editButtonEl.textContent =
- loadTimeData.getString('autofillEditProfileButton');
- editButtonEl.onclick = edit;
-
- editButtonEl.onmousedown = function(e) {
- // Don't select the row when clicking the button.
- e.stopPropagation();
- // Don't focus on the button when clicking it.
- e.preventDefault();
- };
-
- return editButtonEl;
- }
-
- /** @return {!Element} */
- function CreateGoogleAccountLabel() {
- var label = document.createElement('div');
- label.className = 'deemphasized hides-on-hover';
- label.textContent = loadTimeData.getString('autofillFromGoogleAccount');
- return label;
- }
-
- /**
- * Creates a new address list item.
- * @constructor
- * @param {AutofillEntityMetadata} metadata Details about an address profile.
- * @extends {options.DeletableItem}
- * @see chrome/browser/ui/webui/options/autofill_options_handler.cc
- */
- function AddressListItem(metadata) {
- var el = cr.doc.createElement('div');
- el.__proto__ = AddressListItem.prototype;
- /** @private */
- el.metadata_ = metadata;
- el.decorate();
-
- return el;
- }
-
- AddressListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- var label = this.ownerDocument.createElement('div');
- label.className = 'autofill-list-item';
- label.textContent = this.metadata_.label;
- this.contentElement.appendChild(label);
-
- var sublabel = this.ownerDocument.createElement('div');
- sublabel.className = 'deemphasized';
- sublabel.textContent = this.metadata_.sublabel;
- this.contentElement.appendChild(sublabel);
-
- if (!this.metadata_.isLocal) {
- this.deletable = false;
- this.contentElement.appendChild(CreateGoogleAccountLabel());
- }
-
- // The 'Edit' button.
- var metadata = this.metadata_;
- var editButtonEl = AutofillEditProfileButton(
- AddressListItem.prototype.loadAddressEditor.bind(this));
- this.contentElement.appendChild(editButtonEl);
- },
-
- /**
- * For local Autofill data, this function causes the AutofillOptionsHandler
- * to call showEditAddressOverlay(). For Payments data, the user is
- * redirected to the Payments web interface.
- */
- loadAddressEditor: function() {
- if (this.metadata_.isLocal)
- chrome.send('loadAddressEditor', [this.metadata_.guid]);
- else
- window.open(loadTimeData.getString('paymentsManageAddressesUrl'));
- },
- };
-
- /**
- * Creates a new credit card list item.
- * @param {AutofillEntityMetadata} metadata Details about a credit card.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function CreditCardListItem(metadata) {
- var el = cr.doc.createElement('div');
- el.__proto__ = CreditCardListItem.prototype;
- /** @private */
- el.metadata_ = metadata;
- el.decorate();
-
- return el;
- }
-
- CreditCardListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- var label = this.ownerDocument.createElement('div');
- label.className = 'autofill-list-item';
- label.textContent = this.metadata_.label;
- this.contentElement.appendChild(label);
-
- var sublabel = this.ownerDocument.createElement('div');
- sublabel.className = 'deemphasized';
- sublabel.textContent = this.metadata_.sublabel;
- this.contentElement.appendChild(sublabel);
-
- if (!this.metadata_.isLocal) {
- this.deletable = false;
- this.contentElement.appendChild(CreateGoogleAccountLabel());
- }
-
- var guid = this.metadata_.guid;
- if (this.metadata_.isCached) {
- var localCopyText = this.ownerDocument.createElement('span');
- localCopyText.className = 'hide-until-hover deemphasized';
- localCopyText.textContent =
- loadTimeData.getString('autofillDescribeLocalCopy');
- this.contentElement.appendChild(localCopyText);
-
- var clearLocalCopyButton = AutofillEditProfileButton(
- function() { chrome.send('clearLocalCardCopy', [guid]); });
- clearLocalCopyButton.textContent =
- loadTimeData.getString('autofillClearLocalCopyButton');
- this.contentElement.appendChild(clearLocalCopyButton);
- }
-
- // The 'Edit' button.
- var metadata = this.metadata_;
- var editButtonEl = AutofillEditProfileButton(
- CreditCardListItem.prototype.loadCreditCardEditor.bind(this));
- this.contentElement.appendChild(editButtonEl);
- },
-
- /**
- * For local Autofill data, this function causes the AutofillOptionsHandler
- * to call showEditCreditCardOverlay(). For Payments data, the user is
- * redirected to the Payments web interface.
- */
- loadCreditCardEditor: function() {
- if (this.metadata_.isLocal)
- chrome.send('loadCreditCardEditor', [this.metadata_.guid]);
- else
- window.open(loadTimeData.getString('paymentsManageInstrumentsUrl'));
- },
- };
-
- /**
- * Base class for shared implementation between address and credit card lists.
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var AutofillProfileList = cr.ui.define('list');
-
- AutofillProfileList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- decorate: function() {
- DeletableItemList.prototype.decorate.call(this);
-
- this.addEventListener('blur', this.onBlur_);
- },
-
- /**
- * When the list loses focus, unselect all items in the list.
- * @private
- */
- onBlur_: function() {
- this.selectionModel.unselectAll();
- },
- };
-
- /**
- * Create a new address list.
- * @constructor
- * @extends {options.autofillOptions.AutofillProfileList}
- */
- var AutofillAddressList = cr.ui.define('list');
-
- AutofillAddressList.prototype = {
- __proto__: AutofillProfileList.prototype,
-
- decorate: function() {
- AutofillProfileList.prototype.decorate.call(this);
- },
-
- /** @override */
- activateItemAtIndex: function(index) {
- this.getListItemByIndex(index).loadAddressEditor();
- },
-
- /**
- * @override
- * @param {AutofillEntityMetadata} metadata
- */
- createItem: function(metadata) {
- return new AddressListItem(metadata);
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- AutofillOptions.removeData(this.dataModel.item(index).guid,
- 'Options_AutofillAddressDeleted');
- },
- };
-
- /**
- * Create a new credit card list.
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var AutofillCreditCardList = cr.ui.define('list');
-
- AutofillCreditCardList.prototype = {
- __proto__: AutofillProfileList.prototype,
-
- decorate: function() {
- AutofillProfileList.prototype.decorate.call(this);
- },
-
- /** @override */
- activateItemAtIndex: function(index) {
- this.getListItemByIndex(index).loadCreditCardEditor();
- },
-
- /**
- * @override
- * @param {AutofillEntityMetadata} metadata
- */
- createItem: function(metadata) {
- return new CreditCardListItem(metadata);
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- AutofillOptions.removeData(this.dataModel.item(index).guid,
- 'Options_AutofillCreditCardDeleted');
- },
- };
-
- return {
- AutofillProfileList: AutofillProfileList,
- AddressListItem: AddressListItem,
- CreditCardListItem: CreditCardListItem,
- AutofillAddressList: AutofillAddressList,
- AutofillCreditCardList: AutofillCreditCardList,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.css b/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.css
deleted file mode 100644
index d11484a6067..00000000000
--- a/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.css
+++ /dev/null
@@ -1,82 +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. */
-
-.settings-banner {
- background-color: #f5f5f5;
- border-color: #c8c8c8;
- border-radius: 3px;
- border-style: solid;
- border-width: 1px;
- margin-bottom: 24px;
- margin-top: 20px;
- max-width: 716px;
- position: relative;
-}
-
-.settings-banner > .close-button {
- background-image: url(chrome://theme/IDR_CLOSE_DIALOG);
- background-position: center;
- background-repeat: no-repeat;
- height: 14px;
- opacity: 0.5;
- position: absolute;
- right: 4px;
- top: 4px;
- width: 14px;
-}
-
-html[dir='rtl'] .settings-banner > .close-button {
- left: 4px;
- right: auto;
-}
-
-.settings-banner > .close-button:hover {
- background-image: url(chrome://theme/IDR_CLOSE_DIALOG_H);
-}
-
-.settings-banner > .close-button:active {
- background-image: url(chrome://theme/IDR_CLOSE_DIALOG_P);
-}
-
-.settings-banner .content-area {
- align-items: center;
- display: flex;
- padding: 17px;
-}
-
-.settings-banner .content-area .badge {
- background-image: url(yellow_gear.png);
- background-position: center;
- background-repeat: no-repeat;
- height: 55px;
- width: 58px;
-}
-
-.settings-banner .content-area .text {
- -webkit-margin-start: 18px;
- flex: 1;
-}
-
-.settings-banner .content-area .text p {
- margin-bottom: 0;
- margin-top: 0;
-}
-
-.settings-banner .content-area .button-area {
- -webkit-margin-start: 54px;
-}
-
-.settings-banner .nowrap {
- white-space: nowrap;
-}
-
-.settings-banner button {
- margin-bottom: 1px;
- margin-right: 0;
-}
-
-#secondary-user-banner .content-area .badge {
- background-color: rgb(210, 210, 212);
- background-image: url(chrome://theme/IDR_SECONDARY_USER_SETTINGS);
-}
diff --git a/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.html b/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.html
deleted file mode 100644
index fcb16c40176..00000000000
--- a/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<div id="automatic-settings-reset-banner" class="settings-banner" hidden>
- <div id="automatic-settings-reset-banner-close" class="close-button"></div>
- <div class="content-area">
- <div class="badge"></div>
- <div class="text">
- <p>
- <span>$i18nRaw{automaticSettingsResetBannerText}</span>
- <a id="automatic-settings-reset-learn-more" class="nowrap"
- href="$i18nRaw{automaticSettingsResetLearnMoreUrl}"
- target="_blank">$i18n{learnMore}</a>
- </p>
- </div>
- <div class="button-area">
- <button id="automatic-settings-reset-banner-activate-reset">
- $i18n{automaticSettingsResetBannerResetButtonText}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.js b/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.js
deleted file mode 100644
index 5755d802034..00000000000
--- a/chromium/chrome/browser/resources/options/automatic_settings_reset_banner.js
+++ /dev/null
@@ -1,132 +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.
-
-// Note: the native-side handler for this is AutomaticSettingsResetHandler.
-
-cr.define('options', function() {
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * AutomaticSettingsResetBanner class
- * Provides encapsulated handling of the Reset Profile Settings banner.
- * @constructor
- */
- function AutomaticSettingsResetBanner() {}
-
- cr.addSingletonGetter(AutomaticSettingsResetBanner);
-
- AutomaticSettingsResetBanner.prototype = {
- /**
- * Whether or not the banner has already been dismissed.
- *
- * This is needed because of the surprising ordering of asynchronous
- * JS<->native calls when the settings page is opened with specifying a
- * given sub-page, e.g. chrome://settings/AutomaticSettingsReset.
- *
- * In such a case, AutomaticSettingsResetOverlay's didShowPage(), which
- * calls our dismiss() method, would be called before the native Handlers'
- * InitalizePage() methods have an effect in the JS, which includes calling
- * our show() method. This would mean that the banner would be first
- * dismissed, then shown. We want to prevent this.
- *
- * @private {boolean}
- */
- wasDismissed_: false,
-
- /**
- * Metric name to send when a show event occurs.
- * @private {string}
- */
- showMetricName_: '',
-
- /**
- * Name of the native callback invoked when the banner is dismised.
- */
- dismissNativeCallbackName_: '',
-
- /**
- * DOM element whose visibility is set when setVisibility_ is called.
- * @private {?HTMLElement}
- */
- visibleElement_: null,
-
- /**
- * Initializes the banner's event handlers.
- * @suppress {checkTypes}
- * TODO(vitalyp): remove the suppression. Suppression is needed because
- * method dismiss() is attached to AutomaticSettingsResetBanner at run-time
- * via "Forward public APIs to protected implementations" pattern (see
- * below). Currently the compiler pass and cr.js handles only forwarding to
- * private implementations using cr.makePublic().
- */
- initialize: function() {
- this.showMetricName_ = 'AutomaticSettingsReset_WebUIBanner_BannerShown';
-
- this.dismissNativeCallbackName_ =
- 'onDismissedAutomaticSettingsResetBanner';
-
- this.visibleElement_ = getRequiredElement(
- 'automatic-settings-reset-banner');
-
- $('automatic-settings-reset-banner-close').onclick = function(event) {
- chrome.send('metricsHandler:recordAction',
- ['AutomaticSettingsReset_WebUIBanner_ManuallyClosed']);
- AutomaticSettingsResetBanner.dismiss();
- };
- $('automatic-settings-reset-learn-more').onclick = function(event) {
- chrome.send('metricsHandler:recordAction',
- ['AutomaticSettingsReset_WebUIBanner_LearnMoreClicked']);
- };
- $('automatic-settings-reset-banner-activate-reset').onclick =
- function(event) {
- chrome.send('metricsHandler:recordAction',
- ['AutomaticSettingsReset_WebUIBanner_ResetClicked']);
- PageManager.showPageByName('resetProfileSettings');
- };
- },
-
- /**
- * Sets whether or not the reset profile settings banner shall be visible.
- * @param {boolean} show Whether or not to show the banner.
- * @protected
- */
- setVisibility: function(show) {
- this.visibleElement_.hidden = !show;
- },
-
- /**
- * Called by the native code to show the banner if needed.
- * @private
- */
- show_: function() {
- if (!this.wasDismissed_) {
- chrome.send('metricsHandler:recordAction', [this.showMetricName_]);
- this.setVisibility(true);
- }
- },
-
- /**
- * Called when the banner should be closed as a result of something taking
- * place on the WebUI page, i.e. when its close button is pressed, or when
- * the confirmation dialog for the profile settings reset feature is opened.
- * @private
- */
- dismiss_: function() {
- chrome.send(assert(this.dismissNativeCallbackName_));
- this.wasDismissed_ = true;
- this.setVisibility(false);
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(AutomaticSettingsResetBanner, [
- 'show',
- 'dismiss',
- ]);
-
- // Export
- return {
- AutomaticSettingsResetBanner: AutomaticSettingsResetBanner
- };
-});
diff --git a/chromium/chrome/browser/resources/options/browser_options.css b/chromium/chrome/browser/resources/options/browser_options.css
deleted file mode 100644
index cb9a251073b..00000000000
--- a/chromium/chrome/browser/resources/options/browser_options.css
+++ /dev/null
@@ -1,492 +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. */
-
-#change-home-page-section {
- -webkit-margin-start: 30px;
-}
-
-#home-page-url {
- display: inline-block;
- max-width: 400px;
- overflow: hidden;
- text-overflow: ellipsis;
- vertical-align: top;
-}
-
-#default-browser-state,
-#profiles-supervised-dashboard-tip {
- margin-top: 6px;
-}
-
-#sync-overview p {
- display: inline;
-}
-
-#account-picture-wrapper {
- float: left;
- margin: 0 2px 10px 0;
-}
-
-html[dir=rtl] #account-picture-wrapper {
- float: right;
-}
-
-#account-picture-control {
- border: 1px solid rgba(0, 0, 0, 0.3);
- border-radius: 4px;
- display: inline-block;
- padding: 3px;
- position: relative;
-}
-
-#account-picture {
- height: 56px;
- object-fit: cover;
- vertical-align: middle;
- width: 56px;
-}
-
-#account-picture:disabled {
- cursor: default;
-}
-
-#change-picture-caption {
- background: rgba(0, 0, 0, 0.5);
- bottom: 0;
- color: white;
- cursor: pointer;
- font-size: small;
- margin: 3px 0;
- position: absolute;
- text-align: center;
- visibility: hidden;
- /* Width of #account-picture. */
- width: 56px;
-}
-
-#account-picture:not(:disabled):hover + #change-picture-caption,
-#account-picture:not(:disabled) + #change-picture-caption:hover {
- visibility: visible;
-}
-
-#account-picture-indicator {
- -webkit-margin-end: 3px;
-}
-
-#sync-general {
- -webkit-margin-start: 76px;
- margin-bottom: 10px;
-}
-
-#sync-buttons {
- clear: both;
-}
-
-#profiles-list {
- margin-bottom: 10px;
- min-height: 0;
-}
-
-#profiles-list .profile-container {
- -webkit-box-align: center;
- display: -webkit-box;
- max-width: 100%;
-}
-
-#profiles-list .profile-name {
- -webkit-box-flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-#profiles-list .profile-supervised {
- color: #999;
- margin-left: 5px;
-}
-
-#profiles-list > * {
- height: 40px;
-}
-
-#profiles-list:focus {
- border-color: rgb(77, 144, 254);
-}
-
-.profile-img {
- height: 31px;
- padding: 3px;
- vertical-align: middle;
- width: 38px;
-}
-
-.profile-item-current {
- font-weight: bold;
-}
-
-#profiles-buttons {
- white-space: nowrap;
-}
-
-.sync-error {
- background: rgb(255, 219, 219);
- border: 1px solid rgb(206, 76, 76);
- border-radius: 2px;
- padding: 10px;
-}
-
-.sync-error [is='action-link'] {
- margin: 0 1ex;
- padding: 0;
-}
-
-#mac-passwords-warning {
- margin-top: 10px;
-}
-
-input[type='range'] {
- vertical-align: middle;
-}
-
-.extension-controlled-warning-box {
- background-color: #fbfbfb;
- border: 1px solid #cecece;
- border-radius: 3px;
- padding: 19px;
-}
-
-.extension-controlled-warning {
- -webkit-padding-start: 35px;
- background-repeat: no-repeat;
- padding-bottom: 20px;
- padding-top: 3px;
-}
-
-.setting-extra-description {
- -webkit-margin-start: 1.8em;
- color: #999;
-}
-
-.hotword-settings {
- -webkit-margin-start: 22px;
-}
-
-.hotword-audio-history {
- -webkit-margin-start: 1.8em;
-}
-
-#audio-history {
- margin-top: 1.5em;
-}
-
-#hotword-retrain-link {
- text-decoration: none;
-}
-
-/* Internet settings */
-
-#network-settings {
- position: relative;
-}
-
-#network-list {
- min-height: 0;
- width: 320px;
-}
-
-#download-location-label.disabled {
- color: #999;
-}
-
-.network-group {
- -webkit-box-orient: horizontal;
- height: 42px;
- overflow: visible;
-}
-
-list:not([disabled]) > .network-group:hover,
-list:not([disabled]) > .network-group[selected] {
- background-color: #f8f8f8 !important;
- background-image: -webkit-linear-gradient(rgba(255, 255, 255, 0.8),
- rgba(255, 255, 255, 0)) !important;
- box-shadow: inset 0 0 1px 1px #f0f0f0;
-}
-
-.network-group-labels {
- -webkit-box-flex: 1;
- -webkit-box-orient: vertical;
- display: -webkit-box;
- padding-top: 3px;
-}
-
-.network-icon {
- -webkit-margin-end: 10px;
- background-position: left top;
- background-size: 25px;
- height: 25px;
- line-height: normal;
- white-space: normal;
- width: 25px;
-}
-
-.network-icon cr-network-icon {
- height: 100%;
- width: 100%;
-}
-
-@keyframes connecting-animation {
- 0% {
- background-position: 0 25%;
- }
- 12.5% {
- background-position: 0 50%;
- }
- 25% {
- background-position: 0 75%;
- }
- 37.5% {
- background-position: 0 100%;
- }
- 50% {
- background-position: 0 100%;
- }
- 62.5% {
- background-position: 0 75%;
- }
- 75% {
- background-position: 0 50%;
- }
- 87.5% {
- background-position: 0 25%;
- }
-}
-
-.network-add-connection {
- background-image: url(chrome://theme/IDR_NETWORK_ADD_CONNECTION);
- background-position: center center !important;
- background-repeat: no-repeat;
- background-size: 16px;
-}
-
-.network-options-button {
- -webkit-box-flex: 0;
- background-image: none;
- background-position: center center;
- display: block;
- opacity: 0.5;
- transform: scale(0.6);
- vertical-align: middle;
- width: 19px;
-}
-
-.network-group > .controlled-setting-indicator,
-.network-menu-item > .controlled-setting-indicator {
- -webkit-margin-end: 5px;
-}
-
-.network-options-button:hover {
- opacity: 1;
-}
-
-@keyframes vpn-connecting-animation {
- from {
- opacity: 1;
- }
- to {
- opacity: 0.2;
- }
-}
-
-.network-connecting {
- animation: connecting-animation 1s step-end infinite;
-}
-
-.network-vpn.network-connecting {
- animation: vpn-connecting-animation 500ms alternate infinite;
-}
-
-.network-title {
- font-weight: 600;
- line-height: 120%;
-}
-
-.network-subtitle {
- color: #333;
- display: inline-block;
- line-height: 100%;
- max-width: 260px;
- opacity: 0.4;
- overflow: hidden;
- padding-bottom: 3px;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.network-selector {
- background: right center no-repeat;
- background-image: url(../../../../ui/webui/resources/images/select.png);
- padding-right: 20px;
-}
-
-.network-menu {
- background: #fff;
- box-shadow:
- 0 0 0 1px rgba(0,0,0,0.1),
- 0 5px 1px 1px rgba(0,0,0,0.1),
- 0 5px 2px 1px rgba(0,0,0,0.1),
- 0 5px 12px 1px rgba(0,0,0,0.5);
- display: block;
- position: absolute;
- width: 320px;
- z-index: 1;
-}
-
-.network-menu-item {
- -webkit-box-align: center;
- -webkit-box-orient: horizontal;
- display: -webkit-box;
- height: 32px;
- margin-left: 4px;
- margin-right: 4px;
-}
-
-.network-menu-item-label {
- -webkit-box-flex: 1;
- color: #555;
- display: block;
- overflow-x: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.active-network {
- color: black;
- font-weight: bold;
-}
-
-.network-disabled-control {
- color: #999;
-}
-
-/* Restrict the size of the networks menu, by limiting the number of
- visible networks. */
-.network-menu-group {
- max-height: 192px;
- overflow-x: hidden;
- overflow-y: auto;
- text-overflow: ellipsis;
-}
-
-.network-menu-item:hover,
-.network-menu-item[selected] {
- background-color: #eee;
-}
-
-.network-menu > hr {
- opacity: 0.4;
-}
-
-#shared-proxies {
- margin-top: 12px;
-}
-
-#web-content-section select,
-.web-content-select-label {
- min-width: 145px;
-}
-
-.web-content-select-label > span:only-of-type {
- display: inline-block;
- min-width: 100px;
-}
-
-#timezone-value {
- display: inline-block;
- vertical-align: baseline;
-}
-
-.loading #timezone-value select {
- color: transparent;
- text-shadow: none;
-}
-
-#privacy-explanation {
- line-height: 1.8em;
-}
-
-#advanced-settings {
- height: 0;
- margin-top: 8px;
- overflow: hidden;
-}
-
-.sliding {
- overflow-y: hidden;
- transition: height 200ms;
-}
-
-#keyboard-overlay .option-value > select {
- width: 100%;
-}
-
-#keyboard-overlay table,
-#power-overlay table {
- /* Same as .settings-row {margin}. */
- -webkit-border-horizontal-spacing: 0;
- -webkit-border-vertical-spacing: 0.65em;
-}
-
-#stylus-settings-link,
-#power-settings-link {
- /* Match the spacing of the touchpad/mouse slider. */
- line-height: 25px;
-}
-
-#accessibility-autoclick .controlled-setting-with-label {
- -webkit-box-align: baseline;
-}
-
-#accessibility-autoclick-dropdown,
-#accessibility-autoclick-label {
- /* Same as .controlled-setting-with-label > input + span. */
- -webkit-margin-start: 0.6em;
-}
-
-#accessibility-screen-magnifier-center-focus-check {
- -webkit-margin-start: 0.4em;
-}
-
-div[guestmode=true] :-webkit-any(
-<if expr="not chromeos">
- #searchBox,
-</if>
- #appearance-section,
- #startup-section,
- #reset-profile-settings-section) {
- display: none;
-}
-
-div[supervisedMode=true] :-webkit-any(
- #profiles-enable-guest,
- #profiles-enable-add-person) {
- display: none;
-}
-
-footer {
- display: flex;
-}
-
-#about-button {
- -webkit-margin-end: 30px;
-}
-
-/* An input that has no function except to take up the same amount of space as
- * a checkbox. */
-.spacer-checkbox {
- visibility: hidden;
-}
-
-#android-apps-settings {
- -webkit-margin-start: 30px;
-}
diff --git a/chromium/chrome/browser/resources/options/browser_options.html b/chromium/chrome/browser/resources/options/browser_options.html
deleted file mode 100644
index 3d2ce964293..00000000000
--- a/chromium/chrome/browser/resources/options/browser_options.html
+++ /dev/null
@@ -1,1149 +0,0 @@
-<if expr="chromeos">
-<link rel="import" href="/people_page/lock_screen_constants.html">
-</if>
-<div id="settings" class="page" hidden>
- <header>
- <h1>$i18n{settingsTitle}</h1>
- </header>
- <include src="automatic_settings_reset_banner.html">
-<if expr="chromeos">
- <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
- <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
- <include src="secondary_user_banner.html">
- <section id="network-section-cros">
- <div id="network-section-header" class="section-header">
- <h3>$i18n{sectionTitleInternet}</h3>
- <span class="controlled-setting-indicator" plural></span>
- </div>
- <div id="network-settings">
- <list id="network-list"></list>
- <div id="shared-proxies" class="checkbox">
- <label>
- <input id="use-shared-proxies" type="checkbox"
- metric="Options_NetworkUseSharedProxies"
- pref="settings.use_shared_proxies">
- <span>$i18n{useSharedProxies}</span>
- </label>
- </div>
- <div id="network-menus"></div>
- </div>
- </section>
-</if>
-<if expr="not chromeos">
- <include src="sync_section.html">
- <include src="startup_section.html">
-</if>
- <section id="proxy-section" hidden>
- <h3>$i18n{sectionTitleProxy}</h3>
- <div id="proxy-section-content"></div>
- </section>
-
- <section id="appearance-section">
- <h3>$i18n{sectionTitleAppearance}</h3>
- <div class="settings-row">
-<if expr="chromeos">
- <button id="set-wallpaper" guest-visibility="disabled">
- $i18n{setWallpaper}
- </button>
- <span id="wallpaper-indicator" class="controlled-setting-indicator">
- </span>
-</if>
-<if expr="not chromeos and is_posix and not is_macosx">
- <button id="themes-gallery">$i18n{themesGallery}</button>
- <button id="themes-native-button">$i18n{themesNativeButton}</button>
- <button id="themes-reset">$i18n{themesSetClassic}</button>
-</if>
-<if expr="chromeos or is_win or is_macosx">
- <button id="themes-gallery">$i18n{themesGallery}</button>
- <button id="themes-reset">$i18n{themesReset}</button>
-</if>
- </div>
- <div class="checkbox controlled-setting-with-label"
- guest-visibility="disabled">
- <label>
- <input type="checkbox"
- pref="browser.show_home_button"
- metric="Options_Homepage_HomeButton">
- <span>
- <span>$i18n{homePageShowHomeButton}</span>
- <span class="controlled-setting-indicator"
- pref="browser.show_home_button"></span>
- </span>
- </label>
- </div>
- <div id="change-home-page-section" hidden>
- <div id="change-home-page-section-container" guest-visibility="disabled">
- <span id="home-page-ntp" class="home-page-label">
- $i18n{homePageNtp}
- </span>
- <span id="home-page-url" class="home-page-label"></span>
- <a is="action-link" id="change-home-page">$i18n{changeHomePage}</a>
- <div id="extension-controlled-container"></div>
- </div>
- </div>
- <div class="checkbox controlled-setting-with-label"
- guest-visibility="disabled">
- <label>
- <input type="checkbox"
- pref="bookmark_bar.show_on_all_tabs"
- metric="Options_ShowBookmarksBar">
- <span>
- <span>$i18n{toolbarShowBookmarksBar}</span>
- <span class="controlled-setting-indicator"
- pref="bookmark_bar.show_on_all_tabs"></span>
- </span>
- </label>
- </div>
-<if expr="is_linux and not chromeos">
- <div class="checkbox"><label>
- <input id="show-window-decorations" type="checkbox"
- pref="browser.custom_chrome_frame" metric="Options_CustomFrame"
- inverted_pref>
- <span>$i18n{showWindowDecorations}</span>
- </label></div>
-</if>
- </section>
-<if expr="chromeos">
- <section id="device-section">
- <h3>$i18n{sectionTitleDevice}</h3>
- <div>
- <span>$i18n{deviceGroupDescription}</span>
- <div id="touchpad-settings" class="settings-row" hidden>
- <span id="touchpad-speed-label" class="option-name">
- $i18n{touchpadSpeed}
- </span>
- <input id="touchpad-sensitivity-range" type="range" min="1" max="5"
- pref="settings.touchpad.sensitivity2" class="touch-slider"
- aria-labelledby="touchpad-speed-label">
- </div>
- <div id="mouse-settings" class="settings-row" hidden>
- <span id="mouse-speed-label" class="option-name">
- $i18n{mouseSpeed}
- </span>
- <input id="mouse-sensitivity-range" type="range" min="1" max="5"
- pref="settings.mouse.sensitivity2" class="touch-slider"
- aria-labelledby="mouse-speed-label">
- </div>
- <div id="no-pointing-devices" class="settings-row" hidden>
- $i18n{noPointingDevices}
- </div>
- <div class="settings-row">
- <button id="pointer-settings-button" hidden>
- </button>
- <button id="keyboard-settings-button">
- $i18n{keyboardSettingsButtonTitle}
- </button>
- <span id="display-options-section">
- <button id="display-options" disabled>$i18n{displayOptions}</button>
- </span>
- <button id="storage-manager-button">
- $i18n{storageManagerButtonTitle}
- </button>
- </div>
- <div id="stylus-row" hidden>
- <a is="action-link" id="stylus-settings-link">
- $i18n{stylusSettingsButtonTitle}
- </a>
- </div>
- <div id="power-row" hidden>
- <a is="action-link" id="power-settings-link">
- $i18n{powerSettingsButton}
- </a>
- </div>
- </div>
- </section>
-</if>
- <section id="search-section">
- <h3>$i18n{sectionTitleSearch}</h3>
- <div id="search-section-content">
- <span id="default-search-engine-label">
- $i18nRaw{defaultSearchGroupLabel}
- </span>
- <div class="settings-row">
- <select id="default-search-engine" class="weakrtl"
- aria-labelledby="default-search-engine-label"></select>
- <span class="controlled-setting-indicator"
- pref="default_search_provider_data.template_url_data">
- </span>
- <button id="manage-default-search-engines">
- $i18n{defaultSearchManageEngines}
- </button>
- </div>
- <div id="google-now-launcher" hidden>
- <div class="checkbox">
- <label>
- <input pref="google_now_launcher.enabled" type="checkbox">
- <span>$i18n{googleNowLauncherEnable}</span>
- </label>
- </div>
- </div>
- <div id="hotword-always-on-search" hidden>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="hotword-always-on-search-checkbox"
- pref="hotword.always_on_search_enabled" type="checkbox">
- <span>$i18n{hotwordSearchEnable}</span>
- </label>
- <a target="_blank" class="hotword-link"
- href="$i18nRaw{hotwordLearnMoreURL}">
- $i18n{learnMore}
- </a>
- <span id="hotword-always-on-search-setting-indicator"
- pref="hotword.always_on_search_enabled" dialog-pref></span>
- <div>
- <span class="setting-extra-description">
- $i18n{hotwordAlwaysOnDesc}
- </span>
- <a id="hotword-retrain-link" is="action-link" hidden>
- $i18n{hotwordRetrainLink}
- </a>
- </div>
- </div>
- </div>
- <div id="hotword-no-dsp-search" hidden>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="hotword-no-dsp-search-checkbox"
- pref="hotword.search_enabled_2" type="checkbox">
- <span>$i18n{hotwordSearchEnable}</span>
- </label>
- <a target="_blank" class="hotword-link"
- href="$i18nRaw{hotwordLearnMoreURL}">
- $i18n{learnMore}
- </a>
- <span id="hotword-no-dsp-search-setting-indicator"
- pref="hotword.search_enabled_2" dialog-pref></span>
- <div>
- <span class="setting-extra-description">
- $i18n{hotwordNoDSPDesc}
- </span>
- </div>
- </div>
- </div>
- <div id="audio-history" hidden>
- <div class="settings-row">
- <label class="hotword-audio-history">
- <span id="audio-history-label"></span>
- </label>
- <a target="_blank" class="hotword-link"
- href="$i18nRaw{hotwordManageAudioHistoryURL}">
- $i18n{hotwordAudioHistoryManage}
- </a>
- </div>
- <div class="settings-row" id="audio-history-always-on-description">
- <span class="setting-extra-description">
- $i18n{hotwordAlwaysOnAudioHistoryDescription}
- </span>
- </div>
- </div>
- </div>
- </section>
-<if expr="chromeos">
- <section id="android-apps-section" hidden>
- <h3>$i18n{androidAppsTitle}</h3>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="android-apps-enabled" pref="arc.enabled"
- metric="Options_AndroidApps" type="checkbox" dialog-pref>
- <span>
- <span>$i18n{androidAppsEnabled}</span>
- <span class="controlled-setting-indicator"
- pref="arc.enabled"></span>
- </span>
- </label>
- <a target="_blank" href="http://support.google.com/chromebook?p=playapps">
- $i18n{learnMore}
- </a>
- </div>
- <div id="android-apps-settings" class="controlled-setting-with-label"
- hidden>
- <label>
- <span id="android-apps-settings-label"></span>
- </label>
- </div>
- </section>
-</if>
- <section id="sync-users-section" guest-visibility="hidden">
- <h3>$i18n{sectionTitleUsers}</h3>
-<if expr="chromeos">
- <include src="sync_section.html">
-</if>
- <div id="profiles-section" hidden>
- <list id="profiles-list" class="settings-list" hidden></list>
- <div id="profiles-single-message" class="settings-row">
- $i18n{profilesSingleUser}
- </div>
-<if expr="not chromeos">
- <div id="profiles-enable-guest" class="checkbox">
- <label>
- <input pref="profile.browser_guest_enabled"
- type="checkbox"
- metric="Options_BrowserGuestEnabled">
- <span>$i18n{profileBrowserGuestEnable}</span>
- </label>
- </div>
- <div id="profiles-enable-add-person" class="checkbox">
- <label>
- <input pref="profile.add_person_enabled"
- type="checkbox"
- metric="Options_AddPersonEnabled">
- <span>$i18n{profileAddPersonEnable}</span>
- </label>
- </div>
-</if>
- <div id="profiles-buttons">
- <button id="profiles-create">$i18n{profilesCreate}</button>
- <button id="profiles-manage" disabled>$i18n{profilesManage}</button>
- <button id="profiles-delete">$i18n{profilesDelete}</button>
-<if expr="not chromeos">
- <button id="import-data">$i18n{importData}</button>
-</if>
- </div>
- </div>
- <div id="profiles-supervised-dashboard-tip" hidden>
- $i18nRaw{profilesSupervisedDashboardTip}
- </div>
- </section>
-<if expr="not chromeos">
- <section id="set-default-browser-section">
- <h3>$i18n{sectionTitleDefaultBrowser}</h3>
- <div>
- <button id="set-as-default-browser" hidden>
- $i18n{defaultBrowserUseAsDefault}
- </button>
- <div id="default-browser-state">$i18n{defaultBrowserUnknown}</div>
- </div>
- </section>
-</if> <!-- not chromeos -->
-<div id="advanced-settings" hidden>
-<div id="advanced-settings-container">
-<if expr="chromeos">
- <section id="date-time-section">
- <h3>$i18n{datetimeTitle}</h3>
- <div class="option-control-table">
- <div guest-visibility="disabled">
- <span id="timezone-value-label" class="option-name">
- $i18n{timezone}
- </span>
- <div id="timezone-value">
- <select class="control"
- id="timezone-value-select"
- i18n-options="timezoneList" data-type="string"
- pref="cros.system.timezone"
- aria-labelledby="timezone-value-label"
- metric="Options_TimezoneSelect"></select>
- </div>
- </div>
- <div class="checkbox settings-row">
- <div id="resolve-timezone-by-geolocation-selection" hidden>
- <label>
- <input id="resolve-timezone-by-geolocation"
- pref="settings.resolve_timezone_by_geolocation"
- metric="Options_ResolveTimezoneByGeoLocation" type="checkbox">
- <span>$i18n{resolveTimezoneByGeoLocation}</span>
- </label>
- </div>
- <label>
- <input id="use-24hour-clock" pref="settings.clock.use_24hour_clock"
- metric="Options_Use24HourClockCheckbox" type="checkbox">
- <span>$i18n{use24HourClock}</span>
- </label>
- </div>
- <div id="set-time" class="settings-row" hidden>
- <button id="set-time-button">$i18n{setTimeButton}</button>
- </div>
- </div>
- </section>
-</if>
- <section id="privacy-section">
- <h3>$i18n{advancedSectionTitlePrivacy}</h3>
- <div>
- <div class="settings-row">
- <button id="privacyContentSettingsButton">
- $i18n{privacyContentSettingsButton}
- </button>
- <button id="privacyClearDataButton">
- $i18n{privacyClearDataButton}
- </button>
- </div>
- <p id="privacy-explanation" class="settings-row">
- <span>$i18n{improveBrowsingExperience}</span>
- <span>$i18n{disableWebServices}</span>
- <a target="_blank" href="$i18nRaw{privacyLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </p>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="alternateErrorPagesEnabled"
- pref="alternate_error_pages.enabled"
- metric="Options_LinkDoctorCheckbox" type="checkbox">
- <span>
- <span>$i18n{linkDoctorPref}</span>
- <span class="controlled-setting-indicator"
- pref="alternate_error_pages.enabled"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label"
- guest-visibility="disabled">
- <label>
- <input pref="search.suggest_enabled"
- metric="Options_UseSuggestCheckbox" type="checkbox">
- <span>
- <span>$i18n{suggestPref}</span>
- <span class="controlled-setting-indicator"
- pref="search.suggest_enabled"></span>
- </span>
- </label>
- </div>
- <div class="checkbox" guest-visibility="disabled">
- <span class="controlled-setting-with-label">
- <label>
- <input id="networkPredictionOptions"
- metric="Options_DnsPrefetchCheckbox" type="checkbox">
- <span>
- <span>$i18n{networkPredictionEnabledDescription}</span>
- <span class="controlled-setting-indicator"
- pref="net.network_prediction_options"></span>
- </span>
- </label>
- </span>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input
- id="safeBrowsingExtendedReportingCheckbox"
- metric="Options_SafeBrowsingExtendedReportingCheckbox"
- type="checkbox">
- <span>
- <span>$i18n{safeBrowsingEnableExtendedReporting}</span>
- <span class="controlled-setting-indicator"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="safebrowsing.enabled"
- metric="Options_SafeBrowsingCheckbox" type="checkbox">
- <span>
- <span>$i18n{safeBrowsingEnableProtection}</span>
- <span class="controlled-setting-indicator"
- pref="safebrowsing.enabled"></span>
- </span>
- </label>
- </div>
- <div id="spelling-enabled-container"
- class="checkbox controlled-setting-with-label">
- <label>
- <input id="spelling-enabled-control" type="checkbox"
- metric="Options_SpellingServiceCheckbox"
- pref="spellcheck.use_spelling_service" dialog-pref>
- <span>
- <span>$i18n{spellingPref}</span>
- <span id="spelling-enabled-indicator"
- class="controlled-setting-indicator"
- pref="spellcheck.use_spelling_service" dialog-pref>
- </span>
- </label>
- </div>
-<if expr="_google_chrome">
- <div id="metrics-reporting-setting"
- class="checkbox controlled-setting-with-label">
- <label>
- <input id="metrics-reporting-enabled" type="checkbox">
- <span>
- <span>$i18n{enableLogging}</span>
- <span id="metrics-reporting-disabled-icon"
- class="controlled-setting-indicator"></span>
- </span>
- </label>
-<if expr="not chromeos">
- <span id="metrics-reporting-reset-restart" hidden>
- <!-- Text filled by JavaScript -->
- <span></span><a is="action-link" role="button"
- class="standalone-action-link"></a><span></span>
- </span>
-</if> <!-- not chromeos -->
- </div>
-</if> <!-- _google_chrome -->
- <div class="checkbox">
- <label>
- <input id="do-not-track-enabled" pref="enable_do_not_track"
- metric="Options_DoNotTrackCheckbox" type="checkbox" dialog-pref>
- <span>$i18n{doNotTrack}</span>
- </label>
- </div>
-<if expr="chromeos">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="content-protection-attestation-enabled" type="checkbox"
- pref="cros.device.attestation_for_content_protection_enabled">
- <span>
- <span>$i18n{enableContentProtectionAttestation}</span>
- <span class="controlled-setting-indicator"
- pref="cros.device.attestation_for_content_protection_enabled">
- </span>
- </span>
- </label>
- <a target="_blank"
- href="$i18nRaw{contentProtectionAttestationLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </div>
-</if>
- <div id="hotword-search" hidden>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="hotword-search-enable" pref="hotword.search_enabled_2"
- metric="Options_HotwordCheckbox" type="checkbox" dialog-pref>
- <span>
- <span>$i18nRaw{hotwordSearchEnable}</span>
- <span id="hotword-search-setting-indicator"
- pref="hotword.search_enabled_2" dialog-pref></span>
- </span>
- </label>
- </div>
- </div>
-<if expr="chromeos">
- <div id="wake-on-wifi" hidden
- class="checkbox controlled-setting-with-label">
- <label>
- <input id="wake-on-wifi-checkbox" type="checkbox"
- metric="Options_WakeOnWifiSsid"
- pref="settings.internet.wake_on_wifi_darkconnect">
- <span>
- <span>$i18n{wakeOnWifiLabel}</span>
- <span id="wake-on-wifi-indicator"
- class="controlled-setting-indicator"
- pref="settings.internet.wake_on_wifi_darkconnect"></span>
- </span>
- </label>
- </div>
-</if>
- </div>
- </section>
-<if expr="chromeos">
- <!-- By default, the bluetooth section is hidden. It is only visible if a
- bluetooth adapter is discovered -->
- <section id="bluetooth-devices" hidden>
- <h3>$i18n{bluetooth}</h3>
- <div id="bluetooth-options-div">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input type="checkbox" id="enable-bluetooth"
- metric="Options_BluetoothEnabled">
- <span>
- <span>$i18n{enableBluetooth}</span>
- <span id="bluetooth-controlled-setting-indicator"
- class="controlled-setting-indicator"
- pref="cros.device.allow_bluetooth"
- hidden="true">
- </span>
- </span>
- </label>
- </div>
- <div class="settings-list bluetooth-device-list" hidden>
- <list id="bluetooth-paired-devices-list"></list>
- <div id="bluetooth-paired-devices-list-empty-placeholder"
- class="bluetooth-empty-list-label" hidden>
- <span>$i18n{bluetoothNoDevices}</span>
- </div>
- </div>
- <div id="bluetooth-button-group">
- <button id="bluetooth-add-device" hidden>
- $i18n{addBluetoothDevice}
- </button>
- <button id="bluetooth-reconnect-device" disabled hidden>
- $i18n{bluetoothConnectDevice}
- </button>
- </div>
- </div>
- </section>
-</if>
- <section id="passwords-and-autofill-section">
- <h3>$i18n{passwordsAndAutofillGroupName}</h3>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="autofill-enabled" pref="autofill.enabled"
- metric="Options_FormAutofill" type="checkbox">
- <span>
- <span>$i18n{autofillEnabled}</span>
- <span class="controlled-setting-indicator" pref="autofill.enabled">
- </span>
- </span>
- </label>
- <a is="action-link" id="autofill-settings">
- $i18n{manageAutofillSettings}
- </a>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="password-manager-enabled"
- pref="credentials_enable_service"
- metric="Options_PasswordManager" type="checkbox">
- <span>
- <span>$i18n{passwordManagerEnabled}</span>
- <span class="controlled-setting-indicator"
- pref="credentials_enable_service"></span>
- </span>
- </label>
- <a is="action-link" id="manage-passwords">$i18n{managePasswords}</a>
- </div>
-<if expr="is_macosx">
- <div id="mac-passwords-warning" hidden>$i18n{macPasswordsWarning}</div>
-</if>
- </section>
- <section id="easy-unlock-section" guest-visibility="hidden" hidden>
- <h3>$i18n{easyUnlockSectionTitle}</h3>
- <!-- Options shown when the user has not set up Easy Unlock -->
- <div id="easy-unlock-disabled" hidden>
- <div class="settings-row">
- <span>$i18n{easyUnlockSetupIntro}</span>
- <a target="_blank" href="$i18nRaw{easyUnlockLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </div>
- <button id="easy-unlock-setup-button">
- $i18n{easyUnlockSetupButton}
- </button>
- </div>
- <!-- Options shown when the user has set up Easy Unlock -->
- <div id="easy-unlock-enabled" hidden>
- <div class="settings-row">
- <span>$i18n{easyUnlockDescription}</span>
- <a target="_blank" href="$i18nRaw{easyUnlockLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </div>
- <button id="easy-unlock-turn-off-button">
- $i18n{easyUnlockTurnOffButton}
- </button>
- </div>
- </section>
- <section id="web-content-section">
- <h3>$i18n{advancedSectionTitleContent}</h3>
- <div>
- <div class="settings-row">
- <label class="web-content-select-label">
- <span>$i18n{defaultFontSizeLabel}</span>
- <select id="defaultFontSize">
- <option value="9">$i18n{fontSizeLabelVerySmall}</option>
- <option value="12">$i18n{fontSizeLabelSmall}</option>
- <option value="16">$i18n{fontSizeLabelMedium}</option>
- <option value="20">$i18n{fontSizeLabelLarge}</option>
- <option value="24">$i18n{fontSizeLabelVeryLarge}</option>
- </select>
- </label>
- <span id="font-size-indicator"
- class="controlled-setting-indicator"></span>
- <button id="fontSettingsCustomizeFontsButton">
- $i18n{fontSettingsCustomizeFontsButton}
- </button>
- </div>
- <div class="settings-row" guest-visibility="disabled">
- <label class="web-content-select-label">
- <span>$i18n{defaultZoomFactorLabel}</span>
- <select id="defaultZoomFactor" dataType="double"></select>
- </label>
- </div>
-<if expr="is_macosx">
- <div class="checkbox">
- <label>
- <input id="tabsToLinksPref" pref="webkit.webprefs.tabs_to_links"
- metric="Options_TabsToLinks" type="checkbox">
- <span>$i18n{tabsToLinksPref}</span>
- </label>
- </div>
-</if>
- </div>
- </section>
-<if expr="not chromeos">
- <section id="network-section">
- <h3>$i18n{advancedSectionTitleNetwork}</h3>
- <div>
- <span id="proxiesLabel" class="settings-row">
- $i18n{proxiesLabelSystem}
- </span>
- <div class="settings-row">
- <button id="proxiesConfigureButton">
- $i18n{proxiesConfigureButton}
- </button>
- <span class="controlled-setting-indicator" pref="proxy" plural></span>
- </div>
- </div>
- </section>
-</if>
- <section id="languages-section">
- <h3>$i18n{advancedSectionTitleLanguages}</h3>
- <div class="settings-row">
- <span>$i18n{languageSectionLabel}</span>
- <a target="_blank" href="$i18nRaw{languagesLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </div>
- <div class="settings-row">
- <button id="language-button">
- $i18n{languageAndSpellCheckSettingsButton}
- </button>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="translate.enabled"
- metric="Options_Translate" type="checkbox">
- <span>
- <span>$i18n{translateEnableTranslate}</span>
- <span class="controlled-setting-indicator" pref="translate.enabled">
- </span>
- </span>
- </label>
- <a is="action-link" id="manage-languages">$i18n{manageLanguages}</a>
- </div>
- </section>
- <section id="downloads-section">
- <h3>$i18n{downloadLocationGroupName}</h3>
- <div>
- <div class="settings-row">
- <label>
- <span id="download-location-label">
- $i18n{downloadLocationBrowseTitle}
- </span>
- <input id="downloadLocationPath" class="weakrtl" type="text"
- size="36" readonly>
- </label>
- <button id="downloadLocationChangeButton">
- $i18n{downloadLocationChangeButton}
- </button>
- <span class="controlled-setting-indicator"
- pref="download.default_directory">
- </span>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input type="checkbox"
- pref="download.prompt_for_download"
- metric="Options_AskForSaveLocation">
- <span>
- <span>$i18n{downloadLocationAskForSaveLocation}</span>
- <span class="controlled-setting-indicator"
- pref="download.prompt_for_download"></span>
- </span>
- </label>
- </div>
-<if expr="chromeos">
- <div class="checkbox controlled-setting-with-label"
- id="disable-drive-row" guest-visibility="disabled">
- <label>
- <input type="checkbox"
- pref="gdata.disabled"
- metric="Options_DisableGData">
- <span>
- <span>$i18n{disableGData}</span>
- <span class="controlled-setting-indicator" pref="gdata.disabled">
- </span>
- </span>
- </label>
- </div>
-</if>
- <div id="auto-open-file-types-section" hidden>
- <div id="auto-open-file-types-container">
- <div id="auto-open-file-types-label" class="settings-row">
- $i18n{autoOpenFileTypesInfo}
- </div>
- <div class="settings-row">
- <button id="autoOpenFileTypesResetToDefault">
- $i18n{autoOpenFileTypesResetToDefault}
- </button>
- </div>
- </div>
- </div>
- </div>
- </section>
- <section id="certificates-section">
- <h3>$i18n{advancedSectionTitleCertificates}</h3>
- <div>
-<if expr="use_nss_certs or is_win or is_macosx">
- <div class="settings-row">
- <button id="certificatesManageButton">
- $i18n{certificatesManageButton}
- </button>
- </div>
-</if>
- </div>
- </section>
-<if expr="chromeos">
- <section id="cups-printers-section" hidden>
- <h3>$i18n{advancedSectionTitleCupsPrint}</h3>
- <div class="settings-row">
- <span>$i18n{cupsPrintOptionLabel}</span>
- <a target="_blank" href="$i18nRaw{cupsPrintLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </div>
- <div class="settings-row">
- <button id="cupsPrintersManageButton">
- $i18n{cupsPrintersManageButton}
- </button>
- </div>
- </section>
-</if>
-<if expr="enable_service_discovery">
- <section id="cloudprint-options-mdns">
- <h3>$i18n{advancedSectionTitleCloudPrint}</h3>
- <div class="settings-row">
- <span>$i18n{cloudPrintOptionLabel}</span>
- <a target="_blank" href="$i18nRaw{cloudPrintLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </div>
- <div class="settings-row">
- <button id="cloudPrintDevicesPageButton">
- $i18n{cloudPrintDevicesPageButton}
- </button>
- </div>
-
- <div class="settings-row checkbox controlled-setting-with-label"
- i18n-values=".hidden: cloudPrintHideNotificationsCheckbox">
- <label>
- <input id="local-discovery-notifications-enabled"
- pref="local_discovery.notifications_enabled"
- type="checkbox"
- metric="LocalDiscoveryNotificationsDisabled_Settings">
- <span>
- <span>$i18n{cloudPrintEnableNotificationsLabel}</span>
- <span class="controlled-setting-indicator"
- pref="local_discovery.notifications_enabled"></span>
- </span>
- </label>
- </div>
- </section>
-</if>
-
-<if expr="chromeos">
- <include src="startup_section.html">
-</if>
-
-<section id="a11y-section">
- <h3>$i18n{accessibilityTitle}</h3>
-
- <div>
- <a href="https://chrome.google.com/webstore/category/collection/accessibility"
- id="accessibility-features" target="_blank">
- $i18n{accessibilityFeaturesLink}
- </a>
- </div>
-
-<if expr="chromeos">
- <div class="option-control-table">
- <p id="accessibility-explanation" class="settings-row">
- <span>$i18n{accessibilityExplanation}</span>
- <a id="accessibility-learn-more" target="_blank"
- href="$i18nRaw{accessibilityLearnMoreURL}">
- $i18n{learnMore}
- </a>
- </p>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input
- pref="settings.a11y.enable_menu" type="checkbox"
- metric="Options_AccessibilitySystemMenu">
- <span>
- <span>$i18n{accessibilityAlwaysShowMenu}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.enable_menu"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input
- pref="settings.a11y.large_cursor_enabled" type="checkbox"
- metric="Options_AccessibilityLargeMouseCursor">
- <span>
- <span>$i18n{accessibilityLargeCursor}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.large_cursor_enabled"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="accessibility-high-contrast-check"
- pref="settings.a11y.high_contrast_enabled" type="checkbox"
- metric="Options_AccessibilityHighContrastMode">
- <span>
- <span>$i18n{accessibilityHighContrast}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.high_contrast_enabled"></span>
- </span>
- </label>
- </div>
- </div>
- <div id="accessibility-sticky-keys" class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="accessibility-sticky-keys-check"
- pref="settings.a11y.sticky_keys_enabled" type="checkbox"
- metric="Options_AccessibilityStickyKeys">
- <span>
- <span>$i18n{accessibilityStickyKeys}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.sticky_keys_enabled"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="accessibility-spoken-feedback-check"
- pref="settings.accessibility" type="checkbox"
- metric="Options_AccessibilitySpokenFeedback">
- <span>
- <span>$i18n{accessibilitySpokenFeedback}</span>
- <span class="controlled-setting-indicator"
- pref="settings.accessibility"></span>
- </span>
- </label>
- <div id="accessibility-settings" hidden>
- <button id="accessibility-settings-button">
- $i18n{accessibilitySettings}
- </button>
- <button id="talkback-settings-button">
- $i18n{accessibilityTalkBackSettings}
- </button>
- </div>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input
- id="accessibility-screen-magnifier-check"
- pref="settings.a11y.screen_magnifier" type="checkbox"
- metric="Options_AccessibilityScreenMagnifier">
- <span>
- <span>$i18n{accessibilityScreenMagnifier}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.screen_magnifier"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <!-- No whitespace between elements. -->
- <input type="checkbox" class="spacer-checkbox">
- <label>
- <input
- id = "accessibility-screen-magnifier-center-focus-check"
- pref="settings.a11y.screen_magnifier_center_focus" type="checkbox"
- metric="Options_AccessibilityScreenMagnifierCenterFocus">
- <span>
- <span>$i18n{accessibilityScreenMagnifierCenterFocus}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.screen_magnifier_center_focus"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name" id="accessibility-tap-dragging">
- <div class="checkbox">
- <label>
- <input id="accessibility-tap-dragging-check"
- pref="settings.touchpad.enable_tap_dragging" type="checkbox"
- metric="Options_AccessibilityTapDragging">
- <span>$i18n{accessibilityTapDragging}</span>
- </label>
- </div>
- </div>
- <div class="option-name" id="accessibility-autoclick">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="accessibility-autoclick-check"
- pref="settings.a11y.autoclick" type="checkbox">
- <span>
- <span>$i18n{accessibilityAutoclick}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.autoclick"></span>
- </span>
- </label>
- </div>
- <div class="checkbox">
- <!-- No whitespace between elements. -->
- <input type="checkbox" class="spacer-checkbox">
- <span id="accessibility-autoclick-label">
- $i18n{accessibilityAutoclickDropdown}
- </span>
- <select id="accessibility-autoclick-dropdown" class="control"
- data-type="number"
- aria-labelledby="accessibility-autoclick-label"
- pref="settings.a11y.autoclick_delay_ms">
- <!-- i18n strings contain the autoclick duration; if the autoclick
- timing gets changed, then the i18n strings also needs to be
- updated. -->
- <option value="600">$i18n{autoclickDelayExtremelyShort}</option>
- <option value="800">$i18n{autoclickDelayVeryShort}</option>
- <option value="1000">$i18n{autoclickDelayShort}</option>
- <option value="2000">$i18n{autoclickDelayLong}</option>
- <option value="4000">$i18n{autoclickDelayVeryLong}</option>
- </select>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.autoclick_delay_ms"></span>
- </div>
- </div>
- <div class="option-name" id="accessibility_onscreen_keyboard">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.virtual_keyboard" type="checkbox"
- metric="Options_AccessibilityOnScreenKeyboard">
- <span>
- <span>$i18n{accessibilityVirtualKeyboard}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.virtual_keyboard"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name" id="accessibility_mono_audio">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.mono_audio" type="checkbox"
- metric="Options_AccessibilityMonoAudio">
- <span>
- <span>$i18n{accessibilityMonoAudio}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.mono_audio"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.caret_highlight" type="checkbox"
- metric="Options_AccessibilityCaretHighlight">
- <span>
- <span>$i18n{accessibilityCaretHighlight}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.caret_highlight"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.cursor_highlight" type="checkbox"
- metric="Options_AccessibilityCursorHighlight">
- <span>
- <span>$i18n{accessibilityCursorHighlight}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.cursor_highlight"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.focus_highlight" type="checkbox"
- metric="Options_AccessibilityFocusHighlight">
- <span>
- <span>$i18n{accessibilityFocusHighlight}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.focus_highlight"></span>
- </span>
- </label>
- </div>
- </div>
- <div id="experimental-accessibility-features" hidden>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.select_to_speak" type="checkbox"
- metric="Options_AccessibilitySelectToSpeak">
- <span>
- <span>$i18n{accessibilitySelectToSpeak}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.select_to_speak"></span>
- </span>
- </label>
- </div>
- </div>
- <div class="option-name">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="settings.a11y.switch_access" type="checkbox"
- metric="Options_AccessibilitySwitchAccess">
- <span>
- <span>$i18n{accessibilitySwitchAccess}</span>
- <span class="controlled-setting-indicator"
- pref="settings.a11y.switch_access"></span>
- </span>
- </label>
- </div>
- </div>
- </div>
- </div>
-</if>
-
-</section>
-
-<if expr="chromeos">
- <section id="factory-reset-section" hidden>
- <h3>$i18n{factoryResetTitle}</h3>
- <div>
- <span class="settings-row">$i18n{factoryResetDescription}</span>
- <button id="factory-reset-restart">$i18n{factoryResetRestart}</button>
- </div>
- </section>
-</if>
-<if expr="not chromeos">
- <section id="system-section">
- <h3>$i18n{advancedSectionTitleSystem}</h3>
-<if expr="not is_macosx">
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="background_mode.enabled"
- type="checkbox">
- <span>
- <span>$i18n{backgroundModeCheckbox}</span>
- <span class="controlled-setting-indicator"
- pref="background_mode.enabled"></span>
- </span>
- </label>
- </div>
-</if>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="gpu-mode-checkbox"
- pref="hardware_acceleration_mode.enabled" type="checkbox">
- <span>
- <span>$i18n{gpuModeCheckbox}</span>
- <span class="controlled-setting-indicator"
- pref="hardware_acceleration_mode.enabled"></span>
- </span>
- </label>
- <span id="gpu-mode-reset-restart">$i18nRaw{gpuModeResetRestart}</span>
- </div>
- </section>
-</if>
- <section id="reset-profile-settings-section">
- <h3>$i18n{resetProfileSettingsSectionTitle}</h3>
- <div>
- <span class="settings-row">$i18n{resetProfileSettingsDescription}</span>
- <button id="reset-profile-settings">$i18n{resetProfileSettings}</button>
- </div>
- </section>
- </div> <!-- advanced-settings-container -->
- </div> <!-- advanced-settings -->
- <footer id="advanced-settings-footer">
- <a is="action-link" id="advanced-settings-expander">
- $i18n{showAdvancedSettings}
- </a>
- </footer>
-</div>
diff --git a/chromium/chrome/browser/resources/options/browser_options.js b/chromium/chrome/browser/resources/options/browser_options.js
deleted file mode 100644
index 011ef0ce10d..00000000000
--- a/chromium/chrome/browser/resources/options/browser_options.js
+++ /dev/null
@@ -1,2487 +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.
-
-cr.exportPath('options');
-
-/**
- * @typedef {{actionLinkText: (string|undefined),
- * accountInfo: (string|undefined),
- * childUser: (boolean|undefined),
- * hasError: (boolean|undefined),
- * hasUnrecoverableError: (boolean|undefined),
- * managed: (boolean|undefined),
- * setupCompleted: (boolean|undefined),
- * setupInProgress: (boolean|undefined),
- * signedIn: (boolean|undefined),
- * signinAllowed: (boolean|undefined),
- * signoutAllowed: (boolean|undefined),
- * statusAction: (string|undefined),
- * statusText: (string|undefined),
- * supervisedUser: (boolean|undefined),
- * syncSystemEnabled: (boolean|undefined)}}
- * @see chrome/browser/ui/webui/options/browser_options_handler.cc
- */
-options.SyncStatus;
-
-/**
- * @typedef {{id: string, name: string}}
- */
-options.ExtensionData;
-
-/**
- * @typedef {{name: string,
- * filePath: string,
- * isCurrentProfile: boolean,
- * isSupervised: boolean,
- * isChild: boolean,
- * iconUrl: string}}
- * @see chrome/browser/ui/webui/options/browser_options_handler.cc
- */
-options.Profile;
-
-/**
- * Device policy SystemTimezoneAutomaticDetection values.
- * @enum {number}
- * @const
- */
-options.AutomaticTimezoneDetectionType = {
- USERS_DECIDE: 0,
- DISABLED: 1,
- IP_ONLY: 2,
- SEND_WIFI_ACCESS_POINTS: 3,
- SEND_ALL_LOCATION_INFO: 4,
-};
-
-cr.define('options', function() {
- var OptionsPage = options.OptionsPage;
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
- var ArrayDataModel = cr.ui.ArrayDataModel;
- var RepeatingButton = cr.ui.RepeatingButton;
- var HotwordSearchSettingIndicator = options.HotwordSearchSettingIndicator;
- var NetworkPredictionOptions = {
- ALWAYS: 0,
- WIFI_ONLY: 1,
- NEVER: 2,
- DEFAULT: 1
- };
-
- /**
- * Encapsulated handling of browser options page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function BrowserOptions() {
- Page.call(this, 'settings', loadTimeData.getString('settingsTitle'),
- 'settings');
- }
-
- cr.addSingletonGetter(BrowserOptions);
-
- /**
- * @param {HTMLElement} section The section to show or hide.
- * @return {boolean} Whether the section should be shown.
- * @private
- */
- BrowserOptions.shouldShowSection_ = function(section) {
- // If the section is hidden or hiding, it should be shown.
- return section.style.height == '' || section.style.height == '0px';
- };
-
- BrowserOptions.prototype = {
- __proto__: Page.prototype,
-
- /**
- * Keeps track of whether the user is signed in or not.
- * @private {boolean}
- */
- signedIn_: false,
-
- /**
- * Indicates whether signing out is allowed or whether a complete profile
- * wipe is required to remove the current enterprise account.
- * @private {boolean}
- */
- signoutAllowed_: true,
-
- /**
- * Keeps track of whether |onShowHomeButtonChanged_| has been called. See
- * |onShowHomeButtonChanged_|.
- * @private {boolean}
- */
- onShowHomeButtonChangedCalled_: false,
-
- /**
- * Track if page initialization is complete. All C++ UI handlers have the
- * chance to manipulate page content within their InitializePage methods.
- * This flag is set to true after all initializers have been called.
- * @private {boolean}
- */
- initializationComplete_: false,
-
- /**
- * Current status of "Resolve Timezone by Geolocation" checkbox.
- * @private {boolean}
- */
- resolveTimezoneByGeolocation_: false,
-
- /**
- * True if system timezone is managed by policy.
- * @private {boolean}
- */
- systemTimezoneIsManaged_: false,
-
- /**
- * True if system timezone detection is managed by policy.
- * @private {boolean}
- */
- systemTimezoneAutomaticDetectionIsManaged_: false,
-
- /**
- * This is the value of SystemTimezoneAutomaticDetection policy.
- * @private {number}
- */
- systemTimezoneAutomaticDetectionValue_: 0,
-
- /**
- * Cached bluetooth adapter state.
- * @private {?chrome.bluetooth.AdapterState}
- */
- bluetoothAdapterState_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
- var self = this;
-
- if (window.top != window) {
- // The options page is not in its own window.
- document.body.classList.add('uber-frame');
- PageManager.horizontalOffset = 155;
- }
-
- // Ensure that navigation events are unblocked on uber page. A reload of
- // the settings page while an overlay is open would otherwise leave uber
- // page in a blocked state, where tab switching is not possible.
- uber.invokeMethodOnParent('stopInterceptingEvents');
-
- window.addEventListener('message', this.handleWindowMessage_.bind(this));
-
- if (loadTimeData.getBoolean('allowAdvancedSettings')) {
- $('advanced-settings-expander').onclick = function(e) {
- var showAdvanced =
- BrowserOptions.shouldShowSection_($('advanced-settings'));
- if (showAdvanced) {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowAdvancedSettings']);
- }
- self.toggleSectionWithAnimation_(
- $('advanced-settings'),
- $('advanced-settings-container'));
-
- // If the click was triggered using the keyboard and it showed the
- // section (rather than hiding it), focus the first element in the
- // container.
- if (e.detail == 0 && showAdvanced) {
- var focusElement = $('advanced-settings-container').querySelector(
- 'button, input, list, select, a[href]');
- if (focusElement)
- focusElement.focus();
- }
- };
- } else {
- $('advanced-settings-footer').hidden = true;
- $('advanced-settings').hidden = true;
- }
-
- $('advanced-settings').addEventListener('transitionend',
- this.updateAdvancedSettingsExpander_.bind(this));
-
- if (loadTimeData.valueExists('aboutOverlayTabTitle')) {
- $('about-button').hidden = false;
- $('about-button').addEventListener('click', function() {
- PageManager.showPageByName('help');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_About']);
- });
- }
-
- if (cr.isChromeOS) {
- UIAccountTweaks.applyGuestSessionVisibility(document);
- UIAccountTweaks.applyPublicSessionVisibility(document);
- if (loadTimeData.getBoolean('secondaryUser'))
- $('secondary-user-banner').hidden = false;
- }
-
- // Sync (Sign in) section.
- this.updateSyncState_(/** @type {options.SyncStatus} */(
- loadTimeData.getValue('syncData')));
- if (!$('sync-overview').hidden) {
- chrome.send('metricsHandler:recordAction',
- ['Signin_Impression_FromSettings']);
- }
-
- $('start-stop-sync').onclick = function(event) {
- if (self.signedIn_) {
- if (self.signoutAllowed_)
- SyncSetupOverlay.showStopSyncingUI();
- else
- chrome.send('showDisconnectManagedProfileDialog');
- } else if (cr.isChromeOS) {
- SyncSetupOverlay.showSetupUI();
- } else {
- SyncSetupOverlay.startSignIn(false /* creatingSupervisedUser */);
- }
- };
- $('customize-sync').onclick = function(event) {
- SyncSetupOverlay.showSetupUI();
- };
-
- // Internet connection section (ChromeOS only).
- if (cr.isChromeOS) {
- options.network.NetworkList.decorate($('network-list'));
- // Show that the network settings are shared if this is a secondary user
- // in a multi-profile session.
- if (loadTimeData.getBoolean('secondaryUser')) {
- var networkIndicator = document.querySelector(
- '#network-section-header > .controlled-setting-indicator');
- networkIndicator.setAttribute('controlled-by', 'shared');
- networkIndicator.location = cr.ui.ArrowLocation.TOP_START;
- }
- }
-
- // On Startup section.
- Preferences.getInstance().addEventListener('session.restore_on_startup',
- this.onRestoreOnStartupChanged_.bind(this));
- Preferences.getInstance().addEventListener(
- 'session.startup_urls',
- function(event) {
- $('startup-set-pages').disabled = event.value.disabled;
- });
-
- $('startup-set-pages').onclick = function() {
- PageManager.showPageByName('startup');
- };
-
- // Appearance section.
- Preferences.getInstance().addEventListener('browser.show_home_button',
- this.onShowHomeButtonChanged_.bind(this));
-
- Preferences.getInstance().addEventListener('homepage',
- this.onHomePageChanged_.bind(this));
- Preferences.getInstance().addEventListener('homepage_is_newtabpage',
- this.onHomePageIsNtpChanged_.bind(this));
-
- $('change-home-page').onclick = function(event) {
- PageManager.showPageByName('homePageOverlay');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_Homepage_ShowSettings']);
- };
-
- HotwordSearchSettingIndicator.decorate(
- $('hotword-search-setting-indicator'));
- HotwordSearchSettingIndicator.decorate(
- $('hotword-no-dsp-search-setting-indicator'));
- var hotwordIndicator = $('hotword-always-on-search-setting-indicator');
- HotwordSearchSettingIndicator.decorate(hotwordIndicator);
- hotwordIndicator.disabledOnErrorSection =
- $('hotword-always-on-search-checkbox');
- chrome.send('requestHotwordAvailable');
-
- chrome.send('requestGoogleNowAvailable');
-
- if ($('set-wallpaper')) {
- $('set-wallpaper').onclick = function(event) {
- chrome.send('openWallpaperManager');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_OpenWallpaperManager']);
- };
- }
-
- // Control the hotword-always-on pref with the Hotword Audio
- // Verification app.
- $('hotword-always-on-search-checkbox').customChangeHandler =
- function(event) {
- if (!$('hotword-always-on-search-checkbox').checked)
- return false;
-
- $('hotword-always-on-search-checkbox').checked = false;
- chrome.send('launchHotwordAudioVerificationApp', [false]);
- return true;
- };
-
- // Open the Hotword Audio Verification app to retrain a voice model.
- $('hotword-retrain-link').onclick = function(event) {
- chrome.send('launchHotwordAudioVerificationApp', [true]);
- };
- Preferences.getInstance().addEventListener(
- 'hotword.always_on_search_enabled',
- this.onHotwordAlwaysOnChanged_.bind(this));
-
- $('themes-gallery').onclick = function(event) {
- window.open(loadTimeData.getString('themesGalleryURL'));
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ThemesGallery']);
- };
- $('themes-reset').onclick = function(event) {
- chrome.send('themesReset');
- };
-
- if (loadTimeData.getBoolean('profileIsSupervised')) {
- if ($('themes-native-button')) {
- $('themes-native-button').disabled = true;
- $('themes-native-button').hidden = true;
- }
- // Supervised users have just one default theme, even on Linux. So use
- // the same button for Linux as for the other platforms.
- $('themes-reset').textContent = loadTimeData.getString('themesReset');
- }
-
- // Device section (ChromeOS only).
- if (cr.isChromeOS) {
- // Probe for stylus hardware state. C++ will invoke
- // BrowserOptions.setStylusInputStatus_ when the data is available.
- chrome.send('requestStylusHardwareState');
-
- if (loadTimeData.getBoolean('showPowerStatus')) {
- $('power-settings-link').onclick = function(evt) {
- PageManager.showPageByName('power-overlay');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowPowerSettings']);
- };
- $('power-row').hidden = false;
- }
- $('keyboard-settings-button').onclick = function(evt) {
- PageManager.showPageByName('keyboard-overlay');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowKeyboardSettings']);
- };
- $('pointer-settings-button').onclick = function(evt) {
- PageManager.showPageByName('pointer-overlay');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowTouchpadSettings']);
- };
- $('storage-manager-button').onclick = function(evt) {
- PageManager.showPageByName('storage');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowStorageManager']);
- };
- }
-
- // Search section.
- $('manage-default-search-engines').onclick = function(event) {
- PageManager.showPageByName('searchEngines');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ManageSearchEngines']);
- };
- $('default-search-engine').addEventListener('change',
- this.setDefaultSearchEngine_);
-
- // Users section.
- if (loadTimeData.valueExists('profilesInfo')) {
- $('profiles-section').hidden = false;
- this.maybeShowUserSection_();
-
- var profilesList = $('profiles-list');
- options.browser_options.ProfileList.decorate(profilesList);
- profilesList.autoExpands = true;
-
- // The profiles info data in |loadTimeData| might be stale.
- this.setProfilesInfo_(/** @type {!Array<!options.Profile>} */(
- loadTimeData.getValue('profilesInfo')));
- chrome.send('requestProfilesInfo');
-
- profilesList.addEventListener('change',
- this.setProfileViewButtonsStatus_);
- $('profiles-create').onclick = function(event) {
- chrome.send('metricsHandler:recordAction',
- ['Options_ShowCreateProfileDlg']);
- ManageProfileOverlay.showCreateDialog();
- };
- $('profiles-manage').onclick = function(event) {
- chrome.send('metricsHandler:recordAction',
- ['Options_ShowEditProfileDlg']);
- ManageProfileOverlay.showManageDialog();
- };
- $('profiles-delete').onclick = function(event) {
- var selectedProfile = self.getSelectedProfileItem_();
- if (selectedProfile) {
- chrome.send('metricsHandler:recordAction',
- ['Options_ShowDeleteProfileDlg']);
- ManageProfileOverlay.showDeleteDialog(selectedProfile);
- }
- };
- if (loadTimeData.getBoolean('profileIsSupervised')) {
- $('profiles-create').disabled = true;
- }
- if (!loadTimeData.getBoolean('allowProfileDeletion')) {
- $('profiles-delete').disabled = true;
- $('profiles-list').canDeleteItems = false;
- }
- }
-
- if (cr.isChromeOS) {
- // Username (canonical email) of the currently logged in user or
- // |kGuestUser| if a guest session is active.
- this.username_ = loadTimeData.getString('username');
-
- this.updateAccountPicture_();
-
- $('account-picture').onclick = this.showImagerPickerOverlay_;
- $('change-picture-caption').onclick = this.showImagerPickerOverlay_;
-
- $('manage-accounts-button').onclick = function(event) {
- PageManager.showPageByName('accounts');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ManageAccounts']);
- };
-
- if (loadTimeData.getBoolean('showQuickUnlockSettings')) {
- $('manage-screenlock').onclick = function(event) {
- PageManager.showPageByName('quickUnlockConfigureOverlay');
- settings.recordLockScreenProgress(
- LockScreenProgress.START_SCREEN_LOCK);
- };
- $('manage-screenlock').hidden = false;
- }
- } else {
- $('import-data').onclick = function(event) {
- ImportDataOverlay.show();
- chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']);
- };
-
- if ($('themes-native-button')) {
- $('themes-native-button').onclick = function(event) {
- chrome.send('themesSetNative');
- };
- }
- }
-
- // Date and time section (CrOS only).
- if (cr.isChromeOS) {
- if ($('set-time-button'))
- $('set-time-button').onclick = this.handleSetTime_.bind(this);
-
- // Timezone
- if (loadTimeData.getBoolean('enableTimeZoneTrackingOption')) {
- $('resolve-timezone-by-geolocation-selection').hidden = false;
- this.resolveTimezoneByGeolocation_ = loadTimeData.getBoolean(
- 'resolveTimezoneByGeolocationInitialValue');
- this.updateTimezoneSectionState_();
- Preferences.getInstance().addEventListener(
- 'settings.resolve_timezone_by_geolocation',
- this.onResolveTimezoneByGeolocationChanged_.bind(this));
- }
- }
-
- // Default browser section.
- if (!cr.isChromeOS) {
- if (!loadTimeData.getBoolean('showSetDefault')) {
- $('set-default-browser-section').hidden = true;
- }
- $('set-as-default-browser').onclick = function(event) {
- chrome.send('becomeDefaultBrowser');
- };
- }
-
- // Privacy section.
- $('privacyContentSettingsButton').onclick = function(event) {
- PageManager.showPageByName('content');
- OptionsPage.showTab($('cookies-nav-tab'));
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ContentSettings']);
- };
- $('privacyClearDataButton').onclick = function(event) {
- PageManager.showPageByName('clearBrowserData');
- chrome.send('coreOptionsUserMetricsAction', ['Options_ClearData']);
- };
-
- if ($('metrics-reporting-enabled')) {
- $('metrics-reporting-enabled').checked =
- loadTimeData.getBoolean('metricsReportingEnabledAtStart');
-
- // A browser restart is never needed to toggle metrics reporting,
- // and is only needed to toggle crash reporting when using Breakpad.
- // Crashpad, used on Mac, does not require a browser restart.
- var togglingMetricsRequiresRestart = !cr.isMac && !cr.isChromeOS;
- $('metrics-reporting-enabled').onclick = function(event) {
- chrome.send('metricsReportingCheckboxChanged',
- [Boolean(event.currentTarget.checked)]);
- if (cr.isChromeOS) {
- // 'metricsReportingEnabled' element is only present on Chrome
- // branded builds, and the 'metricsReportingCheckboxAction' message
- // is only handled on ChromeOS.
- chrome.send('metricsReportingCheckboxAction',
- [String(event.currentTarget.checked)]);
- }
-
- if (togglingMetricsRequiresRestart) {
- $('metrics-reporting-reset-restart').hidden =
- loadTimeData.getBoolean('metricsReportingEnabledAtStart') ==
- $('metrics-reporting-enabled').checked;
- }
-
- };
-
- // Initialize restart button if needed.
- if (togglingMetricsRequiresRestart) {
- // The localized string has the | symbol on each side of the text that
- // needs to be made into a button to restart Chrome. We parse the text
- // and build the button from that.
- var restartTextFragments =
- loadTimeData.getString('metricsReportingResetRestart').split('|');
- // Assume structure is something like "starting text |link text|
- // ending text" where both starting text and ending text may or may
- // not be present, but the split should always be in three pieces.
- var restartElements =
- $('metrics-reporting-reset-restart').querySelectorAll('*');
- for (var i = 0; i < restartTextFragments.length; i++) {
- restartElements[i].textContent = restartTextFragments[i];
- }
- restartElements[1].onclick = function(event) {
- chrome.send('restartBrowser');
- };
- }
- }
- $('networkPredictionOptions').onchange = function(event) {
- var value = (event.target.checked ?
- NetworkPredictionOptions.WIFI_ONLY :
- NetworkPredictionOptions.NEVER);
- var metric = event.target.metric;
- Preferences.setIntegerPref(
- 'net.network_prediction_options',
- value,
- true,
- metric);
- };
- if (loadTimeData.valueExists('showWakeOnWifi') &&
- loadTimeData.getBoolean('showWakeOnWifi')) {
- $('wake-on-wifi').hidden = false;
- }
-
- // Bluetooth (CrOS only).
- if (cr.isChromeOS) {
- // Request the intial bluetooth adapter state.
- var adapterStateChanged =
- this.onBluetoothAdapterStateChanged_.bind(this);
- chrome.bluetooth.getAdapterState(adapterStateChanged);
-
- // Set up observers.
- chrome.bluetooth.onAdapterStateChanged.addListener(adapterStateChanged);
- var deviceAddedOrChanged =
- this.onBluetoothDeviceAddedOrChanged_.bind(this);
- chrome.bluetooth.onDeviceAdded.addListener(deviceAddedOrChanged);
- chrome.bluetooth.onDeviceChanged.addListener(deviceAddedOrChanged);
- chrome.bluetooth.onDeviceRemoved.addListener(
- this.onBluetoothDeviceRemoved_.bind(this));
-
- chrome.bluetoothPrivate.onPairing.addListener(
- this.onBluetoothPrivatePairing_.bind(this));
-
- // Initialize UI.
- options.system.bluetooth.BluetoothDeviceList.decorate(
- $('bluetooth-paired-devices-list'));
-
- $('bluetooth-add-device').onclick =
- this.handleAddBluetoothDevice_.bind(this);
-
- $('enable-bluetooth').onchange = function(event) {
- var state = $('enable-bluetooth').checked;
- chrome.bluetoothPrivate.setAdapterState({powered: state}, function() {
- if (chrome.runtime.lastError) {
- console.error('Error enabling bluetooth:',
- chrome.runtime.lastError.message);
- }
- });
- };
-
- $('bluetooth-reconnect-device').onclick = function(event) {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_BluetoothConnectPairedDevice']);
- var device = $('bluetooth-paired-devices-list').selectedItem;
- BluetoothPairing.connect(device);
- };
-
- $('bluetooth-paired-devices-list').addEventListener('change',
- function() {
- var item = $('bluetooth-paired-devices-list').selectedItem;
- var disabled = !item || item.connected || !item.connectable;
- $('bluetooth-reconnect-device').disabled = disabled;
- });
- }
-
- // Passwords and Forms section.
- $('autofill-settings').onclick = function(event) {
- PageManager.showPageByName('autofill');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowAutofillSettings']);
- };
- $('manage-passwords').onclick = function(event) {
- PageManager.showPageByName('passwords');
- OptionsPage.showTab($('passwords-nav-tab'));
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowPasswordManager']);
- };
- if (cr.isChromeOS && UIAccountTweaks.loggedInAsGuest()) {
- // Disable and turn off Autofill in guest mode.
- var autofillEnabled = $('autofill-enabled');
- autofillEnabled.disabled = true;
- autofillEnabled.checked = false;
- cr.dispatchSimpleEvent(autofillEnabled, 'change');
- $('autofill-settings').disabled = true;
-
- // Disable and turn off Password Manager in guest mode.
- var passwordManagerEnabled = $('password-manager-enabled');
- passwordManagerEnabled.disabled = true;
- passwordManagerEnabled.checked = false;
- cr.dispatchSimpleEvent(passwordManagerEnabled, 'change');
- $('manage-passwords').disabled = true;
- }
-
- if (cr.isMac) {
- $('mac-passwords-warning').hidden =
- !loadTimeData.getBoolean('multiple_profiles');
- }
-
- // Network section.
- if (!cr.isChromeOS) {
- $('proxiesConfigureButton').onclick = function(event) {
- chrome.send('showNetworkProxySettings');
- };
- }
-
- // Easy Unlock section.
- if (loadTimeData.getBoolean('easyUnlockAllowed')) {
- $('easy-unlock-section').hidden = false;
- $('easy-unlock-setup-button').onclick = function(event) {
- chrome.send('launchEasyUnlockSetup');
- };
- $('easy-unlock-turn-off-button').onclick = function(event) {
- PageManager.showPageByName('easyUnlockTurnOffOverlay');
- };
- }
-
- // Web Content section.
- $('fontSettingsCustomizeFontsButton').onclick = function(event) {
- PageManager.showPageByName('fonts');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ShowFontSettings']);
- };
- $('defaultFontSize').onchange = function(event) {
- var value = event.target.options[event.target.selectedIndex].value;
- Preferences.setIntegerPref(
- 'webkit.webprefs.default_fixed_font_size',
- value - OptionsPage.SIZE_DIFFERENCE_FIXED_STANDARD, true);
- chrome.send('defaultFontSizeAction', [String(value)]);
- };
- $('defaultZoomFactor').onchange = function(event) {
- chrome.send('defaultZoomFactorAction',
- [String(event.target.options[event.target.selectedIndex].value)]);
- };
- $('safeBrowsingExtendedReportingCheckbox').onchange = function(event) {
- chrome.send('safeBrowsingExtendedReportingAction',
- [event.target.checked]);
- };
-
- // Languages section.
- var showLanguageOptions = function(event) {
- PageManager.showPageByName('languages');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_LanuageAndSpellCheckSettings']);
- };
- $('language-button').onclick = showLanguageOptions;
- $('manage-languages').onclick = showLanguageOptions;
-
- // Downloads section.
- Preferences.getInstance().addEventListener('download.default_directory',
- this.onDefaultDownloadDirectoryChanged_.bind(this));
- $('downloadLocationChangeButton').onclick = function(event) {
- chrome.send('selectDownloadLocation');
- };
- if (cr.isChromeOS) {
- $('disable-drive-row').hidden =
- UIAccountTweaks.loggedInAsSupervisedUser();
- }
- $('autoOpenFileTypesResetToDefault').onclick = function(event) {
- chrome.send('autoOpenFileTypesAction');
- };
-
- // HTTPS/SSL section.
- if (cr.isWindows || cr.isMac) {
- $('certificatesManageButton').onclick = function(event) {
- chrome.send('showManageSSLCertificates');
- };
- } else {
- $('certificatesManageButton').onclick = function(event) {
- PageManager.showPageByName('certificates');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_ManageSSLCertificates']);
- };
- }
-
- // CUPS Print section (CrOS only).
- if (cr.isChromeOS) {
- $('cups-printers-section').hidden = false;
- $('cupsPrintersManageButton').onclick = function() {
- chrome.send('showCupsPrintDevicesPage');
- };
- }
-
- if (loadTimeData.getBoolean('cloudPrintShowMDnsOptions')) {
- $('cloudprint-options-mdns').hidden = false;
- $('cloudPrintDevicesPageButton').onclick = function() {
- chrome.send('showCloudPrintDevicesPage');
- };
- }
-
- // Accessibility section (CrOS only).
- if (cr.isChromeOS) {
- var updateAccessibilitySettingsSection = function() {
- $('accessibility-settings').hidden =
- !($('accessibility-spoken-feedback-check').checked);
- };
- Preferences.getInstance().addEventListener(
- 'settings.accessibility',
- updateAccessibilitySettingsSection);
- $('accessibility-learn-more').onclick = function(unused_event) {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_AccessibilityLearnMore']);
- };
- $('accessibility-settings-button').onclick = function(unused_event) {
- window.open(loadTimeData.getString('accessibilitySettingsURL'));
- };
- $('talkback-settings-button').onclick = function(unused_event) {
- chrome.send('showAccessibilityTalkBackSettings');
- };
- $('accessibility-spoken-feedback-check').onchange =
- updateAccessibilitySettingsSection;
- updateAccessibilitySettingsSection();
-
- var updateScreenMagnifierCenterFocus = function() {
- $('accessibility-screen-magnifier-center-focus-check').disabled =
- !$('accessibility-screen-magnifier-check').checked;
- };
- Preferences.getInstance().addEventListener(
- $('accessibility-screen-magnifier-check').getAttribute('pref'),
- updateScreenMagnifierCenterFocus);
-
- var updateDelayDropdown = function() {
- $('accessibility-autoclick-dropdown').disabled =
- !$('accessibility-autoclick-check').checked;
- };
- Preferences.getInstance().addEventListener(
- $('accessibility-autoclick-check').getAttribute('pref'),
- updateDelayDropdown);
- $('experimental-accessibility-features').hidden =
- !loadTimeData.getBoolean('enableExperimentalAccessibilityFeatures');
- }
-
- // Display management section (CrOS only).
- if (cr.isChromeOS) {
- $('display-options').onclick = function(event) {
- PageManager.showPageByName('display');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_Display']);
- };
- }
-
- // Factory reset section (CrOS only).
- if (cr.isChromeOS) {
- $('factory-reset-restart').onclick = function(event) {
- PageManager.showPageByName('factoryResetData');
- chrome.send('onPowerwashDialogShow');
- };
- }
-
- // System section.
- if (!cr.isChromeOS) {
- var updateGpuRestartButton = function() {
- $('gpu-mode-reset-restart').hidden =
- loadTimeData.getBoolean('gpuEnabledAtStart') ==
- $('gpu-mode-checkbox').checked;
- };
- Preferences.getInstance().addEventListener(
- $('gpu-mode-checkbox').getAttribute('pref'),
- updateGpuRestartButton);
- $('gpu-mode-reset-restart-button').onclick = function(event) {
- chrome.send('restartBrowser');
- };
- updateGpuRestartButton();
- }
-
- // Reset profile settings section.
- $('reset-profile-settings').onclick = function(event) {
- // We use the hash to indicate the source of the reset request. The hash
- // is removed by the reset profile settings overlay once it has been
- // consumed.
- PageManager.showPageByName('resetProfileSettings', true,
- {hash: '#userclick'});
- };
-
- // Extension controlled UI.
- this.addExtensionControlledBox_('search-section-content',
- 'search-engine-controlled',
- true);
- this.addExtensionControlledBox_('extension-controlled-container',
- 'homepage-controlled',
- true);
- this.addExtensionControlledBox_('startup-section-content',
- 'startpage-controlled',
- false);
- this.addExtensionControlledBox_('newtab-section-content',
- 'newtab-controlled',
- false);
- this.addExtensionControlledBox_('proxy-section-content',
- 'proxy-controlled',
- true);
-
- document.body.addEventListener('click', function(e) {
- var target = assertInstanceof(e.target, Node);
- var button = findAncestor(target, function(el) {
- return el.tagName == 'BUTTON' &&
- el.dataset.extensionId !== undefined &&
- el.dataset.extensionId.length;
- });
- if (button)
- chrome.send('disableExtension', [button.dataset.extensionId]);
- });
-
- // Setup ARC section.
- if (cr.isChromeOS) {
- $('android-apps-settings-label').innerHTML =
- loadTimeData.getString('androidAppsSettingsLabel');
- Preferences.getInstance().addEventListener('arc.enabled', function(e) {
- // Only change settings visibility on committed settings changes.
- if (e.value.uncommitted)
- return;
-
- var isArcEnabled = !e.value.value;
- $('android-apps-settings').hidden = isArcEnabled;
- $('talkback-settings-button').hidden = isArcEnabled;
- $('stylus-find-more-link').hidden = isArcEnabled;
- });
-
- $('android-apps-settings-link').addEventListener('click', function(e) {
- // MouseEvent.detail indicates the current click count (or tap
- // count, in the case of touch events) in the 'click' event.
- var activatedFromKeyboard = e.detail == 0;
- chrome.send('showAndroidAppsSettings', [activatedFromKeyboard]);
- });
- }
- },
-
- /** @override */
- didShowPage: function() {
- $('search-field').focus();
- },
-
- /**
- * Called after all C++ UI handlers have called InitializePage to notify
- * that initialization is complete.
- * @private
- */
- notifyInitializationComplete_: function() {
- this.initializationComplete_ = true;
- cr.dispatchSimpleEvent(document, 'initializationComplete');
- },
-
- /**
- * Event listener for the 'session.restore_on_startup' pref.
- * @param {Event} event The preference change event.
- * @private
- */
- onRestoreOnStartupChanged_: function(event) {
- /** @const */ var showHomePageValue = 0;
-
- if (event.value.value == showHomePageValue) {
- // If the user previously selected "Show the homepage", the
- // preference will already be migrated to "Open a specific page". So
- // the only way to reach this code is if the 'restore on startup'
- // preference is managed.
- assert(event.value.controlledBy);
-
- // Select "open the following pages" and lock down the list of URLs
- // to reflect the intention of the policy.
- $('startup-show-pages').checked = true;
- StartupOverlay.getInstance().setControlsDisabled(true);
- } else {
- // Re-enable the controls in the startup overlay if necessary.
- StartupOverlay.getInstance().updateControlStates();
- }
- },
-
- /**
- * Handler for messages sent from the main uber page.
- * @param {Event} e The 'message' event from the uber page.
- * @private
- */
- handleWindowMessage_: function(e) {
- if ((/** @type {{method: string}} */(e.data)).method == 'frameSelected')
- $('search-field').focus();
- },
-
- /**
- * Animatedly changes height |from| a px number |to| a px number.
- * @param {HTMLElement} section The section to animate.
- * @param {HTMLElement} container The container of |section|.
- * @param {boolean} showing Whether to go from 0 -> container height or
- * container height -> 0.
- * @private
- */
- animatedSectionHeightChange_: function(section, container, showing) {
- // If the section is already animating, dispatch a synthetic transition
- // end event as the upcoming code will cancel the current one.
- if (section.classList.contains('sliding'))
- cr.dispatchSimpleEvent(section, 'transitionend');
-
- this.addTransitionEndListener_(section);
-
- section.hidden = false;
- section.style.height = (showing ? 0 : container.offsetHeight) + 'px';
- section.classList.add('sliding');
-
- // Force a style recalc before starting the animation.
- /** @suppress {suspiciousCode} */
- section.offsetHeight;
-
- section.style.height = (showing ? container.offsetHeight : 0) + 'px';
- },
-
- /**
- * Shows the given section.
- * @param {HTMLElement} section The section to be shown.
- * @param {HTMLElement} container The container for the section. Must be
- * inside of |section|.
- * @param {boolean} animate Indicate if the expansion should be animated.
- * @private
- */
- showSection_: function(section, container, animate) {
- if (section == $('advanced-settings') &&
- !loadTimeData.getBoolean('allowAdvancedSettings')) {
- return;
- }
- // Delay starting the transition if animating so that hidden change will
- // be processed.
- if (animate) {
- this.animatedSectionHeightChange_(section, container, true);
- } else {
- section.hidden = false;
- section.style.height = 'auto';
- }
- },
-
- /**
- * Shows the given section, with animation.
- * @param {HTMLElement} section The section to be shown.
- * @param {HTMLElement} container The container for the section. Must be
- * inside of |section|.
- * @private
- */
- showSectionWithAnimation_: function(section, container) {
- this.showSection_(section, container, /* animate */ true);
- },
-
- /**
- * Hides the given |section| with animation.
- * @param {HTMLElement} section The section to be hidden.
- * @param {HTMLElement} container The container for the section. Must be
- * inside of |section|.
- * @private
- */
- hideSectionWithAnimation_: function(section, container) {
- this.animatedSectionHeightChange_(section, container, false);
- },
-
- /**
- * Toggles the visibility of |section| in an animated way.
- * @param {HTMLElement} section The section to be toggled.
- * @param {HTMLElement} container The container for the section. Must be
- * inside of |section|.
- * @private
- */
- toggleSectionWithAnimation_: function(section, container) {
- if (BrowserOptions.shouldShowSection_(section))
- this.showSectionWithAnimation_(section, container);
- else
- this.hideSectionWithAnimation_(section, container);
- },
-
- /**
- * Scrolls the settings page to make the section visible auto-expanding
- * advanced settings if required. The transition is not animated. This
- * method is used to ensure that a section associated with an overlay
- * is visible when the overlay is closed.
- * @param {!Element} section The section to make visible.
- * @private
- */
- scrollToSection_: function(section) {
- var advancedSettings = $('advanced-settings');
- var container = $('advanced-settings-container');
- var expander = $('advanced-settings-expander');
- if (!expander.hidden &&
- advancedSettings.hidden &&
- section.parentNode == container) {
- this.showSection_($('advanced-settings'),
- $('advanced-settings-container'),
- /* animate */ false);
- this.updateAdvancedSettingsExpander_();
- }
-
- if (!this.initializationComplete_) {
- var self = this;
- var callback = function() {
- document.removeEventListener('initializationComplete', callback);
- self.scrollToSection_(section);
- };
- document.addEventListener('initializationComplete', callback);
- return;
- }
-
- var pageContainer = $('page-container');
- // pageContainer.offsetTop is relative to the screen.
- var pageTop = pageContainer.offsetTop;
- var sectionBottom = section.offsetTop + section.offsetHeight;
- // section.offsetTop is relative to the 'page-container'.
- var sectionTop = section.offsetTop;
- if (pageTop + sectionBottom > document.body.scrollHeight ||
- pageTop + sectionTop < 0) {
- // Currently not all layout updates are guaranteed to precede the
- // initializationComplete event (for example 'set-as-default-browser'
- // button) leaving some uncertainty in the optimal scroll position.
- // The section is placed approximately in the middle of the screen.
- var top = Math.min(0, document.body.scrollHeight / 2 - sectionBottom);
- pageContainer.style.top = top + 'px';
- pageContainer.oldScrollTop = -top;
- }
- },
-
- /**
- * Adds a |transitionend| listener to the given section so that
- * it can be animated. The listener will only be added to a given section
- * once, so this can be called as multiple times.
- * @param {HTMLElement} section The section to be animated.
- * @private
- */
- addTransitionEndListener_: function(section) {
- if (section.hasTransitionEndListener_)
- return;
-
- section.addEventListener('transitionend',
- this.onTransitionEnd_.bind(this));
- section.hasTransitionEndListener_ = true;
- },
-
- /**
- * Called after an animation transition has ended.
- * @param {Event} event The transitionend event. NOTE: May be
- * synthetic.
- * @private
- */
- onTransitionEnd_: function(event) {
- if (event.propertyName && event.propertyName != 'height') {
- // If not a synthetic event or a real transition we care about, bail.
- return;
- }
-
- var section = event.target;
- section.classList.remove('sliding');
-
- if (!event.propertyName) {
- // Only real transitions past this point.
- return;
- }
-
- if (section.style.height == '0px') {
- // Hide the content so it can't get tab focus.
- section.hidden = true;
- section.style.height = '';
- } else {
- // Set the section height to 'auto' to allow for size changes
- // (due to font change or dynamic content).
- section.style.height = 'auto';
- }
- },
-
- /** @private */
- updateAdvancedSettingsExpander_: function() {
- var expander = $('advanced-settings-expander');
- if (BrowserOptions.shouldShowSection_($('advanced-settings')))
- expander.textContent = loadTimeData.getString('showAdvancedSettings');
- else
- expander.textContent = loadTimeData.getString('hideAdvancedSettings');
- },
-
- /**
- * Updates the sync section with the given state.
- * @param {options.SyncStatus} syncData A bunch of data records that
- * describe the status of the sync system.
- * @private
- */
- updateSyncState_: function(syncData) {
- if (!syncData.signinAllowed &&
- (!syncData.supervisedUser || !cr.isChromeOS)) {
- $('sync-section').hidden = true;
- this.maybeShowUserSection_();
- return;
- }
-
- $('sync-section').hidden = false;
- this.maybeShowUserSection_();
-
- if (cr.isChromeOS && syncData.supervisedUser && !syncData.childUser) {
- var subSection = $('sync-section').firstChild;
- while (subSection) {
- if (subSection.nodeType == Node.ELEMENT_NODE)
- subSection.hidden = true;
- subSection = subSection.nextSibling;
- }
-
- $('account-picture-wrapper').hidden = false;
- $('sync-general').hidden = false;
- $('sync-status').hidden = true;
-
- return;
- }
-
- // If the user gets signed out while the advanced sync settings dialog is
- // visible, say, due to a dashboard clear, close the dialog.
- // However, if the user gets signed out as a result of abandoning first
- // time sync setup, do not call closeOverlay as it will redirect the
- // browser to the main settings page and override any in-progress
- // user-initiated navigation. See crbug.com/278030.
- // Note: SyncSetupOverlay.closeOverlay is a no-op if the overlay is
- // already hidden.
- if (this.signedIn_ && !syncData.signedIn && !syncData.setupInProgress)
- SyncSetupOverlay.closeOverlay();
-
- this.signedIn_ = !!syncData.signedIn;
-
- // Display the "advanced settings" button if we're signed in and sync is
- // not managed/disabled. If the user is signed in, but sync is disabled,
- // this button is used to re-enable sync.
- var customizeSyncButton = $('customize-sync');
- customizeSyncButton.hidden = !this.signedIn_ ||
- syncData.managed ||
- !syncData.syncSystemEnabled;
-
- // Only modify the customize button's text if the new text is different.
- // Otherwise, it can affect search-highlighting in the settings page.
- // See http://crbug.com/268265.
- var customizeSyncButtonNewText = syncData.setupCompleted ?
- loadTimeData.getString('customizeSync') :
- loadTimeData.getString('syncButtonTextStart');
- if (customizeSyncButton.textContent != customizeSyncButtonNewText)
- customizeSyncButton.textContent = customizeSyncButtonNewText;
-
- // Disable the "sign in" button if we're currently signing in, or if we're
- // already signed in and signout is not allowed.
- var signInButton = $('start-stop-sync');
- signInButton.disabled = syncData.setupInProgress;
- this.signoutAllowed_ = !!syncData.signoutAllowed;
- if (!syncData.signoutAllowed)
- $('start-stop-sync-indicator').setAttribute('controlled-by', 'policy');
- else
- $('start-stop-sync-indicator').removeAttribute('controlled-by');
-
- // Hide the "sign in" button on Chrome OS, and show it on desktop Chrome
- // (except for supervised users, which can't change their signed-in
- // status).
- signInButton.hidden = cr.isChromeOS || syncData.supervisedUser;
-
- signInButton.textContent =
- this.signedIn_ ?
- loadTimeData.getString('syncButtonTextStop') :
- syncData.setupInProgress ?
- loadTimeData.getString('syncButtonTextInProgress') :
- loadTimeData.getString('syncButtonTextSignIn');
- $('start-stop-sync-indicator').hidden = signInButton.hidden;
-
- $('account-info').textContent = syncData.accountInfo;
- $('account-info').hidden = !this.signedIn_;
-
- // TODO(estade): can this just be textContent?
- $('sync-status-text').innerHTML = syncData.statusText;
- var statusSet = syncData.statusText.length != 0;
- $('sync-overview').hidden =
- statusSet ||
- (cr.isChromeOS && UIAccountTweaks.loggedInAsPublicAccount());
- $('sync-status').hidden = !statusSet;
-
- $('sync-action-link').textContent = syncData.actionLinkText;
- // Don't show the action link if it is empty or undefined.
- $('sync-action-link').hidden = syncData.actionLinkText.length == 0;
- $('sync-action-link').disabled = syncData.managed ||
- !syncData.syncSystemEnabled;
-
- $('sync-action-link').onclick = function(event) {
- switch (syncData.statusAction) {
- case 'reauthenticate':
- SyncSetupOverlay.startSignIn(false /* creatingSupervisedUser */);
- break;
- case 'signOutAndSignIn':
-// <if expr="chromeos">
- // On Chrome OS, sign out the user and sign in again to get fresh
- // credentials on auth errors.
- SyncSetupOverlay.doSignOutOnAuthError();
-// </if>
-// <if expr="not chromeos">
- if (syncData.signoutAllowed) {
- // Silently sign the user out without deleting their profile and
- // prompt them to sign back in.
- chrome.send('SyncSetupStopSyncing', [false /* deleteProfile */]);
- SyncSetupOverlay.startSignIn(false /* creatingSupervisedUser */);
- } else {
- chrome.send('showDisconnectManagedProfileDialog');
- }
-// </if>
- break;
- case 'upgradeClient':
- PageManager.showPageByName('help');
- break;
- default:
- SyncSetupOverlay.showSetupUI();
- }
- };
-
- if (syncData.hasError)
- $('sync-status').classList.add('sync-error');
- else
- $('sync-status').classList.remove('sync-error');
-
- // Disable the "customize / set up sync" button if sync has an
- // unrecoverable error. Also disable the button if sync has not been set
- // up and the user is being presented with a link to re-auth.
- // See crbug.com/289791.
- customizeSyncButton.disabled =
- syncData.hasUnrecoverableError ||
- (!syncData.setupCompleted && !$('sync-action-link').hidden);
- },
-
- /**
- * Update the UI depending on whether Easy Unlock is enabled for the current
- * profile.
- * @param {boolean} isEnabled True if the feature is enabled for the current
- * profile.
- */
- updateEasyUnlock_: function(isEnabled) {
- $('easy-unlock-disabled').hidden = isEnabled;
- $('easy-unlock-enabled').hidden = !isEnabled;
- if (!isEnabled && EasyUnlockTurnOffOverlay.getInstance().visible) {
- EasyUnlockTurnOffOverlay.dismiss();
- }
- },
-
- /**
- * Update the UI depending on whether the current profile manages any
- * supervised users.
- * @param {boolean} show True if the current profile manages any supervised
- * users.
- */
- updateManagesSupervisedUsers_: function(show) {
- $('profiles-supervised-dashboard-tip').hidden = !show;
- this.maybeShowUserSection_();
- },
-
- /**
- * Get the start/stop sync button DOM element. Used for testing.
- * @return {Element} The start/stop sync button.
- * @private
- */
- getStartStopSyncButton_: function() {
- return $('start-stop-sync');
- },
-
- /**
- * Event listener for the 'show home button' preference. Shows/hides the
- * UI for changing the home page with animation, unless this is the first
- * time this function is called, in which case there is no animation.
- * @param {Event} event The preference change event.
- */
- onShowHomeButtonChanged_: function(event) {
- var section = $('change-home-page-section');
- if (this.onShowHomeButtonChangedCalled_) {
- var container = $('change-home-page-section-container');
- if (event.value.value)
- this.showSectionWithAnimation_(section, container);
- else
- this.hideSectionWithAnimation_(section, container);
- } else {
- section.hidden = !event.value.value;
- this.onShowHomeButtonChangedCalled_ = true;
- }
- },
-
- /**
- * Activates the Hotword section from the System settings page.
- * @param {string} sectionId The id of the section to display.
- * @param {string} indicatorId The id of the indicator to display.
- * @param {string=} opt_error The error message to display.
- * @private
- */
- showHotwordCheckboxAndIndicator_: function(sectionId, indicatorId,
- opt_error) {
- $(sectionId).hidden = false;
- $(indicatorId).setError(opt_error);
- if (opt_error)
- $(indicatorId).updateBasedOnError();
- },
-
- /**
- * Activates the Hotword section from the System settings page.
- * @param {string=} opt_error The error message to display.
- * @private
- */
- showHotwordSection_: function(opt_error) {
- this.showHotwordCheckboxAndIndicator_(
- 'hotword-search',
- 'hotword-search-setting-indicator',
- opt_error);
- },
-
- /**
- * Activates the Always-On Hotword sections from the
- * System settings page.
- * @param {string=} opt_error The error message to display.
- * @private
- */
- showHotwordAlwaysOnSection_: function(opt_error) {
- this.showHotwordCheckboxAndIndicator_(
- 'hotword-always-on-search',
- 'hotword-always-on-search-setting-indicator',
- opt_error);
- },
-
- /**
- * Activates the Hotword section on devices with no DSP
- * from the System settings page.
- * @param {string=} opt_error The error message to display.
- * @private
- */
- showHotwordNoDspSection_: function(opt_error) {
- this.showHotwordCheckboxAndIndicator_(
- 'hotword-no-dsp-search',
- 'hotword-no-dsp-search-setting-indicator',
- opt_error);
- },
-
- /**
- * Controls the visibility of all the hotword sections.
- * @param {boolean} visible Whether to show hotword sections.
- * @private
- */
- setAllHotwordSectionsVisible_: function(visible) {
- $('hotword-search').hidden = !visible;
- $('hotword-always-on-search').hidden = !visible;
- $('hotword-no-dsp-search').hidden = !visible;
- $('audio-history').hidden = !visible;
- },
-
- /**
- * Shows or hides the hotword retrain link
- * @param {boolean} visible Whether to show the link.
- * @private
- */
- setHotwordRetrainLinkVisible_: function(visible) {
- $('hotword-retrain-link').hidden = !visible;
- },
-
- /**
- * Event listener for the 'hotword always on search enabled' preference.
- * Updates the visibility of the 'retrain' link.
- * @param {Event} event The preference change event.
- * @private
- */
- onHotwordAlwaysOnChanged_: function(event) {
- this.setHotwordRetrainLinkVisible_(event.value.value);
- },
-
- /**
- * Controls the visibility of the Now settings.
- * @param {boolean} visible Whether to show Now settings.
- * @private
- */
- setNowSectionVisible_: function(visible) {
- $('google-now-launcher').hidden = !visible;
- },
-
- /**
- * Activates the Audio History section of the Settings page.
- * @param {boolean} visible Whether the audio history section is visible.
- * @param {string} labelText Text describing current audio history state.
- * @private
- */
- setAudioHistorySectionVisible_: function(visible, labelText) {
- $('audio-history').hidden = !visible;
- $('audio-history-label').textContent = labelText;
- },
-
- /**
- * Event listener for the 'homepage is NTP' preference. Updates the label
- * next to the 'Change' button.
- * @param {Event} event The preference change event.
- */
- onHomePageIsNtpChanged_: function(event) {
- if (!event.value.uncommitted) {
- $('home-page-url').hidden = event.value.value;
- $('home-page-ntp').hidden = !event.value.value;
- }
- },
-
- /**
- * Event listener for changes to the homepage preference. Updates the label
- * next to the 'Change' button.
- * @param {Event} event The preference change event.
- */
- onHomePageChanged_: function(event) {
- if (!event.value.uncommitted)
- $('home-page-url').textContent = this.stripHttp_(event.value.value);
- },
-
- /**
- * Removes the 'http://' from a URL, like the omnibox does. If the string
- * doesn't start with 'http://' it is returned unchanged.
- * @param {string} url The url to be processed
- * @return {string} The url with the 'http://' removed.
- */
- stripHttp_: function(url) {
- return url.replace(/^http:\/\//, '');
- },
-
- /**
- * Called when the value of the download.default_directory preference
- * changes.
- * @param {Event} event Change event.
- * @private
- */
- onDefaultDownloadDirectoryChanged_: function(event) {
- $('downloadLocationPath').value = event.value.value;
- if (cr.isChromeOS) {
- // On ChromeOS, replace /special/drive-<hash>/root with "Google Drive"
- // for remote files, /home/chronos/user/Downloads or
- // /home/chronos/u-<hash>/Downloads with "Downloads" for local paths,
- // and '/' with ' \u203a ' (angled quote sign) everywhere. The modified
- // path is used only for display purpose.
- var path = $('downloadLocationPath').value;
- path = path.replace(/^\/special\/drive[^\/]*\/root/, 'Google Drive');
- path = path.replace(/^\/home\/chronos\/(user|u-[^\/]*)\//, '');
- path = path.replace(/\//g, ' \u203a ');
- $('downloadLocationPath').value = path;
- }
- $('download-location-label').classList.toggle('disabled',
- event.value.disabled);
- $('downloadLocationChangeButton').disabled = event.value.disabled;
- },
-
- /**
- * Update the Default Browsers section based on the current state.
- * @param {string} statusString Description of the current default state.
- * @param {boolean} isDefault Whether or not the browser is currently
- * default.
- * @param {boolean} canBeDefault Whether or not the browser can be default.
- * @private
- */
- updateDefaultBrowserState_: function(statusString, isDefault,
- canBeDefault) {
- if (!cr.isChromeOS) {
- var label = $('default-browser-state');
- label.textContent = statusString;
-
- $('set-as-default-browser').hidden = !canBeDefault || isDefault;
- }
- },
-
- /**
- * Clears the search engine popup.
- * @private
- */
- clearSearchEngines_: function() {
- $('default-search-engine').textContent = '';
- },
-
- /**
- * Updates the search engine popup with the given entries.
- * @param {Array} engines List of available search engines.
- * @param {number} defaultValue The value of the current default engine.
- * @param {boolean} defaultManaged Whether the default search provider is
- * managed. If true, the default search provider can't be changed.
- * @private
- */
- updateSearchEngines_: function(engines, defaultValue, defaultManaged) {
- this.clearSearchEngines_();
- var engineSelect = $('default-search-engine');
- engineSelect.disabled = defaultManaged;
- if (defaultManaged && defaultValue == -1)
- return;
- var engineCount = engines.length;
- var defaultIndex = -1;
- for (var i = 0; i < engineCount; i++) {
- var engine = engines[i];
- var option = new Option(engine.name, engine.index);
- if (defaultValue == option.value)
- defaultIndex = i;
- engineSelect.appendChild(option);
- }
- if (defaultIndex >= 0)
- engineSelect.selectedIndex = defaultIndex;
- },
-
- /**
- * Set the default search engine based on the popup selection.
- * @private
- */
- setDefaultSearchEngine_: function() {
- var engineSelect = $('default-search-engine');
- var selectedIndex = engineSelect.selectedIndex;
- if (selectedIndex >= 0) {
- var selection = engineSelect.options[selectedIndex];
- chrome.send('setDefaultSearchEngine', [String(selection.value)]);
- }
- },
-
- /**
- * Get the selected profile item from the profile list. This also works
- * correctly if the list is not displayed.
- * @return {?Object} The profile item object, or null if nothing is
- * selected.
- * @private
- */
- getSelectedProfileItem_: function() {
- var profilesList = $('profiles-list');
- if (profilesList.hidden) {
- if (profilesList.dataModel.length > 0)
- return profilesList.dataModel.item(0);
- } else {
- return profilesList.selectedItem;
- }
- return null;
- },
-
- /**
- * Helper function to set the status of profile view buttons to disabled or
- * enabled, depending on the number of profiles and selection status of the
- * profiles list.
- * @private
- */
- setProfileViewButtonsStatus_: function() {
- var profilesList = $('profiles-list');
- var selectedProfile = profilesList.selectedItem;
- var hasSelection = selectedProfile != null;
- var hasSingleProfile = profilesList.dataModel.length == 1;
- $('profiles-manage').disabled = !hasSelection ||
- !selectedProfile.isCurrentProfile;
- if (hasSelection && !selectedProfile.isCurrentProfile)
- $('profiles-manage').title = loadTimeData.getString('currentUserOnly');
- else
- $('profiles-manage').title = '';
- $('profiles-delete').disabled = !profilesList.canDeleteItems ||
- !hasSelection;
- var importData = $('import-data');
- if (importData) {
- importData.disabled = $('import-data').disabled = hasSelection &&
- !selectedProfile.isCurrentProfile;
- }
- },
-
- /**
- * Display the correct dialog layout, depending on how many profiles are
- * available.
- * @param {number} numProfiles The number of profiles to display.
- * @private
- */
- setProfileViewSingle_: function(numProfiles) {
- // Always show the profiles list when using the new Profiles UI.
- var usingNewProfilesUI = loadTimeData.getBoolean('usingNewProfilesUI');
- var showSingleProfileView = !usingNewProfilesUI && numProfiles == 1;
- $('profiles-list').hidden = showSingleProfileView;
- $('profiles-single-message').hidden = !showSingleProfileView;
- $('profiles-manage').hidden = showSingleProfileView;
- $('profiles-delete').textContent = showSingleProfileView ?
- loadTimeData.getString('profilesDeleteSingle') :
- loadTimeData.getString('profilesDelete');
- },
-
- /**
- * Adds all |profiles| to the list.
- * @param {!Array<!options.Profile>} profiles An array of profile info
- * objects.
- * @private
- */
- setProfilesInfo_: function(profiles) {
- this.setProfileViewSingle_(profiles.length);
- // add it to the list, even if the list is hidden so we can access it
- // later.
- $('profiles-list').dataModel = new ArrayDataModel(profiles);
-
- // Received new data. If showing the "manage" overlay, keep it up to
- // date. If showing the "delete" overlay, close it.
- if (ManageProfileOverlay.getInstance().visible &&
- !$('manage-profile-overlay-manage').hidden) {
- ManageProfileOverlay.showManageDialog(false);
- } else {
- ManageProfileOverlay.getInstance().visible = false;
- }
-
- this.setProfileViewButtonsStatus_();
- },
-
- /**
- * Reports supervised user import errors to the SupervisedUserImportOverlay.
- * @param {string} error The error message to display.
- * @private
- */
- showSupervisedUserImportError_: function(error) {
- SupervisedUserImportOverlay.onError(error);
- },
-
- /**
- * Reports successful importing of a supervised user to
- * the SupervisedUserImportOverlay.
- * @private
- */
- showSupervisedUserImportSuccess_: function() {
- SupervisedUserImportOverlay.onSuccess();
- },
-
- /**
- * Reports an error to the "create" overlay during profile creation.
- * @param {string} error The error message to display.
- * @private
- */
- showCreateProfileError_: function(error) {
- CreateProfileOverlay.onError(error);
- },
-
- /**
- * Sends a warning message to the "create" overlay during profile creation.
- * @param {string} warning The warning message to display.
- * @private
- */
- showCreateProfileWarning_: function(warning) {
- CreateProfileOverlay.onWarning(warning);
- },
-
- /**
- * Reports successful profile creation to the "create" overlay.
- * @param {options.Profile} profileInfo An object of the form:
- * profileInfo = {
- * name: "Profile Name",
- * filePath: "/path/to/profile/data/on/disk"
- * isSupervised: (true|false),
- * };
- * @private
- */
- showCreateProfileSuccess_: function(profileInfo) {
- CreateProfileOverlay.onSuccess(profileInfo);
- },
-
- /**
- * Returns the currently active profile for this browser window.
- * @return {options.Profile} A profile info object.
- * @private
- */
- getCurrentProfile_: function() {
- for (var i = 0; i < $('profiles-list').dataModel.length; i++) {
- var profile = $('profiles-list').dataModel.item(i);
- if (profile.isCurrentProfile)
- return profile;
- }
-
- assertNotReached('There should always be a current profile.');
- },
-
- /**
- * Propmpts user to confirm deletion of the profile for this browser
- * window.
- * @private
- */
- deleteCurrentProfile_: function() {
- ManageProfileOverlay.showDeleteDialog(this.getCurrentProfile_());
- },
-
- /**
- * @param {boolean} enabled
- */
- setNativeThemeButtonEnabled_: function(enabled) {
- var button = $('themes-native-button');
- if (button)
- button.disabled = !enabled;
- },
-
- /**
- * @param {boolean} enabled
- */
- setThemesResetButtonEnabled_: function(enabled) {
- $('themes-reset').disabled = !enabled;
- },
-
- /**
- * @param {boolean} managed
- */
- setAccountPictureManaged_: function(managed) {
- var picture = $('account-picture');
- if (managed || UIAccountTweaks.loggedInAsGuest()) {
- picture.disabled = true;
- ChangePictureOptions.closeOverlay();
- } else {
- picture.disabled = false;
- }
-
- // Create a synthetic pref change event decorated as
- // CoreOptionsHandler::CreateValueForPref() does.
- var event = new Event('account-picture');
- if (managed)
- event.value = { controlledBy: 'policy' };
- else
- event.value = {};
- $('account-picture-indicator').handlePrefChange(event);
- },
-
- /**
- * (Re)loads IMG element with current user account picture.
- * @private
- */
- updateAccountPicture_: function() {
- var picture = $('account-picture');
- if (picture) {
- picture.src = 'chrome://userimage/' + this.username_ + '?id=' +
- Date.now();
- }
- },
-
- /**
- * @param {boolean} managed
- */
- setWallpaperManaged_: function(managed) {
- if (managed)
- $('set-wallpaper').disabled = true;
- else
- this.enableElementIfPossible_(getRequiredElement('set-wallpaper'));
-
- // Create a synthetic pref change event decorated as
- // CoreOptionsHandler::CreateValueForPref() does.
- var event = new Event('wallpaper');
- event.value = managed ? { controlledBy: 'policy' } : {};
- $('wallpaper-indicator').handlePrefChange(event);
- },
-
- /**
- * This enables or disables dependent settings in timezone section.
- * @private
- */
- updateTimezoneSectionState_: function() {
- var self = this;
- $('resolve-timezone-by-geolocation')
- .onclick = function(event) {
- self.resolveTimezoneByGeolocation_ = event.currentTarget.checked;
- };
- if (this.systemTimezoneIsManaged_) {
- $('resolve-timezone-by-geolocation').disabled = true;
- $('resolve-timezone-by-geolocation').checked = false;
- } else if (this.systemTimezoneAutomaticDetectionIsManaged_) {
- if (this.systemTimezoneAutomaticDetectionValue_ ==
- options.AutomaticTimezoneDetectionType.USERS_DECIDE) {
- $('resolve-timezone-by-geolocation').disabled = false;
- $('resolve-timezone-by-geolocation')
- .checked = this.resolveTimezoneByGeolocation_;
- $('timezone-value-select')
- .disabled = this.resolveTimezoneByGeolocation_;
- } else {
- $('resolve-timezone-by-geolocation').disabled = true;
- $('resolve-timezone-by-geolocation')
- .checked =
- (this.systemTimezoneAutomaticDetectionValue_ !=
- options.AutomaticTimezoneDetectionType.DISABLED);
- $('timezone-value-select').disabled = true;
- }
- } else {
- this.enableElementIfPossible_(
- getRequiredElement('resolve-timezone-by-geolocation'));
- $('timezone-value-select').disabled =
- this.resolveTimezoneByGeolocation_;
- $('resolve-timezone-by-geolocation')
- .checked = this.resolveTimezoneByGeolocation_;
- }
- },
-
- /**
- * Called when stylus hardware detection probing is complete.
- * @param {boolean} hasStylus
- * @private
- */
- setStylusInputStatus_: function(hasStylus) {
- if (!hasStylus)
- return;
-
- $('stylus-settings-link').onclick = function(event) {
- PageManager.showPageByName('stylus-overlay');
- };
- $('stylus-row').hidden = false;
- },
-
- /**
- * This is called from chromium code when system timezone "managed" state
- * is changed. Enables or disables dependent settings.
- * @param {boolean} managed Is true when system Timezone is managed by
- * enterprise policy. False otherwize.
- */
- setSystemTimezoneManaged_: function(managed) {
- this.systemTimezoneIsManaged_ = managed;
- this.updateTimezoneSectionState_();
- },
-
- /**
- * This is called from chromium code when system timezone detection
- * "managed" state is changed. Enables or disables dependent settings.
- * @param {boolean} managed Is true when system timezone autodetection is
- * managed by enterprise policy. False otherwize.
- * @param {options.AutomaticTimezoneDetectionType} value Current value of
- * SystemTimezoneAutomaticDetection device policy.
- */
- setSystemTimezoneAutomaticDetectionManaged_: function(managed, value) {
- this.systemTimezoneAutomaticDetectionIsManaged_ = managed;
- this.systemTimezoneAutomaticDetectionValue_ = value;
- this.updateTimezoneSectionState_();
- },
-
- /**
- * This is Preferences event listener, which is called when
- * kResolveTimezoneByGeolocation preference is changed.
- * Enables or disables dependent settings.
- * @param {Event} value New preference state.
- */
- onResolveTimezoneByGeolocationChanged_: function(value) {
- this.resolveTimezoneByGeolocation_ = value.value.value;
- this.updateTimezoneSectionState_();
- },
-
- /**
- * Handle the 'add device' button click.
- * @private
- */
- handleAddBluetoothDevice_: function() {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_BluetoothShowAddDevice']);
- PageManager.showPageByName('bluetooth', false);
- },
-
- /**
- * Enables or disables the Manage SSL Certificates button.
- * @private
- */
- enableCertificateButton_: function(enabled) {
- $('certificatesManageButton').disabled = !enabled;
- },
-
- /**
- * Enables or disables the Chrome OS display settings button and overlay.
- * @param {boolean} uiEnabled
- * @param {boolean} unifiedEnabled
- * @param {boolean} mirroredEnabled
- * @private
- */
- enableDisplaySettings_: function(
- uiEnabled, unifiedEnabled, mirroredEnabled) {
- if (cr.isChromeOS) {
- $('display-options').disabled = !uiEnabled;
- DisplayOptions.getInstance().setEnabled(
- uiEnabled, unifiedEnabled, mirroredEnabled);
- }
- },
-
- /**
- * Enables factory reset section.
- * @private
- */
- enableFactoryResetSection_: function() {
- $('factory-reset-section').hidden = false;
- },
-
- /**
- * Set the checked state of the metrics reporting checkbox.
- * @private
- */
- setMetricsReportingCheckboxState_: function(checked,
- policyManaged,
- ownerManaged) {
- $('metrics-reporting-enabled').checked = checked;
- $('metrics-reporting-enabled').disabled = policyManaged || ownerManaged;
-
- // If checkbox gets disabled then add an attribute for displaying the
- // special icon. Otherwise remove the indicator attribute.
- if (policyManaged) {
- $('metrics-reporting-disabled-icon').setAttribute('controlled-by',
- 'policy');
- } else if (ownerManaged) {
- $('metrics-reporting-disabled-icon').setAttribute('controlled-by',
- 'owner');
- } else {
- $('metrics-reporting-disabled-icon').removeAttribute('controlled-by');
- }
-
- },
-
- /**
- * @private
- */
- setMetricsReportingSettingVisibility_: function(visible) {
- if (visible)
- $('metrics-reporting-setting').style.display = 'block';
- else
- $('metrics-reporting-setting').style.display = 'none';
- },
-
- /**
- * Set the checked state of the Safe Browsing Extended Reporting Enabled
- * checkbox.
- * @private
- */
- setExtendedReportingEnabledCheckboxState_: function(checked) {
- $('safeBrowsingExtendedReportingCheckbox').checked = checked;
- },
-
- /**
- * Set network prediction checkbox value.
- *
- * @param {{value: number, disabled: boolean}} pref Information about
- * network prediction options. |pref.value| is the value of network
- * prediction options. |pref.disabled| shows if the pref is not user
- * modifiable.
- * @private
- */
- setNetworkPredictionValue_: function(pref) {
- var checkbox = $('networkPredictionOptions');
- checkbox.disabled = pref.disabled ||
- loadTimeData.getBoolean('profileIsGuest');
- checkbox.checked = (pref.value != NetworkPredictionOptions.NEVER);
- },
-
- /**
- * Set the font size selected item. This item actually reflects two
- * preferences: the default font size and the default fixed font size.
- *
- * @param {{value: number, disabled: boolean, controlledBy: string}} pref
- * Information about the font size preferences. |pref.value| is the
- * value of the default font size pref. |pref.disabled| is true if
- * either pref not user modifiable. |pref.controlledBy| is the source of
- * the pref value(s) if either pref is currently not controlled by the
- * user.
- * @private
- */
- setFontSize_: function(pref) {
- var selectCtl = /** @type {HTMLSelectElement} */($('defaultFontSize'));
- selectCtl.disabled = pref.disabled;
- // Create a synthetic pref change event decorated as
- // CoreOptionsHandler::CreateValueForPref() does.
- var event = new Event('synthetic-font-size');
- event.value = {
- value: pref.value,
- controlledBy: pref.controlledBy,
- disabled: pref.disabled
- };
- $('font-size-indicator').handlePrefChange(event);
-
- for (var i = 0; i < selectCtl.options.length; i++) {
- if (selectCtl.options[i].value == pref.value) {
- selectCtl.selectedIndex = i;
- if ($('Custom'))
- selectCtl.remove($('Custom').index);
- return;
- }
- }
-
- // Add/Select Custom Option in the font size label list.
- if (!$('Custom')) {
- var option = new Option(loadTimeData.getString('fontSizeLabelCustom'),
- -1, false, true);
- option.setAttribute('id', 'Custom');
- selectCtl.add(option);
- }
- $('Custom').selected = true;
- },
-
- /**
- * Populate the page zoom selector with values received from the caller.
- * @param {Array} items An array of items to populate the selector.
- * each object is an array with three elements as follows:
- * 0: The title of the item (string).
- * 1: The value of the item (number).
- * 2: Whether the item should be selected (boolean).
- * @private
- */
- setupPageZoomSelector_: function(items) {
- var element = $('defaultZoomFactor');
-
- // Remove any existing content.
- element.textContent = '';
-
- // Insert new child nodes into select element.
- var value, title, selected;
- for (var i = 0; i < items.length; i++) {
- title = items[i][0];
- value = items[i][1];
- selected = items[i][2];
- element.appendChild(new Option(title, value, false, selected));
- }
- },
-
- /**
- * Shows/hides the autoOpenFileTypesResetToDefault button and label, with
- * animation.
- * @param {boolean} display Whether to show the button and label or not.
- * @private
- */
- setAutoOpenFileTypesDisplayed_: function(display) {
- if ($('advanced-settings').hidden) {
- // If the Advanced section is hidden, don't animate the transition.
- $('auto-open-file-types-section').hidden = !display;
- } else {
- if (display) {
- this.showSectionWithAnimation_(
- $('auto-open-file-types-section'),
- $('auto-open-file-types-container'));
- } else {
- this.hideSectionWithAnimation_(
- $('auto-open-file-types-section'),
- $('auto-open-file-types-container'));
- }
- }
- },
-
- /**
- * Set the enabled state for the proxy settings button and its associated
- * message when extension controlled.
- * @param {boolean} disabled Whether the button should be disabled.
- * @param {boolean} extensionControlled Whether the proxy is extension
- * controlled.
- * @private
- */
- setupProxySettingsButton_: function(disabled, extensionControlled) {
- if (!cr.isChromeOS) {
- $('proxiesConfigureButton').disabled = disabled;
- $('proxiesLabel').textContent =
- loadTimeData.getString(extensionControlled ?
- 'proxiesLabelExtension' : 'proxiesLabelSystem');
- }
- },
-
- /**
- * Set the initial state of the spoken feedback checkbox.
- * @private
- */
- setSpokenFeedbackCheckboxState_: function(checked) {
- $('accessibility-spoken-feedback-check').checked = checked;
- },
-
- /**
- * Set the initial state of the high contrast checkbox.
- * @private
- */
- setHighContrastCheckboxState_: function(checked) {
- $('accessibility-high-contrast-check').checked = checked;
- },
-
- /**
- * Set the initial state of the virtual keyboard checkbox.
- * @private
- */
- setVirtualKeyboardCheckboxState_: function(checked) {
- // TODO(zork): Update UI
- },
-
- /**
- * Show/hide mouse settings slider.
- * @private
- */
- showMouseControls_: function(show) {
- $('mouse-settings').hidden = !show;
- },
-
- /**
- * Adds hidden warning boxes for settings potentially controlled by
- * extensions.
- * @param {string} parentDiv The div name to append the bubble to.
- * @param {string} bubbleId The ID to use for the bubble.
- * @param {boolean} first Add as first node if true, otherwise last.
- * @private
- */
- addExtensionControlledBox_: function(parentDiv, bubbleId, first) {
- var bubble = $('extension-controlled-warning-template').cloneNode(true);
- bubble.id = bubbleId;
- var parent = $(parentDiv);
- if (first)
- parent.insertBefore(bubble, parent.firstChild);
- else
- parent.appendChild(bubble);
- },
-
- /**
- * Adds a bubble showing that an extension is controlling a particular
- * setting.
- * @param {string} parentDiv The div name to append the bubble to.
- * @param {string} bubbleId The ID to use for the bubble.
- * @param {string} extensionId The ID of the controlling extension.
- * @param {string} extensionName The name of the controlling extension.
- * @private
- */
- toggleExtensionControlledBox_: function(
- parentDiv, bubbleId, extensionId, extensionName) {
- var bubble = $(bubbleId);
- assert(bubble);
- bubble.hidden = extensionId.length == 0;
- if (bubble.hidden)
- return;
-
- // Set the extension image.
- var div = bubble.firstElementChild;
- div.style.backgroundImage =
- 'url(chrome://extension-icon/' + extensionId + '/24/1)';
-
- // Set the bubble label.
- var label = loadTimeData.getStringF('extensionControlled', extensionName);
- var docFrag = parseHtmlSubset('<div>' + label + '</div>', ['B', 'DIV']);
- div.innerHTML = docFrag.firstChild.innerHTML;
-
- // Wire up the button to disable the right extension.
- var button = div.nextElementSibling;
- button.dataset.extensionId = extensionId;
- },
-
- /**
- * Toggles the warning boxes that show which extension is controlling
- * various settings of Chrome.
- * @param {{searchEngine: options.ExtensionData,
- * homePage: options.ExtensionData,
- * startUpPage: options.ExtensionData,
- * newTabPage: options.ExtensionData,
- * proxy: options.ExtensionData}} details A dictionary of ID+name
- * pairs for each of the settings controlled by an extension.
- * @private
- */
- toggleExtensionIndicators_: function(details) {
- this.toggleExtensionControlledBox_('search-section-content',
- 'search-engine-controlled',
- details.searchEngine.id,
- details.searchEngine.name);
- this.toggleExtensionControlledBox_('extension-controlled-container',
- 'homepage-controlled',
- details.homePage.id,
- details.homePage.name);
- this.toggleExtensionControlledBox_('startup-section-content',
- 'startpage-controlled',
- details.startUpPage.id,
- details.startUpPage.name);
- this.toggleExtensionControlledBox_('newtab-section-content',
- 'newtab-controlled',
- details.newTabPage.id,
- details.newTabPage.name);
- this.toggleExtensionControlledBox_('proxy-section-content',
- 'proxy-controlled',
- details.proxy.id,
- details.proxy.name);
-
- // The proxy section contains just the warning box and nothing else, so
- // if we're hiding the proxy warning box, we should also hide its header
- // section.
- $('proxy-section').hidden = details.proxy.id.length == 0;
- },
-
-
- /**
- * Show/hide touchpad-related settings.
- * @private
- */
- showTouchpadControls_: function(show) {
- $('touchpad-settings').hidden = !show;
- $('accessibility-tap-dragging').hidden = !show;
- },
-
- /**
- * Sets the state of the checkbox indicating if Bluetooth is turned on. The
- * state of the "Find devices" button and the list of discovered devices may
- * also be affected by a change to the state.
- * @param {boolean} checked Flag Indicating if Bluetooth is turned on.
- * @private
- */
- setBluetoothState_: function(checked) {
- $('enable-bluetooth').checked = checked;
- $('bluetooth-paired-devices-list').parentNode.hidden = !checked;
- $('bluetooth-add-device').hidden = !checked;
- $('bluetooth-reconnect-device').hidden = !checked;
- },
-
- /**
- * Process a bluetooth.onAdapterStateChanged event.
- * @param {!chrome.bluetooth.AdapterState} state
- * @private
- */
- onBluetoothAdapterStateChanged_: function(state) {
- var disallowBluetooth = !loadTimeData.getBoolean('allowBluetooth');
- // If allowBluetooth is false, state.available will always be false, so
- // assume Bluetooth is available but disabled by policy.
- if (!state || (!state.available && !disallowBluetooth)) {
- this.bluetoothAdapterState_ = null;
- $('bluetooth-devices').hidden = true;
- return;
- }
- $('bluetooth-devices').hidden = false;
- this.bluetoothAdapterState_ = state;
- this.setBluetoothState_(state.powered);
-
- var enableBluetoothEl = $('enable-bluetooth');
- if (disallowBluetooth) {
- enableBluetoothEl.setAttribute('pref', 'cros.device.allow_bluetooth');
- enableBluetoothEl.setAttribute('controlled-by', 'policy');
- enableBluetoothEl.disabled = true;
- $('bluetooth-controlled-setting-indicator').hidden = false;
- return;
- }
- enableBluetoothEl.removeAttribute('pref');
- enableBluetoothEl.removeAttribute('controlled-by');
- enableBluetoothEl.disabled = false;
- $('bluetooth-controlled-setting-indicator').hidden = true;
-
- // Flush the device lists.
- $('bluetooth-paired-devices-list').clear();
- $('bluetooth-unpaired-devices-list').clear();
- if (state.powered) {
- options.BluetoothOptions.updateDiscoveryState(state.discovering);
- // Update the device lists.
- chrome.bluetooth.getDevices(function(devices) {
- for (var device of devices)
- this.updateBluetoothDevicesList_(device);
- }.bind(this));
- } else {
- options.BluetoothOptions.dismissOverlay();
- }
- },
-
- /**
- * Process a bluetooth.onDeviceAdded or onDeviceChanged event and update the
- * device list.
- * @param {!chrome.bluetooth.Device} device
- * @private
- */
- onBluetoothDeviceAddedOrChanged_: function(device) {
- this.updateBluetoothDevicesList_(device);
- },
-
- /**
- * Process a bluetooth.onDeviceRemoved event and update the device list.
- * @param {!chrome.bluetooth.Device} device
- * @private
- */
- onBluetoothDeviceRemoved_: function(device) {
- this.removeBluetoothDevice_(device.address);
- },
-
- /**
- * Process a bluetoothPrivate onPairing event and update the device list.
- * @param {!chrome.bluetoothPrivate.PairingEvent} pairing_event
- * @private
- */
- onBluetoothPrivatePairing_: function(pairing_event) {
- this.updateBluetoothDevicesList_(pairing_event.device);
- BluetoothPairing.onBluetoothPairingEvent(pairing_event);
- },
-
- /**
- * Add |device| to the appropriate list of Bluetooth devices.
- * @param {!chrome.bluetooth.Device} device
- * @private
- */
- addBluetoothDeviceToList_: function(device) {
- // Display the "connecting" (already paired or not yet paired) and the
- // paired devices in the same list.
- if (device.paired || device.connecting)
- $('bluetooth-paired-devices-list').appendDevice(device);
- else
- $('bluetooth-unpaired-devices-list').appendDevice(device);
- },
-
- /**
- * Add |device| to the appropriate list of Bluetooth devices or update the
- * entry if a device with a matching |address| property exists.
- * @param {!chrome.bluetooth.Device} device
- * @private
- */
- updateBluetoothDevicesList_: function(device) {
- // Display the "connecting" (already paired or not yet paired) and the
- // paired devices in the same list.
- if (device.paired || device.connecting) {
- // Test to see if the device is currently in the unpaired list, in which
- // case it should be removed from that list.
- var index = $('bluetooth-unpaired-devices-list').find(device.address);
- if (index != undefined)
- $('bluetooth-unpaired-devices-list').deleteItemAtIndex(index);
- } else {
- // Test to see if the device is currently in the paired list, in which
- // case it should be removed from that list.
- var index = $('bluetooth-paired-devices-list').find(device.address);
- if (index != undefined)
- $('bluetooth-paired-devices-list').deleteItemAtIndex(index);
- }
- this.addBluetoothDeviceToList_(device);
- },
-
- /**
- * Removes an element from the list of available devices.
- * @param {string} address Unique address of the device.
- * @private
- */
- removeBluetoothDevice_: function(address) {
- var index = $('bluetooth-unpaired-devices-list').find(address);
- if (index != undefined) {
- $('bluetooth-unpaired-devices-list').deleteItemAtIndex(index);
- } else {
- index = $('bluetooth-paired-devices-list').find(address);
- if (index != undefined)
- $('bluetooth-paired-devices-list').deleteItemAtIndex(index);
- }
- },
-
- /**
- * Shows the overlay dialog for changing the user avatar image.
- * @private
- */
- showImagerPickerOverlay_: function() {
- PageManager.showPageByName('changePicture');
- },
-
- /**
- * Shows (or not) the "User" section of the settings page based on whether
- * any of the sub-sections are present (or not).
- * @private
- */
- maybeShowUserSection_: function() {
- $('sync-users-section').hidden =
- $('profiles-section').hidden &&
- $('sync-section').hidden &&
- $('profiles-supervised-dashboard-tip').hidden;
- },
-
- /**
- * Updates the date and time section with time sync information.
- * @param {boolean} canSetTime Whether the system time can be set.
- * @private
- */
- setCanSetTime_: function(canSetTime) {
- // If the time has been network-synced, it cannot be set manually.
- $('set-time').hidden = !canSetTime;
- },
-
- /**
- * Handle the 'set date and time' button click.
- * @private
- */
- handleSetTime_: function() {
- chrome.send('showSetTime');
- },
-
- /**
- * Enables the given element if possible; on Chrome OS, it won't enable
- * an element that must stay disabled for the session type.
- * @param {!Element} element Element to enable.
- */
- enableElementIfPossible_: function(element) {
- if (cr.isChromeOS)
- UIAccountTweaks.enableElementIfPossible(element);
- else
- element.disabled = false;
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(BrowserOptions, [
- 'deleteCurrentProfile',
- 'enableCertificateButton',
- 'enableDisplaySettings',
- 'enableFactoryResetSection',
- 'getCurrentProfile',
- 'getStartStopSyncButton',
- 'notifyInitializationComplete',
- 'removeBluetoothDevice',
- 'scrollToSection',
- 'setAccountPictureManaged',
- 'setAllHotwordSectionsVisible',
- 'setAudioHistorySectionVisible',
- 'setAutoOpenFileTypesDisplayed',
- 'setCanSetTime',
- 'setExtendedReportingEnabledCheckboxState',
- 'setFontSize',
- 'setHighContrastCheckboxState',
- 'setHotwordRetrainLinkVisible',
- 'setMetricsReportingCheckboxState',
- 'setMetricsReportingSettingVisibility',
- 'setNativeThemeButtonEnabled',
- 'setNetworkPredictionValue',
- 'setNowSectionVisible',
- 'setProfilesInfo',
- 'setSpokenFeedbackCheckboxState',
- 'setStylusInputStatus',
- 'setSystemTimezoneAutomaticDetectionManaged',
- 'setSystemTimezoneManaged',
- 'setThemesResetButtonEnabled',
- 'setVirtualKeyboardCheckboxState',
- 'setWallpaperManaged',
- 'setupPageZoomSelector',
- 'setupProxySettingsButton',
- 'showCreateProfileError',
- 'showCreateProfileSuccess',
- 'showCreateProfileWarning',
- 'showHotwordAlwaysOnSection',
- 'showHotwordNoDspSection',
- 'showHotwordSection',
- 'showMouseControls',
- 'showSupervisedUserImportError',
- 'showSupervisedUserImportSuccess',
- 'showTouchpadControls',
- 'toggleExtensionIndicators',
- 'updateAccountPicture',
- 'updateDefaultBrowserState',
- 'updateEasyUnlock',
- 'updateManagesSupervisedUsers',
- 'updateSearchEngines',
- 'updateSyncState',
- ]);
-
- if (cr.isChromeOS) {
- /**
- * Returns username (canonical email) of the user logged in (ChromeOS only).
- * @return {string} user email.
- */
- // TODO(jhawkins): Investigate the use case for this method.
- BrowserOptions.getLoggedInUsername = function() {
- return BrowserOptions.getInstance().username_;
- };
-
- /**
- * Shows Android Apps settings when they are available.
- * (Chrome OS only).
- */
- BrowserOptions.showAndroidAppsSection = function(isArcEnabled) {
- var section = $('android-apps-section');
- if (!section)
- return;
-
- section.hidden = false;
- };
-
- /**
- * Shows/hides Android Settings app section.
- * (Chrome OS only).
- */
- BrowserOptions.setAndroidAppsSettingsVisibility = function(isVisible) {
- var settings = $('android-apps-settings');
- if (!settings)
- return;
-
- settings.hidden = !isVisible;
- };
- }
-
- // Export
- return {
- BrowserOptions: BrowserOptions
- };
-});
diff --git a/chromium/chrome/browser/resources/options/browser_options_profile_list.js b/chromium/chrome/browser/resources/options/browser_options_profile_list.js
deleted file mode 100644
index bd232745381..00000000000
--- a/chromium/chrome/browser/resources/options/browser_options_profile_list.js
+++ /dev/null
@@ -1,141 +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.
-
-cr.define('options.browser_options', function() {
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var DeletableItemList = options.DeletableItemList;
- /** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel;
-
- /**
- * Creates a new profile list item.
- * @param {Object} profileInfo The profile this item represents.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function ProfileListItem(profileInfo) {
- var el = cr.doc.createElement('div');
- el.profileInfo_ = profileInfo;
- ProfileListItem.decorate(el);
- return el;
- }
-
- /**
- * Decorates an element as a profile list item.
- * @param {!HTMLElement} el The element to decorate.
- */
- ProfileListItem.decorate = function(el) {
- el.__proto__ = ProfileListItem.prototype;
- el.decorate();
- };
-
- ProfileListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /**
- * @type {string} the file path of this profile list item.
- */
- get profilePath() {
- return this.profileInfo_.filePath;
- },
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- var profileInfo = this.profileInfo_;
-
- var containerEl = this.ownerDocument.createElement('div');
- containerEl.className = 'profile-container';
-
- var iconEl = this.ownerDocument.createElement('img');
- iconEl.className = 'profile-img';
- iconEl.style.content = cr.icon.getImage(profileInfo.iconURL);
- iconEl.alt = '';
- containerEl.appendChild(iconEl);
-
- var nameEl = this.ownerDocument.createElement('div');
- nameEl.className = 'profile-name';
- if (profileInfo.isCurrentProfile)
- nameEl.classList.add('profile-item-current');
- containerEl.appendChild(nameEl);
-
- var displayName = profileInfo.name;
- if (profileInfo.isCurrentProfile) {
- displayName = loadTimeData.getStringF('profilesListItemCurrent',
- profileInfo.name);
- }
- nameEl.textContent = displayName;
-
- if (profileInfo.isSupervised) {
- var supervisedEl = this.ownerDocument.createElement('div');
- supervisedEl.className = 'profile-supervised';
- supervisedEl.textContent = profileInfo.isChild ?
- loadTimeData.getString('childLabel') :
- loadTimeData.getString('supervisedUserLabel');
- containerEl.appendChild(supervisedEl);
- }
-
- this.contentElement.appendChild(containerEl);
-
- // Ensure that the button cannot be tabbed to for accessibility reasons.
- this.closeButtonElement.tabIndex = -1;
- },
- };
-
- var ProfileList = cr.ui.define('list');
-
- ProfileList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- /** @override */
- decorate: function() {
- DeletableItemList.prototype.decorate.call(this);
- this.selectionModel = new ListSingleSelectionModel();
- },
-
- /** @override */
- createItem: function(pageInfo) {
- var item = new ProfileListItem(pageInfo);
- item.deletable = this.canDeleteItems_;
- return item;
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- ManageProfileOverlay.showDeleteDialog(this.dataModel.item(index));
- },
-
- /** @override */
- activateItemAtIndex: function(index) {
- // Don't allow the user to edit a profile that is not current.
- var profileInfo = this.dataModel.item(index);
- if (profileInfo.isCurrentProfile)
- ManageProfileOverlay.showManageDialog(profileInfo);
- },
-
- /**
- * Sets whether items in this list are deletable.
- */
- set canDeleteItems(value) {
- this.canDeleteItems_ = value;
- },
-
- /**
- * @type {boolean} whether the items in this list are deletable.
- */
- get canDeleteItems() {
- return this.canDeleteItems_;
- },
-
- /**
- * If false, items in this list will not be deletable.
- * @private
- */
- canDeleteItems_: true,
- };
-
- return {
- ProfileList: ProfileList
- };
-});
diff --git a/chromium/chrome/browser/resources/options/browser_options_startup_page_list.js b/chromium/chrome/browser/resources/options/browser_options_startup_page_list.js
deleted file mode 100644
index 97fae10bb89..00000000000
--- a/chromium/chrome/browser/resources/options/browser_options_startup_page_list.js
+++ /dev/null
@@ -1,321 +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.
-
-cr.define('options.browser_options', function() {
- /** @const */ var AutocompleteList = cr.ui.AutocompleteList;
- /** @const */ var InlineEditableItem = options.InlineEditableItem;
- /** @const */ var InlineEditableItemList = options.InlineEditableItemList;
-
- /**
- * Creates a new startup page list item.
- * @param {Object} pageInfo The page this item represents.
- * @constructor
- * @extends {options.InlineEditableItem}
- */
- function StartupPageListItem(pageInfo) {
- var el = cr.doc.createElement('div');
- el.pageInfo_ = pageInfo;
- StartupPageListItem.decorate(el);
- return el;
- }
-
- /**
- * Decorates an element as a startup page list item.
- * @param {!HTMLElement} el The element to decorate.
- */
- StartupPageListItem.decorate = function(el) {
- el.__proto__ = StartupPageListItem.prototype;
- el.decorate();
- };
-
- StartupPageListItem.prototype = {
- __proto__: InlineEditableItem.prototype,
-
- /**
- * Input field for editing the page url.
- * @type {HTMLElement}
- * @private
- */
- urlField_: null,
-
- /** @override */
- decorate: function() {
- InlineEditableItem.prototype.decorate.call(this);
-
- var pageInfo = this.pageInfo_;
-
- if (pageInfo.modelIndex == -1) {
- this.isPlaceholder = true;
- pageInfo.title = loadTimeData.getString('startupAddLabel');
- pageInfo.url = '';
- }
-
- var titleEl = this.ownerDocument.createElement('div');
- titleEl.className = 'title';
- titleEl.classList.add('favicon-cell');
- titleEl.classList.add('weakrtl');
- titleEl.textContent = pageInfo.title;
- if (!this.isPlaceholder) {
- titleEl.style.backgroundImage = cr.icon.getFavicon(pageInfo.url);
- titleEl.title = pageInfo.tooltip;
- }
-
- this.contentElement.appendChild(titleEl);
-
- var urlEl = this.createEditableTextCell(pageInfo.url);
- urlEl.className = 'url';
- urlEl.classList.add('weakrtl');
- this.contentElement.appendChild(urlEl);
-
- var urlField = /** @type {HTMLElement} */(urlEl.querySelector('input'));
- urlField.className = 'weakrtl';
- urlField.placeholder = loadTimeData.getString('startupPagesPlaceholder');
- this.urlField_ = urlField;
-
- this.addEventListener('commitedit', this.onEditCommitted_);
-
- var self = this;
- urlField.addEventListener('focus', function(event) {
- self.parentNode.autocompleteList.attachToInput(urlField);
- });
- urlField.addEventListener('blur', function(event) {
- self.parentNode.autocompleteList.detach();
- });
-
- if (!this.isPlaceholder)
- titleEl.draggable = true;
- },
-
- /** @override */
- get currentInputIsValid() {
- return this.urlField_.validity.valid;
- },
-
- /** @override */
- get hasBeenEdited() {
- return this.urlField_.value != this.pageInfo_.url;
- },
-
- /**
- * Called when committing an edit; updates the model.
- * @param {Event} e The end event.
- * @private
- */
- onEditCommitted_: function(e) {
- var url = this.urlField_.value;
- if (this.isPlaceholder)
- chrome.send('addStartupPage', [url]);
- else
- chrome.send('editStartupPage', [this.pageInfo_.modelIndex, url]);
- },
- };
-
- var StartupPageList = cr.ui.define('list');
-
- StartupPageList.prototype = {
- __proto__: InlineEditableItemList.prototype,
-
- /**
- * An autocomplete suggestion list for URL editing.
- * @type {AutocompleteList}
- */
- autocompleteList: null,
-
- /**
- * The drop position information: "below" or "above".
- */
- dropPos: null,
-
- /** @override */
- decorate: function() {
- InlineEditableItemList.prototype.decorate.call(this);
-
- // Listen to drag and drop events.
- this.addEventListener('dragstart', this.handleDragStart_.bind(this));
- this.addEventListener('dragenter', this.handleDragEnter_.bind(this));
- this.addEventListener('dragover', this.handleDragOver_.bind(this));
- this.addEventListener('drop', this.handleDrop_.bind(this));
- this.addEventListener('dragleave', this.handleDragLeave_.bind(this));
- this.addEventListener('dragend', this.handleDragEnd_.bind(this));
- },
-
- /** @override */
- createItem: function(pageInfo) {
- var item = new StartupPageListItem(pageInfo);
- item.urlField_.disabled = this.disabled;
- return item;
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- chrome.send('removeStartupPages', [index]);
- },
-
- /**
- * Computes the target item of drop event.
- * @param {Event} e The drop or dragover event.
- * @private
- */
- getTargetFromDropEvent_: function(e) {
- var target = e.target;
- // e.target may be an inner element of the list item
- while (target != null && !(target instanceof StartupPageListItem)) {
- target = target.parentNode;
- }
- return target;
- },
-
- /**
- * Handles the dragstart event.
- * @param {Event} e The dragstart event.
- * @private
- */
- handleDragStart_: function(e) {
- // Prevent dragging if the list is disabled.
- if (this.disabled) {
- e.preventDefault();
- return false;
- }
-
- var target = this.getTargetFromDropEvent_(e);
- // StartupPageListItem should be the only draggable element type in the
- // page but let's make sure.
- if (target instanceof StartupPageListItem) {
- this.draggedItem = target;
- this.draggedItem.editable = false;
- e.dataTransfer.effectAllowed = 'move';
- // We need to put some kind of data in the drag or it will be
- // ignored. Use the URL in case the user drags to a text field or the
- // desktop.
- e.dataTransfer.setData('text/plain', target.urlField_.value);
- }
- },
-
- /**
- * Handles the dragenter event.
- * @param {Event} e The dragenter event.
- * @private
- */
- handleDragEnter_: function(e) {
- e.preventDefault();
- },
-
- /**
- * Handles the dragover event.
- * @param {Event} e The dragover event.
- * @private
- */
- handleDragOver_: function(e) {
- var dropTarget = this.getTargetFromDropEvent_(e);
- // Determines whether the drop target is to accept the drop.
- // The drop is only successful on another StartupPageListItem.
- if (!(dropTarget instanceof StartupPageListItem) ||
- dropTarget == this.draggedItem || dropTarget.isPlaceholder) {
- this.hideDropMarker_();
- return;
- }
- // Compute the drop postion. Should we move the dragged item to
- // below or above the drop target?
- var rect = dropTarget.getBoundingClientRect();
- var dy = e.clientY - rect.top;
- var yRatio = dy / rect.height;
- var dropPos = yRatio <= .5 ? 'above' : 'below';
- this.dropPos = dropPos;
- this.showDropMarker_(dropTarget, dropPos);
- e.preventDefault();
- },
-
- /**
- * Handles the drop event.
- * @param {Event} e The drop event.
- * @private
- */
- handleDrop_: function(e) {
- var dropTarget = this.getTargetFromDropEvent_(e);
-
- if (!(dropTarget instanceof StartupPageListItem) ||
- dropTarget.pageInfo_.modelIndex == -1) {
- return;
- }
-
- this.hideDropMarker_();
-
- // Insert the selection at the new position.
- var newIndex = this.dataModel.indexOf(dropTarget.pageInfo_);
- if (this.dropPos == 'below')
- newIndex += 1;
-
- // If there are selected indexes, it was a re-order.
- if (this.selectionModel.selectedIndexes.length > 0) {
- chrome.send('dragDropStartupPage',
- [newIndex, this.selectionModel.selectedIndexes]);
- return;
- }
-
- // Otherwise it was potentially a drop of new data (e.g. a bookmark).
- var url = e.dataTransfer.getData('url');
- if (url) {
- e.preventDefault();
- chrome.send('addStartupPage', [url, newIndex]);
- }
- },
-
- /**
- * Handles the dragleave event.
- * @param {Event} e The dragleave event.
- * @private
- */
- handleDragLeave_: function(e) {
- this.hideDropMarker_();
- },
-
- /**
- * Handles the dragend event.
- * @param {Event} e The dragend event.
- * @private
- */
- handleDragEnd_: function(e) {
- this.draggedItem.editable = true;
- this.draggedItem.updateEditState();
- },
-
- /**
- * Shows and positions the marker to indicate the drop target.
- * @param {HTMLElement} target The current target list item of drop.
- * @param {string} pos 'below' or 'above'.
- * @private
- */
- showDropMarker_: function(target, pos) {
- window.clearTimeout(this.hideDropMarkerTimer_);
- var marker = $('startupPagesListDropmarker');
- var rect = target.getBoundingClientRect();
- var markerHeight = 6;
- if (pos == 'above') {
- marker.style.top = (rect.top - markerHeight / 2) + 'px';
- } else {
- marker.style.top = (rect.bottom - markerHeight / 2) + 'px';
- }
- marker.style.width = rect.width + 'px';
- marker.style.left = rect.left + 'px';
- marker.style.display = 'block';
- },
-
- /**
- * Hides the drop marker.
- * @private
- */
- hideDropMarker_: function() {
- // Hide the marker in a timeout to reduce flickering as we move between
- // valid drop targets.
- window.clearTimeout(this.hideDropMarkerTimer_);
- this.hideDropMarkerTimer_ = window.setTimeout(function() {
- $('startupPagesListDropmarker').style.display = '';
- }, 100);
- },
- };
-
- return {
- StartupPageList: StartupPageList
- };
-});
diff --git a/chromium/chrome/browser/resources/options/certificate_backup_overlay.html b/chromium/chrome/browser/resources/options/certificate_backup_overlay.html
deleted file mode 100644
index 92601efb5c8..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_backup_overlay.html
+++ /dev/null
@@ -1,40 +0,0 @@
-<div id="certificateBackupOverlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{certificateExportPasswordDescription}</h1>
- <div class="content-area">
- <table>
- <tr>
- <td id="certificate-backup-password-label">
- $i18n{certificatePasswordLabel}
- </td>
- <td>
- <input id="certificateBackupPassword" type="password"
- aria-labelledby="certificate-backup-password-label">
- </td>
- </tr>
- <tr>
- <td id="certificate-backup-password-2-label">
- $i18n{certificateConfirmPasswordLabel}
- </td>
- <td>
- <input id="certificateBackupPassword2" type="password"
- aria-labelledby="certificate-backup-password-2-label">
- </td>
- </tr>
- </table>
- <p>
- <span>$i18n{certificateExportPasswordHelp}</span>
- </p>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="certificateBackupCancelButton" type="reset">
- $i18n{cancel}
- </button>
- <button id="certificateBackupOkButton" class="default-button"
- type="submit" disabled>
- $i18n{ok}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/certificate_backup_overlay.js b/chromium/chrome/browser/resources/options/certificate_backup_overlay.js
deleted file mode 100644
index 9c516b0f2a8..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_backup_overlay.js
+++ /dev/null
@@ -1,114 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * CertificateBackupOverlay class
- * Encapsulated handling of the 'enter backup password' overlay page.
- * @class
- */
- function CertificateBackupOverlay() {
- Page.call(this, 'certificateBackupOverlay', '', 'certificateBackupOverlay');
- }
-
- cr.addSingletonGetter(CertificateBackupOverlay);
-
- CertificateBackupOverlay.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
- $('certificateBackupCancelButton').onclick = function(event) {
- self.cancelBackup_();
- };
- $('certificateBackupOkButton').onclick = function(event) {
- self.finishBackup_();
- };
- var onBackupPasswordInput = function(event) {
- self.comparePasswords_();
- };
- $('certificateBackupPassword').oninput = onBackupPasswordInput;
- $('certificateBackupPassword2').oninput = onBackupPasswordInput;
-
- self.clearInputFields_();
- },
-
- /**
- * Clears any uncommitted input, and dismisses the overlay.
- * @private
- */
- dismissOverlay_: function() {
- this.clearInputFields_();
- PageManager.closeOverlay();
- },
-
- /**
- * Attempt the Backup operation.
- * The overlay will be left up with inputs disabled until the backend
- * finishes and dismisses it.
- * @private
- */
- finishBackup_: function() {
- chrome.send('exportPersonalCertificatePasswordSelected',
- [$('certificateBackupPassword').value]);
- $('certificateBackupCancelButton').disabled = true;
- $('certificateBackupOkButton').disabled = true;
- $('certificateBackupPassword').disabled = true;
- $('certificateBackupPassword2').disabled = true;
- },
-
- /**
- * Cancel the Backup operation.
- * @private
- */
- cancelBackup_: function() {
- chrome.send('cancelImportExportCertificate');
- this.dismissOverlay_();
- },
-
- /**
- * Compares the password fields and sets the button state appropriately.
- * @private
- */
- comparePasswords_: function() {
- var password1 = $('certificateBackupPassword').value;
- var password2 = $('certificateBackupPassword2').value;
- $('certificateBackupOkButton').disabled =
- !password1 || password1 != password2;
- },
-
- /**
- * Clears the value of each input field.
- * @private
- */
- clearInputFields_: function() {
- $('certificateBackupPassword').value = '';
- $('certificateBackupPassword2').value = '';
- $('certificateBackupPassword').disabled = false;
- $('certificateBackupPassword2').disabled = false;
- $('certificateBackupCancelButton').disabled = false;
- $('certificateBackupOkButton').disabled = true;
- },
- };
-
- CertificateBackupOverlay.show = function() {
- CertificateBackupOverlay.getInstance().clearInputFields_();
- PageManager.showPageByName('certificateBackupOverlay');
- };
-
- CertificateBackupOverlay.dismiss = function() {
- CertificateBackupOverlay.getInstance().dismissOverlay_();
- };
-
- // Export
- return {
- CertificateBackupOverlay: CertificateBackupOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.html b/chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.html
deleted file mode 100644
index 198002dd621..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<div id="certificateEditCaTrustOverlay" class="page" hidden>
- <h1><span>$i18n{certificateEditCaTitle}</span></h1>
- <div class="close-button"></div>
- <div class="content-area">
- <div>
- <span id="certificateEditCaTrustDescription"></span>
- </div>
- <section>
- <h3><span>$i18n{certificateEditTrustLabel}</span></h3>
- <div class="checkbox">
- <label id="certificateCaTrustSSLLabel">
- <input id="certificateCaTrustSSLCheckbox" type="checkbox">
- <span>$i18n{certificateCaTrustSSLLabel}</span>
- </label>
- </div>
- <div class="checkbox">
- <label id="certificateCaTrustEmailLabel">
- <input id="certificateCaTrustEmailCheckbox" type="checkbox">
- <span>$i18n{certificateCaTrustEmailLabel}</span>
- </label>
- </div>
- <div class="checkbox">
- <label id="certificateCaTrustObjSignLabel">
- <input id="certificateCaTrustObjSignCheckbox" type="checkbox">
- <span>$i18n{certificateCaTrustObjSignLabel}</span>
- </label>
- </div>
- </section>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="certificateEditCaTrustCancelButton" type="reset">
- $i18n{cancel}
- </button>
- <button id="certificateEditCaTrustOkButton" class="default-button"
- type="submit">
- $i18n{ok}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.js b/chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.js
deleted file mode 100644
index f65b26b4365..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_edit_ca_trust_overlay.js
+++ /dev/null
@@ -1,162 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * CertificateEditCaTrustOverlay class
- * Encapsulated handling of the 'edit ca trust' and 'import ca' overlay pages.
- * @class
- */
- function CertificateEditCaTrustOverlay() {
- Page.call(this, 'certificateEditCaTrustOverlay', '',
- 'certificateEditCaTrustOverlay');
- }
-
- cr.addSingletonGetter(CertificateEditCaTrustOverlay);
-
- CertificateEditCaTrustOverlay.prototype = {
- __proto__: Page.prototype,
-
- /**
- * Dismisses the overlay.
- * @private
- */
- dismissOverlay_: function() {
- PageManager.closeOverlay();
- },
-
- /**
- * Enables or disables input fields.
- * @private
- */
- enableInputs_: function(enabled) {
- $('certificateCaTrustSSLCheckbox').disabled =
- $('certificateCaTrustEmailCheckbox').disabled =
- $('certificateCaTrustObjSignCheckbox').disabled =
- $('certificateEditCaTrustCancelButton').disabled =
- $('certificateEditCaTrustOkButton').disabled = !enabled;
- },
-
- /**
- * Attempt the Edit operation.
- * The overlay will be left up with inputs disabled until the backend
- * finishes and dismisses it.
- * @private
- */
- finishEdit_: function() {
- // TODO(mattm): Send checked values as booleans. For now send them as
- // strings, since WebUIBindings::send does not support any other types :(
- chrome.send('editCaCertificateTrust',
- [this.certId,
- $('certificateCaTrustSSLCheckbox').checked.toString(),
- $('certificateCaTrustEmailCheckbox').checked.toString(),
- $('certificateCaTrustObjSignCheckbox').checked.toString()]);
- this.enableInputs_(false);
- },
-
- /**
- * Cancel the Edit operation.
- * @private
- */
- cancelEdit_: function() {
- this.dismissOverlay_();
- },
-
- /**
- * Attempt the Import operation.
- * The overlay will be left up with inputs disabled until the backend
- * finishes and dismisses it.
- * @private
- */
- finishImport_: function() {
- // TODO(mattm): Send checked values as booleans. For now send them as
- // strings, since WebUIBindings::send does not support any other types :(
- chrome.send('importCaCertificateTrustSelected',
- [$('certificateCaTrustSSLCheckbox').checked.toString(),
- $('certificateCaTrustEmailCheckbox').checked.toString(),
- $('certificateCaTrustObjSignCheckbox').checked.toString()]);
- this.enableInputs_(false);
- },
-
- /**
- * Cancel the Import operation.
- * @private
- */
- cancelImport_: function() {
- chrome.send('cancelImportExportCertificate');
- this.dismissOverlay_();
- },
- };
-
- /**
- * Callback from CertificateManagerHandler with the trust values.
- * @param {boolean} trustSSL The initial value of SSL trust checkbox.
- * @param {boolean} trustEmail The initial value of Email trust checkbox.
- * @param {boolean} trustObjSign The initial value of Object Signing trust.
- */
- CertificateEditCaTrustOverlay.populateTrust = function(
- trustSSL, trustEmail, trustObjSign) {
- $('certificateCaTrustSSLCheckbox').checked = trustSSL;
- $('certificateCaTrustEmailCheckbox').checked = trustEmail;
- $('certificateCaTrustObjSignCheckbox').checked = trustObjSign;
- CertificateEditCaTrustOverlay.getInstance().enableInputs_(true);
- };
-
- /**
- * Show the Edit CA Trust overlay.
- * @param {string} certId The id of the certificate to be passed to the
- * certificate manager model.
- * @param {string} certName The display name of the certificate.
- * checkbox.
- */
- CertificateEditCaTrustOverlay.show = function(certId, certName) {
- var self = CertificateEditCaTrustOverlay.getInstance();
- self.certId = certId;
- $('certificateEditCaTrustCancelButton').onclick = function(event) {
- self.cancelEdit_();
- };
- $('certificateEditCaTrustOkButton').onclick = function(event) {
- self.finishEdit_();
- };
- $('certificateEditCaTrustDescription').textContent =
- loadTimeData.getStringF('certificateEditCaTrustDescriptionFormat',
- certName);
- self.enableInputs_(false);
- PageManager.showPageByName('certificateEditCaTrustOverlay');
- chrome.send('getCaCertificateTrust', [certId]);
- };
-
- /**
- * Show the Import CA overlay.
- * @param {string} certName The display name of the certificate.
- * checkbox.
- */
- CertificateEditCaTrustOverlay.showImport = function(certName) {
- var self = CertificateEditCaTrustOverlay.getInstance();
- // TODO(mattm): do we want a view certificate button here like firefox has?
- $('certificateEditCaTrustCancelButton').onclick = function(event) {
- self.cancelImport_();
- };
- $('certificateEditCaTrustOkButton').onclick = function(event) {
- self.finishImport_();
- };
- $('certificateEditCaTrustDescription').textContent =
- loadTimeData.getStringF('certificateImportCaDescriptionFormat',
- certName);
- CertificateEditCaTrustOverlay.populateTrust(false, false, false);
- PageManager.showPageByName('certificateEditCaTrustOverlay');
- };
-
- CertificateEditCaTrustOverlay.dismiss = function() {
- CertificateEditCaTrustOverlay.getInstance().dismissOverlay_();
- };
-
- // Export
- return {
- CertificateEditCaTrustOverlay: CertificateEditCaTrustOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/certificate_import_error_overlay.html b/chromium/chrome/browser/resources/options/certificate_import_error_overlay.html
deleted file mode 100644
index c468b019878..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_import_error_overlay.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<div id="certificateImportErrorOverlay" class="page" hidden>
- <div class="close-button"></div>
- <h1 id="certificateImportErrorOverlayTitle"></h1>
- <div class="content-area">
- <div id="certificateImportErrorOverlayMessage"></div>
- <ul id="certificateImportErrorOverlayCertErrors"></ul>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="certificateImportErrorOverlayOk" class="default-button"
- type="submit">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/certificate_import_error_overlay.js b/chromium/chrome/browser/resources/options/certificate_import_error_overlay.js
deleted file mode 100644
index 2e291859ce8..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_import_error_overlay.js
+++ /dev/null
@@ -1,65 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * CertificateImportErrorOverlay class
- * Displays a list of certificates and errors.
- * @class
- */
- function CertificateImportErrorOverlay() {
- Page.call(this, 'certificateImportErrorOverlay', '',
- 'certificateImportErrorOverlay');
- }
-
- cr.addSingletonGetter(CertificateImportErrorOverlay);
-
- CertificateImportErrorOverlay.prototype = {
- // Inherit CertificateImportErrorOverlay from Page.
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('certificateImportErrorOverlayOk').onclick = function(event) {
- PageManager.closeOverlay();
- };
- },
- };
-
- /**
- * Show an alert overlay with the given message, button titles, and
- * callbacks.
- * @param {string} title The alert title to display to the user.
- * @param {string} message The alert message to display to the user.
- * @param {Array} certErrors The list of cert errors. Each error should have
- * a .name and .error attribute.
- */
- CertificateImportErrorOverlay.show = function(title, message, certErrors) {
- $('certificateImportErrorOverlayTitle').textContent = title;
- $('certificateImportErrorOverlayMessage').textContent = message;
-
- var ul = $('certificateImportErrorOverlayCertErrors');
- ul.innerHTML = '';
- for (var i = 0; i < certErrors.length; ++i) {
- var li = document.createElement('li');
- li.textContent = loadTimeData.getStringF('certificateImportErrorFormat',
- certErrors[i].name,
- certErrors[i].error);
- ul.appendChild(li);
- }
-
- PageManager.showPageByName('certificateImportErrorOverlay');
- };
-
- // Export
- return {
- CertificateImportErrorOverlay: CertificateImportErrorOverlay
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/certificate_manager.css b/chromium/chrome/browser/resources/options/certificate_manager.css
deleted file mode 100644
index 0516e5b580a..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_manager.css
+++ /dev/null
@@ -1,32 +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. */
-
-#certificateManagerPage {
- min-width: 700px;
-}
-
-#certificateRestoreOverlay h1 {
- /* Leave enough space for the close-button. */
- /* TODO(KGR): make dialogs to use flex-boxes instead of relying on padding. */
- padding-right: 35px;
-}
-
-/* Force tab strip to extend to the left and right edges of the window. */
-#certificate-manager-content-area {
- padding: 6px 0 6px 0;
-}
-
-#certificate-manager-content-area .subpages-tab-contents {
- padding-left: 28px;
- padding-right: 14px;
-}
-
-.certificate-tree-table {
- width: 100%;
-}
-
-.certificate-tree {
- /* TODO(mattm): BLAH. Make this not statically sized. */
- height: 300px;
-}
diff --git a/chromium/chrome/browser/resources/options/certificate_manager.html b/chromium/chrome/browser/resources/options/certificate_manager.html
deleted file mode 100644
index b619dd81421..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_manager.html
+++ /dev/null
@@ -1,143 +0,0 @@
-<div id="certificateManagerPage" class="page" hidden>
- <div class="close-button"></div>
- <h1 id='cert-manager-header'>$i18n{certificateManagerPage}</h1>
- <div id="certificate-manager-content-area" class="content-area">
- <!-- Navigation tabs -->
- <div class="subpages-nav-tabs">
- <span id="personal-certs-nav-tab" class="tab"
- tab-contents="personalCertsTab">
- <span class="tab-label">$i18n{personalCertsTabTitle}</span>
- <span class="active-tab-label">$i18n{personalCertsTabTitle}</span>
- </span>
- <span id="server-certs-nav-tab" class="tab" tab-contents="serverCertsTab">
- <span class="tab-label">$i18n{serverCertsTabTitle}</span>
- <span class="active-tab-label">$i18n{serverCertsTabTitle}</span>
- </span>
- <span id="ca-certs-nav-tab" class="tab" tab-contents="caCertsTab">
- <span class="tab-label">$i18n{caCertsTabTitle}</span>
- <span class="active-tab-label">$i18n{caCertsTabTitle}</span>
- </span>
- <span id="other-certs-nav-tab" class="tab" tab-contents="otherCertsTab">
- <span class="tab-label">$i18n{otherCertsTabTitle}</span>
- <span class="active-tab-label">$i18n{otherCertsTabTitle}</span>
- </span>
- </div>
- <!-- TODO(mattm): get rid of use of tables -->
- <!-- Tab contents -->
- <div id="personalCertsTab" class="subpages-tab-contents">
- <table class="certificate-tree-table">
- <tr><td>
- <span>$i18n{personalCertsTabDescription}</span>
- </td></tr>
- <tr><td>
- <tree id="personalCertsTab-tree" class="certificate-tree"
- icon-visibility="parent">
- </tree>
- </td></tr>
- <tr><td>
- <button id="personalCertsTab-view" disabled>
- $i18n{view_certificate}
- </button>
- <button id="personalCertsTab-import" disabled>
- $i18n{import_certificate}
- </button>
-<if expr="chromeos">
- <button id="personalCertsTab-import-and-bind" disabled>
- $i18n{importAndBindCertificate}
- </button>
-</if>
- <button id="personalCertsTab-backup" disabled>
- $i18n{export_certificate}
- </button>
- <button id="personalCertsTab-delete" disabled>
- $i18n{delete_certificate}
- </button>
- </td></tr>
- </table>
- </div>
- <div id="serverCertsTab" class="subpages-tab-contents">
- <table class="certificate-tree-table">
- <tr><td>
- <span>$i18n{serverCertsTabDescription}</span>
- </td></tr>
- <tr><td>
- <tree id="serverCertsTab-tree" class="certificate-tree"
- icon-visibility="parent">
- </tree>
- </td></tr>
- <tr><td>
- <button id="serverCertsTab-view" disabled>
- $i18n{view_certificate}
- </button>
- <button id="serverCertsTab-import" disabled>
- $i18n{import_certificate}
- </button>
- <button id="serverCertsTab-export" disabled>
- $i18n{export_certificate}
- </button>
- <button id="serverCertsTab-delete" disabled>
- $i18n{delete_certificate}
- </button>
- </td></tr>
- </table>
- </div>
- <div id="caCertsTab" class="subpages-tab-contents">
- <table class="certificate-tree-table">
- <tr><td>
- <span>$i18n{caCertsTabDescription}</span>
- </td></tr>
- <tr><td>
- <tree id="caCertsTab-tree" class="certificate-tree"
- icon-visibility="parent">
- </tree>
- </td></tr>
- <tr><td>
- <button id="caCertsTab-view" disabled>
- $i18n{view_certificate}
- </button>
- <button id="caCertsTab-edit" disabled>
- $i18n{edit_certificate}
- </button>
- <button id="caCertsTab-import" disabled>
- $i18n{import_certificate}
- </button>
- <button id="caCertsTab-export" disabled>
- $i18n{export_certificate}
- </button>
- <button id="caCertsTab-delete" disabled>
- $i18n{delete_certificate}
- </button>
- </td></tr>
- </table>
- </div>
- <div id="otherCertsTab" class="subpages-tab-contents">
- <table class="certificate-tree-table">
- <tr><td>
- <span>$i18n{otherCertsTabDescription}</span>
- </td></tr>
- <tr><td>
- <tree id="otherCertsTab-tree" class="certificate-tree"
- icon-visibility="parent"></tree>
- </td></tr>
- <tr><td>
- <button id="otherCertsTab-view" disabled>
- $i18n{view_certificate}
- </button>
- <button id="otherCertsTab-export" disabled>
- $i18n{export_certificate}
- </button>
- <button id="otherCertsTab-delete" disabled>
- $i18n{delete_certificate}
- </button>
- </td></tr>
- </table>
- </div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="certificate-confirm" class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/certificate_manager.js b/chromium/chrome/browser/resources/options/certificate_manager.js
deleted file mode 100644
index 14470082432..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_manager.js
+++ /dev/null
@@ -1,264 +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.
-
-cr.define('options', function() {
- var OptionsPage = options.OptionsPage;
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /////////////////////////////////////////////////////////////////////////////
- // CertificateManagerTab class:
-
- /**
- * blah
- * @param {!string} id The id of this tab.
- * @param {boolean} isKiosk True if dialog is shown during CrOS kiosk launch.
- * @constructor
- */
- function CertificateManagerTab(id, isKiosk) {
- this.tree = $(id + '-tree');
-
- options.CertificatesTree.decorate(this.tree);
- this.tree.addEventListener('change',
- this.handleCertificatesTreeChange_.bind(this));
-
- var tree = this.tree;
-
- this.viewButton = $(id + '-view');
- this.viewButton.onclick = function(e) {
- var selected = tree.selectedItem;
- chrome.send('viewCertificate', [selected.data.id]);
- };
-
- this.editButton = $(id + '-edit');
- if (this.editButton !== null) {
- if (id == 'serverCertsTab') {
- this.editButton.onclick = function(e) {
- var selected = tree.selectedItem;
- chrome.send('editServerCertificate', [selected.data.id]);
- };
- } else if (id == 'caCertsTab') {
- this.editButton.onclick = function(e) {
- var data = tree.selectedItem.data;
- CertificateEditCaTrustOverlay.show(data.id, data.name);
- };
- }
- }
-
- this.backupButton = $(id + '-backup');
- if (this.backupButton !== null) {
- if (id == 'personalCertsTab' && isKiosk) {
- this.backupButton.hidden = true;
- } else {
- this.backupButton.onclick = function(e) {
- var selected = tree.selectedItem;
- chrome.send('exportPersonalCertificate', [selected.data.id]);
- };
- }
- }
-
- this.backupAllButton = $(id + '-backup-all');
- if (this.backupAllButton !== null) {
- if (id == 'personalCertsTab' && isKiosk) {
- this.backupAllButton.hidden = true;
- } else {
- this.backupAllButton.onclick = function(e) {
- chrome.send('exportAllPersonalCertificates');
- };
- }
- }
-
- this.importButton = $(id + '-import');
- if (this.importButton !== null) {
- if (id == 'personalCertsTab') {
- if (isKiosk) {
- this.importButton.hidden = true;
- } else {
- this.importButton.onclick = function(e) {
- chrome.send('importPersonalCertificate', [false]);
- };
- }
- } else if (id == 'serverCertsTab') {
- this.importButton.onclick = function(e) {
- chrome.send('importServerCertificate');
- };
- } else if (id == 'caCertsTab') {
- this.importButton.onclick = function(e) {
- chrome.send('importCaCertificate');
- };
- }
- }
-
- this.importAndBindButton = $(id + '-import-and-bind');
- if (this.importAndBindButton !== null) {
- if (id == 'personalCertsTab') {
- this.importAndBindButton.onclick = function(e) {
- chrome.send('importPersonalCertificate', [true]);
- };
- }
- }
-
- this.exportButton = $(id + '-export');
- if (this.exportButton !== null) {
- if (id == 'personalCertsTab' && isKiosk) {
- this.exportButton.hidden = true;
- } else {
- this.exportButton.onclick = function(e) {
- var selected = tree.selectedItem;
- chrome.send('exportCertificate', [selected.data.id]);
- };
- }
- }
-
- this.deleteButton = $(id + '-delete');
- this.deleteButton.onclick = function(e) {
- var data = tree.selectedItem.data;
- AlertOverlay.show(
- loadTimeData.getStringF(id + 'DeleteConfirm', data.name),
- loadTimeData.getString(id + 'DeleteImpact'),
- loadTimeData.getString('ok'),
- loadTimeData.getString('cancel'),
- function() {
- tree.selectedItem = null;
- chrome.send('deleteCertificate', [data.id]);
- });
- };
- }
-
- CertificateManagerTab.prototype = {
- /**
- * Update button state.
- * @private
- * @param {!Object} data The data of the selected item.
- */
- updateButtonState: function(data) {
- var isCert = !!data && data.isCert;
- var readOnly = !!data && data.readonly;
- var extractable = !!data && data.extractable;
- var hasChildren = this.tree.items.length > 0;
- var isPolicy = !!data && data.policy;
- this.viewButton.disabled = !isCert;
- if (this.editButton !== null)
- this.editButton.disabled = !isCert || isPolicy;
- if (this.backupButton !== null)
- this.backupButton.disabled = !isCert || !extractable;
- if (this.backupAllButton !== null)
- this.backupAllButton.disabled = !hasChildren;
- if (this.exportButton !== null)
- this.exportButton.disabled = !isCert;
- this.deleteButton.disabled = !isCert || readOnly || isPolicy;
- },
-
- /**
- * Handles certificate tree selection change.
- * @private
- * @param {!Event} e The change event object.
- */
- handleCertificatesTreeChange_: function(e) {
- var data = null;
- if (this.tree.selectedItem)
- data = this.tree.selectedItem.data;
-
- this.updateButtonState(data);
- },
- };
-
- /////////////////////////////////////////////////////////////////////////////
- // CertificateManager class:
-
- /**
- * Encapsulated handling of ChromeOS accounts options page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function CertificateManager() {
- Page.call(this, 'certificates',
- loadTimeData.getString('certificateManagerPageTabTitle'),
- 'certificateManagerPage');
- }
-
- cr.addSingletonGetter(CertificateManager);
-
- CertificateManager.prototype = {
- __proto__: Page.prototype,
-
- /** @private {boolean} */
- isKiosk_: false,
-
- /** @param {boolean} isKiosk */
- setIsKiosk: function(isKiosk) {
- this.isKiosk_ = isKiosk;
- },
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- this.personalTab = new CertificateManagerTab('personalCertsTab',
- this.isKiosk_);
- this.serverTab = new CertificateManagerTab('serverCertsTab',
- this.isKiosk_);
- this.caTab = new CertificateManagerTab('caCertsTab', this.isKiosk_);
- this.otherTab = new CertificateManagerTab('otherCertsTab', this.isKiosk_);
-
- if (this.isKiosk_) {
- // No "Servers" and "Authorities" tab in kiosk mode.
- // See http://crbug.com/719907 for details.
- $('server-certs-nav-tab').hidden = true;
- $('ca-certs-nav-tab').hidden = true;
- }
-
- this.addEventListener('visibleChange', this.handleVisibleChange_);
-
- $('certificate-confirm').onclick = function() {
- PageManager.closeOverlay();
- };
- },
-
- initalized_: false,
-
- /**
- * Handler for Page's visible property change event.
- * @private
- * @param {Event} e Property change event.
- */
- handleVisibleChange_: function(e) {
- if (!this.initalized_ && this.visible) {
- this.initalized_ = true;
- OptionsPage.showTab($('personal-certs-nav-tab'));
- chrome.send('populateCertificateManager');
- }
- }
- };
-
- // CertificateManagerHandler callbacks.
- CertificateManager.onPopulateTree = function(args) {
- $(args[0]).populate(args[1]);
- };
-
- CertificateManager.exportPersonalAskPassword = function(args) {
- CertificateBackupOverlay.show();
- };
-
- CertificateManager.importPersonalAskPassword = function(args) {
- CertificateRestoreOverlay.show();
- };
-
- CertificateManager.onModelReady = function(userDbAvailable,
- tpmAvailable) {
- if (!userDbAvailable)
- return;
- if (tpmAvailable)
- $('personalCertsTab-import-and-bind').disabled = false;
- $('personalCertsTab-import').disabled = false;
- $('serverCertsTab-import').disabled = false;
- $('caCertsTab-import').disabled = false;
- };
-
- // Export
- return {
- CertificateManagerTab: CertificateManagerTab,
- CertificateManager: CertificateManager
- };
-});
diff --git a/chromium/chrome/browser/resources/options/certificate_restore_overlay.html b/chromium/chrome/browser/resources/options/certificate_restore_overlay.html
deleted file mode 100644
index f238cbca73b..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_restore_overlay.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<div id="certificateRestoreOverlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{certificateRestorePasswordDescription}</h1>
- <div class="content-area">
- <label id="certificateRestorePasswordLabel">
- <span>$i18n{certificatePasswordLabel}</span>
- <input id="certificateRestorePassword" type="password">
- </label>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="certificateRestoreCancelButton" type="reset">
- $i18n{cancel}
- </button>
- <button id="certificateRestoreOkButton" class="default-button"
- type="submit">
- $i18n{ok}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/certificate_restore_overlay.js b/chromium/chrome/browser/resources/options/certificate_restore_overlay.js
deleted file mode 100644
index 5070c6ec195..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_restore_overlay.js
+++ /dev/null
@@ -1,99 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * CertificateRestoreOverlay class
- * Encapsulated handling of the 'enter restore password' overlay page.
- * @class
- */
- function CertificateRestoreOverlay() {
- Page.call(this, 'certificateRestore', '', 'certificateRestoreOverlay');
- }
-
- cr.addSingletonGetter(CertificateRestoreOverlay);
-
- CertificateRestoreOverlay.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
- $('certificateRestoreCancelButton').onclick = function(event) {
- self.cancelRestore_();
- };
- $('certificateRestoreOkButton').onclick = function(event) {
- self.finishRestore_();
- };
-
- self.clearInputFields_();
- },
-
- /** @override */
- didShowPage: function() {
- $('certificateRestorePassword').focus();
- },
-
- /**
- * Clears any uncommitted input, and dismisses the overlay.
- * @private
- */
- dismissOverlay_: function() {
- this.clearInputFields_();
- PageManager.closeOverlay();
- },
-
- /**
- * Attempt the restore operation.
- * The overlay will be left up with inputs disabled until the backend
- * finishes and dismisses it.
- * @private
- */
- finishRestore_: function() {
- chrome.send('importPersonalCertificatePasswordSelected',
- [$('certificateRestorePassword').value]);
- $('certificateRestoreCancelButton').disabled = true;
- $('certificateRestoreOkButton').disabled = true;
- },
-
- /**
- * Cancel the restore operation.
- * @private
- */
- cancelRestore_: function() {
- chrome.send('cancelImportExportCertificate');
- this.dismissOverlay_();
- },
-
- /**
- * Clears the value of each input field.
- * @private
- */
- clearInputFields_: function() {
- $('certificateRestorePassword').value = '';
- $('certificateRestoreCancelButton').disabled = false;
- $('certificateRestoreOkButton').disabled = false;
- },
- };
-
- CertificateRestoreOverlay.show = function() {
- CertificateRestoreOverlay.getInstance().clearInputFields_();
- PageManager.showPageByName('certificateRestore');
- };
-
- CertificateRestoreOverlay.dismiss = function() {
- CertificateRestoreOverlay.getInstance().dismissOverlay_();
- };
-
- // Export
- return {
- CertificateRestoreOverlay: CertificateRestoreOverlay
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/certificate_tree.css b/chromium/chrome/browser/resources/options/certificate_tree.css
deleted file mode 100644
index ee83aed86f8..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_tree.css
+++ /dev/null
@@ -1,17 +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. */
-
-span.cert-untrusted {
- background-color: pink;
- border: 1px solid red;
- border-radius: 3px;
- margin-right: 3px;
- padding-left: 1px;
- padding-right: 1px;
-}
-
-span.cert-policy {
- margin-left: 3px;
- vertical-align: middle;
-}
diff --git a/chromium/chrome/browser/resources/options/certificate_tree.js b/chromium/chrome/browser/resources/options/certificate_tree.js
deleted file mode 100644
index 6265e14d2a8..00000000000
--- a/chromium/chrome/browser/resources/options/certificate_tree.js
+++ /dev/null
@@ -1,177 +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.
-
-/**
- * @typedef {{
- * id: string,
- * name: string,
- * subnodes: Array<{id: string, name: string, readonly: boolean,
- * untrusted: boolean, extractable: boolean,
- * policy: boolean}>
- * }}
- */
-var CertificateData;
-
-cr.define('options', function() {
- /** @const */ var Tree = cr.ui.Tree;
- /** @const */ var TreeItem = cr.ui.TreeItem;
-
- /**
- * Creates a new tree folder for certificate data.
- * @param {Object=} data Data used to create a certificate tree folder.
- * @constructor
- * @extends {TreeItem}
- */
- function CertificateTreeFolder(data) {
- data.isCert = false;
- var treeFolder = new TreeItem({
- label: data.name,
- data: data
- });
- treeFolder.__proto__ = CertificateTreeFolder.prototype;
-
- if (data.icon)
- treeFolder.icon = data.icon;
-
- return treeFolder;
- }
-
- CertificateTreeFolder.prototype = {
- __proto__: TreeItem.prototype,
-
- /**
- * The tree path id/.
- * @type {string}
- */
- get pathId() {
- return this.data.id;
- }
- };
-
- /**
- * Creates a new tree item for certificate data.
- * @param {Object=} data Data used to create a certificate tree item.
- * @constructor
- * @extends {TreeItem}
- */
- function CertificateTreeItem(data) {
- data.isCert = true;
- // TODO(mattm): other columns
- var treeItem = new TreeItem({
- label: data.name,
- data: data
- });
- treeItem.__proto__ = CertificateTreeItem.prototype;
-
- if (data.icon)
- treeItem.icon = data.icon;
-
- if (data.untrusted) {
- var badge = document.createElement('span');
- badge.classList.add('cert-untrusted');
- badge.textContent = loadTimeData.getString('badgeCertUntrusted');
- treeItem.labelElement.insertBefore(
- badge, treeItem.labelElement.firstChild);
- }
-
- if (data.policy) {
- var policyIndicator = new options.ControlledSettingIndicator();
- policyIndicator.controlledBy = 'policy';
- policyIndicator.setAttribute(
- 'textpolicy', loadTimeData.getString('certPolicyInstalled'));
- policyIndicator.classList.add('cert-policy');
- treeItem.labelElement.appendChild(policyIndicator);
- }
-
- return treeItem;
- }
-
- CertificateTreeItem.prototype = {
- __proto__: TreeItem.prototype,
-
- /**
- * The tree path id/.
- * @type {string}
- */
- get pathId() {
- return this.parentItem.pathId + ',' + this.data.id;
- }
- };
-
- /**
- * Creates a new cookies tree.
- * @param {Object=} opt_propertyBag Optional properties.
- * @constructor
- * @extends {Tree}
- */
- var CertificatesTree = cr.ui.define('tree');
-
- CertificatesTree.prototype = {
- __proto__: Tree.prototype,
-
- /** @override */
- decorate: function() {
- Tree.prototype.decorate.call(this);
- this.treeLookup_ = {};
- },
-
- /** @override */
- addAt: function(child, index) {
- Tree.prototype.addAt.call(this, child, index);
- if (child.data && child.data.id)
- this.treeLookup_[child.data.id] = child;
- },
-
- /**
- * @param {!cr.ui.TreeItem=} child
- * @override
- */
- remove: function(child) {
- Tree.prototype.remove.call(this, child);
- if (child.data && child.data.id)
- delete this.treeLookup_[child.data.id];
- },
-
- /**
- * Clears the tree.
- */
- clear: function() {
- // Remove all fields without recreating the object since other code
- // references it.
- for (var id in this.treeLookup_)
- delete this.treeLookup_[id];
- this.textContent = '';
- },
-
- /**
- * Populate the tree.
- * @param {Array<CertificateData>} nodesData Nodes data array.
- */
- populate: function(nodesData) {
- this.clear();
-
- for (var i = 0; i < nodesData.length; ++i) {
- var subnodes = nodesData[i].subnodes;
- delete nodesData[i].subnodes;
-
- var item = new CertificateTreeFolder(nodesData[i]);
- this.addAt(item, i);
-
- for (var j = 0; j < subnodes.length; ++j) {
- var subitem = new CertificateTreeItem(subnodes[j]);
- item.addAt(subitem, j);
- }
- // Make tree expanded by default.
- item.expanded = true;
- }
-
- cr.dispatchSimpleEvent(this, 'change');
- },
- };
-
- return {
- CertificatesTree: CertificatesTree
- };
-});
-
diff --git a/chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.html b/chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.html
deleted file mode 100644
index f77e4b55704..00000000000
--- a/chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<div id="clear-browser-data-history-notice" class="page" hidden>
- <h1>$i18n{clearBrowserDataHistoryNoticeTitle}</h1>
- <div class="content-area">
- <p>$i18nRaw{clearBrowserDataHistoryNotice}</p>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="clear-browser-data-history-notice-ok" class="default-button">
- $i18n{clearBrowserDataHistoryNoticeOk}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.js b/chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.js
deleted file mode 100644
index a96f20f139c..00000000000
--- a/chromium/chrome/browser/resources/options/clear_browser_data_history_notice_overlay.js
+++ /dev/null
@@ -1,45 +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.
-
-/**
- * @fileoverview A popup that may be shown on top of the Clear Browsing Data
- * overlay after the deletion finished.
- */
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * A notice to be shown atop of the Clear Browsing Data overlay after
- * the deletion of browsing history, informing the user that other forms
- * of browsing history are still available.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function ClearBrowserDataHistoryNotice() {
- Page.call(this, 'clearBrowserDataHistoryNotice',
- loadTimeData.getString('clearBrowserDataOverlayTabTitle'),
- 'clear-browser-data-history-notice');
- }
-
- cr.addSingletonGetter(ClearBrowserDataHistoryNotice);
-
- ClearBrowserDataHistoryNotice.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- $('clear-browser-data-history-notice-ok').onclick = function() {
- // Close this popup, and the Clear Browsing Data overlay below it.
- PageManager.closeOverlay();
- ClearBrowserDataOverlay.dismiss();
- };
- },
- };
-
- return {
- ClearBrowserDataHistoryNotice: ClearBrowserDataHistoryNotice
- };
-});
diff --git a/chromium/chrome/browser/resources/options/clear_browser_data_overlay.css b/chromium/chrome/browser/resources/options/clear_browser_data_overlay.css
deleted file mode 100644
index 2cfeb46d255..00000000000
--- a/chromium/chrome/browser/resources/options/clear_browser_data_overlay.css
+++ /dev/null
@@ -1,86 +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. */
-
-#clear-browser-data-overlay {
- width: 500px;
-}
-
-#clear-data-checkboxes {
- -webkit-padding-start: 8px;
- margin: 5px 0;
-}
-
-#cbd-throbber {
- /* This should be changed to align-self: center; when the parent is changed to
- * display: flex; */
- position: relative;
- top: 5px;
- visibility: hidden;
-}
-
-#flash-storage-settings {
- padding-top: 5px;
-}
-
-#clear-browser-data-info-banner {
- background-color: rgb(249, 237, 184);
- border: solid 1px rgb(237, 201, 103);
- border-radius: 2px;
- font-weight: bold;
- margin: 0 20px 11px 17px;
- padding: 6px 8px;
-}
-
-.clear-browser-data-counter {
- color: #999;
-}
-
-input[type=checkbox] ~ span {
- line-height: 1.4em;
-}
-
-.clear-browser-data-counter:not(:empty)::before {
- content: '\00a0–\00a0\00a0';
-}
-
-input[type=checkbox]:not(:checked) ~ span > .clear-browser-data-counter {
- display: none;
-}
-
-#clear-browser-data-info-banner:empty {
- display: none;
-}
-
-#some-stuff-remains-footer {
- display: block;
-}
-
-#some-stuff-remains-footer > p {
- -webkit-padding-start: 33px;
-}
-
-#some-stuff-remains-footer button {
- padding: 0;
-}
-
-#clear-browser-data-history-footer {
- background: url(googleg.svg) left no-repeat;
- margin: 0 0 0.8em 0;
- min-height: 16px;
-}
-
-#clear-browser-data-general-footer {
- background: url(info.svg) left no-repeat;
- margin: 0;
- min-height: 18px;
-}
-
-html[dir='rtl'] #clear-browser-data-history-footer,
-html[dir='rtl'] #clear-browser-data-general-footer {
- background-position: right center;
-}
-
-#clear-browser-data-history-notice {
- width: 300px;
-}
diff --git a/chromium/chrome/browser/resources/options/clear_browser_data_overlay.html b/chromium/chrome/browser/resources/options/clear_browser_data_overlay.html
deleted file mode 100644
index ec5faefa27a..00000000000
--- a/chromium/chrome/browser/resources/options/clear_browser_data_overlay.html
+++ /dev/null
@@ -1,138 +0,0 @@
-<div id="clear-browser-data-overlay" class="page not-resizable" hidden>
- <div class="close-button"></div>
- <h1>$i18n{clearBrowserDataOverlay}</h1>
- <!-- NOTE: Make sure there's not whitespace between <div></div> for
- #clear-browser-data-info-banner as it's styled with :empty. -->
- <div id="clear-browser-data-info-banner"></div>
- <div id="cbd-content-area" class="content-area">
- <span>$i18n{clearBrowserDataLabel}</span>
- <select id="clear-browser-data-time-period"
- i18n-options="clearBrowserDataTimeList"
- pref="browser.clear_data.time_period"
- data-type="number">
- </select>
- <div id="clear-data-checkboxes">
- <div id="delete-browsing-history-container" class="checkbox">
- <label>
- <input id="delete-browsing-history-checkbox"
- pref="browser.clear_data.browsing_history" type="checkbox"
- aria-controls="delete-browsing-history-counter">
- <span>
- <span>$i18n{deleteBrowsingHistoryCheckbox}</span>
- <span class="controlled-setting-indicator"
- pref="history.deleting_enabled">
- </span>
- <span class="clear-browser-data-counter" role="note"
- aria-live="polite" id="delete-browsing-history-counter"></span>
- </span>
- </label>
- </div>
- <div id="delete-download-history-container" class="checkbox">
- <label>
- <input id="delete-download-history-checkbox"
- pref="browser.clear_data.download_history" type="checkbox">
- <span>$i18n{deleteDownloadHistoryCheckbox}</span>
- <span class="controlled-setting-indicator"
- pref="history.deleting_enabled">
- </span>
- </label>
- </div>
- <div id="delete-cookies-container" class="checkbox">
- <label>
- <input id="delete-cookies-checkbox"
- pref="browser.clear_data.cookies" type="checkbox">
- <span class="clear-plugin-lso-data-enabled">
- $i18n{deleteCookiesFlashCheckbox}
- </span>
- <span class="clear-plugin-lso-data-disabled">
- $i18n{deleteCookiesCheckbox}
- </span>
- </label>
- </div>
- <div id="delete-cache-container" class="checkbox">
- <label>
- <input id="delete-cache-checkbox"
- pref="browser.clear_data.cache" type="checkbox"
- aria-controls="delete-cache-counter">
- <span>
- <span>$i18n{deleteCacheCheckbox}</span>
- <span class="clear-browser-data-counter" role="note"
- aria-live="polite" id="delete-cache-counter"></span>
- </span>
- </label>
- </div>
- <div id="delete-passwords-container" class="checkbox">
- <label>
- <input id="delete-passwords-checkbox"
- pref="browser.clear_data.passwords" type="checkbox"
- aria-controls="delete-passwords-counter">
- <span>
- <span>$i18n{deletePasswordsCheckbox}</span>
- <span class="clear-browser-data-counter" role="note"
- aria-live="polite" id="delete-passwords-counter"></span>
- </span>
- </label>
- </div>
- <div id="delete-form-data-container" class="checkbox">
- <label>
- <input id="delete-form-data-checkbox"
- pref="browser.clear_data.form_data" type="checkbox"
- aria-controls="delete-form-data-counter">
- <span>
- <span>$i18n{deleteFormDataCheckbox}</span>
- <span class="clear-browser-data-counter" role="note"
- aria-live="polite" id="delete-form-data-counter"></span>
- </span>
- </label>
- </div>
- <div id="delete-hosted-apps-data-container" class="checkbox">
- <label>
- <input id="delete-hosted-apps-data-checkbox"
- pref="browser.clear_data.hosted_apps_data" type="checkbox">
- <span>$i18n{deleteHostedAppsDataCheckbox}</span>
- </label>
- </div>
- <div id="delete-media-licenses-container" class="checkbox">
- <label>
- <input id="delete-media-licenses-checkbox"
- pref="browser.clear_data.media_licenses" type="checkbox"
- aria-controls="delete-media-licenses-counter">
- <span>
- <span>$i18n{deleteMediaLicensesCheckbox}</span>
- <span class="clear-browser-data-counter" role="note"
- aria-live="polite" id="delete-media-licenses-counter"></span>
- </span>
- </label>
- </div>
- </div>
- <div id="flash-storage-settings" class="flash-plugin-area">
- <a target="_blank"
- href="$i18nRaw{flashStorageUrl}">$i18n{flashStorageSettings}</a>
- </div>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a id="clear-browser-data-old-learn-more-link" hidden target="_blank"
- href="$i18nRaw{clearBrowsingDataLearnMoreUrl}">$i18n{learnMore}</a>
- </div>
- <div class="action-area-right">
- <div id="cbd-throbber" class="throbber"></div>
- <div class="button-strip">
- <button id="clear-browser-data-dismiss">$i18n{cancel}</button>
- <button id="clear-browser-data-commit" class="default-button">
- $i18n{clearBrowserDataCommit}
- </button>
- </div>
- </div>
- </div>
- <div id="some-stuff-remains-footer" class="gray-bottom-bar">
- <p id="clear-browser-data-history-footer" hidden>
- $i18nRaw{clearBrowserDataHistoryFooter}
- </p>
- <p id="clear-browser-data-general-footer">
- <span><!--This is filled by JavaScript--></span>
- <a id="clear-browser-data-footer-learn-more-link" hidden target="_blank"
- href="$i18nRaw{clearBrowsingDataLearnMoreUrl}">$i18n{learnMore}</a>
- </p>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/clear_browser_data_overlay.js b/chromium/chrome/browser/resources/options/clear_browser_data_overlay.js
deleted file mode 100644
index 092353e8b51..00000000000
--- a/chromium/chrome/browser/resources/options/clear_browser_data_overlay.js
+++ /dev/null
@@ -1,341 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * ClearBrowserDataOverlay class
- * Encapsulated handling of the 'Clear Browser Data' overlay page.
- * @class
- */
- function ClearBrowserDataOverlay() {
- Page.call(this, 'clearBrowserData',
- loadTimeData.getString('clearBrowserDataOverlayTabTitle'),
- 'clear-browser-data-overlay');
- }
-
- cr.addSingletonGetter(ClearBrowserDataOverlay);
-
- ClearBrowserDataOverlay.prototype = {
- // Inherit ClearBrowserDataOverlay from Page.
- __proto__: Page.prototype,
-
- /**
- * Whether deleting history and downloads is allowed.
- * @type {boolean}
- * @private
- */
- allowDeletingHistory_: true,
-
- /**
- * Whether or not clearing browsing data is currently in progress.
- * @type {boolean}
- * @private
- */
- isClearingInProgress_: false,
-
- /**
- * Whether or not the WebUI handler has completed initialization.
- *
- * Unless this becomes true, it must be assumed that the above flags might
- * not contain the authoritative values.
- *
- * @type {boolean}
- * @private
- */
- isInitializationComplete_: false,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var f = this.updateStateOfControls_.bind(this);
- var types = ['browser.clear_data.browsing_history',
- 'browser.clear_data.download_history',
- 'browser.clear_data.cache',
- 'browser.clear_data.cookies',
- 'browser.clear_data.passwords',
- 'browser.clear_data.form_data',
- 'browser.clear_data.hosted_apps_data',
- 'browser.clear_data.media_licenses'];
- types.forEach(function(type) {
- Preferences.getInstance().addEventListener(type, f);
- });
-
- var checkboxes = document.querySelectorAll(
- '#cbd-content-area input[type=checkbox]');
- for (var i = 0; i < checkboxes.length; i++) {
- checkboxes[i].onclick = f;
- }
-
- $('clear-browser-data-dismiss').onclick = function(event) {
- ClearBrowserDataOverlay.dismiss();
- };
- $('clear-browser-data-commit').onclick = function(event) {
- ClearBrowserDataOverlay.setClearing(true);
- chrome.send('performClearBrowserData');
- };
-
- // For managed profiles, hide the checkboxes controlling whether or not
- // browsing and download history should be cleared. Note that this is
- // different than just disabling them as a result of enterprise policies.
- if (!loadTimeData.getBoolean('showDeleteBrowsingHistoryCheckboxes')) {
- $('delete-browsing-history-container').hidden = true;
- $('delete-download-history-container').hidden = true;
- }
-
- this.updateStateOfControls_();
- },
-
- /** @override */
- didShowPage: function() {
- chrome.send('openedClearBrowserData');
- },
-
- /**
- * Create a footer that explains that some content is not cleared by the
- * clear browsing data dialog and warns that the deletion may be synced.
- * @param {boolean} simple Whether to use a simple support string.
- * @param {boolean} syncing Whether the user uses Sync.
- * @param {boolean} showHistoryFooter Whether to show an additional footer
- * about other forms of browsing history.
- * @private
- */
- createFooter_: function(simple, syncing, showHistoryFooter) {
- // The localized string is of the form "Saved [content settings] and
- // {search engines} will not be cleared and may reflect your browsing
- // habits.", or of the form "Some settings that may reflect browsing
- // habits |will not be cleared|." if the simplified support string
- // experiment is enabled. The following parses out the parts in brackets
- // and braces and converts them into buttons whereas the remainders are
- // represented as span elements.
- var footer =
- document.querySelector('#some-stuff-remains-footer p span');
- var footerFragments =
- loadTimeData.getString('clearBrowserDataSupportString')
- .split(/([|#])/);
-
- if (simple) {
- footerFragments.unshift(
- loadTimeData.getString('clearBrowserDataSyncWarning') +
- ' ' // Padding between the sync warning and the rest of the footer.
- );
- }
-
- for (var i = 0; i < footerFragments.length;) {
- var linkId = '';
- if (i + 2 < footerFragments.length) {
- if (footerFragments[i] == '|' && footerFragments[i + 2] == '|') {
- linkId = 'open-content-settings-from-clear-browsing-data';
- } else if (footerFragments[i] == '#' &&
- footerFragments[i + 2] == '#') {
- linkId = 'open-search-engines-from-clear-browsing-data';
- }
- }
-
- if (linkId) {
- var link = new ActionLink;
- link.id = linkId;
- link.textContent = footerFragments[i + 1];
- footer.appendChild(link);
- i += 3;
- } else {
- var span = document.createElement('span');
- span.textContent = footerFragments[i];
- if (simple && i == 0) {
- span.id = 'clear-browser-data-sync-warning';
- span.hidden = !syncing;
- }
- footer.appendChild(span);
- i += 1;
- }
- }
-
- if (!simple) {
- $('open-content-settings-from-clear-browsing-data').onclick =
- function(event) {
- PageManager.showPageByName('content');
- };
- $('open-search-engines-from-clear-browsing-data').onclick =
- function(event) {
- PageManager.showPageByName('searchEngines');
- };
- }
-
- $('clear-browser-data-old-learn-more-link').hidden = simple;
- $('clear-browser-data-footer-learn-more-link').hidden = !simple;
- $('flash-storage-settings').hidden = simple;
- $('clear-browser-data-history-footer').hidden = !showHistoryFooter;
- },
-
- /**
- * Shows or hides the sync warning based on whether the user uses Sync.
- * @param {boolean} syncing Whether the user uses Sync.
- * @param {boolean} showHistoryFooter Whether the user syncs history
- * and conditions are met to show an additional history footer.
- * @private
- */
- updateSyncWarningAndHistoryFooter_: function(syncing, showHistoryFooter) {
- $('clear-browser-data-sync-warning').hidden = !syncing;
- $('clear-browser-data-history-footer').hidden = !showHistoryFooter;
- },
-
- /**
- * Sets whether or not we are in the process of clearing data.
- * @param {boolean} clearing Whether the browsing data is currently being
- * cleared.
- * @private
- */
- setClearing_: function(clearing) {
- this.isClearingInProgress_ = clearing;
- this.updateStateOfControls_();
- },
-
- /**
- * Sets whether deleting history and downloads is disallowed by enterprise
- * policies. This is called on initialization and in response to a change in
- * the corresponding preference.
- * @param {boolean} allowed Whether to allow deleting history and downloads.
- * @private
- */
- setAllowDeletingHistory_: function(allowed) {
- this.allowDeletingHistory_ = allowed;
- this.updateStateOfControls_();
- },
-
- /**
- * Called by the WebUI handler to signal that it has finished calling all
- * initialization methods.
- * @private
- */
- markInitializationComplete_: function() {
- this.isInitializationComplete_ = true;
- this.updateStateOfControls_();
- },
-
- /**
- * Updates the enabled/disabled/hidden status of all controls on the dialog.
- * @private
- */
- updateStateOfControls_: function() {
- // The commit button is enabled if at least one data type selected to be
- // cleared, and if we are not already in the process of clearing.
- // To prevent the commit button from being hazardously enabled for a very
- // short time before setClearing() is called the first time by the native
- // side, also disable the button if |isInitializationComplete_| is false.
- var enabled = false;
- if (this.isInitializationComplete_ && !this.isClearingInProgress_) {
- var checkboxes = document.querySelectorAll(
- '#cbd-content-area input[type=checkbox]');
- for (var i = 0; i < checkboxes.length; i++) {
- if (checkboxes[i].checked) {
- enabled = true;
- break;
- }
- }
- }
- $('clear-browser-data-commit').disabled = !enabled;
-
- // The checkboxes for clearing history/downloads are enabled unless they
- // are disallowed by policies, or we are in the process of clearing data.
- // To prevent flickering, these, and the rest of the controls can safely
- // be enabled for a short time before the first call to setClearing().
- var enabled = this.allowDeletingHistory_ && !this.isClearingInProgress_;
- $('delete-browsing-history-checkbox').disabled = !enabled;
- $('delete-download-history-checkbox').disabled = !enabled;
- if (!this.allowDeletingHistory_) {
- $('delete-browsing-history-checkbox').checked = false;
- $('delete-download-history-checkbox').checked = false;
- }
-
- // Enable everything else unless we are in the process of clearing.
- var clearing = this.isClearingInProgress_;
- $('delete-cache-checkbox').disabled = clearing;
- $('delete-cookies-checkbox').disabled = clearing;
- $('delete-passwords-checkbox').disabled = clearing;
- $('delete-form-data-checkbox').disabled = clearing;
- $('delete-hosted-apps-data-checkbox').disabled = clearing;
- $('delete-media-licenses-checkbox').disabled = clearing;
- $('clear-browser-data-time-period').disabled = clearing;
- $('cbd-throbber').style.visibility = clearing ? 'visible' : 'hidden';
- $('clear-browser-data-dismiss').disabled = clearing;
- },
-
- /**
- * Updates the given data volume counter with a given text.
- * @param {string} pref_name Name of the deletion preference of the counter
- * to be updated.
- * @param {string} text The new text of the counter.
- * @private
- */
- updateCounter_: function(pref_name, text) {
- var counter = document.querySelector(
- 'input[pref="' + pref_name +
- '"] ~ span > .clear-browser-data-counter');
- counter.textContent = text;
- }
- };
-
- //
- // Chrome callbacks
- //
- ClearBrowserDataOverlay.setAllowDeletingHistory = function(allowed) {
- ClearBrowserDataOverlay.getInstance().setAllowDeletingHistory_(allowed);
- };
-
- ClearBrowserDataOverlay.updateCounter = function(pref_name, text) {
- ClearBrowserDataOverlay.getInstance().updateCounter_(pref_name, text);
- };
-
- ClearBrowserDataOverlay.createFooter = function(
- simple, syncing, showHistoryFooter) {
- ClearBrowserDataOverlay.getInstance().createFooter_(
- simple, syncing, showHistoryFooter);
- };
-
- ClearBrowserDataOverlay.updateSyncWarningAndHistoryFooter = function(
- syncing, showHistoryFooter) {
- ClearBrowserDataOverlay.getInstance().updateSyncWarningAndHistoryFooter_(
- syncing, showHistoryFooter);
- };
-
- ClearBrowserDataOverlay.setClearing = function(clearing) {
- ClearBrowserDataOverlay.getInstance().setClearing_(clearing);
- };
-
- ClearBrowserDataOverlay.markInitializationComplete = function() {
- ClearBrowserDataOverlay.getInstance().markInitializationComplete_();
- };
-
- ClearBrowserDataOverlay.setBannerText = function(text) {
- $('clear-browser-data-info-banner').innerText = text;
- };
-
- ClearBrowserDataOverlay.doneClearing = function(showHistoryNotice) {
- // The delay gives the user some feedback that the clearing
- // actually worked. Otherwise the dialog just vanishes instantly in most
- // cases.
- window.setTimeout(function() {
- ClearBrowserDataOverlay.setClearing(false);
-
- if (showHistoryNotice)
- PageManager.showPageByName('clearBrowserDataHistoryNotice');
- else
- ClearBrowserDataOverlay.dismiss();
- }, 200);
- };
-
- ClearBrowserDataOverlay.dismiss = function() {
- var topmostVisiblePage = PageManager.getTopmostVisiblePage();
- if (topmostVisiblePage && topmostVisiblePage.name == 'clearBrowserData')
- PageManager.closeOverlay();
- };
-
- // Export
- return {
- ClearBrowserDataOverlay: ClearBrowserDataOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/compiled_resources2.gyp b/chromium/chrome/browser/resources/options/compiled_resources2.gyp
deleted file mode 100644
index 50ff2da5f97..00000000000
--- a/chromium/chrome/browser/resources/options/compiled_resources2.gyp
+++ /dev/null
@@ -1,101 +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.
-{
- 'targets': [
- {
- 'target_name': 'options_bundle',
- 'variables': {
- 'extra_inputs': [
- '<!@(python <(CLOSURE_DIR)/build/get_includes.py options_bundle.js)',
- ],
- 'script_args': ['--custom_sources', '--custom_includes'],
- 'source_files': [
- # Note: this code is deprecated. If you really need to change this
- # list for some reason, please also update the copies at:
- # ../help/compiled_resources2.gyp:help#source_files
- # ../chromeos/compiled_resources2.gyp:*#source_files
- '<(DEPTH)/third_party/jstemplate/util.js',
- '<(DEPTH)/third_party/jstemplate/jsevalcontext.js',
- '<(DEPTH)/third_party/jstemplate/jstemplate.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js',
- '<(DEPTH)/ui/webui/resources/js/action_link.js',
- '<(DEPTH)/ui/webui/resources/js/cr.js',
- '<(DEPTH)/ui/webui/resources/js/cr/event_target.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/array_data_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/autocomplete_list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/bubble_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/command.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/controlled_indicator.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_outline_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/focus_without_ink.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_controller.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/list_single_selection_model.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/grid.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/menu_item.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/overlay.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/position_util.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/node_utils.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/page_manager/page_manager.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/repeating_button.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/touch_handler.js',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/tree.js',
- '<(DEPTH)/ui/webui/resources/js/event_tracker.js',
- '<(DEPTH)/ui/webui/resources/js/icon.js',
- '<(DEPTH)/ui/webui/resources/js/load_time_data.js',
- '<(DEPTH)/ui/webui/resources/js/parse_html_subset.js',
- '<(DEPTH)/ui/webui/resources/js/promise_resolver.js',
- '<(DEPTH)/ui/webui/resources/js/util.js',
- '../chromeos/keyboard/keyboard_utils.js',
- '<(DEPTH)/ui/webui/resources/js/i18n_behavior.js',
- '<(DEPTH)/ui/webui/resources/js/web_ui_listener_behavior.js',
- '../settings/page_visibility.js',
- '../settings/route.js',
- '../settings/people_page/easy_unlock_browser_proxy.js',
- '../settings/people_page/fingerprint_browser_proxy.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selection-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/iron-multi-selectable-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menu-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-menu-behavior/iron-menubar-behavior-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector_grid.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.js',
- '../settings/people_page/lock_screen_constants.js',
- '<(DEPTH)/third_party/closure_compiler/externs/quick_unlock_private.js',
- '../settings/people_page/lock_state_behavior.js',
- '../settings/people_page/password_prompt_dialog.js',
- '<(DEPTH)/ui/webui/resources/js/assert.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-meta/iron-meta-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-icon/iron-icon-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-control-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-ripple/paper-ripple-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-inky-focus-behavior-extracted.js',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-icon-button/paper-icon-button-extracted.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js',
- '../settings/people_page/lock_screen.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth.js',
- '<(DEPTH)/third_party/closure_compiler/externs/bluetooth_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/management.js',
- '<(DEPTH)/third_party/closure_compiler/externs/metrics_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/networking_private.js',
- '<(DEPTH)/third_party/closure_compiler/externs/chrome_send.js',
- '<(DEPTH)/third_party/closure_compiler/externs/web_animations.js',
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/cr_network_icon_externs.js',
- 'options_bundle.js',
- ],
- },
- 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- ],
-}
diff --git a/chromium/chrome/browser/resources/options/confirm_dialog.js b/chromium/chrome/browser/resources/options/confirm_dialog.js
deleted file mode 100644
index c70c338b7ae..00000000000
--- a/chromium/chrome/browser/resources/options/confirm_dialog.js
+++ /dev/null
@@ -1,134 +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.
-
-cr.define('options', function() {
- /** @const */ var SettingsDialog = options.SettingsDialog;
-
- /**
- * A dialog that will pop up when the user attempts to set the value of the
- * Boolean |pref| to |true|, asking for confirmation. If the user clicks OK,
- * the new value is committed to Chrome. If the user clicks Cancel or leaves
- * the settings page, the new value is discarded.
- * @constructor
- * @param {string} name See Page constructor.
- * @param {string} title See Page constructor.
- * @param {string} pageDivName See Page constructor.
- * @param {HTMLButtonElement} okButton The confirmation button element.
- * @param {HTMLButtonElement} cancelButton The cancellation button element.
- * @param {string} pref The pref that requires confirmation.
- * @param {string} metric User metrics identifier.
- * @param {string=} opt_confirmedPref A pref used to remember whether the
- * user has confirmed the dialog before. This ensures that the user is
- * presented with the dialog only once. If left |undefined|, the dialog
- * will pop up every time the user attempts to set |pref| to |true|.
- * @param {boolean=} opt_confirmValue The value to which changing should
- * trigger the confirmation dialog. Defaults to |true| if left
- * |undefined|.
- * @extends {options.SettingsDialog}
- */
- function ConfirmDialog(name, title, pageDivName, okButton, cancelButton, pref,
- metric, opt_confirmedPref, opt_confirmValue) {
- SettingsDialog.call(this, name, title, pageDivName, okButton, cancelButton);
-
- /** @protected */
- this.pref = pref;
-
- /** @protected */
- this.metric = metric;
-
- /** @private */
- this.confirmedPref_ = opt_confirmedPref;
-
- /** @private */
- this.confirmed_ = false;
-
- /** @private */
- this.confirmValue_ = opt_confirmValue === false ? false : true;
- }
-
- ConfirmDialog.prototype = {
- // Set up the prototype chain
- __proto__: SettingsDialog.prototype,
-
- /**
- * Handle changes to |pref|. Only uncommitted changes are relevant as these
- * originate from user and need to be explicitly committed to take effect.
- * Pop up the dialog or commit the change, depending on whether confirmation
- * is needed.
- * @param {Event} event Change event.
- * @private
- */
- onPrefChanged_: function(event) {
- if (!event.value.uncommitted)
- return;
-
- if (event.value.value == this.confirmValue_ && !this.confirmed_)
- PageManager.showPageByName(this.name, false);
- else
- Preferences.getInstance().commitPref(this.pref, this.metric);
- },
-
- /**
- * Handle changes to |confirmedPref_| by caching them.
- * @param {Event} event Change event.
- * @private
- */
- onConfirmedChanged_: function(event) {
- this.confirmed_ = event.value.value;
- },
-
- /** @override */
- initializePage: function() {
- SettingsDialog.prototype.initializePage.call(this);
-
- this.okButton.onclick = this.handleConfirm.bind(this);
- this.cancelButton.onclick = this.handleCancel.bind(this);
- Preferences.getInstance().addEventListener(
- this.pref, this.onPrefChanged_.bind(this));
- if (this.confirmedPref_) {
- Preferences.getInstance().addEventListener(
- this.confirmedPref_, this.onConfirmedChanged_.bind(this));
- }
- },
-
- /**
- * Handle the confirm button by committing the |pref| change. If
- * |confirmedPref_| has been specified, also remember that the dialog has
- * been confirmed to avoid bringing it up in the future.
- * @override
- */
- handleConfirm: function() {
- SettingsDialog.prototype.handleConfirm.call(this);
-
- Preferences.getInstance().commitPref(this.pref, this.metric);
- if (this.confirmedPref_)
- Preferences.setBooleanPref(
- this.confirmedPref_, this.confirmValue_, true);
- },
-
- /**
- * Handle the cancel button by rolling back the |pref| change without it
- * ever taking effect.
- * @override
- */
- handleCancel: function() {
- SettingsDialog.prototype.handleCancel.call(this);
- Preferences.getInstance().rollbackPref(this.pref);
- },
-
- /**
- * When a user navigates away from a confirm dialog, treat as a cancel.
- * @protected
- * @override
- */
- willHidePage: function() {
- if (this.visible)
- Preferences.getInstance().rollbackPref(this.pref);
- },
- };
-
- return {
- ConfirmDialog: ConfirmDialog
- };
-});
diff --git a/chromium/chrome/browser/resources/options/content_settings.css b/chromium/chrome/browser/resources/options/content_settings.css
deleted file mode 100644
index 6f9a4537137..00000000000
--- a/chromium/chrome/browser/resources/options/content_settings.css
+++ /dev/null
@@ -1,117 +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. */
-
-#content-settings-page {
- min-width: 620px;
-}
-
-#content-settings-exceptions-area {
- min-width: 540px;
-}
-
-.exception-pattern {
- -webkit-box-flex: 1;
- -webkit-margin-end: 10px;
- -webkit-margin-start: 14px;
-}
-
-.exception-setting {
- display: inline-block;
- width: 120px;
-}
-
-.settings-list div[role='listitem'][controlled-by='policy'] .exception-setting,
-.settings-list div[role='listitem'][controlled-by='extension']
- .exception-setting {
- width: calc(120px - 8px);
-}
-
-select.exception-setting {
- vertical-align: middle;
-}
-
-.overruled .exception-setting {
- width: calc(120px - 24px);
-}
-
-.overruled .overruleable {
- text-decoration: line-through;
-}
-
-#exception-column-headers {
- -webkit-margin-start: 17px;
- display: -webkit-box;
- margin-top: 17px;
-}
-
-#exception-column-headers > div {
- font-weight: bold;
-}
-
-#exception-pattern-column {
- -webkit-box-flex: 1;
-}
-
-.exception-value-column-header {
- width: 145px;
-}
-
-.otr-explanation {
- font-style: italic;
-}
-
-#content-settings-exceptions-area list {
- margin-bottom: 10px;
- margin-top: 4px;
-}
-
-#group-indicator {
- margin-left: 5px;
-}
-
-div[role='listitem'][controlled-by] {
- color: #666;
- font-style: italic;
- position: relative;
-}
-
-.settings-list div[role='listitem'][controlled-by='policy'],
-.settings-list div[role='listitem'][controlled-by='extension'] {
- background: rgb(250, 230, 146);
- border-bottom: 1px solid rgb(201, 189, 141);
- border-top: 0;
-}
-
-.sublabel {
- -webkit-margin-start: 2em;
-}
-
-select.media-device-control {
- margin: 5px 0;
- width: 12em;
-}
-
-select.media-device-control:empty {
- display: none;
-}
-
-.exception-setting.media-audio-setting {
- width: 6em;
-}
-
-.exception-setting.media-video-setting {
- width: 6.5em;
-}
-
-#media-column-header {
- display: -webkit-box;
-}
-
-#media-audio-column {
- width: 6em;
-}
-
-#media-video-column {
- width: 8.5em;
-}
diff --git a/chromium/chrome/browser/resources/options/content_settings.html b/chromium/chrome/browser/resources/options/content_settings.html
deleted file mode 100644
index db5099486cf..00000000000
--- a/chromium/chrome/browser/resources/options/content_settings.html
+++ /dev/null
@@ -1,649 +0,0 @@
-<div id="content-settings-page" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{contentSettingsPage}</h1>
- <div class="content-area">
- <!-- Cookie filter tab contents -->
- <section>
- <h3>$i18n{cookiesTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="cookies" value="allow">
- <span>
- <span>$i18n{cookiesAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="cookies" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="cookies" value="session_only">
- <span>
- <span>$i18n{cookiesSessionOnly}</span>
- <span class="controlled-setting-indicator"
- content-setting="cookies" value="session_only"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="cookies" value="block">
- <span>
- <span>$i18n{cookiesBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="cookies" value="block"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input pref="profile.block_third_party_cookies" type="checkbox">
- <span>
- <span>$i18n{cookiesBlock3rdParty}</span>
- <span class="controlled-setting-indicator"
- pref="profile.block_third_party_cookies"></span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="cookies">
- $i18n{manageExceptions}
- </button>
- <button id="show-cookies-button">$i18n{cookiesShowCookies}</button>
- </div>
- </div>
- </section>
- <!-- Image filter -->
- <section>
- <h3>$i18n{imagesTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="images" value="allow">
- <span>
- <span>$i18n{imagesAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="images" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="images" value="block">
- <span>
- <span>$i18n{imagesBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="images" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="images">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- JavaScript filter -->
- <section>
- <h3>$i18n{javascriptTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="javascript" value="allow">
- <span>
- <span>$i18n{javascriptAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="javascript" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="javascript" value="block">
- <span>
- <span>$i18n{javascriptBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="javascript" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="javascript">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Handlers settings -->
- <section id="handlers-section">
- <h3>$i18n{handlersTabLabel}</h3>
- <div>
- <div class="radio">
- <label>
- <input type="radio" name="handlers" value="allow"
- class="handler-radio">
- <span>$i18n{handlersAllow}</span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="handlers" value="block"
- class="handler-radio">
- <span>$i18n{handlersBlock}</span>
- </label>
- </div>
- <div class="settings-row">
- <button id="manage-handlers-button" contentType="handlers">
- $i18n{manageHandlers}
- </button>
- </div>
- </div>
- </section>
- <!-- Plugins filter -->
- <section>
- <h3>$i18n{pluginsTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input id="plugins-allow-radio" type="radio" name="plugins"
- value="allow">
- <span>
- <span>$i18n{pluginsAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="plugins" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="plugins" value="detect_important_content">
- <span>
- <span>$i18n{pluginsDetectImportantContent}</span>
- <span class="controlled-setting-indicator"
- content-setting="plugins" value="detect_important_content">
- </span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="plugins" value="block">
- <span>
- <span>$i18n{pluginsBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="plugins" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="plugins">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Pop-ups filter -->
- <section>
- <h3 class="content-settings-header">$i18n{popupsTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="popups" value="allow">
- <span>
- <span>$i18n{popupsAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="popups" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="popups" value="block">
- <span>
- <span>$i18n{popupsBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="popups" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="popups">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Location filter -->
- <section>
- <h3>$i18n{locationTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="location" value="allow">
- <span>
- <span>$i18n{locationAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="location" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="location" value="ask">
- <span>
- <span>$i18n{locationAsk}</span>
- <span class="controlled-setting-indicator"
- content-setting="location" value="ask"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="location"
- value="block">
- <span>
- <span>$i18n{locationBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="location" value="block"></span>
- </span>
- </label>
- </div>
-<if expr="enable_google_now">
- <div class="checkbox controlled-setting-with-label"
- id="geolocationCheckbox" hidden>
- <label>
- <input pref="googlegeolocationaccess.enabled"
- metric="Options_GoogleGeolocationAccessCheckbox"
- type="checkbox">
- <span>
- <span>$i18n{googleGeolocationAccessEnable}</span>
- <span class="controlled-setting-indicator"
- pref="googlegeolocationaccess.enabled"></span>
- </span>
- </label>
- </div>
-</if>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="location">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Notifications filter tab contents -->
- <section id="notifications-section">
- <h3>$i18n{notificationsTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="notifications" value="allow">
- <span>
- <span>$i18n{notificationsAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="notifications" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="notifications" value="ask">
- <span>
- <span>$i18n{notificationsAsk}</span>
- <span class="controlled-setting-indicator"
- content-setting="notifications" value="ask"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="notifications" value="block">
- <span>
- <span>$i18n{notificationsBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="notifications" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="notifications">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Protected Content filter -->
- <section guest-visibility="disabled">
- <h3 class="content-settings-header">$i18n{protectedContentTabLabel}</h3>
- <div>
- <div class="checkbox">
- <label>
- <input pref="webkit.webprefs.encrypted_media_enabled"
- type="checkbox">
- <span>$i18n{protectedContentEnableCheckbox}</span>
- </label>
- </div>
-<if expr="chromeos or is_win">
- <div class="settings-row">
- <p>$i18n{protectedContentInfo}</p>
- </div>
- <div class="checkbox">
- <label>
- <input pref="settings.privacy.drm_enabled" type="checkbox">
- <span>$i18n{protectedContentEnableIdentifiersCheckbox}</span>
- </label>
- </div>
-</if>
-<if expr="chromeos">
- <div class="settings-row">
- <button id="protected-content-exceptions"
- class="exceptions-list-button" contentType="protectedContent">
- $i18n{manageExceptions}
- </button>
- </div>
-</if>
- </div>
- </section>
- <!-- Microphone filter -->
- <section id="media-stream-mic">
- <h3>$i18n{mediaStreamMicTabLabel}</h3>
- <div>
- <span id="media-select-mic-label" hidden>
- $i18n{mediaSelectMicLabel}
- </span>
- <select id="media-select-mic" class="weakrtl media-device-control"
- aria-labelledby="media-select-mic-label"></select>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="media-stream-mic" value="ask">
- <span>
- <span>$i18n{mediaStreamMicAsk}</span>
- <span class="controlled-setting-indicator"
- content-setting="media-stream-mic" value="ask"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="media-stream-mic" value="block">
- <span>
- <span>$i18n{mediaStreamMicBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="media-stream-mic" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="media-stream-mic">
- $i18n{manageExceptions}
- </button>
- </div>
- <div id="media-pepper-flash-default-mic" class="pepper-flash-settings">
- <span>$i18n{mediaPepperFlashMicDefaultDivergedLabel}</span>
- <a target="_blank" href="$i18nRaw{mediaPepperFlashGlobalPrivacyURL}">
- $i18n{mediaPepperFlashChangeLink}
- </a>
- </div>
- </div>
- </section>
- <!-- Camera filter -->
- <section id="media-stream-camera">
- <h3>$i18n{mediaStreamCameraTabLabel}</h3>
- <div>
- <span id="media-select-camera-label" hidden>
- $i18n{mediaSelectCameraLabel}
- </span>
- <select id="media-select-camera" class="weakrtl media-device-control"
- aria-labelledby="media-select-camera-label"></select>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="media-stream-camera" value="ask">
- <span>
- <span>$i18n{mediaStreamCameraAsk}</span>
- <span class="controlled-setting-indicator"
- content-setting="media-stream-camera" value="ask"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="media-stream-camera" value="block">
- <span>
- <span>$i18n{mediaStreamCameraBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="media-stream-camera" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button"
- contentType="media-stream-camera">
- $i18n{manageExceptions}
- </button>
- </div>
- <div id="media-pepper-flash-default-camera"
- class="pepper-flash-settings">
- <span>$i18n{mediaPepperFlashCameraDefaultDivergedLabel}</span>
- <a target="_blank" href="$i18nRaw{mediaPepperFlashGlobalPrivacyURL}">
- $i18n{mediaPepperFlashChangeLink}
- </a>
- </div>
- </div>
- </section>
- <!-- PPAPI broker -->
- <section>
- <h3>$i18n{ppapiBrokerTabLabel}</h3>
- <div>
- <div class="radio">
- <label>
- <input type="radio" name="ppapi-broker" value="allow">
- <span>
- <span>$i18n{ppapiBrokerAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="ppapi-broker" value="allow"></span>
- </span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="ppapi-broker" value="ask">
- <span>
- <span>$i18n{ppapiBrokerAsk}</span>
- <span class="controlled-setting-indicator"
- content-setting="ppapi-broker" value="ask"></span>
- </span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="ppapi-broker" value="block">
- <span>
- <span>$i18n{ppapiBrokerBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="ppapi-broker" value="block"></span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="ppapi-broker">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Automatic Downloads filter -->
- <section>
- <h3>$i18n{multipleAutomaticDownloadsTabLabel}</h3>
- <div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="multiple-automatic-downloads"
- value="allow">
- <span>
- <span>$i18n{multipleAutomaticDownloadsAllow}</span>
- <span class="controlled-setting-indicator"
- content-setting="multiple-automatic-downloads" value="allow">
- </span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="multiple-automatic-downloads" value="ask">
- <span>
- <span>$i18n{multipleAutomaticDownloadsAsk}</span>
- <span class="controlled-setting-indicator"
- content-setting="multiple-automatic-downloads" value="ask">
- </span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input type="radio" name="multiple-automatic-downloads"
- value="block">
- <span>
- <span>$i18n{multipleAutomaticDownloadsBlock}</span>
- <span class="controlled-setting-indicator"
- content-setting="multiple-automatic-downloads" value="block">
- </span>
- </span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button"
- contentType="multiple-automatic-downloads">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- MIDI system exclusive messages filter -->
- <section>
- <h3>$i18n{midiSysexHeader}</h3>
- <div>
- <div class="radio">
- <label>
- <input type="radio" name="midi-sysex" value="allow">
- <span>$i18n{midiSysExAllow}</span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="midi-sysex" value="ask">
- <span>$i18n{midiSysExAsk}</span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="midi-sysex" value="block">
- <span>$i18n{midiSysExBlock}</span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="midi-sysex">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Push messaging filter -->
- <section id="experimental-push-messaging-settings" hidden="true">
- <h3>$i18n{pushMessagingHeader}</h3>
- <div>
- <div class="radio">
- <label>
- <input type="radio" name="push-messaging" value="allow">
- <span>$i18n{pushMessagingAllow}</span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="push-messaging" value="ask">
- <span>$i18n{pushMessagingAsk}</span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="push-messaging" value="block">
- <span>$i18n{pushMessagingBlock}</span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="push-messaging">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- USB devices -->
- <section>
- <h3>$i18n{usbDevicesHeader}</h3>
- <div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="usb-devices">
- $i18n{usbDevicesManage}
- </button>
- </div>
- </div>
- </section>
- <!-- Background sync -->
- <section>
- <h3>$i18n{backgroundSyncHeader}</h3>
- <div>
- <div class="radio">
- <label>
- <input type="radio" name="background-sync" value="allow">
- <span>$i18n{backgroundSyncAllow}</span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input type="radio" name="background-sync" value="block">
- <span>$i18n{backgroundSyncBlock}</span>
- </label>
- </div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="background-sync">
- $i18n{manageExceptions}
- </button>
- </div>
- </div>
- </section>
- <!-- Page zoom levels -->
- <section id="page-zoom-levels">
- <h3>$i18n{zoomlevelsHeader}</h3>
- <div>
- <div class="settings-row">
- <button class="exceptions-list-button" contentType="zoomlevels">
- $i18n{zoomLevelsManage}
- </button>
- </div>
- </div>
- </section>
- <!-- PDF Plugin filter -->
- <section id="pdf-section">
- <h3 class="content-settings-header">$i18n{pdfTabLabel}</h3>
- <div>
- <div class="checkbox">
- <label>
- <input pref="plugins.always_open_pdf_externally" type="checkbox">
- <span>
- <span>$i18n{pdfEnable}</span>
- <span class="controlled-setting-indicator"
- pref="plugins.always_open_pdf_externally">
- </span>
- </span>
- </label>
- </div>
- </div>
- </section>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="content-settings-overlay-confirm" class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/content_settings.js b/chromium/chrome/browser/resources/options/content_settings.js
deleted file mode 100644
index edcadafe489..00000000000
--- a/chromium/chrome/browser/resources/options/content_settings.js
+++ /dev/null
@@ -1,286 +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.
-
-cr.exportPath('options');
-
-/**
- * @typedef {{appId: string,
- * appName: (string|undefined),
- * embeddingOrigin: (string|undefined),
- * origin: string,
- * setting: string,
- * source: string,
- * video: (string|undefined)}}
- */
-options.Exception;
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- //////////////////////////////////////////////////////////////////////////////
- // ContentSettings class:
-
- /**
- * Encapsulated handling of content settings page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function ContentSettings() {
- this.activeNavTab = null;
- Page.call(this, 'content',
- loadTimeData.getString('contentSettingsPageTabTitle'),
- 'content-settings-page');
- }
-
- cr.addSingletonGetter(ContentSettings);
-
- ContentSettings.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var exceptionsButtons =
- this.pageDiv.querySelectorAll('.exceptions-list-button');
- for (var i = 0; i < exceptionsButtons.length; i++) {
- exceptionsButtons[i].onclick = function(event) {
- var hash = event.currentTarget.getAttribute('contentType');
- PageManager.showPageByName('contentExceptions', true,
- {hash: '#' + hash});
- };
- }
-
- var manageHandlersButton = $('manage-handlers-button');
- if (manageHandlersButton) {
- manageHandlersButton.onclick = function(event) {
- PageManager.showPageByName('handlers');
- };
- }
-
- if (cr.isChromeOS) {
- // Disable some controls for Guest in Chrome OS.
- UIAccountTweaks.applyGuestSessionVisibility(document);
-
- // Disable some controls for Public session in Chrome OS.
- UIAccountTweaks.applyPublicSessionVisibility(document);
- }
-
- // Cookies filter page ---------------------------------------------------
- $('show-cookies-button').onclick = function(event) {
- chrome.send('coreOptionsUserMetricsAction', ['Options_ShowCookies']);
- PageManager.showPageByName('cookies');
- };
-
- $('content-settings-overlay-confirm').onclick =
- PageManager.closeOverlay.bind(PageManager);
-
- $('media-pepper-flash-default-mic').hidden = true;
- $('media-pepper-flash-default-camera').hidden = true;
- $('media-pepper-flash-exceptions-mic').hidden = true;
- $('media-pepper-flash-exceptions-camera').hidden = true;
-
- $('media-select-mic').addEventListener('change',
- ContentSettings.setDefaultMicrophone_);
- $('media-select-camera').addEventListener('change',
- ContentSettings.setDefaultCamera_);
- },
- };
-
- ContentSettings.updateHandlersEnabledRadios = function(enabled) {
- var selector = '#content-settings-page input[type=radio][value=' +
- (enabled ? 'allow' : 'block') + '].handler-radio';
- document.querySelector(selector).checked = true;
- };
-
- /**
- * Sets the values for all the content settings radios and labels.
- * @param {Object<{managedBy: string, value: string}>} dict A mapping from
- * radio groups to the checked value for that group.
- */
- ContentSettings.setContentFilterSettingsValue = function(dict) {
- for (var group in dict) {
- var managedBy = dict[group].managedBy;
- var controlledBy = managedBy == 'policy' || managedBy == 'extension' ?
- managedBy : null;
- document.querySelector('input[type=radio][name=' + group + '][value=' +
- dict[group].value + ']').checked = true;
- var radios = document.querySelectorAll('input[type=radio][name=' +
- group + ']');
- for (var i = 0, len = radios.length; i < len; i++) {
- radios[i].disabled = (managedBy != 'default');
- radios[i].controlledBy = controlledBy;
- }
- var indicators = document.querySelectorAll(
- 'span.controlled-setting-indicator[content-setting=' + group + ']');
- if (indicators.length == 0)
- continue;
- // Create a synthetic pref change event decorated as
- // CoreOptionsHandler::CreateValueForPref() does.
- var event = new Event(group);
- event.value = {
- value: dict[group].value,
- controlledBy: controlledBy,
- };
- for (var i = 0; i < indicators.length; i++) {
- indicators[i].handlePrefChange(event);
- }
- if (controlledBy)
- this.getExceptionsList(group, 'normal').setOverruledBy(controlledBy);
- }
- };
-
- /**
- * Initializes an exceptions list.
- * @param {string} type The content type that we are setting exceptions for.
- * @param {Array<options.Exception>} exceptions An array of pairs, where the
- * first element of each pair is the filter string, and the second is the
- * setting (allow/block).
- */
- ContentSettings.setExceptions = function(type, exceptions) {
- this.getExceptionsList(type, 'normal').setExceptions(exceptions);
- };
-
- ContentSettings.setHandlers = function(handlers) {
- $('handlers-list').setHandlers(handlers);
- };
-
- ContentSettings.setIgnoredHandlers = function(ignoredHandlers) {
- $('ignored-handlers-list').setHandlers(ignoredHandlers);
- };
-
- ContentSettings.setOTRExceptions = function(type, otrExceptions) {
- var exceptionsList = this.getExceptionsList(type, 'otr');
- // Settings for Guest hides many sections, so check for null first.
- if (exceptionsList) {
- exceptionsList.parentNode.hidden = false;
- exceptionsList.setExceptions(otrExceptions);
- }
- };
-
- /**
- * @param {string} type The type of exceptions (e.g. "location") to get.
- * @param {string} mode The mode of the desired exceptions list (e.g. otr).
- * @return {?options.contentSettings.ExceptionsList} The corresponding
- * exceptions list or null.
- */
- ContentSettings.getExceptionsList = function(type, mode) {
- var exceptionsList = document.querySelector(
- 'div[contentType=' + type + '] list[mode=' + mode + ']');
- return !exceptionsList ? null :
- assertInstanceof(exceptionsList,
- options.contentSettings.ExceptionsList);
- };
-
- /**
- * The browser's response to a request to check the validity of a given URL
- * pattern.
- * @param {string} type The content type.
- * @param {string} mode The browser mode.
- * @param {string} pattern The pattern.
- * @param {boolean} valid Whether said pattern is valid in the context of
- * a content exception setting.
- */
- ContentSettings.patternValidityCheckComplete =
- function(type, mode, pattern, valid) {
- this.getExceptionsList(type, mode).patternValidityCheckComplete(pattern,
- valid);
- };
-
- /**
- * Shows/hides the link to the Pepper Flash camera or microphone,
- * default or exceptions settings.
- * Please note that whether the link is actually showed or not is also
- * affected by the style class pepper-flash-settings.
- * @param {string} linkType Can be 'default' or 'exceptions'.
- * @param {string} contentType Can be 'mic' or 'camera'.
- * @param {boolean} show Whether to show (or hide) the link.
- */
- ContentSettings.showMediaPepperFlashLink =
- function(linkType, contentType, show) {
- assert(['default', 'exceptions'].indexOf(linkType) >= 0);
- assert(['mic', 'camera'].indexOf(contentType) >= 0);
- $('media-pepper-flash-' + linkType + '-' + contentType).hidden = !show;
- };
-
- /**
- * Updates the microphone/camera devices menu with the given entries.
- * @param {string} type The device type.
- * @param {Array} devices List of available devices.
- * @param {string} defaultdevice The unique id of the current default device.
- */
- ContentSettings.updateDevicesMenu = function(type, devices, defaultdevice) {
- var deviceSelect = '';
- if (type == 'mic') {
- deviceSelect = $('media-select-mic');
- } else if (type == 'camera') {
- deviceSelect = $('media-select-camera');
- } else {
- console.error('Unknown device type for <device select> UI element: ' +
- type);
- return;
- }
-
- deviceSelect.textContent = '';
-
- var deviceCount = devices.length;
- var defaultIndex = -1;
- for (var i = 0; i < deviceCount; i++) {
- var device = devices[i];
- var option = new Option(device.name, device.id);
- if (option.value == defaultdevice)
- defaultIndex = i;
- deviceSelect.appendChild(option);
- }
- if (defaultIndex >= 0)
- deviceSelect.selectedIndex = defaultIndex;
- };
-
- /**
- * Sets the visibility of the microphone/camera devices menu.
- * @param {string} type The content settings type name of this device.
- * @param {boolean} show Whether to show the menu.
- */
- ContentSettings.setDevicesMenuVisibility = function(type, show) {
- assert(type == 'media-stream-mic' || type == 'media-stream-camera');
- var deviceSelect = $(type == 'media-stream-mic' ? 'media-select-mic' :
- 'media-select-camera');
- deviceSelect.hidden = !show;
- };
-
- /**
- * Enables/disables the protected content exceptions button.
- * @param {boolean} enable Whether to enable the button.
- */
- ContentSettings.enableProtectedContentExceptions = function(enable) {
- var exceptionsButton = $('protected-content-exceptions');
- if (exceptionsButton)
- exceptionsButton.disabled = !enable;
- };
-
- /**
- * Set the default microphone device based on the popup selection.
- * @private
- */
- ContentSettings.setDefaultMicrophone_ = function() {
- var deviceSelect = $('media-select-mic');
- chrome.send('setDefaultCaptureDevice', ['mic', deviceSelect.value]);
- };
-
- /**
- * Set the default camera device based on the popup selection.
- * @private
- */
- ContentSettings.setDefaultCamera_ = function() {
- var deviceSelect = $('media-select-camera');
- chrome.send('setDefaultCaptureDevice', ['camera', deviceSelect.value]);
- };
-
- // Export
- return {
- ContentSettings: ContentSettings
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/content_settings_exceptions_area.html b/chromium/chrome/browser/resources/options/content_settings_exceptions_area.html
deleted file mode 100644
index c6b5efdf08e..00000000000
--- a/chromium/chrome/browser/resources/options/content_settings_exceptions_area.html
+++ /dev/null
@@ -1,155 +0,0 @@
-<div id="content-settings-exceptions-area" class="page" hidden>
- <div class="close-button"></div>
- <h1></h1>
- <div class="content-area">
- <div id="exception-column-headers">
- <div id="exception-pattern-column">$i18n{exceptionPatternHeader}</div>
- <div id="exception-behavior-column" class="exception-value-column-header">
- $i18n{exceptionBehaviorHeader}
- </div>
- <div id="exception-zoom-column" class="exception-value-column-header"
- hidden>
- $i18n{exceptionZoomHeader}
- </div>
- <div id="exception-usb-device-column"
- class="exception-value-column-header" hidden>
- $i18n{exceptionUsbDeviceHeader}
- </div>
- </div>
- <div contentType="cookies">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- <div class="flash-plugin-area">
- <a href="$i18nRaw{flashStorageUrl}" target="_blank">
- $i18n{flashStorageSettings}
- </a>
- </div>
- </div>
- <div contentType="images">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="javascript">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="plugins">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="popups">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="location">
- <list mode="normal"></list>
- </div>
- <div contentType="notifications">
- <list mode="normal"></list>
- </div>
- <div contentType="protectedContent">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="media-stream-mic">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- <div id="media-pepper-flash-exceptions-mic" class="pepper-flash-settings">
- <span>$i18n{mediaPepperFlashMicExceptionsDivergedLabel}</span>
- <a target="_blank" href="$i18nRaw{mediaPepperFlashWebsitePrivacyURL}">
- $i18n{mediaPepperFlashChangeLink}
- </a>
- </div>
- </div>
- <div contentType="media-stream-camera">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- <div id="media-pepper-flash-exceptions-camera"
- class="pepper-flash-settings">
- <span>$i18n{mediaPepperFlashCameraExceptionsDivergedLabel}</span>
- <a target="_blank" href="$i18nRaw{mediaPepperFlashWebsitePrivacyURL}">
- $i18n{mediaPepperFlashChangeLink}
- </a>
- </div>
- </div>
- <div contentType="ppapi-broker">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="multiple-automatic-downloads">
- <list mode="normal"></list>
- </div>
- <div contentType="midi-sysex">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="push-messaging">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="usb-devices">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- <div contentType="background-sync">
- <list mode="normal"></list>
- </div>
- <div contentType="zoomlevels">
- <list mode="normal"></list>
- <div>
- <span class="otr-explanation">$i18n{otrExceptionsExplanation}</span>
- <list mode="otr"></list>
- </div>
- </div>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a target="_blank"
- href="$i18nRaw{exceptionsLearnMoreUrl}">$i18n{learnMore}</a>
- </div>
- <div class="action-area-right">
- <div class="button-strip">
- <button id="content-settings-exceptions-overlay-confirm"
- class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/content_settings_exceptions_area.js b/chromium/chrome/browser/resources/options/content_settings_exceptions_area.js
deleted file mode 100644
index 9043b0886e4..00000000000
--- a/chromium/chrome/browser/resources/options/content_settings_exceptions_area.js
+++ /dev/null
@@ -1,734 +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.
-
-cr.define('options.contentSettings', function() {
- /** @const */ var ControlledSettingIndicator =
- options.ControlledSettingIndicator;
- /** @const */ var InlineEditableItemList = options.InlineEditableItemList;
- /** @const */ var InlineEditableItem = options.InlineEditableItem;
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /**
- * Returns whether exceptions list for the type is editable.
- *
- * @param {string} contentType The type of the list.
- */
- function isEditableType(contentType) {
- // Exceptions of the following lists are not editable for now.
- return !(contentType == 'location' ||
- contentType == 'media-stream-mic' ||
- contentType == 'media-stream-camera' ||
- contentType == 'midi-sysex' ||
- contentType == 'zoomlevels' ||
- isChosenObjectType(contentType));
- }
-
- /**
- * Returns whether exceptions of this type represent chosen objects.
- *
- * @param {string} contentType The type of the list.
- */
- function isChosenObjectType(contentType) {
- return contentType == 'usb-devices';
- }
-
- /**
- * Returns the ID of the column containing values for the given content type.
- *
- * @param {string} contentType The type of the list.
- */
- function valueColumnForContentType(contentType) {
- if (contentType == 'usb-devices')
- return 'exception-usb-device-column';
- if (contentType == 'zoomlevels')
- return 'exception-zoom-column';
- return 'exception-behavior-column';
- }
-
- /**
- * Creates a new exceptions list item.
- *
- * @param {string} contentType The type of the list.
- * @param {string} mode The browser mode, 'otr' or 'normal'.
- * @param {Object} exception A dictionary that contains the data of the
- * exception.
- * @constructor
- * @extends {options.InlineEditableItem}
- */
- function ExceptionsListItem(contentType, mode, exception) {
- var el = cr.doc.createElement('div');
- el.mode = mode;
- el.contentType = contentType;
- el.dataItem = exception;
- el.__proto__ = ExceptionsListItem.prototype;
- el.decorate();
-
- return el;
- }
-
- ExceptionsListItem.prototype = {
- __proto__: InlineEditableItem.prototype,
-
- /**
- * Called when an element is decorated as a list item.
- */
- decorate: function() {
- InlineEditableItem.prototype.decorate.call(this);
-
- this.isPlaceholder = !this.pattern;
- var patternCell = this.createEditableTextCell(this.pattern);
- patternCell.className = 'exception-pattern';
- patternCell.classList.add('weakrtl');
- this.contentElement.appendChild(patternCell);
- if (this.pattern)
- this.patternLabel = patternCell.querySelector('.static-text');
- var input = patternCell.querySelector('input');
-
- // Setting label for display mode. |pattern| will be null for the 'add new
- // exception' row.
- if (this.pattern) {
- var settingLabel = cr.doc.createElement('span');
- settingLabel.textContent = this.settingForDisplay();
- settingLabel.className = 'exception-setting overruleable';
- settingLabel.setAttribute('displaymode', 'static');
- this.contentElement.appendChild(settingLabel);
- this.settingLabel = settingLabel;
- }
-
- // Setting select element for edit mode.
- var select = cr.doc.createElement('select');
- var optionAllow = cr.doc.createElement('option');
- optionAllow.textContent = loadTimeData.getString('allowException');
- optionAllow.value = 'allow';
- select.appendChild(optionAllow);
-
- if (this.contentType == 'plugins') {
- var optionDetect = cr.doc.createElement('option');
- optionDetect.textContent = loadTimeData.getString('detectException');
- optionDetect.value = 'detect_important_content';
- select.appendChild(optionDetect);
- }
-
- if (this.contentType == 'cookies') {
- var optionSession = cr.doc.createElement('option');
- optionSession.textContent = loadTimeData.getString('sessionException');
- optionSession.value = 'session_only';
- select.appendChild(optionSession);
- }
-
- var optionBlock = cr.doc.createElement('option');
- optionBlock.textContent = loadTimeData.getString('blockException');
- optionBlock.value = 'block';
- select.appendChild(optionBlock);
-
- if (this.isEmbeddingRule()) {
- this.patternLabel.classList.add('sublabel');
- this.editable = false;
- }
-
- if (this.setting == 'default') {
- // Items that don't have their own settings (parents of 'embedded on'
- // items) aren't deletable.
- this.deletable = false;
- this.editable = false;
- }
-
- if (this.contentType != 'zoomlevels' &&
- !isChosenObjectType(this.contentType)) {
- this.addEditField(select, this.settingLabel);
- this.contentElement.appendChild(select);
- }
- select.className = 'exception-setting';
- select.setAttribute('aria-labelledby',
- valueColumnForContentType(this.contentType));
-
- if (this.pattern)
- select.setAttribute('displaymode', 'edit');
-
- if (this.contentType == 'zoomlevels') {
- this.deletable = true;
-
- var zoomLabel = cr.doc.createElement('span');
- zoomLabel.textContent = this.dataItem.zoom;
- zoomLabel.className = 'exception-setting';
- zoomLabel.setAttribute('displaymode', 'static');
- this.contentElement.appendChild(zoomLabel);
- this.zoomLabel = zoomLabel;
- }
-
- if (isChosenObjectType(this.contentType) &&
- this.dataItem.object !== undefined) {
- this.deletable = true;
-
- var objectLabel = cr.doc.createElement('span');
- objectLabel.textContent = this.dataItem['objectName'];
- objectLabel.className = 'exception-setting';
- objectLabel.setAttribute('displaymode', 'static');
- this.contentElement.appendChild(objectLabel);
- this.objectLabel = objectLabel;
- }
-
- // Used to track whether the URL pattern in the input is valid.
- // This will be true if the browser process has informed us that the
- // current text in the input is valid. Changing the text resets this to
- // false, and getting a response from the browser sets it back to true.
- // It starts off as false for empty string (new exceptions) or true for
- // already-existing exceptions (which we assume are valid).
- this.inputValidityKnown = this.pattern;
- // This one tracks the actual validity of the pattern in the input. This
- // starts off as true so as not to annoy the user when they add a new and
- // empty input.
- this.inputIsValid = true;
-
- this.input = input;
- this.select = select;
-
- this.updateEditables();
- this.editable = this.editable && isEditableType(this.contentType);
-
- // If the source of the content setting exception is not a user
- // preference, that source controls the exception and the user cannot edit
- // or delete it.
- var controlledBy =
- this.dataItem.source && this.dataItem.source != 'preference' ?
- this.dataItem.source : null;
-
- if (controlledBy) {
- this.setAttribute('controlled-by', controlledBy);
- this.deletable = false;
- this.editable = false;
- }
-
- if (controlledBy == 'policy' || controlledBy == 'extension') {
- this.querySelector('.row-delete-button').hidden = true;
- this.appendIndicatorElement(controlledBy);
- }
-
- // If the exception comes from a hosted app, display the name and the
- // icon of the app.
- if (controlledBy == 'HostedApp') {
- this.title =
- loadTimeData.getString('setBy') + ' ' + this.dataItem.appName;
- var button = this.querySelector('.row-delete-button');
- // Use the host app's favicon (16px, match bigger size).
- // See c/b/ui/webui/extensions/extension_icon_source.h
- // for a description of the chrome://extension-icon URL.
- button.style.backgroundImage =
- 'url(\'chrome://extension-icon/' + this.dataItem.appId + '/16/1\')';
- }
-
- var listItem = this;
- // Handle events on the editable nodes.
- input.oninput = function(event) {
- listItem.inputValidityKnown = false;
- chrome.send('checkExceptionPatternValidity',
- [listItem.contentType, listItem.mode, input.value]);
- };
-
- // Listen for edit events.
- this.addEventListener('canceledit', this.onEditCancelled_);
- this.addEventListener('commitedit', this.onEditCommitted_);
- },
-
- /**
- * Appends an indicator element to the item. Should be called at most once.
- *
- * @param {string} controlledBy The source that controls the item.
- */
- appendIndicatorElement: function(controlledBy) {
- var indicator = new ControlledSettingIndicator();
- indicator.setAttribute('content-exception', this.contentType);
- // Create a synthetic pref change event decorated as
- // CoreOptionsHandler::CreateValueForPref() does.
- var event = new Event(this.contentType);
- event.value = {controlledBy: controlledBy};
- indicator.handlePrefChange(event);
- this.appendChild(indicator);
- },
-
- isEmbeddingRule: function() {
- return this.dataItem.embeddingOrigin &&
- this.dataItem.embeddingOrigin !== this.dataItem.origin;
- },
-
- /**
- * The pattern (e.g., a URL) for the exception.
- *
- * @type {string}
- */
- get pattern() {
- if (!this.isEmbeddingRule())
- return this.dataItem.origin;
-
- return loadTimeData.getStringF('embeddedOnHost',
- this.dataItem.embeddingOrigin);
- },
- set pattern(pattern) {
- if (!this.editable)
- console.error('Tried to change uneditable pattern');
-
- this.dataItem.displayPattern = pattern;
- },
-
- /**
- * The setting (allow/block) for the exception.
- *
- * @type {string}
- */
- get setting() {
- return this.dataItem.setting;
- },
- set setting(setting) {
- this.dataItem.setting = setting;
- },
-
- /**
- * Gets a human-readable setting string.
- *
- * @return {string} The display string.
- */
- settingForDisplay: function() {
- return this.getDisplayStringForSetting(this.setting);
- },
-
- /**
- * Gets a human-readable display string for setting.
- *
- * @param {string} setting The setting to be displayed.
- * @return {string} The display string.
- */
- getDisplayStringForSetting: function(setting) {
- if (setting == 'allow')
- return loadTimeData.getString('allowException');
- else if (setting == 'block')
- return loadTimeData.getString('blockException');
- else if (setting == 'ask')
- return loadTimeData.getString('askException');
- else if (setting == 'session_only')
- return loadTimeData.getString('sessionException');
- else if (setting == 'detect_important_content')
- return loadTimeData.getString('detectException');
- else if (setting == 'default')
- return '';
-
- console.error('Unknown setting: [' + setting + ']');
- return '';
- },
-
- /**
- * Update this list item to reflect whether the input is a valid pattern.
- *
- * @param {boolean} valid Whether said pattern is valid in the context of a
- * content exception setting.
- */
- setPatternValid: function(valid) {
- if (valid || !this.input.value)
- this.input.setCustomValidity('');
- else
- this.input.setCustomValidity(' ');
- this.inputIsValid = valid;
- this.inputValidityKnown = true;
- },
-
- /**
- * Set the <input> to its original contents. Used when the user quits
- * editing.
- */
- resetInput: function() {
- this.input.value = this.pattern;
- },
-
- /**
- * Copy the data model values to the editable nodes.
- */
- updateEditables: function() {
- this.resetInput();
-
- var settingOption =
- this.select.querySelector('[value=\'' + this.setting + '\']');
- if (settingOption)
- settingOption.selected = true;
- },
-
- /**
- * Updates UI to indicate that the exception was overruled by a source.
- *
- * @param {string} overruledBy The source that overrules the exception.
- */
- setOverruledBy: function(overruledBy) {
- this.classList.toggle('overruled', !!overruledBy);
- this.appendIndicatorElement(overruledBy);
- },
-
- /** @override */
- get currentInputIsValid() {
- return this.inputValidityKnown && this.inputIsValid;
- },
-
- /** @override */
- get hasBeenEdited() {
- var livePattern = this.input.value;
- var liveSetting = this.select.value;
- return livePattern != this.pattern || liveSetting != this.setting;
- },
-
- /**
- * Called when committing an edit.
- *
- * @param {Event} e The end event.
- * @private
- */
- onEditCommitted_: function(e) {
- var newPattern = this.input.value;
- var newSetting = this.select.value;
-
- this.finishEdit(newPattern, newSetting);
- },
-
- /**
- * Called when cancelling an edit; resets the control states.
- *
- * @param {Event} e The cancel event.
- * @private
- */
- onEditCancelled_: function(e) {
- this.updateEditables();
- this.setPatternValid(true);
- },
-
- /**
- * Editing is complete; update the model.
- *
- * @param {string} newPattern The pattern that the user entered.
- * @param {string} newSetting The setting the user chose.
- */
- finishEdit: function(newPattern, newSetting) {
- this.patternLabel.textContent = newPattern;
- this.settingLabel.textContent = this.settingForDisplay();
- var oldPattern = this.pattern;
- this.pattern = newPattern;
- this.setting = newSetting;
-
- // TODO(estade): this will need to be updated if geolocation/notifications
- // become editable.
- if (oldPattern != newPattern) {
- chrome.send('removeException',
- [this.contentType, this.mode, oldPattern]);
- }
-
- chrome.send('setException',
- [this.contentType, this.mode, newPattern, newSetting]);
- },
- };
-
- /**
- * Creates a new list item for the Add New Item row, which doesn't represent
- * an actual entry in the exceptions list but allows the user to add new
- * exceptions.
- *
- * @param {string} contentType The type of the list.
- * @param {string} mode The browser mode, 'otr' or 'normal'.
- * @constructor
- * @extends {options.contentSettings.ExceptionsListItem}
- */
- function ExceptionsAddRowListItem(contentType, mode) {
- var el = cr.doc.createElement('div');
- el.mode = mode;
- el.contentType = contentType;
- el.dataItem = [];
- el.__proto__ = ExceptionsAddRowListItem.prototype;
- el.decorate();
-
- return el;
- }
-
- ExceptionsAddRowListItem.prototype = {
- __proto__: ExceptionsListItem.prototype,
-
- decorate: function() {
- ExceptionsListItem.prototype.decorate.call(this);
-
- this.input.placeholder =
- loadTimeData.getString('addNewExceptionInstructions');
-
- // Do we always want a default of allow?
- this.setting = 'allow';
- },
-
- /**
- * Clear the <input> and let the placeholder text show again.
- */
- resetInput: function() {
- this.input.value = '';
- },
-
- /** @override */
- get hasBeenEdited() {
- return this.input.value != '';
- },
-
- /**
- * Editing is complete; update the model. As long as the pattern isn't
- * empty, we'll just add it.
- *
- * @param {string} newPattern The pattern that the user entered.
- * @param {string} newSetting The setting the user chose.
- */
- finishEdit: function(newPattern, newSetting) {
- this.resetInput();
- chrome.send('setException',
- [this.contentType, this.mode, newPattern, newSetting]);
- },
- };
-
- /**
- * Creates a new exceptions list.
- *
- * @constructor
- * @extends {options.InlineEditableItemList}
- */
- var ExceptionsList = cr.ui.define('list');
-
- ExceptionsList.prototype = {
- __proto__: InlineEditableItemList.prototype,
-
- /**
- * Called when an element is decorated as a list.
- */
- decorate: function() {
- InlineEditableItemList.prototype.decorate.call(this);
-
- this.classList.add('settings-list');
-
- for (var parentNode = this.parentNode; parentNode;
- parentNode = parentNode.parentNode) {
- if (parentNode.hasAttribute('contentType')) {
- this.contentType = parentNode.getAttribute('contentType');
- break;
- }
- }
-
- if (!this.isEditable())
- this.tabIndex = 0;
-
- this.mode = this.getAttribute('mode');
- this.autoExpands = true;
- this.reset();
- },
-
- /**
- * Creates an item to go in the list.
- *
- * @param {Object} entry The element from the data model for this row.
- */
- createItem: function(entry) {
- if (entry) {
- return new ExceptionsListItem(this.contentType,
- this.mode,
- entry);
- } else {
- var addRowItem = new ExceptionsAddRowListItem(this.contentType,
- this.mode);
- addRowItem.deletable = false;
- return addRowItem;
- }
- },
-
- /**
- * Updates UI to indicate that user exceptions were overruled by a source.
- *
- * @param {string} overruledBy The source that overrules user exceptions.
- */
- setOverruledBy: function(overruledBy) {
- for (var index = 0; index < this.dataModel.length; ++index) {
- var item = this.getListItemByIndex(index);
- if (item.dataItem.source == 'preference')
- item.setOverruledBy(overruledBy);
- }
- },
-
- /**
- * Sets the exceptions in the js model.
- *
- * @param {Array<options.Exception>} entries A list of dictionaries of
- * values, each dictionary represents an exception.
- */
- setExceptions: function(entries) {
- var deleteCount = this.dataModel.length;
-
- if (this.isEditable()) {
- // We don't want to remove the Add New Exception row.
- deleteCount = deleteCount - 1;
- }
-
- var args = [0, deleteCount];
- args.push.apply(args, entries);
- this.dataModel.splice.apply(this.dataModel, args);
- },
-
- /**
- * The browser has finished checking a pattern for validity. Update the list
- * item to reflect this.
- *
- * @param {string} pattern The pattern.
- * @param {boolean} valid Whether said pattern is valid in the context of a
- * content exception setting.
- */
- patternValidityCheckComplete: function(pattern, valid) {
- var listItems = this.items;
- for (var i = 0; i < listItems.length; i++) {
- var listItem = listItems[i];
- // Don't do anything for messages for the item if it is not the intended
- // recipient, or if the response is stale (i.e. the input value has
- // changed since we sent the request to analyze it).
- if (pattern == listItem.input.value)
- listItem.setPatternValid(valid);
- }
- },
-
- /**
- * Returns whether the rows are editable in this list.
- */
- isEditable: function() {
- // Exceptions of the following lists are not editable for now.
- return isEditableType(this.contentType);
- },
-
- /**
- * Removes all exceptions from the js model.
- */
- reset: function() {
- if (this.isEditable()) {
- // The null creates the Add New Exception row.
- this.dataModel = new ArrayDataModel([null]);
- } else {
- this.dataModel = new ArrayDataModel([]);
- }
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- var listItem = this.getListItemByIndex(index);
- if (!listItem.deletable)
- return;
-
- var dataItem = listItem.dataItem;
- var params = [listItem.contentType,
- listItem.mode,
- dataItem.origin,
- dataItem.embeddingOrigin];
-
- if (isChosenObjectType(this.contentType))
- params.push(dataItem.object);
-
- chrome.send('removeException', params);
- },
- };
-
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Encapsulated handling of content settings list subpage.
- *
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function ContentSettingsExceptionsArea() {
- Page.call(this, 'contentExceptions',
- loadTimeData.getString('contentSettingsPageTabTitle'),
- 'content-settings-exceptions-area');
- }
-
- cr.addSingletonGetter(ContentSettingsExceptionsArea);
-
- ContentSettingsExceptionsArea.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var exceptionsLists = this.pageDiv.querySelectorAll('list');
- for (var i = 0; i < exceptionsLists.length; i++) {
- options.contentSettings.ExceptionsList.decorate(exceptionsLists[i]);
- }
-
- ContentSettingsExceptionsArea.hideOTRLists(false);
-
- // If the user types in the URL without a hash, show just cookies.
- this.showList('cookies');
-
- $('content-settings-exceptions-overlay-confirm').onclick =
- PageManager.closeOverlay.bind(PageManager);
- },
-
- /**
- * Shows one list and hides all others.
- *
- * @param {string} type The content type.
- */
- showList: function(type) {
- // Update the title for the type that was shown.
- this.title = loadTimeData.getString(type + 'TabTitle');
-
- var header = this.pageDiv.querySelector('h1');
- var camelCasedType = type.replace(/-([a-z])/g, function(g) {
- return g[1].toUpperCase();
- });
- header.textContent = loadTimeData.getString(camelCasedType + 'Header');
-
- var divs = this.pageDiv.querySelectorAll('div[contentType]');
- for (var i = 0; i < divs.length; i++) {
- if (divs[i].getAttribute('contentType') == type)
- divs[i].hidden = false;
- else
- divs[i].hidden = true;
- }
-
- var valueColumnId = valueColumnForContentType(type);
- var headers =
- this.pageDiv.querySelectorAll('div.exception-value-column-header');
- for (var i = 0; i < headers.length; ++i)
- headers[i].hidden = (headers[i].id != valueColumnId);
- },
-
- /**
- * Called after the page has been shown. Show the content type for the
- * location's hash.
- */
- didShowPage: function() {
- if (this.hash)
- this.showList(this.hash.slice(1));
- },
- };
-
- /**
- * Called when the last incognito window is closed.
- */
- ContentSettingsExceptionsArea.OTRProfileDestroyed = function() {
- this.hideOTRLists(true);
- };
-
- /**
- * Hides the incognito exceptions lists and optionally clears them as well.
- * @param {boolean} clear Whether to clear the lists.
- */
- ContentSettingsExceptionsArea.hideOTRLists = function(clear) {
- var otrLists = document.querySelectorAll('list[mode=otr]');
-
- for (var i = 0; i < otrLists.length; i++) {
- otrLists[i].parentNode.hidden = true;
- if (clear)
- otrLists[i].reset();
- }
- };
-
- return {
- ExceptionsListItem: ExceptionsListItem,
- ExceptionsAddRowListItem: ExceptionsAddRowListItem,
- ExceptionsList: ExceptionsList,
- ContentSettingsExceptionsArea: ContentSettingsExceptionsArea,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/content_settings_ui.js b/chromium/chrome/browser/resources/options/content_settings_ui.js
deleted file mode 100644
index 995b52aa240..00000000000
--- a/chromium/chrome/browser/resources/options/content_settings_ui.js
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-cr.define('options', function() {
-
- //////////////////////////////////////////////////////////////////////////////
- // ContentSettingsRadio class:
-
- // Define a constructor that uses an input element as its underlying element.
- var ContentSettingsRadio = cr.ui.define('input');
-
- ContentSettingsRadio.prototype = {
- __proto__: HTMLInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- this.type = 'radio';
- var self = this;
-
- this.addEventListener('change',
- function(e) {
- chrome.send('setContentFilter', [this.name, this.value]);
- });
- },
- };
-
- /**
- * Whether the content setting is controlled by something else than the user's
- * settings (either 'policy' or 'extension').
- */
- cr.defineProperty(ContentSettingsRadio, 'controlledBy', cr.PropertyKind.ATTR);
-
- //////////////////////////////////////////////////////////////////////////////
- // HandlersEnabledRadio class:
-
- // Define a constructor that uses an input element as its underlying element.
- var HandlersEnabledRadio = cr.ui.define('input');
-
- HandlersEnabledRadio.prototype = {
- __proto__: HTMLInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- this.type = 'radio';
- var self = this;
-
- this.addEventListener('change',
- function(e) {
- chrome.send('setHandlersEnabled', [this.value == 'allow']);
- });
- },
- };
-
- // Export
- return {
- ContentSettingsRadio: ContentSettingsRadio,
- HandlersEnabledRadio: HandlersEnabledRadio
- };
-
-});
-
diff --git a/chromium/chrome/browser/resources/options/controlled_setting.js b/chromium/chrome/browser/resources/options/controlled_setting.js
deleted file mode 100644
index 7b383215ac4..00000000000
--- a/chromium/chrome/browser/resources/options/controlled_setting.js
+++ /dev/null
@@ -1,226 +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.
-
-cr.define('options', function() {
- /** @const */ var Preferences = options.Preferences;
-
- /**
- * A controlled setting indicator that can be placed on a setting as an
- * indicator that the value is controlled by some external entity such as
- * policy or an extension.
- * @constructor
- * @extends {cr.ui.ControlledIndicator}
- */
- var ControlledSettingIndicator = cr.ui.define('span');
-
- ControlledSettingIndicator.prototype = {
- __proto__: cr.ui.ControlledIndicator.prototype,
-
- /**
- * Decorates the base element to show the proper icon.
- */
- decorate: function() {
- cr.ui.ControlledIndicator.prototype.decorate.call(this);
-
- // If there is a pref, track its controlledBy and recommendedValue
- // properties in order to be able to bring up the correct bubble.
- if (this.pref) {
- Preferences.getInstance().addEventListener(
- this.pref, this.handlePrefChange.bind(this));
- this.resetHandler = this.clearAssociatedPref_;
- }
- },
-
- /**
- * The given handler will be called when the user clicks on the 'reset to
- * recommended value' link shown in the indicator bubble. The |this| object
- * will be the indicator itself.
- * @param {function()} handler The handler to be called.
- */
- set resetHandler(handler) {
- this.resetHandler_ = handler;
- },
-
- /**
- * Clears the preference associated with this indicator.
- * @private
- */
- clearAssociatedPref_: function() {
- Preferences.clearPref(this.pref, !this.dialogPref);
- },
-
- /**
- * Handle changes to the associated pref by hiding any currently visible
- * bubble and updating the controlledBy property.
- * @param {Event} event Pref change event.
- * @suppress {checkTypes}
- * TODO(vitalyp): remove the suppression. |controlledBy| property is defined
- * by cr.defineProperty(). Currently null can't be assigned to such
- * properties due to implementation of ChromePass.java. See this discussion
- * to change nulls to empty string below:
- * https://chromiumcodereview.appspot.com/11066015/
- */
- handlePrefChange: function(event) {
- PageManager.hideBubble();
- if (event.value.controlledBy) {
- if (!this.value || String(event.value.value) == this.value) {
- this.controlledBy = event.value.controlledBy;
- if (event.value.extension) {
- this.extensionId = event.value.extension.id;
- this.extensionIcon = event.value.extension.icon;
- this.extensionName = event.value.extension.name;
- }
- } else {
- this.controlledBy = null;
- }
- } else if (event.value.recommendedValue != undefined) {
- this.controlledBy =
- !this.value || String(event.value.recommendedValue) == this.value ?
- 'hasRecommendation' : null;
- } else {
- this.controlledBy = null;
- }
- },
-
- /**
- * Uses the page's PageManager to display an informational bubble.
- * @override
- */
- showBubble: function(content) {
- PageManager.showBubble(content, this.image, this, this.location);
- },
-
- /**
- * Uses the page's PageManager to hide the currently visible bubble, if
- * any.
- * @override
- */
- hideBubble: function() {
- PageManager.hideBubble();
- },
-
- /**
- * Queries the |loadTimeData| singleton for the default bubble text strings.
- * @override
- */
- getDefaultStrings: function() {
- // Construct the bubble text.
- if (this.hasAttribute('plural')) {
- var defaultStrings = {
- 'policy': loadTimeData.getString('controlledSettingsPolicy'),
- 'extension': loadTimeData.getString('controlledSettingsExtension'),
- 'extensionWithName':
- loadTimeData.getString('controlledSettingsExtensionWithName'),
- };
- if (cr.isChromeOS) {
- defaultStrings.shared =
- loadTimeData.getString('controlledSettingsShared');
- }
- } else {
- var defaultStrings = {
- 'policy': loadTimeData.getString('controlledSettingPolicy'),
- 'extension': loadTimeData.getString('controlledSettingExtension'),
- 'extensionWithName':
- loadTimeData.getString('controlledSettingExtensionWithName'),
- 'recommended': loadTimeData.getString('controlledSettingRecommended'),
- 'hasRecommendation':
- loadTimeData.getString('controlledSettingHasRecommendation'),
- };
- if (cr.isChromeOS) {
- defaultStrings.owner =
- loadTimeData.getString('controlledSettingOwner');
- defaultStrings.shared =
- loadTimeData.getString('controlledSettingShared');
- }
- }
- return defaultStrings;
- },
-
- /**
- * Returns the DOM tree for a showing the message |text|.
- * @param {string} text to be shown in the bubble.
- * @override
- */
- createDomTree: function(text) {
- var content = document.createElement('div');
- content.classList.add('controlled-setting-bubble-header');
- content.textContent = text;
-
- if (this.controlledBy == 'hasRecommendation' && this.resetHandler_ &&
- !this.readOnly) {
- var container = document.createElement('div');
- var action = new ActionLink;
- action.classList.add('controlled-setting-bubble-action');
- action.textContent =
- loadTimeData.getString('controlledSettingFollowRecommendation');
- action.addEventListener('click', this.resetHandler_.bind(this));
- container.appendChild(action);
- content.appendChild(container);
- } else if (this.controlledBy == 'extension' && this.extensionName) {
- var extensionContainer =
- $('extension-controlled-settings-bubble-template').cloneNode(true);
- // No need for an id anymore, and thus remove to avoid id collision.
- extensionContainer.removeAttribute('id');
- extensionContainer.hidden = false;
-
- var extensionName = extensionContainer.querySelector(
- '.controlled-setting-bubble-extension-name');
- extensionName.textContent = this.extensionName;
- extensionName.style.backgroundImage =
- 'url("' + this.extensionIcon + '")';
-
- var manageLink = extensionContainer.querySelector(
- '.controlled-setting-bubble-extension-manage-link');
- var extensionId = this.extensionId;
- manageLink.onclick = function() {
- if (window != window.top) {
- uber.invokeMethodOnWindow(
- window.top, 'showPage',
- {pageId: 'extensions', path: '?id=' + extensionId});
- } else {
- window.open('chrome://extensions/?id=' + extensionId);
- }
- };
-
- var disableButton = extensionContainer.querySelector(
- '.controlled-setting-bubble-extension-disable-button');
- disableButton.onclick =
- function() { chrome.send('disableExtension', [extensionId]); };
- content.appendChild(extensionContainer);
- }
- return content;
- },
- };
-
- /**
- * The name of the associated preference.
- */
- cr.defineProperty(ControlledSettingIndicator, 'pref', cr.PropertyKind.ATTR);
-
- /**
- * Whether this indicator is part of a dialog. If so, changes made to the
- * associated preference take effect in the settings UI immediately but are
- * only actually committed when the user confirms the dialog. If the user
- * cancels the dialog instead, the changes are rolled back in the settings UI
- * and never committed.
- */
- cr.defineProperty(ControlledSettingIndicator, 'dialogPref',
- cr.PropertyKind.BOOL_ATTR);
-
- /**
- * The value of the associated preference that the indicator represents. If
- * this is not set, the indicator will be visible whenever any value is
- * enforced or recommended. If it is set, the indicator will be visible only
- * when the enforced or recommended value matches the value it represents.
- * This allows multiple indicators to be created for a set of radio buttons,
- * ensuring that only one of them is visible at a time.
- */
- cr.defineProperty(ControlledSettingIndicator, 'value',
- cr.PropertyKind.ATTR);
-
- // Export.
- return {
- ControlledSettingIndicator: ControlledSettingIndicator
- };
-});
diff --git a/chromium/chrome/browser/resources/options/cookies_list.js b/chromium/chrome/browser/resources/options/cookies_list.js
deleted file mode 100644
index 5cd0f977799..00000000000
--- a/chromium/chrome/browser/resources/options/cookies_list.js
+++ /dev/null
@@ -1,961 +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.
-
-cr.define('options', function() {
- /** @const */ var DeletableItemList = options.DeletableItemList;
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
- /** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel;
-
- // This structure maps the various cookie type names from C++ (hence the
- // underscores) to arrays of the different types of data each has, along with
- // the i18n name for the description of that data type.
- /** @const */ var cookieInfo = {
- 'cookie': [['name', 'label_cookie_name'],
- ['content', 'label_cookie_content'],
- ['domain', 'label_cookie_domain'],
- ['path', 'label_cookie_path'],
- ['sendfor', 'label_cookie_send_for'],
- ['accessibleToScript', 'label_cookie_accessible_to_script'],
- ['created', 'label_cookie_created'],
- ['expires', 'label_cookie_expires']],
- 'app_cache': [['manifest', 'label_app_cache_manifest'],
- ['size', 'label_local_storage_size'],
- ['created', 'label_cookie_created'],
- ['accessed', 'label_cookie_last_accessed']],
- 'database': [['name', 'label_cookie_name'],
- ['desc', 'label_webdb_desc'],
- ['size', 'label_local_storage_size'],
- ['modified', 'label_local_storage_last_modified']],
- 'local_storage': [['origin', 'label_local_storage_origin'],
- ['size', 'label_local_storage_size'],
- ['modified', 'label_local_storage_last_modified']],
- 'indexed_db': [['origin', 'label_indexed_db_origin'],
- ['size', 'label_indexed_db_size'],
- ['modified', 'label_indexed_db_last_modified']],
- 'file_system': [['origin', 'label_file_system_origin'],
- ['persistent', 'label_file_system_persistent_usage'],
- ['temporary', 'label_file_system_temporary_usage']],
- 'channel_id': [['serverId', 'label_channel_id_server_id'],
- ['certType', 'label_channel_id_type'],
- ['created', 'label_channel_id_created']],
- 'service_worker': [['origin', 'label_service_worker_origin'],
- ['size', 'label_service_worker_size'],
- ['scopes', 'label_service_worker_scopes']],
- 'cache_storage': [['origin', 'label_cache_storage_origin'],
- ['size', 'label_cache_storage_size'],
- ['modified', 'label_cache_storage_last_modified']],
- 'flash_lso': [['domain', 'label_cookie_domain']],
- 'media_license': [['origin', 'label_media_license_origin'],
- ['size', 'label_media_license_size'],
- ['modified', 'label_media_license_last_modified']],
- };
-
- /**
- * Returns the item's height, like offsetHeight but such that it works better
- * when the page is zoomed. See the similar calculation in @{code cr.ui.List}.
- * This version also accounts for the animation done in this file.
- * @param {Element} item The item to get the height of.
- * @return {number} The height of the item, calculated with zooming in mind.
- */
- function getItemHeight(item) {
- var height = item.style.height;
- // Use the fixed animation target height if set, in case the element is
- // currently being animated and we'd get an intermediate height below.
- if (height && height.substr(-2) == 'px')
- return parseInt(height.substr(0, height.length - 2), 10);
- return item.getBoundingClientRect().height;
- }
-
- /**
- * Create tree nodes for the objects in the data array, and insert them all
- * into the given list using its @{code splice} method at the given index.
- * @param {Array<Object>} data The data objects for the nodes to add.
- * @param {number} start The index at which to start inserting the nodes.
- * @return {Array<options.CookieTreeNode>} An array of CookieTreeNodes added.
- */
- function spliceTreeNodes(data, start, list) {
- var nodes = data.map(function(x) { return new CookieTreeNode(x); });
- // Insert [start, 0] at the beginning of the array of nodes, making it
- // into the arguments we want to pass to @{code list.splice} below.
- nodes.splice(0, 0, start, 0);
- list.splice.apply(list, nodes);
- // Remove the [start, 0] prefix and return the array of nodes.
- nodes.splice(0, 2);
- return nodes;
- }
-
- /**
- * Adds information about an app that protects this data item to the
- * |element|.
- * @param {Element} element The DOM element the information should be
- appended to.
- * @param {{id: string, name: string}} appInfo Information about an app.
- */
- function addAppInfo(element, appInfo) {
- var img = element.ownerDocument.createElement('img');
- img.src = 'chrome://extension-icon/' + appInfo.id + '/16/1';
- element.title = loadTimeData.getString('label_protected_by_apps') +
- ' ' + appInfo.name;
- img.className = 'protecting-app';
- element.appendChild(img);
- }
-
- var parentLookup = {};
- var lookupRequests = {};
-
- /**
- * Creates a new list item for sites data. Note that these are created and
- * destroyed lazily as they scroll into and out of view, so they must be
- * stateless. We cache the expanded item in @{code CookiesList} though, so it
- * can keep state. (Mostly just which item is selected.)
- * @param {Object} origin Data used to create a cookie list item.
- * @param {options.CookiesList} list The list that will contain this item.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function CookieListItem(origin, list) {
- var listItem = new DeletableItem();
- listItem.__proto__ = CookieListItem.prototype;
-
- listItem.origin = origin;
- listItem.list = list;
- listItem.decorate();
-
- // This hooks up updateOrigin() to the list item, makes the top-level
- // tree nodes (i.e., origins) register their IDs in parentLookup, and
- // causes them to request their children if they have none. Note that we
- // have special logic in the setter for the parent property to make sure
- // that we can still garbage collect list items when they scroll out of
- // view, even though it appears that we keep a direct reference.
- if (origin) {
- origin.parent = listItem;
- origin.updateOrigin();
- }
-
- return listItem;
- }
-
- CookieListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /** @override */
- decorate: function() {
- this.siteChild = this.ownerDocument.createElement('div');
- this.siteChild.className = 'cookie-site';
- this.dataChild = this.ownerDocument.createElement('div');
- this.dataChild.className = 'cookie-data';
- this.sizeChild = this.ownerDocument.createElement('div');
- this.sizeChild.className = 'cookie-size';
- this.itemsChild = this.ownerDocument.createElement('div');
- this.itemsChild.className = 'cookie-items';
- this.infoChild = this.ownerDocument.createElement('div');
- this.infoChild.className = 'cookie-details';
- this.infoChild.hidden = true;
-
- var remove = this.ownerDocument.createElement('button');
- remove.textContent = loadTimeData.getString('remove_cookie');
- remove.onclick = this.removeCookie_.bind(this);
- this.infoChild.appendChild(remove);
- var content = this.contentElement;
- content.appendChild(this.siteChild);
- content.appendChild(this.dataChild);
- content.appendChild(this.sizeChild);
- content.appendChild(this.itemsChild);
- this.itemsChild.appendChild(this.infoChild);
- if (this.origin && this.origin.data) {
- this.siteChild.textContent = this.origin.data.title;
- this.siteChild.setAttribute('title', this.origin.data.title);
- }
- this.itemList_ = [];
- },
-
- /** @type {boolean} */
- get expanded() {
- return this.expanded_;
- },
- set expanded(expanded) {
- if (this.expanded_ == expanded)
- return;
- this.expanded_ = expanded;
- if (expanded) {
- this.classList.add('show-items');
- var oldExpanded = this.list.expandedItem;
- this.list.expandedItem = this;
- this.updateItems_();
- if (oldExpanded)
- oldExpanded.expanded = false;
- } else {
- if (this.list.expandedItem == this) {
- this.list.expandedItem = null;
- }
- this.style.height = '';
- this.itemsChild.style.height = '';
- this.classList.remove('show-items');
- }
- },
-
- /**
- * The callback for the "remove" button shown when an item is selected.
- * Requests that the currently selected cookie be removed.
- * @private
- */
- removeCookie_: function() {
- if (this.selectedIndex_ >= 0) {
- var item = this.itemList_[this.selectedIndex_];
- if (item && item.node)
- chrome.send('removeCookie', [item.node.pathId]);
- }
- },
-
- /**
- * Disable animation within this cookie list item, in preparation for making
- * changes that will need to be animated. Makes it possible to measure the
- * contents without displaying them, to set animation targets.
- * @private
- */
- disableAnimation_: function() {
- this.itemsHeight_ = getItemHeight(this.itemsChild);
- this.classList.add('measure-items');
- },
-
- /**
- * Enable animation after changing the contents of this cookie list item.
- * See @{code disableAnimation_}.
- * @private
- */
- enableAnimation_: function() {
- if (!this.classList.contains('measure-items'))
- this.disableAnimation_();
- this.itemsChild.style.height = '';
- // This will force relayout in order to calculate the new heights.
- var itemsHeight = getItemHeight(this.itemsChild);
- var fixedHeight = getItemHeight(this) + itemsHeight - this.itemsHeight_;
- this.itemsChild.style.height = this.itemsHeight_ + 'px';
- // Force relayout before enabling animation, so that if we have
- // changed things since the last layout, they will not be animated
- // during subsequent layouts.
- /** @suppress {suspiciousCode} */
- this.itemsChild.offsetHeight;
- this.classList.remove('measure-items');
- this.itemsChild.style.height = itemsHeight + 'px';
- this.style.height = fixedHeight + 'px';
- },
-
- /**
- * Updates the origin summary to reflect changes in its items.
- * Both CookieListItem and CookieTreeNode implement this API.
- * This implementation scans the descendants to update the text.
- */
- updateOrigin: function() {
- var info = {
- cookies: 0,
- database: false,
- localStorage: false,
- appCache: false,
- indexedDb: false,
- fileSystem: false,
- channelIDs: 0,
- serviceWorker: false,
- cacheStorage: false,
- mediaLicense: false,
- };
- if (this.origin)
- this.origin.collectSummaryInfo(info);
-
- var list = [];
- if (info.cookies > 1)
- list.push(loadTimeData.getStringF('cookie_plural', info.cookies));
- else if (info.cookies > 0)
- list.push(loadTimeData.getString('cookie_singular'));
- if (info.database || info.indexedDb)
- list.push(loadTimeData.getString('cookie_database_storage'));
- if (info.localStorage)
- list.push(loadTimeData.getString('cookie_local_storage'));
- if (info.appCache)
- list.push(loadTimeData.getString('cookie_app_cache'));
- if (info.fileSystem)
- list.push(loadTimeData.getString('cookie_file_system'));
- if (info.channelIDs)
- list.push(loadTimeData.getString('cookie_channel_id'));
- if (info.serviceWorker)
- list.push(loadTimeData.getString('cookie_service_worker'));
- if (info.cacheStorage)
- list.push(loadTimeData.getString('cookie_cache_storage'));
- if (info.flashLSO)
- list.push(loadTimeData.getString('cookie_flash_lso'));
- if (info.mediaLicense)
- list.push(loadTimeData.getString('cookie_media_license'));
-
- var text = '';
- for (var i = 0; i < list.length; ++i) {
- if (text.length > 0)
- text += ', ' + list[i];
- else
- text = list[i];
- }
- this.dataChild.textContent = text;
-
- var apps = info.appsProtectingThis;
- for (var key in apps) {
- addAppInfo(this.dataChild, apps[key]);
- }
-
- if (info.quota && info.quota.totalUsage)
- this.sizeChild.textContent = info.quota.totalUsage;
-
- if (this.expanded)
- this.updateItems_();
- },
-
- /**
- * Updates the items section to reflect changes, animating to the new state.
- * Removes existing contents and calls @{code CookieTreeNode.createItems}.
- * @private
- */
- updateItems_: function() {
- this.disableAnimation_();
- this.itemsChild.textContent = '';
- this.infoChild.hidden = true;
- this.selectedIndex_ = -1;
- this.itemList_ = [];
- if (this.origin)
- this.origin.createItems(this);
- this.itemsChild.appendChild(this.infoChild);
- this.enableAnimation_();
- },
-
- /**
- * Append a new cookie node "bubble" to this list item.
- * @param {options.CookieTreeNode} node The cookie node to add a bubble for.
- * @param {Element} div The DOM element for the bubble itself.
- * @return {number} The index the bubble was added at.
- */
- appendItem: function(node, div) {
- this.itemList_.push({node: node, div: div});
- this.itemsChild.appendChild(div);
- return this.itemList_.length - 1;
- },
-
- /**
- * The currently selected cookie node ("cookie bubble") index.
- * @type {number}
- * @private
- */
- selectedIndex_: -1,
-
- /**
- * Get the currently selected cookie node ("cookie bubble") index.
- * @type {number}
- */
- get selectedIndex() {
- return this.selectedIndex_;
- },
-
- /**
- * Set the currently selected cookie node ("cookie bubble") index to
- * |itemIndex|, unselecting any previously selected node first.
- * @param {number} itemIndex The index to set as the selected index.
- */
- set selectedIndex(itemIndex) {
- // Get the list index up front before we change anything.
- var index = this.list.getIndexOfListItem(this);
- // Unselect any previously selected item.
- if (this.selectedIndex_ >= 0) {
- var item = this.itemList_[this.selectedIndex_];
- if (item && item.div)
- item.div.removeAttribute('selected');
- }
- // Special case: decrementing -1 wraps around to the end of the list.
- if (itemIndex == -2)
- itemIndex = this.itemList_.length - 1;
- // Check if we're going out of bounds and hide the item details.
- if (itemIndex < 0 || itemIndex >= this.itemList_.length) {
- this.selectedIndex_ = -1;
- this.disableAnimation_();
- this.infoChild.hidden = true;
- this.enableAnimation_();
- return;
- }
- // Set the new selected item and show the item details for it.
- this.selectedIndex_ = itemIndex;
- this.itemList_[itemIndex].div.setAttribute('selected', '');
- this.disableAnimation_();
- this.itemList_[itemIndex].node.setDetailText(this.infoChild,
- this.list.infoNodes);
- this.infoChild.hidden = false;
- this.enableAnimation_();
- // If we're near the bottom of the list this may cause the list item to go
- // beyond the end of the visible area. Fix it after the animation is done.
- var list = this.list;
- window.setTimeout(function() { list.scrollIndexIntoView(index); }, 150);
- },
- };
-
- /**
- * {@code CookieTreeNode}s mirror the structure of the cookie tree lazily, and
- * contain all the actual data used to generate the {@code CookieListItem}s.
- * @param {Object} data The data object for this node.
- * @constructor
- */
- function CookieTreeNode(data) {
- this.data = data;
- this.children = [];
- }
-
- CookieTreeNode.prototype = {
- /**
- * Insert the given list of cookie tree nodes at the given index.
- * Both CookiesList and CookieTreeNode implement this API.
- * @param {Array<Object>} data The data objects for the nodes to add.
- * @param {number} start The index at which to start inserting the nodes.
- */
- insertAt: function(data, start) {
- var nodes = spliceTreeNodes(data, start, this.children);
- for (var i = 0; i < nodes.length; i++)
- nodes[i].parent = this;
- this.updateOrigin();
- },
-
- /**
- * Remove a cookie tree node from the given index.
- * Both CookiesList and CookieTreeNode implement this API.
- *
- * TODO(dbeam): this method now conflicts with HTMLElement#remove(), which
- * is why the param is optional. Rename.
- *
- * @param {number=} index The index of the tree node to remove.
- */
- remove: function(index) {
- if (index < this.children.length) {
- this.children.splice(index, 1);
- this.updateOrigin();
- }
- },
-
- /**
- * Clears all children.
- * Both CookiesList and CookieTreeNode implement this API.
- * It is used by CookiesList.loadChildren().
- */
- clear: function() {
- // We might leave some garbage in parentLookup for removed children.
- // But that should be OK because parentLookup is cleared when we
- // reload the tree.
- this.children = [];
- this.updateOrigin();
- },
-
- /**
- * The counter used by startBatchUpdates() and endBatchUpdates().
- * @type {number}
- */
- batchCount_: 0,
-
- /**
- * See cr.ui.List.startBatchUpdates().
- * Both CookiesList (via List) and CookieTreeNode implement this API.
- */
- startBatchUpdates: function() {
- this.batchCount_++;
- },
-
- /**
- * See cr.ui.List.endBatchUpdates().
- * Both CookiesList (via List) and CookieTreeNode implement this API.
- */
- endBatchUpdates: function() {
- if (!--this.batchCount_)
- this.updateOrigin();
- },
-
- /**
- * Requests updating the origin summary to reflect changes in this item.
- * Both CookieListItem and CookieTreeNode implement this API.
- */
- updateOrigin: function() {
- if (!this.batchCount_ && this.parent)
- this.parent.updateOrigin();
- },
-
- /**
- * Summarize the information in this node and update @{code info}.
- * This will recurse into child nodes to summarize all descendants.
- * @param {Object} info The info object from @{code updateOrigin}.
- */
- collectSummaryInfo: function(info) {
- if (this.children.length > 0) {
- for (var i = 0; i < this.children.length; ++i)
- this.children[i].collectSummaryInfo(info);
- } else if (this.data && !this.data.hasChildren) {
- if (this.data.type == 'cookie') {
- info.cookies++;
- } else if (this.data.type == 'database') {
- info.database = true;
- } else if (this.data.type == 'local_storage') {
- info.localStorage = true;
- } else if (this.data.type == 'app_cache') {
- info.appCache = true;
- } else if (this.data.type == 'indexed_db') {
- info.indexedDb = true;
- } else if (this.data.type == 'file_system') {
- info.fileSystem = true;
- } else if (this.data.type == 'quota') {
- info.quota = this.data;
- } else if (this.data.type == 'channel_id') {
- info.channelIDs++;
- } else if (this.data.type == 'service_worker') {
- info.serviceWorker = true;
- } else if (this.data.type == 'cache_storage') {
- info.cacheStorage = true;
- } else if (this.data.type == 'flash_lso') {
- info.flashLSO = true;
- } else if (this.data.type == 'media_license') {
- info.mediaLicense = true;
- }
-
- var apps = this.data.appsProtectingThis;
- if (apps) {
- if (!info.appsProtectingThis)
- info.appsProtectingThis = {};
- apps.forEach(function(appInfo) {
- info.appsProtectingThis[appInfo.id] = appInfo;
- });
- }
- }
- },
-
- /**
- * Create the cookie "bubbles" for this node, recursing into children
- * if there are any. Append the cookie bubbles to @{code item}.
- * @param {options.CookieListItem} item The cookie list item to create items
- * in.
- */
- createItems: function(item) {
- if (this.children.length > 0) {
- for (var i = 0; i < this.children.length; ++i)
- this.children[i].createItems(item);
- return;
- }
-
- if (!this.data || this.data.hasChildren)
- return;
-
- var text = '';
- switch (this.data.type) {
- case 'cookie':
- case 'database':
- text = this.data.name;
- break;
- default:
- text = loadTimeData.getString('cookie_' + this.data.type);
- }
- if (!text)
- return;
-
- var div = item.ownerDocument.createElement('div');
- div.className = 'cookie-item';
- // Help out screen readers and such: this is a clickable thing.
- div.setAttribute('role', 'button');
- div.textContent = text;
- var apps = this.data.appsProtectingThis;
- if (apps)
- apps.forEach(addAppInfo.bind(null, div));
-
- var index = item.appendItem(this, div);
- div.onclick = function() {
- item.selectedIndex = (item.selectedIndex == index) ? -1 : index;
- };
- },
-
- /**
- * Set the detail text to be displayed to that of this cookie tree node.
- * Uses preallocated DOM elements for each cookie node type from @{code
- * infoNodes}, and inserts the appropriate elements to @{code element}.
- * @param {Element} element The DOM element to insert elements to.
- * @param {Object<{table: Element, info: Object<Element>}>} infoNodes The
- * map from cookie node types to maps from cookie attribute names to DOM
- * elements to display cookie attribute values, created by
- * @see {CookiesList.decorate}.
- */
- setDetailText: function(element, infoNodes) {
- var table;
- if (this.data && !this.data.hasChildren && cookieInfo[this.data.type]) {
- var info = cookieInfo[this.data.type];
- var nodes = infoNodes[this.data.type].info;
- for (var i = 0; i < info.length; ++i) {
- var name = info[i][0];
- if (name != 'id' && this.data[name])
- nodes[name].textContent = this.data[name];
- else
- nodes[name].textContent = '';
- }
- table = infoNodes[this.data.type].table;
- }
-
- while (element.childNodes.length > 1)
- element.removeChild(element.firstChild);
-
- if (table)
- element.insertBefore(table, element.firstChild);
- },
-
- /**
- * The parent of this cookie tree node.
- * @type {?(options.CookieTreeNode|options.CookieListItem)}
- */
- get parent() {
- // See below for an explanation of this special case.
- if (typeof this.parent_ == 'number')
- return this.list_.getListItemByIndex(this.parent_);
- return this.parent_;
- },
- set parent(parent) {
- if (parent == this.parent)
- return;
-
- if (parent instanceof CookieListItem) {
- // If the parent is to be a CookieListItem, then we keep the reference
- // to it by its containing list and list index, rather than directly.
- // This allows the list items to be garbage collected when they scroll
- // out of view (except the expanded item, which we cache). This is
- // transparent except in the setter and getter, where we handle it.
- if (this.parent_ == undefined || parent.listIndex != -1) {
- // Setting the parent is somewhat tricky because the CookieListItem
- // constructor has side-effects on the |origin| that it wraps. Every
- // time a CookieListItem is created for an |origin|, it registers
- // itself as the parent of the |origin|.
- // The List implementation may create a temporary CookieListItem item
- // that wraps the |origin| of the very first entry of the CokiesList,
- // when the List is redrawn the first time. This temporary
- // CookieListItem is fresh (has listIndex = -1) and is never inserted
- // into the List. Therefore it gets never updated. This destroys the
- // chain of parent pointers.
- // This is the stack trace:
- // CookieListItem
- // CookiesList.createItem
- // List.measureItem
- // List.getDefaultItemSize_
- // List.getDefaultItemHeight_
- // List.getIndexForListOffset_
- // List.getItemsInViewPort
- // List.redraw
- // List.endBatchUpdates
- // CookiesList.loadChildren
- this.parent_ = parent.listIndex;
- }
- this.list_ = parent.list;
- parent.addEventListener('listIndexChange',
- this.parentIndexChanged_.bind(this));
- } else {
- this.parent_ = parent;
- }
-
- if (this.data && this.data.id) {
- if (parent)
- parentLookup[this.data.id] = this;
- else
- delete parentLookup[this.data.id];
- }
-
- if (this.data && this.data.hasChildren &&
- !this.children.length && !lookupRequests[this.data.id]) {
- lookupRequests[this.data.id] = true;
- chrome.send('loadCookie', [this.pathId]);
- }
- },
-
- /**
- * Called when the parent is a CookieListItem whose index has changed.
- * See the code above that avoids keeping a direct reference to
- * CookieListItem parents, to allow them to be garbage collected.
- * @private
- */
- parentIndexChanged_: function(event) {
- if (typeof this.parent_ == 'number') {
- this.parent_ = event.newValue;
- // We set a timeout to update the origin, rather than doing it right
- // away, because this callback may occur while the list items are
- // being repopulated following a scroll event. Calling updateOrigin()
- // immediately could trigger relayout that would reset the scroll
- // position within the list, among other things.
- window.setTimeout(this.updateOrigin.bind(this), 0);
- }
- },
-
- /**
- * The cookie tree path id.
- * @type {string}
- */
- get pathId() {
- var parent = this.parent;
- if (parent && parent instanceof CookieTreeNode)
- return parent.pathId + ',' + this.data.id;
- return this.data.id;
- },
- };
-
- /**
- * Creates a new cookies list.
- * @param {Object=} opt_propertyBag Optional properties.
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var CookiesList = cr.ui.define('list');
-
- CookiesList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- /** @override */
- decorate: function() {
- DeletableItemList.prototype.decorate.call(this);
- this.classList.add('cookie-list');
- this.dataModel = new ArrayDataModel([]);
- this.addEventListener('keydown', this.handleKeyLeftRight_.bind(this));
- var sm = new ListSingleSelectionModel();
- sm.addEventListener('change', this.cookieSelectionChange_.bind(this));
- sm.addEventListener('leadIndexChange', this.cookieLeadChange_.bind(this));
- this.selectionModel = sm;
- this.infoNodes = {};
- this.fixedHeight = false;
- var doc = this.ownerDocument;
- // Create a table for each type of site data (e.g. cookies, databases,
- // etc.) and save it so that we can reuse it for all origins.
- for (var type in cookieInfo) {
- var table = doc.createElement('table');
- table.className = 'cookie-details-table';
- var tbody = doc.createElement('tbody');
- table.appendChild(tbody);
- var info = {};
- for (var i = 0; i < cookieInfo[type].length; i++) {
- var tr = doc.createElement('tr');
- var name = doc.createElement('td');
- var data = doc.createElement('td');
- var pair = cookieInfo[type][i];
- name.className = 'cookie-details-label';
- name.textContent = loadTimeData.getString(pair[1]);
- data.className = 'cookie-details-value';
- data.textContent = '';
- tr.appendChild(name);
- tr.appendChild(data);
- tbody.appendChild(tr);
- info[pair[0]] = data;
- }
- this.infoNodes[type] = {table: table, info: info};
- }
- },
-
- /**
- * Handles key down events and looks for left and right arrows, then
- * dispatches to the currently expanded item, if any.
- * @param {Event} e The keydown event.
- * @private
- */
- handleKeyLeftRight_: function(e) {
- var id = e.key;
- if (hasKeyModifiers(e))
- return;
- if ((id == 'ArrowLeft' || id == 'ArrowRight') && this.expandedItem) {
- var cs = this.ownerDocument.defaultView.getComputedStyle(this);
- var rtl = cs.direction == 'rtl';
- if ((!rtl && id == 'ArrowLeft') || (rtl && id == 'ArrowRight'))
- this.expandedItem.selectedIndex--;
- else
- this.expandedItem.selectedIndex++;
- this.scrollIndexIntoView(this.expandedItem.listIndex);
- // Prevent the page itself from scrolling.
- e.preventDefault();
- }
- },
-
- /**
- * Called on selection model selection changes.
- * @param {Event} ce The selection change event.
- * @private
- */
- cookieSelectionChange_: function(ce) {
- ce.changes.forEach(function(change) {
- var listItem = this.getListItemByIndex(change.index);
- if (listItem) {
- if (!change.selected) {
- // We set a timeout here, rather than setting the item unexpanded
- // immediately, so that if another item gets set expanded right
- // away, it will be expanded before this item is unexpanded. It
- // will notice that, and unexpand this item in sync with its own
- // expansion. Later, this callback will end up having no effect.
- window.setTimeout(function() {
- if (!listItem.selected || !listItem.lead)
- listItem.expanded = false;
- }, 0);
- } else if (listItem.lead) {
- listItem.expanded = true;
- }
- }
- }, this);
- },
-
- /**
- * Called on selection model lead changes.
- * @param {Event} pe The lead change event.
- * @private
- */
- cookieLeadChange_: function(pe) {
- if (pe.oldValue != -1) {
- var listItem = this.getListItemByIndex(pe.oldValue);
- if (listItem) {
- // See cookieSelectionChange_ above for why we use a timeout here.
- window.setTimeout(function() {
- if (!listItem.lead || !listItem.selected)
- listItem.expanded = false;
- }, 0);
- }
- }
- if (pe.newValue != -1) {
- var listItem = this.getListItemByIndex(pe.newValue);
- if (listItem && listItem.selected)
- listItem.expanded = true;
- }
- },
-
- /**
- * The currently expanded item. Used by CookieListItem above.
- * @type {?options.CookieListItem}
- */
- expandedItem: null,
-
- // from cr.ui.List
- /**
- * @override
- * @param {Object} data
- */
- createItem: function(data) {
- // We use the cached expanded item in order to allow it to maintain some
- // state (like its fixed height, and which bubble is selected).
- if (this.expandedItem && this.expandedItem.origin == data)
- return this.expandedItem;
- return new CookieListItem(data, this);
- },
-
- // from options.DeletableItemList
- /** @override */
- deleteItemAtIndex: function(index) {
- var item = this.dataModel.item(index);
- if (item) {
- var pathId = item.pathId;
- if (pathId)
- chrome.send('removeCookie', [pathId]);
- }
- },
-
- /**
- * Insert the given list of cookie tree nodes at the given index.
- * Both CookiesList and CookieTreeNode implement this API.
- * @param {Array<Object>} data The data objects for the nodes to add.
- * @param {number} start The index at which to start inserting the nodes.
- */
- insertAt: function(data, start) {
- spliceTreeNodes(data, start, this.dataModel);
- },
-
- /**
- * Remove a cookie tree node from the given index.
- * Both CookiesList and CookieTreeNode implement this API.
- *
- * TODO(dbeam): this method now conflicts with HTMLElement#remove(), which
- * is why the param is optional. Rename.
- *
- * @param {number=} index The index of the tree node to remove.
- */
- remove: function(index) {
- if (index < this.dataModel.length)
- this.dataModel.splice(index, 1);
- },
-
- /**
- * Clears the list.
- * Both CookiesList and CookieTreeNode implement this API.
- * It is used by CookiesList.loadChildren().
- */
- clear: function() {
- parentLookup = {};
- this.dataModel.splice(0, this.dataModel.length);
- this.redraw();
- },
-
- /**
- * Add tree nodes by given parent.
- * @param {Object} parent The parent node.
- * @param {number} start The index at which to start inserting the nodes.
- * @param {Array} nodesData Nodes data array.
- * @private
- */
- addByParent_: function(parent, start, nodesData) {
- if (!parent)
- return;
-
- parent.startBatchUpdates();
- parent.insertAt(nodesData, start);
- parent.endBatchUpdates();
-
- cr.dispatchSimpleEvent(this, 'change');
- },
-
- /**
- * Add tree nodes by parent id.
- * This is used by cookies_view.js.
- * @param {string} parentId Id of the parent node.
- * @param {number} start The index at which to start inserting the nodes.
- * @param {Array} nodesData Nodes data array.
- */
- addByParentId: function(parentId, start, nodesData) {
- var parent = parentId ? parentLookup[parentId] : this;
- this.addByParent_(parent, start, nodesData);
- },
-
- /**
- * Removes tree nodes by parent id.
- * This is used by cookies_view.js.
- * @param {string} parentId Id of the parent node.
- * @param {number} start The index at which to start removing the nodes.
- * @param {number} count Number of nodes to remove.
- */
- removeByParentId: function(parentId, start, count) {
- var parent = parentId ? parentLookup[parentId] : this;
- if (!parent)
- return;
-
- parent.startBatchUpdates();
- while (count-- > 0)
- parent.remove(start);
- parent.endBatchUpdates();
-
- cr.dispatchSimpleEvent(this, 'change');
- },
-
- /**
- * Loads the immediate children of given parent node.
- * This is used by cookies_view.js.
- * @param {string} parentId Id of the parent node.
- * @param {Array} children The immediate children of parent node.
- */
- loadChildren: function(parentId, children) {
- if (parentId)
- delete lookupRequests[parentId];
- var parent = parentId ? parentLookup[parentId] : this;
- if (!parent)
- return;
-
- parent.startBatchUpdates();
- parent.clear();
- this.addByParent_(parent, 0, children);
- parent.endBatchUpdates();
- },
- };
-
- return {
- CookiesList: CookiesList,
- CookieListItem: CookieListItem,
- CookieTreeNode: CookieTreeNode,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/cookies_view.css b/chromium/chrome/browser/resources/options/cookies_view.css
deleted file mode 100644
index c435819f15e..00000000000
--- a/chromium/chrome/browser/resources/options/cookies_view.css
+++ /dev/null
@@ -1,200 +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. */
-
-/* Styles for the cookies list page. */
-.cookies-view-page {
- height: 90%;
- margin-left: -15px;
- width: 720px;
-}
-
-/* Styles for the cookies list elements in cookies_view.html. */
-.cookies-list {
- -webkit-box-flex: 1;
- /* This property overrides the |min-height: 192px;| property above due to
- * special behavior of the cookies list. */
- border: 1px solid #D9D9D9;
- margin: 0;
- margin-top: 5px;
- min-height: 0;
-}
-
-.cookies-list-content-area {
- -webkit-box-orient: vertical;
- display: -webkit-box;
- overflow-y: hidden;
-}
-
-.cookies-column-headers {
- -webkit-box-align: baseline;
- -webkit-box-orient: horizontal;
- display: -webkit-box;
- position: relative;
- width: 100%;
-}
-
-.cookies-column-headers > * {
- display: block;
-}
-
-.cookies-column-headers h3 {
- font-size: 105%;
- font-weight: bold;
- margin: 10px 0;
-}
-
-/* Notice the width and padding for these columns match up with those below. */
-.cookies-site-column {
- -webkit-padding-start: 7px;
- width: 14em;
-}
-
-.cookies-data-column {
- -webkit-box-flex: 1;
- -webkit-padding-start: 7px;
-}
-
-/* Enable animating the height of items. */
-list.cookie-list .deletable-item {
- transition: height 150ms ease-in-out;
-}
-
-/* Disable webkit-box display. */
-list.cookie-list .deletable-item > :first-child {
- display: block;
-}
-
-/* Force the X for deleting an origin to stay at the top. */
-list.cookie-list > .deletable-item > .close-button {
- position: absolute;
- right: 2px;
- top: 8px;
-}
-
-html[dir=rtl] list.cookie-list > .deletable-item > .close-button {
- left: 2px;
- right: auto;
-}
-
-/* Styles for the site (aka origin) and its summary. */
-.cookie-site {
- /* Notice that the width, margin, and padding match up with those above. */
- -webkit-margin-end: 2px;
- -webkit-padding-start: 5px;
- display: inline-block;
- overflow: hidden;
- text-overflow: ellipsis;
- width: 14em;
-}
-
-list.cookie-list > .deletable-item[selected] .cookie-site {
- -webkit-user-select: text;
-}
-
-.cookie-data {
- display: inline-block;
- max-width: 410px;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.cookie-size {
- display: inline-block;
- float: right;
- margin-right: 0;
-}
-
-list.cookie-list > .deletable-item[selected] .cookie-data {
- -webkit-user-select: text;
-}
-
-
-/* Styles for the individual items (cookies, etc.). */
-.cookie-items {
- /* Notice that the margin and padding match up with those above. */
- -webkit-margin-start: 14em;
- -webkit-padding-start: 7px;
- display: none;
- height: 0;
- opacity: 0;
- transition: 150ms ease-in-out;
- /* Make the cookie items wrap correctly. */
- white-space: normal;
-}
-
-.measure-items .cookie-items {
- height: auto;
- transition: none;
- visibility: hidden;
-}
-
-.show-items .cookie-items {
- display: block;
- opacity: 1;
-}
-
-.cookie-items .cookie-item {
- background: rgb(224, 233, 245);
- border: 1px solid rgb(131, 146, 174);
- border-radius: 5px;
- display: inline-block;
- font-size: 85%;
- height: auto;
- margin: 2px 4px 2px 0;
- max-width: 120px;
- min-width: 40px;
- overflow: hidden;
- padding: 0 3px;
- text-align: center;
- text-overflow: ellipsis;
-}
-
-.cookie-items .cookie-item:hover {
- background: rgb(238, 243, 249);
- border-color: rgb(100, 113, 135);
-}
-
-.cookie-items .cookie-item[selected] {
- background: rgb(245, 248, 248);
- border-color: #B2B2B2;
-}
-
-.cookie-items .cookie-item[selected]:hover {
- background: rgb(245, 248, 248);
- border-color: rgb(100, 113, 135);
-}
-
-.cookie-items .cookie-item .protecting-app,
-.cookie-data .protecting-app {
- margin-bottom: -3px;
- margin-left: 4px;
-}
-
-/* Styles for the cookie details box. */
-.cookie-details {
- background: rgb(245, 248, 248);
- border: 1px solid #B2B2B2;
- border-radius: 5px;
- margin-top: 2px;
- padding: 5px;
-}
-
-list.cookie-list > .deletable-item[selected] .cookie-details {
- -webkit-user-select: text;
-}
-
-.cookie-details-table {
- table-layout: fixed;
- width: 100%;
-}
-
-.cookie-details-label {
- vertical-align: top;
- white-space: pre;
- width: 10em;
-}
-
-.cookie-details-value {
- word-wrap: break-word;
-}
diff --git a/chromium/chrome/browser/resources/options/cookies_view.html b/chromium/chrome/browser/resources/options/cookies_view.html
deleted file mode 100644
index 8176c3b0b19..00000000000
--- a/chromium/chrome/browser/resources/options/cookies_view.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<div id="cookies-view-page" class="page cookies-view-page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{cookiesViewPage}</h1>
- <div class="content-area cookies-list-content-area">
- <div class="cookies-column-headers">
- <div class="cookies-site-column">
- <h3>$i18n{cookie_domain}</h3>
- </div>
- <div class="cookies-data-column">
- <h3>$i18n{cookie_local_data}</h3>
- </div>
- <div class="cookies-header-controls">
- <button class="remove-all-cookies-button">
- $i18n{remove_all_cookie}
- </button>
- <input type="search" class="cookies-search-box"
- placeholder="$i18n{search_cookies}" incremental>
- </div>
- </div>
- <list id="cookies-list" class="cookies-list"></list>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button class="cookies-view-overlay-confirm default-button">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/cookies_view.js b/chromium/chrome/browser/resources/options/cookies_view.js
deleted file mode 100644
index 7e2221ae0dc..00000000000
--- a/chromium/chrome/browser/resources/options/cookies_view.js
+++ /dev/null
@@ -1,147 +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.
-
-cr.define('options', function() {
-
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /////////////////////////////////////////////////////////////////////////////
- // CookiesView class:
-
- /**
- * Encapsulated handling of the cookies and other site data page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function CookiesView(model) {
- Page.call(this, 'cookies',
- loadTimeData.getString('cookiesViewPageTabTitle'),
- 'cookies-view-page');
- }
-
- cr.addSingletonGetter(CookiesView);
-
- CookiesView.prototype = {
- __proto__: Page.prototype,
-
- /**
- * The timer id of the timer set on search query change events.
- * @type {number}
- * @private
- */
- queryDelayTimerId_: 0,
-
- /**
- * The most recent search query, empty string if the query is empty.
- * @type {string}
- * @private
- */
- lastQuery_: '',
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var searchBox = this.pageDiv.querySelector('.cookies-search-box');
- searchBox.addEventListener(
- 'search', this.handleSearchQueryChange_.bind(this));
- searchBox.onkeydown = function(e) {
- // Prevent the overlay from handling this event.
- if (e.key == 'Enter')
- e.stopPropagation();
- };
-
- this.pageDiv.querySelector('.remove-all-cookies-button').onclick =
- function(e) {
- chrome.send('removeAllCookies');
- };
-
- var cookiesList = this.pageDiv.querySelector('.cookies-list');
- options.CookiesList.decorate(cookiesList);
-
- this.addEventListener('visibleChange', this.handleVisibleChange_);
-
- this.pageDiv.querySelector('.cookies-view-overlay-confirm').onclick =
- PageManager.closeOverlay.bind(PageManager);
- },
-
- /** @override */
- didShowPage: function() {
- this.pageDiv.querySelector('.cookies-search-box').value = '';
- this.lastQuery_ = '';
- },
-
- /**
- * Search cookie using text in |cookies-search-box|.
- */
- searchCookie: function() {
- this.queryDelayTimerId_ = 0;
- var filter = this.pageDiv.querySelector('.cookies-search-box').value;
- if (this.lastQuery_ != filter) {
- this.lastQuery_ = filter;
- chrome.send('updateCookieSearchResults', [filter]);
- }
- },
-
- /**
- * Handles search query changes.
- * @param {!Event} e The event object.
- * @private
- */
- handleSearchQueryChange_: function(e) {
- var stringId = document.querySelector('.cookies-search-box').value ?
- 'remove_all_shown_cookie' : 'remove_all_cookie';
- document.querySelector('.remove-all-cookies-button').innerHTML =
- loadTimeData.getString(stringId);
- if (this.queryDelayTimerId_)
- window.clearTimeout(this.queryDelayTimerId_);
-
- this.queryDelayTimerId_ = window.setTimeout(
- this.searchCookie.bind(this), 500);
- },
-
- initialized_: false,
-
- /**
- * Handler for Page's visible property change event.
- * @param {Event} e Property change event.
- * @private
- */
- handleVisibleChange_: function(e) {
- if (!this.visible)
- return;
-
- chrome.send('reloadCookies');
-
- if (!this.initialized_) {
- this.initialized_ = true;
- this.searchCookie();
- } else {
- this.pageDiv.querySelector('.cookies-list').redraw();
- }
-
- this.pageDiv.querySelector('.cookies-search-box').focus();
- },
- };
-
- // CookiesViewHandler callbacks.
- CookiesView.onTreeItemAdded = function(args) {
- $('cookies-list').addByParentId(args[0], args[1], args[2]);
- };
-
- CookiesView.onTreeItemRemoved = function(args) {
- $('cookies-list').removeByParentId(args[0], args[1], args[2]);
- };
-
- CookiesView.loadChildren = function(args) {
- $('cookies-list').loadChildren(args[0], args[1]);
- };
-
- // Export
- return {
- CookiesView: CookiesView
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/deletable_item_list.js b/chromium/chrome/browser/resources/options/deletable_item_list.js
deleted file mode 100644
index 57b684bfe3a..00000000000
--- a/chromium/chrome/browser/resources/options/deletable_item_list.js
+++ /dev/null
@@ -1,214 +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.
-
-cr.define('options', function() {
- /** @const */ var List = cr.ui.List;
- /** @const */ var ListItem = cr.ui.ListItem;
-
- /**
- * Creates a deletable list item, which has a button that will trigger a call
- * to deleteItemAtIndex(index) in the list.
- * @constructor
- * @extends {cr.ui.ListItem}
- */
- var DeletableItem = cr.ui.define('li');
-
- DeletableItem.prototype = {
- __proto__: ListItem.prototype,
-
- /**
- * The element subclasses should populate with content.
- * @type {HTMLElement}
- * @private
- */
- contentElement_: null,
-
- /**
- * The close button element.
- * @type {HTMLElement}
- * @private
- */
- closeButtonElement_: null,
-
- /**
- * Whether or not this item can be deleted.
- * @type {boolean}
- * @private
- */
- deletable_: true,
-
- /**
- * Whether or not the close button can ever be navigated to using the
- * keyboard.
- * @type {boolean}
- * @protected
- */
- closeButtonFocusAllowed: false,
-
- /** @override */
- decorate: function() {
- ListItem.prototype.decorate.call(this);
-
- this.classList.add('deletable-item');
-
- this.contentElement_ = /** @type {HTMLElement} */(
- this.ownerDocument.createElement('div'));
- this.appendChild(this.contentElement_);
-
- this.closeButtonElement_ = /** @type {HTMLElement} */(
- this.ownerDocument.createElement('button'));
- this.closeButtonElement_.className =
- 'raw-button row-delete-button custom-appearance';
- this.closeButtonElement_.addEventListener('mousedown',
- this.handleMouseDownUpOnClose_);
- this.closeButtonElement_.addEventListener('mouseup',
- this.handleMouseDownUpOnClose_);
- this.closeButtonElement_.addEventListener('focus',
- this.handleFocus.bind(this));
- this.closeButtonElement_.tabIndex = -1;
- this.closeButtonElement_.title =
- loadTimeData.getString('deletableItemDeleteButtonTitle');
- this.appendChild(this.closeButtonElement_);
- },
-
- /**
- * Returns the element subclasses should add content to.
- * @return {HTMLElement} The element subclasses should popuplate.
- */
- get contentElement() {
- return this.contentElement_;
- },
-
- /**
- * Returns the close button element.
- * @return {HTMLElement} The close |<button>| element.
- */
- get closeButtonElement() {
- return this.closeButtonElement_;
- },
-
- /* Gets/sets the deletable property. An item that is not deletable doesn't
- * show the delete button (although space is still reserved for it).
- */
- get deletable() {
- return this.deletable_;
- },
- set deletable(value) {
- this.deletable_ = value;
- this.closeButtonElement_.disabled = !value;
- },
-
- /**
- * Called when a focusable child element receives focus. Selects this item
- * in the list selection model.
- * @protected
- */
- handleFocus: function() {
- // This handler is also fired when the child receives focus as a result of
- // the item getting selected by the customized mouse/keyboard handling in
- // SelectionController. Take care not to destroy a potential multiple
- // selection in this case.
- if (this.selected)
- return;
-
- var list = this.parentNode;
- var index = list.getIndexOfListItem(this);
- list.selectionModel.selectedIndex = index;
- list.selectionModel.anchorIndex = index;
- },
-
- /**
- * Don't let the list have a crack at the event. We don't want clicking the
- * close button to change the selection of the list or to focus on the close
- * button.
- * @param {Event} e The mouse down/up event object.
- * @private
- */
- handleMouseDownUpOnClose_: function(e) {
- if (e.target.disabled)
- return;
- e.stopPropagation();
- e.preventDefault();
- },
- };
-
- /**
- * @constructor
- * @extends {cr.ui.List}
- */
- var DeletableItemList = cr.ui.define('list');
-
- DeletableItemList.prototype = {
- __proto__: List.prototype,
-
- /** @override */
- decorate: function() {
- List.prototype.decorate.call(this);
- this.addEventListener('click', this.handleClick);
- this.addEventListener('keydown', this.handleKeyDown_);
- },
-
- /**
- * Callback for onclick events.
- * @param {Event} e The click event object.
- * @protected
- */
- handleClick: function(e) {
- if (this.disabled)
- return;
-
- var target = e.target;
- if (target.classList.contains('row-delete-button')) {
- var listItem = this.getListItemAncestor(
- /** @type {HTMLElement} */(target));
- var idx = this.getIndexOfListItem(listItem);
- this.deleteItemAtIndex(idx);
- }
- },
-
- /**
- * Callback for keydown events.
- * @param {Event} e The keydown event object.
- * @private
- */
- handleKeyDown_: function(e) {
- // Map delete (and backspace on Mac) to item deletion (unless focus is
- // in an input field, where it's intended for text editing).
- if ((e.keyCode == 46 || (e.keyCode == 8 && cr.isMac)) &&
- e.target.tagName != 'INPUT') {
- this.deleteSelectedItems_();
- // Prevent the browser from going back.
- e.preventDefault();
- }
- },
-
- /**
- * Deletes all the currently selected items that are deletable.
- * @private
- */
- deleteSelectedItems_: function() {
- var selected = this.selectionModel.selectedIndexes;
- // Reverse through the list of selected indexes to maintain the
- // correct index values after deletion.
- for (var j = selected.length - 1; j >= 0; j--) {
- var index = selected[j];
- if (this.getListItemByIndex(index).deletable)
- this.deleteItemAtIndex(index);
- }
- },
-
- /**
- * Called when an item should be deleted; subclasses are responsible for
- * implementing.
- * @param {number} index The index of the item that is being deleted.
- */
- deleteItemAtIndex: function(index) {
- },
- };
-
- return {
- DeletableItemList: DeletableItemList,
- DeletableItem: DeletableItem,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.css b/chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.css
deleted file mode 100644
index 96950c10265..00000000000
--- a/chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.css
+++ /dev/null
@@ -1,7 +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. */
-
-#do-not-track-confirm-overlay {
- width: 500px;
-}
diff --git a/chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.html b/chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.html
deleted file mode 100644
index 311696822cb..00000000000
--- a/chromium/chrome/browser/resources/options/do_not_track_confirm_overlay.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<div id="do-not-track-confirm-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{doNotTrackConfirmOverlay}</h1>
- <div class="content-area">
- <span id="do-not-track-confirm-text">$i18n{doNotTrackConfirmMessage}</span>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a target="_blank"
- href="$i18nRaw{doNotTrackLearnMoreURL}">$i18n{learnMore}</a>
- </div>
- <div class="action-area-right">
- <div class="button-strip">
- <button id="do-not-track-confirm-cancel">
- $i18n{doNotTrackConfirmDisable}
- </button>
- <button id="do-not-track-confirm-ok" class="default-button">
- $i18n{doNotTrackConfirmEnable}
- </button>
- </div>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.css b/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.css
deleted file mode 100644
index 817db4b9aa6..00000000000
--- a/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.css
+++ /dev/null
@@ -1,7 +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. */
-
-#easy-unlock-turn-off-overlay {
- max-width: 480px;
-}
diff --git a/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.html b/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.html
deleted file mode 100644
index 8a2db2ed43a..00000000000
--- a/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<div id="easy-unlock-turn-off-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1 id="easy-unlock-turn-off-title">$i18n{easyUnlockTurnOffTitle}</h1>
- <div class="content-area">
- <p id="easy-unlock-turn-off-messagee" class="settings-row">
- $i18n{easyUnlockTurnOffDescription}
- </p>
- </div>
- <div class="action-area button-strip">
- <button id="easy-unlock-turn-off-dismiss">$i18n{cancel}</button>
- <button id="easy-unlock-turn-off-confirm" class="default-button">
- $i18n{easyUnlockTurnOffButton}
- </button>
- <div class="stretch"></div>
- <div id="easy-unlock-turn-off-spinner" class="spinner" hidden></div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.js b/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.js
deleted file mode 100644
index eb065df016a..00000000000
--- a/chromium/chrome/browser/resources/options/easy_unlock_turn_off_overlay.js
+++ /dev/null
@@ -1,193 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- // UI state of the turn off overlay.
- // @enum {string}
- var UIState = {
- UNKNOWN: 'unknown',
- OFFLINE: 'offline',
- IDLE: 'idle',
- PENDING: 'pending',
- SERVER_ERROR: 'server-error',
- };
-
- /**
- * EasyUnlockTurnOffOverlay class
- * Encapsulated handling of the Factory Reset confirmation overlay page.
- * @class
- */
- function EasyUnlockTurnOffOverlay() {
- Page.call(this, 'easyUnlockTurnOffOverlay',
- loadTimeData.getString('easyUnlockTurnOffTitle'),
- 'easy-unlock-turn-off-overlay');
- }
-
- cr.addSingletonGetter(EasyUnlockTurnOffOverlay);
-
- EasyUnlockTurnOffOverlay.prototype = {
- // Inherit EasyUnlockTurnOffOverlay from Page.
- __proto__: Page.prototype,
-
- /** Current UI state */
- uiState_: UIState.UNKNOWN,
- get uiState() {
- return this.uiState_;
- },
- set uiState(newUiState) {
- if (newUiState == this.uiState_)
- return;
-
- this.uiState_ = newUiState;
- switch (this.uiState_) {
- case UIState.OFFLINE:
- this.setUpOfflineUI_();
- break;
- case UIState.IDLE:
- this.setUpTurnOffUI_(false);
- break;
- case UIState.PENDING:
- this.setUpTurnOffUI_(true);
- break;
- case UIState.SERVER_ERROR:
- this.setUpServerErrorUI_();
- break;
- default:
- console.error('Unknow Easy unlock turn off UI state: ' +
- this.uiState_);
- this.setUpTurnOffUI_(false);
- break;
- }
- },
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('easy-unlock-turn-off-dismiss').onclick = function(event) {
- EasyUnlockTurnOffOverlay.dismiss();
- };
- $('easy-unlock-turn-off-confirm').onclick = function(event) {
- this.uiState = UIState.PENDING;
- chrome.send('easyUnlockRequestTurnOff');
- }.bind(this);
- },
-
- /** @override */
- didShowPage: function() {
- if (navigator.onLine) {
- this.uiState = UIState.IDLE;
- chrome.send('easyUnlockGetTurnOffFlowStatus');
- } else {
- this.uiState = UIState.OFFLINE;
- }
- },
-
- /** @override */
- didClosePage: function() {
- chrome.send('easyUnlockTurnOffOverlayDismissed');
- },
-
- /**
- * Returns the button strip element.
- * @return {HTMLDivElement} The container div of action buttons.
- */
- get buttonStrip() {
- return this.pageDiv.querySelector('.button-strip');
- },
-
- /**
- * Set visibility of action buttons in button strip.
- * @private
- */
- setActionButtonsVisible_: function(visible) {
- var buttons = this.buttonStrip.querySelectorAll('button');
- for (var i = 0; i < buttons.length; ++i) {
- buttons[i].hidden = !visible;
- }
- },
-
- /**
- * Set visibility of spinner.
- * @private
- */
- setSpinnerVisible_: function(visible) {
- $('easy-unlock-turn-off-spinner').hidden = !visible;
- },
-
- /**
- * Set up UI for showing offline message.
- * @private
- */
- setUpOfflineUI_: function() {
- $('easy-unlock-turn-off-title').textContent =
- loadTimeData.getString('easyUnlockTurnOffOfflineTitle');
- $('easy-unlock-turn-off-messagee').textContent =
- loadTimeData.getString('easyUnlockTurnOffOfflineMessage');
-
- this.setActionButtonsVisible_(false);
- this.setSpinnerVisible_(false);
- },
-
- /**
- * Set up UI for turning off Easy Unlock.
- * @param {boolean} pending Whether there is a pending turn-off call.
- * @private
- */
- setUpTurnOffUI_: function(pending) {
- $('easy-unlock-turn-off-title').textContent =
- loadTimeData.getString('easyUnlockTurnOffTitle');
- $('easy-unlock-turn-off-messagee').textContent =
- loadTimeData.getString('easyUnlockTurnOffDescription');
- $('easy-unlock-turn-off-confirm').textContent =
- loadTimeData.getString('easyUnlockTurnOffButton');
-
- this.setActionButtonsVisible_(true);
- this.setSpinnerVisible_(pending);
- $('easy-unlock-turn-off-confirm').disabled = pending;
- $('easy-unlock-turn-off-dismiss').hidden = false;
- },
-
- /**
- * Set up UI for showing server error.
- * @private
- */
- setUpServerErrorUI_: function() {
- $('easy-unlock-turn-off-title').textContent =
- loadTimeData.getString('easyUnlockTurnOffErrorTitle');
- $('easy-unlock-turn-off-messagee').textContent =
- loadTimeData.getString('easyUnlockTurnOffErrorMessage');
- $('easy-unlock-turn-off-confirm').textContent =
- loadTimeData.getString('easyUnlockTurnOffRetryButton');
-
- this.setActionButtonsVisible_(true);
- this.setSpinnerVisible_(false);
- $('easy-unlock-turn-off-confirm').disabled = false;
- $('easy-unlock-turn-off-dismiss').hidden = true;
- },
- };
-
- /**
- * Closes the Easy unlock turn off overlay.
- */
- EasyUnlockTurnOffOverlay.dismiss = function() {
- PageManager.closeOverlay();
- };
-
- /**
- * Update UI to reflect the turn off operation status.
- * @param {string} newState The UIState string representing the new state.
- */
- EasyUnlockTurnOffOverlay.updateUIState = function(newState) {
- EasyUnlockTurnOffOverlay.getInstance().uiState = newState;
- };
-
- // Export
- return {
- EasyUnlockTurnOffOverlay: EasyUnlockTurnOffOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/editable_text_field.js b/chromium/chrome/browser/resources/options/editable_text_field.js
deleted file mode 100644
index b895613007e..00000000000
--- a/chromium/chrome/browser/resources/options/editable_text_field.js
+++ /dev/null
@@ -1,372 +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.
-
-cr.define('options', function() {
- /**
- * @constructor
- * @extends {HTMLDivElement}
- */
- var EditableTextField = cr.ui.define('div');
-
- EditableTextField.prototype = {
- __proto__: HTMLDivElement.prototype,
-
- /**
- * The actual input element in this field.
- * @type {?HTMLElement}
- * @private
- */
- editField_: null,
-
- /**
- * The static text displayed when this field isn't editable.
- * @type {?HTMLElement}
- * @private
- */
- staticText_: null,
-
- /**
- * The data model for this field.
- * @type {?Object}
- * @private
- */
- model_: null,
-
- /**
- * Whether or not the current edit should be considered canceled, rather
- * than committed, when editing ends.
- * @type {boolean}
- * @private
- */
- editCanceled_: true,
-
- /** @protected */
- decorate: function() {
- this.classList.add('editable-text-field');
-
- this.createEditableTextCell('');
-
- if (this.hasAttribute('i18n-placeholder-text')) {
- var identifier = this.getAttribute('i18n-placeholder-text');
- var localizedText = loadTimeData.getString(identifier);
- if (localizedText)
- this.setAttribute('placeholder-text', localizedText);
- }
-
- this.addEventListener('keydown', this.handleKeyDown_);
- this.editField_.addEventListener('focus', this.handleFocus_.bind(this));
- this.editField_.addEventListener('blur', this.handleBlur_.bind(this));
- this.checkForEmpty_();
- },
-
- /**
- * Indicates that this field has no value in the model, and the placeholder
- * text (if any) should be shown.
- * @type {boolean}
- */
- get empty() {
- return this.hasAttribute('empty');
- },
-
- /**
- * The placeholder text to be used when the model or its value is empty.
- * @type {string}
- */
- get placeholderText() {
- return this.getAttribute('placeholder-text');
- },
- set placeholderText(text) {
- if (text)
- this.setAttribute('placeholder-text', text);
- else
- this.removeAttribute('placeholder-text');
-
- this.checkForEmpty_();
- },
-
- /**
- * Returns the input element in this text field.
- * @type {HTMLElement} The element that is the actual input field.
- */
- get editField() {
- return this.editField_;
- },
-
- /**
- * Whether the user is currently editing the list item.
- * @type {boolean}
- */
- get editing() {
- return this.hasAttribute('editing');
- },
- set editing(editing) {
- if (this.editing == editing)
- return;
-
- if (editing)
- this.setAttribute('editing', '');
- else
- this.removeAttribute('editing');
-
- if (editing) {
- this.editCanceled_ = false;
-
- if (this.empty) {
- this.removeAttribute('empty');
- if (this.editField)
- this.editField.value = '';
- }
- if (this.editField) {
- this.editField.focus();
- this.editField.select();
- }
- } else {
- if (!this.editCanceled_ && this.hasBeenEdited &&
- this.currentInputIsValid) {
- this.updateStaticValues_();
- cr.dispatchSimpleEvent(this, 'commitedit', true);
- } else {
- this.resetEditableValues_();
- cr.dispatchSimpleEvent(this, 'canceledit', true);
- }
- this.checkForEmpty_();
- }
- },
-
- /**
- * Whether the item is editable.
- * @type {boolean}
- */
- get editable() {
- return this.hasAttribute('editable');
- },
- set editable(editable) {
- if (this.editable == editable)
- return;
-
- if (editable)
- this.setAttribute('editable', '');
- else
- this.removeAttribute('editable');
- this.editable_ = editable;
- },
-
- /**
- * The data model for this field.
- * @type {Object}
- */
- get model() {
- return this.model_;
- },
- set model(model) {
- this.model_ = model;
- this.checkForEmpty_(); // This also updates the editField value.
- this.updateStaticValues_();
- },
-
- /**
- * The HTML element that should have focus initially when editing starts,
- * if a specific element wasn't clicked. Defaults to the first <input>
- * element; can be overridden by subclasses if a different element should be
- * focused.
- * @type {?HTMLElement}
- */
- get initialFocusElement() {
- return this.querySelector('input');
- },
-
- /**
- * Whether the input in currently valid to submit. If this returns false
- * when editing would be submitted, either editing will not be ended,
- * or it will be cancelled, depending on the context. Can be overridden by
- * subclasses to perform input validation.
- * @type {boolean}
- */
- get currentInputIsValid() {
- return true;
- },
-
- /**
- * Returns true if the item has been changed by an edit. Can be overridden
- * by subclasses to return false when nothing has changed to avoid
- * unnecessary commits.
- * @type {boolean}
- */
- get hasBeenEdited() {
- return true;
- },
-
- /**
- * Mutates the input during a successful commit. Can be overridden to
- * provide a way to "clean up" valid input so that it conforms to a
- * desired format. Will only be called when commit succeeds for valid
- * input, or when the model is set.
- * @param {string} value Input text to be mutated.
- * @return {string} mutated text.
- */
- mutateInput: function(value) {
- return value;
- },
-
- /**
- * Creates a div containing an <input>, as well as static text, keeping
- * references to them so they can be manipulated.
- * @param {string} text The text of the cell.
- * @private
- */
- createEditableTextCell: function(text) {
- // This function should only be called once.
- if (this.editField_)
- return;
-
- var container = this.ownerDocument.createElement('div');
-
- var textEl = /** @type {HTMLElement} */(
- this.ownerDocument.createElement('div'));
- textEl.className = 'static-text';
- textEl.textContent = text;
- textEl.setAttribute('displaymode', 'static');
- this.appendChild(textEl);
- this.staticText_ = textEl;
-
- var inputEl = /** @type {HTMLElement} */(
- this.ownerDocument.createElement('input'));
- inputEl.className = 'editable-text';
- inputEl.type = 'text';
- inputEl.value = text;
- inputEl.setAttribute('displaymode', 'edit');
- inputEl.staticVersion = textEl;
- this.appendChild(inputEl);
- this.editField_ = inputEl;
- },
-
- /**
- * Resets the editable version of any controls created by
- * createEditableTextCell to match the static text.
- * @private
- */
- resetEditableValues_: function() {
- var editField = this.editField_;
- var staticLabel = editField.staticVersion;
- if (!staticLabel)
- return;
-
- if (editField instanceof HTMLInputElement)
- editField.value = staticLabel.textContent;
-
- editField.setCustomValidity('');
- },
-
- /**
- * Sets the static version of any controls created by createEditableTextCell
- * to match the current value of the editable version. Called on commit so
- * that there's no flicker of the old value before the model updates. Also
- * updates the model's value with the mutated value of the edit field.
- * @private
- */
- updateStaticValues_: function() {
- var editField = this.editField_;
- var staticLabel = editField.staticVersion;
- if (!staticLabel)
- return;
-
- if (editField instanceof HTMLInputElement) {
- staticLabel.textContent = editField.value;
- this.model_.value = this.mutateInput(editField.value);
- }
- },
-
- /**
- * Checks to see if the model or its value are empty. If they are, then set
- * the edit field to the placeholder text, if any, and if not, set it to the
- * model's value.
- * @private
- */
- checkForEmpty_: function() {
- var editField = this.editField_;
- if (!editField)
- return;
-
- if (!this.model_ || !this.model_.value) {
- this.setAttribute('empty', '');
- editField.value = this.placeholderText || '';
- } else {
- this.removeAttribute('empty');
- editField.value = this.model_.value;
- }
- },
-
- /**
- * Called when this widget receives focus.
- * @param {Event} e the focus event.
- * @private
- */
- handleFocus_: function(e) {
- if (this.editing)
- return;
-
- this.editing = true;
- if (this.editField_)
- this.editField_.focus();
- },
-
- /**
- * Called when this widget loses focus.
- * @param {Event} e the blur event.
- * @private
- */
- handleBlur_: function(e) {
- if (!this.editing)
- return;
-
- this.editing = false;
- },
-
- /**
- * Called when a key is pressed. Handles committing and canceling edits.
- * @param {Event} e The key down event.
- * @private
- */
- handleKeyDown_: function(e) {
- if (!this.editing)
- return;
-
- var endEdit;
- switch (e.key) {
- case 'Escape':
- this.editCanceled_ = true;
- endEdit = true;
- break;
- case 'Enter':
- if (this.currentInputIsValid)
- endEdit = true;
- break;
- }
-
- if (endEdit) {
- // Blurring will trigger the edit to end.
- this.ownerDocument.activeElement.blur();
- // Make sure that handled keys aren't passed on and double-handled.
- // (e.g., esc shouldn't both cancel an edit and close a subpage)
- e.stopPropagation();
- }
- },
- };
-
- /**
- * Takes care of committing changes to EditableTextField items when the
- * window loses focus.
- */
- window.addEventListener('blur', function(e) {
- var itemAncestor = findAncestor(document.activeElement, function(node) {
- return node instanceof EditableTextField;
- });
- if (itemAncestor)
- document.activeElement.blur();
- });
-
- return {
- EditableTextField: EditableTextField,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/factory_reset_overlay.css b/chromium/chrome/browser/resources/options/factory_reset_overlay.css
deleted file mode 100644
index c7369e3fa50..00000000000
--- a/chromium/chrome/browser/resources/options/factory_reset_overlay.css
+++ /dev/null
@@ -1,7 +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. */
-
-#factory-reset-overlay {
- max-width: 550px;
-}
diff --git a/chromium/chrome/browser/resources/options/factory_reset_overlay.html b/chromium/chrome/browser/resources/options/factory_reset_overlay.html
deleted file mode 100644
index 3c0a0f0a27b..00000000000
--- a/chromium/chrome/browser/resources/options/factory_reset_overlay.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<div id="factory-reset-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{factoryResetHeading}</h1>
- <div class="content-area">
- <span>$i18n{factoryResetWarning}</span>
- <a href="$i18nRaw{factoryResetHelpUrl}"
- target="_blank">$i18n{errorLearnMore}</a>
- </div>
- <div class="action-area button-strip">
- <button id="factory-reset-data-dismiss">$i18n{cancel}</button>
- <button id="factory-reset-data-restart" class="default-button">
- $i18n{factoryResetDataRestart}
- </button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/factory_reset_overlay.js b/chromium/chrome/browser/resources/options/factory_reset_overlay.js
deleted file mode 100644
index 0a446488016..00000000000
--- a/chromium/chrome/browser/resources/options/factory_reset_overlay.js
+++ /dev/null
@@ -1,47 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * FactoryResetOverlay class
- * Encapsulated handling of the Factory Reset confirmation overlay page.
- * @class
- */
- function FactoryResetOverlay() {
- Page.call(this, 'factoryResetData',
- loadTimeData.getString('factoryResetTitle'),
- 'factory-reset-overlay');
- }
-
- cr.addSingletonGetter(FactoryResetOverlay);
-
- FactoryResetOverlay.prototype = {
- // Inherit FactoryResetOverlay from Page.
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('factory-reset-data-dismiss').onclick = function(event) {
- FactoryResetOverlay.dismiss();
- };
- $('factory-reset-data-restart').onclick = function(event) {
- chrome.send('performFactoryResetRestart');
- };
- },
- };
-
- FactoryResetOverlay.dismiss = function() {
- PageManager.closeOverlay();
- };
-
- // Export
- return {
- FactoryResetOverlay: FactoryResetOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/font_settings.css b/chromium/chrome/browser/resources/options/font_settings.css
deleted file mode 100644
index f999c586f2b..00000000000
--- a/chromium/chrome/browser/resources/options/font_settings.css
+++ /dev/null
@@ -1,62 +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. */
-
-#font-settings > section {
- overflow: hidden;
-}
-
-#font-settings .action-area {
- -webkit-box-pack: start;
-}
-
-#font-settings .action-area .spacer {
- -webkit-box-flex: 1;
- display: -webkit-box;
-}
-
-#font-settings .button-strip {
- width: 100%;
-}
-
-.font-setting-container {
- display: -webkit-box;
-}
-
-#font-settings input[type='range'] {
- width: 100%;
-}
-
-#minimum-font-sample {
- height: 35px;
- overflow: hidden;
- width: 270px;
-}
-
-.font-input-div {
- -webkit-margin-end: 3em;
- width: 12em;
-}
-
-.font-input-div > div > select {
- margin-bottom: 10px;
-}
-
-.font-input {
- width: 100%;
-}
-
-.font-sample-div {
- direction: ltr;
- height: 70px;
- overflow: hidden;
- width: 270px;
-}
-
-.font-settings-huge {
- float: right;
-}
-
-html[dir=rtl] .font-settings-huge {
- float: left;
-}
diff --git a/chromium/chrome/browser/resources/options/font_settings.html b/chromium/chrome/browser/resources/options/font_settings.html
deleted file mode 100644
index f22c3dc4287..00000000000
--- a/chromium/chrome/browser/resources/options/font_settings.html
+++ /dev/null
@@ -1,104 +0,0 @@
-<div id="font-settings" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{fontSettingsPage}</h1>
- <div class="content-area">
- <section>
- <h3>$i18n{fontSettingsStandard}</h3>
- <div class="font-setting-container">
- <div class="font-input-div">
- <div>
- <select id="standard-font-family" class="font-input"
- data-type="string" metric="Options_ChangeStandardFont"
- pref="webkit.webprefs.fonts.standard.Zyyy">
- </select>
- </div>
- <div>
- <input id="standard-font-size" type="range" min="0" max="24"
- pref="webkit.webprefs.default_font_size">
- <div>
- <span>$i18n{fontSettingsSizeTiny}</span>
- <span class="font-settings-huge">
- $i18n{fontSettingsSizeHuge}
- </span>
- </div>
- </div>
- </div>
- <div id="standard-font-sample" class="font-sample-div"></div>
- </div>
- </section>
- <section>
- <h3>$i18n{fontSettingsSerif}</h3>
- <div class="font-setting-container">
- <div class="font-input-div">
- <div>
- <select id="serif-font-family" class="font-input" data-type="string"
- pref="webkit.webprefs.fonts.serif.Zyyy"
- metric="Options_ChangeSerifFont">
- </select>
- </div>
- </div>
- <div id="serif-font-sample" class="font-sample-div"></div>
- </div>
- </section>
- <section>
- <h3>$i18n{fontSettingsSansSerif}</h3>
- <div class="font-setting-container">
- <div class="font-input-div">
- <div>
- <select id="sans-serif-font-family" class="font-input"
- data-type="string" metric="Options_ChangeSansSerifFont"
- pref="webkit.webprefs.fonts.sansserif.Zyyy">
- </select>
- </div>
- </div>
- <div id="sans-serif-font-sample" class="font-sample-div"></div>
- </div>
- </section>
- <section>
- <h3>$i18n{fontSettingsFixedWidth}</h3>
- <div class="font-setting-container">
- <div class="font-input-div">
- <div>
- <select id="fixed-font-family" class="font-input" data-type="string"
- pref="webkit.webprefs.fonts.fixed.Zyyy"
- metric="Options_ChangeFixedFont">
- </select>
- </div>
- </div>
- <div id="fixed-font-sample" class="font-sample-div"></div>
- </div>
- </section>
- <section>
- <h3>$i18n{fontSettingsMinimumSize}</h3>
- <div class="font-setting-container">
- <div class="font-input-div">
- <div>
- <input id="minimum-font-size" type="range" min="0" max="15"
- pref="webkit.webprefs.minimum_font_size">
- <div>
- <span>$i18n{fontSettingsSizeTiny}</span>
- <span class="font-settings-huge">
- $i18n{fontSettingsSizeHuge}
- </span>
- </div>
- </div>
- </div>
- <div id="minimum-font-sample" class="font-sample-div"></div>
- </div>
- </section>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <span id="advanced-font-settings-install" hidden>
- $i18nRaw{advancedFontSettingsInstall}
- </span>
- <a is="action-link" id="advanced-font-settings-options" hidden>
- $i18n{advancedFontSettingsOptions}
- </a>
- <span class="spacer"></span>
- <button id="font-settings-confirm" class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/font_settings.js b/chromium/chrome/browser/resources/options/font_settings.js
deleted file mode 100644
index 74be53dfcca..00000000000
--- a/chromium/chrome/browser/resources/options/font_settings.js
+++ /dev/null
@@ -1,252 +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.
-
-cr.define('options', function() {
-
- var OptionsPage = options.OptionsPage;
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * FontSettings class
- * Encapsulated handling of the 'Fonts' page.
- * @class
- */
- function FontSettings() {
- Page.call(this, 'fonts',
- loadTimeData.getString('fontSettingsPageTabTitle'),
- 'font-settings');
- }
-
- cr.addSingletonGetter(FontSettings);
-
- FontSettings.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var standardFontRange = $('standard-font-size');
- standardFontRange.valueMap = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20,
- 22, 24, 26, 28, 30, 32, 34, 36, 40, 44, 48, 56, 64, 72];
- standardFontRange.addEventListener(
- 'change', this.standardRangeChanged_.bind(this, standardFontRange));
- standardFontRange.addEventListener(
- 'input', this.standardRangeChanged_.bind(this, standardFontRange));
- standardFontRange.customChangeHandler =
- this.standardFontSizeChanged_.bind(standardFontRange);
-
- var minimumFontRange = $('minimum-font-size');
- minimumFontRange.valueMap = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
- 18, 20, 22, 24];
- minimumFontRange.addEventListener(
- 'change', this.minimumRangeChanged_.bind(this, minimumFontRange));
- minimumFontRange.addEventListener(
- 'input', this.minimumRangeChanged_.bind(this, minimumFontRange));
- minimumFontRange.customChangeHandler =
- this.minimumFontSizeChanged_.bind(minimumFontRange);
-
- var placeholder = loadTimeData.getString('fontSettingsPlaceholder');
- var elements = [$('standard-font-family'), $('serif-font-family'),
- $('sans-serif-font-family'), $('fixed-font-family')];
- elements.forEach(function(el) {
- el.appendChild(new Option(placeholder));
- el.setDisabled('noFontsAvailable', true);
- });
-
- $('font-settings-confirm').onclick = function() {
- PageManager.closeOverlay();
- };
-
- $('advanced-font-settings-options').onclick = function() {
- chrome.send('openAdvancedFontSettingsOptions');
- };
- },
-
- /** @override */
- didShowPage: function() {
- // The fonts list may be large so we only load it when this page is
- // loaded for the first time. This makes opening the options window
- // faster and consume less memory if the user never opens the fonts
- // dialog.
- if (!this.hasShown) {
- chrome.send('fetchFontsData');
- this.hasShown = true;
- }
- },
-
- /**
- * Handler that is called when the user changes the position of the standard
- * font size slider. This allows the UI to show a preview of the change
- * before the slider has been released and the associated prefs updated.
- * @param {Element} el The slider input element.
- * @param {Event} event Change event.
- * @private
- */
- standardRangeChanged_: function(el, event) {
- var size = el.mapPositionToPref(el.value);
- var fontSampleEl = $('standard-font-sample');
- this.setUpFontSample_(fontSampleEl, size, fontSampleEl.style.fontFamily,
- true);
-
- fontSampleEl = $('serif-font-sample');
- this.setUpFontSample_(fontSampleEl, size, fontSampleEl.style.fontFamily,
- true);
-
- fontSampleEl = $('sans-serif-font-sample');
- this.setUpFontSample_(fontSampleEl, size, fontSampleEl.style.fontFamily,
- true);
-
- fontSampleEl = $('fixed-font-sample');
- this.setUpFontSample_(fontSampleEl,
- size - OptionsPage.SIZE_DIFFERENCE_FIXED_STANDARD,
- fontSampleEl.style.fontFamily, false);
- },
-
- /**
- * Sets the 'default_fixed_font_size' preference when the user changes the
- * standard font size.
- * @param {Event} event Change event.
- * @private
- */
- standardFontSizeChanged_: function(event) {
- var size = this.mapPositionToPref(this.value);
- Preferences.setIntegerPref(
- 'webkit.webprefs.default_fixed_font_size',
- size - OptionsPage.SIZE_DIFFERENCE_FIXED_STANDARD, true);
- return false;
- },
-
- /**
- * Handler that is called when the user changes the position of the minimum
- * font size slider. This allows the UI to show a preview of the change
- * before the slider has been released and the associated prefs updated.
- * @param {Element} el The slider input element.
- * @param {Event} event Change event.
- * @private
- */
- minimumRangeChanged_: function(el, event) {
- var size = el.mapPositionToPref(el.value);
- var fontSampleEl = $('minimum-font-sample');
- this.setUpFontSample_(fontSampleEl, size, fontSampleEl.style.fontFamily,
- true);
- },
-
- /**
- * Sets the 'minimum_logical_font_size' preference when the user changes the
- * minimum font size.
- * @param {Event} event Change event.
- * @private
- */
- minimumFontSizeChanged_: function(event) {
- var size = this.mapPositionToPref(this.value);
- Preferences.setIntegerPref(
- 'webkit.webprefs.minimum_logical_font_size', size, true);
- return false;
- },
-
- /**
- * Sets the text, font size and font family of the sample text.
- * @param {Element} el The div containing the sample text.
- * @param {number} size The font size of the sample text.
- * @param {string} font The font family of the sample text.
- * @param {boolean} showSize True if the font size should appear in the
- * sample.
- * @private
- */
- setUpFontSample_: function(el, size, font, showSize) {
- var prefix = showSize ? (size + ': ') : '';
- el.textContent = prefix +
- loadTimeData.getString('fontSettingsLoremIpsum');
- el.style.fontSize = size + 'px';
- if (font)
- el.style.fontFamily = font;
- },
-
- /**
- * Populates a select list and selects the specified item.
- * @param {Element} element The select element to populate.
- * @param {Array} items The array of items from which to populate.
- * @param {string} selectedValue The selected item.
- * @private
- */
- populateSelect_: function(element, items, selectedValue) {
- // Remove any existing content.
- element.textContent = '';
-
- // Insert new child nodes into select element.
- for (var i = 0; i < items.length; i++) {
- var value = items[i][0];
- var text = items[i][1];
- var dir = items[i][2];
- if (text) {
- var selected = value == selectedValue;
- var option = new Option(text, value, false, selected);
- option.dir = dir;
- element.appendChild(option);
- } else {
- element.appendChild(document.createElement('hr'));
- }
- }
-
- element.setDisabled('noFontsAvailable', false);
- }
- };
-
- // Chrome callbacks
- FontSettings.setFontsData = function(fonts, selectedValues) {
- FontSettings.getInstance().populateSelect_($('standard-font-family'), fonts,
- selectedValues[0]);
- FontSettings.getInstance().populateSelect_($('serif-font-family'), fonts,
- selectedValues[1]);
- FontSettings.getInstance().populateSelect_($('sans-serif-font-family'),
- fonts, selectedValues[2]);
- FontSettings.getInstance().populateSelect_($('fixed-font-family'), fonts,
- selectedValues[3]);
- };
-
- FontSettings.setUpStandardFontSample = function(font, size) {
- FontSettings.getInstance().setUpFontSample_($('standard-font-sample'), size,
- font, true);
- };
-
- FontSettings.setUpSerifFontSample = function(font, size) {
- FontSettings.getInstance().setUpFontSample_($('serif-font-sample'), size,
- font, true);
- };
-
- FontSettings.setUpSansSerifFontSample = function(font, size) {
- FontSettings.getInstance().setUpFontSample_($('sans-serif-font-sample'),
- size, font, true);
- };
-
- FontSettings.setUpFixedFontSample = function(font, size) {
- FontSettings.getInstance().setUpFontSample_($('fixed-font-sample'),
- size, font, false);
- };
-
- FontSettings.setUpMinimumFontSample = function(size) {
- // If size is less than 6, represent it as six in the sample to account
- // for the minimum logical font size.
- if (size < 6)
- size = 6;
- FontSettings.getInstance().setUpFontSample_($('minimum-font-sample'), size,
- null, true);
- };
-
- /**
- * @param {boolean} available Whether the Advanced Font Settings Extension
- * is installed and enabled.
- */
- FontSettings.notifyAdvancedFontSettingsAvailability = function(available) {
- $('advanced-font-settings-install').hidden = available;
- $('advanced-font-settings-options').hidden = !available;
- };
-
- // Export
- return {
- FontSettings: FontSettings
- };
-});
diff --git a/chromium/chrome/browser/resources/options/geolocation_options.js b/chromium/chrome/browser/resources/options/geolocation_options.js
deleted file mode 100644
index 30071df3912..00000000000
--- a/chromium/chrome/browser/resources/options/geolocation_options.js
+++ /dev/null
@@ -1,33 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
-
- /**
- * GeolocationOptions class
- * Handles initialization of the geolocation options.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function GeolocationOptions() {
- Page.call(this, 'geolocationOptions',
- loadTimeData.getString('geolocationOptionsPageTabTitle'),
- 'geolocationCheckbox');
- }
-
- cr.addSingletonGetter(GeolocationOptions);
-
- GeolocationOptions.prototype = {
- __proto__: Page.prototype
- };
-
- // TODO(robliao): Determine if a full unroll is necessary
- // (http://crbug.com/306613).
- GeolocationOptions.showGeolocationOption = function() {};
-
- return {
- GeolocationOptions: GeolocationOptions
- };
-});
diff --git a/chromium/chrome/browser/resources/options/googleg.svg b/chromium/chrome/browser/resources/options/googleg.svg
deleted file mode 100644
index 7a1ad34425d..00000000000
--- a/chromium/chrome/browser/resources/options/googleg.svg
+++ /dev/null
@@ -1,7 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 16 16">
- <path fill="#4285F4" d="M14.72 8.16c0-.46-.05-.81-.11-1.16H8v2.4h3.97c-.1.62-.52 1.59-1.45 2.26v1.64h2.12c1.32-1.21 2.08-3.01 2.08-5.14z"/>
- <path fill="#34A853" d="M8 15c1.89 0 3.47-.63 4.63-1.69l-2.12-1.64c-.6.43-1.42.75-2.51.75-1.89 0-3.48-1.24-4.08-2.96H1.75v1.69C2.9 13.43 5.26 15 8 15z"/>
- <path fill="#FBBC05" d="M3.92 9.45C3.77 9 3.66 8.51 3.66 8s.1-1 .26-1.45V4.86H1.75C1.27 5.81 1 6.87 1 8s.27 2.19.75 3.14l2.17-1.69z"/>
- <path fill="#EA4335" d="M8 3.58c1.36 0 2.27.58 2.79 1.08l1.9-1.83C11.47 1.69 9.89 1 8 1 5.26 1 2.9 2.57 1.75 4.86l2.17 1.69C4.52 4.83 6.11 3.58 8 3.58z"/>
- <path fill="none" d="M1 1h14v14H1z"/>
-</svg>
diff --git a/chromium/chrome/browser/resources/options/handler_options.css b/chromium/chrome/browser/resources/options/handler_options.css
deleted file mode 100644
index a022d975a94..00000000000
--- a/chromium/chrome/browser/resources/options/handler_options.css
+++ /dev/null
@@ -1,55 +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. */
-
-.handlers-column-headers {
- display: -webkit-box;
- font-size: 13px;
- font-weight: bold;
-}
-
-.handlers-type-column {
- -webkit-margin-end: 10px;
- -webkit-margin-start: 14px;
- width: 100px;
-}
-
-.handlers-site-column {
- max-width: 180px;
-}
-
-.handlers-site-column select {
- max-width: 170px;
-}
-
-.handlers-remove-column {
- -webkit-box-flex: 1;
-}
-
-.handlers-remove-link {
- color: #555;
- cursor: pointer;
- opacity: 0;
- padding-left: 14px;
- text-decoration: underline;
- transition: 150ms opacity;
-}
-
-div > .handlers-remove-column {
- opacity: 0;
-}
-
-div:not(.none):hover > .handlers-remove-column {
- opacity: 1;
-}
-
-#handlers {
- min-height: 250px;
-}
-
-#handler-options list {
- border: solid 1px #D9D9D9;
- border-radius: 2px;
- margin-bottom: 10px;
- margin-top: 4px;
-}
diff --git a/chromium/chrome/browser/resources/options/handler_options.html b/chromium/chrome/browser/resources/options/handler_options.html
deleted file mode 100644
index fb4f576e2d8..00000000000
--- a/chromium/chrome/browser/resources/options/handler_options.html
+++ /dev/null
@@ -1,44 +0,0 @@
-<div id="handler-options" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{handlersPage}</h1>
- <div class="content-area">
- <h3>$i18n{handlersActiveHeading}</h3>
- <div class="handlers-column-headers">
- <div class="handlers-type-column">
- <div>$i18n{handlersTypeColumnHeader}</div>
- </div>
- <div class="handlers-site-column">
- <div>$i18n{handlersSiteColumnHeader}</div>
- </div>
- <div class="handlers-remove-column"></div>
- </div>
- <list id="handlers-list"></list>
-
- <div id="ignored-handlers-section">
- <h3>$i18n{handlersIgnoredHeading}</h3>
- <div class="handlers-column-headers">
- <div class="handlers-type-column">
- <h3>$i18n{handlersTypeColumnHeader}</h3>
- </div>
- <div class="handlers-site-column">
- <h3>$i18n{handlersSiteColumnHeader}</h3>
- </div>
- <div class="handlers-remove-column"></div>
- </div>
- <list id="ignored-handlers-list"></list>
- </div>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a target="_blank"
- href="$i18nRaw{handlersLearnMoreUrl}">$i18n{learnMore}</a>
- </div>
- <div class="action-area-right">
- <div class="button-strip">
- <button id="handler-options-overlay-confirm" class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/handler_options.js b/chromium/chrome/browser/resources/options/handler_options.js
deleted file mode 100644
index a01261f199f..00000000000
--- a/chromium/chrome/browser/resources/options/handler_options.js
+++ /dev/null
@@ -1,97 +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.
-
-/**
- * @typedef {{
- * default_handler: number,
- * handlers: Array,
- * has_policy_recommendations: boolean,
- * is_default_handler_set_by_user: boolean,
- * protocol: string
- * }}
- * @see chrome/browser/ui/webui/options/handler_options_handler.cc
- */
-var Handlers;
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /////////////////////////////////////////////////////////////////////////////
- // HandlerOptions class:
-
- /**
- * Encapsulated handling of handler options page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function HandlerOptions() {
- this.activeNavTab = null;
- Page.call(this,
- 'handlers',
- loadTimeData.getString('handlersPageTabTitle'),
- 'handler-options');
- }
-
- cr.addSingletonGetter(HandlerOptions);
-
- HandlerOptions.prototype = {
- __proto__: Page.prototype,
-
- /**
- * The handlers list.
- * @type {options.HandlersList}
- * @private
- */
- handlersList_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- this.createHandlersList_();
-
- $('handler-options-overlay-confirm').onclick =
- PageManager.closeOverlay.bind(PageManager);
- },
-
- /**
- * Creates, decorates and initializes the handlers list.
- * @private
- */
- createHandlersList_: function() {
- var handlersList = $('handlers-list');
- options.HandlersList.decorate(handlersList);
- this.handlersList_ = assertInstanceof(handlersList, options.HandlersList);
- this.handlersList_.autoExpands = true;
-
- var ignoredHandlersList = $('ignored-handlers-list');
- options.IgnoredHandlersList.decorate(ignoredHandlersList);
- this.ignoredHandlersList_ = assertInstanceof(ignoredHandlersList,
- options.IgnoredHandlersList);
- this.ignoredHandlersList_.autoExpands = true;
- },
- };
-
- /**
- * Sets the list of handlers shown by the view.
- * @param {Array<Handlers>} handlers Handlers to be shown in the view.
- */
- HandlerOptions.setHandlers = function(handlers) {
- $('handlers-list').setHandlers(handlers);
- };
-
- /**
- * Sets the list of ignored handlers shown by the view.
- * @param {Array} handlers Handlers to be shown in the view.
- */
- HandlerOptions.setIgnoredHandlers = function(handlers) {
- $('ignored-handlers-section').hidden = handlers.length == 0;
- $('ignored-handlers-list').setHandlers(handlers);
- };
-
- return {
- HandlerOptions: HandlerOptions
- };
-});
diff --git a/chromium/chrome/browser/resources/options/handler_options_list.js b/chromium/chrome/browser/resources/options/handler_options_list.js
deleted file mode 100644
index 283e21b12c1..00000000000
--- a/chromium/chrome/browser/resources/options/handler_options_list.js
+++ /dev/null
@@ -1,268 +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.
-
-cr.define('options', function() {
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
- /** @const */ var List = cr.ui.List;
- /** @const */ var ListItem = cr.ui.ListItem;
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var DeletableItemList = options.DeletableItemList;
-
- /**
- * Creates a new ignored protocol / content handler list item.
- *
- * Accepts values in the form
- * ['mailto', 'http://www.thesite.com/%s', 'www.thesite.com'],
- * @param {Object} entry A dictionary describing the handlers for a given
- * protocol.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function IgnoredHandlersListItem(entry) {
- var el = cr.doc.createElement('div');
- el.dataItem = entry;
- el.__proto__ = IgnoredHandlersListItem.prototype;
- el.decorate();
- return el;
- }
-
- IgnoredHandlersListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- // Protocol.
- var protocolElement = document.createElement('div');
- protocolElement.textContent = this.dataItem[0];
- protocolElement.className = 'handlers-type-column';
- this.contentElement_.appendChild(protocolElement);
-
- // Host name.
- var hostElement = document.createElement('div');
- hostElement.textContent = this.dataItem[2];
- hostElement.className = 'handlers-site-column';
- hostElement.title = this.dataItem[1];
- this.contentElement_.appendChild(hostElement);
- },
- };
-
- /**
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var IgnoredHandlersList = cr.ui.define('list');
-
- IgnoredHandlersList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- /**
- * @override
- * @param {Object} entry
- */
- createItem: function(entry) {
- return new IgnoredHandlersListItem(entry);
- },
-
- deleteItemAtIndex: function(index) {
- chrome.send('removeIgnoredHandler', [this.dataModel.item(index)]);
- },
-
- /**
- * The length of the list.
- */
- get length() {
- return this.dataModel.length;
- },
-
- /**
- * Set the protocol handlers displayed by this list. See
- * IgnoredHandlersListItem for an example of the format the list should
- * take.
- *
- * @param {!Array} list A list of ignored protocol handlers.
- */
- setHandlers: function(list) {
- this.dataModel = new ArrayDataModel(list);
- },
- };
-
- /**
- * Creates a new protocol / content handler list item.
- *
- * Accepts values in the form
- * { protocol: 'mailto',
- * handlers: [
- * ['mailto', 'http://www.thesite.com/%s', 'www.thesite.com'],
- * ...,
- * ],
- * }
- * @param {Object} entry A dictionary describing the handlers for a given
- * protocol.
- * @constructor
- * @extends {cr.ui.ListItem}
- */
- function HandlerListItem(entry) {
- var el = cr.doc.createElement('div');
- el.dataItem = entry;
- el.__proto__ = HandlerListItem.prototype;
- el.decorate();
- return el;
- }
-
- HandlerListItem.prototype = {
- __proto__: ListItem.prototype,
-
- /**
- * @param {Handlers} data
- * @param {{removeHandler: Function, setDefault: Function,
- * clearDefault: Function}} delegate
- */
- buildWidget_: function(data, delegate) {
- // Protocol.
- var protocolElement = document.createElement('div');
- protocolElement.textContent = data.protocol;
- protocolElement.className = 'handlers-type-column';
- this.appendChild(protocolElement);
-
- // Handler selection.
- var handlerElement = document.createElement('div');
- var selectElement = document.createElement('select');
- var defaultOptionElement = document.createElement('option');
- defaultOptionElement.selected = data.default_handler == -1;
- defaultOptionElement.textContent =
- loadTimeData.getString('handlersNoneHandler');
- defaultOptionElement.value = -1;
- selectElement.appendChild(defaultOptionElement);
-
- for (var i = 0; i < data.handlers.length; ++i) {
- var optionElement = document.createElement('option');
- optionElement.selected = i == data.default_handler;
- optionElement.textContent = data.handlers[i][2];
- optionElement.value = i;
- selectElement.appendChild(optionElement);
- }
-
- selectElement.addEventListener('change', function(e) {
- var index = e.target.value;
- if (index == -1) {
- this.classList.add('none');
- delegate.clearDefault(data.protocol);
- } else {
- handlerElement.classList.remove('none');
- delegate.setDefault(data.handlers[index]);
- }
- });
- handlerElement.appendChild(selectElement);
- handlerElement.className = 'handlers-site-column';
- if (data.default_handler == -1)
- this.classList.add('none');
- this.appendChild(handlerElement);
-
- if (data.has_policy_recommendations) {
- // Create an indicator to show that the handler has policy
- // recommendations.
- var indicator = new options.ControlledSettingIndicator();
- if (data.is_default_handler_set_by_user || data.default_handler == -1) {
- // The default handler is registered by the user or set to none, which
- // indicates that the user setting has overridden a policy
- // recommendation. Show the appropriate bubble.
- indicator.controlledBy = 'hasRecommendation';
- indicator.resetHandler = function() {
- // If there is a policy recommendation, data.handlers.length >= 1.
- // Setting the default handler to 0 ensures that it won't be 'none',
- // and there *is* a user registered handler created by setDefault,
- // which is required for a change notification.
- // The user-registered handlers are removed in a loop. Note that if
- // a handler is installed by policy, removeHandler does nothing.
- delegate.setDefault(data.handlers[0]);
- for (var i = 0; i < data.handlers.length; ++i) {
- delegate.removeHandler(i, data.handlers[i]);
- }
- };
- } else {
- indicator.controlledBy = 'recommended';
- }
- this.appendChild(indicator);
- }
-
- if (data.is_default_handler_set_by_user) {
- // Remove link.
- var removeElement = document.createElement('div');
- removeElement.textContent =
- loadTimeData.getString('handlersRemoveLink');
- removeElement.addEventListener('click', function(e) {
- var value = selectElement ? selectElement.value : 0;
- delegate.removeHandler(value, data.handlers[value]);
- });
- removeElement.className =
- 'handlers-remove-column handlers-remove-link';
- this.appendChild(removeElement);
- }
- },
-
- /** @override */
- decorate: function() {
- ListItem.prototype.decorate.call(this);
-
- var delegate = {
- removeHandler: function(index, handler) {
- chrome.send('removeHandler', [handler]);
- },
- setDefault: function(handler) {
- chrome.send('setDefault', [handler]);
- },
- clearDefault: function(protocol) {
- chrome.send('clearDefault', [protocol]);
- },
- };
-
- this.buildWidget_(this.dataItem, delegate);
- },
- };
-
- /**
- * Create a new passwords list.
- * @constructor
- * @extends {cr.ui.List}
- */
- var HandlersList = cr.ui.define('list');
-
- HandlersList.prototype = {
- __proto__: List.prototype,
-
- /**
- * @override
- * @param {Object} entry
- */
- createItem: function(entry) {
- return new HandlerListItem(entry);
- },
-
- /**
- * The length of the list.
- */
- get length() {
- return this.dataModel.length;
- },
-
- /**
- * Set the protocol handlers displayed by this list.
- * See HandlerListItem for an example of the format the list should take.
- *
- * @param {!Array} list A list of protocols with their registered handlers.
- */
- setHandlers: function(list) {
- this.dataModel = new ArrayDataModel(list);
- },
- };
-
- return {
- IgnoredHandlersListItem: IgnoredHandlersListItem,
- IgnoredHandlersList: IgnoredHandlersList,
- HandlerListItem: HandlerListItem,
- HandlersList: HandlersList,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/home_page_overlay.html b/chromium/chrome/browser/resources/options/home_page_overlay.html
deleted file mode 100644
index d73b0f5b113..00000000000
--- a/chromium/chrome/browser/resources/options/home_page_overlay.html
+++ /dev/null
@@ -1,45 +0,0 @@
-<div id="home-page-overlay" class="page" role="dialog" hidden>
- <div class="close-button"></div>
- <h1>$i18n{homePageOverlay}</h1>
- <div class="content-area">
- <div class="radio controlled-setting-with-label">
- <label>
- <input id="homepage-use-ntp" type="radio" name="homepage"
- pref="homepage_is_newtabpage" value="true"
- metric="Options_Homepage_IsNewTabPage" dialog-pref>
- <span>
- <span>$i18n{homePageUseNewTab}</span>
- <span class="controlled-setting-indicator"
- pref="homepage_is_newtabpage" value="true" dialog-pref></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label class="option-name">
- <input id="homepage-use-url" type="radio" name="homepage"
- pref="homepage_is_newtabpage" value="false"
- metric="Options_Homepage_IsNewTabPage" dialog-pref>
- <span>
- <span id="homepage-use-url-label">$i18n{homePageUseURL}</span>
- <span class="controlled-setting-indicator"
- pref="homepage_is_newtabpage" value="false" dialog-pref></span>
- </span>
- </label>
- <input id="homepage-url-field" type="url" data-type="url"
- class="weakrtl favicon-cell stretch" pref="homepage"
- aria-labelledby="homepage-use-url-label"
- metric="Options_Homepage_URL" dialog-pref>
- </input>
- <span id="homepage-url-field-indicator"
- class="controlled-setting-indicator" pref="homepage"
- dialog-pref>
- </span>
- </div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="home-page-cancel" type="reset">$i18n{cancel}</button>
- <button id="home-page-confirm" class="default-button">$i18n{ok}</button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/home_page_overlay.js b/chromium/chrome/browser/resources/options/home_page_overlay.js
deleted file mode 100644
index d4b1b8f3261..00000000000
--- a/chromium/chrome/browser/resources/options/home_page_overlay.js
+++ /dev/null
@@ -1,154 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var SettingsDialog = options.SettingsDialog;
-
- /**
- * HomePageOverlay class
- * Dialog that allows users to set the home page.
- * @constructor
- * @extends {options.SettingsDialog}
- */
- function HomePageOverlay() {
- SettingsDialog.call(this, 'homePageOverlay',
- loadTimeData.getString('homePageOverlayTabTitle'),
- 'home-page-overlay',
- assertInstanceof($('home-page-confirm'), HTMLButtonElement),
- assertInstanceof($('home-page-cancel'), HTMLButtonElement));
- }
-
- cr.addSingletonGetter(HomePageOverlay);
-
- HomePageOverlay.prototype = {
- __proto__: SettingsDialog.prototype,
-
- /**
- * An autocomplete list that can be attached to the home page URL field.
- * @type {cr.ui.AutocompleteList}
- * @private
- */
- autocompleteList_: null,
-
- /** @override */
- initializePage: function() {
- SettingsDialog.prototype.initializePage.call(this);
-
- var self = this;
- options.Preferences.getInstance().addEventListener(
- 'homepage_is_newtabpage',
- this.handleHomepageIsNTPPrefChange.bind(this));
-
- var urlField = $('homepage-url-field');
- urlField.addEventListener('keydown', function(event) {
- // Don't auto-submit when the user selects something from the
- // auto-complete list.
- if (event.key == 'Enter' && !self.autocompleteList_.hidden)
- event.stopPropagation();
- });
- urlField.addEventListener('change', this.updateFavicon_.bind(this));
-
- var suggestionList = new cr.ui.AutocompleteList();
- suggestionList.autoExpands = true;
- suggestionList.requestSuggestions =
- this.requestAutocompleteSuggestions_.bind(this);
- $('home-page-overlay').appendChild(suggestionList);
- this.autocompleteList_ = suggestionList;
-
- urlField.addEventListener('focus', function(event) {
- self.autocompleteList_.attachToInput(urlField);
- });
- urlField.addEventListener('blur', function(event) {
- self.autocompleteList_.detach();
- });
- },
-
- /** @override */
- didShowPage: function() {
- this.updateFavicon_();
- },
-
- /**
- * Updates the state of the homepage text input and its controlled setting
- * indicator when the |homepage_is_newtabpage| pref changes. The input is
- * enabled only if the homepage is not the NTP. The indicator is always
- * enabled but treats the input's value as read-only if the homepage is the
- * NTP.
- * @param {Event} event Pref change event.
- */
- handleHomepageIsNTPPrefChange: function(event) {
- var urlField = $('homepage-url-field');
- var urlFieldIndicator = $('homepage-url-field-indicator');
- urlField.setDisabled('homepage-is-ntp', event.value.value);
- urlFieldIndicator.readOnly = event.value.value;
- },
-
- /**
- * Updates the background of the url field to show the favicon for the
- * URL that is currently typed in.
- * @private
- */
- updateFavicon_: function() {
- var urlField = $('homepage-url-field');
- urlField.style.backgroundImage = cr.icon.getFavicon(urlField.value);
- },
-
- /**
- * Sends an asynchronous request for new autocompletion suggestions for the
- * the given query. When new suggestions are available, the C++ handler will
- * call updateAutocompleteSuggestions_.
- * @param {string} query List of autocomplete suggestions.
- * @private
- */
- requestAutocompleteSuggestions_: function(query) {
- chrome.send('requestAutocompleteSuggestionsForHomePage', [query]);
- },
-
- /**
- * Updates the autocomplete suggestion list with the given entries.
- * @param {Array} suggestions List of autocomplete suggestions.
- * @private
- */
- updateAutocompleteSuggestions_: function(suggestions) {
- var list = this.autocompleteList_;
- // If the trigger for this update was a value being selected from the
- // current list, do nothing.
- if (list.targetInput && list.selectedItem &&
- list.selectedItem.url == list.targetInput.value) {
- return;
- }
- list.suggestions = suggestions;
- },
-
- /**
- * Sets the 'show home button' and 'home page is new tab page' preferences.
- * (The home page url preference is set automatically by the SettingsDialog
- * code.)
- */
- handleConfirm: function() {
- // Strip whitespace.
- var urlField = $('homepage-url-field');
- var homePageValue = urlField.value.replace(/\s*/g, '');
- urlField.value = homePageValue;
-
- // Don't save an empty URL for the home page. If the user left the field
- // empty, switch to the New Tab page.
- if (!homePageValue)
- $('homepage-use-ntp').checked = true;
-
- SettingsDialog.prototype.handleConfirm.call(this);
- },
- };
-
- HomePageOverlay.updateAutocompleteSuggestions = function() {
- var instance = HomePageOverlay.getInstance();
- instance.updateAutocompleteSuggestions_.apply(instance, arguments);
- };
-
- // Export
- return {
- HomePageOverlay: HomePageOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/hotword_confirm_dialog.js b/chromium/chrome/browser/resources/options/hotword_confirm_dialog.js
deleted file mode 100644
index a14d1fe9296..00000000000
--- a/chromium/chrome/browser/resources/options/hotword_confirm_dialog.js
+++ /dev/null
@@ -1,81 +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.
-
-cr.define('options', function() {
- /** @const */ var ConfirmDialog = options.ConfirmDialog;
- /** @const */ var SettingsDialog = options.SettingsDialog;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * A dialog that will pop up when the user attempts to set the value of the
- * Boolean |pref| to |true|, asking for confirmation. It will first check for
- * any errors and if any exist, not display the dialog but toggle the
- * indicator. Like its superclass, if the user clicks OK, the new value is
- * committed to Chrome. If the user clicks Cancel or leaves the settings page,
- * the new value is discarded.
- * @constructor
- * @extends {options.ConfirmDialog}
- */
- function HotwordConfirmDialog() {
- ConfirmDialog.call(this,
- 'hotwordConfim', // name
- loadTimeData.getString('hotwordConfirmOverlayTabTitle'),
- 'hotword-confirm-overlay', // pageDivName
- assertInstanceof($('hotword-confirm-ok'), HTMLButtonElement),
- assertInstanceof($('hotword-confirm-cancel'), HTMLButtonElement),
- $('hotword-search-enable')['pref'], // pref
- $('hotword-search-enable')['metric']); // metric
-
- this.indicator = $('hotword-search-setting-indicator');
- }
-
- HotwordConfirmDialog.prototype = {
- // TODO(dbeam): this class should probably derive SettingsDialog again as it
- // evily duplicates much of ConfirmDialog's functionality, calls methods
- // on SettingsDialog.prototype, and shadows private method names.
- __proto__: ConfirmDialog.prototype,
-
- /**
- * Handle changes to |pref|. Only uncommitted changes are relevant as these
- * originate from user and need to be explicitly committed to take effect.
- * Pop up the dialog if there are no errors from the indicator or commit the
- * change, depending on whether confirmation is needed.
- * @param {Event} event Change event.
- * @private
- */
- onPrefChanged_: function(event) {
- if (!event.value.uncommitted)
- return;
-
- if (event.value.value && !this.confirmed_) {
- // If there is an error, show the indicator icon with more information.
- if (this.indicator.errorText)
- this.indicator.updateBasedOnError();
-
- // Show confirmation dialog (regardless of whether there is an error).
- PageManager.showPageByName(this.name, false);
- } else {
- Preferences.getInstance().commitPref(this.pref, this.metric);
- }
- },
-
- /**
- * Override the initializePage function so that an updated version of
- * onPrefChanged_ can be used.
- * @override
- */
- initializePage: function() {
- SettingsDialog.prototype.initializePage.call(this);
-
- this.okButton.onclick = this.handleConfirm.bind(this);
- this.cancelButton.onclick = this.handleCancel.bind(this);
- Preferences.getInstance().addEventListener(
- this.pref, this.onPrefChanged_.bind(this));
- }
- };
-
- return {
- HotwordConfirmDialog: HotwordConfirmDialog
- };
-});
diff --git a/chromium/chrome/browser/resources/options/hotword_confirm_overlay.css b/chromium/chrome/browser/resources/options/hotword_confirm_overlay.css
deleted file mode 100644
index 542d87455b1..00000000000
--- a/chromium/chrome/browser/resources/options/hotword_confirm_overlay.css
+++ /dev/null
@@ -1,7 +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. */
-
-#hotword-confirm-overlay {
- width: 500px;
-}
diff --git a/chromium/chrome/browser/resources/options/hotword_confirm_overlay.html b/chromium/chrome/browser/resources/options/hotword_confirm_overlay.html
deleted file mode 100644
index 5733921fbb7..00000000000
--- a/chromium/chrome/browser/resources/options/hotword_confirm_overlay.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<div id="hotword-confirm-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{hotwordConfirmOverlay}</h1>
- <div class="content-area">
- <span id="hotword-confirm-text">$i18n{hotwordConfirmMessage}</span>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a target="_blank"
- href="$i18nRaw{hotwordLearnMoreURL}">$i18n{learnMore}</a>
- </div>
- <div class="action-area-right">
- <div class="button-strip">
- <button id="hotword-confirm-cancel">
- $i18n{hotwordConfirmDisable}
- </button>
- <button id="hotword-confirm-ok" class="default-button">
- $i18n{hotwordConfirmEnable}
- </button>
- </div>
- </div>
- </div>
- <div id="audio-logging-bar" class="gray-bottom-bar checkbox">
- <label>
- <input
- pref="hotword.audio_logging_enabled"
- metric="Options_Hotword_AudioLogging_Checkbox"
- type="checkbox" dialog-pref checked>
- <span>$i18n{hotwordAudioLoggingEnable}</span>
- </label>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/hotword_search_setting_indicator.css b/chromium/chrome/browser/resources/options/hotword_search_setting_indicator.css
deleted file mode 100644
index d486d1a5d5d..00000000000
--- a/chromium/chrome/browser/resources/options/hotword_search_setting_indicator.css
+++ /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. */
-
-/* Hotword extension-specific controlled setting indicator and bubble. */
-
-#hotword-search-setting-indicator > div,
-#hotword-always-on-search-setting-indicator > div,
-#hotword-no-dsp-search-setting-indicator > div {
- background: url(chrome://theme/IDR_WARNING) left top no-repeat;
- background-size: 18px;
-}
diff --git a/chromium/chrome/browser/resources/options/hotword_search_setting_indicator.js b/chromium/chrome/browser/resources/options/hotword_search_setting_indicator.js
deleted file mode 100644
index 40e1b170798..00000000000
--- a/chromium/chrome/browser/resources/options/hotword_search_setting_indicator.js
+++ /dev/null
@@ -1,122 +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.
-
-cr.define('options', function() {
- /** @const */ var ControlledSettingIndicator =
- options.ControlledSettingIndicator;
-
- /**
- * A variant of the {@link ControlledSettingIndicator} that shows the status
- * of the hotword search setting, including a bubble to show setup errors
- * (such as failures to download extension resources).
- * @constructor
- * @extends {options.ControlledSettingIndicator}
- */
- var HotwordSearchSettingIndicator = cr.ui.define('span');
-
- HotwordSearchSettingIndicator.prototype = {
- __proto__: ControlledSettingIndicator.prototype,
-
- /**
- * Decorates the base element to show the proper icon.
- * @override
- */
- decorate: function() {
- ControlledSettingIndicator.prototype.decorate.call(this);
- this.hidden = true;
- },
-
- /**
- * Handle changes to the associated pref by hiding any currently visible
- * bubble.
- * @param {Event} event Pref change event.
- * @override
- */
- handlePrefChange: function(event) {
- PageManager.hideBubble();
- },
-
- /**
- * Sets the variable tracking the section which becomes disabled if an
- * error exists.
- * @param {HTMLElement} section The section to disable.
- */
- set disabledOnErrorSection(section) {
- // TODO(kcarattini): Instead of this, add a cr.EventTarget and have
- // the element to disable register an event on it.
- this.disabledOnErrorSection_ = section;
- },
-
- /**
- * Returns the current error.
- * @return {string} The error message to be displayed. May be undefined if
- * there is no error.
- */
- get errorText() {
- return this.errorText_;
- },
-
- /**
- * Checks for errors and records them.
- * @param {string} errorMsg The error message to be displayed. May be
- * undefined if there is no error.
- */
- setError: function(errorMsg) {
- this.setAttribute('controlled-by', 'policy');
- this.errorText_ = errorMsg;
- },
-
- /**
- * Changes the display to be visible if there are errors and disables
- * the section.
- */
- updateBasedOnError: function() {
- if (this.errorText_)
- this.hidden = false;
- if (this.disabledOnErrorSection_)
- this.disabledOnErrorSection_.disabled = !!this.errorText_;
- },
-
- /**
- * Toggles showing and hiding the error message bubble. An empty
- * |errorText_| indicates that there is no error message. So the bubble
- * only be shown if |errorText_| has a value.
- * @override
- */
- toggleBubble: function() {
- if (this.showingBubble) {
- PageManager.hideBubble();
- return;
- }
-
- if (!this.errorText_)
- return;
-
- var self = this;
- // Create the DOM tree for the bubble content.
- var closeButton = document.createElement('div');
- closeButton.classList.add('close-button');
-
- var text = document.createElement('p');
- text.innerHTML = this.errorText_;
-
- var textDiv = document.createElement('div');
- textDiv.appendChild(text);
-
- var container = document.createElement('div');
- container.appendChild(closeButton);
- container.appendChild(textDiv);
-
- var content = document.createElement('div');
- content.appendChild(container);
-
- PageManager.showBubble(content, this.image, this, this.location);
- },
- };
-
- // Export
- return {
- HotwordSearchSettingIndicator: HotwordSearchSettingIndicator
- };
-});
diff --git a/chromium/chrome/browser/resources/options/i18n_setup.html b/chromium/chrome/browser/resources/options/i18n_setup.html
deleted file mode 100644
index cec2322227e..00000000000
--- a/chromium/chrome/browser/resources/options/i18n_setup.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<!-- This file is intentionally empty.
- settings-lock-screen element will import i18n_setup.html file in settings.
- The scripts included by i18n_setup.html is already included in options.html,
- including the same script again seems to throw some errors. So creating an
- empty file here just for options.
--->
diff --git a/chromium/chrome/browser/resources/options/import_data_overlay.css b/chromium/chrome/browser/resources/options/import_data_overlay.css
deleted file mode 100644
index 0d730dcb19b..00000000000
--- a/chromium/chrome/browser/resources/options/import_data_overlay.css
+++ /dev/null
@@ -1,36 +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. */
-
-#import-data-overlay {
- width: 400px;
-}
-
-#import-from-div {
- margin-bottom: 20px;
-}
-
-#import-checkboxes > div:not(:first-child) {
- -webkit-padding-start: 8px;
-}
-
-#import-throbber {
- margin: 4px 10px;
- vertical-align: middle;
- visibility: hidden;
-}
-
-#import-success-header {
- font-size: 1.2em;
-}
-
-#import-success-image {
- -webkit-mask-image: url(../../../../ui/webui/resources/images/check_circle.svg);
- -webkit-mask-position: center;
- -webkit-mask-repeat: no-repeat;
- -webkit-mask-size: 96px;
- background-color: rgb(15, 157, 88);
- height: 96px;
- margin: 20px 0;
- width: 100%;
-}
diff --git a/chromium/chrome/browser/resources/options/import_data_overlay.html b/chromium/chrome/browser/resources/options/import_data_overlay.html
deleted file mode 100644
index 7d604146bfd..00000000000
--- a/chromium/chrome/browser/resources/options/import_data_overlay.html
+++ /dev/null
@@ -1,120 +0,0 @@
-<div id="import-data-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{importDataOverlay}</h1>
- <div class="content-area">
- <div class="import-data-configure">
- <div id="import-from-div">
- <span>$i18n{importFromLabel}</span>
- <select id="import-browsers">
- <option>$i18n{importLoading}</option>
- </select>
- </div>
- <div id="import-checkboxes">
- <div>$i18n{importDescription}</div>
- <div class="checkbox controlled-setting-with-label"
- id="import-history-with-label">
- <label>
- <input id="import-history" type="checkbox"
- pref="import_dialog_history">
- <span>
- <span>$i18n{importHistory}</span>
- <span class="controlled-setting-indicator"
- pref="import_dialog_history">
- </span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label"
- id="import-favorites-with-label">
- <label>
- <input id="import-favorites" type="checkbox"
- pref="import_dialog_bookmarks">
- <span>
- <span>$i18n{importFavorites}</span>
- <span class="controlled-setting-indicator"
- pref="import_dialog_bookmarks"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label"
- id="import-passwords-with-label">
- <label>
- <input id="import-passwords" type="checkbox"
- pref="import_dialog_saved_passwords">
- <span>
- <span>$i18n{importPasswords}</span>
- <span class="controlled-setting-indicator"
- pref="import_dialog_saved_passwords"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label"
- id="import-search-with-label">
- <label>
- <input id="import-search" type="checkbox"
- pref="import_dialog_search_engine">
- <span>
- <span>$i18n{importSearch}</span>
- <span class="controlled-setting-indicator"
- pref="import_dialog_search_engine"></span>
- </span>
- </label>
- </div>
- <div class="checkbox controlled-setting-with-label"
- id="import-autofill-form-data-with-label">
- <label>
- <input id="import-autofill-form-data" type="checkbox"
- pref="import_dialog_autofill_form_data">
- <span>$i18n{importAutofillFormData}</span>
- </label>
- <span class="controlled-setting-indicator"
- pref="import_dialog_autofill_form_data"></span>
- </div>
- </div>
- </div>
- <div class="import-data-success" hidden>
- <div id="import-success-header">
- <strong>$i18n{importSucceeded}</strong>
- </div>
- <div id="import-success-image"></div>
- <div id="import-find-your-bookmarks">
- <span>$i18n{findYourImportedBookmarks}</span>
- <div class="checkbox controlled-setting-with-label">
- <label>
- <input id="import-data-show-bookmarks-bar"
- pref="bookmark_bar.show_on_all_tabs"
- metric="Options_ShowBookmarksBar" type="checkbox">
- <span>
- <span>$i18n{toolbarShowBookmarksBar}</span>
- <span class="controlled-setting-indicator"
- pref="bookmark_bar.show_on_all_tabs"></span>
- </span>
- </label>
- </div>
- </div>
- </div>
- </div>
- <div class="action-area">
- <div class="import-data-configure">
- <div class="action-area-right">
- <div id="import-throbber" class="throbber"></div>
- <div class="button-strip">
- <button id="import-data-cancel">$i18n{cancel}</button>
- <button id="import-choose-file">$i18n{importChooseFile}</button>
- <button id="import-data-commit" class="default-button">
- $i18n{importCommit}
- </button>
- </div>
- </div>
- </div>
- <div class="import-data-success" hidden>
- <div class="action-area-right">
- <div class="button-strip">
- <button id="import-data-confirm" class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/import_data_overlay.js b/chromium/chrome/browser/resources/options/import_data_overlay.js
deleted file mode 100644
index 2d9fd60dc8d..00000000000
--- a/chromium/chrome/browser/resources/options/import_data_overlay.js
+++ /dev/null
@@ -1,269 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * ImportDataOverlay class
- * Encapsulated handling of the 'Import Data' overlay page.
- * @class
- */
- function ImportDataOverlay() {
- Page.call(this,
- 'importData',
- loadTimeData.getString('importDataOverlayTabTitle'),
- 'import-data-overlay');
- }
-
- cr.addSingletonGetter(ImportDataOverlay);
-
- /**
- * @param {string} type The type of data to import. Used in the element's ID.
- */
- function importable(type) {
- var id = 'import-' + type;
- return $(id).checked && !$(id + '-with-label').hidden;
- }
-
- ImportDataOverlay.prototype = {
- // Inherit from Page.
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
- var checkboxes =
- document.querySelectorAll('#import-checkboxes input[type=checkbox]');
- for (var i = 0; i < checkboxes.length; i++) {
- checkboxes[i].customPrefChangeHandler = function(e) {
- options.PrefCheckbox.prototype.defaultPrefChangeHandler.call(this, e);
- self.validateCommitButton_();
- return true;
- };
- }
-
- $('import-browsers').onchange = function() {
- self.updateCheckboxes_();
- self.validateCommitButton_();
- };
-
- $('import-data-commit').onclick = function() {
- chrome.send('importData', [
- String($('import-browsers').selectedIndex),
- String($('import-history').checked),
- String($('import-favorites').checked),
- String($('import-passwords').checked),
- String($('import-search').checked),
- String($('import-autofill-form-data').checked)]);
- };
-
- $('import-data-cancel').onclick = function() {
- ImportDataOverlay.dismiss();
- };
-
- $('import-choose-file').onclick = function() {
- chrome.send('chooseBookmarksFile');
- };
-
- $('import-data-confirm').onclick = function() {
- ImportDataOverlay.dismiss();
- };
-
- // Form controls are disabled until the profile list has been loaded.
- self.setAllControlsEnabled_(false);
- },
-
- /**
- * Sets the enabled and checked state of the commit button.
- * @private
- */
- validateCommitButton_: function() {
- var somethingToImport =
- importable('history') || importable('favorites') ||
- importable('passwords') || importable('search') ||
- importable('autofill-form-data');
- $('import-data-commit').disabled = !somethingToImport;
- $('import-choose-file').disabled = !$('import-favorites').checked;
- },
-
- /**
- * Sets the enabled state of all the checkboxes and the commit button.
- * @private
- */
- setAllControlsEnabled_: function(enabled) {
- var checkboxes =
- document.querySelectorAll('#import-checkboxes input[type=checkbox]');
- for (var i = 0; i < checkboxes.length; i++)
- this.setUpCheckboxState_(checkboxes[i], enabled);
- $('import-data-commit').disabled = !enabled;
- $('import-choose-file').hidden = !enabled;
- },
-
- /**
- * Sets the enabled state of a checkbox element.
- * @param {Object} checkbox A checkbox element.
- * @param {boolean} enabled The enabled state of the checkbox. If false,
- * the checkbox is disabled. If true, the checkbox is enabled.
- * @private
- */
- setUpCheckboxState_: function(checkbox, enabled) {
- checkbox.setDisabled('noProfileData', !enabled);
- },
-
- /**
- * Update the enabled and visible states of all the checkboxes.
- * @private
- */
- updateCheckboxes_: function() {
- var index = $('import-browsers').selectedIndex;
- var bookmarksFileSelected = index == this.browserProfiles.length - 1;
- $('import-choose-file').hidden = !bookmarksFileSelected;
- $('import-data-commit').hidden = bookmarksFileSelected;
-
- var browserProfile;
- if (this.browserProfiles.length > index)
- browserProfile = this.browserProfiles[index];
- var importOptions = ['history',
- 'favorites',
- 'passwords',
- 'search',
- 'autofill-form-data'];
- for (var i = 0; i < importOptions.length; i++) {
- var id = 'import-' + importOptions[i];
- var enable = browserProfile && browserProfile[importOptions[i]];
- this.setUpCheckboxState_($(id), enable);
- $(id + '-with-label').hidden = !enable;
- }
- },
-
- /**
- * Update the supported browsers popup with given entries.
- * @param {Array} browsers List of supported browsers name.
- * @private
- */
- updateSupportedBrowsers_: function(browsers) {
- this.browserProfiles = browsers;
- var browserSelect = /** @type {HTMLSelectElement} */(
- $('import-browsers'));
- browserSelect.remove(0); // Remove the 'Loading...' option.
- browserSelect.textContent = '';
- var browserCount = browsers.length;
-
- if (browserCount == 0) {
- var option = new Option(loadTimeData.getString('noProfileFound'), 0);
- browserSelect.appendChild(option);
-
- this.setAllControlsEnabled_(false);
- } else {
- this.setAllControlsEnabled_(true);
- for (var i = 0; i < browserCount; i++) {
- var browser = browsers[i];
- var option = new Option(browser.name, browser.index);
- browserSelect.appendChild(option);
- }
-
- this.updateCheckboxes_();
- this.validateCommitButton_();
- }
- },
-
- /**
- * Clear import prefs set when user checks/unchecks a checkbox so that each
- * checkbox goes back to the default "checked" state (or alternatively, to
- * the state set by a recommended policy).
- * @private
- */
- clearUserPrefs_: function() {
- var importPrefs = [
- 'import_dialog_history', 'import_dialog_bookmarks',
- 'import_dialog_saved_passwords', 'import_dialog_search_engine',
- 'import_dialog_autofill_form_data'
- ];
- for (var i = 0; i < importPrefs.length; i++)
- Preferences.clearPref(importPrefs[i], true);
- },
-
- /**
- * Update the dialog layout to reflect success state.
- * @param {boolean} success If true, show success dialog elements.
- * @private
- */
- updateSuccessState_: function(success) {
- var sections = document.querySelectorAll('.import-data-configure');
- for (var i = 0; i < sections.length; i++)
- sections[i].hidden = success;
-
- sections = document.querySelectorAll('.import-data-success');
- for (var i = 0; i < sections.length; i++)
- sections[i].hidden = !success;
- },
- };
-
- ImportDataOverlay.clearUserPrefs = function() {
- ImportDataOverlay.getInstance().clearUserPrefs_();
- };
-
- /**
- * Update the supported browsers popup with given entries.
- * @param {Array} browsers List of supported browsers name.
- */
- ImportDataOverlay.updateSupportedBrowsers = function(browsers) {
- ImportDataOverlay.getInstance().updateSupportedBrowsers_(browsers);
- };
-
- /**
- * Update the UI to reflect whether an import operation is in progress.
- * @param {boolean} importing True if an import operation is in progress.
- */
- ImportDataOverlay.setImportingState = function(importing) {
- var checkboxes =
- document.querySelectorAll('#import-checkboxes input[type=checkbox]');
- for (var i = 0; i < checkboxes.length; i++)
- checkboxes[i].setDisabled('Importing', importing);
- if (!importing)
- ImportDataOverlay.getInstance().updateCheckboxes_();
- $('import-browsers').disabled = importing;
- $('import-throbber').style.visibility = importing ? 'visible' : 'hidden';
- ImportDataOverlay.getInstance().validateCommitButton_();
- };
-
- /**
- * Remove the import overlay from display.
- */
- ImportDataOverlay.dismiss = function() {
- ImportDataOverlay.clearUserPrefs();
- PageManager.closeOverlay();
- };
-
- /**
- * Show a message confirming the success of the import operation.
- */
- ImportDataOverlay.confirmSuccess = function() {
- var showBookmarksMessage = $('import-favorites').checked;
- ImportDataOverlay.setImportingState(false);
- $('import-find-your-bookmarks').hidden = !showBookmarksMessage;
- ImportDataOverlay.getInstance().updateSuccessState_(true);
- };
-
- /**
- * Show the import data overlay.
- */
- ImportDataOverlay.show = function() {
- // Make sure that any previous import success message is hidden, and
- // we're showing the UI to import further data.
- ImportDataOverlay.getInstance().updateSuccessState_(false);
- ImportDataOverlay.getInstance().validateCommitButton_();
-
- PageManager.showPageByName('importData');
- };
-
- // Export
- return {
- ImportDataOverlay: ImportDataOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/info.svg b/chromium/chrome/browser/resources/options/info.svg
deleted file mode 100644
index e76e2476640..00000000000
--- a/chromium/chrome/browser/resources/options/info.svg
+++ /dev/null
@@ -1,4 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" viewBox="0 0 48 48" fill="#757575">
- <path d="M0 0h48v48H0z" fill="none"/>
- <path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm2 30h-4V22h4v12zm0-16h-4v-4h4v4z"/>
-</svg>
diff --git a/chromium/chrome/browser/resources/options/inline_editable_list.js b/chromium/chrome/browser/resources/options/inline_editable_list.js
deleted file mode 100644
index da5751e2719..00000000000
--- a/chromium/chrome/browser/resources/options/inline_editable_list.js
+++ /dev/null
@@ -1,774 +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.
-
-cr.define('options', function() {
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var DeletableItemList = options.DeletableItemList;
-
- /**
- * Creates a new list item with support for inline editing.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function InlineEditableItem() {
- var el = cr.doc.createElement('div');
- InlineEditableItem.decorate(el);
- return el;
- }
-
- /**
- * Decorates an element as a inline-editable list item. Note that this is
- * a subclass of DeletableItem.
- * @param {!HTMLElement} el The element to decorate.
- */
- InlineEditableItem.decorate = function(el) {
- el.__proto__ = InlineEditableItem.prototype;
- el.decorate();
- };
-
- InlineEditableItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /**
- * Index of currently focused column, or -1 for none.
- * @type {number}
- */
- focusedColumnIndex: -1,
-
- /**
- * Whether or not this item can be edited.
- * @type {boolean}
- * @private
- */
- editable_: true,
-
- /**
- * Whether or not this is a placeholder for adding a new item.
- * @type {boolean}
- * @private
- */
- isPlaceholder_: false,
-
- /**
- * Fields associated with edit mode.
- * @type {Array}
- * @private
- */
- editFields_: null,
-
- /**
- * Whether or not the current edit should be considered cancelled, rather
- * than committed, when editing ends.
- * @type {boolean}
- * @private
- */
- editCancelled_: true,
-
- /**
- * The editable item corresponding to the last click, if any. Used to decide
- * initial focus when entering edit mode.
- * @type {HTMLElement}
- * @private
- */
- editClickTarget_: null,
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- this.editFields_ = [];
- this.addEventListener('mousedown', this.handleMouseDown_);
- this.addEventListener('keydown', this.handleKeyDown_);
- this.addEventListener('focusin', this.handleFocusIn_);
- },
-
- /** @override */
- selectionChanged: function() {
- if (!this.parentNode.ignoreChangeEvents_)
- this.updateEditState();
- },
-
- /**
- * Called when this element gains or loses 'lead' status. Updates editing
- * mode accordingly.
- */
- updateLeadState: function() {
- // Add focusability before call to updateEditState.
- if (this.lead) {
- this.setEditableValuesFocusable(true);
- this.setCloseButtonFocusable(true);
- }
-
- this.updateEditState();
-
- // Remove focusability after call to updateEditState.
- this.setStaticValuesFocusable(false);
- if (!this.lead) {
- this.setEditableValuesFocusable(false);
- this.setCloseButtonFocusable(false);
- }
- },
-
- /**
- * Updates the edit state based on the current selected and lead states.
- */
- updateEditState: function() {
- if (this.editable)
- this.editing = this.selected && this.lead;
- },
-
- /**
- * Whether the user is currently editing the list item.
- * @type {boolean}
- */
- get editing() {
- return this.hasAttribute('editing');
- },
- set editing(editing) {
- if (this.editing == editing)
- return;
-
- if (editing)
- this.setAttribute('editing', '');
- else
- this.removeAttribute('editing');
-
- if (editing) {
- this.editCancelled_ = false;
-
- cr.dispatchSimpleEvent(this, 'edit', true);
-
- var isMouseClick = this.editClickTarget_;
- var focusElement = this.getEditFocusElement_();
- if (focusElement) {
- if (isMouseClick) {
- // Delay focus to fix http://crbug.com/436789
- setTimeout(function() {
- this.focusAndMaybeSelect_(focusElement);
- }.bind(this), 0);
- } else {
- this.focusAndMaybeSelect_(focusElement);
- }
- }
- } else {
- if (!this.editCancelled_ && this.hasBeenEdited &&
- this.currentInputIsValid) {
- this.parentNode.needsToFocusPlaceholder_ = this.isPlaceholder &&
- this.parentNode.shouldFocusPlaceholderOnEditCommit();
- this.updateStaticValues_();
- cr.dispatchSimpleEvent(this, 'commitedit', true);
- } else {
- this.parentNode.needsToFocusPlaceholder_ = false;
- this.resetEditableValues_();
- cr.dispatchSimpleEvent(this, 'canceledit', true);
- }
- }
- },
-
- /**
- * Return editable element that should be focused, or null for none.
- * @private
- */
- getEditFocusElement_: function() {
- // If an edit field was clicked on then use the clicked element.
- if (this.editClickTarget_) {
- var result = this.editClickTarget_;
- this.editClickTarget_ = null;
- return result;
- }
-
- // If focusedColumnIndex is valid then use the element in that column.
- if (this.focusedColumnIndex != -1) {
- var nearestColumn =
- this.getNearestColumnByIndex_(this.focusedColumnIndex);
- if (nearestColumn)
- return nearestColumn;
- }
-
- // It's possible that focusedColumnIndex hasn't been updated yet.
- // Check getFocusedColumnIndex_ directly.
- // This can't completely replace the above focusedColumnIndex check
- // because InlineEditableItemList may have set focusedColumnIndex to a
- // different value.
- var columnIndex = this.getFocusedColumnIndex_();
- if (columnIndex != -1) {
- var nearestColumn = this.getNearestColumnByIndex_(columnIndex);
- if (nearestColumn)
- return nearestColumn;
- }
-
- // Everything else failed so return the default.
- return this.initialFocusElement;
- },
-
- /**
- * Focus on the specified element, and select the editable text in it
- * if possible.
- * @param {!Element} control An element to be focused.
- * @private
- */
- focusAndMaybeSelect_: function(control) {
- control.focus();
- if (control.tagName == 'INPUT')
- control.select();
- },
-
- /**
- * Whether the item is editable.
- * @type {boolean}
- */
- get editable() {
- return this.editable_;
- },
- set editable(editable) {
- this.editable_ = editable;
- if (!editable)
- this.editing = false;
- },
-
- /**
- * Whether the item is a new item placeholder.
- * @type {boolean}
- */
- get isPlaceholder() {
- return this.isPlaceholder_;
- },
- set isPlaceholder(isPlaceholder) {
- this.isPlaceholder_ = isPlaceholder;
- if (isPlaceholder)
- this.deletable = false;
- },
-
- /**
- * The HTML element that should have focus initially when editing starts,
- * if a specific element wasn't clicked.
- * Defaults to the first <input> element; can be overridden by subclasses if
- * a different element should be focused.
- * @type {HTMLElement}
- */
- get initialFocusElement() {
- return this.contentElement.querySelector('input');
- },
-
- /**
- * Whether the input in currently valid to submit. If this returns false
- * when editing would be submitted, either editing will not be ended,
- * or it will be cancelled, depending on the context.
- * Can be overridden by subclasses to perform input validation.
- * @type {boolean}
- */
- get currentInputIsValid() {
- return true;
- },
-
- /**
- * Returns true if the item has been changed by an edit.
- * Can be overridden by subclasses to return false when nothing has changed
- * to avoid unnecessary commits.
- * @type {boolean}
- */
- get hasBeenEdited() {
- return true;
- },
-
- /**
- * Sets whether the editable values can be given focus using the keyboard.
- * @param {boolean} focusable The desired focusable state.
- */
- setEditableValuesFocusable: function(focusable) {
- focusable = focusable && this.editable;
- var editFields = this.editFields_;
- for (var i = 0; i < editFields.length; i++) {
- editFields[i].tabIndex = focusable ? 0 : -1;
- }
- },
-
- /**
- * Sets whether the static values can be given focus using the keyboard.
- * @param {boolean} focusable The desired focusable state.
- */
- setStaticValuesFocusable: function(focusable) {
- var editFields = this.editFields_;
- for (var i = 0; i < editFields.length; i++) {
- var staticVersion = editFields[i].staticVersion;
- if (!staticVersion)
- continue;
- if (this.editable) {
- staticVersion.tabIndex = focusable ? 0 : -1;
- } else {
- // staticVersion remains visible when !this.editable. Remove
- // tabindex so that it will not become focused by clicking on it and
- // have selection box drawn around it.
- staticVersion.removeAttribute('tabindex');
- }
- }
- },
-
- /**
- * Sets whether the close button can be focused using the keyboard.
- * @param {boolean} focusable The desired focusable state.
- */
- setCloseButtonFocusable: function(focusable) {
- this.closeButtonElement.tabIndex =
- focusable && this.closeButtonFocusAllowed ? 0 : -1;
- },
-
- /**
- * Returns a div containing an <input>, as well as static text if
- * isPlaceholder is not true.
- * @param {string} text The text of the cell.
- * @return {HTMLElement} The HTML element for the cell.
- * @private
- */
- createEditableTextCell: function(text) {
- var container = /** @type {HTMLElement} */(
- this.ownerDocument.createElement('div'));
- var textEl = null;
- if (!this.isPlaceholder) {
- textEl = this.ownerDocument.createElement('div');
- textEl.className = 'static-text overruleable';
- textEl.textContent = text;
- textEl.setAttribute('displaymode', 'static');
- container.appendChild(textEl);
- }
-
- var inputEl = this.ownerDocument.createElement('input');
- inputEl.type = 'text';
- inputEl.value = text;
- if (!this.isPlaceholder)
- inputEl.setAttribute('displaymode', 'edit');
-
- // In some cases 'focus' event may arrive before 'input'.
- // To make sure revalidation is triggered we postpone 'focus' handling.
- var handler = this.handleFocus.bind(this);
- inputEl.addEventListener('focus', function() {
- window.setTimeout(function() {
- if (inputEl.ownerDocument.activeElement == inputEl)
- handler();
- }, 0);
- });
- container.appendChild(inputEl);
- this.addEditField(inputEl, textEl);
-
- return container;
- },
-
- /**
- * Register an edit field.
- * @param {!Element} control An editable element. It's a form control
- * element typically.
- * @param {Element} staticElement An element representing non-editable
- * state.
- */
- addEditField: function(control, staticElement) {
- control.staticVersion = staticElement;
- if (this.editable)
- control.tabIndex = -1;
-
- if (control.staticVersion) {
- if (this.editable)
- control.staticVersion.tabIndex = -1;
- control.staticVersion.editableVersion = control;
- control.staticVersion.addEventListener('focus',
- this.handleFocus.bind(this));
- }
- this.editFields_.push(control);
- },
-
- /**
- * Set the column index for a child element of this InlineEditableItem.
- * Only elements with a column index will be keyboard focusable, e.g. by
- * pressing the tab key.
- * @param {Element} element Element whose column index to set. Method does
- * nothing if element is null.
- * @param {number} columnIndex The new column index to set on the element.
- * -1 removes the column index.
- */
- setFocusableColumnIndex: function(element, columnIndex) {
- if (!element)
- return;
-
- if (columnIndex >= 0)
- element.setAttribute('inlineeditable-column', columnIndex);
- else
- element.removeAttribute('inlineeditable-column');
- },
-
- /**
- * Resets the editable version of any controls created by createEditable*
- * to match the static text.
- * @private
- */
- resetEditableValues_: function() {
- var editFields = this.editFields_;
- for (var i = 0; i < editFields.length; i++) {
- var staticLabel = editFields[i].staticVersion;
- if (!staticLabel && !this.isPlaceholder)
- continue;
-
- if (editFields[i].tagName == 'INPUT') {
- editFields[i].value =
- this.isPlaceholder ? '' : staticLabel.textContent;
- }
- // Add more tag types here as new createEditable* methods are added.
-
- editFields[i].setCustomValidity('');
- }
- },
-
- /**
- * Sets the static version of any controls created by createEditable*
- * to match the current value of the editable version. Called on commit so
- * that there's no flicker of the old value before the model updates.
- * @private
- */
- updateStaticValues_: function() {
- var editFields = this.editFields_;
- for (var i = 0; i < editFields.length; i++) {
- var staticLabel = editFields[i].staticVersion;
- if (!staticLabel)
- continue;
-
- if (editFields[i].tagName == 'INPUT')
- staticLabel.textContent = editFields[i].value;
- // Add more tag types here as new createEditable* methods are added.
- }
- },
-
- /**
- * Returns the index of the column that currently has focus, or -1 if no
- * column has focus.
- * @return {number}
- * @private
- */
- getFocusedColumnIndex_: function() {
- var element = document.activeElement.editableVersion ||
- document.activeElement;
-
- if (element.hasAttribute('inlineeditable-column'))
- return parseInt(element.getAttribute('inlineeditable-column'), 10);
- return -1;
- },
-
- /**
- * Returns the element from the column that has the largest index where:
- * where:
- * + index <= startIndex, and
- * + the element exists, and
- * + the element is not disabled
- * @return {Element}
- * @private
- */
- getNearestColumnByIndex_: function(startIndex) {
- for (var i = startIndex; i >= 0; --i) {
- var el = this.querySelector('[inlineeditable-column="' + i + '"]');
- if (el && !el.disabled)
- return el;
- }
- return null;
- },
-
- /**
- * Called when a key is pressed. Handles committing and canceling edits.
- * @param {Event} e The key down event.
- * @private
- */
- handleKeyDown_: function(e) {
- if (!this.editing)
- return;
-
- var endEdit = false;
- var handledKey = true;
- switch (e.key) {
- case 'Escape':
- this.editCancelled_ = true;
- endEdit = true;
- break;
- case 'Enter':
- if (this.currentInputIsValid)
- endEdit = true;
- break;
- default:
- handledKey = false;
- }
- if (handledKey) {
- // Make sure that handled keys aren't passed on and double-handled.
- // (e.g., esc shouldn't both cancel an edit and close a subpage)
- e.stopPropagation();
- }
- if (endEdit) {
- // Blurring will trigger the edit to end; see InlineEditableItemList.
- this.ownerDocument.activeElement.blur();
- }
- },
-
- /**
- * Called when the list item is clicked. If the click target corresponds to
- * an editable item, stores that item to focus when edit mode is started.
- * @param {Event} e The mouse down event.
- * @private
- */
- handleMouseDown_: function(e) {
- if (!this.editable)
- return;
-
- var clickTarget = e.target;
- var editFields = this.editFields_;
- var editClickTarget;
- for (var i = 0; i < editFields.length; i++) {
- if (editFields[i] == clickTarget ||
- editFields[i].staticVersion == clickTarget) {
- editClickTarget = editFields[i];
- break;
- }
- }
-
- if (this.editing) {
- if (!editClickTarget) {
- // Clicked on the list item outside of an edit field. Don't lose focus
- // from currently selected edit field.
- e.stopPropagation();
- e.preventDefault();
- }
- return;
- }
-
- if (editClickTarget && !editClickTarget.disabled)
- this.editClickTarget_ = editClickTarget;
- },
-
- /**
- * Called when this InlineEditableItem or any of its children are given
- * focus. Updates focusedColumnIndex with the index of the newly focused
- * column, or -1 if the focused element does not have a column index.
- * @param {Event} e The focusin event.
- * @private
- */
- handleFocusIn_: function(e) {
- var target = e.target.editableVersion || e.target;
- this.focusedColumnIndex = target.hasAttribute('inlineeditable-column') ?
- parseInt(target.getAttribute('inlineeditable-column'), 10) : -1;
- },
- };
-
- /**
- * Takes care of committing changes to inline editable list items when the
- * window loses focus.
- */
- function handleWindowBlurs() {
- window.addEventListener('blur', function(e) {
- var itemAncestor = findAncestor(document.activeElement, function(node) {
- return node instanceof InlineEditableItem;
- });
- if (itemAncestor)
- document.activeElement.blur();
- });
- }
- handleWindowBlurs();
-
- /**
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var InlineEditableItemList = cr.ui.define('list');
-
- InlineEditableItemList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- /**
- * Whether to ignore list change events.
- * Used to modify the list without processing selection change and lead
- * change events.
- * @type {boolean}
- * @private
- */
- ignoreChangeEvents_: false,
-
- /**
- * Focuses the input element of the placeholder if true.
- * @type {boolean}
- * @private
- */
- needsToFocusPlaceholder_: false,
-
- /** @override */
- decorate: function() {
- DeletableItemList.prototype.decorate.call(this);
- this.setAttribute('inlineeditable', '');
- this.addEventListener('hasElementFocusChange',
- this.handleListFocusChange_);
- // <list> isn't focusable by default, but cr.ui.List defaults tabindex to
- // 0 if it's not set.
- this.tabIndex = -1;
- },
-
- /**
- * Called when the list hierarchy as a whole loses or gains focus; starts
- * or ends editing for the lead item if necessary.
- * @param {Event} e The change event.
- * @private
- */
- handleListFocusChange_: function(e) {
- var leadItem = this.getListItemByIndex(this.selectionModel.leadIndex);
- if (leadItem) {
- if (e.newValue) {
- // Add focusability before making other changes.
- leadItem.setEditableValuesFocusable(true);
- leadItem.setCloseButtonFocusable(true);
- leadItem.focusedColumnIndex = -1;
- leadItem.updateEditState();
- // Remove focusability after making other changes.
- leadItem.setStaticValuesFocusable(false);
- } else {
- // Add focusability before making other changes.
- leadItem.setStaticValuesFocusable(true);
- leadItem.setCloseButtonFocusable(true);
- leadItem.editing = false;
- // Remove focusability after making other changes.
- if (!leadItem.isPlaceholder)
- leadItem.setEditableValuesFocusable(false);
- }
- }
- },
-
- /** @override */
- handleLeadChange: function(e) {
- if (this.ignoreChangeEvents_)
- return;
-
- DeletableItemList.prototype.handleLeadChange.call(this, e);
-
- var focusedColumnIndex = -1;
- if (e.oldValue != -1) {
- var element = this.getListItemByIndex(e.oldValue);
- if (element) {
- focusedColumnIndex = element.focusedColumnIndex;
- element.updateLeadState();
- }
- }
-
- if (e.newValue != -1) {
- var element = this.getListItemByIndex(e.newValue);
- if (element) {
- element.focusedColumnIndex = focusedColumnIndex;
- element.updateLeadState();
- }
- }
- },
-
- /** @override */
- onSetDataModelComplete: function() {
- DeletableItemList.prototype.onSetDataModelComplete.call(this);
-
- if (this.needsToFocusPlaceholder_) {
- this.focusPlaceholder();
- } else {
- var item = this.getInitialFocusableItem();
- if (item) {
- item.setStaticValuesFocusable(true);
- item.setCloseButtonFocusable(true);
- if (item.isPlaceholder)
- item.setEditableValuesFocusable(true);
- }
- }
- },
-
- /**
- * Execute |callback| with list change events disabled. Selection change and
- * lead change events will not be processed.
- * @param {!Function} callback The function to execute.
- * @protected
- */
- ignoreChangeEvents: function(callback) {
- assert(!this.ignoreChangeEvents_);
- this.ignoreChangeEvents_ = true;
- callback();
- this.ignoreChangeEvents_ = false;
- },
-
- /**
- * Set the selected index without changing the focused element on the page.
- * Used to change the selected index when the list doesn't have focus (and
- * doesn't want to take focus).
- * @param {number} index The index to select.
- */
- selectIndexWithoutFocusing: function(index) {
- // Remove focusability from old item.
- var oldItem = this.getListItemByIndex(this.selectionModel.leadIndex) ||
- this.getInitialFocusableItem();
- if (oldItem) {
- oldItem.setEditableValuesFocusable(false);
- oldItem.setStaticValuesFocusable(false);
- oldItem.setCloseButtonFocusable(false);
- oldItem.lead = false;
- }
-
- // Select the new item.
- this.ignoreChangeEvents(function() {
- this.selectionModel.selectedIndex = index;
- }.bind(this));
-
- // Add focusability to new item.
- var newItem = this.getListItemByIndex(index);
- if (newItem) {
- if (newItem.isPlaceholder)
- newItem.setEditableValuesFocusable(true);
- else
- newItem.setStaticValuesFocusable(true);
-
- newItem.setCloseButtonFocusable(true);
- newItem.lead = true;
- }
- },
-
- /**
- * Focus the placeholder's first input field.
- * Should only be called immediately after the list has been repopulated.
- */
- focusPlaceholder: function() {
- // Remove focusability from initial item.
- var item = this.getInitialFocusableItem();
- if (item) {
- item.setStaticValuesFocusable(false);
- item.setCloseButtonFocusable(false);
- }
- // Find placeholder and focus it.
- for (var i = 0; i < this.dataModel.length; i++) {
- var item = this.getListItemByIndex(i);
- if (item.isPlaceholder) {
- item.setEditableValuesFocusable(true);
- item.setCloseButtonFocusable(true);
- item.querySelector('input').focus();
- return;
- }
- }
- },
-
- /**
- * May be overridden by subclasses to disable focusing the placeholder.
- * @return {boolean} True if the placeholder element should be focused on
- * edit commit.
- * @protected
- */
- shouldFocusPlaceholderOnEditCommit: function() {
- return true;
- },
-
- /**
- * Override to change which item is initially focusable.
- * @return {options.InlineEditableItem} Initially focusable item or null.
- * @protected
- */
- getInitialFocusableItem: function() {
- return /** @type {options.InlineEditableItem} */(
- this.getListItemByIndex(0));
- },
- };
-
- // Export
- return {
- InlineEditableItem: InlineEditableItem,
- InlineEditableItemList: InlineEditableItemList,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/language_add_language_overlay.html b/chromium/chrome/browser/resources/options/language_add_language_overlay.html
deleted file mode 100644
index c95a56ac435..00000000000
--- a/chromium/chrome/browser/resources/options/language_add_language_overlay.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<div id="add-language-overlay-page" class="page" role="dialog" hidden>
- <div class="close-button"></div>
- <h1>$i18n{addLanguageTitle}</h1>
- <div class="content-area">
- <label id="add-language-overlay-language-list-label">
- $i18n{addLanguageSelectLabel}
- </label>
- <select id="add-language-overlay-language-list"
- aria-labelledby="add-language-overlay-language-list-label"></select>
- </div>
- <div class="action-area button-strip">
- <button id="add-language-overlay-cancel-button">$i18n{cancel}</button>
- <button id="add-language-overlay-ok-button" class="default-button">
- $i18n{ok}
- </button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/language_add_language_overlay.js b/chromium/chrome/browser/resources/options/language_add_language_overlay.js
deleted file mode 100644
index 9ea8904b1a2..00000000000
--- a/chromium/chrome/browser/resources/options/language_add_language_overlay.js
+++ /dev/null
@@ -1,75 +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.
-
-///////////////////////////////////////////////////////////////////////////////
-// AddLanguageOverlay class:
-
-/**
- * @typedef {{
- * code: string,
- * displayName: string,
- * textDirection: string,
- * nativeDisplayName: string
- * }}
- */
-options.LanguageData;
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Encapsulated handling of ChromeOS add language overlay page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function AddLanguageOverlay() {
- Page.call(this, 'addLanguage',
- loadTimeData.getString('addButton'),
- 'add-language-overlay-page');
- }
-
- cr.addSingletonGetter(AddLanguageOverlay);
-
- AddLanguageOverlay.prototype = {
- // Inherit AddLanguageOverlay from Page.
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- // Set up the cancel button.
- $('add-language-overlay-cancel-button').onclick = function(e) {
- PageManager.closeOverlay();
- };
-
- // Create the language list with which users can add a language.
- var addLanguageList = $('add-language-overlay-language-list');
-
- /**
- * @type {!Array<!options.LanguageData>}
- * @see chrome/browser/ui/webui/options/language_options_handler.cc
- */
- var languageListData = /** @type {!Array<!options.LanguageData>} */(
- loadTimeData.getValue('languageList'));
- for (var i = 0; i < languageListData.length; i++) {
- var language = languageListData[i];
- var displayText = language.displayName;
- // If the native name is different, add it.
- if (language.displayName != language.nativeDisplayName)
- displayText += ' - ' + language.nativeDisplayName;
-
- var option = cr.doc.createElement('option');
- option.value = language.code;
- option.textContent = displayText;
- addLanguageList.appendChild(option);
- }
- },
- };
-
- return {
- AddLanguageOverlay: AddLanguageOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/language_dictionary_overlay.css b/chromium/chrome/browser/resources/options/language_dictionary_overlay.css
deleted file mode 100644
index a02c181ecdf..00000000000
--- a/chromium/chrome/browser/resources/options/language_dictionary_overlay.css
+++ /dev/null
@@ -1,47 +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. */
-
-#language-dictionary-overlay-no-matches {
- line-height: 2.5em;
- margin-bottom: 0;
- margin-top: 0;
- padding: 0 3px;
-}
-
-#language-dictionary-overlay-page h1 {
- margin-right: 16em;
- padding-top: 25px;
-}
-
-html[dir=rtl] #language-dictionary-overlay-page h1 {
- margin-left: 16em;
- margin-right: auto;
-}
-
-#language-dictionary-overlay-search-field {
- position: absolute;
- right: 32px;
- top: 21px;
-}
-
-html[dir=rtl] #language-dictionary-overlay-search-field {
- left: 32px;
- right: auto;
-}
-
-#language-dictionary-overlay-word-list {
- height: 20em;
-}
-
-#language-dictionary-overlay-word-list.no-search-matches {
- height: 17.5em;
-}
-
-#language-dictionary-overlay-word-list > * {
- height: 2.5em;
-}
-
-.language-dictionary-overlay-word-list-item {
- width: 30em;
-}
diff --git a/chromium/chrome/browser/resources/options/language_dictionary_overlay.html b/chromium/chrome/browser/resources/options/language_dictionary_overlay.html
deleted file mode 100644
index 9e1a67f13aa..00000000000
--- a/chromium/chrome/browser/resources/options/language_dictionary_overlay.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<div id="language-dictionary-overlay-page" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{languageDictionaryOverlayTitle}</h1>
- <input id="language-dictionary-overlay-search-field" type="search"
- placeholder="$i18n{languageDictionaryOverlaySearchPlaceholder}"
- aria-label="$i18n{languageDictionaryOverlaySearchPlaceholder}"
- incremental>
- <div class="content-area">
- <div class="settings-list">
- <p id="language-dictionary-overlay-no-matches" hidden>
- $i18n{languageDictionaryOverlayNoMatches}
- </p>
- <list id="language-dictionary-overlay-word-list"></list>
- </div>
- </div>
- <div class="action-area button-strip">
- <button id="language-dictionary-overlay-done-button" class="default-button">
- $i18n{done}
- </button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/language_dictionary_overlay.js b/chromium/chrome/browser/resources/options/language_dictionary_overlay.js
deleted file mode 100644
index 6f7a4a2ccb8..00000000000
--- a/chromium/chrome/browser/resources/options/language_dictionary_overlay.js
+++ /dev/null
@@ -1,117 +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.
-
-cr.define('options', function() {
- /** @const */ var DictionaryWordsList =
- options.dictionary_words.DictionaryWordsList;
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Adding and removing words in custom spelling dictionary.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function EditDictionaryOverlay() {
- Page.call(this, 'editDictionary',
- loadTimeData.getString('languageDictionaryOverlayPage'),
- 'language-dictionary-overlay-page');
- }
-
- cr.addSingletonGetter(EditDictionaryOverlay);
-
- EditDictionaryOverlay.prototype = {
- __proto__: Page.prototype,
-
- /**
- * A list of words in the dictionary.
- * @type {options.dictionary_words.DictionaryWordsList}
- * @private
- */
- wordList_: null,
-
- /**
- * The input field for searching for words in the dictionary.
- * @type {HTMLElement}
- * @private
- */
- searchField_: null,
-
- /**
- * The paragraph of text that indicates that search returned no results.
- * @type {HTMLElement}
- * @private
- */
- noMatchesLabel_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var wordList = $('language-dictionary-overlay-word-list');
- DictionaryWordsList.decorate(wordList);
- this.wordList_ = assertInstanceof(wordList, DictionaryWordsList);
- this.wordList_.onWordListChanged = function() {
- this.onWordListChanged_();
- }.bind(this);
-
- this.searchField_ = $('language-dictionary-overlay-search-field');
- this.searchField_.onsearch = function(e) {
- this.wordList_.search(e.currentTarget.value);
- }.bind(this);
- this.searchField_.onkeydown = function(e) {
- // Don't propagate enter key events. Otherwise the default button will
- // activate.
- if (e.key == 'Enter')
- e.stopPropagation();
- };
-
- this.noMatchesLabel_ = getRequiredElement(
- 'language-dictionary-overlay-no-matches');
-
- $('language-dictionary-overlay-done-button').onclick = function(e) {
- PageManager.closeOverlay();
- };
- },
-
- /**
- * Refresh the dictionary words when the page is displayed.
- * @override
- */
- didShowPage: function() {
- chrome.send('refreshDictionaryWords');
- },
-
- /**
- * Update the view based on the changes in the word list.
- * @private
- */
- onWordListChanged_: function() {
- if (this.searchField_.value.length > 0 && this.wordList_.empty) {
- this.noMatchesLabel_.hidden = false;
- this.wordList_.classList.add('no-search-matches');
- } else {
- this.noMatchesLabel_.hidden = true;
- this.wordList_.classList.remove('no-search-matches');
- }
- },
- };
-
- EditDictionaryOverlay.setWordList = function(entries) {
- EditDictionaryOverlay.getInstance().wordList_.setWordList(entries);
- };
-
- EditDictionaryOverlay.updateWords = function(add_words, remove_words) {
- EditDictionaryOverlay.getInstance().wordList_.addWords(add_words);
- EditDictionaryOverlay.getInstance().wordList_.removeWords(remove_words);
- };
-
- EditDictionaryOverlay.getWordListForTesting = function() {
- return EditDictionaryOverlay.getInstance().wordList_;
- };
-
- return {
- EditDictionaryOverlay: EditDictionaryOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/language_dictionary_overlay_word_list.js b/chromium/chrome/browser/resources/options/language_dictionary_overlay_word_list.js
deleted file mode 100644
index fbc868e1b36..00000000000
--- a/chromium/chrome/browser/resources/options/language_dictionary_overlay_word_list.js
+++ /dev/null
@@ -1,267 +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.
-
-cr.define('options.dictionary_words', function() {
- /** @const */ var InlineEditableItemList = options.InlineEditableItemList;
- /** @const */ var InlineEditableItem = options.InlineEditableItem;
-
- /**
- * Creates a new dictionary word list item.
- * @param {string} dictionaryWord The dictionary word.
- * @param {function(string)} addDictionaryWordCallback Callback for
- * adding a dictionary word.
- * @constructor
- * @extends {options.InlineEditableItem}
- */
- function DictionaryWordsListItem(dictionaryWord, addDictionaryWordCallback) {
- var el = cr.doc.createElement('div');
- el.dictionaryWord_ = dictionaryWord;
- el.addDictionaryWordCallback_ = addDictionaryWordCallback;
- DictionaryWordsListItem.decorate(el);
- return el;
- }
-
- /**
- * Decorates an HTML element as a dictionary word list item.
- * @param {HTMLElement} el The element to decorate.
- */
- DictionaryWordsListItem.decorate = function(el) {
- el.__proto__ = DictionaryWordsListItem.prototype;
- el.decorate();
- };
-
- DictionaryWordsListItem.prototype = {
- __proto__: InlineEditableItem.prototype,
-
- /** @override */
- decorate: function() {
- InlineEditableItem.prototype.decorate.call(this);
- if (this.dictionaryWord_ == '')
- this.isPlaceholder = true;
- else
- this.editable = false;
-
- var wordEl = this.createEditableTextCell(this.dictionaryWord_);
- wordEl.classList.add('weakrtl');
- wordEl.classList.add('language-dictionary-overlay-word-list-item');
- this.contentElement.appendChild(wordEl);
-
- var wordField = wordEl.querySelector('input');
- wordField.classList.add('language-dictionary-overlay-word-list-item');
- if (this.isPlaceholder) {
- wordField.placeholder =
- loadTimeData.getString('languageDictionaryOverlayAddWordLabel');
- }
-
- this.addEventListener('commitedit', this.onEditCommitted_.bind(this));
- },
-
- /** @override */
- get hasBeenEdited() {
- return this.querySelector('input').value.length > 0;
- },
-
- /** @override */
- updateLeadState: function() {
- InlineEditableItem.prototype.updateLeadState.call(this);
-
- // Allow focusing the list item itself if not editable.
- if (!this.editable)
- this.tabIndex = this.lead ? 0 : -1;
- },
-
- /** @override */
- updateEditState: function() {
- InlineEditableItem.prototype.updateEditState.call(this);
-
- // Focus the list item itself if not editable.
- if (!this.editable && this.selected && this.lead)
- this.focus();
- },
-
- /**
- * Adds a word to the dictionary.
- * @param {Event} e Edit committed event.
- * @private
- */
- onEditCommitted_: function(e) {
- var input = e.currentTarget.querySelector('input');
- this.addDictionaryWordCallback_(input.value);
- input.value = '';
- },
- };
-
- /**
- * A list of words in the dictionary.
- * @constructor
- * @extends {options.InlineEditableItemList}
- */
- var DictionaryWordsList = cr.ui.define('list');
-
- DictionaryWordsList.prototype = {
- __proto__: InlineEditableItemList.prototype,
-
- /**
- * The function to notify that the word list has changed.
- * @type {?Function}
- */
- onWordListChanged: null,
-
- /**
- * The list of all words in the dictionary. Used to generate a filtered word
- * list in the |search(searchTerm)| method.
- * @type {Array}
- * @private
- */
- allWordsList_: null,
-
- /**
- * The list of words that the user removed, but |DictionaryWordList| has not
- * received a notification of their removal yet.
- * @type {Array}
- * @private
- */
- removedWordsList_: [],
-
- /**
- * Adds a dictionary word.
- * @param {string} dictionaryWord The word to add.
- * @private
- */
- addDictionaryWord_: function(dictionaryWord) {
- this.allWordsList_.push(dictionaryWord);
- this.dataModel.splice(this.dataModel.length - 1, 0, dictionaryWord);
- this.onWordListChanged();
- chrome.send('addDictionaryWord', [dictionaryWord]);
- },
-
- /**
- * Searches the list for the matching words.
- * @param {string} searchTerm The search term.
- */
- search: function(searchTerm) {
- var filteredWordList = this.allWordsList_.filter(
- function(element, index, array) {
- return element.indexOf(searchTerm) > -1;
- });
- filteredWordList.push('');
- this.dataModel = new cr.ui.ArrayDataModel(filteredWordList);
- this.onWordListChanged();
- },
-
- /**
- * Sets the list of dictionary words.
- * @param {Array} entries The list of dictionary words.
- */
- setWordList: function(entries) {
- this.allWordsList_ = entries.slice(0);
- // Empty string is a placeholder for entering new words.
- entries.push('');
- this.dataModel = new cr.ui.ArrayDataModel(entries);
- this.onWordListChanged();
- },
-
- /**
- * Adds non-duplicate dictionary words.
- * @param {Array} entries The list of dictionary words.
- */
- addWords: function(entries) {
- var toAdd = [];
- for (var i = 0; i < entries.length; i++) {
- if (this.allWordsList_.indexOf(entries[i]) == -1) {
- this.allWordsList_.push(entries[i]);
- toAdd.push(entries[i]);
- }
- }
- if (toAdd.length == 0)
- return;
- for (var i = 0; i < toAdd.length; i++)
- this.dataModel.splice(this.dataModel.length - 1, 0, toAdd[i]);
- this.onWordListChanged();
- },
-
- /**
- * Removes dictionary words that are not in |removedWordsList_|. If a word
- * is in |removedWordsList_|, then removes the word from there instead.
- * @param {Array} entries The list of dictionary words.
- */
- removeWords: function(entries) {
- var index;
- var toRemove = [];
- for (var i = 0; i < entries.length; i++) {
- index = this.removedWordsList_.indexOf(entries[i]);
- if (index > -1) {
- this.removedWordsList_.splice(index, 1);
- } else {
- index = this.allWordsList_.indexOf(entries[i]);
- if (index > -1) {
- this.allWordsList_.splice(index, 1);
- toRemove.push(entries[i]);
- }
- }
- }
- if (toRemove.length == 0)
- return;
- for (var i = 0; i < toRemove.length; i++) {
- index = this.dataModel.indexOf(toRemove[i]);
- if (index > -1)
- this.dataModel.splice(index, 1);
- }
- this.onWordListChanged();
- },
-
- /**
- * Returns true if the data model contains no words, otherwise returns
- * false.
- * @type {boolean}
- */
- get empty() {
- // A data model without dictionary words contains one placeholder for
- // entering new words.
- return this.dataModel.length < 2;
- },
-
- /**
- * @override
- * @param {string} dictionaryWord
- */
- createItem: function(dictionaryWord) {
- return new DictionaryWordsListItem(
- dictionaryWord,
- this.addDictionaryWord_.bind(this));
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- // The last element in the data model is an undeletable placeholder for
- // entering new words.
- assert(index > -1 && index < this.dataModel.length - 1);
- var item = this.dataModel.item(index);
- var allWordsListIndex = this.allWordsList_.indexOf(item);
- assert(allWordsListIndex > -1);
- this.allWordsList_.splice(allWordsListIndex, 1);
- this.dataModel.splice(index, 1);
- this.removedWordsList_.push(item);
- this.onWordListChanged();
- chrome.send('removeDictionaryWord', [item]);
- },
-
- /** @override */
- shouldFocusPlaceholderOnEditCommit: function() {
- return false;
- },
-
- /** @override */
- getInitialFocusableItem: function() {
- return /** @type {options.InlineEditableItem} */(
- this.getListItemByIndex(this.selectionModel.length - 1));
- },
- };
-
- return {
- DictionaryWordsList: DictionaryWordsList
- };
-
-});
-
diff --git a/chromium/chrome/browser/resources/options/language_list.js b/chromium/chrome/browser/resources/options/language_list.js
deleted file mode 100644
index 7fc79e56a29..00000000000
--- a/chromium/chrome/browser/resources/options/language_list.js
+++ /dev/null
@@ -1,444 +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.
-
-cr.define('options', function() {
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var DeletableItemList = options.DeletableItemList;
- /** @const */ var List = cr.ui.List;
- /** @const */ var ListItem = cr.ui.ListItem;
- /** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel;
-
- /**
- * Creates a new Language list item.
- * @param {Object} languageInfo The information of the language.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function LanguageListItem(languageInfo) {
- var el = cr.doc.createElement('li');
- el.__proto__ = LanguageListItem.prototype;
- el.language_ = languageInfo;
- el.decorate();
- return el;
- }
-
- LanguageListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /**
- * The language code of this language.
- * @type {?string}
- * @private
- */
- languageCode_: null,
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- var languageCode = this.language_.code;
- var languageOptions = options.LanguageOptions.getInstance();
- this.deletable = languageOptions.languageIsDeletable(languageCode);
- this.languageCode = languageCode;
- this.languageName = cr.doc.createElement('div');
- this.languageName.className = 'language-name';
- this.languageName.dir = this.language_.textDirection;
- this.languageName.textContent = this.language_.displayName;
- this.contentElement.appendChild(this.languageName);
- this.title = this.language_.nativeDisplayName;
- this.draggable = true;
- },
- };
-
- /**
- * Creates a new language list.
- * @param {Object=} opt_propertyBag Optional properties.
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var LanguageList = cr.ui.define('list');
-
- /**
- * Gets information of a language from the given language code.
- * @param {string} languageCode Language code (ex. "fr").
- */
- LanguageList.getLanguageInfoFromLanguageCode = function(languageCode) {
- // Build the language code to language info dictionary at first time.
- if (!this.languageCodeToLanguageInfo_) {
- this.languageCodeToLanguageInfo_ = {};
- var languageList = loadTimeData.getValue('languageList');
- for (var i = 0; i < languageList.length; i++) {
- var languageInfo = languageList[i];
- this.languageCodeToLanguageInfo_[languageInfo.code] = languageInfo;
- }
- }
-
- return this.languageCodeToLanguageInfo_[languageCode];
- };
-
- /**
- * Returns true if the given language code is valid.
- * @param {string} languageCode Language code (ex. "fr").
- */
- LanguageList.isValidLanguageCode = function(languageCode) {
- // Having the display name for the language code means that the
- // language code is valid.
- if (LanguageList.getLanguageInfoFromLanguageCode(languageCode)) {
- return true;
- }
- return false;
- };
-
- LanguageList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- // The list item being dragged.
- draggedItem: null,
- // The drop position information: "below" or "above".
- dropPos: null,
- // The preference is a CSV string that describes preferred languages
- // in Chrome OS. The language list is used for showing the language
- // list in "Language and Input" options page.
- preferredLanguagesPref: 'settings.language.preferred_languages',
- // The preference is a CSV string that describes accept languages used
- // for content negotiation. To be more precise, the list will be used
- // in "Accept-Language" header in HTTP requests.
- acceptLanguagesPref: 'intl.accept_languages',
-
- /** @override */
- decorate: function() {
- DeletableItemList.prototype.decorate.call(this);
- this.selectionModel = new ListSingleSelectionModel;
-
- // HACK(arv): http://crbug.com/40902
- window.addEventListener('resize', this.redraw.bind(this));
-
- // Listen to pref change.
- if (cr.isChromeOS) {
- Preferences.getInstance().addEventListener(this.preferredLanguagesPref,
- this.handlePreferredLanguagesPrefChange_.bind(this));
- } else {
- Preferences.getInstance().addEventListener(this.acceptLanguagesPref,
- this.handleAcceptLanguagesPrefChange_.bind(this));
- }
-
- // Listen to drag and drop events.
- this.addEventListener('dragstart', this.handleDragStart_.bind(this));
- this.addEventListener('dragenter', this.handleDragEnter_.bind(this));
- this.addEventListener('dragover', this.handleDragOver_.bind(this));
- this.addEventListener('drop', this.handleDrop_.bind(this));
- this.addEventListener('dragleave', this.handleDragLeave_.bind(this));
- },
-
- /**
- * @override
- * @param {string} languageCode
- */
- createItem: function(languageCode) {
- var languageInfo =
- LanguageList.getLanguageInfoFromLanguageCode(languageCode);
- return new LanguageListItem(languageInfo);
- },
-
- /*
- * For each item, determines whether it's deletable.
- */
- updateDeletable: function() {
- var items = this.items;
- for (var i = 0; i < items.length; ++i) {
- var item = items[i];
- var languageCode = item.languageCode;
- var languageOptions = options.LanguageOptions.getInstance();
- item.deletable = languageOptions.languageIsDeletable(languageCode);
- }
- },
-
- /**
- * Adds a language to the language list.
- * @param {string} languageCode language code (ex. "fr").
- */
- addLanguage: function(languageCode) {
- // It shouldn't happen but ignore the language code if it's
- // null/undefined, or already present.
- if (!languageCode || this.dataModel.indexOf(languageCode) >= 0) {
- return;
- }
- this.dataModel.push(languageCode);
- // Select the last item, which is the language added.
- this.selectionModel.selectedIndex = this.dataModel.length - 1;
-
- this.savePreference_();
- },
-
- /**
- * Gets the language codes of the currently listed languages.
- */
- getLanguageCodes: function() {
- return this.dataModel.slice();
- },
-
- /**
- * Clears the selection
- */
- clearSelection: function() {
- this.selectionModel.unselectAll();
- },
-
- /**
- * Gets the language code of the selected language.
- */
- getSelectedLanguageCode: function() {
- return this.selectedItem;
- },
-
- /**
- * Selects the language by the given language code.
- * @return {boolean} True if the operation is successful.
- */
- selectLanguageByCode: function(languageCode) {
- var index = this.dataModel.indexOf(languageCode);
- if (index >= 0) {
- this.selectionModel.selectedIndex = index;
- return true;
- }
- return false;
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- if (index >= 0) {
- this.dataModel.splice(index, 1);
- // Once the selected item is removed, there will be no selected item.
- // Select the item pointed by the lead index.
- index = this.selectionModel.leadIndex;
- this.savePreference_();
- }
- return index;
- },
-
- /**
- * Computes the target item of drop event.
- * @param {Event} e The drop or dragover event.
- * @private
- */
- getTargetFromDropEvent_: function(e) {
- var target = e.target;
- // e.target may be an inner element of the list item
- while (target != null && !(target instanceof ListItem)) {
- target = target.parentNode;
- }
- return target;
- },
-
- /**
- * Handles the dragstart event.
- * @param {Event} e The dragstart event.
- * @private
- */
- handleDragStart_: function(e) {
- var target = e.target;
- // ListItem should be the only draggable element type in the page,
- // but just in case.
- if (target instanceof ListItem) {
- this.draggedItem = target;
- e.dataTransfer.effectAllowed = 'move';
- // We need to put some kind of data in the drag or it will be
- // ignored. Use the display name in case the user drags to a text
- // field or the desktop.
- e.dataTransfer.setData('text/plain', target.title);
- }
- },
-
- /**
- * Handles the dragenter event.
- * @param {Event} e The dragenter event.
- * @private
- */
- handleDragEnter_: function(e) {
- e.preventDefault();
- },
-
- /**
- * Handles the dragover event.
- * @param {Event} e The dragover event.
- * @private
- */
- handleDragOver_: function(e) {
- var dropTarget = this.getTargetFromDropEvent_(e);
- // Determines whether the drop target is to accept the drop.
- // The drop is only successful on another ListItem.
- if (!(dropTarget instanceof ListItem) ||
- dropTarget == this.draggedItem) {
- this.hideDropMarker_();
- return;
- }
- // Compute the drop postion. Should we move the dragged item to
- // below or above the drop target?
- var rect = dropTarget.getBoundingClientRect();
- var dy = e.clientY - rect.top;
- var yRatio = dy / rect.height;
- var dropPos = yRatio <= .5 ? 'above' : 'below';
- this.dropPos = dropPos;
- this.showDropMarker_(dropTarget, dropPos);
- e.preventDefault();
- },
-
- /**
- * Handles the drop event.
- * @param {Event} e The drop event.
- * @private
- */
- handleDrop_: function(e) {
- var dropTarget = this.getTargetFromDropEvent_(e);
- this.hideDropMarker_();
-
- // Delete the language from the original position.
- var languageCode = this.draggedItem.languageCode;
- var originalIndex = this.dataModel.indexOf(languageCode);
- this.dataModel.splice(originalIndex, 1);
- // Insert the language to the new position.
- var newIndex = this.dataModel.indexOf(dropTarget.languageCode);
- if (this.dropPos == 'below')
- newIndex += 1;
- this.dataModel.splice(newIndex, 0, languageCode);
- // The cursor should move to the moved item.
- this.selectionModel.selectedIndex = newIndex;
- // Save the preference.
- this.savePreference_();
- },
-
- /**
- * Handles the dragleave event.
- * @param {Event} e The dragleave event
- * @private
- */
- handleDragLeave_: function(e) {
- this.hideDropMarker_();
- },
-
- /**
- * Shows and positions the marker to indicate the drop target.
- * @param {HTMLElement} target The current target list item of drop
- * @param {string} pos 'below' or 'above'
- * @private
- */
- showDropMarker_: function(target, pos) {
- window.clearTimeout(this.hideDropMarkerTimer_);
- var marker = $('language-options-list-dropmarker');
- var rect = target.getBoundingClientRect();
- var markerHeight = 8;
- if (pos == 'above') {
- marker.style.top = (rect.top - markerHeight / 2) + 'px';
- } else {
- marker.style.top = (rect.bottom - markerHeight / 2) + 'px';
- }
- marker.style.width = rect.width + 'px';
- marker.style.left = rect.left + 'px';
- marker.style.display = 'block';
- },
-
- /**
- * Hides the drop marker.
- * @private
- */
- hideDropMarker_: function() {
- // Hide the marker in a timeout to reduce flickering as we move between
- // valid drop targets.
- window.clearTimeout(this.hideDropMarkerTimer_);
- this.hideDropMarkerTimer_ = window.setTimeout(function() {
- $('language-options-list-dropmarker').style.display = '';
- }, 100);
- },
-
- /**
- * Handles preferred languages pref change.
- * @param {Event} e The change event object.
- * @private
- */
- handlePreferredLanguagesPrefChange_: function(e) {
- var languageCodesInCsv = e.value.value;
- var languageCodes = languageCodesInCsv.split(',');
-
- // Add the UI language to the initial list of languages. This is to avoid
- // a bug where the UI language would be removed from the preferred
- // language list by sync on first login.
- // See: crosbug.com/14283
- languageCodes.push(navigator.language);
- languageCodes = this.filterBadLanguageCodes_(languageCodes);
- this.load_(languageCodes);
- },
-
- /**
- * Handles accept languages pref change.
- * @param {Event} e The change event object.
- * @private
- */
- handleAcceptLanguagesPrefChange_: function(e) {
- var languageCodesInCsv = e.value.value;
- var languageCodes = this.filterBadLanguageCodes_(
- languageCodesInCsv.split(','));
- this.load_(languageCodes);
- },
-
- /**
- * Loads given language list.
- * @param {!Array} languageCodes List of language codes.
- * @private
- */
- load_: function(languageCodes) {
- // Preserve the original selected index. See comments below.
- var originalSelectedIndex = this.selectionModel.selectedIndex;
- this.dataModel = new ArrayDataModel(languageCodes);
- if (originalSelectedIndex >= 0 &&
- originalSelectedIndex < this.dataModel.length) {
- // Restore the original selected index if the selected index is
- // valid after the data model is loaded. This is needed to keep
- // the selected language after the languge is added or removed.
- this.selectionModel.selectedIndex = originalSelectedIndex;
- // The lead index should be updated too.
- this.selectionModel.leadIndex = originalSelectedIndex;
- } else if (this.dataModel.length > 0) {
- // Otherwise, select the first item if it's not empty.
- // Note that ListSingleSelectionModel won't select an item
- // automatically, hence we manually select the first item here.
- this.selectionModel.selectedIndex = 0;
- }
- },
-
- /**
- * Saves the preference.
- */
- savePreference_: function() {
- chrome.send('updateLanguageList', [this.dataModel.slice()]);
- cr.dispatchSimpleEvent(this, 'save');
- },
-
- /**
- * Filters bad language codes in case bad language codes are
- * stored in the preference. Removes duplicates as well.
- * @param {Array} languageCodes List of language codes.
- * @private
- */
- filterBadLanguageCodes_: function(languageCodes) {
- var filteredLanguageCodes = [];
- var seen = {};
- for (var i = 0; i < languageCodes.length; i++) {
- // Check if the the language code is valid, and not
- // duplicate. Otherwise, skip it.
- if (LanguageList.isValidLanguageCode(languageCodes[i]) &&
- !(languageCodes[i] in seen)) {
- filteredLanguageCodes.push(languageCodes[i]);
- seen[languageCodes[i]] = true;
- }
- }
- return filteredLanguageCodes;
- },
- };
-
- return {
- LanguageList: LanguageList,
- LanguageListItem: LanguageListItem
- };
-});
diff --git a/chromium/chrome/browser/resources/options/language_options.css b/chromium/chrome/browser/resources/options/language_options.css
deleted file mode 100644
index e34f513d2b9..00000000000
--- a/chromium/chrome/browser/resources/options/language_options.css
+++ /dev/null
@@ -1,192 +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. */
-
-#languagePage .content-area {
- width: 660px;
-}
-
-.language-options {
- display: -webkit-box;
- margin: 10px 0;
-}
-
-.language-options-lower-left button,
-#language-options-details button {
- min-width: 70px;
-}
-
-.language-options h3 {
- -webkit-margin-start: 12px;
- font-size: 100%;
- font-weight: bold;
- margin-bottom: 12px;
- margin-top: 12px;
-}
-
-.language-options-contents {
- min-height: 28px;
- padding: 0 12px 4px;
-}
-
-.language-options-contents >
- span:not(.input-method-label):not(.controlled-setting-indicator) {
- display: inline-block;
- margin: 1px;
- padding: 0.42em 10px;
-}
-
-.language-options-header,
-.language-options-footer {
- margin: 10px 0;
-}
-
-#language-options-languages,
-#language-options-details {
- border: 1px solid #ccc;
- height: 369px;
- padding: 0;
- vertical-align: top;
-}
-
-#language-options-languages {
- -webkit-box-orient: vertical;
- background-color: rgb(235, 239, 249);
- display: -webkit-box;
- width: 300px;
-}
-
-.language-options-lower-left {
- -webkit-box-flex: 0;
- -webkit-padding-start: 12px;
- padding-bottom: 10px;
-}
-
-#language-options-details {
- -webkit-box-flex: 1;
- /* To share the center line with the left pane. */
- -webkit-margin-start: -1px;
- overflow-y: auto;
-}
-
-#language-options-details h3:not(:first-of-type) {
- margin-top: 24px;
-}
-
-.language-options-notification {
- background-color: rgb(255, 247, 193);
- margin: 0 0 4px;
- padding: 8px 30px 8px 12px;
-}
-
-.language-options-notification > div {
- margin-bottom: 4px;
-}
-
-#language-options-input-method-list button {
- -webkit-margin-start: 20px;
- display: block;
- /* Same margin as .settings-row. */
- margin-bottom: 0.65em;
- margin-top: 0.65em;
-}
-
-#language-options-list {
- -webkit-box-flex: 1;
- outline: none;
- padding: 0;
- width: 100%;
-}
-
-#language-options-list .language-name {
- -webkit-box-flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-#language-options-list li {
- -webkit-padding-start: 12px;
- padding-bottom: 2px;
- padding-top: 2px;
-}
-
-#language-options-list-dropmarker {
- background-clip: padding-box;
- background-color: hsl(214, 91%, 65%);
- border: 3px solid hsl(214, 91%, 65%);
- border-bottom-color: transparent;
- border-radius: 0;
- border-top-color: transparent;
- box-sizing: border-box;
- display: none;
- height: 8px;
- overflow: hidden;
- pointer-events: none;
- position: fixed;
- z-index: 10;
-}
-
-/* TODO(kochi): This is temporary copy from new_tab.css */
-/* Notification */
-
-#notification {
- background-color: hsl(52, 100%, 80%);
- border: 1px solid rgb(211, 211, 211);
- border-radius: 6px;
- color: black;
- display: table;
- font-weight: bold;
- /* Set the height and margin so that the element does not use any vertical
- space. */
- height: 16px;
- margin: -44px auto 12px auto;
- opacity: 0;
- padding: 7px 15px;
- pointer-events: none;
- position: relative;
- transition: opacity 150ms;
- white-space: nowrap;
- z-index: 1;
-}
-
-#notification > * {
- display: table-cell;
- max-width: 500px;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-#notification.show {
- opacity: 1;
- pointer-events: all;
- transition: opacity 1s;
-}
-
-#notification .link {
- -webkit-appearance: none;
- -webkit-padding-start: 20px;
- background: none;
- border: 0;
- color: rgba(0, 102, 204, 0.3);
- cursor: pointer;
- text-decoration: underline;
-}
-
-#notification .link-color {
- color: rgb(0, 102, 204);
-}
-
-#chewing-max-chi-symbol-len {
- height: 30%;
- width: 100px;
-}
-
-#add-language-overlay-page .content-area {
- padding-bottom: 10px;
-}
-
-/* TODO(hshi): Remove this temporary hack once the bug is fixed in Chrome. */
-#add-language-overlay-language-list {
- width: -webkit-calc(100% - 4px);
-}
diff --git a/chromium/chrome/browser/resources/options/language_options.html b/chromium/chrome/browser/resources/options/language_options.html
deleted file mode 100644
index 7f9f33a1f7b..00000000000
--- a/chromium/chrome/browser/resources/options/language_options.html
+++ /dev/null
@@ -1,142 +0,0 @@
-<div id="languagePage" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{languagePage}</h1>
- <div class="content-area">
- <div id="notification">
- <span>&nbsp;</span>
- <span class="link"><span class="link-color"></span></span>
- </div>
- <div class="language-options-header">
- <span>$i18n{addLanguageInstructions}</span>
-<if expr="chromeos">
- <span>$i18n{inputMethodInstructions}</span>
-</if>
- <a target="_blank"
- href="$i18nRaw{languagesLearnMoreURL}">$i18n{learnMore}</a>
- </div>
- <div class="language-options">
- <div id="language-options-languages">
- <h3>$i18n{languages}</h3>
- <list id="language-options-list"></list>
- <div class="language-options-lower-left">
- <button id="language-options-add-button">$i18n{addButton}</button>
- </div>
- <div id="language-options-list-dropmarker"></div>
- </div>
- <div id="language-options-details">
- <h3 id="language-options-language-name"></h3>
-<if expr="os == 'win32' or chromeos">
- <div id="language-options-ui-language-section"
- class="language-options-contents">
- <button id="language-options-ui-language-button">
- $i18n{displayInThisLanguage}
- </button>
- <span class="controlled-setting-indicator"></span>
- <span id="language-options-ui-language-message" hidden></span>
- </div>
-</if>
-<!-- Chrome uses the native OS spellchecker in OS X, so don't display the
- dictionary pane. -->
-<if expr="not is_macosx">
- <div id="language-options-spellcheck" class="language-options-contents">
- <div class="checkbox" id="spellcheck-language-checkbox-container">
- <label>
- <input type="checkbox" id="spellcheck-language-checkbox">
- <span>$i18n{useThisForSpellChecking}</span>
- </label>
- </div>
- <span id="spellcheck-language-message" hidden></span>
- <span id="language-options-dictionary-downloading-message" hidden>
- $i18n{downloadingDictionary}
- </span>
- </div>
- <div id="language-options-dictionary-download-failed-message"
- class="language-options-notification" hidden>
- <div>$i18n{downloadFailed}</div>
- <div id="language-options-dictionary-download-fail-help-message"
- hidden>
- $i18n{downloadFailHelp}
- </div>
- <button id="dictionary-download-retry-button">
- $i18n{retryButton}
- </button>
- </div>
- <div id="language-options-ui-notification-bar"
- class="language-options-notification" hidden>
- <div>$i18n{restartRequired}</div>
-<if expr="chromeos">
- <button id="language-options-ui-restart-button">
- $i18n{restartButton}
- </button>
-</if>
- </div>
-</if>
- <div id="language-options-offer-to-translate"
- class="language-options-contents" hidden>
- <div class="checkbox">
- <label>
- <input type="checkbox" id="offer-to-translate-in-this-language">
- <span class="offer-to-translate-label">
- $i18n{offerToTranslateInThisLanguage}
- </span>
- </label>
- </div>
- <span id="cannot-translate-in-this-language" hidden>
- $i18n{cannotTranslateInThisLanguage}
- </span>
- </div>
-<if expr="chromeos">
- <h3>$i18n{inputMethod}</h3>
- <div id="language-options-input-method-template" class="input-method"
- hidden>
- <div class="checkbox">
- <label>
- <input type="checkbox">
- <span class="input-method-label"></span>
- </label>
- </div>
- </div>
- <div id="language-options-input-method-list"
- class="language-options-contents">
- <span id="language-options-input-method-none" hidden>
- $i18n{noInputMethods}
- </span>
- </div>
-</if>
- </div>
- </div>
- <div class="language-options-footer">
-<if expr="chromeos">
- <div>$i18n{switchInputMethodsHint}</div>
- <div>$i18n{selectPreviousInputMethodHint}</div>
- <a is="action-link" id="edit-custom-dictionary-button"
- class="standalone-action-link">
- $i18n{languageDictionaryOverlayTitle}
- </a>
- <div id="language-options-ime-menu-template" class="checkbox" hidden>
- <label>
- <input type="checkbox" id="activate-ime-menu">
- <span>$i18n{activateImeMenu}</span>
- </label>
- </div>
-</if>
-<if expr="not chromeos and not is_macosx">
- <div class="checkbox">
- <label id="enable-spellcheck-container">
- <input id="enable-spellcheck" pref="browser.enable_spellchecking"
- metric="Options_SpellCheck" type="checkbox">
- <span>$i18n{enableSpellCheck}</span>
- </label>
- <a is="action-link" id="edit-custom-dictionary-button" hidden>
- $i18n{languageDictionaryOverlayTitle}
- </a>
- </div>
-</if>
- </div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="language-confirm" class="default-button">$i18n{done}</button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/language_options.js b/chromium/chrome/browser/resources/options/language_options.js
deleted file mode 100644
index 0e85622be11..00000000000
--- a/chromium/chrome/browser/resources/options/language_options.js
+++ /dev/null
@@ -1,1446 +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.
-
-// TODO(kochi): Generalize the notification as a component and put it
-// in js/cr/ui/notification.js .
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
- /** @const */ var LanguageList = options.LanguageList;
- /** @const */ var ThirdPartyImeConfirmOverlay =
- options.ThirdPartyImeConfirmOverlay;
-
- /**
- * Spell check dictionary download status.
- * @type {Enum}
- */
- /** @const*/ var DOWNLOAD_STATUS = {
- IN_PROGRESS: 1,
- FAILED: 2
- };
-
- /**
- * The preference is a boolean that enables/disables spell checking.
- * @type {string}
- * @const
- */
- var ENABLE_SPELL_CHECK_PREF = 'browser.enable_spellchecking';
-
- /**
- * The preference is a CSV string that describes preload engines
- * (i.e. active input methods).
- * @type {string}
- * @const
- */
- var PRELOAD_ENGINES_PREF = 'settings.language.preload_engines';
-
- /**
- * The preference that lists the extension IMEs that are enabled in the
- * language menu.
- * @type {string}
- * @const
- */
- var ENABLED_EXTENSION_IME_PREF = 'settings.language.enabled_extension_imes';
-
- /**
- * The preference that lists the languages which are not translated.
- * @type {string}
- * @const
- */
- var TRANSLATE_BLOCKED_LANGUAGES_PREF = 'translate_blocked_languages';
-
- /**
- * The preference key that is a list of strings that describes the spellcheck
- * dictionary language, like ["en-US", "fr"].
- * @type {string}
- * @const
- */
- var SPELL_CHECK_DICTIONARIES_PREF = 'spellcheck.dictionaries';
-
- /**
- * The preference that indicates if the Translate feature is enabled.
- * @type {string}
- * @const
- */
- var ENABLE_TRANSLATE = 'translate.enabled';
-
- /**
- * The preference is a boolean that activates/deactivates IME menu on shelf.
- * @type {string}
- * @const
- */
- var ACTIVATE_IME_MENU_PREF = 'settings.language.ime_menu_activated';
-
- /////////////////////////////////////////////////////////////////////////////
- // LanguageOptions class:
-
- /**
- * Encapsulated handling of ChromeOS language options page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function LanguageOptions(model) {
- Page.call(this, 'languages',
- loadTimeData.getString('languagePageTabTitle'), 'languagePage');
- }
-
- cr.addSingletonGetter(LanguageOptions);
-
- // Inherit LanguageOptions from Page.
- LanguageOptions.prototype = {
- __proto__: Page.prototype,
-
- /**
- * For recording the prospective language (the next locale after relaunch).
- * @type {?string}
- * @private
- */
- prospectiveUiLanguageCode_: null,
-
- /**
- * Map from language code to spell check dictionary download status for that
- * language.
- * @type {!Object}
- * @private
- */
- spellcheckDictionaryDownloadStatus_: {},
-
- /**
- * Number of times a spell check dictionary download failed.
- * @type {number}
- * @private
- */
- spellcheckDictionaryDownloadFailures_: 0,
-
- /**
- * The list of preload engines, like ['mozc', 'pinyin'].
- * @type {Array}
- * @private
- */
- preloadEngines_: [],
-
- /**
- * The list of extension IMEs that are enabled out of the language menu.
- * @type {Array}
- * @private
- */
- enabledExtensionImes_: [],
-
- /**
- * The list of the languages which is not translated.
- * @type {Array}
- * @private
- */
- translateBlockedLanguages_: [],
-
- /**
- * The list of the languages supported by Translate server
- * @type {Array}
- * @private
- */
- translateSupportedLanguages_: [],
-
- /**
- * The dictionary of currently selected spellcheck dictionary languages,
- * like {"en-US": true, "sl-SI": true}.
- * @type {!Object}
- * @private
- */
- spellCheckLanguages_: {},
-
- /**
- * The map of language code to input method IDs, like:
- * {'ja': ['mozc', 'mozc-jp'], 'zh-CN': ['pinyin'], ...}
- * @type {Object}
- * @private
- */
- languageCodeToInputMethodIdsMap_: {},
-
- /**
- * The value that indicates if Translate feature is enabled or not.
- * @type {boolean}
- * @private
- */
- enableTranslate_: false,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var languageOptionsList = $('language-options-list');
- LanguageList.decorate(languageOptionsList);
-
- languageOptionsList.addEventListener('change',
- this.handleLanguageOptionsListChange_.bind(this));
- languageOptionsList.addEventListener('save',
- this.handleLanguageOptionsListSave_.bind(this));
-
- this.prospectiveUiLanguageCode_ =
- loadTimeData.getString('prospectiveUiLanguageCode');
- this.addEventListener('visibleChange',
- this.handleVisibleChange_.bind(this));
-
- if (cr.isChromeOS) {
- this.initializeInputMethodList_();
- this.initializeLanguageCodeToInputMethodIdsMap_();
- }
-
- var checkbox = $('offer-to-translate-in-this-language');
- checkbox.addEventListener('click',
- this.handleOfferToTranslateCheckboxClick_.bind(this));
-
- Preferences.getInstance().addEventListener(
- TRANSLATE_BLOCKED_LANGUAGES_PREF,
- this.handleTranslateBlockedLanguagesPrefChange_.bind(this));
- Preferences.getInstance().addEventListener(SPELL_CHECK_DICTIONARIES_PREF,
- this.handleSpellCheckDictionariesPrefChange_.bind(this));
- Preferences.getInstance().addEventListener(ENABLE_TRANSLATE,
- this.handleEnableTranslatePrefChange_.bind(this));
- this.translateSupportedLanguages_ = /** @type {Array} */(
- loadTimeData.getValue('translateSupportedLanguages'));
-
- // Set up add button.
- var onclick = function(e) {
- // Add the language without showing the overlay if it's specified in
- // the URL hash (ex. lang_add=ja). Used for automated testing.
- var match = document.location.hash.match(/\blang_add=([\w-]+)/);
- if (match) {
- var addLanguageCode = match[1];
- $('language-options-list').addLanguage(addLanguageCode);
- this.addBlockedLanguage_(addLanguageCode);
- } else {
- PageManager.showPageByName('addLanguage');
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_Languages_Add']);
- }
- };
- $('language-options-add-button').onclick = onclick.bind(this);
-
- if (!cr.isMac) {
- // Set up the button for editing custom spelling dictionary.
- $('edit-custom-dictionary-button').onclick = function(e) {
- PageManager.showPageByName('editDictionary');
- };
- $('dictionary-download-retry-button').onclick = function(e) {
- chrome.send('retryDictionaryDownload',
- [e.currentTarget.languageCode]);
- };
- }
-
- // Listen to add language dialog ok button.
- $('add-language-overlay-ok-button').addEventListener(
- 'click', this.handleAddLanguageOkButtonClick_.bind(this));
-
- if (!(cr.isMac || cr.isChromeOS)) {
- // Handle spell check enable/disable.
- Preferences.getInstance().addEventListener(
- ENABLE_SPELL_CHECK_PREF, this.updateEnableSpellCheck_.bind(this));
- }
-
- // Handle clicks on "Use this language for spell checking" button.
- if (!cr.isMac) {
- $('spellcheck-language-checkbox').addEventListener(
- 'change',
- this.handleSpellCheckLanguageCheckboxClick_.bind(this));
- }
-
- if (cr.isChromeOS) {
- $('language-options-ui-restart-button').onclick = function() {
- chrome.send('uiLanguageRestart');
- };
- }
-
- $('language-confirm').onclick =
- PageManager.closeOverlay.bind(PageManager);
-
- // Public session users cannot change the locale.
- if (cr.isChromeOS && UIAccountTweaks.loggedInAsPublicAccount())
- $('language-options-ui-language-section').hidden = true;
-
- // IME menu (CrOS only).
- if (cr.isChromeOS) {
- // Show the 'activate-ime-menu' checkbox if the flag is tured on.
- if (loadTimeData.getBoolean('enableLanguageOptionsImeMenu'))
- $('language-options-ime-menu-template').hidden = false;
-
- // Updates the initial checked state of the check box.
- Preferences.getInstance().addEventListener(
- ACTIVATE_IME_MENU_PREF, this.updateImeMenuCheckbox_.bind(this));
-
- // Listen to check on 'activate-ime-menu' checkbox.
- var checkboxImeMenu = $('activate-ime-menu');
- checkboxImeMenu.addEventListener('click',
- this.handleActivateImeMenuCheckboxClick_.bind(this));
- }
- },
-
- /**
- * Initializes the input method list.
- */
- initializeInputMethodList_: function() {
- var inputMethodList = $('language-options-input-method-list');
- var inputMethodPrototype = $('language-options-input-method-template');
-
- // Add all input methods, but make all of them invisible here. We'll
- // change the visibility in handleLanguageOptionsListChange_() based
- // on the selected language. Note that we only have less than 100
- // input methods, so creating DOM nodes at once here should be ok.
- this.appendInputMethodElement_(/** @type {!Array} */(
- loadTimeData.getValue('inputMethodList')));
- this.appendComponentExtensionIme_(/** @type {!Array} */(
- loadTimeData.getValue('componentExtensionImeList')));
- this.appendInputMethodElement_(/** @type {!Array} */(
- loadTimeData.getValue('extensionImeList')));
-
- // Listen to pref change once the input method list is initialized.
- Preferences.getInstance().addEventListener(
- PRELOAD_ENGINES_PREF,
- this.handlePreloadEnginesPrefChange_.bind(this));
- Preferences.getInstance().addEventListener(
- ENABLED_EXTENSION_IME_PREF,
- this.handleEnabledExtensionsPrefChange_.bind(this));
- },
-
- /**
- * Appends input method lists based on component extension ime list.
- * @param {!Array} componentExtensionImeList A list of input method
- * descriptors.
- * @private
- */
- appendComponentExtensionIme_: function(componentExtensionImeList) {
- this.appendInputMethodElement_(componentExtensionImeList);
-
- for (var i = 0; i < componentExtensionImeList.length; i++) {
- var inputMethod = componentExtensionImeList[i];
- for (var languageCode in inputMethod.languageCodeSet) {
- if (languageCode in this.languageCodeToInputMethodIdsMap_) {
- this.languageCodeToInputMethodIdsMap_[languageCode].push(
- inputMethod.id);
- } else {
- this.languageCodeToInputMethodIdsMap_[languageCode] =
- [inputMethod.id];
- }
- }
- }
- },
-
- /**
- * Appends input methods into input method list.
- * @param {!Array} inputMethods A list of input method descriptors.
- * @private
- */
- appendInputMethodElement_: function(inputMethods) {
- var inputMethodList = $('language-options-input-method-list');
- var inputMethodTemplate = $('language-options-input-method-template');
-
- for (var i = 0; i < inputMethods.length; i++) {
- var inputMethod = inputMethods[i];
- var element = inputMethodTemplate.cloneNode(true);
- element.id = '';
- element.languageCodeSet = inputMethod.languageCodeSet;
-
- var input = element.querySelector('input');
- input.inputMethodId = inputMethod.id;
- input.imeProvider = inputMethod.extensionName;
- var span = element.querySelector('span');
- span.textContent = inputMethod.displayName;
-
- if (inputMethod.optionsPage) {
- var button = document.createElement('button');
- button.textContent = loadTimeData.getString('configure');
- button.inputMethodId = inputMethod.id;
- button.onclick = function(inputMethodId, e) {
- chrome.send('inputMethodOptionsOpen', [inputMethodId]);
- }.bind(this, inputMethod.id);
- element.appendChild(button);
- }
-
- // Listen to user clicks.
- input.addEventListener('click',
- this.handleCheckboxClick_.bind(this));
- inputMethodList.appendChild(element);
- }
- },
-
- /**
- * Adds a language to the preference 'translate_blocked_languages'. If
- * |langCode| is already added, nothing happens. |langCode| is converted
- * to a Translate language synonym before added.
- * @param {string} langCode A language code like 'en'
- * @private
- */
- addBlockedLanguage_: function(langCode) {
- langCode = this.convertLangCodeForTranslation_(langCode);
- if (this.translateBlockedLanguages_.indexOf(langCode) == -1) {
- this.translateBlockedLanguages_.push(langCode);
- Preferences.setListPref(TRANSLATE_BLOCKED_LANGUAGES_PREF,
- this.translateBlockedLanguages_, true);
- }
- },
-
- /**
- * Removes a language from the preference 'translate_blocked_languages'.
- * If |langCode| doesn't exist in the preference, nothing happens.
- * |langCode| is converted to a Translate language synonym before removed.
- * @param {string} langCode A language code like 'en'
- * @private
- */
- removeBlockedLanguage_: function(langCode) {
- langCode = this.convertLangCodeForTranslation_(langCode);
- if (this.translateBlockedLanguages_.indexOf(langCode) != -1) {
- this.translateBlockedLanguages_ =
- this.translateBlockedLanguages_.filter(
- function(langCodeNotTranslated) {
- return langCodeNotTranslated != langCode;
- });
- Preferences.setListPref(TRANSLATE_BLOCKED_LANGUAGES_PREF,
- this.translateBlockedLanguages_, true);
- }
- },
-
- /**
- * Handles Page's visible property change event.
- * @param {Event} e Property change event.
- * @private
- */
- handleVisibleChange_: function(e) {
- if (this.visible) {
- $('language-options-list').redraw();
- chrome.send('languageOptionsOpen');
- }
- },
-
- /**
- * Handles languageOptionsList's change event.
- * @param {Event} e Change event.
- * @private
- */
- handleLanguageOptionsListChange_: function(e) {
- var languageOptionsList = $('language-options-list');
- var languageCode = languageOptionsList.getSelectedLanguageCode();
-
- // If there's no selection, just return.
- if (!languageCode)
- return;
-
- // Select the language if it's specified in the URL hash (ex. lang=ja).
- // Used for automated testing.
- var match = document.location.hash.match(/\blang=([\w-]+)/);
- if (match) {
- var specifiedLanguageCode = match[1];
- if (languageOptionsList.selectLanguageByCode(specifiedLanguageCode)) {
- languageCode = specifiedLanguageCode;
- }
- }
-
- this.updateOfferToTranslateCheckbox_(languageCode);
-
- if (cr.isWindows || cr.isChromeOS)
- this.updateUiLanguageButton_(languageCode);
-
- this.updateSelectedLanguageName_(languageCode);
-
- if (!cr.isMac)
- this.updateSpellCheckLanguageControls_(languageCode);
-
- if (cr.isChromeOS)
- this.updateInputMethodList_(languageCode);
-
- this.updateLanguageListInAddLanguageOverlay_();
- },
-
- /**
- * Handles languageOptionsList's save event.
- * @param {Event} e Save event.
- * @private
- */
- handleLanguageOptionsListSave_: function(e) {
- if (cr.isChromeOS) {
- // Sort the preload engines per the saved languages before save.
- this.preloadEngines_ = this.sortPreloadEngines_(this.preloadEngines_);
- this.savePreloadEnginesPref_();
- }
- },
-
- /**
- * Sorts preloadEngines_ by languageOptionsList's order.
- * @param {Array} preloadEngines List of preload engines.
- * @return {Array} Returns sorted preloadEngines.
- * @private
- */
- sortPreloadEngines_: function(preloadEngines) {
- // For instance, suppose we have two languages and associated input
- // methods:
- //
- // - Korean: hangul
- // - Chinese: pinyin
- //
- // The preloadEngines preference should look like "hangul,pinyin".
- // If the user reverse the order, the preference should be reorderd
- // to "pinyin,hangul".
- var languageOptionsList = $('language-options-list');
- var languageCodes = languageOptionsList.getLanguageCodes();
-
- // Convert the list into a dictonary for simpler lookup.
- var preloadEngineSet = {};
- for (var i = 0; i < preloadEngines.length; i++) {
- preloadEngineSet[preloadEngines[i]] = true;
- }
-
- // Create the new preload engine list per the language codes.
- var newPreloadEngines = [];
- for (var i = 0; i < languageCodes.length; i++) {
- var languageCode = languageCodes[i];
- var inputMethodIds = this.languageCodeToInputMethodIdsMap_[
- languageCode];
- if (!inputMethodIds)
- continue;
-
- // Check if we have active input methods associated with the language.
- for (var j = 0; j < inputMethodIds.length; j++) {
- var inputMethodId = inputMethodIds[j];
- if (inputMethodId in preloadEngineSet) {
- // If we have, add it to the new engine list.
- newPreloadEngines.push(inputMethodId);
- // And delete it from the set. This is necessary as one input
- // method can be associated with more than one language thus
- // we should avoid having duplicates in the new list.
- delete preloadEngineSet[inputMethodId];
- }
- }
- }
-
- return newPreloadEngines;
- },
-
- /**
- * Initializes the map of language code to input method IDs.
- * @private
- */
- initializeLanguageCodeToInputMethodIdsMap_: function() {
- var inputMethodList = loadTimeData.getValue('inputMethodList');
- for (var i = 0; i < inputMethodList.length; i++) {
- var inputMethod = inputMethodList[i];
- for (var languageCode in inputMethod.languageCodeSet) {
- if (languageCode in this.languageCodeToInputMethodIdsMap_) {
- this.languageCodeToInputMethodIdsMap_[languageCode].push(
- inputMethod.id);
- } else {
- this.languageCodeToInputMethodIdsMap_[languageCode] =
- [inputMethod.id];
- }
- }
- }
- },
-
- /**
- * Updates the currently selected language name.
- * @param {string} languageCode Language code (ex. "fr").
- * @private
- */
- updateSelectedLanguageName_: function(languageCode) {
- var languageInfo = LanguageList.getLanguageInfoFromLanguageCode(
- languageCode);
- var languageDisplayName = languageInfo.displayName;
- var languageNativeDisplayName = languageInfo.nativeDisplayName;
- var textDirection = languageInfo.textDirection;
-
- // If the native name is different, add it.
- if (languageDisplayName != languageNativeDisplayName) {
- languageDisplayName += ' - ' + languageNativeDisplayName;
- }
-
- // Update the currently selected language name.
- var languageName = $('language-options-language-name');
- languageName.textContent = languageDisplayName;
- languageName.dir = textDirection;
- },
-
- /**
- * Updates the UI language button.
- * @param {string} languageCode Language code (ex. "fr").
- * @private
- */
- updateUiLanguageButton_: function(languageCode) {
- var uiLanguageButton = $('language-options-ui-language-button');
- var uiLanguageMessage = $('language-options-ui-language-message');
- var uiLanguageNotification = $('language-options-ui-notification-bar');
-
- // Remove the event listener and add it back if useful.
- uiLanguageButton.onclick = null;
-
- // Unhide the language button every time, as it could've been previously
- // hidden by a language change.
- uiLanguageButton.hidden = false;
-
- // Hide the controlled setting indicator.
- var uiLanguageIndicator = document.querySelector(
- '.language-options-contents .controlled-setting-indicator');
- uiLanguageIndicator.removeAttribute('controlled-by');
-
- if (languageCode == this.prospectiveUiLanguageCode_) {
- uiLanguageMessage.textContent =
- loadTimeData.getString('isDisplayedInThisLanguage');
- showMutuallyExclusiveNodes(
- [uiLanguageButton, uiLanguageMessage, uiLanguageNotification], 1);
- } else if (languageCode in loadTimeData.getValue('uiLanguageCodeSet')) {
- if (cr.isChromeOS && UIAccountTweaks.loggedInAsGuest()) {
- // In the guest mode for ChromeOS, changing UI language does not make
- // sense because it does not take effect after browser restart.
- uiLanguageButton.hidden = true;
- uiLanguageMessage.hidden = true;
- } else {
- uiLanguageButton.textContent =
- loadTimeData.getString('displayInThisLanguage');
-
- if (loadTimeData.valueExists('secondaryUser') &&
- loadTimeData.getBoolean('secondaryUser')) {
- uiLanguageButton.disabled = true;
- uiLanguageIndicator.setAttribute('controlled-by', 'shared');
- } else {
- uiLanguageButton.onclick = function(e) {
- chrome.send('uiLanguageChange', [languageCode]);
- };
- }
- showMutuallyExclusiveNodes(
- [uiLanguageButton, uiLanguageMessage, uiLanguageNotification], 0);
- }
- } else {
- uiLanguageMessage.textContent =
- loadTimeData.getString('cannotBeDisplayedInThisLanguage');
- showMutuallyExclusiveNodes(
- [uiLanguageButton, uiLanguageMessage, uiLanguageNotification], 1);
- }
- },
-
- /**
- * Updates the spell check language button/checkbox, dictionary download
- * dialog, and the "Enable spell checking" checkbox.
- * @param {string} languageCode Language code (ex. "fr").
- * @private
- */
- updateSpellCheckLanguageControls_: function(languageCode) {
- assert(languageCode);
- var spellCheckLanguageSection = $('language-options-spellcheck');
- var spellCheckLanguageCheckboxContainer =
- $('spellcheck-language-checkbox-container');
- var spellCheckLanguageCheckbox = $('spellcheck-language-checkbox');
- var spellCheckLanguageMessage = $('spellcheck-language-message');
- var dictionaryDownloadInProgress =
- $('language-options-dictionary-downloading-message');
- var dictionaryDownloadFailed =
- $('language-options-dictionary-download-failed-message');
- var dictionaryDownloadFailHelp =
- $('language-options-dictionary-download-fail-help-message');
-
- spellCheckLanguageSection.hidden = false;
- spellCheckLanguageMessage.hidden = true;
- spellCheckLanguageCheckboxContainer.hidden = true;
- dictionaryDownloadInProgress.hidden = true;
- dictionaryDownloadFailed.hidden = true;
- dictionaryDownloadFailHelp.hidden = true;
- spellCheckLanguageCheckbox.checked = false;
-
- var canBeUsedForSpellchecking =
- languageCode in loadTimeData.getValue('spellCheckLanguageCodeSet');
-
- if (!canBeUsedForSpellchecking) {
- spellCheckLanguageMessage.textContent =
- loadTimeData.getString('cannotBeUsedForSpellChecking');
- spellCheckLanguageMessage.hidden = false;
- return;
- }
-
- var isUsedForSpellchecking = languageCode in this.spellCheckLanguages_;
-
- spellCheckLanguageCheckbox.languageCode = languageCode;
- spellCheckLanguageCheckbox.checked = isUsedForSpellchecking;
- spellCheckLanguageCheckboxContainer.hidden = false;
-
- switch (this.spellcheckDictionaryDownloadStatus_[languageCode]) {
- case DOWNLOAD_STATUS.IN_PROGRESS:
- dictionaryDownloadInProgress.hidden = false;
- break;
- case DOWNLOAD_STATUS.FAILED:
- showMutuallyExclusiveNodes(
- [spellCheckLanguageSection, dictionaryDownloadFailed], 1);
- if (this.spellcheckDictionaryDownloadFailures_ > 1)
- dictionaryDownloadFailHelp.hidden = false;
- $('dictionary-download-retry-button').languageCode = languageCode;
- break;
- }
-
- var areNoLanguagesSelected =
- Object.keys(this.spellCheckLanguages_).length == 0;
- var usesSystemSpellchecker = !$('enable-spellcheck-container');
- var isSpellcheckingEnabled = usesSystemSpellchecker ||
- $('enable-spellcheck').checked;
- $('edit-custom-dictionary-button').hidden =
- areNoLanguagesSelected || !isSpellcheckingEnabled;
- },
-
- /**
- * Updates the checkbox for stopping translation.
- * @param {string} languageCode Language code (ex. "fr").
- * @private
- */
- updateOfferToTranslateCheckbox_: function(languageCode) {
- var div = $('language-options-offer-to-translate');
-
- // Translation server supports Chinese (Transitional) and Chinese
- // (Simplified) but not 'general' Chinese. To avoid ambiguity, we don't
- // show this preference when general Chinese is selected.
- if (languageCode != 'zh') {
- div.hidden = false;
- } else {
- div.hidden = true;
- return;
- }
-
- var offerToTranslate = div.querySelector('div');
- var cannotTranslate = $('cannot-translate-in-this-language');
- var nodes = [offerToTranslate, cannotTranslate];
-
- var convertedLangCode = this.convertLangCodeForTranslation_(languageCode);
- if (this.translateSupportedLanguages_.indexOf(convertedLangCode) != -1) {
- showMutuallyExclusiveNodes(nodes, 0);
- } else {
- showMutuallyExclusiveNodes(nodes, 1);
- return;
- }
-
- var checkbox = $('offer-to-translate-in-this-language');
-
- if (!this.enableTranslate_) {
- checkbox.disabled = true;
- checkbox.checked = false;
- return;
- }
-
- // If the language corresponds to the default target language (in most
- // cases, the user's locale language), "Offer to translate" checkbox
- // should be always unchecked.
- var defaultTargetLanguage =
- loadTimeData.getString('defaultTargetLanguage');
- if (convertedLangCode == defaultTargetLanguage) {
- checkbox.disabled = true;
- checkbox.checked = false;
- return;
- }
-
- checkbox.disabled = false;
-
- var blockedLanguages = this.translateBlockedLanguages_;
- var checked = blockedLanguages.indexOf(convertedLangCode) == -1;
- checkbox.checked = checked;
- },
-
- /**
- * Updates the input method list.
- * @param {string} languageCode Language code (ex. "fr").
- * @private
- */
- updateInputMethodList_: function(languageCode) {
- // Give one of the checkboxes or buttons focus, if it's specified in the
- // URL hash (ex. focus=mozc). Used for automated testing.
- var focusInputMethodId = -1;
- var match = document.location.hash.match(/\bfocus=([\w:-]+)\b/);
- if (match) {
- focusInputMethodId = match[1];
- }
- // Change the visibility of the input method list. Input methods that
- // matches |languageCode| will become visible.
- var inputMethodList = $('language-options-input-method-list');
- var methods = inputMethodList.querySelectorAll('.input-method');
- for (var i = 0; i < methods.length; i++) {
- var method = methods[i];
- if (languageCode in method.languageCodeSet) {
- method.hidden = false;
- var input = method.querySelector('input');
- // Give it focus if the ID matches.
- if (input.inputMethodId == focusInputMethodId) {
- input.focus();
- }
- } else {
- method.hidden = true;
- }
- }
-
- $('language-options-input-method-none').hidden =
- (languageCode in this.languageCodeToInputMethodIdsMap_);
-
- if (focusInputMethodId == 'add') {
- $('language-options-add-button').focus();
- }
- },
-
- /**
- * Updates the language list in the add language overlay.
- * @private
- */
- updateLanguageListInAddLanguageOverlay_: function() {
- // Change the visibility of the language list in the add language
- // overlay. Languages that are already active will become invisible,
- // so that users don't add the same language twice.
- var languageOptionsList = $('language-options-list');
- var languageCodes = languageOptionsList.getLanguageCodes();
- var languageCodeSet = {};
- for (var i = 0; i < languageCodes.length; i++) {
- languageCodeSet[languageCodes[i]] = true;
- }
-
- var addLanguageList = $('add-language-overlay-language-list');
- var options = addLanguageList.querySelectorAll('option');
- assert(options.length > 0);
- var selectedFirstItem = false;
- for (var i = 0; i < options.length; i++) {
- var option = options[i];
- option.hidden = option.value in languageCodeSet;
- if (!option.hidden && !selectedFirstItem) {
- // Select first visible item, otherwise previously selected hidden
- // item will be selected by default at the next time.
- option.selected = true;
- selectedFirstItem = true;
- }
- }
- },
-
- /**
- * Handles preloadEnginesPref change.
- * @param {Event} e Change event.
- * @private
- */
- handlePreloadEnginesPrefChange_: function(e) {
- var value = e.value.value;
- this.preloadEngines_ = this.filterBadPreloadEngines_(value.split(','));
- this.updateCheckboxesFromPreloadEngines_();
- $('language-options-list').updateDeletable();
- },
-
- /**
- * Handles enabledExtensionImePref change.
- * @param {Event} e Change event.
- * @private
- */
- handleEnabledExtensionsPrefChange_: function(e) {
- var value = e.value.value;
- this.enabledExtensionImes_ = value.split(',');
- this.updateCheckboxesFromEnabledExtensions_();
- },
-
- /**
- * Handles offer-to-translate checkbox's click event.
- * @param {Event} e Click event.
- * @private
- */
- handleOfferToTranslateCheckboxClick_: function(e) {
- var checkbox = e.target;
- var checked = checkbox.checked;
-
- var languageOptionsList = $('language-options-list');
- var selectedLanguageCode = languageOptionsList.getSelectedLanguageCode();
-
- if (checked)
- this.removeBlockedLanguage_(selectedLanguageCode);
- else
- this.addBlockedLanguage_(selectedLanguageCode);
- },
-
- /**
- * Handles input method checkbox's click event.
- * @param {Event} e Click event.
- * @private
- */
- handleCheckboxClick_: function(e) {
- var checkbox = assertInstanceof(e.target, Element);
-
- // Third party IMEs require additional confirmation prior to enabling due
- // to privacy risk.
- if (/^_ext_ime_/.test(checkbox.inputMethodId) && checkbox.checked) {
- var confirmationCallback = this.handleCheckboxUpdate_.bind(this,
- checkbox);
- var cancellationCallback = function() {
- checkbox.checked = false;
- };
- ThirdPartyImeConfirmOverlay.showConfirmationDialog({
- extension: checkbox.imeProvider,
- confirm: confirmationCallback,
- cancel: cancellationCallback
- });
- } else {
- this.handleCheckboxUpdate_(checkbox);
- }
-
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_Languages_InputMethodCheckbox' +
- (checkbox.checked ? '_Enable' : '_Disable')]);
- },
-
- /**
- * Updates active IMEs based on change in state of a checkbox for an input
- * method.
- * @param {!Element} checkbox Updated checkbox element.
- * @private
- */
- handleCheckboxUpdate_: function(checkbox) {
- if (checkbox.inputMethodId.match(/^_ext_ime_/)) {
- this.updateEnabledExtensionsFromCheckboxes_();
- this.saveEnabledExtensionPref_();
- return;
- }
- if (this.preloadEngines_.length == 1 && !checkbox.checked) {
- // Don't allow disabling the last input method.
- this.showNotification_(
- loadTimeData.getString('pleaseAddAnotherInputMethod'),
- loadTimeData.getString('okButton'));
- checkbox.checked = true;
- return;
- }
- if (checkbox.checked) {
- chrome.send('inputMethodEnable', [checkbox.inputMethodId]);
- } else {
- chrome.send('inputMethodDisable', [checkbox.inputMethodId]);
- }
- this.updatePreloadEnginesFromCheckboxes_();
- this.preloadEngines_ = this.sortPreloadEngines_(this.preloadEngines_);
- this.savePreloadEnginesPref_();
- },
-
- /**
- * Handles clicks on the "OK" button of the "Add language" dialog.
- * @param {Event} e Click event.
- * @private
- */
- handleAddLanguageOkButtonClick_: function(e) {
- var languagesSelect = $('add-language-overlay-language-list');
- var selectedIndex = languagesSelect.selectedIndex;
- if (selectedIndex >= 0) {
- var selection = languagesSelect.options[selectedIndex];
- var langCode = String(selection.value);
- $('language-options-list').addLanguage(langCode);
- this.addBlockedLanguage_(langCode);
- PageManager.closeOverlay();
- }
- },
-
- /**
- * Checks if languageCode is deletable or not.
- * @param {string} languageCode the languageCode to check for deletability.
- */
- languageIsDeletable: function(languageCode) {
- // Don't allow removing the language if it's a UI language.
- if (languageCode == this.prospectiveUiLanguageCode_)
- return false;
- return (!cr.isChromeOS ||
- this.canDeleteLanguage_(languageCode));
- },
-
- /**
- * Handles browser.enable_spellchecking change.
- * @param {Event} e Change event.
- * @private
- */
- updateEnableSpellCheck_: function(e) {
- var value = !$('enable-spellcheck').checked;
- var languageControl = $('spellcheck-language-checkbox');
- languageControl.disabled = value;
- if (!cr.isMac)
- $('edit-custom-dictionary-button').hidden = value;
- },
-
- /**
- * Handles translateBlockedLanguagesPref change.
- * @param {Event} e Change event.
- * @private
- */
- handleTranslateBlockedLanguagesPrefChange_: function(e) {
- this.translateBlockedLanguages_ = e.value.value;
- this.updateOfferToTranslateCheckbox_(
- $('language-options-list').getSelectedLanguageCode());
- },
-
- /**
- * Updates spellcheck dictionary UI (checkboxes, buttons, and labels) when
- * preferences change.
- * @param {Event} e Preference change event where e.value.value is the list
- * of languages currently used for spellchecking.
- * @private
- */
- handleSpellCheckDictionariesPrefChange_: function(e) {
- if (cr.isMac)
- return;
-
- var languages = e.value.value;
- this.spellCheckLanguages_ = {};
- for (var i = 0; i < languages.length; i++) {
- this.spellCheckLanguages_[languages[i]] = true;
- }
- this.updateSpellCheckLanguageControls_(
- $('language-options-list').getSelectedLanguageCode());
- },
-
- /**
- * Handles translate.enabled change.
- * @param {Event} e Change event.
- * @private
- */
- handleEnableTranslatePrefChange_: function(e) {
- var enabled = e.value.value;
- this.enableTranslate_ = enabled;
- this.updateOfferToTranslateCheckbox_(
- $('language-options-list').getSelectedLanguageCode());
- },
-
- /**
- * Updates the spellcheck.dictionaries preference with the currently
- * selected language codes.
- * @param {Event} e Click event. e.currentTarget represents the "Use this
- * language for spellchecking" checkbox.
- * @private
- */
- handleSpellCheckLanguageCheckboxClick_: function(e) {
- var languageCode = e.currentTarget.languageCode;
-
- if (e.currentTarget.checked)
- this.spellCheckLanguages_[languageCode] = true;
- else
- delete this.spellCheckLanguages_[languageCode];
-
- var languageCodes = Object.keys(this.spellCheckLanguages_);
- Preferences.setListPref(SPELL_CHECK_DICTIONARIES_PREF,
- languageCodes, true);
-
- // The spellCheckLanguageChange argument is only used for logging.
- chrome.send('spellCheckLanguageChange', [languageCodes.join(',')]);
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_Languages_SpellCheck']);
- },
-
- /**
- * Checks whether it's possible to remove the language specified by
- * languageCode and returns true if possible. This function returns false
- * if the removal causes the number of preload engines to be zero.
- *
- * @param {string} languageCode Language code (ex. "fr").
- * @return {boolean} Returns true on success.
- * @private
- */
- canDeleteLanguage_: function(languageCode) {
- // First create the set of engines to be removed from input methods
- // associated with the language code.
- var enginesToBeRemovedSet = {};
- var inputMethodIds = this.languageCodeToInputMethodIdsMap_[languageCode];
-
- // If this language doesn't have any input methods, it can be deleted.
- if (!inputMethodIds)
- return true;
-
- for (var i = 0; i < inputMethodIds.length; i++) {
- enginesToBeRemovedSet[inputMethodIds[i]] = true;
- }
-
- // Then eliminate engines that are also used for other active languages.
- // For instance, if "xkb:us::eng" is used for both English and Filipino.
- var languageCodes = $('language-options-list').getLanguageCodes();
- for (var i = 0; i < languageCodes.length; i++) {
- // Skip the target language code.
- if (languageCodes[i] == languageCode) {
- continue;
- }
- // Check if input methods used in this language are included in
- // enginesToBeRemovedSet. If so, eliminate these from the set, so
- // we don't remove this time.
- var inputMethodIdsForAnotherLanguage =
- this.languageCodeToInputMethodIdsMap_[languageCodes[i]];
- if (!inputMethodIdsForAnotherLanguage)
- continue;
-
- for (var j = 0; j < inputMethodIdsForAnotherLanguage.length; j++) {
- var inputMethodId = inputMethodIdsForAnotherLanguage[j];
- if (inputMethodId in enginesToBeRemovedSet) {
- delete enginesToBeRemovedSet[inputMethodId];
- }
- }
- }
-
- // Update the preload engine list with the to-be-removed set.
- var newPreloadEngines = [];
- for (var i = 0; i < this.preloadEngines_.length; i++) {
- if (!(this.preloadEngines_[i] in enginesToBeRemovedSet)) {
- newPreloadEngines.push(this.preloadEngines_[i]);
- }
- }
- // Don't allow this operation if it causes the number of preload
- // engines to be zero.
- return (newPreloadEngines.length > 0);
- },
-
- /**
- * Saves the enabled extension preference.
- * @private
- */
- saveEnabledExtensionPref_: function() {
- Preferences.setStringPref(ENABLED_EXTENSION_IME_PREF,
- this.enabledExtensionImes_.join(','), true);
- },
-
- /**
- * Updates the checkboxes in the input method list from the enabled
- * extensions preference.
- * @private
- */
- updateCheckboxesFromEnabledExtensions_: function() {
- // Convert the list into a dictonary for simpler lookup.
- var dictionary = {};
- for (var i = 0; i < this.enabledExtensionImes_.length; i++)
- dictionary[this.enabledExtensionImes_[i]] = true;
-
- var inputMethodList = $('language-options-input-method-list');
- var checkboxes = inputMethodList.querySelectorAll('input');
- for (var i = 0; i < checkboxes.length; i++) {
- if (checkboxes[i].inputMethodId.match(/^_ext_ime_/))
- checkboxes[i].checked = (checkboxes[i].inputMethodId in dictionary);
- }
- var configureButtons = inputMethodList.querySelectorAll('button');
- for (var i = 0; i < configureButtons.length; i++) {
- if (configureButtons[i].inputMethodId.match(/^_ext_ime_/)) {
- configureButtons[i].hidden =
- !(configureButtons[i].inputMethodId in dictionary);
- }
- }
- },
-
- /**
- * Updates the enabled extensions preference from the checkboxes in the
- * input method list.
- * @private
- */
- updateEnabledExtensionsFromCheckboxes_: function() {
- this.enabledExtensionImes_ = [];
- var inputMethodList = $('language-options-input-method-list');
- var checkboxes = inputMethodList.querySelectorAll('input');
- for (var i = 0; i < checkboxes.length; i++) {
- if (checkboxes[i].inputMethodId.match(/^_ext_ime_/)) {
- if (checkboxes[i].checked)
- this.enabledExtensionImes_.push(checkboxes[i].inputMethodId);
- }
- }
- },
-
- /**
- * Saves the preload engines preference.
- * @private
- */
- savePreloadEnginesPref_: function() {
- Preferences.setStringPref(PRELOAD_ENGINES_PREF,
- this.preloadEngines_.join(','), true);
- },
-
- /**
- * Updates the checkboxes in the input method list from the preload
- * engines preference.
- * @private
- */
- updateCheckboxesFromPreloadEngines_: function() {
- // Convert the list into a dictonary for simpler lookup.
- var dictionary = {};
- for (var i = 0; i < this.preloadEngines_.length; i++) {
- dictionary[this.preloadEngines_[i]] = true;
- }
-
- var inputMethodList = $('language-options-input-method-list');
- var checkboxes = inputMethodList.querySelectorAll('input');
- for (var i = 0; i < checkboxes.length; i++) {
- if (!checkboxes[i].inputMethodId.match(/^_ext_ime_/))
- checkboxes[i].checked = (checkboxes[i].inputMethodId in dictionary);
- }
- var configureButtons = inputMethodList.querySelectorAll('button');
- for (var i = 0; i < configureButtons.length; i++) {
- if (!configureButtons[i].inputMethodId.match(/^_ext_ime_/)) {
- configureButtons[i].hidden =
- !(configureButtons[i].inputMethodId in dictionary);
- }
- }
- },
-
- /**
- * Updates the preload engines preference from the checkboxes in the
- * input method list.
- * @private
- */
- updatePreloadEnginesFromCheckboxes_: function() {
- this.preloadEngines_ = [];
- var inputMethodList = $('language-options-input-method-list');
- var checkboxes = inputMethodList.querySelectorAll('input');
- for (var i = 0; i < checkboxes.length; i++) {
- if (!checkboxes[i].inputMethodId.match(/^_ext_ime_/)) {
- if (checkboxes[i].checked)
- this.preloadEngines_.push(checkboxes[i].inputMethodId);
- }
- }
- var languageOptionsList = $('language-options-list');
- languageOptionsList.updateDeletable();
- },
-
- /**
- * Filters bad preload engines in case bad preload engines are
- * stored in the preference. Removes duplicates as well.
- * @param {Array} preloadEngines List of preload engines.
- * @private
- */
- filterBadPreloadEngines_: function(preloadEngines) {
- // Convert the list into a dictonary for simpler lookup.
- var dictionary = {};
- var list = loadTimeData.getValue('inputMethodList');
- for (var i = 0; i < list.length; i++) {
- dictionary[list[i].id] = true;
- }
-
- var enabledPreloadEngines = [];
- var seen = {};
- for (var i = 0; i < preloadEngines.length; i++) {
- // Check if the preload engine is present in the
- // dictionary, and not duplicate. Otherwise, skip it.
- // Component Extension IME should be handled same as preloadEngines and
- // "_comp_" is the special prefix of its ID.
- if ((preloadEngines[i] in dictionary && !(preloadEngines[i] in seen)) ||
- /^_comp_/.test(preloadEngines[i])) {
- enabledPreloadEngines.push(preloadEngines[i]);
- seen[preloadEngines[i]] = true;
- }
- }
- return enabledPreloadEngines;
- },
-
- // TODO(kochi): This is an adapted copy from new_tab.js.
- // If this will go as final UI, refactor this to share the component with
- // new new tab page.
- /**
- * @private
- */
- notificationTimeout_: null,
-
- /**
- * Shows notification.
- * @param {string} text
- * @param {string} actionText
- * @param {number=} opt_delay
- * @private
- */
- showNotification_: function(text, actionText, opt_delay) {
- var notificationElement = $('notification');
- var actionLink = notificationElement.querySelector('.link-color');
- var delay = opt_delay || 10000;
-
- function show() {
- window.clearTimeout(this.notificationTimeout_);
- notificationElement.classList.add('show');
- document.body.classList.add('notification-shown');
- }
-
- function hide() {
- window.clearTimeout(this.notificationTimeout_);
- notificationElement.classList.remove('show');
- document.body.classList.remove('notification-shown');
- // Prevent tabbing to the hidden link.
- actionLink.tabIndex = -1;
- // Setting tabIndex to -1 only prevents future tabbing to it. If,
- // however, the user switches window or a tab and then moves back to
- // this tab the element may gain focus. We therefore make sure that we
- // blur the element so that the element focus is not restored when
- // coming back to this window.
- actionLink.blur();
- }
-
- function delayedHide() {
- this.notificationTimeout_ = window.setTimeout(hide, delay);
- }
-
- notificationElement.firstElementChild.textContent = text;
- actionLink.textContent = actionText;
-
- actionLink.onclick = hide;
- actionLink.onkeydown = function(e) {
- if (e.key == 'Enter') {
- hide();
- }
- };
- notificationElement.onmouseover = show;
- notificationElement.onmouseout = delayedHide;
- actionLink.onfocus = show;
- actionLink.onblur = delayedHide;
- // Enable tabbing to the link now that it is shown.
- actionLink.tabIndex = 0;
-
- show();
- delayedHide();
- },
-
- /**
- * Chrome callback for when the UI language preference is saved.
- * @param {string} languageCode The newly selected language to use.
- * @private
- */
- uiLanguageSaved_: function(languageCode) {
- this.prospectiveUiLanguageCode_ = languageCode;
-
- // If the user is no longer on the same language code, ignore.
- if ($('language-options-list').getSelectedLanguageCode() != languageCode)
- return;
-
- // Special case for when a user changes to a different language, and
- // changes back to the same language without having restarted Chrome or
- // logged in/out of ChromeOS.
- if (languageCode == loadTimeData.getString('currentUiLanguageCode')) {
- this.updateUiLanguageButton_(languageCode);
- return;
- }
-
- // Otherwise, show a notification telling the user that their changes will
- // only take effect after restart.
- showMutuallyExclusiveNodes([$('language-options-ui-language-button'),
- $('language-options-ui-notification-bar')],
- 1);
- },
-
- /**
- * A handler for when dictionary for |languageCode| begins downloading.
- * @param {string} languageCode The language of the dictionary that just
- * began downloading.
- * @private
- */
- onDictionaryDownloadBegin_: function(languageCode) {
- this.spellcheckDictionaryDownloadStatus_[languageCode] =
- DOWNLOAD_STATUS.IN_PROGRESS;
- if (!cr.isMac &&
- languageCode ==
- $('language-options-list').getSelectedLanguageCode()) {
- this.updateSpellCheckLanguageControls_(languageCode);
- }
- },
-
- /**
- * A handler for when dictionary for |languageCode| successfully downloaded.
- * @param {string} languageCode The language of the dictionary that
- * succeeded downloading.
- * @private
- */
- onDictionaryDownloadSuccess_: function(languageCode) {
- delete this.spellcheckDictionaryDownloadStatus_[languageCode];
- this.spellcheckDictionaryDownloadFailures_ = 0;
- if (!cr.isMac &&
- languageCode ==
- $('language-options-list').getSelectedLanguageCode()) {
- this.updateSpellCheckLanguageControls_(languageCode);
- }
- },
-
- /**
- * A handler for when dictionary for |languageCode| fails to download.
- * @param {string} languageCode The language of the dictionary that failed
- * to download.
- * @private
- */
- onDictionaryDownloadFailure_: function(languageCode) {
- this.spellcheckDictionaryDownloadStatus_[languageCode] =
- DOWNLOAD_STATUS.FAILED;
- this.spellcheckDictionaryDownloadFailures_++;
- if (!cr.isMac &&
- languageCode ==
- $('language-options-list').getSelectedLanguageCode()) {
- this.updateSpellCheckLanguageControls_(languageCode);
- }
- },
-
- /**
- * Converts the language code for Translation. There are some differences
- * between the language set for Translation and that for Accept-Language.
- * @param {string} languageCode The language code like 'fr'.
- * @return {string} The converted language code.
- * @private
- */
- convertLangCodeForTranslation_: function(languageCode) {
- var tokens = languageCode.split('-');
- var main = tokens[0];
-
- // See also: components/translate/core/browser/common/translate_util.cc
- var synonyms = {
- 'nb': 'no',
- 'he': 'iw',
- 'jv': 'jw',
- 'fil': 'tl',
- 'zh-HK': 'zh-TW',
- 'zh-MO': 'zh-TW',
- 'zh-SG': 'zh-CN',
- };
-
- if (main in synonyms) {
- return synonyms[main];
- } else if (main == 'zh') {
- // In Translation, general Chinese is not used, and the sub code is
- // necessary as a language code for Translate server.
- return languageCode;
- }
-
- return main;
- },
-
- /**
- * Handles activate-ime-menu checkbox's click event.
- * @param {Event} e Click event.
- * @private
- */
- handleActivateImeMenuCheckboxClick_: function(e) {
- if (cr.isChromeOS) {
- var checkbox = e.target;
- Preferences.setBooleanPref(ACTIVATE_IME_MENU_PREF,
- checkbox.checked, true);
- }
- },
-
- /**
- * Updates the activate-ime-menu check box's checked state.
- * @param {Event} e Change event.
- * @private
- */
- updateImeMenuCheckbox_: function(e) {
- $('activate-ime-menu').checked = e.value.value;
- },
- };
-
- /**
- * Shows the node at |index| in |nodes|, hides all others.
- * @param {Array<HTMLElement>} nodes The nodes to be shown or hidden.
- * @param {number} index The index of |nodes| to show.
- */
- function showMutuallyExclusiveNodes(nodes, index) {
- assert(index >= 0 && index < nodes.length);
- for (var i = 0; i < nodes.length; ++i) {
- assert(nodes[i] instanceof HTMLElement); // TODO(dbeam): Ignore null?
- nodes[i].hidden = i != index;
- }
- }
-
- LanguageOptions.uiLanguageSaved = function(languageCode) {
- LanguageOptions.getInstance().uiLanguageSaved_(languageCode);
- };
-
- LanguageOptions.onDictionaryDownloadBegin = function(languageCode) {
- LanguageOptions.getInstance().onDictionaryDownloadBegin_(languageCode);
- };
-
- LanguageOptions.onDictionaryDownloadSuccess = function(languageCode) {
- LanguageOptions.getInstance().onDictionaryDownloadSuccess_(languageCode);
- };
-
- LanguageOptions.onDictionaryDownloadFailure = function(languageCode) {
- LanguageOptions.getInstance().onDictionaryDownloadFailure_(languageCode);
- };
-
- // Export
- return {
- LanguageOptions: LanguageOptions
- };
-});
diff --git a/chromium/chrome/browser/resources/options/manage_profile_overlay.css b/chromium/chrome/browser/resources/options/manage_profile_overlay.css
deleted file mode 100644
index f8a022ec0aa..00000000000
--- a/chromium/chrome/browser/resources/options/manage_profile_overlay.css
+++ /dev/null
@@ -1,163 +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. */
-
-#manage-profile-overlay {
- width: 616px;
-}
-
-.profile-icon-grid-item {
- height: 31px;
- margin: 2px 4px;
- padding: 4px;
- width: 38px;
-}
-
-.profile-icon {
- height: 31px;
- width: 38px;
-}
-
-#create-profile-name-input-container,
-#manage-profile-name-input-container {
- margin-top: 5px;
-}
-
-#create-profile-name-input-container {
- margin-bottom: 5px;
-}
-
-#create-profile-name,
-#manage-profile-name {
- margin-left: 10px;
-}
-
-#create-profile-name:invalid,
-#manage-profile-name:invalid {
- background-color: pink;
-}
-
-#disconnect-managed-profile-domain-name {
- font-weight: bold;
-}
-
-#disconnect-managed-profile-domain-information {
- background-color: #f0f0f0;
- padding: 14px 0 14px 17px;
-}
-
-#disconnect-managed-profile-message {
- padding-top: 9px;
-}
-
-#create-profile-error-bubble,
-#manage-profile-error-bubble {
- background-color: rgb(238, 185, 57);
- border-radius: 4px;
- font-weight: bold;
- margin-left: auto;
- margin-right: auto;
- max-height: 50px;
- overflow: hidden;
- padding: 10px 10px;
- text-align: center;
- transition: max-height 200ms, padding 200ms;
- width: 80%;
-}
-
-html[dir='ltr'] #create-profile-error-bubble {
- margin-left: 20px;
- width: 90%;
-}
-
-html[dir='rtl'] #create-profile-error-bubble {
- margin-right: 20px;
- width: 90%;
-}
-
-#create-profile-error-bubble[hidden],
-#manage-profile-error-bubble[hidden] {
- display: block !important;
- max-height: 0;
- padding: 0 10px;
-}
-
-#create-profile-icon-grid,
-#manage-profile-icon-grid {
- background-color: rgba(255, 255, 255, 0.75);
- padding: 2px;
-}
-
-:-webkit-any(#create-profile-content, #manage-profile-content) >
- :not(:last-child) {
- margin-bottom: 10px;
-}
-
-:-webkit-any(#create-profile-content, #manage-profile-content) >
- :not(:first-child) {
- margin-top: 10px;
-}
-
-:-webkit-any(#create-profile-content, #manage-profile-content) >
- .name-input-container {
- margin-top: 5px;
-}
-
-:-webkit-any(#create-profile-content, #manage-profile-content) >
- .name-label-container {
- margin-bottom: 5px;
-}
-
-#create-profile-content {
- padding-bottom: 0;
-}
-
-.action-area-shortcut-container {
- -webkit-box-flex: 1;
-}
-
-/* Proper spacing for the buttons. */
-#remove-shortcut-button,
-#add-shortcut-button {
- -webkit-margin-end: 10px;
-}
-
-#delete-supervised-profile-addendum {
- -webkit-padding-start: 48px;
- margin-top: 10px;
-}
-
-html[dir='ltr'] #delete-profile-icon {
- float: left;
- margin-right: 10px;
-}
-
-html[dir='rtl'] #delete-profile-icon {
- float: right;
- margin-left: 10px;
-}
-
-#create-profile-supervised-not-signed-in {
- color: #999;
-}
-
-#create-profile-supervised-not-signed-in-label,
-#create-profile-supervised-account-details-out-of-date-label {
- white-space: pre-wrap;
- word-wrap: break-word;
-}
-
-#create-profile-supervised-content-area {
- padding-top: 5px;
-}
-
-#import-existing-supervised-user-link {
- bottom: 25px;
- left: 17px;
- position: absolute;
-}
-
-#supervised-user-import-existing {
- margin: 0;
- padding: 0;
-}
diff --git a/chromium/chrome/browser/resources/options/manage_profile_overlay.html b/chromium/chrome/browser/resources/options/manage_profile_overlay.html
deleted file mode 100644
index f72093c014a..00000000000
--- a/chromium/chrome/browser/resources/options/manage_profile_overlay.html
+++ /dev/null
@@ -1,141 +0,0 @@
-<div id="manage-profile-overlay" class="page" hidden>
- <div class="close-button"></div>
- <!-- Dialog for managing profiles. -->
- <div id="manage-profile-overlay-manage" hidden>
- <h1>$i18n{manageProfile}</h1>
- <div id="manage-profile-content" class="content-area">
- <div id="manage-profile-icon-label">$i18n{manageProfilesIconLabel}</div>
- <grid id="manage-profile-icon-grid"></grid>
- <div id="manage-profile-name-input-container">
- <label>
- <span>$i18n{manageProfilesNameLabel}</span>
- <input id="manage-profile-name" type="text" pattern=".*\S.*" required>
- </label>
- </div>
- <div id="manage-profile-error-bubble" hidden></div>
- </div>
- <div class="action-area">
- <div class="action-area-shortcut-container">
- <button id="remove-shortcut-button" hidden>
- $i18n{removeProfileShortcutButton}
- </button>
- <button id="add-shortcut-button" hidden>
- $i18n{createProfileShortcutButton}
- </button>
- </div>
- <div class="button-strip">
- <button id="manage-profile-cancel">$i18n{cancel}</button>
- <button id="manage-profile-ok" class="default-button">
- $i18n{manageProfilesConfirm}
- </button>
- </div>
- </div>
- </div>
- <!-- Dialog for deleting profiles. -->
- <div id="manage-profile-overlay-delete" hidden>
- <h1>$i18n{deleteProfileTitle}</h1>
- <div class="content-area">
- <div id="delete-profile-message">
- <img id="delete-profile-icon" class="profile-icon">
- <div id="delete-profile-text"></div>
- </div>
- <div id="delete-supervised-profile-addendum" hidden>
- $i18nRaw{deleteSupervisedProfileAddendum}
- </div>
- </div>
- <div class="action-area button-strip">
- <button id="delete-profile-ok">$i18n{deleteProfileOK}</button>
- <button id="delete-profile-cancel" class="default-button">
- $i18n{cancel}
- </button>
- </div>
- </div>
- <!-- Dialog for disconnecting enterprise managed profiles. -->
- <div id="manage-profile-overlay-disconnect-managed" hidden>
- <h1>$i18n{disconnectManagedProfileTitle}</h1>
- <div class="content-area"
- id="disconnect-managed-profile-domain-information">
- $i18nRaw{disconnectManagedProfileDomainInformation}
- </div>
- <div class="content-area">
- <div id="disconnect-managed-profile-message">
- <div id="disconnect-managed-profile-text">
- $i18nRaw{disconnectManagedProfileText}
- </div>
- </div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="disconnect-managed-profile-ok">
- $i18n{disconnectManagedProfileOK}
- </button>
- <button id="disconnect-managed-profile-cancel" class="default-button">
- $i18n{cancel}
- </button>
- </div>
- </div>
- </div>
- <!-- Dialog for creating profiles. -->
- <div id="manage-profile-overlay-create" hidden>
- <h1>$i18n{createProfileTitle}</h1>
- <div id="create-profile-content" class="content-area">
- <div id="create-profile-instructions"></div>
- <grid id="create-profile-icon-grid"></grid>
- <div id="create-profile-name-input-container">
- <label>
- <span id="create-profile-name-label">
- $i18n{manageProfilesNameLabel}
- </span>
- <input id="create-profile-name" type="text" pattern=".*\S.*" required>
- </label>
- </div>
- </div>
- <div id="create-profile-supervised-content-area" class="content-area">
- <div id="create-shortcut-container" class="checkbox" hidden>
- <label>
- <input id="create-shortcut" type="checkbox">
- <span>$i18n{createProfileShortcutCheckbox}</span>
- </label>
- </div>
- <div id="create-profile-supervised-container" class="checkbox">
- <label>
- <input id="create-profile-supervised" type="checkbox">
- <span id="create-profile-supervised-signed-in">
- <span id="create-profile-supervised-signed-in-label"></span>
- <span
- id="create-profile-supervised-account-details-out-of-date-label"
- hidden>
- </span>
- <a id="create-profile-supervised-signed-in-learn-more-link"
- is="action-link">
- $i18n{learnMore}
- </a>
- <a id="create-profile-supervised-sign-in-again-link"
- is="action-link" hidden>
- $i18n{manageProfilesSupervisedSignInAgainLink}
- </a>
- </span>
- <span id="create-profile-supervised-not-signed-in" hidden>
- $i18nRaw{manageProfilesSupervisedNotSignedIn}
- </span>
- </label>
- <span id="create-profile-supervised-indicator"
- class="bubble-button controlled-setting-indicator">
- </span>
- </div>
- <div id="create-profile-error-bubble" hidden></div>
- </div>
- <div class="action-area">
- <div id="create-profile-throbber" class="throbber"></div>
- <a is="action-link" id="import-existing-supervised-user-link" hidden>
- $i18n{importExistingSupervisedUserLink}
- </a>
- <div class="button-strip">
- <button id="create-profile-cancel">$i18n{cancel}</button>
- <button id="create-profile-ok" class="default-button">
- $i18n{createProfileConfirm}
- </button>
- </div>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/manage_profile_overlay.js b/chromium/chrome/browser/resources/options/manage_profile_overlay.js
deleted file mode 100644
index 7e3371df917..00000000000
--- a/chromium/chrome/browser/resources/options/manage_profile_overlay.js
+++ /dev/null
@@ -1,917 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
- var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /**
- * ManageProfileOverlay class
- * Encapsulated handling of the 'Manage profile...' overlay page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function ManageProfileOverlay() {
- Page.call(this, 'manageProfile',
- loadTimeData.getString('manageProfileTabTitle'),
- 'manage-profile-overlay');
- }
-
- cr.addSingletonGetter(ManageProfileOverlay);
-
- ManageProfileOverlay.prototype = {
- // Inherit from Page.
- __proto__: Page.prototype,
-
- // Info about the currently managed/deleted profile.
- profileInfo_: null,
-
- // Whether the currently chosen name for a new profile was assigned
- // automatically by choosing an avatar. Set on receiveNewProfileDefaults;
- // cleared on first edit (in onNameChanged_).
- profileNameIsDefault_: false,
-
- // List of default profile names corresponding to the respective icons.
- defaultProfileNames_: [],
-
- // An object containing all names of existing profiles.
- existingProfileNames_: {},
-
- // The currently selected icon in the icon grid.
- iconGridSelectedURL_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
- options.ProfilesIconGrid.decorate($('manage-profile-icon-grid'));
- options.ProfilesIconGrid.decorate($('create-profile-icon-grid'));
- self.registerCommonEventHandlers_('create',
- self.submitCreateProfile_.bind(self));
- self.registerCommonEventHandlers_('manage',
- self.submitManageChanges_.bind(self));
-
- // Override the create-profile-ok and create-* keydown handlers, to avoid
- // closing the overlay until we finish creating the profile.
- $('create-profile-ok').onclick = function(event) {
- self.submitCreateProfile_();
- };
-
- $('create-profile-cancel').onclick = function(event) {
- CreateProfileOverlay.cancelCreateProfile();
- };
-
- $('manage-profile-cancel').onclick =
- $('disconnect-managed-profile-cancel').onclick =
- $('delete-profile-cancel').onclick = function(event) {
- PageManager.closeOverlay();
- };
- $('delete-profile-ok').onclick = function(event) {
- PageManager.closeOverlay();
- chrome.send('deleteProfile', [self.profileInfo_.filePath]);
- options.SupervisedUserListData.resetPromise();
- };
- $('add-shortcut-button').onclick = function(event) {
- chrome.send('addProfileShortcut', [self.profileInfo_.filePath]);
- };
- $('remove-shortcut-button').onclick = function(event) {
- chrome.send('removeProfileShortcut', [self.profileInfo_.filePath]);
- };
-
- $('disconnect-managed-profile-ok').onclick = function(event) {
- PageManager.closeOverlay();
- chrome.send('deleteProfile',
- [BrowserOptions.getCurrentProfile().filePath]);
- };
-
- $('create-profile-supervised-signed-in-learn-more-link').onclick =
- function(event) {
- PageManager.showPageByName('supervisedUserLearnMore');
- return false;
- };
-
- $('create-profile-supervised-sign-in-link').onclick =
- function(event) {
- SyncSetupOverlay.startSignIn(true /* creatingSupervisedUser */);
- };
-
- $('create-profile-supervised-sign-in-again-link').onclick =
- function(event) {
- SyncSetupOverlay.showSetupUI();
- };
-
- $('import-existing-supervised-user-link').onclick = function(event) {
- // Hide the import button to trigger a cursor update. The import button
- // is shown again when the import overlay loads. TODO(akuegel): Remove
- // this temporary fix when crbug/246304 is resolved.
- $('import-existing-supervised-user-link').hidden = true;
- PageManager.showPageByName('supervisedUserImport');
- };
- },
-
- /** @override */
- didShowPage: function() {
- chrome.send('requestDefaultProfileIcons', ['manage']);
-
- // Just ignore the manage profile dialog on Chrome OS, they use /accounts.
- if (!cr.isChromeOS && window.location.pathname == '/manageProfile')
- ManageProfileOverlay.getInstance().prepareForManageDialog_();
-
- // When editing a profile, initially hide the "add shortcut" and
- // "remove shortcut" buttons and ask the handler which to show. It will
- // call |receiveHasProfileShortcuts|, which will show the appropriate one.
- $('remove-shortcut-button').hidden = true;
- $('add-shortcut-button').hidden = true;
-
- if (loadTimeData.getBoolean('profileShortcutsEnabled')) {
- var profileInfo = ManageProfileOverlay.getInstance().profileInfo_;
- chrome.send('requestHasProfileShortcuts', [profileInfo.filePath]);
- }
-
- var manageNameField = $('manage-profile-name');
- // Legacy supervised users cannot edit their names.
- if (manageNameField.disabled)
- $('manage-profile-ok').focus();
- else
- manageNameField.focus();
-
- this.profileNameIsDefault_ = false;
- },
-
- /**
- * Registers event handlers that are common between create and manage modes.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @param {function()} submitFunction The function that should be called
- * when the user chooses to submit (e.g. by clicking the OK button).
- * @private
- */
- registerCommonEventHandlers_: function(mode, submitFunction) {
- var self = this;
- $(mode + '-profile-icon-grid').addEventListener('change', function(e) {
- self.onIconGridSelectionChanged_(mode);
- });
- $(mode + '-profile-name').oninput = function(event) {
- self.onNameChanged_(mode);
- };
- $(mode + '-profile-ok').onclick = function(event) {
- PageManager.closeOverlay();
- submitFunction();
- };
- },
-
- /**
- * Set the profile info used in the dialog.
- * @param {Object} profileInfo An object of the form:
- * profileInfo = {
- * name: "Profile Name",
- * iconURL: "chrome://path/to/icon/image",
- * filePath: "/path/to/profile/data/on/disk",
- * isCurrentProfile: false,
- * isSupervised: false
- * };
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- setProfileInfo_: function(profileInfo, mode) {
- this.iconGridSelectedURL_ = profileInfo.iconURL;
- this.profileInfo_ = profileInfo;
- $(mode + '-profile-name').value = profileInfo.name;
- $(mode + '-profile-icon-grid').selectedItem = profileInfo.iconURL;
- },
-
- /**
- * Sets the name of the profile being edited or created.
- * @param {string} name New profile name.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- setProfileName_: function(name, mode) {
- if (this.profileInfo_)
- this.profileInfo_.name = name;
- $(mode + '-profile-name').value = name;
- },
-
- /**
- * Set an array of default icon URLs. These will be added to the grid that
- * the user will use to choose their profile icon.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @param {!Array<string>} iconURLs An array of icon URLs.
- * @param {Array<string>} names An array of default names
- * corresponding to the icons.
- * @private
- */
- receiveDefaultProfileIconsAndNames_: function(mode, iconURLs, names) {
- this.defaultProfileNames_ = names;
-
- var grid = $(mode + '-profile-icon-grid');
-
- grid.dataModel = new ArrayDataModel(iconURLs);
-
- if (this.profileInfo_)
- grid.selectedItem = this.profileInfo_.iconURL;
-
- // Recalculate the measured item size.
- grid.measured_ = null;
- grid.columns = 0;
- grid.redraw();
- },
-
- /**
- * Callback to set the initial values when creating a new profile.
- * @param {Object} profileInfo An object of the form:
- * profileInfo = {
- * name: "Profile Name",
- * iconURL: "chrome://path/to/icon/image",
- * };
- * @private
- */
- receiveNewProfileDefaults_: function(profileInfo) {
- ManageProfileOverlay.setProfileInfo(profileInfo, 'create');
- this.profileNameIsDefault_ = true;
- $('create-profile-name-label').hidden = false;
- $('create-profile-name').hidden = false;
- // Trying to change the focus if this isn't the topmost overlay can
- // instead cause the FocusManager to override another overlay's focus,
- // e.g. if an overlay above this one is in the process of being reloaded.
- // But the C++ handler calls this method directly on ManageProfileOverlay,
- // so check the pageDiv to also include its subclasses (in particular
- // CreateProfileOverlay, which has higher sub-overlays).
- if (PageManager.getTopmostVisiblePage().pageDiv == this.pageDiv) {
- // This will only have an effect if the 'create-profile-name' element
- // is visible, i.e. if the overlay is in create mode.
- $('create-profile-name').focus();
- }
- $('create-profile-ok').disabled = false;
- },
-
- /**
- * Set a dictionary of all profile names. These are used to prevent the
- * user from naming two profiles the same.
- * @param {Object} profileNames A dictionary of profile names.
- * @private
- */
- receiveExistingProfileNames_: function(profileNames) {
- this.existingProfileNames_ = profileNames;
- },
-
- /**
- * Callback to show the add/remove shortcut buttons when in edit mode,
- * called by the handler as a result of the 'requestHasProfileShortcuts_'
- * message.
- * @param {boolean} hasShortcuts Whether profile has any existing shortcuts.
- * @private
- */
- receiveHasProfileShortcuts_: function(hasShortcuts) {
- $('add-shortcut-button').hidden = hasShortcuts;
- $('remove-shortcut-button').hidden = !hasShortcuts;
- },
-
- /**
- * Display the error bubble, with |errorHtml| in the bubble.
- * @param {string} errorHtml The html string to display as an error.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @param {boolean} disableOKButton True if the dialog's OK button should be
- * disabled when the error bubble is shown. It will be (re-)enabled when
- * the error bubble is hidden.
- * @private
- */
- showErrorBubble_: function(errorHtml, mode, disableOKButton) {
- var nameErrorEl = $(mode + '-profile-error-bubble');
- nameErrorEl.hidden = false;
- nameErrorEl.innerHTML = errorHtml;
-
- if (disableOKButton)
- $(mode + '-profile-ok').disabled = true;
- },
-
- /**
- * Hide the error bubble.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- hideErrorBubble_: function(mode) {
- $(mode + '-profile-error-bubble').innerHTML = '';
- $(mode + '-profile-error-bubble').hidden = true;
- $(mode + '-profile-ok').disabled = false;
- },
-
- /**
- * oninput callback for <input> field.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- onNameChanged_: function(mode) {
- this.profileNameIsDefault_ = false;
- this.updateCreateOrImport_(mode);
- },
-
- /**
- * Called when the profile name is changed or the 'create supervised'
- * checkbox is toggled. Updates the 'ok' button and the 'import existing
- * supervised user' link.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- updateCreateOrImport_: function(mode) {
- this.updateOkButton_(mode);
- // In 'create' mode, check for existing supervised users with the same
- // name.
- if (mode == 'create')
- this.requestExistingSupervisedUsers_();
- },
-
- /**
- * Tries to get the list of existing supervised users and updates the UI
- * accordingly.
- * @private
- */
- requestExistingSupervisedUsers_: function() {
- options.SupervisedUserListData.requestExistingSupervisedUsers().then(
- this.receiveExistingSupervisedUsers_.bind(this),
- this.onSigninError_.bind(this));
- },
-
- /**
- * @param {Object} supervisedUser
- * @param {boolean} nameIsUnique
- */
- getImportHandler_: function(supervisedUser, nameIsUnique) {
- return function() {
- if (supervisedUser.needAvatar || !nameIsUnique) {
- PageManager.showPageByName('supervisedUserImport');
- } else {
- this.hideErrorBubble_('create');
- CreateProfileOverlay.updateCreateInProgress(true);
- chrome.send('createProfile',
- [supervisedUser.name, supervisedUser.iconURL, false, true,
- supervisedUser.id]);
- }
- }.bind(this);
- },
-
- /**
- * Callback which receives the list of existing supervised users. Checks if
- * the currently entered name is the name of an already existing supervised
- * user. If yes, the user is prompted to import the existing supervised
- * user, and the create button is disabled.
- * If the received list is empty, hides the "import" link.
- * @param {Array<Object>} supervisedUsers The list of existing supervised
- * users.
- * @private
- */
- receiveExistingSupervisedUsers_: function(supervisedUsers) {
- // After a supervised user has been created and the dialog has been
- // hidden, this gets called again with a list including
- // the just-created SU. Ignore, to prevent the "already exists" bubble
- // from showing up if the overlay is already hidden.
- if (PageManager.getTopmostVisiblePage().pageDiv != this.pageDiv)
- return;
- $('import-existing-supervised-user-link').hidden =
- supervisedUsers.length === 0;
- if (!$('create-profile-supervised').checked)
- return;
-
- var newName = $('create-profile-name').value;
- var i;
- for (i = 0; i < supervisedUsers.length; ++i) {
- if (supervisedUsers[i].name != newName)
- continue;
- // Check if another supervised user also exists with that name.
- var nameIsUnique = true;
- // Handling the case when multiple supervised users with the same
- // name exist, but not all of them are on the device.
- // If at least one is not imported, we want to offer that
- // option to the user. This could happen due to a bug that allowed
- // creating SUs with the same name (https://crbug.com/557445).
- var allOnCurrentDevice = supervisedUsers[i].onCurrentDevice;
- var j;
- for (j = i + 1; j < supervisedUsers.length; ++j) {
- if (supervisedUsers[j].name == newName) {
- nameIsUnique = false;
- allOnCurrentDevice = allOnCurrentDevice &&
- supervisedUsers[j].onCurrentDevice;
- }
- }
-
- var errorHtml = allOnCurrentDevice ?
- loadTimeData.getStringF(
- 'managedProfilesExistingLocalSupervisedUser') :
- loadTimeData.getStringF(
- 'manageProfilesExistingSupervisedUser',
- HTMLEscape(elide(newName, /* maxLength */ 50)));
- this.showErrorBubble_(errorHtml, 'create', true);
-
- if ($('supervised-user-import-existing')) {
- $('supervised-user-import-existing').onclick =
- this.getImportHandler_(supervisedUsers[i], nameIsUnique);
- }
- $('create-profile-ok').disabled = true;
- return;
- }
- },
-
- /**
- * Called in case the request for the list of supervised users fails because
- * of a signin error.
- * @private
- */
- onSigninError_: function() {
- this.updateSignedInStatus(this.signedInEmail_, true);
- },
-
- /**
- * Called to update the state of the ok button depending if the name is
- * already used or not.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- updateOkButton_: function(mode) {
- var oldName = this.profileInfo_.name;
- var newName = $(mode + '-profile-name').value;
- this.hideErrorBubble_(mode);
-
- var nameIsValid = $(mode + '-profile-name').validity.valid;
- $(mode + '-profile-ok').disabled = !nameIsValid;
- },
-
- /**
- * Called when the user clicks "OK" or hits enter. Saves the newly changed
- * profile info.
- * @private
- */
- submitManageChanges_: function() {
- var name = $('manage-profile-name').value;
- var iconURL = $('manage-profile-icon-grid').selectedItem;
-
- chrome.send('setProfileIconAndName',
- [this.profileInfo_.filePath, iconURL, name]);
- if (name != this.profileInfo_.name)
- options.SupervisedUserListData.resetPromise();
- },
-
- /**
- * Abstract method. Should be overriden in subclasses.
- * @param {string} email
- * @param {boolean} hasError
- * @protected
- */
- updateSignedInStatus: function(email, hasError) {
- // TODO: Fix triggering the assert, crbug.com/423267
- // assertNotReached();
- },
-
- /**
- * Called when the user clicks "OK" or hits enter. Creates the profile
- * using the information in the dialog.
- * @private
- */
- submitCreateProfile_: function() {
- // This is visual polish: the UI to access this should be disabled for
- // supervised users, and the back end will prevent user creation anyway.
- if (this.profileInfo_ && this.profileInfo_.isSupervised)
- return;
-
- this.hideErrorBubble_('create');
- CreateProfileOverlay.updateCreateInProgress(true);
-
- // Get the user's chosen name and icon, or default if they do not
- // wish to customize their profile.
- var name = $('create-profile-name').value;
- var iconUrl = $('create-profile-icon-grid').selectedItem;
- var createShortcut = $('create-shortcut').checked;
- var isSupervised = $('create-profile-supervised').checked;
- var existingSupervisedUserId = '';
-
- // 'createProfile' is handled by the CreateProfileHandler.
- chrome.send('createProfile',
- [name, iconUrl, createShortcut,
- isSupervised, existingSupervisedUserId]);
- },
-
- /**
- * Called when the selected icon in the icon grid changes.
- * @param {string} mode A label that specifies the type of dialog box which
- * is currently being viewed (i.e. 'create' or 'manage').
- * @private
- */
- onIconGridSelectionChanged_: function(mode) {
- var iconURL = $(mode + '-profile-icon-grid').selectedItem;
- if (!iconURL || iconURL == this.iconGridSelectedURL_)
- return;
- this.iconGridSelectedURL_ = iconURL;
- if (this.profileNameIsDefault_) {
- var index = $(mode + '-profile-icon-grid').selectionModel.selectedIndex;
- var name = this.defaultProfileNames_[index];
- if (name) {
- this.setProfileName_(name, mode);
- this.updateCreateOrImport_(mode);
- }
- }
- if (this.profileInfo_ && this.profileInfo_.filePath) {
- chrome.send('profileIconSelectionChanged',
- [this.profileInfo_.filePath, iconURL]);
- }
- },
-
- /**
- * Updates the contents of the "Manage Profile" section of the dialog,
- * and shows that section.
- * @private
- */
- prepareForManageDialog_: function() {
- chrome.send('refreshGaiaPicture');
- var profileInfo = BrowserOptions.getCurrentProfile();
- ManageProfileOverlay.setProfileInfo(profileInfo, 'manage');
- $('manage-profile-overlay-create').hidden = true;
- $('manage-profile-overlay-manage').hidden = false;
- $('manage-profile-overlay-delete').hidden = true;
- $('manage-profile-overlay-disconnect-managed').hidden = true;
- $('manage-profile-name').disabled =
- profileInfo.isSupervised && !profileInfo.isChild;
- this.hideErrorBubble_('manage');
- },
-
- /**
- * Display the "Manage Profile" dialog.
- * @param {boolean=} opt_updateHistory If we should update the history after
- * showing the dialog (defaults to true).
- * @private
- */
- showManageDialog_: function(opt_updateHistory) {
- var updateHistory = opt_updateHistory !== false;
- this.prepareForManageDialog_();
- PageManager.showPageByName('manageProfile', updateHistory);
- },
-
- /**
- * Display the "Delete Profile" dialog.
- * @param {Object} profileInfo The profile object of the profile to delete.
- * @private
- */
- showDeleteDialog_: function(profileInfo) {
- ManageProfileOverlay.setProfileInfo(profileInfo, 'manage');
- $('manage-profile-overlay-create').hidden = true;
- $('manage-profile-overlay-manage').hidden = true;
- $('manage-profile-overlay-delete').hidden = false;
- $('manage-profile-overlay-disconnect-managed').hidden = true;
- $('delete-profile-icon').style.content =
- cr.icon.getImage(profileInfo.iconURL);
- $('delete-profile-text').textContent =
- loadTimeData.getStringF('deleteProfileMessage',
- elide(profileInfo.name, /* maxLength */ 50));
- $('delete-supervised-profile-addendum').hidden =
- !profileInfo.isSupervised || profileInfo.isChild;
-
- // Because this dialog isn't useful when refreshing or as part of the
- // history, don't create a history entry for it when showing.
- PageManager.showPageByName('manageProfile', false);
- chrome.send('logDeleteUserDialogShown');
- },
-
- /**
- * Display the "Disconnect Managed Profile" dialog.
- * @private
- */
- showDisconnectManagedProfileDialog_: function(replacements) {
- loadTimeData.overrideValues(replacements);
- $('manage-profile-overlay-create').hidden = true;
- $('manage-profile-overlay-manage').hidden = true;
- $('manage-profile-overlay-delete').hidden = true;
- $('disconnect-managed-profile-domain-information').innerHTML =
- loadTimeData.getString('disconnectManagedProfileDomainInformation');
- $('disconnect-managed-profile-text').innerHTML =
- loadTimeData.getString('disconnectManagedProfileText');
- $('manage-profile-overlay-disconnect-managed').hidden = false;
-
- PageManager.showPageByName('signOut');
- },
-
- /**
- * Display the "Create Profile" dialog.
- * @private
- */
- showCreateDialog_: function() {
- PageManager.showPageByName('createProfile');
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(ManageProfileOverlay, [
- 'receiveDefaultProfileIconsAndNames',
- 'receiveNewProfileDefaults',
- 'receiveExistingProfileNames',
- 'receiveHasProfileShortcuts',
- 'setProfileInfo',
- 'setProfileName',
- 'showManageDialog',
- 'showDeleteDialog',
- 'showDisconnectManagedProfileDialog',
- 'showCreateDialog',
- ]);
-
- /**
- * @constructor
- * @extends {options.ManageProfileOverlay}
- */
- function DisconnectAccountOverlay() {
- Page.call(this, 'signOut',
- loadTimeData.getString('disconnectAccountTabTitle'),
- 'manage-profile-overlay');
- }
-
- cr.addSingletonGetter(DisconnectAccountOverlay);
-
- DisconnectAccountOverlay.prototype = {
- __proto__: ManageProfileOverlay.prototype,
-
- /** @override */
- canShowPage: function() {
- var syncData = loadTimeData.getValue('syncData');
- return syncData.signedIn && !syncData.signoutAllowed;
- },
-
- /** @override */
- didShowPage: function() {
- chrome.send('showDisconnectManagedProfileDialog');
- }
- };
-
- /**
- * @constructor
- * @extends {options.ManageProfileOverlay}
- */
- function CreateProfileOverlay() {
- Page.call(this, 'createProfile',
- loadTimeData.getString('createProfileTabTitle'),
- 'manage-profile-overlay');
- }
-
- cr.addSingletonGetter(CreateProfileOverlay);
-
- CreateProfileOverlay.prototype = {
- __proto__: ManageProfileOverlay.prototype,
-
- // The signed-in email address of the current profile, or empty if they're
- // not signed in.
- signedInEmail_: '',
-
- /** @override */
- canShowPage: function() {
- return !BrowserOptions.getCurrentProfile().isSupervised;
- },
-
- /**
- * Configures the overlay to the "create user" mode.
- * @override
- */
- didShowPage: function() {
- chrome.send('requestCreateProfileUpdate');
- chrome.send('requestDefaultProfileIcons', ['create']);
- chrome.send('requestNewProfileDefaults');
-
- $('manage-profile-overlay-create').hidden = false;
- $('manage-profile-overlay-manage').hidden = true;
- $('manage-profile-overlay-delete').hidden = true;
- $('manage-profile-overlay-disconnect-managed').hidden = true;
- $('create-profile-instructions').textContent =
- loadTimeData.getStringF('createProfileInstructions');
- this.hideErrorBubble_();
- this.updateCreateInProgress_(false);
-
- var shortcutsEnabled = loadTimeData.getBoolean('profileShortcutsEnabled');
- $('create-shortcut-container').hidden = !shortcutsEnabled;
- $('create-shortcut').checked = shortcutsEnabled;
-
- $('create-profile-name-label').hidden = true;
- $('create-profile-name').hidden = true;
- $('create-profile-ok').disabled = true;
-
- $('create-profile-supervised').checked = false;
- $('import-existing-supervised-user-link').hidden = true;
- $('create-profile-supervised').onchange = function() {
- ManageProfileOverlay.getInstance().updateCreateOrImport_('create');
- };
- $('create-profile-supervised').hidden = true;
- $('create-profile-supervised-signed-in').disabled = true;
- $('create-profile-supervised-signed-in').hidden = true;
- $('create-profile-supervised-not-signed-in').hidden = true;
-
- this.profileNameIsDefault_ = false;
- },
-
- /** @override */
- handleCancel: function() {
- this.cancelCreateProfile_();
- },
-
- /** @override */
- showErrorBubble_: function(errorHtml) {
- ManageProfileOverlay.getInstance().showErrorBubble_(errorHtml,
- 'create',
- false);
- },
-
- /** @override */
- hideErrorBubble_: function() {
- ManageProfileOverlay.getInstance().hideErrorBubble_('create');
- },
-
- /**
- * Updates the UI when a profile create step begins or ends.
- * Note that hideErrorBubble_() also enables the "OK" button, so it
- * must be called before this function if both are used.
- * @param {boolean} inProgress True if the UI should be updated to show that
- * profile creation is now in progress.
- * @private
- */
- updateCreateInProgress_: function(inProgress) {
- this.createInProgress_ = inProgress;
- this.updateCreateSupervisedUserCheckbox_();
-
- $('create-profile-icon-grid').disabled = inProgress;
- $('create-profile-name').disabled = inProgress;
- $('create-shortcut').disabled = inProgress;
- $('create-profile-ok').disabled = inProgress;
- $('import-existing-supervised-user-link').disabled = inProgress;
-
- $('create-profile-throbber').hidden = !inProgress;
- },
-
- /**
- * Cancels the creation of the a profile. It is safe to call this even
- * when no profile is in the process of being created.
- * @private
- */
- cancelCreateProfile_: function() {
- PageManager.closeOverlay();
- chrome.send('cancelCreateProfile');
- this.hideErrorBubble_();
- this.updateCreateInProgress_(false);
- },
-
- /**
- * Shows an error message describing an error that occurred while creating
- * a new profile.
- * Called by BrowserOptions via the BrowserOptionsHandler.
- * @param {string} error The error message to display.
- * @private
- */
- onError_: function(error) {
- this.updateCreateInProgress_(false);
- this.showErrorBubble_(error);
- },
-
- /**
- * Shows a warning message giving information while creating a new profile.
- * Called by BrowserOptions via the BrowserOptionsHandler.
- * @param {string} warning The warning message to display.
- * @private
- */
- onWarning_: function(warning) {
- this.showErrorBubble_(warning);
- },
-
- /**
- * For new supervised users, shows a confirmation page after successfully
- * creating a new profile; otherwise, the handler will open a new window.
- * @param {Object} profileInfo An object of the form:
- * profileInfo = {
- * name: "Profile Name",
- * filePath: "/path/to/profile/data/on/disk"
- * isSupervised: (true|false),
- * };
- * @private
- */
- onSuccess_: function(profileInfo) {
- this.updateCreateInProgress_(false);
- PageManager.closeOverlay();
- if (profileInfo.isSupervised) {
- options.SupervisedUserListData.resetPromise();
- profileInfo.custodianEmail = this.signedInEmail_;
- SupervisedUserCreateConfirmOverlay.setProfileInfo(profileInfo);
- PageManager.showPageByName('supervisedUserCreateConfirm', false);
- BrowserOptions.updateManagesSupervisedUsers(true);
- }
- },
-
- /**
- * @param {string} email
- * @param {boolean} hasError
- * @override
- */
- updateSignedInStatus: function(email, hasError) {
- this.updateSignedInStatus_(email, hasError);
- },
-
- /**
- * Updates the signed-in or not-signed-in UI when in create mode. Called by
- * the handler in response to the 'requestCreateProfileUpdate' message.
- * updateSupervisedUsersAllowed_ is expected to be called after this is, and
- * will update additional UI elements.
- * @param {string} email The email address of the currently signed-in user.
- * An empty string indicates that the user is not signed in.
- * @param {boolean} hasError Whether the user's sign-in credentials are
- * still valid.
- * @private
- */
- updateSignedInStatus_: function(email, hasError) {
- this.signedInEmail_ = email;
- this.hasError_ = hasError;
- var isSignedIn = email !== '';
- $('create-profile-supervised').hidden = !isSignedIn;
- $('create-profile-supervised-signed-in').hidden = !isSignedIn;
- $('create-profile-supervised-not-signed-in').hidden = isSignedIn;
-
- if (isSignedIn) {
- var accountDetailsOutOfDate =
- $('create-profile-supervised-account-details-out-of-date-label');
- accountDetailsOutOfDate.textContent = loadTimeData.getStringF(
- 'manageProfilesSupervisedAccountDetailsOutOfDate', email);
- accountDetailsOutOfDate.hidden = !hasError;
-
- $('create-profile-supervised-signed-in-label').textContent =
- loadTimeData.getStringF(
- 'manageProfilesSupervisedSignedInLabel', email);
- $('create-profile-supervised-signed-in-label').hidden = hasError;
-
- $('create-profile-supervised-sign-in-again-link').hidden = !hasError;
- $('create-profile-supervised-signed-in-learn-more-link').hidden =
- hasError;
- }
-
- this.updateCreateSupervisedUserCheckbox_();
- // If we're signed in, showing/hiding import-existing-supervised-user-link
- // is handled in receiveExistingSupervisedUsers_.
- if (isSignedIn && !hasError)
- this.requestExistingSupervisedUsers_();
- else
- $('import-existing-supervised-user-link').hidden = true;
- },
-
- /**
- * Sets whether creating supervised users is allowed or not. Called by the
- * handler in response to the 'requestCreateProfileUpdate' message or a
- * change in the (policy-controlled) pref that prohibits creating supervised
- * users, after the signed-in status has been updated.
- * @param {boolean} allowed True if creating supervised users should be
- * allowed.
- * @private
- */
- updateSupervisedUsersAllowed_: function(allowed) {
- this.supervisedUsersAllowed_ = allowed;
- this.updateCreateSupervisedUserCheckbox_();
-
- $('create-profile-supervised-sign-in-link').enabled = allowed;
- if (!allowed) {
- $('create-profile-supervised-indicator').setAttribute('controlled-by',
- 'policy');
- } else {
- $('create-profile-supervised-indicator').removeAttribute(
- 'controlled-by');
- }
- },
-
- /**
- * Updates the status of the "create supervised user" checkbox. Called from
- * updateSupervisedUsersAllowed_() or updateCreateInProgress_().
- * updateSignedInStatus_() does not call this method directly, because it
- * will be followed by a call to updateSupervisedUsersAllowed_().
- * @private
- */
- updateCreateSupervisedUserCheckbox_: function() {
- $('create-profile-supervised').disabled =
- !this.supervisedUsersAllowed_ || this.createInProgress_ ||
- this.signedInEmail_ == '' || this.hasError_;
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(CreateProfileOverlay, [
- 'cancelCreateProfile',
- 'onError',
- 'onSuccess',
- 'onWarning',
- 'updateCreateInProgress',
- 'updateSignedInStatus',
- 'updateSupervisedUsersAllowed',
- ]);
-
- // Export
- return {
- ManageProfileOverlay: ManageProfileOverlay,
- DisconnectAccountOverlay: DisconnectAccountOverlay,
- CreateProfileOverlay: CreateProfileOverlay,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/options.html b/chromium/chrome/browser/resources/options/options.html
deleted file mode 100644
index 95936d53545..00000000000
--- a/chromium/chrome/browser/resources/options/options.html
+++ /dev/null
@@ -1,218 +0,0 @@
-<!doctype html>
-<html id="t" dir="$i18n{textdirection}" lang="$i18n{language}">
-<head>
-<meta charset="utf-8">
-<title>$i18n{optionsPageTitle}</title>
-<link rel="stylesheet" href="chrome://resources/css/bubble.css">
-<link rel="stylesheet" href="chrome://resources/css/bubble_button.css">
-<link rel="stylesheet" href="chrome://resources/css/chrome_shared.css">
-<link rel="stylesheet" href="chrome://resources/css/controlled_indicator.css">
-<link rel="stylesheet" href="chrome://resources/css/list.css">
-<link rel="stylesheet" href="chrome://resources/css/overlay.css">
-<link rel="stylesheet" href="chrome://resources/css/spinner.css">
-<link rel="stylesheet" href="chrome://resources/css/throbber.css">
-<link rel="stylesheet" href="chrome://resources/css/tree.css">
-<link rel="stylesheet" href="../uber/uber_shared.css">
-<link rel="stylesheet" href="options_page.css">
-<link rel="stylesheet" href="alert_overlay.css">
-<link rel="stylesheet" href="autofill_edit_overlay.css">
-<link rel="stylesheet" href="autofill_options.css">
-<link rel="stylesheet" href="automatic_settings_reset_banner.css">
-<link rel="stylesheet" href="browser_options.css">
-<if expr="chromeos">
- <link rel="stylesheet" href="chromeos/browser_options.css">
-</if>
-<link rel="stylesheet" href="clear_browser_data_overlay.css">
-<link rel="stylesheet" href="content_settings.css">
-<link rel="stylesheet" href="cookies_view.css">
-<link rel="stylesheet" href="do_not_track_confirm_overlay.css">
-<link rel="stylesheet" href="easy_unlock_turn_off_overlay.css">
-<link rel="stylesheet" href="font_settings.css">
-<link rel="stylesheet" href="handler_options.css">
-<link rel="stylesheet" href="hotword_confirm_overlay.css">
-<link rel="stylesheet" href="hotword_search_setting_indicator.css">
-<link rel="stylesheet" href="import_data_overlay.css">
-<if expr="not is_macosx">
-<link rel="stylesheet" href="language_dictionary_overlay.css">
-</if>
-<link rel="stylesheet" href="language_options.css">
-<link rel="stylesheet" href="manage_profile_overlay.css">
-<link rel="stylesheet" href="password_manager.css">
-<link rel="stylesheet" href="password_manager_list.css">
-<link rel="stylesheet" href="reset_profile_settings_overlay.css">
-<link rel="stylesheet" href="search_engine_manager.css">
-<link rel="stylesheet" href="search_page.css">
-<link rel="stylesheet" href="spelling_confirm_overlay.css">
-<link rel="stylesheet" href="startup_overlay.css">
-<link rel="stylesheet" href="subpages_tab_controls.css">
-<link rel="stylesheet" href="supervised_user_create_confirm.css">
-<link rel="stylesheet" href="supervised_user_import.css">
-<link rel="stylesheet" href="supervised_user_learn_more.css">
-<link rel="stylesheet" href="../help/help_content.css">
-<link rel="stylesheet" href="sync_setup_overlay.css">
-<if expr="chromeos">
-<link rel="stylesheet" href="chromeos/third_party_ime_confirm_overlay.css">
-<link rel="stylesheet" href="chromeos/accounts_options_page.css">
-<link rel="stylesheet" href="chromeos/arc_opt_out_confirm_overlay.css">
-<link rel="stylesheet" href="chromeos/bluetooth.css">
-<link rel="stylesheet" href="chromeos/change_picture_options.css">
-<link rel="stylesheet" href="chromeos/display_options.css">
-<link rel="stylesheet" href="chromeos/display_overscan.css">
-<link rel="stylesheet" href="chromeos/internet_detail.css">
-<link rel="stylesheet" href="chromeos/keyboard_overlay.css">
-<link rel="stylesheet" href="chromeos/stylus_overlay.css">
-<link rel="stylesheet" href="chromeos/pointer_overlay.css">
-<link rel="stylesheet" href="chromeos/quick_unlock_configure_overlay.css">
-<link rel="stylesheet" href="chromeos/storage_clear_drive_cache_overlay.css">
-<link rel="stylesheet" href="chromeos/storage_manager.css">
-<link rel="stylesheet" href="factory_reset_overlay.css">
-<link rel="stylesheet" href="../help/channel_change_page.css">
-</if>
-<if expr="use_nss_certs">
-<link rel="stylesheet" href="certificate_manager.css">
-<link rel="stylesheet" href="certificate_tree.css">
-</if>
-<link rel="import" href="chrome://resources/html/action_link.html">
-<script src="chrome://resources/js/cr.js"></script>
-<script src="chrome://resources/js/event_tracker.js"></script>
-<script src="chrome://resources/js/cr/event_target.js"></script>
-<script src="chrome://resources/js/cr/ui.js"></script>
-<script src="chrome://resources/js/cr/ui/touch_handler.js"></script>
-<script src="chrome://resources/js/cr/ui/array_data_model.js"></script>
-<script src="chrome://resources/js/cr/ui/bubble.js"></script>
-<script src="chrome://resources/js/cr/ui/bubble_button.js"></script>
-<script src="chrome://resources/js/cr/ui/controlled_indicator.js"></script>
-<script src="chrome://resources/js/cr/ui/focus_manager.js"></script>
-<script src="chrome://resources/js/cr/ui/focus_outline_manager.js"></script>
-<script src="chrome://resources/js/cr/ui/list_selection_model.js"></script>
-<script src="chrome://resources/js/cr/ui/list_selection_controller.js"></script>
-<script src="chrome://resources/js/cr/ui/list_single_selection_model.js">
-</script>
-<script src="chrome://resources/js/cr/ui/list_item.js"></script>
-<script src="chrome://resources/js/cr/ui/list.js"></script>
-<script src="chrome://resources/js/cr/ui/menu_item.js"></script>
-<script src="chrome://resources/js/cr/ui/menu.js"></script>
-<script src="chrome://resources/js/cr/ui/autocomplete_list.js"></script>
-<script src="chrome://resources/js/cr/ui/grid.js"></script>
-<script src="chrome://resources/js/cr/ui/overlay.js"></script>
-<script src="chrome://resources/js/cr/ui/position_util.js"></script>
-<script src="chrome://resources/js/cr/ui/repeating_button.js"></script>
-<script src="chrome://resources/js/cr/ui/tree.js"></script>
-<script src="chrome://resources/js/cr/ui/page_manager/page_manager.js"></script>
-<script src="chrome://resources/js/cr/ui/page_manager/page.js"></script>
-<script src="chrome://resources/js/icon.js"></script>
-<script src="chrome://resources/js/load_time_data.js"></script>
-<script src="chrome://resources/js/parse_html_subset.js"></script>
-<script src="chrome://resources/js/util.js"></script>
-
-<script src="chrome://settings-frame/strings.js"></script>
-<script src="chrome://settings-frame/options_bundle.js"></script>
-</head>
-
-<body>
-<div id="overlay-container-1" class="overlay transparent" hidden>
- <include src="autofill_options.html">
- <include src="clear_browser_data_overlay.html">
- <include src="content_settings.html">
- <include src="do_not_track_confirm_overlay.html">
- <include src="easy_unlock_turn_off_overlay.html">
- <include src="font_settings.html">
- <include src="home_page_overlay.html">
- <include src="hotword_confirm_overlay.html">
- <include src="import_data_overlay.html">
- <include src="language_options.html">
- <include src="manage_profile_overlay.html">
- <include src="password_manager.html">
- <include src="reset_profile_settings_overlay.html">
- <include src="search_engine_manager.html">
- <include src="spelling_confirm_overlay.html">
- <include src="startup_overlay.html">
- <include src="supervised_user_create_confirm.html">
- <include src="../help/help_page.html">
- <include src="sync_setup_overlay.html">
-<if expr="chromeos">
- <include src="chromeos/accounts_options.html">
- <include src="chromeos/arc_opt_out_confirm_overlay.html">
- <include src="chromeos/bluetooth_add_device_overlay.html">
- <include src="chromeos/bluetooth_pair_device_overlay.html">
- <include src="chromeos/change_picture_options.html">
- <include src="chromeos/display_options.html">
- <include src="chromeos/keyboard_overlay.html">
- <include src="chromeos/stylus_overlay.html">
- <include src="chromeos/pointer_overlay.html">
- <include src="chromeos/power_overlay.html">
- <include src="chromeos/quick_unlock_configure_overlay.html">
- <include src="chromeos/storage_manager.html">
- <include src="factory_reset_overlay.html">
-</if>
-<if expr="use_nss_certs">
- <include src="certificate_manager.html">
-</if>
-</div>
-<div id="overlay-container-2" class="overlay transparent" hidden>
- <include src="alert_overlay.html">
- <include src="autofill_edit_address_overlay.html">
- <include src="autofill_edit_creditcard_overlay.html">
- <include src="clear_browser_data_history_notice_overlay.html">
- <include src="content_settings_exceptions_area.html">
- <include src="cookies_view.html">
- <include src="handler_options.html">
- <include src="language_add_language_overlay.html">
- <include src="supervised_user_import.html">
- <include src="supervised_user_learn_more.html">
-<if expr="not is_macosx">
- <include src="language_dictionary_overlay.html">
-</if>
-<if expr="chromeos">
- <include src="chromeos/display_overscan.html">
- <include src="chromeos/internet_detail.html">
- <include src="chromeos/preferred_networks.html">
- <include src="chromeos/storage_clear_drive_cache_overlay.html">
- <include src="chromeos/third_party_ime_confirm_overlay.html">
- <include src="../help/channel_change_page.html">
-</if>
-<if expr="not is_win and not is_macosx">
- <include src="certificate_restore_overlay.html">
- <include src="certificate_backup_overlay.html">
- <include src="certificate_edit_ca_trust_overlay.html">
- <include src="certificate_import_error_overlay.html">
-</if>
-</div>
-<div id="extension-controlled-settings-bubble-template" hidden>
- <div class="controlled-setting-bubble-content-row">
- <div class="controlled-setting-bubble-extension-name"></div>
- </div>
- <div class="controlled-setting-bubble-content-row">
- <a is="action-link" class="controlled-setting-bubble-extension-manage-link">
- $i18n{controlledSettingManageExtension}
- </a>
- <button class='controlled-setting-bubble-extension-disable-button'>
- $i18n{controlledSettingDisableExtension}
- </button>
- </div>
-</div>
-
-<div id="extension-controlled-warning-template"
- class="extension-controlled-warning-box settings-row" hidden>
- <div class="extension-controlled-warning"></div>
- <button>$i18n{extensionDisable}</button>
-</div>
-
-<div id="main-content"
- i18n-values="guestMode:profileIsGuest;supervisedMode:profileIsSupervised">
- <div id="mainview">
- <div id="mainview-content">
- <div id="page-container">
- <!-- Please keep the main pages in desired order of display. This will
- allow search results to display in the desired order. -->
- <include src="search_box.html">
- <include src="search_page.html">
- <include src="browser_options.html">
- </div>
- </div>
- </div>
-</div>
-
-<script src="chrome://resources/js/i18n_template.js"></script>
-</body>
-</html>
diff --git a/chromium/chrome/browser/resources/options/options.js b/chromium/chrome/browser/resources/options/options.js
deleted file mode 100644
index cdfb732b1ad..00000000000
--- a/chromium/chrome/browser/resources/options/options.js
+++ /dev/null
@@ -1,316 +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.
-
-var AddLanguageOverlay = options.AddLanguageOverlay;
-var AlertOverlay = options.AlertOverlay;
-var AutofillEditAddressOverlay = options.AutofillEditAddressOverlay;
-var AutofillEditCreditCardOverlay = options.AutofillEditCreditCardOverlay;
-var AutofillOptions = options.AutofillOptions;
-var AutomaticSettingsResetBanner = options.AutomaticSettingsResetBanner;
-var BrowserOptions = options.BrowserOptions;
-var ClearBrowserDataOverlay = options.ClearBrowserDataOverlay;
-var ClearBrowserDataHistoryNotice = options.ClearBrowserDataHistoryNotice;
-var ConfirmDialog = options.ConfirmDialog;
-var ContentSettingsExceptionsArea =
- options.contentSettings.ContentSettingsExceptionsArea;
-var ContentSettings = options.ContentSettings;
-var CookiesView = options.CookiesView;
-var CreateProfileOverlay = options.CreateProfileOverlay;
-var EditDictionaryOverlay = cr.IsMac ? null : options.EditDictionaryOverlay;
-var EasyUnlockTurnOffOverlay = options.EasyUnlockTurnOffOverlay;
-var FactoryResetOverlay = options.FactoryResetOverlay;
-// <if expr="enable_google_now">
-var GeolocationOptions = options.GeolocationOptions;
-// </if>
-var FontSettings = options.FontSettings;
-var HandlerOptions = options.HandlerOptions;
-var HomePageOverlay = options.HomePageOverlay;
-var HotwordConfirmDialog = options.HotwordConfirmDialog;
-var ImportDataOverlay = options.ImportDataOverlay;
-var LanguageOptions = options.LanguageOptions;
-var ManageProfileOverlay = options.ManageProfileOverlay;
-var DisconnectAccountOverlay = options.DisconnectAccountOverlay;
-var OptionsFocusManager = options.OptionsFocusManager;
-var OptionsPage = options.OptionsPage;
-var PageManager = cr.ui.pageManager.PageManager;
-var PasswordManager = options.PasswordManager;
-var Preferences = options.Preferences;
-var PreferredNetworks = options.PreferredNetworks;
-var ResetProfileSettingsOverlay = options.ResetProfileSettingsOverlay;
-var SearchEngineManager = options.SearchEngineManager;
-var SearchPage = options.SearchPage;
-var StartupOverlay = options.StartupOverlay;
-var SupervisedUserCreateConfirmOverlay =
- options.SupervisedUserCreateConfirmOverlay;
-var SupervisedUserImportOverlay = options.SupervisedUserImportOverlay;
-var SupervisedUserLearnMoreOverlay = options.SupervisedUserLearnMoreOverlay;
-var SyncSetupOverlay = options.SyncSetupOverlay;
-var ThirdPartyImeConfirmOverlay = options.ThirdPartyImeConfirmOverlay;
-
-/**
- * DOMContentLoaded handler, sets up the page.
- */
-function load() {
- // Decorate the existing elements in the document.
- cr.ui.decorate('input[pref][type=checkbox]', options.PrefCheckbox);
- cr.ui.decorate('input[pref][type=number]', options.PrefNumber);
- cr.ui.decorate('input[pref][type=radio]', options.PrefRadio);
- cr.ui.decorate('input[pref][type=range]', options.PrefRange);
- cr.ui.decorate('select[pref]', options.PrefSelect);
- cr.ui.decorate('input[pref][type=text]', options.PrefTextField);
- cr.ui.decorate('input[pref][type=url]', options.PrefTextField);
- cr.ui.decorate('button[pref]', options.PrefButton);
- cr.ui.decorate('#content-settings-page input[type=radio]:not(.handler-radio)',
- options.ContentSettingsRadio);
- cr.ui.decorate('#content-settings-page input[type=radio].handler-radio',
- options.HandlersEnabledRadio);
- cr.ui.decorate('span.controlled-setting-indicator',
- options.ControlledSettingIndicator);
-
- // Top level pages.
- PageManager.register(SearchPage.getInstance());
- PageManager.register(BrowserOptions.getInstance());
-
- // Overlays.
- PageManager.registerOverlay(AddLanguageOverlay.getInstance(),
- LanguageOptions.getInstance());
- PageManager.registerOverlay(AlertOverlay.getInstance());
- PageManager.registerOverlay(AutofillEditAddressOverlay.getInstance(),
- AutofillOptions.getInstance());
- PageManager.registerOverlay(AutofillEditCreditCardOverlay.getInstance(),
- AutofillOptions.getInstance());
- PageManager.registerOverlay(AutofillOptions.getInstance(),
- BrowserOptions.getInstance(),
- [$('autofill-settings')]);
- PageManager.registerOverlay(ClearBrowserDataOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('privacyClearDataButton')]);
- PageManager.registerOverlay(
- ClearBrowserDataHistoryNotice.getInstance(),
- ClearBrowserDataOverlay.getInstance());
- PageManager.registerOverlay(
- new ConfirmDialog(
- 'doNotTrackConfirm',
- loadTimeData.getString('doNotTrackConfirmOverlayTabTitle'),
- 'do-not-track-confirm-overlay',
- /** @type {HTMLButtonElement} */($('do-not-track-confirm-ok')),
- /** @type {HTMLButtonElement} */($('do-not-track-confirm-cancel')),
- $('do-not-track-enabled')['pref'],
- $('do-not-track-enabled')['metric']),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(
- new ConfirmDialog(
- 'spellingConfirm',
- loadTimeData.getString('spellingConfirmOverlayTabTitle'),
- 'spelling-confirm-overlay',
- /** @type {HTMLButtonElement} */($('spelling-confirm-ok')),
- /** @type {HTMLButtonElement} */($('spelling-confirm-cancel')),
- $('spelling-enabled-control')['pref'],
- $('spelling-enabled-control')['metric']),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(new HotwordConfirmDialog(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(ContentSettings.getInstance(),
- BrowserOptions.getInstance(),
- [$('privacyContentSettingsButton')]);
- PageManager.registerOverlay(ContentSettingsExceptionsArea.getInstance(),
- ContentSettings.getInstance());
- PageManager.registerOverlay(CookiesView.getInstance(),
- ContentSettings.getInstance(),
- [$('privacyContentSettingsButton'),
- $('show-cookies-button')]);
- PageManager.registerOverlay(CreateProfileOverlay.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(DisconnectAccountOverlay.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(EasyUnlockTurnOffOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('easy-unlock-turn-off-button')]);
- if (!cr.isMac) {
- PageManager.registerOverlay(EditDictionaryOverlay.getInstance(),
- LanguageOptions.getInstance(),
- [$('edit-custom-dictionary-button')]);
- }
- PageManager.registerOverlay(FontSettings.getInstance(),
- BrowserOptions.getInstance(),
- [$('fontSettingsCustomizeFontsButton')]);
- if (HandlerOptions && $('manage-handlers-button')) {
- PageManager.registerOverlay(HandlerOptions.getInstance(),
- ContentSettings.getInstance(),
- [$('manage-handlers-button')]);
- }
- PageManager.registerOverlay(HomePageOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('change-home-page')]);
- PageManager.registerOverlay(ImportDataOverlay.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(LanguageOptions.getInstance(),
- BrowserOptions.getInstance(),
- [$('language-button'),
- $('manage-languages')]);
- PageManager.registerOverlay(ManageProfileOverlay.getInstance(),
- BrowserOptions.getInstance());
- if (!cr.isChromeOS) {
- PageManager.registerOverlay(SupervisedUserCreateConfirmOverlay.
- getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(SupervisedUserImportOverlay.getInstance(),
- CreateProfileOverlay.getInstance());
- PageManager.registerOverlay(SupervisedUserLearnMoreOverlay.getInstance(),
- CreateProfileOverlay.getInstance());
- }
- PageManager.registerOverlay(PasswordManager.getInstance(),
- BrowserOptions.getInstance(),
- [$('manage-passwords')]);
- PageManager.registerOverlay(
- new ResetProfileSettingsOverlay(false /* isTriggered */),
- BrowserOptions.getInstance(),
- [$('reset-profile-settings')]);
- PageManager.registerOverlay(SearchEngineManager.getInstance(),
- BrowserOptions.getInstance(),
- [$('manage-default-search-engines')]);
- PageManager.registerOverlay(StartupOverlay.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(SyncSetupOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('customize-sync')]);
-
-// <if expr="is_win">
- PageManager.registerOverlay(
- new ResetProfileSettingsOverlay(true /* isTriggered */),
- BrowserOptions.getInstance());
-// </if>
-
- if (loadTimeData.valueExists('aboutOverlayTabTitle')) {
- PageManager.registerOverlay(help.HelpPage.getInstance(),
- BrowserOptions.getInstance());
- if (help.ChannelChangePage) {
- PageManager.registerOverlay(help.ChannelChangePage.getInstance(),
- help.HelpPage.getInstance());
- }
- }
- if (cr.isChromeOS) {
- PageManager.registerOverlay(AccountsOptions.getInstance(),
- BrowserOptions.getInstance(),
- [$('manage-accounts-button')]);
- PageManager.registerOverlay(BluetoothOptions.getInstance(),
- BrowserOptions.getInstance(),
- [$('bluetooth-add-device')]);
- PageManager.registerOverlay(BluetoothPairing.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(FactoryResetOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('factory-reset-restart')]);
- PageManager.registerOverlay(ChangePictureOptions.getInstance(),
- BrowserOptions.getInstance(),
- [$('account-picture')]);
- PageManager.registerOverlay(StorageClearDriveCacheOverlay.getInstance(),
- StorageManager.getInstance());
- PageManager.registerOverlay(DetailsInternetPage.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(DisplayOptions.getInstance(),
- BrowserOptions.getInstance(),
- [$('display-options')]);
- PageManager.registerOverlay(DisplayOverscan.getInstance(),
- DisplayOptions.getInstance());
- PageManager.registerOverlay(KeyboardOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('keyboard-settings-button')]);
- PageManager.registerOverlay(PointerOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('pointer-settings-button')]);
- PageManager.registerOverlay(PreferredNetworks.getInstance(),
- BrowserOptions.getInstance());
- PageManager.registerOverlay(StylusOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('stylus-settings-link')]);
- PageManager.registerOverlay(PowerOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('power-settings-link')]);
- PageManager.registerOverlay(QuickUnlockConfigureOverlay.getInstance(),
- BrowserOptions.getInstance(),
- [$('manage-screenlock')]);
- PageManager.registerOverlay(StorageManager.getInstance(),
- BrowserOptions.getInstance(),
- [$('storage-manager-button')]);
- PageManager.registerOverlay(ThirdPartyImeConfirmOverlay.getInstance(),
- LanguageOptions.getInstance());
- PageManager.registerOverlay(
- new ConfirmDialog(
- 'arcOptOutConfirm',
- loadTimeData.getString('arcOptOutConfirmOverlayTabTitle'),
- 'arc-opt-out-confirm-overlay',
- /** @type {HTMLButtonElement} */($('arc-opt-out-confirm-ok')),
- /** @type {HTMLButtonElement} */($('arc-opt-out-confirm-cancel')),
- $('android-apps-enabled')['pref'],
- $('android-apps-enabled')['metric'],
- undefined,
- false),
- BrowserOptions.getInstance());
- }
-
- if (!cr.isWindows && !cr.isMac) {
- PageManager.registerOverlay(CertificateBackupOverlay.getInstance(),
- CertificateManager.getInstance());
- PageManager.registerOverlay(CertificateEditCaTrustOverlay.getInstance(),
- CertificateManager.getInstance());
- PageManager.registerOverlay(CertificateImportErrorOverlay.getInstance(),
- CertificateManager.getInstance());
- PageManager.registerOverlay(CertificateManager.getInstance(),
- BrowserOptions.getInstance(),
- [$('certificatesManageButton')]);
- PageManager.registerOverlay(CertificateRestoreOverlay.getInstance(),
- CertificateManager.getInstance());
- }
-
- OptionsFocusManager.getInstance().initialize();
- Preferences.getInstance().initialize();
- AutomaticSettingsResetBanner.getInstance().initialize();
- OptionsPage.initialize();
- PageManager.initialize(BrowserOptions.getInstance());
- PageManager.addObserver(new uber.PageManagerObserver());
- uber.onContentFrameLoaded();
-
- var pageName = PageManager.getPageNameFromPath();
- // Still update history so that chrome://settings/nonexistant redirects
- // appropriately to chrome://settings/. If the URL matches, updateHistory_
- // will avoid the extra replaceState.
- var updateHistory = true;
- PageManager.showPageByName(pageName, updateHistory,
- {replaceState: true, hash: location.hash});
-
- var subpagesNavTabs = document.querySelectorAll('.subpages-nav-tabs');
- for (var i = 0; i < subpagesNavTabs.length; i++) {
- subpagesNavTabs[i].onclick = function(event) {
- OptionsPage.showTab(event.srcElement);
- };
- }
-
- window.setTimeout(function() {
- document.documentElement.classList.remove('loading');
- chrome.send('onFinishedLoadingOptions');
- chrome.send(
- 'metricsHandler:recordTime',
- ['Settings.TimeUntilInteractive', window.performance.now()]);
- }, 0);
-}
-
-document.documentElement.classList.add('loading');
-document.addEventListener('DOMContentLoaded', load);
-
-/**
- * Listener for the |beforeunload| event.
- */
-window.onbeforeunload = function() {
- PageManager.willClose();
-};
-
-/**
- * Listener for the |popstate| event.
- * @param {Event} e The |popstate| event.
- */
-window.onpopstate = function(e) {
- var pageName = PageManager.getPageNameFromPath();
- PageManager.setState(pageName, location.hash, e.state);
-};
diff --git a/chromium/chrome/browser/resources/options/options_bundle.js b/chromium/chrome/browser/resources/options/options_bundle.js
deleted file mode 100644
index 2dca0034861..00000000000
--- a/chromium/chrome/browser/resources/options/options_bundle.js
+++ /dev/null
@@ -1,130 +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.
-//
-// This file exists to aggregate all of the javascript used by the
-// settings page into a single file which will be flattened and served
-// as a single resource.
-// <include src="preferences.js">
-// <include src="controlled_setting.js">
-// <include src="deletable_item_list.js">
-// <include src="editable_text_field.js">
-// <include src="hotword_search_setting_indicator.js">
-// <include src="inline_editable_list.js">
-// <include src="options_page.js">
-// <include src="pref_ui.js">
-// <include src="settings_dialog.js">
-// <if expr="chromeos">
-// <include src="../chromeos/user_images_grid.js">
-// <include src="../help/channel_change_page.js">
-// <include src="../../../../ui/webui/resources/js/chromeos/ui_account_tweaks.js">
-// <include src="chromeos/onc_data.js">
-// <include src="chromeos/change_picture_options.js">
-// <include src="chromeos/internet_detail_ip_address_field.js">
-// <include src="chromeos/internet_detail.js">
-// <include src="chromeos/network_list.js">
-// <include src="chromeos/preferred_networks.js">
-// <include src="chromeos/bluetooth_device_list.js">
-// <include src="chromeos/bluetooth_add_device_overlay.js">
-// <include src="chromeos/bluetooth_pair_device_overlay.js">
-// <include src="chromeos/accounts_options.js">
-// <include src="chromeos/proxy_rules_list.js">
-// <include src="chromeos/accounts_user_list.js">
-// <include src="chromeos/accounts_user_name_edit.js">
-// <include src="chromeos/display_layout.js">
-// <include src="chromeos/display_layout_manager.js">
-// <include src="chromeos/display_layout_manager_multi.js">
-// <include src="chromeos/display_options.js">
-// <include src="chromeos/display_overscan.js">
-// <include src="chromeos/keyboard_overlay.js">
-// <include src="chromeos/stylus_overlay.js">
-// <include src="chromeos/pointer_overlay.js">
-// <include src="chromeos/quick_unlock_configure_overlay.js">
-// <include src="chromeos/storage_clear_drive_cache_overlay.js">
-// <include src="chromeos/storage_manager.js">
-// <include src="chromeos/third_party_ime_confirm_overlay.js">
-// <include src="chromeos/power_overlay.js">
-var AccountsOptions = options.AccountsOptions;
-var ChangePictureOptions = options.ChangePictureOptions;
-var DetailsInternetPage = options.internet.DetailsInternetPage;
-var DisplayOptions = options.DisplayOptions;
-var DisplayOverscan = options.DisplayOverscan;
-var BluetoothOptions = options.BluetoothOptions;
-var BluetoothPairing = options.BluetoothPairing;
-var KeyboardOverlay = options.KeyboardOverlay;
-var StylusOverlay = options.StylusOverlay;
-var PointerOverlay = options.PointerOverlay;
-var PowerOverlay = options.PowerOverlay;
-var QuickUnlockConfigureOverlay = options.QuickUnlockConfigureOverlay;
-var StorageClearDriveCacheOverlay = options.StorageClearDriveCacheOverlay;
-var StorageManager = options.StorageManager;
-var UIAccountTweaks = uiAccountTweaks.UIAccountTweaks;
-// </if>
-// <if expr="use_nss_certs">
-// <include src="certificate_tree.js">
-// <include src="certificate_manager.js">
-// <include src="certificate_restore_overlay.js">
-// <include src="certificate_backup_overlay.js">
-// <include src="certificate_edit_ca_trust_overlay.js">
-// <include src="certificate_import_error_overlay.js">
-var CertificateManager = options.CertificateManager;
-var CertificateRestoreOverlay = options.CertificateRestoreOverlay;
-var CertificateBackupOverlay = options.CertificateBackupOverlay;
-var CertificateEditCaTrustOverlay = options.CertificateEditCaTrustOverlay;
-var CertificateImportErrorOverlay = options.CertificateImportErrorOverlay;
-// </if>
-// <include src="alert_overlay.js">
-// <include src="autofill_edit_address_overlay.js">
-// <include src="autofill_edit_creditcard_overlay.js">
-// <include src="autofill_options.js">
-// <include src="autofill_options_list.js">
-// <include src="automatic_settings_reset_banner.js">
-// <include src="browser_options.js">
-// <include src="browser_options_profile_list.js">
-// <include src="browser_options_startup_page_list.js">
-// <include src="clear_browser_data_overlay.js">
-// <include src="clear_browser_data_history_notice_overlay.js">
-// <include src="confirm_dialog.js">
-// <include src="content_settings.js">
-// <include src="content_settings_exceptions_area.js">
-// <include src="content_settings_ui.js">
-// <include src="cookies_list.js">
-// <include src="cookies_view.js">
-// <include src="easy_unlock_turn_off_overlay.js">
-// <include src="factory_reset_overlay.js">
-// <include src="font_settings.js">
-// <if expr="enable_google_now">
-// <include src="geolocation_options.js">
-// </if>
-// <include src="handler_options.js">
-// <include src="handler_options_list.js">
-// <include src="home_page_overlay.js">
-// <include src="hotword_confirm_dialog.js">
-// <include src="import_data_overlay.js">
-// <include src="language_add_language_overlay.js">
-// <if expr="not is_macosx">
-// <include src="language_dictionary_overlay_word_list.js">
-// <include src="language_dictionary_overlay.js">
-// </if>
-// <include src="language_list.js">
-// <include src="language_options.js">
-// <include src="manage_profile_overlay.js">
-// <include src="options_focus_manager.js">
-// <include src="password_manager.js">
-// <include src="password_manager_list.js">
-// <include src="profiles_icon_grid.js">
-// <include src="reset_profile_settings_overlay.js">
-// <include src="search_engine_manager.js">
-// <include src="search_engine_manager_engine_list.js">
-// <include src="search_page.js">
-// <include src="startup_overlay.js">
-// <include src="supervised_user_create_confirm.js">
-// <include src="supervised_user_import.js">
-// <include src="supervised_user_learn_more.js">
-// <include src="supervised_user_list.js">
-// <include src="supervised_user_list_data.js">
-// <include src="../help/help_page.js">
-// <include src="sync_setup_overlay.js">
-// <include src="../uber/uber_page_manager_observer.js">
-// <include src="../uber/uber_utils.js">
-// <include src="options.js">
diff --git a/chromium/chrome/browser/resources/options/options_focus_manager.js b/chromium/chrome/browser/resources/options/options_focus_manager.js
deleted file mode 100644
index 9fc3f21a99a..00000000000
--- a/chromium/chrome/browser/resources/options/options_focus_manager.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-cr.define('options', function() {
- var FocusManager = cr.ui.FocusManager;
- var PageManager = cr.ui.pageManager.PageManager;
-
- function OptionsFocusManager() {
- }
-
- cr.addSingletonGetter(OptionsFocusManager);
-
- OptionsFocusManager.prototype = {
- __proto__: FocusManager.prototype,
-
- /** @override */
- getFocusParent: function() {
- var topPage = PageManager.getTopmostVisiblePage().pageDiv;
-
- // The default page and search page include a search field that is a
- // sibling of the rest of the page instead of a child. Thus, use the
- // parent node to allow the search field to receive focus.
- if (topPage.parentNode.id == 'page-container')
- return topPage.parentNode;
-
- return topPage;
- },
- };
-
- return {
- OptionsFocusManager: OptionsFocusManager,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/options_page.css b/chromium/chrome/browser/resources/options/options_page.css
deleted file mode 100644
index 485cdc76ca1..00000000000
--- a/chromium/chrome/browser/resources/options/options_page.css
+++ /dev/null
@@ -1,451 +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. */
-
-body {
- position: relative;
-}
-
-#main-content {
- bottom: 0;
- display: -webkit-box;
- left: 0;
- position: absolute;
- right: 0;
- top: 0;
-}
-
-#mainview {
- -webkit-box-align: stretch;
- bottom: 0;
- left: 0;
- margin: 0;
- position: absolute;
- right: 0;
- top: 0;
- z-index: 1;
-}
-
-#mainview-content {
- min-height: 100%;
- position: relative;
-}
-
-#page-container {
- box-sizing: border-box;
- max-width: 888px;
- min-width: 600px;
-}
-
-body #searchBox {
- position: fixed;
- z-index: 4;
-}
-
-div.disabled {
- color: #999;
-}
-
-.settings-row {
- display: block;
- margin: 0.65em 0;
-}
-
-.hbox {
- -webkit-box-orient: horizontal;
- display: -webkit-box;
-}
-
-.vbox {
- -webkit-box-orient: vertical;
- display: -webkit-box;
-}
-
-.box-align-center {
- -webkit-box-align: center;
-}
-
-.stretch {
- -webkit-box-flex: 1;
-}
-
-.raw-button,
-.raw-button:hover,
-.raw-button:active {
- background-color: transparent;
- background-repeat: no-repeat;
- border: none;
- box-shadow: none;
- min-width: 0;
- padding: 1px 6px;
-}
-
-.bottom-strip {
- border-top: none;
- bottom: 0;
- padding: 12px;
- position: absolute;
- right: 0;
-}
-
-/* Omit top padding (currently only on #settings) whenever the search page is
- * showing. */
-#searchPage:not([hidden]) + #settings {
- padding-top: 0;
-}
-
-.page list {
- /* Min height is a multiple of the list item height (32) */
- min-height: 192px;
-}
-
-.option {
- margin-top: 0;
-}
-
-.touch-slider {
- -webkit-appearance: slider-horizontal;
-}
-
-.settings-list,
-.settings-list-empty {
- border: 1px solid #d9d9d9;
- border-radius: 2px;
-}
-
-.settings-list-empty {
- background-color: #f4f4f4;
- box-sizing: border-box;
- min-height: 125px;
- padding-left: 20px;
- padding-top: 20px;
-}
-
-
-/* Editable text field properties */
-.editable-text-field > * {
- -webkit-box-align: center;
- border: none;
- box-sizing: border-box;
- display: -webkit-box;
- height: 20px;
- margin: 0;
- transition: 150ms background-color;
-}
-
-.editable-text-field > .spacer {
- /* The above height rule should not apply to spacers. */
- height: 0;
-}
-
-.editable-text-field .editable-text {
- padding: 2px 3px;
-}
-
-.editable-text-field .static-text {
- height: 24px;
- overflow: hidden;
- padding: 3px 4px;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.editable-text-field:not([editable]) > [displaymode='edit'] {
- display: none;
-}
-
-.editable-text-field[editable] > [displaymode='static'] {
- display: none;
-}
-
-.editable-text-field[empty] > input[type='text'] {
- color: #ccc;
- font-style: italic;
-}
-
-.editable-text-field[disabled] {
- opacity: 0.6;
-}
-
-/* Editable List properties */
-list > * {
- -webkit-box-align: center;
- border: none;
- border-radius: 0; /* TODO(dbeam): Is this necessary? */
- box-sizing: border-box;
- display: -webkit-box;
- height: 32px;
- margin: 0;
- transition: 150ms background-color;
-}
-
-list > .spacer {
- /* The above height rule should not apply to spacers. When redraw is called
- on the list they will be given an explicit element height but this ensures
- they have 0 height to begin with. */
- height: 0;
-}
-
-list:not([disabled]) > :hover {
- background-color: rgb(228, 236, 247);
-}
-
-/* Note: If this becomes the list style for other WebUI pages these rules can be
- * simplified (since they wont need to override other rules). */
-
-list:not([has-element-focus]) > [selected],
-list:not([has-element-focus]) > [lead][selected] {
- background-color: #d0d0d0;
- background-image: none;
-}
-
-list[has-element-focus] > [selected],
-list[has-element-focus] > [lead][selected],
-list:not([has-element-focus]) > [selected]:hover,
-list:not([has-element-focus]) > [selected][lead]:hover {
- background-color: rgb(187, 206, 233);
- background-image: none;
-}
-
-.settings-list[has-element-focus] > [lead],
-.settings-list[has-element-focus] > [lead][selected] {
- border-bottom: 1px solid rgb(120, 146, 180);
- border-top: 1px solid rgb(120, 146, 180);
-}
-
-.settings-list[has-element-focus] > [lead]:nth-child(2),
-.settings-list[has-element-focus] > [lead][selected]:nth-child(2) {
- border-top: 1px solid transparent;
-}
-
-.settings-list[has-element-focus] > [lead]:nth-last-child(2),
-.settings-list[has-element-focus] > [lead][selected]:nth-last-child(2) {
- border-bottom: 1px solid transparent;
-}
-
-.settings-list[disabled] > [lead][selected],
-.settings-list[disabled]:focus > [lead][selected] {
- border: none;
-}
-
-list[disabled] {
- opacity: 0.6;
-}
-
-list > .heading {
- color: #666;
-}
-
-list > .heading:hover {
- background-color: transparent;
- border-color: transparent;
-}
-
-list .deletable-item {
- -webkit-box-align: center;
- outline: none;
-}
-
-list .deletable-item > :first-child {
- -webkit-box-align: center;
- -webkit-box-flex: 1;
- -webkit-padding-end: 5px;
- display: -webkit-box;
-}
-
-list .row-delete-button {
- background-color: transparent;
- background-image: -webkit-image-set(
- url(../../../../ui/resources/default_100_percent/close_2.png) 1x,
- url(../../../../ui/resources/default_200_percent/close_2.png) 2x);
- border: none;
- display: block;
- height: 16px;
- opacity: 1;
- transition: 150ms opacity;
- width: 16px;
-}
-
-list > *:not(:hover):not([selected]):not([lead]) .row-delete-button,
-list:not([has-element-focus]) > *:not(:hover):not([selected])
- .row-delete-button,
-list[disabled] .row-delete-button,
-list .row-delete-button[disabled] {
- opacity: 0;
- pointer-events: none;
-}
-
-/* HostedApp entries use the disabled closing button to display the App's
- * favicon, as an indicator that instead of deleting the permission here
- * the user has to remove the hosted app.*/
-list div[role='listitem'][managedby='HostedApp'] .row-delete-button {
- opacity: 1;
-}
-
-list .row-delete-button:hover {
- background-image: -webkit-image-set(
- url(../../../../ui/resources/default_100_percent/close_2_hover.png) 1x,
- url(../../../../ui/resources/default_200_percent/close_2_hover.png) 2x);
-}
-
-list .row-delete-button:active {
- background-image: -webkit-image-set(
- url(../../../../ui/resources/default_100_percent/close_2_pressed.png)
- 1x,
- url(../../../../ui/resources/default_200_percent/close_2_pressed.png)
- 2x);
-}
-
-list .static-text {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-list[type='text'][inlineeditable] input {
- box-sizing: border-box;
- margin: 0;
- width: 100%;
-}
-
-list > :not([editing]) [displaymode='edit'] {
- display: none;
-}
-
-list > [editing] [displaymode='static'] {
- /* Don't use display:none or visibility:hidden because we need to keep an
- * element focusable.
- * We shrink only height. We don't shrink width to avoid to change the size
- * of containing boxes. */
- border-bottom: 0 !important;
- border-top: 0 !important;
- height: 0 !important;
- margin-bottom: 0 !important;
- margin-top: 0 !important;
- overflow: hidden;
- pointer-events: none;
-}
-
-list > [editing] input:invalid {
- background-color: pink;
-}
-
-.list-inline-button {
- -webkit-appearance: none;
- background: rgb(138, 170, 237);
- border: none;
- border-radius: 2px;
- color: white;
- font-weight: bold;
- opacity: 0.7;
- transition: opacity 150ms;
-}
-
-.list-inline-button:hover {
- opacity: 1;
-}
-
-.option-name {
- -webkit-padding-end: 5px;
-}
-
-.favicon-cell {
- -webkit-padding-start: 20px;
- background-position: left;
- background-repeat: no-repeat;
- background-size: 16px;
-}
-
-input[type='url'].favicon-cell {
- -webkit-padding-start: 22px;
- background-position-x: 4px;
-}
-
-html[dir=rtl] input.favicon-cell,
-input[dir=rtl].favicon-cell {
- background-position-x: -webkit-calc(100% - 4px);
-}
-
-list .favicon-cell {
- -webkit-margin-start: 7px;
- -webkit-padding-start: 26px;
- display: block;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-html[dir=rtl] list .favicon-cell {
- background-position: right;
-}
-
-html[enable-background-mode=false] #background-mode-section {
- display: none;
-}
-
-/* UI Controls */
-
-/* LIST */
-.settings-list[has-element-focus] {
-<if expr="not is_macosx">
- outline: 1px solid rgba(0, 128, 256, 0.5);
- outline-offset: -2px;
-</if>
-<if expr="is_macosx">
- /* This matches the native list outline on Mac */
- outline-color: rgb(117, 154, 217);
- outline-offset: -1px;
- outline-style: auto;
- outline-width: 5px;
-</if>
-}
-
-.suboption {
- -webkit-margin-start: 23px;
-}
-
-list.autocomplete-suggestions {
- background-color: white;
- border: 1px solid #aaa;
- border-radius: 2px;
- min-height: 0;
- opacity: 0.9;
- position: fixed;
- z-index: 3;
-}
-
-list.autocomplete-suggestions > div {
- height: auto;
-}
-
-list.autocomplete-suggestions:not([has-element-focus]) > [selected],
-list.autocomplete-suggestions:not([has-element-focus]) > [lead][selected] {
- background-color: rgb(187, 206, 233);
-}
-
-html:not(.focus-outline-visible)
-:enabled:focus:-webkit-any(input[type='checkbox'], input[type='radio']) {
- /* Cancel border-color for :focus specified in widgets.css. */
- border-color: rgba(0, 0, 0, 0.25);
-}
-
-html:not([hasFlashPlugin]) .flash-plugin-area,
-/* If the Flash plug-in supports the NPP_ClearSiteData API, we don't need to
- * show the link to the Flash storage settings manager: */
-html[flashPluginSupportsClearSiteData] .flash-plugin-area,
-html:not([flashPluginSupportsClearSiteData]) .clear-plugin-lso-data-enabled,
-html[flashPluginSupportsClearSiteData] .clear-plugin-lso-data-disabled,
-html:not([enablePepperFlashSettings]) .pepper-flash-settings {
- display: none;
-}
-
-.standalone-action-link {
- padding: 0;
-}
-
-:-webkit-any(.checkbox, .radio) label ~ a {
- display: inline-block;
- /* Matches padding of -webkit-any(.checkbox, .radio) */
- padding-bottom: 7px;
- vertical-align: bottom;
-}
diff --git a/chromium/chrome/browser/resources/options/options_page.js b/chromium/chrome/browser/resources/options/options_page.js
deleted file mode 100644
index 9700c7420b3..00000000000
--- a/chromium/chrome/browser/resources/options/options_page.js
+++ /dev/null
@@ -1,94 +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.
-
-cr.define('options', function() {
- /** @const */ var FocusOutlineManager = cr.ui.FocusOutlineManager;
-
- var OptionsPage = {
- /**
- * This is the absolute difference maintained between standard and
- * fixed-width font sizes. Refer http://crbug.com/91922.
- * @const
- */
- SIZE_DIFFERENCE_FIXED_STANDARD: 3,
-
- /**
- * Initializes the complete options page. This will cause all C++ handlers
- * to be invoked to do final setup.
- */
- initialize: function() {
- chrome.send('coreOptionsInitialize');
- },
-
- /**
- * Shows the tab contents for the given navigation tab.
- * @param {Node} tab The tab that the user clicked.
- */
- showTab: function(tab) {
- // Search parents until we find a tab, or the nav bar itself. This allows
- // tabs to have child nodes, e.g. labels in separately-styled spans.
- while (tab && tab.classList &&
- !tab.classList.contains('subpages-nav-tabs') &&
- !tab.classList.contains('tab')) {
- tab = tab.parentNode;
- }
- if (!tab || !tab.classList || !tab.classList.contains('tab'))
- return;
-
- // Find tab bar of the tab.
- var tabBar = tab;
- while (tabBar && tabBar.classList &&
- !tabBar.classList.contains('subpages-nav-tabs')) {
- tabBar = tabBar.parentNode;
- }
- if (!tabBar || !tabBar.classList)
- return;
-
- if (tabBar.activeNavTab != null) {
- tabBar.activeNavTab.classList.remove('active-tab');
- $(tabBar.activeNavTab.getAttribute('tab-contents')).classList.
- remove('active-tab-contents');
- }
-
- tab.classList.add('active-tab');
- $(tab.getAttribute('tab-contents')).classList.add('active-tab-contents');
- tabBar.activeNavTab = tab;
- },
-
- /**
- * Shows or hides options for clearing Flash LSOs.
- * @param {boolean} enabled Whether plugin data can be cleared.
- */
- setClearPluginLSODataEnabled: function(enabled) {
- if (enabled) {
- document.documentElement.setAttribute(
- 'flashPluginSupportsClearSiteData', '');
- } else {
- document.documentElement.removeAttribute(
- 'flashPluginSupportsClearSiteData');
- }
- if (navigator.plugins['Shockwave Flash'])
- document.documentElement.setAttribute('hasFlashPlugin', '');
- },
-
- /**
- * Shows or hides Pepper Flash settings.
- * @param {boolean} enabled Whether Pepper Flash settings should be enabled.
- */
- setPepperFlashSettingsEnabled: function(enabled) {
- if (enabled) {
- document.documentElement.setAttribute(
- 'enablePepperFlashSettings', '');
- } else {
- document.documentElement.removeAttribute(
- 'enablePepperFlashSettings');
- }
- },
- };
-
- // Export
- return {
- OptionsPage: OptionsPage
- };
-});
diff --git a/chromium/chrome/browser/resources/options/options_polymer.html b/chromium/chrome/browser/resources/options/options_polymer.html
deleted file mode 100644
index afbf9fd4885..00000000000
--- a/chromium/chrome/browser/resources/options/options_polymer.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-radio-group/paper-radio-group.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-radio-button/paper-radio-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-checkbox/paper-checkbox.html">
-<link rel="import" href="chrome://settings-frame/people_page/lock_screen.html">
diff --git a/chromium/chrome/browser/resources/options/password_manager.css b/chromium/chrome/browser/resources/options/password_manager.css
deleted file mode 100644
index 33bc94b2a59..00000000000
--- a/chromium/chrome/browser/resources/options/password_manager.css
+++ /dev/null
@@ -1,33 +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. */
-
-#password-manager > div.content-area {
- width: 600px;
-}
-
-#password-search-column {
- bottom: 10px;
- position: absolute;
- right: 0;
-}
-
-html[dir=rtl] #password-search-column {
- left: 0;
- right: auto;
-}
-
-#password-list-headers {
- position: relative;
- width: 100%;
-}
-
-#passwords-title {
- display: inline-block;
-}
-
-#saved-passwords-list,
-#password-exceptions-list {
- max-height: 192px; /* For performance (crbug.com/651049). */
- min-height: 128px; /* Smallest value rendering enough initial list items. */
-}
diff --git a/chromium/chrome/browser/resources/options/password_manager.html b/chromium/chrome/browser/resources/options/password_manager.html
deleted file mode 100644
index c128a3be325..00000000000
--- a/chromium/chrome/browser/resources/options/password_manager.html
+++ /dev/null
@@ -1,67 +0,0 @@
-<div id="password-manager" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{passwordsPage}</h1>
- <div class="content-area">
- <div class="password-manager-home">
- <div id="auto-signin-block" class="checkbox">
- <label>
- <input pref="credentials_enable_autosignin" type="checkbox">
- <span>$i18n{autoSigninTitle}</span>
- </label>
- <div class="setting-extra-description">
- <span>$i18n{autoSigninDescription}</span>
- </div>
- </div>
- <div id="password-list-headers">
- <div id="passwords-title">
- <h3>$i18n{savedPasswordsTitle}</h3>
- </div>
- <div id="password-search-column">
- <input id="password-search-box" type="search"
- placeholder="$i18n{passwordSearchPlaceholder}" incremental>
- </div>
- </div>
- <list id="saved-passwords-list" class="settings-list"></list>
- <div id="saved-passwords-list-empty-placeholder"
- class="settings-list-empty" hidden>
- <span>$i18n{passwordsNoPasswordsDescription}</span>
- <a target="_blank"
- href="$i18nRaw{passwordManagerLearnMoreURL}">$i18n{learnMore}</a>
- </div>
- <div id="password-manager-import-export" class="action-area" hidden>
- <div class="button-strip">
- <button id="password-manager-import" class="password-manager-home">
- $i18n{passwordManagerImportPasswordButtonText}
- </button>
- <button id="password-manager-export" class="password-manager-home">
- $i18n{passwordManagerExportPasswordButtonText}
- </button>
- </div>
- </div>
- <h3>$i18n{passwordExceptionsTitle}</h3>
- <list id="password-exceptions-list" class="settings-list"></list>
- <div id="password-exceptions-list-empty-placeholder" hidden
- class="settings-list-empty">
- <span>$i18n{passwordsNoExceptionsDescription}</span>
- <a id="exceptions-learn-more" target="_blank"
- href="$i18nRaw{passwordManagerLearnMoreURL}">$i18n{learnMore}</a>
- </div>
- </div>
- </div>
- <div class="action-area">
- <span id="manage-passwords-span">
- <span>$i18n{passwordsManagePasswordsBeforeLinkText}</span>
- <a id="manage-passwords-link" target="_blank"
- href="$i18nRaw{passwordsManagePasswordsLink}">
- $i18n{passwordsManagePasswordsLinkText}
- </a>
- <span>$i18n{passwordsManagePasswordsAfterLinkText}</span>
- </span>
- <div class="spacer-div"></div>
- <div class="button-strip">
- <button id="password-manager-confirm" class="password-manager-home">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/password_manager.js b/chromium/chrome/browser/resources/options/password_manager.js
deleted file mode 100644
index 5d4825b8a7f..00000000000
--- a/chromium/chrome/browser/resources/options/password_manager.js
+++ /dev/null
@@ -1,285 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /////////////////////////////////////////////////////////////////////////////
- // PasswordManager class:
-
- /**
- * Encapsulated handling of password and exceptions page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function PasswordManager() {
- this.activeNavTab = null;
- Page.call(this, 'passwords',
- loadTimeData.getString('passwordsPageTabTitle'),
- 'password-manager');
- }
-
- cr.addSingletonGetter(PasswordManager);
-
- PasswordManager.prototype = {
- __proto__: Page.prototype,
-
- /**
- * The saved passwords list.
- * @type {options.DeletableItemList}
- * @private
- */
- savedPasswordsList_: null,
-
- /**
- * The password exceptions list.
- * @type {options.DeletableItemList}
- * @private
- */
- passwordExceptionsList_: null,
-
- /**
- * The timer id of the timer set on search query change events.
- * @type {number}
- * @private
- */
- queryDelayTimerId_: 0,
-
- /**
- * The most recent search query, or null if the query is empty.
- * @type {?string}
- * @private
- */
- lastQuery_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('password-manager-confirm').onclick = function() {
- PageManager.closeOverlay();
- };
-
- $('password-manager-import').onclick = function() {
- chrome.send('importPassword');
- };
-
- $('password-manager-export').onclick = function() {
- chrome.send('exportPassword');
- };
-
- $('password-search-box').addEventListener('search',
- this.handleSearchQueryChange_.bind(this));
-
- $('exceptions-learn-more').onclick = function() {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_PasswordManagerExceptionsLearnMore']);
- return true; // Always follow the href
- };
-
- this.createSavedPasswordsList_();
- this.createPasswordExceptionsList_();
- },
-
- /** @override */
- canShowPage: function() {
- return !(cr.isChromeOS && UIAccountTweaks.loggedInAsGuest());
- },
-
- /** @override */
- didShowPage: function() {
- // Updating the password lists may cause a blocking platform dialog pop up
- // (Mac, Linux), so we delay this operation until the page is shown.
- chrome.send('updatePasswordLists');
- $('password-search-box').focus();
- },
-
- /**
- * Creates, decorates and initializes the saved passwords list.
- * @private
- */
- createSavedPasswordsList_: function() {
- var savedPasswordsList = $('saved-passwords-list');
- options.passwordManager.PasswordsList.decorate(savedPasswordsList);
- this.savedPasswordsList_ = assertInstanceof(savedPasswordsList,
- options.DeletableItemList);
- },
-
- /**
- * Creates, decorates and initializes the password exceptions list.
- * @private
- */
- createPasswordExceptionsList_: function() {
- var passwordExceptionsList = $('password-exceptions-list');
- options.passwordManager.PasswordExceptionsList.decorate(
- passwordExceptionsList);
- this.passwordExceptionsList_ = assertInstanceof(passwordExceptionsList,
- options.DeletableItemList);
- },
-
- /**
- * Handles search query changes.
- * @param {!Event} e The event object.
- * @private
- */
- handleSearchQueryChange_: function(e) {
- if (this.queryDelayTimerId_)
- window.clearTimeout(this.queryDelayTimerId_);
-
- // Searching cookies uses a timeout of 500ms. We use a shorter timeout
- // because there are probably fewer passwords and we want the UI to be
- // snappier since users will expect that it's "less work."
- this.queryDelayTimerId_ = window.setTimeout(
- this.searchPasswords_.bind(this), 250);
-
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_PasswordManagerSearch']);
- },
-
- /**
- * Search passwords using text in |password-search-box|.
- * @private
- */
- searchPasswords_: function() {
- this.queryDelayTimerId_ = 0;
- var filter = $('password-search-box').value;
- filter = (filter == '') ? null : filter;
- if (this.lastQuery_ != filter) {
- this.lastQuery_ = filter;
- // Searching for passwords has the side effect of requerying the
- // underlying password store. This is done intentionally, as on OS X and
- // Linux they can change from outside and we won't be notified of it.
- chrome.send('updatePasswordLists');
- }
- },
-
- /**
- * Updates the list with the given entries and updates the visibility of the
- * list and empty list placeholder.
- * @param {!cr.ui.List} list The list to toggle visilibility for.
- * @param {!Array} entries The list of entries.
- */
- updateListAndVisibility_: function(list, entries) {
- // Setting the dataModel results in a redraw of the viewport, which is why
- // the visibility needs to be updated first. Otherwise, redraw will not
- // render the updated entries when transitioning from a previously empty
- // list to a non-empty one. The attribute list.hidden would be true in
- // this case, resulting in |redraw()| not adding the new elements to the
- // viewport and thus showing a empty list to the user
- // (http://crbug.com/672869).
- var empty = entries.length == 0;
- var listPlaceHolderID = list.id + '-empty-placeholder';
- list.hidden = empty;
- $(listPlaceHolderID).hidden = !empty;
- list.dataModel = new ArrayDataModel(entries);
- },
-
- /**
- * Updates the data model for the saved passwords list with the values from
- * |entries|.
- * @param {!Array} entries The list of saved password data.
- */
- setSavedPasswordsList_: function(entries) {
- if (this.lastQuery_) {
- // Implement password searching here in javascript, rather than in C++.
- // The number of saved passwords shouldn't be too big for us to handle.
- var query = this.lastQuery_;
- var filter = function(entry, index, list) {
- // Search both shown URL and username.
- var shownOrigin = entry[options.passwordManager.SHOWN_ORIGIN_FIELD];
- var username = entry[options.passwordManager.USERNAME_FIELD];
- if (shownOrigin.toLowerCase().indexOf(query.toLowerCase()) >= 0 ||
- username.toLowerCase().indexOf(query.toLowerCase()) >= 0) {
- // Keep the original index so we can delete correctly. See also
- // deleteItemAtIndex() in password_manager_list.js that uses this.
- entry[options.passwordManager.ORIGINAL_INDEX_FIELD] = index;
- return true;
- }
- return false;
- };
- entries = entries.filter(filter);
- }
- this.updateListAndVisibility_(assert(this.savedPasswordsList_), entries);
- },
-
- /**
- * Updates the data model for the password exceptions list with the values
- * from |entries|.
- * @param {!Array} entries The list of password exception data.
- */
- setPasswordExceptionsList_: function(entries) {
- this.updateListAndVisibility_(
- assert(this.passwordExceptionsList_), entries);
- },
-
- /**
- * Reveals the password for a saved password entry. This is called by the
- * backend after it has authenticated the user.
- * @param {number} index The original index of the entry in the model.
- * @param {string} password The saved password.
- */
- showPassword_: function(index, password) {
- var model = this.savedPasswordsList_.dataModel;
- if (this.lastQuery_) {
- // When a filter is active, |index| does not represent the current
- // index in the model, but each entry stores its original index, so
- // we can find the item using a linear search.
- for (var i = 0; i < model.length; ++i) {
- if (model.item(i)[options.passwordManager.ORIGINAL_INDEX_FIELD] ==
- index) {
- index = i;
- break;
- }
- }
- }
-
- // Reveal the password in the UI.
- var item = this.savedPasswordsList_.getListItemByIndex(index);
- item.showPassword(password);
- },
-
- /** @private */
- showImportExportButton_: function() {
- $('password-manager-import-export').hidden = false;
- },
- };
-
- /**
- * Removes a saved password.
- * @param {number} rowIndex indicating the row to remove.
- */
- PasswordManager.removeSavedPassword = function(rowIndex) {
- chrome.send('removeSavedPassword', [String(rowIndex)]);
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_PasswordManagerDeletePassword']);
- };
-
- /**
- * Removes a password exception.
- * @param {number} rowIndex indicating the row to remove.
- */
- PasswordManager.removePasswordException = function(rowIndex) {
- chrome.send('removePasswordException', [String(rowIndex)]);
- };
-
- PasswordManager.requestShowPassword = function(index) {
- chrome.send('requestShowPassword', [index]);
- };
-
- // Forward public APIs to private implementations on the singleton instance.
- cr.makePublic(PasswordManager, [
- 'setSavedPasswordsList',
- 'setPasswordExceptionsList',
- 'showImportExportButton',
- 'showPassword',
- ]);
-
- // Export
- return {
- PasswordManager: PasswordManager
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/password_manager_list.css b/chromium/chrome/browser/resources/options/password_manager_list.css
deleted file mode 100644
index 8ead88c22d4..00000000000
--- a/chromium/chrome/browser/resources/options/password_manager_list.css
+++ /dev/null
@@ -1,95 +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. */
-
-#saved-passwords-list .list-inline-button {
- background: rgb(138, 170, 237);
- font-size: 0.9em;
- height: 18px;
- margin-left: 2px;
- margin-right: 2px;
- padding: 0 2px;
- position: absolute;
- top: 3px;
- transition: opacity 150ms;
-}
-
-html[dir='ltr'] #saved-passwords-list .list-inline-button {
- right: 2px;
-}
-
-html[dir='rtl'] #saved-passwords-list .list-inline-button {
- left: 2px;
-}
-
-input.inactive-item {
- background: transparent;
- border: none;
-}
-
-#saved-passwords-list .url {
- box-sizing: border-box;
- width: 40%;
-}
-
-#saved-passwords-list .deletable-item:not(:hover) a:not(:focus) {
- color: black;
- text-decoration: none;
-}
-
-#saved-passwords-list .name {
- -webkit-box-flex: 1;
- width: 30%;
-}
-
-#saved-passwords-list .url,
-#password-exceptions-list .url {
- -webkit-user-select: text;
-}
-
-#saved-passwords-list .password,
-#saved-passwords-list .federation {
- -webkit-box-flex: 1;
- position: relative;
- width: 30%;
-}
-
-#saved-passwords-list .password input[type='password'],
-#saved-passwords-list .password input[type='text'] {
- box-sizing: border-box;
- width: 100%;
-}
-
-#password-exceptions-list .url {
- -webkit-box-flex: 1;
-}
-
-#saved-passwords-list .url,
-#saved-passwords-list .name,
-#saved-passwords-list .federation,
-#password-exceptions-list .url {
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-html[dir='ltr'] #saved-passwords-list .url,
-html[dir='ltr'] #password-exceptions-list .url {
- -webkit-margin-end: 1em;
- -webkit-margin-start: 0;
- -webkit-padding-end: 2em;
- -webkit-padding-start: 1em;
- direction: rtl;
- text-align: left;
-}
-
-html[dir='rtl'] #saved-passwords-list .url,
-html[dir='rtl'] #password-exceptions-list .url {
- -webkit-margin-end: 0;
- -webkit-margin-start: 1em;
- -webkit-padding-end: 1em;
- -webkit-padding-start: 2em;
- /* Explicitly mention the direction, which, while the same, is independent of
- * the surrounding text the for URLs. */
- direction: rtl;
- text-align: right;
-}
diff --git a/chromium/chrome/browser/resources/options/password_manager_list.js b/chromium/chrome/browser/resources/options/password_manager_list.js
deleted file mode 100644
index 9fd160f57fd..00000000000
--- a/chromium/chrome/browser/resources/options/password_manager_list.js
+++ /dev/null
@@ -1,552 +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.
-
-cr.define('options.passwordManager', function() {
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
- /** @const */ var DeletableItemList = options.DeletableItemList;
- /** @const */ var DeletableItem = options.DeletableItem;
- /** @const */ var List = cr.ui.List;
-
- // The following constants should be synchronized with the constants in
- // chrome/browser/ui/webui/options/password_manager_handler.cc.
- /** @const */ var URL_FIELD = 'url';
- /** @const */ var SHOWN_ORIGIN_FIELD = 'shownOrigin';
- /** @const */ var IS_ANDROID_URI_FIELD = 'isAndroidUri';
- /** @const */ var IS_CLICKABLE_FIELD = 'isClickable';
- /** @const */ var IS_SECURE_FIELD = 'isSecure';
- /** @const */ var USERNAME_FIELD = 'username';
- /** @const */ var PASSWORD_FIELD = 'password';
- /** @const */ var FEDERATION_FIELD = 'federation';
- /** @const */ var ORIGINAL_INDEX_FIELD = 'index';
-
- /**
- * Creates a new passwords list item.
- * @param {cr.ui.ArrayDataModel} dataModel The data model that contains this
- * item.
- * @param {Object} entry A dictionary of data on new list item. When the
- * list has been filtered, one more element [index] may be present.
- * @param {boolean} showPasswords If true, add a button to the element to
- * allow the user to reveal the saved password.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function PasswordListItem(dataModel, entry, showPasswords) {
- var el = cr.doc.createElement('div');
- el.dataItem = entry;
- el.dataModel = dataModel;
- el.__proto__ = PasswordListItem.prototype;
- el.showPasswords_ = showPasswords;
- el.decorate();
-
- return el;
- }
-
- /**
- * Returns title for password's origin. If the origin is not clickable,
- * returns the origin as it is. For clickable origins, removes the scheme if
- * the url is insecure and removes trailing punctuation symbols.
- * @param {Object} item A dictionary of data on the list item.
- * @return {string} The title for password's origin.
- */
- function getTitleForPasswordOrigin(item) {
- var title = item.url;
- if (!item.isClickable)
- return title;
- if (!item.isSecure) {
- var ind = title.indexOf('://');
- if (ind >= 0) {
- title = title.substring(ind + 3);
- }
- }
- return title;
- }
-
- /**
- * Helper function that creates an HTML element for displaying the link to
- * the origin of saved password.
- * @param {Object} item A dictionary of data on the list item.
- * @param {Element} urlDiv div-element that will enclose the created
- * element.
- * @return {Element} The element for displaying the link to the origin.
- */
- function createUrlLink(item, urlDiv) {
- var urlLink;
- if (item.isClickable) {
- urlLink = item.ownerDocument.createElement('a');
- urlLink.href = item.url;
- urlLink.setAttribute('target', '_blank');
- } else {
- urlLink = item.ownerDocument.createElement('span');
- }
- urlLink.textContent = item.shownOrigin;
- urlLink.addEventListener('focus', function() {
- item.handleFocus();
- }.bind(item));
- return urlLink;
- }
-
- /**
- * Helper function that creates an HTML element for displaying the origin of
- * saved password. It also sets some properties in |item|.
- * @param {Object} item A dictionary of data on the list item.
- * @return {Element} The element for displaying the origin of saved password.
- */
- function createUrlDiv(item) {
- var urlDiv = cr.doc.createElement('div');
- urlDiv.className = 'favicon-cell url';
- urlDiv.setAttribute('title', getTitleForPasswordOrigin(item));
- urlDiv.style.backgroundImage = cr.icon.getFavicon(item.url);
-
- item.urlLink = createUrlLink(item, urlDiv);
- urlDiv.appendChild(item.urlLink);
-
- if (item.isAndroidUri && item.isClickable) {
- item.androidUriSuffix = cr.doc.createElement('span');
- item.androidUriSuffix.textContent =
- loadTimeData.getString('androidUriSuffix');
- urlDiv.appendChild(item.androidUriSuffix);
- }
-
- item.urlDiv = urlDiv;
- return urlDiv;
- }
-
- PasswordListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /** @override */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- // The URL of the site.
- this.contentElement.appendChild(createUrlDiv(this));
-
- // The stored username.
- var usernameDiv = this.ownerDocument.createElement('div');
- usernameDiv.className = 'name';
- usernameDiv.title = this.username;
- this.contentElement.appendChild(usernameDiv);
- var usernameInput = this.ownerDocument.createElement('input');
- usernameInput.type = 'text';
- usernameInput.className = 'inactive-item';
- usernameInput.readOnly = true;
- usernameInput.value = this.username;
- usernameInput.addEventListener('focus', function() {
- this.handleFocus();
- }.bind(this));
- usernameDiv.appendChild(usernameInput);
- this.usernameField = usernameInput;
-
- if (this.federation) {
- // The federation.
- var federationDiv = this.ownerDocument.createElement('div');
- federationDiv.className = 'federation';
- federationDiv.textContent = this.federation;
- federationDiv.title = this.federation;
- this.contentElement.appendChild(federationDiv);
- } else {
- // The stored password.
- var passwordInputDiv = this.ownerDocument.createElement('div');
- passwordInputDiv.className = 'password';
-
- // The password input field.
- var passwordInput = this.ownerDocument.createElement('input');
- passwordInput.type = 'password';
- passwordInput.className = 'inactive-item';
- passwordInput.readOnly = true;
- passwordInput.value = this.showPasswords_ ? this.password : '********';
- passwordInputDiv.appendChild(passwordInput);
- passwordInput.addEventListener('focus', function() {
- this.handleFocus();
- }.bind(this));
- this.passwordField = passwordInput;
-
- // The show/hide button.
- if (this.showPasswords_) {
- var button = this.ownerDocument.createElement('button');
- button.hidden = true;
- button.className = 'list-inline-button custom-appearance';
- button.textContent = loadTimeData.getString('passwordShowButton');
- button.addEventListener('click', this.onClick_.bind(this), true);
- button.addEventListener('mousedown', function(event) {
- // Don't focus on this button by mousedown.
- event.preventDefault();
- // Don't handle list item selection. It causes focus change.
- event.stopPropagation();
- }, false);
- button.addEventListener('focus', function() {
- this.handleFocus();
- }.bind(this));
- passwordInputDiv.appendChild(button);
- this.passwordShowButton = button;
- }
- this.contentElement.appendChild(passwordInputDiv);
- }
- this.setFocusable_(false);
- },
-
- /** @override */
- selectionChanged: function() {
- var usernameInput = this.usernameField;
- var passwordInput = this.passwordField;
- var button = this.passwordShowButton;
-
- this.setFocusable_(this.selected);
-
- if (this.selected) {
- usernameInput.classList.remove('inactive-item');
- if (button) {
- passwordInput.classList.remove('inactive-item');
- button.hidden = false;
- passwordInput.focus();
- } else {
- usernameInput.focus();
- }
- } else {
- usernameInput.classList.add('inactive-item');
- if (button) {
- passwordInput.classList.add('inactive-item');
- button.hidden = true;
- }
- }
- },
-
- /**
- * Set the focusability of this row.
- * @param {boolean} focusable
- * @private
- */
- setFocusable_: function(focusable) {
- var tabIndex = focusable ? 0 : -1;
- this.urlLink.tabIndex = tabIndex;
- this.usernameField.tabIndex = tabIndex;
- this.closeButtonElement.tabIndex = tabIndex;
- if (this.passwordShowButton)
- this.passwordField.tabIndex = tabIndex;
- },
-
- /**
- * Reveals the plain text password of this entry.
- */
- showPassword: function(password) {
- this.passwordField.value = password;
- this.passwordField.type = 'text';
-
- var button = this.passwordShowButton;
- if (button)
- button.textContent = loadTimeData.getString('passwordHideButton');
- },
-
- /**
- * Hides the plain text password of this entry.
- */
- hidePassword: function() {
- this.passwordField.type = 'password';
-
- var button = this.passwordShowButton;
- if (button)
- button.textContent = loadTimeData.getString('passwordShowButton');
- },
-
- /**
- * Get the original index of this item in the data model.
- * @return {number} The index.
- * @private
- */
- getOriginalIndex_: function() {
- var index = this.dataItem[ORIGINAL_INDEX_FIELD];
- return index ? index : this.dataModel.indexOf(this.dataItem);
- },
-
- /**
- * On-click event handler. Swaps the type of the input field from password
- * to text and back.
- * @private
- */
- onClick_: function(event) {
- if (this.passwordField.type == 'password') {
- // After the user is authenticated, showPassword() will be called.
- PasswordManager.requestShowPassword(this.getOriginalIndex_());
- } else {
- this.hidePassword();
- }
- },
-
- /**
- * Get the URL for the entry.
- * @type {string}
- */
- get url() {
- return this.dataItem[URL_FIELD];
- },
-
- /**
- * Get the shown origin for the entry.
- * @type {string}
- */
- get shownOrigin() {
- return this.dataItem[SHOWN_ORIGIN_FIELD];
- },
-
- /**
- * Get whether the origin is Android URI.
- * @type {boolean}
- */
- get isAndroidUri() {
- return this.dataItem[IS_ANDROID_URI_FIELD];
- },
-
- /**
- * Get whether the origin is clickable.
- * @type {boolean}
- */
- get isClickable() {
- return this.dataItem[IS_CLICKABLE_FIELD];
- },
-
- /**
- * Get whether the origin uses secure scheme.
- * @type {boolean}
- */
- get isSecure() {
- return this.dataItem[IS_SECURE_FIELD];
- },
-
- /**
- * Get the username for the entry.
- * @type {string}
- */
- get username() {
- return this.dataItem[USERNAME_FIELD];
- },
-
- /**
- * Get the password for the entry.
- * @type {string}
- */
- get password() {
- return this.dataItem[PASSWORD_FIELD];
- },
-
- /**
- * Get the federation for the entry.
- * @type {string}
- */
- get federation() {
- return this.dataItem[FEDERATION_FIELD];
- },
- };
-
- /**
- * Creates a new PasswordExceptions list item.
- * @param {Object} entry A dictionary of data on new list item.
- * @constructor
- * @extends {options.DeletableItem}
- */
- function PasswordExceptionsListItem(entry) {
- var el = cr.doc.createElement('div');
- el.dataItem = entry;
- el.__proto__ = PasswordExceptionsListItem.prototype;
- el.decorate();
-
- return el;
- }
-
- PasswordExceptionsListItem.prototype = {
- __proto__: DeletableItem.prototype,
-
- /**
- * Call when an element is decorated as a list item.
- */
- decorate: function() {
- DeletableItem.prototype.decorate.call(this);
-
- // The URL of the site.
- this.contentElement.appendChild(createUrlDiv(this));
- },
-
- /** @override */
- selectionChanged: function() {
- if (this.selected) {
- this.setFocusable_(true);
- this.urlLink.focus();
- } else {
- this.setFocusable_(false);
- }
- },
-
- /**
- * Set the focusability of this row.
- * @param {boolean} focusable
- * @private
- */
- setFocusable_: function(focusable) {
- var tabIndex = focusable ? 0 : -1;
- this.urlLink.tabIndex = tabIndex;
- this.closeButtonElement.tabIndex = tabIndex;
- },
-
- /**
- * Get the url for the entry.
- * @type {string}
- */
- get url() {
- return this.dataItem[URL_FIELD];
- },
-
- /**
- * Get the shown origin for the entry.
- * @type {string}
- */
- get shownOrigin() {
- return this.dataItem[SHOWN_ORIGIN_FIELD];
- },
-
- /**
- * Get whether the origin is Android URI.
- * @type {boolean}
- */
- get isAndroidUri() {
- return this.dataItem[IS_ANDROID_URI_FIELD];
- },
-
- /**
- * Get whether the origin is clickable.
- * @type {boolean}
- */
- get isClickable() {
- return this.dataItem[IS_CLICKABLE_FIELD];
- },
-
- /**
- * Get whether the origin uses secure scheme.
- * @type {boolean}
- */
- get isSecure() {
- return this.dataItem[IS_SECURE_FIELD];
- },
- };
-
- /**
- * Create a new passwords list.
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var PasswordsList = cr.ui.define('list');
-
- PasswordsList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- /**
- * Whether passwords can be revealed or not.
- * @type {boolean}
- * @private
- */
- showPasswords_: true,
-
- /** @override */
- decorate: function() {
- DeletableItemList.prototype.decorate.call(this);
- this.addEventListener('focus', this.onFocus_.bind(this));
- },
-
- /**
- * Listener for changes on the preference.
- * @param {Event} event The preference update event.
- * @private
- */
- onPreferenceChanged_: function(event) {
- this.showPasswords_ = event.value.value;
- this.redraw();
- },
-
- /**
- * @override
- * @param {Array} entry
- */
- createItem: function(entry) {
- var showPasswords = this.showPasswords_;
-
- if (loadTimeData.getBoolean('disableShowPasswords'))
- showPasswords = false;
-
- return new PasswordListItem(this.dataModel, entry, showPasswords);
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- var item = this.dataModel.item(index);
- if (item && item[ORIGINAL_INDEX_FIELD] != undefined) {
- // The fifth element, if present, is the original index to delete.
- index = item[ORIGINAL_INDEX_FIELD];
- }
- PasswordManager.removeSavedPassword(index);
- },
-
- /**
- * The length of the list.
- */
- get length() {
- return this.dataModel.length;
- },
-
- /**
- * Will make to first row focusable if none are selected. This makes it
- * possible to tab into the rows without pressing up/down first.
- * @param {Event} e The focus event.
- * @private
- */
- onFocus_: function(e) {
- if (!this.selectedItem && this.items)
- this.items[0].setFocusable_(true);
- },
- };
-
- /**
- * Create a new passwords list.
- * @constructor
- * @extends {options.DeletableItemList}
- */
- var PasswordExceptionsList = cr.ui.define('list');
-
- PasswordExceptionsList.prototype = {
- __proto__: DeletableItemList.prototype,
-
- /**
- * @override
- * @param {Array} entry
- */
- createItem: function(entry) {
- return new PasswordExceptionsListItem(entry);
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- PasswordManager.removePasswordException(index);
- },
-
- /**
- * The length of the list.
- */
- get length() {
- return this.dataModel.length;
- },
- };
-
- return {
- PasswordListItem: PasswordListItem,
- PasswordExceptionsListItem: PasswordExceptionsListItem,
- PasswordsList: PasswordsList,
- PasswordExceptionsList: PasswordExceptionsList,
- URL_FIELD: URL_FIELD,
- SHOWN_ORIGIN_FIELD: SHOWN_ORIGIN_FIELD,
- IS_ANDROID_URI_FIELD: IS_ANDROID_URI_FIELD,
- IS_CLICKABLE_FIELD: IS_CLICKABLE_FIELD,
- IS_SECURE_FIELD: IS_SECURE_FIELD,
- USERNAME_FIELD: USERNAME_FIELD,
- PASSWORD_FIELD: PASSWORD_FIELD,
- FEDERATION_FIELD: FEDERATION_FIELD,
- ORIGINAL_INDEX_FIELD: ORIGINAL_INDEX_FIELD
- };
-});
diff --git a/chromium/chrome/browser/resources/options/pref_ui.js b/chromium/chrome/browser/resources/options/pref_ui.js
deleted file mode 100644
index c0776fee447..00000000000
--- a/chromium/chrome/browser/resources/options/pref_ui.js
+++ /dev/null
@@ -1,639 +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.
-
-cr.define('options', function() {
- var Preferences = options.Preferences;
-
- /**
- * Allows an element to be disabled for several reasons.
- * The element is disabled if at least one reason is true, and the reasons
- * can be set separately.
- * @private
- * @param {!HTMLElement} el The element to update.
- * @param {string} reason The reason for disabling the element.
- * @param {boolean} disabled Whether the element should be disabled or enabled
- * for the given |reason|.
- */
- function updateDisabledState(el, reason, disabled) {
- if (!el.disabledReasons)
- el.disabledReasons = {};
-
- if (el.disabled && (Object.keys(el.disabledReasons).length == 0)) {
- // The element has been previously disabled without a reason, so we add
- // one to keep it disabled.
- el.disabledReasons.other = true;
- }
-
- if (!el.disabled) {
- // If the element is not disabled, there should be no reason, except for
- // 'other'.
- delete el.disabledReasons.other;
- if (Object.keys(el.disabledReasons).length > 0)
- console.error('Element is not disabled but should be');
- }
-
- if (disabled)
- el.disabledReasons[reason] = true;
- else
- delete el.disabledReasons[reason];
-
- el.disabled = Object.keys(el.disabledReasons).length > 0;
- }
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefInputElement class:
-
- /**
- * Define a constructor that uses an input element as its underlying element.
- * @constructor
- * @extends {HTMLInputElement}
- */
- var PrefInputElement = cr.ui.define('input');
-
- PrefInputElement.prototype = {
- // Set up the prototype chain
- __proto__: HTMLInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- var self = this;
-
- // Listen for user events.
- this.addEventListener('change', this.handleChange.bind(this));
-
- // Listen for pref changes.
- Preferences.getInstance().addEventListener(this.pref, function(event) {
- if (event.value.uncommitted && !self.dialogPref)
- return;
- self.updateStateFromPref(event);
- updateDisabledState(self, 'notUserModifiable', event.value.disabled);
- self.controlledBy = event.value.controlledBy;
- });
- },
-
- /**
- * Handle changes to the input element's state made by the user. If a custom
- * change handler does not suppress it, a default handler is invoked that
- * updates the associated pref.
- * @param {Event} event Change event.
- * @protected
- */
- handleChange: function(event) {
- if (!this.customChangeHandler(event))
- this.updatePrefFromState();
- },
-
- /**
- * Handles changes to the pref. If a custom change handler does not suppress
- * it, a default handler is invoked that updates the input element's state.
- * @param {Event} event Pref change event.
- * @protected
- */
- updateStateFromPref: function(event) {
- if (!this.customPrefChangeHandler(event))
- this.value = event.value.value;
- },
-
- /**
- * An abstract method for all subclasses to override to update their
- * preference from existing state.
- * @protected
- */
- updatePrefFromState: assertNotReached,
-
- /**
- * See |updateDisabledState| above.
- */
- setDisabled: function(reason, disabled) {
- updateDisabledState(this, reason, disabled);
- },
-
- /**
- * Custom change handler that is invoked first when the user makes changes
- * to the input element's state. If it returns false, a default handler is
- * invoked next that updates the associated pref. If it returns true, the
- * default handler is suppressed (i.e., this works like stopPropagation or
- * cancelBubble).
- * @param {Event} event Input element change event.
- */
- customChangeHandler: function(event) {
- return false;
- },
-
- /**
- * Custom change handler that is invoked first when the preference
- * associated with the input element changes. If it returns false, a default
- * handler is invoked next that updates the input element. If it returns
- * true, the default handler is suppressed.
- * @param {Event} event Input element change event.
- */
- customPrefChangeHandler: function(event) {
- return false;
- },
- };
-
- /**
- * The name of the associated preference.
- */
- cr.defineProperty(PrefInputElement, 'pref', cr.PropertyKind.ATTR);
-
- /**
- * The data type of the associated preference, only relevant for derived
- * classes that support different data types.
- */
- cr.defineProperty(PrefInputElement, 'dataType', cr.PropertyKind.ATTR);
-
- /**
- * Whether this input element is part of a dialog. If so, changes take effect
- * in the settings UI immediately but are only actually committed when the
- * user confirms the dialog. If the user cancels the dialog instead, the
- * changes are rolled back in the settings UI and never committed.
- */
- cr.defineProperty(PrefInputElement, 'dialogPref', cr.PropertyKind.BOOL_ATTR);
-
- /**
- * Whether the associated preference is controlled by a source other than the
- * user's setting (can be 'policy', 'extension', 'recommended' or unset).
- */
- cr.defineProperty(PrefInputElement, 'controlledBy', cr.PropertyKind.ATTR);
-
- /**
- * The user metric string.
- */
- cr.defineProperty(PrefInputElement, 'metric', cr.PropertyKind.ATTR);
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefCheckbox class:
-
- /**
- * Define a constructor that uses an input element as its underlying element.
- * @constructor
- * @extends {options.PrefInputElement}
- */
- var PrefCheckbox = cr.ui.define('input');
-
- PrefCheckbox.prototype = {
- // Set up the prototype chain
- __proto__: PrefInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- PrefInputElement.prototype.decorate.call(this);
- this.type = 'checkbox';
-
- // Consider a checked dialog checkbox as a 'suggestion' which is committed
- // once the user confirms the dialog.
- if (this.dialogPref && this.checked)
- this.updatePrefFromState();
- },
-
- /**
- * Update the associated pref when when the user makes changes to the
- * checkbox state.
- * @override
- */
- updatePrefFromState: function() {
- var value = this.inverted_pref ? !this.checked : this.checked;
- Preferences.setBooleanPref(this.pref, value,
- !this.dialogPref, this.metric);
- },
-
- /** @override */
- updateStateFromPref: function(event) {
- if (!this.customPrefChangeHandler(event))
- this.defaultPrefChangeHandler(event);
- },
-
- /**
- * @param {Event} event A pref change event.
- */
- defaultPrefChangeHandler: function(event) {
- var value = Boolean(event.value.value);
- this.checked = this.inverted_pref ? !value : value;
- },
- };
-
- /**
- * Whether the mapping between checkbox state and associated pref is inverted.
- */
- cr.defineProperty(PrefCheckbox, 'inverted_pref', cr.PropertyKind.BOOL_ATTR);
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefNumber class:
-
- // Define a constructor that uses an input element as its underlying element.
- var PrefNumber = cr.ui.define('input');
-
- PrefNumber.prototype = {
- // Set up the prototype chain
- __proto__: PrefInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- PrefInputElement.prototype.decorate.call(this);
- this.type = 'number';
- },
-
- /**
- * Update the associated pref when the user inputs a number.
- * @override
- */
- updatePrefFromState: function() {
- if (this.validity.valid) {
- Preferences.setIntegerPref(this.pref, this.value,
- !this.dialogPref, this.metric);
- }
- },
- };
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefRadio class:
-
- //Define a constructor that uses an input element as its underlying element.
- var PrefRadio = cr.ui.define('input');
-
- PrefRadio.prototype = {
- // Set up the prototype chain
- __proto__: PrefInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- PrefInputElement.prototype.decorate.call(this);
- this.type = 'radio';
- },
-
- /**
- * Update the associated pref when when the user selects the radio button.
- * @override
- */
- updatePrefFromState: function() {
- if (this.value == 'true' || this.value == 'false') {
- Preferences.setBooleanPref(this.pref,
- this.value == String(this.checked),
- !this.dialogPref, this.metric);
- } else {
- Preferences.setIntegerPref(this.pref, this.value,
- !this.dialogPref, this.metric);
- }
- },
-
- /** @override */
- updateStateFromPref: function(event) {
- if (!this.customPrefChangeHandler(event))
- this.checked = this.value == String(event.value.value);
- },
- };
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefRange class:
-
- /**
- * Define a constructor that uses an input element as its underlying element.
- * @constructor
- * @extends {options.PrefInputElement}
- */
- var PrefRange = cr.ui.define('input');
-
- PrefRange.prototype = {
- // Set up the prototype chain
- __proto__: PrefInputElement.prototype,
-
- /**
- * The map from slider position to corresponding pref value.
- */
- valueMap: undefined,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- PrefInputElement.prototype.decorate.call(this);
- this.type = 'range';
-
- // Listen for user events.
- // TODO(jhawkins): Add onmousewheel handling once the associated WK bug is
- // fixed.
- // https://bugs.webkit.org/show_bug.cgi?id=52256
- this.addEventListener('keyup', this.handleRelease_.bind(this));
- this.addEventListener('mouseup', this.handleRelease_.bind(this));
- this.addEventListener('touchcancel', this.handleRelease_.bind(this));
- this.addEventListener('touchend', this.handleRelease_.bind(this));
- },
-
- /**
- * Update the associated pref when when the user releases the slider.
- * @override
- */
- updatePrefFromState: function() {
- Preferences.setIntegerPref(
- this.pref,
- this.mapPositionToPref(parseInt(this.value, 10)),
- !this.dialogPref,
- this.metric);
- },
-
- /** @override */
- handleChange: function() {
- // Ignore changes to the slider position made by the user while the slider
- // has not been released.
- },
-
- /**
- * Handle changes to the slider position made by the user when the slider is
- * released. If a custom change handler does not suppress it, a default
- * handler is invoked that updates the associated pref.
- * @param {Event} event Change event.
- * @private
- */
- handleRelease_: function(event) {
- if (!this.customChangeHandler(event))
- this.updatePrefFromState();
- },
-
- /**
- * Handles changes to the pref associated with the slider. If a custom
- * change handler does not suppress it, a default handler is invoked that
- * updates the slider position.
- * @override.
- */
- updateStateFromPref: function(event) {
- if (this.customPrefChangeHandler(event))
- return;
- var value = event.value.value;
- this.value = this.valueMap ? this.valueMap.indexOf(value) : value;
- },
-
- /**
- * Map slider position to the range of values provided by the client,
- * represented by |valueMap|.
- * @param {number} position The slider position to map.
- */
- mapPositionToPref: function(position) {
- return this.valueMap ? this.valueMap[position] : position;
- },
- };
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefSelect class:
-
- // Define a constructor that uses a select element as its underlying element.
- var PrefSelect = cr.ui.define('select');
-
- PrefSelect.prototype = {
- // Set up the prototype chain
- __proto__: HTMLSelectElement.prototype,
-
- /** @override */
- decorate: PrefInputElement.prototype.decorate,
-
- /** @override */
- handleChange: PrefInputElement.prototype.handleChange,
-
- /**
- * Update the associated pref when when the user selects an item.
- * @override
- */
- updatePrefFromState: function() {
- var value = this.options[this.selectedIndex].value;
- switch (this.dataType) {
- case 'number':
- Preferences.setIntegerPref(this.pref, value,
- !this.dialogPref, this.metric);
- break;
- case 'double':
- Preferences.setDoublePref(this.pref, value,
- !this.dialogPref, this.metric);
- break;
- case 'boolean':
- Preferences.setBooleanPref(this.pref, value == 'true',
- !this.dialogPref, this.metric);
- break;
- case 'string':
- Preferences.setStringPref(this.pref, value,
- !this.dialogPref, this.metric);
- break;
- default:
- console.error('Unknown data type for <select> UI element: ' +
- this.dataType);
- }
- },
-
- /** @override */
- updateStateFromPref: function(event) {
- if (this.customPrefChangeHandler(event))
- return;
-
- // Make sure the value is a string, because the value is stored as a
- // string in the HTMLOptionElement.
- var value = String(event.value.value);
-
- var found = false;
- for (var i = 0; i < this.options.length; i++) {
- if (this.options[i].value == value) {
- this.selectedIndex = i;
- found = true;
- }
- }
-
- // Item not found, select first item.
- if (!found)
- this.selectedIndex = 0;
-
- // The "onchange" event automatically fires when the user makes a manual
- // change. It should never be fired for a programmatic change. However,
- // these two lines were here already and it is hard to tell who may be
- // relying on them.
- if (this.onchange)
- this.onchange(event);
- },
-
- /** @override */
- setDisabled: PrefInputElement.prototype.setDisabled,
-
- /** @override */
- customChangeHandler: PrefInputElement.prototype.customChangeHandler,
-
- /** @override */
- customPrefChangeHandler: PrefInputElement.prototype.customPrefChangeHandler,
- };
-
- /**
- * The name of the associated preference.
- */
- cr.defineProperty(PrefSelect, 'pref', cr.PropertyKind.ATTR);
-
- /**
- * The data type of the associated preference, only relevant for derived
- * classes that support different data types.
- */
- cr.defineProperty(PrefSelect, 'dataType', cr.PropertyKind.ATTR);
-
- /**
- * Whether this input element is part of a dialog. If so, changes take effect
- * in the settings UI immediately but are only actually committed when the
- * user confirms the dialog. If the user cancels the dialog instead, the
- * changes are rolled back in the settings UI and never committed.
- */
- cr.defineProperty(PrefSelect, 'dialogPref', cr.PropertyKind.BOOL_ATTR);
-
- /**
- * Whether the associated preference is controlled by a source other than the
- * user's setting (can be 'policy', 'extension', 'recommended' or unset).
- */
- cr.defineProperty(PrefSelect, 'controlledBy', cr.PropertyKind.ATTR);
-
- /**
- * The user metric string.
- */
- cr.defineProperty(PrefSelect, 'metric', cr.PropertyKind.ATTR);
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefTextField class:
-
- // Define a constructor that uses an input element as its underlying element.
- var PrefTextField = cr.ui.define('input');
-
- PrefTextField.prototype = {
- // Set up the prototype chain
- __proto__: PrefInputElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- PrefInputElement.prototype.decorate.call(this);
- var self = this;
-
- // Listen for user events.
- window.addEventListener('unload', function() {
- if (document.activeElement == self)
- self.blur();
- });
- },
-
- /**
- * Update the associated pref when when the user inputs text.
- * @override
- */
- updatePrefFromState: function(event) {
- switch (this.dataType) {
- case 'number':
- Preferences.setIntegerPref(this.pref, this.value,
- !this.dialogPref, this.metric);
- break;
- case 'double':
- Preferences.setDoublePref(this.pref, this.value,
- !this.dialogPref, this.metric);
- break;
- case 'url':
- Preferences.setURLPref(this.pref, this.value,
- !this.dialogPref, this.metric);
- break;
- default:
- Preferences.setStringPref(this.pref, this.value,
- !this.dialogPref, this.metric);
- break;
- }
- },
- };
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefPortNumber class:
-
- // Define a constructor that uses an input element as its underlying element.
- var PrefPortNumber = cr.ui.define('input');
-
- PrefPortNumber.prototype = {
- // Set up the prototype chain
- __proto__: PrefTextField.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- var self = this;
- self.type = 'text';
- self.dataType = 'number';
- PrefTextField.prototype.decorate.call(this);
- self.oninput = function() {
- // Note that using <input type="number"> is insufficient to restrict
- // the input as it allows negative numbers and does not limit the
- // number of charactes typed even if a range is set. Furthermore,
- // it sometimes produces strange repaint artifacts.
- var filtered = self.value.replace(/[^0-9]/g, '');
- if (filtered != self.value)
- self.value = filtered;
- };
- }
- };
-
- /////////////////////////////////////////////////////////////////////////////
- // PrefButton class:
-
- // Define a constructor that uses a button element as its underlying element.
- var PrefButton = cr.ui.define('button');
-
- PrefButton.prototype = {
- // Set up the prototype chain
- __proto__: HTMLButtonElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- var self = this;
-
- // Listen for pref changes.
- // This element behaves like a normal button and does not affect the
- // underlying preference; it just becomes disabled when the preference is
- // managed, and its value is false. This is useful for buttons that should
- // be disabled when the underlying Boolean preference is set to false by a
- // policy or extension.
- Preferences.getInstance().addEventListener(this.pref, function(event) {
- updateDisabledState(self, 'notUserModifiable',
- event.value.disabled && !event.value.value);
- self.controlledBy = event.value.controlledBy;
- });
- },
-
- /**
- * See |updateDisabledState| above.
- */
- setDisabled: function(reason, disabled) {
- updateDisabledState(this, reason, disabled);
- },
- };
-
- /**
- * The name of the associated preference.
- */
- cr.defineProperty(PrefButton, 'pref', cr.PropertyKind.ATTR);
-
- /**
- * Whether the associated preference is controlled by a source other than the
- * user's setting (can be 'policy', 'extension', 'recommended' or unset).
- */
- cr.defineProperty(PrefButton, 'controlledBy', cr.PropertyKind.ATTR);
-
- // Export
- return {
- PrefCheckbox: PrefCheckbox,
- PrefInputElement: PrefInputElement,
- PrefNumber: PrefNumber,
- PrefRadio: PrefRadio,
- PrefRange: PrefRange,
- PrefSelect: PrefSelect,
- PrefTextField: PrefTextField,
- PrefPortNumber: PrefPortNumber,
- PrefButton: PrefButton
- };
-});
diff --git a/chromium/chrome/browser/resources/options/preferences.js b/chromium/chrome/browser/resources/options/preferences.js
deleted file mode 100644
index c7ea93d37ea..00000000000
--- a/chromium/chrome/browser/resources/options/preferences.js
+++ /dev/null
@@ -1,338 +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.
-
-cr.define('options', function() {
-
- /////////////////////////////////////////////////////////////////////////////
- // Preferences class:
-
- /**
- * Preferences class manages access to Chrome profile preferences.
- * @constructor
- * @extends {cr.EventTarget}
- */
- function Preferences() {
- // Map of registered preferences.
- this.registeredPreferences_ = {};
- }
-
- cr.addSingletonGetter(Preferences);
-
- /**
- * Sets a Boolean preference and signals its new value.
- * @param {string} name Preference name.
- * @param {boolean} value New preference value.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string=} opt_metric User metrics identifier.
- */
- Preferences.setBooleanPref = function(name, value, commit, opt_metric) {
- if (!commit) {
- Preferences.getInstance().setPrefNoCommit_(name, 'bool', Boolean(value));
- return;
- }
-
- var argumentList = [name, Boolean(value)];
- if (opt_metric != undefined) argumentList.push(opt_metric);
- chrome.send('setBooleanPref', argumentList);
- };
-
- /**
- * Sets an integer preference and signals its new value.
- * @param {string} name Preference name.
- * @param {number} value New preference value.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string} metric User metrics identifier.
- */
- Preferences.setIntegerPref = function(name, value, commit, metric) {
- if (!commit) {
- Preferences.getInstance().setPrefNoCommit_(name, 'int', Number(value));
- return;
- }
-
- var argumentList = [name, Number(value)];
- if (metric != undefined) argumentList.push(metric);
- chrome.send('setIntegerPref', argumentList);
- };
-
- /**
- * Sets a double-valued preference and signals its new value.
- * @param {string} name Preference name.
- * @param {number} value New preference value.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string} metric User metrics identifier.
- */
- Preferences.setDoublePref = function(name, value, commit, metric) {
- if (!commit) {
- Preferences.getInstance().setPrefNoCommit_(name, 'double', Number(value));
- return;
- }
-
- var argumentList = [name, Number(value)];
- if (metric != undefined) argumentList.push(metric);
- chrome.send('setDoublePref', argumentList);
- };
-
- /**
- * Sets a string preference and signals its new value.
- * @param {string} name Preference name.
- * @param {string} value New preference value.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string} metric User metrics identifier.
- */
- Preferences.setStringPref = function(name, value, commit, metric) {
- if (!commit) {
- Preferences.getInstance().setPrefNoCommit_(name, 'string', String(value));
- return;
- }
-
- var argumentList = [name, String(value)];
- if (metric != undefined) argumentList.push(metric);
- chrome.send('setStringPref', argumentList);
- };
-
- /**
- * Sets a string preference that represents a URL and signals its new value.
- * The value will be fixed to be a valid URL when it gets committed to Chrome.
- * @param {string} name Preference name.
- * @param {string} value New preference value.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string} metric User metrics identifier.
- */
- Preferences.setURLPref = function(name, value, commit, metric) {
- if (!commit) {
- Preferences.getInstance().setPrefNoCommit_(name, 'url', String(value));
- return;
- }
-
- var argumentList = [name, String(value)];
- if (metric != undefined) argumentList.push(metric);
- chrome.send('setURLPref', argumentList);
- };
-
- /**
- * Sets a JSON list preference and signals its new value.
- * @param {string} name Preference name.
- * @param {Array} value New preference value.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string} metric User metrics identifier.
- */
- Preferences.setListPref = function(name, value, commit, metric) {
- if (!commit) {
- Preferences.getInstance().setPrefNoCommit_(name, 'list', value);
- return;
- }
-
- var argumentList = [name, JSON.stringify(value)];
- if (metric != undefined) argumentList.push(metric);
- chrome.send('setListPref', argumentList);
- };
-
- /**
- * Clears the user setting for a preference and signals its new effective
- * value.
- * @param {string} name Preference name.
- * @param {boolean} commit Whether to commit the change to Chrome.
- * @param {string=} opt_metric User metrics identifier.
- */
- Preferences.clearPref = function(name, commit, opt_metric) {
- if (!commit) {
- Preferences.getInstance().clearPrefNoCommit_(name);
- return;
- }
-
- var argumentList = [name];
- if (opt_metric != undefined) argumentList.push(opt_metric);
- chrome.send('clearPref', argumentList);
- };
-
- Preferences.prototype = {
- __proto__: cr.EventTarget.prototype,
-
- /**
- * Adds an event listener to the target.
- * @param {string} type The name of the event.
- * @param {EventListenerType} handler The handler for the event. This is
- * called when the event is dispatched.
- */
- addEventListener: function(type, handler) {
- cr.EventTarget.prototype.addEventListener.call(this, type, handler);
- if (!(type in this.registeredPreferences_))
- this.registeredPreferences_[type] = {};
- },
-
- /**
- * Initializes preference reading and change notifications.
- */
- initialize: function() {
- var params1 = ['Preferences.prefsFetchedCallback'];
- var params2 = ['Preferences.prefsChangedCallback'];
- for (var prefName in this.registeredPreferences_) {
- params1.push(prefName);
- params2.push(prefName);
- }
- chrome.send('fetchPrefs', params1);
- chrome.send('observePrefs', params2);
- },
-
- /**
- * Helper function for flattening of dictionary passed via fetchPrefs
- * callback.
- * @param {string} prefix Preference name prefix.
- * @param {Object} dict Map with preference values.
- * @private
- */
- flattenMapAndDispatchEvent_: function(prefix, dict) {
- for (var prefName in dict) {
- var value = dict[prefName];
- if (typeof value == 'object' &&
- !this.registeredPreferences_[prefix + prefName]) {
- this.flattenMapAndDispatchEvent_(prefix + prefName + '.', value);
- } else if (value) {
- var event = new Event(prefix + prefName);
- this.registeredPreferences_[prefix + prefName].orig = value;
- event.value = value;
- this.dispatchEvent(event);
- }
- }
- },
-
- /**
- * Sets a preference and signals its new value. The change is propagated
- * throughout the UI code but is not committed to Chrome yet. The new value
- * and its data type are stored so that commitPref() can later be used to
- * invoke the appropriate set*Pref() method and actually commit the change.
- * @param {string} name Preference name.
- * @param {string} type Preference data type.
- * @param {*} value New preference value.
- * @private
- */
- setPrefNoCommit_: function(name, type, value) {
- var pref = this.registeredPreferences_[name];
- pref.action = 'set';
- pref.type = type;
- pref.value = value;
-
- var event = new Event(name);
- // Decorate pref value as CoreOptionsHandler::CreateValueForPref() does.
- event.value = {value: value, uncommitted: true};
- if (pref.orig) {
- event.value.recommendedValue = pref.orig.recommendedValue;
- event.value.disabled = pref.orig.disabled;
- }
- this.dispatchEvent(event);
- },
-
- /**
- * Clears a preference and signals its new value. The change is propagated
- * throughout the UI code but is not committed to Chrome yet.
- * @param {string} name Preference name.
- * @private
- */
- clearPrefNoCommit_: function(name) {
- var pref = this.registeredPreferences_[name];
- pref.action = 'clear';
- delete pref.type;
- delete pref.value;
-
- var event = new Event(name);
- // Decorate pref value as CoreOptionsHandler::CreateValueForPref() does.
- event.value = {controlledBy: 'recommended', uncommitted: true};
- if (pref.orig) {
- event.value.value = pref.orig.recommendedValue;
- event.value.recommendedValue = pref.orig.recommendedValue;
- event.value.disabled = pref.orig.disabled;
- }
- this.dispatchEvent(event);
- },
-
- /**
- * Commits a preference change to Chrome and signals the new preference
- * value. Does nothing if there is no uncommitted change.
- * @param {string} name Preference name.
- * @param {string} metric User metrics identifier.
- */
- commitPref: function(name, metric) {
- var pref = this.registeredPreferences_[name];
- switch (pref.action) {
- case 'set':
- switch (pref.type) {
- case 'bool':
- Preferences.setBooleanPref(name, pref.value, true, metric);
- break;
- case 'int':
- Preferences.setIntegerPref(name, pref.value, true, metric);
- break;
- case 'double':
- Preferences.setDoublePref(name, pref.value, true, metric);
- break;
- case 'string':
- Preferences.setStringPref(name, pref.value, true, metric);
- break;
- case 'url':
- Preferences.setURLPref(name, pref.value, true, metric);
- break;
- case 'list':
- Preferences.setListPref(name, pref.value, true, metric);
- break;
- }
- break;
- case 'clear':
- Preferences.clearPref(name, true, metric);
- break;
- }
- delete pref.action;
- delete pref.type;
- delete pref.value;
- },
-
- /**
- * Rolls back a preference change and signals the original preference value.
- * Does nothing if there is no uncommitted change.
- * @param {string} name Preference name.
- */
- rollbackPref: function(name) {
- var pref = this.registeredPreferences_[name];
- if (!pref.action)
- return;
-
- delete pref.action;
- delete pref.type;
- delete pref.value;
-
- var event = new Event(name);
- event.value = pref.orig || {};
- event.value.uncommitted = true;
- this.dispatchEvent(event);
- }
- };
-
- /**
- * Callback for fetchPrefs method.
- * @param {Object} dict Map of fetched property values.
- */
- Preferences.prefsFetchedCallback = function(dict) {
- Preferences.getInstance().flattenMapAndDispatchEvent_('', dict);
- };
-
- /**
- * Callback for observePrefs method.
- * @param {Array} notification An array defining changed preference values.
- * notification[0] contains name of the change preference while its new
- * value is stored in notification[1].
- */
- Preferences.prefsChangedCallback = function(notification) {
- var event = new Event(notification[0]);
- event.value = notification[1];
- var prefs = Preferences.getInstance();
- prefs.registeredPreferences_[notification[0]] = {orig: notification[1]};
- if (event.value)
- prefs.dispatchEvent(event);
- };
-
- // Export
- return {
- Preferences: Preferences
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/profiles_icon_grid.js b/chromium/chrome/browser/resources/options/profiles_icon_grid.js
deleted file mode 100644
index 9d0401d0df3..00000000000
--- a/chromium/chrome/browser/resources/options/profiles_icon_grid.js
+++ /dev/null
@@ -1,67 +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.
-
-cr.define('options', function() {
- /** @const */ var ListItem = cr.ui.ListItem;
- /** @const */ var Grid = cr.ui.Grid;
- /** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel;
-
- /**
- * Creates a new profile icon grid item.
- * @param {Object} iconURL The profile icon URL.
- * @constructor
- * @extends {cr.ui.GridItem}
- */
- function ProfilesIconGridItem(iconURL) {
- var el = cr.doc.createElement('span');
- el.iconURL_ = iconURL;
- ProfilesIconGridItem.decorate(el);
- return el;
- }
-
- /**
- * Decorates an element as a profile grid item.
- * @param {!HTMLElement} el The element to decorate.
- */
- ProfilesIconGridItem.decorate = function(el) {
- el.__proto__ = ProfilesIconGridItem.prototype;
- el.decorate();
- };
-
- ProfilesIconGridItem.prototype = {
- __proto__: ListItem.prototype,
-
- /** @override */
- decorate: function() {
- ListItem.prototype.decorate.call(this);
- var imageEl = cr.doc.createElement('img');
- imageEl.className = 'profile-icon';
- imageEl.style.content = cr.icon.getImage(this.iconURL_);
- this.appendChild(imageEl);
-
- this.className = 'profile-icon-grid-item';
- },
- };
-
- var ProfilesIconGrid = cr.ui.define('grid');
-
- ProfilesIconGrid.prototype = {
- __proto__: Grid.prototype,
-
- /** @override */
- decorate: function() {
- Grid.prototype.decorate.call(this);
- this.selectionModel = new ListSingleSelectionModel();
- },
-
- /** @override */
- createItem: function(iconURL) {
- return new ProfilesIconGridItem(iconURL);
- },
- };
-
- return {
- ProfilesIconGrid: ProfilesIconGrid
- };
-});
diff --git a/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.css b/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.css
deleted file mode 100644
index c20f8220edf..00000000000
--- a/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.css
+++ /dev/null
@@ -1,65 +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. */
-
-#reset-profile-settings-overlay {
- width: 500px;
-}
-
-#reset-profile-settings-content-area {
- -webkit-box-flex: 0;
-}
-
-#reset-profile-settings-throbber {
- margin: 4px 10px;
- vertical-align: middle;
- visibility: hidden;
-}
-
-#feedback-bar {
- -webkit-box-flex: 1;
- -webkit-box-orient: vertical;
-}
-
-#feedback-template {
- -webkit-box-flex: 1;
- overflow-y: auto;
-}
-
-#feedback-template table {
- table-layout: fixed;
- width: 100%;
-}
-
-#feedback-template table td {
- word-wrap: break-word;
-}
-
-#feedback-template .key {
- padding-right: 5px;
- text-align: right;
- vertical-align: top;
-}
-
-#feedback-template .value {
- color: #333;
- text-align: left;
- white-space: pre-line;
-}
-
-#feedback-bar span {
- vertical-align: middle;
-}
-
-#expand-feedback {
- -webkit-mask-box-image: url(../../../../ui/webui/resources/images/help.svg);
- background-color: #828282;
- display: inline-block;
- height: 14px;
- opacity: 0.33;
- width: 14px;
-}
-
-#expand-feedback:hover {
- opacity: 1;
-}
diff --git a/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.html b/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.html
deleted file mode 100644
index 07ba37200bb..00000000000
--- a/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.html
+++ /dev/null
@@ -1,45 +0,0 @@
-<div id="reset-profile-settings-overlay" class="page not-resizable" hidden>
- <div class="close-button"></div>
- <!-- Text populated dynamically from didShowPage. -->
- <h1 id="reset-profile-settings-title"></h1>
- <div id="reset-profile-settings-content-area" class="content-area">
- <!-- Text populated dynamically from didShowPage. -->
- <span id="reset-profile-settings-explanation"></span>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a target="_blank"
- href="$i18nRaw{resetProfileSettingsLearnMoreUrl}">$i18n{learnMore}</a>
- </div>
- <div class="action-area-right">
- <div id="reset-profile-settings-throbber" class="throbber"></div>
- <div class="button-strip">
- <button id="reset-profile-settings-dismiss">$i18n{cancel}</button>
- <button id="reset-profile-settings-commit">
- $i18n{resetProfileSettingsCommit}
- </button>
- </div>
- </div>
- </div>
- <div id="feedback-bar"
- class="gray-bottom-bar checkbox controlled-setting-with-label">
- <label>
- <input id="send-settings" type="checkbox" checked>
- <span>
- <span>$i18n{resetProfileSettingsFeedback}</span>
- <span id="expand-feedback"></span>
- </span>
- </label>
- <div id="feedback-template" hidden>
- <div>
- <table>
- <tr jsselect="feedbackInfo">
- <td class="key"><span jscontent="key">KEY</span></td>
- <td class="value"><span jscontent="value">VALUE</span></td>
- </tr>
- </table>
- </div>
- </div>
- </div>
-</div>
-<script src="chrome://resources/js/jstemplate_compiled.js"></script>
diff --git a/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.js b/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.js
deleted file mode 100644
index 55091cf4efb..00000000000
--- a/chromium/chrome/browser/resources/options/reset_profile_settings_overlay.js
+++ /dev/null
@@ -1,156 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
-
- var AutomaticSettingsResetBanner = options.AutomaticSettingsResetBanner;
-
- /**
- * ResetProfileSettingsOverlay class
- *
- * Encapsulated handling of the 'Reset Profile Settings' and the 'Triggered
- * Reset Profile Settings' overlay pages. See triggered_profile_resetter.h for
- * when the triggered variant will be used.
- *
- * @constructor
- * @param {boolean} isTriggered Whether the overlay is the triggered variant.
- * @extends {cr.ui.pageManager.Page}
- */
- function ResetProfileSettingsOverlay(isTriggered) {
- this.isTriggered_ = isTriggered;
- Page.call(
- this,
- isTriggered ? 'triggeredResetProfileSettings' : 'resetProfileSettings',
- loadTimeData.getString(isTriggered ?
- 'triggeredResetProfileSettingsOverlay' :
- 'resetProfileSettingsOverlayTabTitle'),
- 'reset-profile-settings-overlay');
- }
-
- ResetProfileSettingsOverlay.prototype = {
- // Inherit ResetProfileSettingsOverlay from Page.
- __proto__: Page.prototype,
-
- /**
- * Indicates whether the overlay is a triggered reset overlay.
- * @type {boolean}
- * @private
- */
- isTriggered_: false,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- if (!ResetProfileSettingsOverlay.listenersAdded_) {
- $('reset-profile-settings-dismiss').onclick = function(e) {
- ResetProfileSettingsOverlay.dismiss();
- };
- $('reset-profile-settings-commit').onclick = function(e) {
- ResetProfileSettingsOverlay.setResettingState(true);
- chrome.send('performResetProfileSettings',
- [$('send-settings').checked,
- ResetProfileSettingsOverlay.resetRequestOrigin_]);
- };
- $('expand-feedback').onclick = function(e) {
- var feedbackTemplate = $('feedback-template');
- feedbackTemplate.hidden = !feedbackTemplate.hidden;
- e.preventDefault();
- };
-
- ResetProfileSettingsOverlay.listenersAdded_ = true;
- }
- },
-
- /**
- * @override
- * @suppress {checkTypes}
- * TODO(vitalyp): remove the suppression. See the explanation in
- * chrome/browser/resources/options/automatic_settings_reset_banner.js.
- */
- didShowPage: function() {
- $('reset-profile-settings-title').textContent =
- loadTimeData.getString(this.isTriggered_ ?
- 'triggeredResetProfileSettingsOverlay' :
- 'resetProfileSettingsOverlay');
- $('reset-profile-settings-explanation').textContent =
- loadTimeData.getString(this.isTriggered_ ?
- 'triggeredResetProfileSettingsExplanation' :
- 'resetProfileSettingsExplanation');
-
- // Set ResetProfileSettingsOverlay.resetRequestOrigin_ to indicate where
- // the reset request came from.
- if (this.isTriggered_) {
- ResetProfileSettingsOverlay.resetRequestOrigin_ = 'triggeredreset';
- } else {
- // For the non-triggered reset overlay, a '#userclick' hash indicates
- // that the reset request came from the user clicking on the reset
- // settings button and is set by the browser_options page. A '#cct' hash
- // indicates that the reset request came from the CCT by launching
- // Chrome with the startup URL
- // chrome://settings/resetProfileSettings#cct.
- var hash = this.hash.slice(1).toLowerCase();
- ResetProfileSettingsOverlay.resetRequestOrigin_ =
- (hash === 'cct' || hash === 'userclick') ? hash : '';
- this.setHash('');
- }
-
- chrome.send('onShowResetProfileDialog');
- },
-
- /** @override */
- didClosePage: function() {
- chrome.send('onHideResetProfileDialog');
- },
- };
-
- /** @private {boolean} */
- ResetProfileSettingsOverlay.listenersAdded_ = false;
-
- /** @private {string} */
- ResetProfileSettingsOverlay.resetRequestOrigin_ = '';
-
- /**
- * Enables/disables UI elements after/while Chrome is performing a reset.
- * @param {boolean} state If true, UI elements are disabled.
- */
- ResetProfileSettingsOverlay.setResettingState = function(state) {
- $('reset-profile-settings-throbber').style.visibility =
- state ? 'visible' : 'hidden';
- $('reset-profile-settings-dismiss').disabled = state;
- $('reset-profile-settings-commit').disabled = state;
- };
-
- /**
- * Chrome callback to notify ResetProfileSettingsOverlay that the reset
- * operation has terminated.
- * @suppress {checkTypes}
- * TODO(vitalyp): remove the suppression. See the explanation in
- * chrome/browser/resources/options/automatic_settings_reset_banner.js.
- */
- ResetProfileSettingsOverlay.doneResetting = function() {
- AutomaticSettingsResetBanner.dismiss();
- ResetProfileSettingsOverlay.dismiss();
- };
-
- /**
- * Dismisses the overlay.
- */
- ResetProfileSettingsOverlay.dismiss = function() {
- PageManager.closeOverlay();
- ResetProfileSettingsOverlay.setResettingState(false);
- };
-
- ResetProfileSettingsOverlay.setFeedbackInfo = function(feedbackListData) {
- var input = new JsEvalContext(feedbackListData);
- var output = $('feedback-template');
- jstProcess(input, output);
- };
-
- // Export
- return {
- ResetProfileSettingsOverlay: ResetProfileSettingsOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/search_box.html b/chromium/chrome/browser/resources/options/search_box.html
deleted file mode 100644
index 854538e5b55..00000000000
--- a/chromium/chrome/browser/resources/options/search_box.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<div id="searchBox" class="page">
- <header >
- <span id="browser-options-search-field-container"
- class="search-field-container">
- <a is="action-link" id="about-button" hidden>$i18n{aboutButton}</a>
- <input id="search-field" type="search"
- placeholder="$i18n{searchPlaceholder}"
- aria-label="$i18n{searchPlaceholder}" incremental>
- </span>
- </header>
-</div>
diff --git a/chromium/chrome/browser/resources/options/search_engine_manager.css b/chromium/chrome/browser/resources/options/search_engine_manager.css
deleted file mode 100644
index 3235031b035..00000000000
--- a/chromium/chrome/browser/resources/options/search_engine_manager.css
+++ /dev/null
@@ -1,89 +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. */
-
-#search-engine-manager-page {
- width: 700px;
-}
-
-.search-engine-list input {
- width: 100%;
-}
-
-.search-engine-list > div {
- display: -webkit-box;
-}
-
-.search-engine-list .favicon {
- background-position: center center;
- background-repeat: no-repeat;
- background-size: 16px;
- height: 16px;
- line-height: 16px;
- padding: 0 7px;
- width: 16px;
-}
-
-.search-engine-list .name-column {
- -webkit-box-align: center;
- -webkit-padding-end: 1ex;
- box-sizing: border-box;
- display: -webkit-box;
- width: 30%;
-}
-
-.search-engine-list .name-column :last-child {
- -webkit-box-flex: 1;
-}
-
-.search-engine-list .keyword-column {
- -webkit-padding-end: 1ex;
- box-sizing: border-box;
- width: 26%;
-}
-
-.search-engine-list .url-column {
- box-sizing: border-box;
- width: 44%;
-}
-
-.search-engine-list .keyword-column,
-.search-engine-list .url-column {
- color: #666;
-}
-
-.search-engine-list .default .name-column,
-.search-engine-list .default .keyword-column {
- font-weight: bold;
-}
-
-/* For temporary Make Default button */
-.search-engine-list .url-column {
- -webkit-box-align: center;
- display: -webkit-box;
-}
-
-.search-engine-list .url-column :first-child {
- -webkit-box-flex: 1;
-}
-
-.search-engine-list .url-column .list-inline-button {
- -webkit-margin-start: 1ex;
- margin-top: 0;
- padding: 1px 6px 2px 6px;
-}
-
-.search-engine-list > :not(:hover):not([editing]) .url-column
- .list-inline-button {
- display: none;
-}
-
-#default-search-engine-list {
- z-index: 2;
-}
-
-#other-search-engine-list {
- z-index: 1;
-}
-
-/* End temporary Make Default button styling */
diff --git a/chromium/chrome/browser/resources/options/search_engine_manager.html b/chromium/chrome/browser/resources/options/search_engine_manager.html
deleted file mode 100644
index 9d76000730d..00000000000
--- a/chromium/chrome/browser/resources/options/search_engine_manager.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<div id="search-engine-manager-page" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{searchEngineManagerPage}</h1>
- <div class="content-area">
- <h3>$i18n{defaultSearchEngineListTitle}</h3>
- <list id="default-search-engine-list"
- class="search-engine-list settings-list"></list>
- <h3>$i18n{otherSearchEngineListTitle}</h3>
- <list id="other-search-engine-list"
- class="search-engine-list settings-list"></list>
- <div id="extension-keyword-div" hidden>
- <h3 id="extension-keyword-list-title">
- $i18n{extensionKeywordsListTitle}
- </h3>
- <list id="extension-keyword-list"
- class="search-engine-list settings-list"></list>
- </div>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="search-engine-manager-confirm" type="submit"
- class="default-button">
- $i18n{done}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/search_engine_manager.js b/chromium/chrome/browser/resources/options/search_engine_manager.js
deleted file mode 100644
index ce31ef69181..00000000000
--- a/chromium/chrome/browser/resources/options/search_engine_manager.js
+++ /dev/null
@@ -1,133 +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.
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /**
- * Encapsulated handling of search engine management page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function SearchEngineManager() {
- this.activeNavTab = null;
- Page.call(this, 'searchEngines',
- loadTimeData.getString('searchEngineManagerPageTabTitle'),
- 'search-engine-manager-page');
- }
-
- cr.addSingletonGetter(SearchEngineManager);
-
- SearchEngineManager.prototype = {
- __proto__: Page.prototype,
-
- /**
- * List for default search engine options.
- * @private
- */
- defaultsList_: null,
-
- /**
- * List for other search engine options.
- * @private
- */
- othersList_: null,
-
- /**
- * List for extension keywords.
- * @private
- */
- extensionList_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- this.defaultsList_ = $('default-search-engine-list');
- this.setUpList_(this.defaultsList_);
-
- this.othersList_ = $('other-search-engine-list');
- this.setUpList_(this.othersList_);
-
- this.extensionList_ = $('extension-keyword-list');
- this.setUpList_(this.extensionList_);
-
- $('search-engine-manager-confirm').onclick = function() {
- PageManager.closeOverlay();
- };
- },
-
- /**
- * Sets up the given list as a search engine list
- * @param {HTMLElement} list The list to set up.
- * @private
- */
- setUpList_: function(list) {
- options.search_engines.SearchEngineList.decorate(list);
- list.autoExpands = true;
- },
-
- /**
- * Updates the search engine list with the given entries.
- * @private
- * @param {!Array} defaultEngines List of possible default search engines.
- * @param {!Array} otherEngines List of other search engines.
- * @param {!Array} keywords List of keywords from extensions.
- */
- updateSearchEngineList_: function(defaultEngines, otherEngines, keywords) {
- this.defaultsList_.dataModel = new ArrayDataModel(defaultEngines);
-
- otherEngines = otherEngines.map(function(x) {
- return [x, x.name.toLocaleLowerCase()];
- }).sort(function(a, b) {
- return a[1].localeCompare(b[1]);
- }).map(function(x) {
- return x[0];
- });
-
- var othersModel = new ArrayDataModel(otherEngines);
- // Add a "new engine" row.
- othersModel.push({
- 'modelIndex': '-1',
- 'canBeEdited': true
- });
- this.othersList_.dataModel = othersModel;
-
- if (keywords.length > 0) {
- $('extension-keyword-div').hidden = false;
- var extensionsModel = new ArrayDataModel(keywords);
- this.extensionList_.dataModel = extensionsModel;
- } else {
- $('extension-keyword-div').hidden = true;
- }
- },
- };
-
- SearchEngineManager.updateSearchEngineList = function(defaultEngines,
- otherEngines,
- keywords) {
- SearchEngineManager.getInstance().updateSearchEngineList_(defaultEngines,
- otherEngines,
- keywords);
- };
-
- SearchEngineManager.validityCheckCallback = function(validity, modelIndex) {
- // Forward to all lists; those without a matching modelIndex will ignore it.
- SearchEngineManager.getInstance().defaultsList_.validationComplete(
- validity, modelIndex);
- SearchEngineManager.getInstance().othersList_.validationComplete(
- validity, modelIndex);
- SearchEngineManager.getInstance().extensionList_.validationComplete(
- validity, modelIndex);
- };
-
- // Export
- return {
- SearchEngineManager: SearchEngineManager
- };
-
-});
-
diff --git a/chromium/chrome/browser/resources/options/search_engine_manager_engine_list.js b/chromium/chrome/browser/resources/options/search_engine_manager_engine_list.js
deleted file mode 100644
index 7284ae9ca3a..00000000000
--- a/chromium/chrome/browser/resources/options/search_engine_manager_engine_list.js
+++ /dev/null
@@ -1,379 +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.
-
-/**
- * @typedef {{canBeDefault: boolean,
- * canBeEdited: boolean,
- * canBeRemoved: boolean,
- * default: boolean,
- * displayName: string,
- * extension: (Object|undefined),
- * iconURL: (string|undefined),
- * isOmniboxExtension: boolean,
- * keyword: string,
- * modelIndex: string,
- * name: string,
- * url: string,
- * urlLocked: boolean}}
- * @see chrome/browser/ui/webui/options/search_engine_manager_handler.cc
- */
-var SearchEngine;
-
-cr.define('options.search_engines', function() {
- /** @const */ var ControlledSettingIndicator =
- options.ControlledSettingIndicator;
- /** @const */ var InlineEditableItemList = options.InlineEditableItemList;
- /** @const */ var InlineEditableItem = options.InlineEditableItem;
- /** @const */ var ListSelectionController = cr.ui.ListSelectionController;
-
- /**
- * Creates a new search engine list item.
- * @param {SearchEngine} searchEngine The search engine this represents.
- * @constructor
- * @extends {options.InlineEditableItem}
- */
- function SearchEngineListItem(searchEngine) {
- var el = cr.doc.createElement('div');
- el.searchEngine_ = searchEngine;
- SearchEngineListItem.decorate(el);
- return el;
- }
-
- /**
- * Decorates an element as a search engine list item.
- * @param {!HTMLElement} el The element to decorate.
- */
- SearchEngineListItem.decorate = function(el) {
- el.__proto__ = SearchEngineListItem.prototype;
- el.decorate();
- };
-
- SearchEngineListItem.prototype = {
- __proto__: InlineEditableItem.prototype,
-
- /**
- * Input field for editing the engine name.
- * @type {HTMLElement}
- * @private
- */
- nameField_: null,
-
- /**
- * Input field for editing the engine keyword.
- * @type {HTMLElement}
- * @private
- */
- keywordField_: null,
-
- /**
- * Input field for editing the engine url.
- * @type {HTMLElement}
- * @private
- */
- urlField_: null,
-
- /**
- * Whether or not an input validation request is currently outstanding.
- * @type {boolean}
- * @private
- */
- waitingForValidation_: false,
-
- /**
- * Whether or not the current set of input is known to be valid.
- * @type {boolean}
- * @private
- */
- currentlyValid_: false,
-
- /**
- * @type {?SearchEngine}
- */
- searchEngine_: null,
-
- /** @override */
- decorate: function() {
- InlineEditableItem.prototype.decorate.call(this);
-
- var engine = this.searchEngine_;
-
- if (engine.modelIndex == '-1') {
- this.isPlaceholder = true;
- engine.name = '';
- engine.keyword = '';
- engine.url = '';
- }
-
- this.currentlyValid_ = !this.isPlaceholder;
-
- if (engine.default)
- this.classList.add('default');
-
- this.deletable = engine.canBeRemoved;
- this.closeButtonFocusAllowed = true;
-
- // Construct the name column.
- var nameColEl = this.ownerDocument.createElement('div');
- nameColEl.className = 'name-column';
- nameColEl.classList.add('weakrtl');
- this.contentElement.appendChild(nameColEl);
-
- // Add the favicon.
- var faviconDivEl = this.ownerDocument.createElement('div');
- faviconDivEl.className = 'favicon';
- if (!this.isPlaceholder) {
- // Force default icon if no iconURL is available.
- faviconDivEl.style.backgroundImage =
- cr.icon.getFavicon(engine.iconURL || '');
- }
-
- nameColEl.appendChild(faviconDivEl);
-
- var nameEl = this.createEditableTextCell(engine.displayName);
- nameEl.classList.add('weakrtl');
- nameColEl.appendChild(nameEl);
-
- // Then the keyword column.
- var keywordEl = this.createEditableTextCell(engine.keyword);
- keywordEl.className = 'keyword-column';
- keywordEl.classList.add('weakrtl');
- this.contentElement.appendChild(keywordEl);
-
- // And the URL column.
- var urlEl = this.createEditableTextCell(engine.url);
- var makeDefaultButtonEl = null;
- // Extensions should not display a URL column.
- if (!engine.isOmniboxExtension) {
- var urlWithButtonEl = this.ownerDocument.createElement('div');
- urlWithButtonEl.appendChild(urlEl);
- urlWithButtonEl.className = 'url-column';
- urlWithButtonEl.classList.add('weakrtl');
- this.contentElement.appendChild(urlWithButtonEl);
- // Add the Make Default button. Temporary until drag-and-drop
- // re-ordering is implemented. When this is removed, remove the extra
- // div above.
- if (engine.canBeDefault) {
- makeDefaultButtonEl = this.ownerDocument.createElement('button');
- makeDefaultButtonEl.className =
- 'custom-appearance list-inline-button';
- makeDefaultButtonEl.textContent =
- loadTimeData.getString('makeDefaultSearchEngineButton');
- makeDefaultButtonEl.onclick = function(e) {
- chrome.send('managerSetDefaultSearchEngine', [engine.modelIndex]);
- };
- makeDefaultButtonEl.onmousedown = function(e) {
- // Don't select the row when clicking the button.
- e.stopPropagation();
- // Don't focus on the button.
- e.preventDefault();
- };
- urlWithButtonEl.appendChild(makeDefaultButtonEl);
- }
- }
-
- // Do final adjustment to the input fields.
- this.nameField_ = /** @type {HTMLElement} */(
- nameEl.querySelector('input'));
- // The editable field uses the raw name, not the display name.
- this.nameField_.value = engine.name;
- this.keywordField_ = /** @type {HTMLElement} */(
- keywordEl.querySelector('input'));
- this.urlField_ = /** @type {HTMLElement} */(urlEl.querySelector('input'));
-
- if (engine.urlLocked)
- this.urlField_.disabled = true;
-
- if (this.isPlaceholder) {
- this.nameField_.placeholder =
- loadTimeData.getString('searchEngineTableNamePlaceholder');
- this.keywordField_.placeholder =
- loadTimeData.getString('searchEngineTableKeywordPlaceholder');
- this.urlField_.placeholder =
- loadTimeData.getString('searchEngineTableURLPlaceholder');
- }
-
- this.setFocusableColumnIndex(this.nameField_, 0);
- this.setFocusableColumnIndex(this.keywordField_, 1);
- this.setFocusableColumnIndex(this.urlField_, 2);
- this.setFocusableColumnIndex(makeDefaultButtonEl, 3);
- this.setFocusableColumnIndex(this.closeButtonElement, 4);
-
- var fields = [this.nameField_, this.keywordField_, this.urlField_];
- for (var i = 0; i < fields.length; i++) {
- fields[i].oninput = this.startFieldValidation_.bind(this);
- }
-
- // Listen for edit events.
- if (engine.canBeEdited) {
- this.addEventListener('edit', this.onEditStarted_.bind(this));
- this.addEventListener('canceledit', this.onEditCancelled_.bind(this));
- this.addEventListener('commitedit', this.onEditCommitted_.bind(this));
- } else {
- this.editable = false;
- this.querySelector('.row-delete-button').hidden = true;
- var indicator = new ControlledSettingIndicator();
- indicator.setAttribute('setting', 'search-engine');
- // Create a synthetic pref change event decorated as
- // CoreOptionsHandler::CreateValueForPref() does.
- var event = new Event(this.contentType);
- if (engine.extension) {
- event.value = { controlledBy: 'extension',
- extension: engine.extension };
- } else {
- event.value = { controlledBy: 'policy' };
- }
- indicator.handlePrefChange(event);
- this.appendChild(indicator);
- }
- },
-
- /** @override */
- get currentInputIsValid() {
- return !this.waitingForValidation_ && this.currentlyValid_;
- },
-
- /** @override */
- get hasBeenEdited() {
- var engine = this.searchEngine_;
- return this.nameField_.value != engine.name ||
- this.keywordField_.value != engine.keyword ||
- this.urlField_.value != engine.url;
- },
-
- /**
- * Called when entering edit mode; starts an edit session in the model.
- * @param {Event} e The edit event.
- * @private
- */
- onEditStarted_: function(e) {
- var editIndex = this.searchEngine_.modelIndex;
- chrome.send('editSearchEngine', [String(editIndex)]);
- this.startFieldValidation_();
- },
-
- /**
- * Called when committing an edit; updates the model.
- * @param {Event} e The end event.
- * @private
- */
- onEditCommitted_: function(e) {
- chrome.send('searchEngineEditCompleted', this.getInputFieldValues_());
- },
-
- /**
- * Called when cancelling an edit; informs the model and resets the control
- * states.
- * @param {Event} e The cancel event.
- * @private
- */
- onEditCancelled_: function(e) {
- chrome.send('searchEngineEditCancelled');
-
- // The name field has been automatically set to match the display name,
- // but it should use the raw name instead.
- this.nameField_.value = this.searchEngine_.name;
- this.currentlyValid_ = !this.isPlaceholder;
- },
-
- /**
- * Returns the input field values as an array suitable for passing to
- * chrome.send. The order of the array is important.
- * @private
- * @return {Array} The current input field values.
- */
- getInputFieldValues_: function() {
- return [this.nameField_.value,
- this.keywordField_.value,
- this.urlField_.value];
- },
-
- /**
- * Begins the process of asynchronously validing the input fields.
- * @private
- */
- startFieldValidation_: function() {
- this.waitingForValidation_ = true;
- var args = this.getInputFieldValues_();
- args.push(this.searchEngine_.modelIndex);
- chrome.send('checkSearchEngineInfoValidity', args);
- },
-
- /**
- * Callback for the completion of an input validition check.
- * @param {Object} validity A dictionary of validitation results.
- */
- validationComplete: function(validity) {
- this.waitingForValidation_ = false;
- if (validity.name) {
- this.nameField_.setCustomValidity('');
- } else {
- this.nameField_.setCustomValidity(
- loadTimeData.getString('editSearchEngineInvalidTitleToolTip'));
- }
-
- if (validity.keyword) {
- this.keywordField_.setCustomValidity('');
- } else {
- this.keywordField_.setCustomValidity(
- loadTimeData.getString('editSearchEngineInvalidKeywordToolTip'));
- }
-
- if (validity.url) {
- this.urlField_.setCustomValidity('');
- } else {
- this.urlField_.setCustomValidity(
- loadTimeData.getString('editSearchEngineInvalidURLToolTip'));
- }
-
- this.currentlyValid_ = validity.name && validity.keyword && validity.url;
- },
- };
-
- /**
- * @constructor
- * @extends {options.InlineEditableItemList}
- */
- var SearchEngineList = cr.ui.define('list');
-
- SearchEngineList.prototype = {
- __proto__: InlineEditableItemList.prototype,
-
- /**
- * @override
- * @param {SearchEngine} searchEngine
- */
- createItem: function(searchEngine) {
- return new SearchEngineListItem(searchEngine);
- },
-
- /** @override */
- deleteItemAtIndex: function(index) {
- var modelIndex = this.dataModel.item(index).modelIndex;
- chrome.send('removeSearchEngine', [String(modelIndex)]);
- },
-
- /**
- * Passes the results of an input validation check to the requesting row
- * if it's still being edited.
- * @param {number} modelIndex The model index of the item that was checked.
- * @param {Object} validity A dictionary of validitation results.
- */
- validationComplete: function(validity, modelIndex) {
- // If it's not still being edited, it no longer matters.
- var currentSelection = this.selectedItem;
- if (!currentSelection)
- return;
- var listItem = this.getListItem(currentSelection);
- if (listItem.editing && currentSelection.modelIndex == modelIndex)
- listItem.validationComplete(validity);
- },
- };
-
- // Export
- return {
- SearchEngineList: SearchEngineList
- };
-
-});
-
diff --git a/chromium/chrome/browser/resources/options/search_page.css b/chromium/chrome/browser/resources/options/search_page.css
deleted file mode 100644
index 2d047ba781a..00000000000
--- a/chromium/chrome/browser/resources/options/search_page.css
+++ /dev/null
@@ -1,80 +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. */
-
-.search-hidden {
- display: none !important;
-}
-
-.search-highlighted {
- background-color: rgba(255, 240, 120, 0.9);
-}
-
-/* Container for the elements that make up the search bubble. */
-.search-bubble {
- left: 0;
- position: absolute;
- top: -1000px; /* Minor hack: position off-screen by default. */
- /* Create a z-context for search-bubble-innards, its after and before. */
- z-index: 1;
-}
-
-/* Contains the text content of the bubble. */
-.search-bubble-innards {
- background: -webkit-linear-gradient(rgba(255, 248, 172, 0.9),
- rgba(255, 243, 128, 0.9));
- border-radius: 2px;
- padding: 4px 10px;
- text-align: center;
- width: 100px;
-}
-
-/* Provides the border around the bubble (has to be behind ::after). */
-.search-bubble-innards::before {
- border: 1px solid rgb(220, 198, 72);
- border-radius: 2px;
- bottom: -1px;
- content: '';
- left: -1px;
- position: absolute;
- right: -1px;
- top: -1px;
- z-index: -2;
-}
-
-/* Provides the arrow which points at the anchor element. */
-.search-bubble-innards::after {
- background:
- -webkit-linear-gradient(-45deg, rgb(251, 255, 181),
- rgb(255, 248, 172) 50%,
- rgba(255, 248, 172, 0));
- border: 1px solid rgb(220, 198, 72);
- border-bottom-color: transparent;
- border-right-color: transparent;
- content: '';
- height: 12px;
- left: 53px;
- position: absolute;
- top: -7px;
- transform: rotate(45deg);
- width: 12px;
- z-index: -1;
-}
-
-/* Turns the arrow direction downwards, when the bubble is placed above the
- * anchor element */
-.search-bubble-innards.above::after {
- bottom: -7px;
- top: auto;
- transform: rotate(-135deg);
-}
-
-.search-bubble-wrapper {
- position: relative;
-}
-
-/* #mainview is here to win specificity. :( */
-#mainview #searchPage.page,
-#mainview #searchBox.page {
- padding-bottom: 0;
-}
diff --git a/chromium/chrome/browser/resources/options/search_page.html b/chromium/chrome/browser/resources/options/search_page.html
deleted file mode 100644
index dcc9ed70751..00000000000
--- a/chromium/chrome/browser/resources/options/search_page.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<div id="searchPage" class="page" hidden>
- <header>
- <h1>$i18n{searchPage}</h1>
- </header>
- <div id="searchPageNoMatches" hidden>
- <p>$i18n{searchPageNoMatches}</p>
- <p><span>$i18n{searchPageHelpLabel}</span>
- <a target="_blank"
- href="$i18nRaw{searchPageHelpURL}">$i18n{searchPageHelpTitle}</a>
- </p>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/search_page.js b/chromium/chrome/browser/resources/options/search_page.js
deleted file mode 100644
index c561a0cccbb..00000000000
--- a/chromium/chrome/browser/resources/options/search_page.js
+++ /dev/null
@@ -1,710 +0,0 @@
-// Copyright 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.
-
-/**
- * Section IDs use for metrics. The integer values should match up with the
- * |SettingsSections| in histograms.xml.
- * @type {Object<string, number>}
- */
-var SettingsSections = {
- 'None': 0,
- 'Unknown': 1,
- 'network-section-cros': 2,
- 'proxy-section': 3,
- 'appearance-section': 4,
- 'device-section': 5,
- 'search-section': 6,
- 'sync-users-section': 7,
- 'set-default-browser-section': 8,
- 'date-time-section': 9,
- 'device-control-section': 10,
- 'privacy-section': 11,
- 'bluetooth-devices': 12,
- 'passwords-and-autofill-section': 13,
- 'easy-unlock-section': 14,
- 'web-content-section': 15,
- 'network-section': 16,
- 'languages-section': 17,
- 'downloads-section': 18,
- 'certificates-section': 19,
- 'cloudprint-options-mdns': 20,
- 'a11y-section': 21,
- 'factory-reset-section': 22,
- 'system-section': 23,
- 'reset-profile-settings-section': 24,
- 'sync-section': 25,
- 'startup-section': 26,
- 'mouselock-section': 27,
- 'page-zoom-levels': 28,
- 'status-section': 29,
- 'main-section': 30,
- 'pointer-section-touchpad': 31,
- 'pointer-section-mouse': 32,
- 'prefs-blocked-languages': 33,
- 'prefs-language-blacklist': 34,
- 'prefs-site-blacklist': 35,
- 'prefs-whitelists': 36,
- 'prefs-supported-languages': 37,
- 'prefs-cld-version': 38,
- 'prefs-cld-data-source': 39,
- 'prefs-dump': 40,
-};
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Encapsulated handling of a search bubble.
- * @constructor
- * @extends {HTMLDivElement}
- */
- function SearchBubble(text) {
- var el = cr.doc.createElement('div');
- SearchBubble.decorate(el);
- el.content = text;
- return el;
- }
-
- /**
- * Prohibit search for guests on desktop.
- */
- function ShouldEnableSearch() {
- return !loadTimeData.getBoolean('profileIsGuest') || cr.isChromeOS;
- }
-
- SearchBubble.decorate = function(el) {
- el.__proto__ = SearchBubble.prototype;
- el.decorate();
- };
-
- SearchBubble.prototype = {
- __proto__: HTMLDivElement.prototype,
-
- decorate: function() {
- this.className = 'search-bubble';
-
- this.innards_ = cr.doc.createElement('div');
- this.innards_.className = 'search-bubble-innards';
- this.appendChild(this.innards_);
-
- // We create a timer to periodically update the position of the bubbles.
- // While this isn't all that desirable, it's the only sure-fire way of
- // making sure the bubbles stay in the correct location as sections
- // may dynamically change size at any time.
- this.intervalId = setInterval(this.updatePosition.bind(this), 250);
-
- this.addEventListener('mouseover', function() {
- this.innards_.classList.toggle('above');
- this.updatePosition();
- });
- },
-
- /**
- * Sets the text message in the bubble.
- * @param {string} text The text the bubble will show.
- */
- set content(text) {
- this.innards_.textContent = text;
- },
-
- /**
- * Attach the bubble to the element.
- */
- attachTo: function(element) {
- var parent = element.parentElement;
- if (!parent)
- return;
- if (parent.tagName == 'TD') {
- // To make absolute positioning work inside a table cell we need
- // to wrap the bubble div into another div with position:relative.
- // This only works properly if the element is the first child of the
- // table cell which is true for all options pages.
- this.wrapper = cr.doc.createElement('div');
- this.wrapper.className = 'search-bubble-wrapper';
- this.wrapper.appendChild(this);
- parent.insertBefore(this.wrapper, element);
- } else {
- parent.insertBefore(this, element);
- }
- },
-
- /**
- * Clear the interval timer and remove the element from the page.
- */
- dispose: function() {
- clearInterval(this.intervalId);
-
- var child = this.wrapper || this;
- var parent = child.parentNode;
- if (parent)
- parent.removeChild(child);
- },
-
- /**
- * Update the position of the bubble. Called at creation time and then
- * periodically while the bubble remains visible.
- */
- updatePosition: function() {
- // This bubble is 'owned' by the next sibling.
- var owner = (this.wrapper || this).nextSibling;
-
- // If there isn't an offset parent, we have nothing to do.
- if (!owner.offsetParent)
- return;
-
- // Position the bubble below the location of the owner.
- var left = owner.offsetLeft + owner.offsetWidth / 2 -
- this.offsetWidth / 2;
-
- var BUBBLE_EDGE_OFFSET = 5;
- var top = owner.offsetTop;
- if (this.innards_.classList.contains('above'))
- top -= this.offsetHeight + BUBBLE_EDGE_OFFSET;
- else
- top += owner.offsetHeight + BUBBLE_EDGE_OFFSET;
-
- // Update the position in the CSS. Cache the last values for
- // best performance.
- if (left != this.lastLeft) {
- this.style.left = left + 'px';
- this.lastLeft = left;
- }
- if (top != this.lastTop) {
- this.style.top = top + 'px';
- this.lastTop = top;
- }
- },
- };
-
- /**
- * Encapsulated handling of the search page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function SearchPage() {
- Page.call(this, 'search',
- loadTimeData.getString('searchPageTabTitle'),
- 'searchPage');
- }
-
- cr.addSingletonGetter(SearchPage);
-
- SearchPage.prototype = {
- // Inherit SearchPage from Page.
- __proto__: Page.prototype,
-
- /**
- * Wait a bit to see if the user is still entering search text.
- * @type {number|undefined}
- * @private
- */
- delayedSearchMetric_: undefined,
-
- /**
- * Only send the time of first search once.
- * @type {boolean}
- * @private
- */
- hasSentFirstSearchTime_: false,
-
- /**
- * A boolean to prevent recursion. Used by setSearchText_().
- * @type {boolean}
- * @private
- */
- insideSetSearchText_: false,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- // Record the start time for use in reporting metrics.
- this.createdTimestamp_ = Date.now();
-
- this.searchField = $('search-field');
-
- // Handle search events. (No need to throttle, WebKit's search field
- // will do that automatically.)
- this.searchField.onsearch = function(e) {
- this.setSearchText_(e.currentTarget.value);
- }.bind(this);
-
- // Install handler for key presses.
- document.addEventListener('keydown',
- this.keyDownEventHandler_.bind(this));
- },
-
- /** @override */
- get sticky() {
- return true;
- },
-
- /** @override */
- didShowPage: function() {
- // This method is called by the PageManager after all pages have had their
- // visibility attribute set. At this point we can perform the
- // search-specific DOM manipulation.
- this.setSearchActive_(true);
- },
-
- /** @override */
- didChangeHash: function() {
- this.setSearchActive_(true);
- },
-
- /** @override */
- willHidePage: function() {
- // This method is called by the PageManager before all pages have their
- // visibility attribute set. Before that happens, we need to undo the
- // search-specific DOM manipulation that was performed in didShowPage.
- this.setSearchActive_(false);
- },
-
- /**
- * Update the UI to reflect whether we are in a search state.
- * @param {boolean} active True if we are on the search page.
- * @private
- */
- setSearchActive_: function(active) {
- // It's fine to exit if search wasn't active and we're not going to
- // activate it now.
- if (!this.searchActive_ && !active)
- return;
-
- if (!ShouldEnableSearch())
- return;
-
- this.searchActive_ = active;
-
- if (active) {
- var hash = this.hash;
- if (hash) {
- this.searchField.value =
- decodeURIComponent(hash.slice(1).replace(/\+/g, ' '));
- } else if (!this.searchField.value) {
- // This should only happen if the user goes directly to
- // chrome://settings-frame/search
- PageManager.showDefaultPage();
- return;
- }
-
- // Move 'advanced' sections into the main settings page to allow
- // searching.
- if (!this.advancedSections_) {
- this.advancedSections_ =
- $('advanced-settings-container').querySelectorAll('section');
- for (var i = 0, section; section = this.advancedSections_[i]; i++)
- $('settings').appendChild(section);
- }
- } else {
- this.searchField.value = '';
- }
-
- var pagesToSearch = this.getSearchablePages_();
- for (var i = 0; i < pagesToSearch.length; i++) {
- var page = pagesToSearch[i];
-
- if (!active)
- page.visible = false;
-
- // Update the visible state of all top-level elements that are not
- // sections (ie titles, button strips). We do this before changing
- // the page visibility to avoid excessive re-draw.
- for (var i = 0, childDiv; childDiv = page.pageDiv.children[i]; i++) {
- if (active) {
- if (childDiv.tagName != 'SECTION')
- childDiv.classList.add('search-hidden');
- } else {
- childDiv.classList.remove('search-hidden');
- }
- }
-
- if (active) {
- // When search is active, remove the 'hidden' tag. This tag may have
- // been added by the PageManager.
- page.pageDiv.hidden = false;
- }
- }
-
- if (active) {
- this.setSearchText_(this.searchField.value);
- this.searchField.focus();
- } else {
- // After hiding all page content, remove any search results.
- this.unhighlightMatches_();
- this.removeSearchBubbles_();
-
- // Move 'advanced' sections back into their original container.
- if (this.advancedSections_) {
- for (var i = 0, section; section = this.advancedSections_[i]; i++)
- $('advanced-settings-container').appendChild(section);
- this.advancedSections_ = null;
- }
- }
- },
-
- /**
- * Set the current search criteria.
- * @param {string} text Search text.
- * @private
- */
- setSearchText_: function(text) {
- if (!ShouldEnableSearch())
- return;
-
- // Prevent recursive execution of this method.
- if (this.insideSetSearchText_) return;
- this.insideSetSearchText_ = true;
-
- // Cleanup the search query string.
- text = SearchPage.canonicalizeQuery(text);
-
- // If the search string becomes empty, flip back to the default page.
- if (!text) {
- if (this.searchActive_)
- PageManager.showDefaultPage();
- this.insideSetSearchText_ = false;
- return;
- }
-
- if (!this.hasSentFirstSearchTime_) {
- this.hasSentFirstSearchTime_ = true;
- chrome.metricsPrivate.recordMediumTime('Settings.TimeToFirstSearch',
- Date.now() - this.createdTimestamp_);
- }
-
- // Toggle the search page if necessary. Otherwise, update the hash.
- var hash = '#' + encodeURIComponent(text);
- if (this.searchActive_) {
- if (this.hash != hash)
- this.setHash(hash);
- } else {
- PageManager.showPageByName(this.name, true, {hash: hash});
- }
-
- var foundMatches = false;
-
- // Remove any prior search results.
- this.unhighlightMatches_();
- this.removeSearchBubbles_();
-
- var pagesToSearch = this.getSearchablePages_();
- for (var i = 0; i < pagesToSearch.length; i++) {
- var page = pagesToSearch[i];
- var elements = page.pageDiv.querySelectorAll('section');
- for (var i = 0, node; node = elements[i]; i++) {
- node.classList.add('search-hidden');
- }
- }
-
- var bubbleControls = [];
- var pageMatchesForMetrics = 0;
- var subpageMatchesForMetrics = 0;
- var sectionMatchesForMetrics = {};
-
- // Generate search text by applying lowercase and escaping any characters
- // that would be problematic for regular expressions.
- var searchText =
- text.toLowerCase().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
- // Generate a regular expression for hilighting search terms.
- var regExp = new RegExp('(' + searchText + ')', 'ig');
-
- if (searchText.length) {
- // Search all top-level sections for anchored string matches.
- for (var i = 0; i < pagesToSearch.length; i++) {
- var page = pagesToSearch[i];
- var elements =
- page.pageDiv.querySelectorAll('section');
- for (var i = 0, node; node = elements[i]; i++) {
- if (this.highlightMatches_(regExp, node)) {
- node.classList.remove('search-hidden');
- if (!node.hidden) {
- foundMatches = true;
- pageMatchesForMetrics += 1;
- var section = SettingsSections[node.id] ||
- SettingsSections['Unknown'];
- sectionMatchesForMetrics[section] = section;
- }
- }
- }
- }
-
- // Search all sub-pages, generating an array of top-level sections that
- // we need to make visible.
- var subPagesToSearch = this.getSearchableSubPages_();
- var control, node;
- for (var i = 0; i < subPagesToSearch.length; i++) {
- var page = subPagesToSearch[i];
- if (this.highlightMatches_(regExp, page.pageDiv)) {
- this.revealAssociatedSections_(page);
-
- bubbleControls =
- bubbleControls.concat(this.getAssociatedControls_(page));
-
- foundMatches = true;
- subpageMatchesForMetrics += 1;
- }
- }
- }
-
- // Configure elements on the search results page based on search results.
- $('searchPageNoMatches').hidden = foundMatches;
-
- // Create search balloons for sub-page results.
- var bubbleCount = bubbleControls.length;
- for (var i = 0; i < bubbleCount; i++)
- this.createSearchBubble_(bubbleControls[i], text);
-
- // If the search doesn't change for one second, send some metrics.
- clearTimeout(this.delayedSearchMetric_);
- this.delayedSearchMetric_ = setTimeout(function() {
- if (!foundMatches) {
- chrome.metricsPrivate.recordSmallCount(
- 'Settings.SearchLengthNoMatch', text.length);
- chrome.metricsPrivate.recordSmallCount(
- 'Settings.SearchSections', SettingsSections['None']);
- } else {
- for (var section in sectionMatchesForMetrics) {
- var sectionId = sectionMatchesForMetrics[section];
- assert(sectionId !== undefined);
- chrome.metricsPrivate.recordSmallCount(
- 'Settings.SearchSections', sectionId);
- }
- }
-
- chrome.metricsPrivate.recordUserAction('Settings.Searching');
- chrome.metricsPrivate.recordSmallCount(
- 'Settings.SearchLength', text.length);
- chrome.metricsPrivate.recordSmallCount(
- 'Settings.SearchPageMatchCount', pageMatchesForMetrics);
- chrome.metricsPrivate.recordSmallCount(
- 'Settings.SearchSubpageMatchCount', subpageMatchesForMetrics);
- }, 1000);
-
- // Cleanup the recursion-prevention variable.
- this.insideSetSearchText_ = false;
- },
-
- /**
- * Reveal the associated section for |subpage|, as well as the one for its
- * |parentPage|, and its |parentPage|'s |parentPage|, etc.
- * @private
- */
- revealAssociatedSections_: function(subpage) {
- for (var page = subpage; page; page = page.parentPage) {
- var section = page.associatedSection;
- if (section)
- section.classList.remove('search-hidden');
- }
- },
-
- /**
- * @return {!Array<HTMLElement>} all the associated controls for |subpage|,
- * including |subpage.associatedControls| as well as any controls on parent
- * pages that are indirectly necessary to get to the subpage.
- * @private
- */
- getAssociatedControls_: function(subpage) {
- var controls = [];
- for (var page = subpage; page; page = page.parentPage) {
- if (page.associatedControls)
- controls = controls.concat(page.associatedControls);
- }
- return controls;
- },
-
- /**
- * Wraps matches in spans.
- * @param {RegExp} regExp The search query (in regexp form).
- * @param {Element} element An HTML container element to recursively search
- * within.
- * @return {boolean} true if the element was changed.
- * @private
- */
- highlightMatches_: function(regExp, element) {
- var found = false;
- var div, child, tmp;
-
- // Walk the tree, searching each TEXT node.
- var walker = document.createTreeWalker(element,
- NodeFilter.SHOW_TEXT,
- null,
- false);
- var node = walker.nextNode();
- while (node) {
- var textContent = node.nodeValue;
- // Perform a search and replace on the text node value.
- var split = textContent.split(regExp);
- if (split.length > 1) {
- found = true;
- var nextNode = walker.nextNode();
- var parentNode = node.parentNode;
- // Use existing node as placeholder to determine where to insert the
- // replacement content.
- for (var i = 0; i < split.length; ++i) {
- if (i % 2 == 0) {
- parentNode.insertBefore(document.createTextNode(split[i]), node);
- } else {
- var span = document.createElement('span');
- span.className = 'search-highlighted';
- span.textContent = split[i];
- parentNode.insertBefore(span, node);
- }
- }
- // Remove old node.
- parentNode.removeChild(node);
- node = nextNode;
- } else {
- node = walker.nextNode();
- }
- }
-
- return found;
- },
-
- /**
- * Removes all search highlight tags from the document.
- * @private
- */
- unhighlightMatches_: function() {
- // Find all search highlight elements.
- var elements = document.querySelectorAll('.search-highlighted');
-
- // For each element, remove the highlighting.
- var parent, i;
- for (var i = 0, node; node = elements[i]; i++) {
- parent = node.parentNode;
-
- // Replace the highlight element with the first child (the text node).
- parent.replaceChild(node.firstChild, node);
-
- // Normalize the parent so that multiple text nodes will be combined.
- parent.normalize();
- }
- },
-
- /**
- * Creates a search result bubble attached to an element.
- * @param {Element} element An HTML element, usually a button.
- * @param {string} text A string to show in the bubble.
- * @private
- */
- createSearchBubble_: function(element, text) {
- // avoid appending multiple bubbles to a button.
- var sibling = element.previousElementSibling;
- if (sibling && (sibling.classList.contains('search-bubble') ||
- sibling.classList.contains('search-bubble-wrapper')))
- return;
-
- var parent = element.parentElement;
- if (parent) {
- var bubble = new SearchBubble(text);
- bubble.attachTo(element);
- bubble.updatePosition();
- }
- },
-
- /**
- * Removes all search match bubbles.
- * @private
- */
- removeSearchBubbles_: function() {
- var elements = document.querySelectorAll('.search-bubble');
- var length = elements.length;
- for (var i = 0; i < length; i++)
- elements[i].dispose();
- },
-
- /**
- * Builds a list of top-level pages to search. Omits the search page and
- * all sub-pages.
- * @return {Array} An array of pages to search.
- * @private
- */
- getSearchablePages_: function() {
- var name, page, pages = [];
- for (name in PageManager.registeredPages) {
- if (name != this.name) {
- page = PageManager.registeredPages[name];
- if (!page.parentPage)
- pages.push(page);
- }
- }
- return pages;
- },
-
- /**
- * Builds a list of sub-pages (and overlay pages) to search. Ignore pages
- * that have no associated controls, or whose controls are hidden.
- * @return {Array} An array of pages to search.
- * @private
- */
- getSearchableSubPages_: function() {
- var name, pageInfo, page, pages = [];
- for (name in PageManager.registeredPages) {
- page = PageManager.registeredPages[name];
- if (page.parentPage &&
- page.associatedSection &&
- !page.associatedSection.hidden) {
- pages.push(page);
- }
- }
- for (name in PageManager.registeredOverlayPages) {
- page = PageManager.registeredOverlayPages[name];
- if (page.associatedSection &&
- !page.associatedSection.hidden &&
- page.pageDiv != undefined) {
- pages.push(page);
- }
- }
- return pages;
- },
-
- /**
- * A function to handle key press events.
- * @param {Event} event A keydown event.
- * @private
- */
- keyDownEventHandler_: function(event) {
- /** @const */ var ESCAPE_KEY_CODE = 27;
- /** @const */ var FORWARD_SLASH_KEY_CODE = 191;
-
- switch (event.keyCode) {
- case ESCAPE_KEY_CODE:
- if (event.target == this.searchField) {
- this.setSearchText_('');
- this.searchField.blur();
- event.stopPropagation();
- event.preventDefault();
- }
- break;
- case FORWARD_SLASH_KEY_CODE:
- if (!/INPUT|SELECT|BUTTON|TEXTAREA/.test(event.target.tagName) &&
- !event.ctrlKey && !event.altKey) {
- this.searchField.focus();
- event.stopPropagation();
- event.preventDefault();
- }
- break;
- }
- },
- };
-
- /**
- * Standardizes a user-entered text query by removing extra whitespace.
- * @param {string} text The user-entered text.
- * @return {string} The trimmed query.
- */
- SearchPage.canonicalizeQuery = function(text) {
- // Trim beginning and ending whitespace.
- return text.replace(/^\s+|\s+$/g, '');
- };
-
- // Export
- return {
- SearchPage: SearchPage
- };
-
-});
diff --git a/chromium/chrome/browser/resources/options/secondary_user_banner.html b/chromium/chrome/browser/resources/options/secondary_user_banner.html
deleted file mode 100644
index f609d07953d..00000000000
--- a/chromium/chrome/browser/resources/options/secondary_user_banner.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<div id="secondary-user-banner" class="settings-banner" hidden>
- <div class="content-area">
- <div class="badge"></div>
- <div class="text">
- <p>
- <span>$i18nRaw{secondaryUserBannerText}</span>
- </p>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/settings_dialog.js b/chromium/chrome/browser/resources/options/settings_dialog.js
deleted file mode 100644
index 01b2562de49..00000000000
--- a/chromium/chrome/browser/resources/options/settings_dialog.js
+++ /dev/null
@@ -1,71 +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.
-
-/**
- * @fileoverview Base class for dialogs that require saving preferences on
- * confirm and resetting preference inputs on cancel.
- */
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * Base class for settings dialogs.
- * @constructor
- * @param {string} name See Page constructor.
- * @param {string} title See Page constructor.
- * @param {string} pageDivName See Page constructor.
- * @param {HTMLButtonElement} okButton The confirmation button element.
- * @param {HTMLButtonElement} cancelButton The cancellation button element.
- * @extends {cr.ui.pageManager.Page}
- */
- function SettingsDialog(name, title, pageDivName, okButton, cancelButton) {
- Page.call(this, name, title, pageDivName);
- this.okButton = okButton;
- this.cancelButton = cancelButton;
- }
-
- SettingsDialog.prototype = {
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- this.okButton.onclick = this.handleConfirm.bind(this);
- this.cancelButton.onclick = this.handleCancel.bind(this);
- },
-
- /**
- * Handles the confirm button by saving the dialog preferences.
- */
- handleConfirm: function() {
- PageManager.closeOverlay();
-
- var prefs = Preferences.getInstance();
- var els = this.pageDiv.querySelectorAll('[dialog-pref]');
- for (var i = 0; i < els.length; i++) {
- if (els[i].pref)
- prefs.commitPref(els[i].pref, els[i].metric);
- }
- },
-
- /**
- * Handles the cancel button by closing the overlay.
- */
- handleCancel: function() {
- PageManager.closeOverlay();
-
- var prefs = Preferences.getInstance();
- var els = this.pageDiv.querySelectorAll('[dialog-pref]');
- for (var i = 0; i < els.length; i++) {
- if (els[i].pref)
- prefs.rollbackPref(els[i].pref);
- }
- },
- };
-
- return {
- SettingsDialog: SettingsDialog
- };
-});
diff --git a/chromium/chrome/browser/resources/options/spelling_confirm_overlay.css b/chromium/chrome/browser/resources/options/spelling_confirm_overlay.css
deleted file mode 100644
index ea3594b9386..00000000000
--- a/chromium/chrome/browser/resources/options/spelling_confirm_overlay.css
+++ /dev/null
@@ -1,7 +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. */
-
-#spelling-confirm-overlay {
- width: 500px;
-}
diff --git a/chromium/chrome/browser/resources/options/spelling_confirm_overlay.html b/chromium/chrome/browser/resources/options/spelling_confirm_overlay.html
deleted file mode 100644
index a8c977a0774..00000000000
--- a/chromium/chrome/browser/resources/options/spelling_confirm_overlay.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<div id="spelling-confirm-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{spellingConfirmOverlay}</h1>
- <div class="content-area">
- <span id="spelling-confirm-text">$i18n{spellingConfirmMessage}</span>
- <a id="spelling-confirm-learn-more" target="_blank"
- href="$i18nRaw{privacyLearnMoreURL}">$i18n{learnMore}</a>
- </div>
- <div class="action-area">
- <div class="button-strip">
- <button id="spelling-confirm-cancel">
- $i18n{spellingConfirmDisable}
- </button>
- <button id="spelling-confirm-ok" class="default-button">
- $i18n{spellingConfirmEnable}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/startup_overlay.css b/chromium/chrome/browser/resources/options/startup_overlay.css
deleted file mode 100644
index 322662c39e1..00000000000
--- a/chromium/chrome/browser/resources/options/startup_overlay.css
+++ /dev/null
@@ -1,45 +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. */
-
-#startup-overlay {
- min-width: 500px;
-}
-
-#startupPagesList {
- margin-bottom: 20px;
- min-height: 64px;
-}
-
-#startupPagesList .title {
- width: 40%;
-}
-
-#startupPagesList .url {
- -webkit-box-flex: 1;
- color: #666;
-}
-
-#startupPagesList > * {
- max-width: 700px;
-}
-
-#startupPagesList .url input {
- width: 100%;
-}
-
-#startupPagesListDropmarker {
- background-clip: padding-box;
- background-color: hsl(214, 91%, 65%);
- border: 2px solid hsl(214, 91%, 65%);
- border-bottom-color: transparent;
- border-radius: 0;
- border-top-color: transparent;
- box-sizing: border-box;
- display: none;
- height: 6px;
- overflow: hidden;
- pointer-events: none;
- position: fixed;
- z-index: 10;
-}
diff --git a/chromium/chrome/browser/resources/options/startup_overlay.html b/chromium/chrome/browser/resources/options/startup_overlay.html
deleted file mode 100644
index 7864b704944..00000000000
--- a/chromium/chrome/browser/resources/options/startup_overlay.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<div id="startup-overlay" class="page" hidden>
- <div class="close-button"></div>
- <h1>$i18n{startupPagesOverlay}</h1>
- <!-- This <input> element is always hidden. It needs to be here so that
- its 'controlled-by' attribute will get set when the urls preference is
- managed by a policy, so that the managed prefs bar will show up.
- -->
- <input type="text" pref="session.startup_urls" hidden>
- <div class="content-area">
- <list id="startupPagesList"></list>
- </div>
- <div class="action-area">
- <span class="hbox stretch">
- <button id="startupUseCurrentButton">$i18n{startupUseCurrent}</button>
- </span>
- <div class="button-strip">
- <button id="startup-overlay-cancel">$i18n{cancel}</button>
- <button id="startup-overlay-confirm" class="default-button">
- $i18n{ok}
- </button>
- </div>
- </div>
- <div id="startupPagesListDropmarker"></div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/startup_overlay.js b/chromium/chrome/browser/resources/options/startup_overlay.js
deleted file mode 100644
index 8d761fe5a95..00000000000
--- a/chromium/chrome/browser/resources/options/startup_overlay.js
+++ /dev/null
@@ -1,166 +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.
-
-cr.define('options', function() {
- /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
- /** @const */ var SettingsDialog = options.SettingsDialog;
-
- /**
- * StartupOverlay class
- * Encapsulated handling of the 'Set Startup pages' overlay page.
- * @constructor
- * @extends {options.SettingsDialog}
- */
- function StartupOverlay() {
- SettingsDialog.call(this, 'startup',
- loadTimeData.getString('startupPagesOverlayTabTitle'),
- 'startup-overlay',
- assertInstanceof($('startup-overlay-confirm'), HTMLButtonElement),
- assertInstanceof($('startup-overlay-cancel'), HTMLButtonElement));
- }
-
- cr.addSingletonGetter(StartupOverlay);
-
- StartupOverlay.prototype = {
- __proto__: SettingsDialog.prototype,
-
- /**
- * An autocomplete list that can be attached to a text field during editing.
- * @type {HTMLElement}
- * @private
- */
- autocompleteList_: null,
-
- startup_pages_pref_: {
- 'name': 'session.startup_urls',
- 'disabled': false
- },
-
- /** @override */
- initializePage: function() {
- SettingsDialog.prototype.initializePage.call(this);
-
- var self = this;
-
- var startupPagesList = $('startupPagesList');
- options.browser_options.StartupPageList.decorate(startupPagesList);
- startupPagesList.autoExpands = true;
-
- $('startupUseCurrentButton').onclick = function(event) {
- chrome.send('setStartupPagesToCurrentPages');
- };
-
- Preferences.getInstance().addEventListener(
- this.startup_pages_pref_.name,
- this.handleStartupPageListChange_.bind(this));
-
- var suggestionList = new cr.ui.AutocompleteList();
- suggestionList.autoExpands = true;
- suggestionList.requestSuggestions =
- this.requestAutocompleteSuggestions_.bind(this);
- $('startup-overlay').appendChild(suggestionList);
- this.autocompleteList_ = suggestionList;
- startupPagesList.autocompleteList = suggestionList;
- },
-
- /** @override */
- handleConfirm: function() {
- SettingsDialog.prototype.handleConfirm.call(this);
- chrome.send('commitStartupPrefChanges');
- // Set the startup behavior to "open specific set of pages" so that the
- // pages the user selected actually get opened on startup.
- Preferences.setIntegerPref('session.restore_on_startup', 4, true);
- },
-
- /** @override */
- handleCancel: function() {
- SettingsDialog.prototype.handleCancel.call(this);
- chrome.send('cancelStartupPrefChanges');
- },
-
- /**
- * Sets the enabled state of the custom startup page list
- * @param {boolean} disable True to disable, false to enable
- */
- setControlsDisabled: function(disable) {
- var startupPagesList = $('startupPagesList');
- startupPagesList.disabled = disable;
- // Explicitly set disabled state for input text elements.
- var inputs = startupPagesList.querySelectorAll("input[type='text']");
- for (var i = 0; i < inputs.length; i++)
- inputs[i].disabled = disable;
- $('startupUseCurrentButton').disabled = disable;
- },
-
- /**
- * Enables or disables the the custom startup page list controls
- * based on the whether the 'pages to restore on startup' pref is enabled.
- */
- updateControlStates: function() {
- this.setControlsDisabled(
- this.startup_pages_pref_.disabled);
- },
-
- /**
- * Handles change events of the preference
- * 'session.startup_urls'.
- * @param {Event} event Preference changed event.
- * @private
- */
- handleStartupPageListChange_: function(event) {
- this.startup_pages_pref_.disabled = event.value.disabled;
- this.updateControlStates();
- },
-
- /**
- * Updates the startup pages list with the given entries.
- * @param {!Array} pages List of startup pages.
- * @private
- */
- updateStartupPages_: function(pages) {
- var model = new ArrayDataModel(pages);
- // Add a "new page" row.
- model.push({modelIndex: -1});
- $('startupPagesList').dataModel = model;
- },
-
- /**
- * Sends an asynchronous request for new autocompletion suggestions for the
- * the given query. When new suggestions are available, the C++ handler will
- * call updateAutocompleteSuggestions_.
- * @param {string} query List of autocomplete suggestions.
- * @private
- */
- requestAutocompleteSuggestions_: function(query) {
- chrome.send('requestAutocompleteSuggestionsForStartupPages', [query]);
- },
-
- /**
- * Updates the autocomplete suggestion list with the given entries.
- * @param {Array} suggestions List of autocomplete suggestions.
- * @private
- */
- updateAutocompleteSuggestions_: function(suggestions) {
- var list = this.autocompleteList_;
- // If the trigger for this update was a value being selected from the
- // current list, do nothing.
- if (list.targetInput && list.selectedItem &&
- list.selectedItem.url == list.targetInput.value) {
- return;
- }
- list.suggestions = suggestions;
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(StartupOverlay, [
- 'updateStartupPages',
- 'updateAutocompleteSuggestions',
- ]);
-
- // Export
- return {
- StartupOverlay: StartupOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/startup_section.html b/chromium/chrome/browser/resources/options/startup_section.html
deleted file mode 100644
index 764f63a42ff..00000000000
--- a/chromium/chrome/browser/resources/options/startup_section.html
+++ /dev/null
@@ -1,45 +0,0 @@
-<section id="startup-section" guest-visibility="hidden">
- <h3>$i18n{sectionTitleStartup}</h3>
- <div id="startup-section-content">
- <div class="radio controlled-setting-with-label"
- id="newtab-section-content">
- <label>
- <input type="radio" name="startup" value="5"
- pref="session.restore_on_startup"
- metric="Options_Startup_NewTab">
- <span>
- <span>$i18n{startupShowNewTab}</span>
- <span class="controlled-setting-indicator"
- pref="session.restore_on_startup" value="5"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input id="startup-restore-session" type="radio" name="startup"
- value="1" pref="session.restore_on_startup"
- metric="Options_Startup_LastSession">
- <span>
- <span>$i18n{startupRestoreLastSession}</span>
- <span class="controlled-setting-indicator"
- pref="session.restore_on_startup" value="1"></span>
- </span>
- </label>
- </div>
- <div class="radio controlled-setting-with-label">
- <label>
- <input id="startup-show-pages" type="radio" name="startup"
- pref="session.restore_on_startup"
- value="4" metric="Options_Startup_Custom">
- <span>
- <span>$i18n{startupShowPages}</span>
- <span class="controlled-setting-indicator"
- pref="session.restore_on_startup" value="4"></span>
- </span>
- </label>
- <a is="action-link" id="startup-set-pages">$i18n{startupSetPages}</a>
- <span class="controlled-setting-indicator"
- pref="session.startup_urls"></span>
- </div>
- </div>
-</section>
diff --git a/chromium/chrome/browser/resources/options/subpages_tab_controls.css b/chromium/chrome/browser/resources/options/subpages_tab_controls.css
deleted file mode 100644
index 5ab21c3c037..00000000000
--- a/chromium/chrome/browser/resources/options/subpages_tab_controls.css
+++ /dev/null
@@ -1,70 +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. */
-
-.subpages-nav-tabs .tab {
- padding: 4px 8px;
- position: relative;
-}
-
-.subpages-nav-tabs .active-tab {
- background: white;
- border: 1px solid #ddd;
- border-bottom: 2px solid white;
- border-top-left-radius: 3px;
- border-top-right-radius: 3px;
- box-shadow: 8px -8px 12px -6px rgb(240, 240, 240);
- position: relative;
-}
-
-/* To avoid tabs changing size when they are clicked and their labels become
- * bold, we actually put two labels inside each tab: an inactive label and an
- * active label. Only one is visible at a time, but the bold label is used to
- * size the tab even when it's not visible. This keeps the tab size constant. */
-.subpages-nav-tabs .active-tab-label,
-.subpages-nav-tabs .tab-label:hover {
- font-weight: bold;
-}
-
-.subpages-nav-tabs .tab-label {
- left: 9px;
- position: absolute;
- top: 5px;
-}
-
-html[dir=rtl] .subpages-nav-tabs .tab-label {
- right: 9px;
-}
-
-.subpages-nav-tabs .active-tab-label,
-.subpages-nav-tabs .active-tab .tab-label {
- visibility: hidden;
-}
-
-/* .tab is not removed when .active-tab is added, so we must override the hidden
- * visibility above in the active tab case. */
-.subpages-nav-tabs .active-tab .active-tab-label {
- visibility: visible;
-}
-
-.subpages-nav-tabs {
- background-image: linear-gradient(
- to bottom,
- rgb(255,255,255),
- rgb(255,255,255) 60%,
- rgb(250, 250, 250) 80%,
- rgb(242,242,242)
- );
- border-bottom: 1px solid #ddd;
- padding: 4px 20px;
-}
-
-.subpages-tab-contents {
- -webkit-padding-start: 10px;
- display: none;
- padding-top: 15px;
-}
-
-.active-tab-contents {
- display: block;
-}
diff --git a/chromium/chrome/browser/resources/options/supervised_user_create_confirm.css b/chromium/chrome/browser/resources/options/supervised_user_create_confirm.css
deleted file mode 100644
index 828448a8622..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_create_confirm.css
+++ /dev/null
@@ -1,46 +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. */
-
-#supervised-user-created {
- width: 722px;
-}
-
-#supervised-user-created-title {
- padding: 20px;
- word-wrap: break-word;
-}
-
-@media only screen and (max-height:400px) {
-
-/* Omit the image on very small screens. */
-#supervised-user-created-image {
- display: none;
-}
-
-} /* @media only screen and (max-height:400px) */
-
-#supervised-user-created-image {
- background-image: -webkit-image-set(
- url(../../../../ui/resources/default_100_percent/supervised_illustration_done.png) 1x,
- url(../../../../ui/resources/default_200_percent/supervised_illustration_done.png) 2x);
- background-position: center;
- border-radius: 3px 3px 0 0;
- flex: 5;
- height: 344px;
-}
-
-#supervised-user-created-text {
- padding: 0 20px 0 20px;
- white-space: pre-wrap;
- word-wrap: break-word;
-}
-
-#supervised-user-created-switch {
- max-width: 600px;
- word-wrap: break-word;
-}
-
-#supervised-user-created-action-area {
- padding: 20px;
-}
diff --git a/chromium/chrome/browser/resources/options/supervised_user_create_confirm.html b/chromium/chrome/browser/resources/options/supervised_user_create_confirm.html
deleted file mode 100644
index ae4076ab678..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_create_confirm.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<div id="supervised-user-created" class="page" hidden>
- <div class="close-button"></div>
- <!-- Overlay for the confirmation after creating a supervised user. -->
- <div id="supervised-user-created-image"></div>
- <h1 id="supervised-user-created-title"></h1>
- <div id="supervised-user-created-text" class="content-area"></div>
- <div id="supervised-user-created-action-area"
- class="action-area button-strip">
- <button id="supervised-user-created-done">
- $i18n{supervisedUserCreatedDone}
- </button>
- <button id="supervised-user-created-switch"></button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/supervised_user_create_confirm.js b/chromium/chrome/browser/resources/options/supervised_user_create_confirm.js
deleted file mode 100644
index cd3274b790d..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_create_confirm.js
+++ /dev/null
@@ -1,128 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * SupervisedUserCreateConfirm class.
- * Encapsulated handling of the confirmation overlay page when creating a
- * supervised user.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function SupervisedUserCreateConfirmOverlay() {
- Page.call(this, 'supervisedUserCreateConfirm',
- '', // The title will be based on the new profile name.
- 'supervised-user-created');
- }
-
- cr.addSingletonGetter(SupervisedUserCreateConfirmOverlay);
-
- SupervisedUserCreateConfirmOverlay.prototype = {
- // Inherit from Page.
- __proto__: Page.prototype,
-
- // Info about the newly created profile.
- profileInfo_: null,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('supervised-user-created-done').onclick = function(event) {
- PageManager.closeOverlay();
- };
-
- var self = this;
-
- $('supervised-user-created-switch').onclick = function(event) {
- PageManager.closeOverlay();
- chrome.send('switchToProfile', [self.profileInfo_.filePath]);
- };
- },
-
- /** @override */
- didShowPage: function() {
- $('supervised-user-created-switch').focus();
- },
-
- /**
- * Sets the profile info used in the dialog and updates the profile name
- * displayed. Called by the profile creation overlay when this overlay is
- * opened.
- * @param {Object} info An object of the form:
- * info = {
- * name: "Profile Name",
- * filePath: "/path/to/profile/data/on/disk",
- * isSupervised: (true|false)
- * custodianEmail: "example@gmail.com"
- * };
- * @private
- */
- setProfileInfo_: function(info) {
- this.profileInfo_ = info;
- var MAX_LENGTH = 50;
- var elidedName = elide(info.name, MAX_LENGTH);
- $('supervised-user-created-title').textContent =
- loadTimeData.getStringF('supervisedUserCreatedTitle', elidedName);
- $('supervised-user-created-switch').textContent =
- loadTimeData.getStringF('supervisedUserCreatedSwitch', elidedName);
-
- // HTML-escape the user-supplied strings before putting them into
- // innerHTML. This is probably excessive for the email address, but
- // belt-and-suspenders is cheap here.
- $('supervised-user-created-text').innerHTML =
- loadTimeData.getStringF('supervisedUserCreatedText',
- HTMLEscape(elidedName),
- HTMLEscape(elide(info.custodianEmail,
- MAX_LENGTH)));
- },
-
- /** @override */
- canShowPage: function() {
- return this.profileInfo_ != null;
- },
-
- /**
- * Updates the displayed profile name if it has changed. Called by the
- * handler.
- * @param {string} filePath The file path of the profile whose name
- * changed.
- * @param {string} newName The changed profile's new name.
- * @private
- */
- onUpdatedProfileName_: function(filePath, newName) {
- if (filePath == this.profileInfo_.filePath) {
- this.profileInfo_.name = newName;
- this.setProfileInfo_(this.profileInfo_);
- }
- },
-
- /**
- * Closes this overlay if the new profile has been deleted. Called by the
- * handler.
- * @param {string} filePath The file path of the profile that was deleted.
- * @private
- */
- onDeletedProfile_: function(filePath) {
- if (filePath == this.profileInfo_.filePath) {
- PageManager.closeOverlay();
- }
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(SupervisedUserCreateConfirmOverlay, [
- 'onDeletedProfile',
- 'onUpdatedProfileName',
- 'setProfileInfo',
- ]);
-
- // Export
- return {
- SupervisedUserCreateConfirmOverlay: SupervisedUserCreateConfirmOverlay,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/supervised_user_import.css b/chromium/chrome/browser/resources/options/supervised_user_import.css
deleted file mode 100644
index af4b8c45a04..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_import.css
+++ /dev/null
@@ -1,84 +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. */
-
-#supervised-user-import {
- width: 612px;
-}
-
-#supervised-user-import-text,
-#supervised-user-select-avatar-text {
- padding-bottom: 10px;
- padding-left: 17px;
- white-space: pre-wrap;
- word-wrap: break-word;
-}
-
-#supervised-user-list {
- height: 240px;
- margin-bottom: 10px;
-}
-
-#supervised-user-list .list-item {
- align-items: center;
- display: flex;
-}
-
-#supervised-user-list .profile-img {
- flex-shrink: 0;
-}
-
-#supervised-user-list .profile-name {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-#supervised-user-list .already-on-this-device {
- flex-shrink: 0;
-}
-
-#supervised-user-list > * {
- height: 40px;
-}
-
-#supervised-user-list:focus {
- border-color: rgb(77, 144, 254);
-}
-
-#select-avatar-grid {
- background-color: rgba(255, 255, 255, 0.75);
- padding: 2px;
-}
-
-#supervised-user-import-error-bubble {
- background-color: rgb(238, 185, 57);
- border-radius: 4px;
- font-weight: bold;
- margin-left: auto;
- margin-right: auto;
- margin-top: 10px;
- max-height: 50px;
- overflow: hidden;
- padding: 1px 10px;
- text-align: center;
- transition: max-height 200ms, padding 200ms;
- width: 80%;
-}
-
-#supervised-user-import-error-bubble[hidden] {
- max-height: 0;
-}
-
-.profile-img-disabled {
- opacity: 0.4;
-}
-
-.profile-name-disabled {
- color: rgb(153, 153, 153);
-}
-
-.already-on-this-device {
- padding-left: 20px;
- padding-right: 6px;
-}
diff --git a/chromium/chrome/browser/resources/options/supervised_user_import.html b/chromium/chrome/browser/resources/options/supervised_user_import.html
deleted file mode 100644
index 9fd806d9a44..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_import.html
+++ /dev/null
@@ -1,40 +0,0 @@
-<div id="supervised-user-import" class="page" hidden>
- <div class="close-button"></div>
- <!-- Overlay to import an existing supervised user during user creation -->
- <h1 id="supervised-user-import-title" class="supervised-user-import">
- $i18n{supervisedUserImportTitle}
- </h1>
- <h1 id="supervised-user-select-avatar-title"
- class="supervised-user-select-avatar" hidden>
- $i18n{supervisedUserSelectAvatarTitle}
- </h1>
- <div id="supervised-user-import-text" class="supervised-user-import">
- $i18n{supervisedUserImportText}
- </div>
- <div id="supervised-user-select-avatar-text"
- class="supervised-user-select-avatar" hidden>
- $i18n{supervisedUserSelectAvatarText}
- </div>
- <div id="supervised-user-import-content-area" class="content-area">
- <list id="supervised-user-list"
- class="settings-list supervised-user-import">
- </list>
- <grid id="select-avatar-grid" class="supervised-user-select-avatar" hidden>
- </grid>
- </div>
- <div id="supervised-user-import-error-bubble" hidden></div>
- <div id="supervised-user-import-action-area" class="action-area">
- <div class="button-strip">
- <div id="supervised-user-import-throbber" class="throbber"></div>
- <button id="supervised-user-import-cancel">$i18n{cancel}</button>
- <button id="supervised-user-import-ok"
- class="default-button supervised-user-import">
- $i18n{supervisedUserImportOk}
- </button>
- <button id="supervised-user-select-avatar-ok"
- class="default-button supervised-user-select-avatar" hidden>
- $i18n{supervisedUserSelectAvatarOk}
- </button>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/supervised_user_import.js b/chromium/chrome/browser/resources/options/supervised_user_import.js
deleted file mode 100644
index ea97b42b25f..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_import.js
+++ /dev/null
@@ -1,252 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
- var PageManager = cr.ui.pageManager.PageManager;
- var ArrayDataModel = cr.ui.ArrayDataModel;
-
- /**
- * SupervisedUserImportOverlay class.
- * Encapsulated handling of the 'Import existing supervised user' overlay
- * page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function SupervisedUserImportOverlay() {
- var title = loadTimeData.getString('supervisedUserImportTitle');
- Page.call(this, 'supervisedUserImport', title, 'supervised-user-import');
- }
-
- cr.addSingletonGetter(SupervisedUserImportOverlay);
-
- SupervisedUserImportOverlay.prototype = {
- // Inherit from Page.
- __proto__: Page.prototype,
-
- /** @override */
- canShowPage: function() {
- return !BrowserOptions.getCurrentProfile().isSupervised;
- },
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var supervisedUserList = $('supervised-user-list');
- options.supervisedUserOptions.SupervisedUserList.decorate(
- supervisedUserList);
-
- var avatarGrid = $('select-avatar-grid');
- options.ProfilesIconGrid.decorate(avatarGrid);
- var avatarIcons = loadTimeData.getValue('avatarIcons');
- avatarGrid.dataModel = new ArrayDataModel(
- /** @type {!Array} */(avatarIcons));
-
- supervisedUserList.addEventListener('change', function(event) {
- var supervisedUser = supervisedUserList.selectedItem;
- $('supervised-user-import-ok').disabled =
- !supervisedUser || supervisedUser.onCurrentDevice;
- });
-
- var self = this;
- $('supervised-user-import-cancel').onclick = function(event) {
- if (self.inProgress_) {
- self.updateImportInProgress_(false);
-
- // 'cancelCreateProfile' is handled by CreateProfileHandler.
- chrome.send('cancelCreateProfile');
- }
- PageManager.closeOverlay();
- };
-
- $('supervised-user-import-ok').onclick =
- this.showAvatarGridOrSubmit_.bind(this);
- $('supervised-user-select-avatar-ok').onclick =
- this.showAvatarGridOrSubmit_.bind(this);
- },
-
- /**
- * @override
- */
- didShowPage: function() {
- // When the import link is clicked to open this overlay, it is hidden in
- // order to trigger a cursor update. We can show the import link again
- // now. TODO(akuegel): Remove this temporary fix when crbug/246304 is
- // resolved.
- $('import-existing-supervised-user-link').hidden = false;
-
- options.SupervisedUserListData.requestExistingSupervisedUsers().then(
- this.receiveExistingSupervisedUsers_.bind(this),
- this.onSigninError_.bind(this));
- options.SupervisedUserListData.addObserver(this);
-
- this.updateImportInProgress_(false);
- $('supervised-user-import-error-bubble').hidden = true;
- $('supervised-user-import-ok').disabled = true;
- this.showAppropriateElements_(/* isSelectAvatarMode */ false);
- },
-
- /**
- * @override
- */
- didClosePage: function() {
- options.SupervisedUserListData.removeObserver(this);
- },
-
- /**
- * Shows either the supervised user import dom elements or the select avatar
- * dom elements.
- * @param {boolean} isSelectAvatarMode True if the overlay should show the
- * select avatar grid, and false if the overlay should show the
- * supervised user list.
- * @private
- */
- showAppropriateElements_: function(isSelectAvatarMode) {
- var avatarElements =
- this.pageDiv.querySelectorAll('.supervised-user-select-avatar');
- for (var i = 0; i < avatarElements.length; i++)
- avatarElements[i].hidden = !isSelectAvatarMode;
- var importElements =
- this.pageDiv.querySelectorAll('.supervised-user-import');
- for (var i = 0; i < importElements.length; i++)
- importElements[i].hidden = isSelectAvatarMode;
- },
-
- /**
- * Called when the user clicks the "OK" button. In case the supervised
- * user being imported has no avatar in sync, it shows the avatar
- * icon grid. In case the avatar grid is visible or the supervised user
- * already has an avatar stored in sync, it proceeds with importing
- * the supervised user.
- * @private
- */
- showAvatarGridOrSubmit_: function() {
- var supervisedUser = $('supervised-user-list').selectedItem;
- if (!supervisedUser)
- return;
-
- $('supervised-user-import-error-bubble').hidden = true;
-
- if ($('select-avatar-grid').hidden && supervisedUser.needAvatar) {
- this.showAvatarGridHelper_();
- return;
- }
-
- var avatarUrl = supervisedUser.needAvatar ?
- $('select-avatar-grid').selectedItem : supervisedUser.iconURL;
-
- this.updateImportInProgress_(true);
-
- // 'createProfile' is handled by CreateProfileHandler.
- chrome.send('createProfile', [supervisedUser.name, avatarUrl,
- false, true, supervisedUser.id]);
- },
-
- /**
- * Hides the 'supervised user list' and shows the avatar grid instead.
- * It also updates the overlay text and title to instruct the user
- * to choose an avatar for the supervised user.
- * @private
- */
- showAvatarGridHelper_: function() {
- this.showAppropriateElements_(/* isSelectAvatarMode */ true);
- $('select-avatar-grid').redraw();
- $('select-avatar-grid').selectedItem =
- loadTimeData.getValue('avatarIcons')[0];
- },
-
- /**
- * Updates the UI according to the importing state.
- * @param {boolean} inProgress True to indicate that
- * importing is in progress and false otherwise.
- * @private
- */
- updateImportInProgress_: function(inProgress) {
- this.inProgress_ = inProgress;
- $('supervised-user-import-ok').disabled = inProgress;
- $('supervised-user-select-avatar-ok').disabled = inProgress;
- $('supervised-user-list').disabled = inProgress;
- $('select-avatar-grid').disabled = inProgress;
- $('supervised-user-import-throbber').hidden = !inProgress;
- },
-
- /**
- * Sets the data model of the supervised user list to |supervisedUsers|.
- * @param {Array<{id: string, name: string, iconURL: string,
- * onCurrentDevice: boolean, needAvatar: boolean}>} supervisedUsers
- * Array of supervised user objects.
- * @private
- */
- receiveExistingSupervisedUsers_: function(supervisedUsers) {
- supervisedUsers.sort(function(a, b) {
- if (a.onCurrentDevice != b.onCurrentDevice)
- return a.onCurrentDevice ? 1 : -1;
- return a.name.localeCompare(b.name);
- });
-
- $('supervised-user-list').dataModel = new ArrayDataModel(supervisedUsers);
- if (supervisedUsers.length == 0) {
- this.onErrorInternal_(
- loadTimeData.getString('noExistingSupervisedUsers'));
- $('supervised-user-import-ok').disabled = true;
- } else {
- // Hide the error bubble.
- $('supervised-user-import-error-bubble').hidden = true;
- }
- },
-
- onSigninError_: function() {
- $('supervised-user-list').dataModel = null;
- this.onErrorInternal_(
- loadTimeData.getString('supervisedUserImportSigninError'));
- },
-
- /**
- * Displays an error message if an error occurs while
- * importing a supervised user.
- * Called by BrowserOptions via the BrowserOptionsHandler.
- * @param {string} error The error message to display.
- * @private
- */
- onError_: function(error) {
- this.onErrorInternal_(error);
- this.updateImportInProgress_(false);
- },
-
- /**
- * Displays an error message.
- * @param {string} error The error message to display.
- * @private
- */
- onErrorInternal_: function(error) {
- var errorBubble = $('supervised-user-import-error-bubble');
- errorBubble.hidden = false;
- errorBubble.textContent = error;
- },
-
- /**
- * Closes the overlay if importing the supervised user was successful. Also
- * reset the cached list of supervised users in order to get an updated list
- * when the overlay is reopened.
- * @private
- */
- onSuccess_: function() {
- this.updateImportInProgress_(false);
- options.SupervisedUserListData.resetPromise();
- PageManager.closeAllOverlays();
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(SupervisedUserImportOverlay, [
- 'onError',
- 'onSuccess',
- ]);
-
- // Export
- return {
- SupervisedUserImportOverlay: SupervisedUserImportOverlay,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/supervised_user_learn_more.css b/chromium/chrome/browser/resources/options/supervised_user_learn_more.css
deleted file mode 100644
index e54d68b89a3..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_learn_more.css
+++ /dev/null
@@ -1,41 +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. */
-
-#supervised-user-learn-more {
- display: flex;
- flex-direction: column;
- width: 722px;
-}
-
-#supervised-user-learn-more-title {
- padding: 20px;
-}
-
-#supervised-user-learn-more-text {
- padding: 0 20px 0 20px;
- white-space: pre-wrap;
- word-wrap: break-word;
-}
-
-@media only screen and (max-height:500px) {
-
-/* Omit the image on very small screens. */
-#supervised-user-learn-more-image {
- display: none;
-}
-
-} /* @media only screen and (max-height:500px) */
-
-#supervised-user-learn-more-image {
- background-image: -webkit-image-set(
- url(../../../../ui/resources/default_100_percent/supervised_illustration_start.png) 1x,
- url(../../../../ui/resources/default_200_percent/supervised_illustration_start.png) 2x);
- background-position: center;
- border-radius: 3px 3px 0 0;
- height: 344px;
-}
-
-#supervised-user-learn-more-action-area {
- padding: 20px;
-}
diff --git a/chromium/chrome/browser/resources/options/supervised_user_learn_more.html b/chromium/chrome/browser/resources/options/supervised_user_learn_more.html
deleted file mode 100644
index 651cfb5e52c..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_learn_more.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<div id="supervised-user-learn-more" class="page" hidden>
- <div class="close-button"></div>
- <!-- Overlay for the 'Learn more' link when creating a supervised user. -->
- <div id="supervised-user-learn-more-image"></div>
- <h1 id="supervised-user-learn-more-title"
- i18n-content="supervisedUserLearnMoreTitle">
- </h1>
- <div id="supervised-user-learn-more-text" class="content-area"
- i18n-values=".innerHTML:supervisedUserLearnMoreText">
- </div>
- <div id="supervised-user-learn-more-action-area"
- class="action-area button-strip">
- <button id="supervised-user-learn-more-done"
- i18n-content="supervisedUserLearnMoreDone">
- </button>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/supervised_user_learn_more.js b/chromium/chrome/browser/resources/options/supervised_user_learn_more.js
deleted file mode 100644
index da7975e4061..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_learn_more.js
+++ /dev/null
@@ -1,40 +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.
-
-cr.define('options', function() {
- var Page = cr.ui.pageManager.Page;
-
- /**
- * SupervisedUserLearnMore class.
- * Encapsulated handling of the 'Learn more...' overlay page.
- * @constructor
- * @extends {cr.ui.pageManager.Page}
- */
- function SupervisedUserLearnMoreOverlay() {
- Page.call(this, 'supervisedUserLearnMore',
- loadTimeData.getString('supervisedUserLearnMoreTitle'),
- 'supervised-user-learn-more');
- }
-
- cr.addSingletonGetter(SupervisedUserLearnMoreOverlay);
-
- SupervisedUserLearnMoreOverlay.prototype = {
- // Inherit from Page.
- __proto__: Page.prototype,
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- $('supervised-user-learn-more-done').onclick = function(event) {
- cr.ui.pageManager.PageManager.closeOverlay();
- };
- },
- };
-
- // Export
- return {
- SupervisedUserLearnMoreOverlay: SupervisedUserLearnMoreOverlay,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/supervised_user_list.js b/chromium/chrome/browser/resources/options/supervised_user_list.js
deleted file mode 100644
index ca4a47975ec..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_list.js
+++ /dev/null
@@ -1,120 +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.
-
-cr.define('options.supervisedUserOptions', function() {
- /** @const */ var List = cr.ui.List;
- /** @const */ var ListItem = cr.ui.ListItem;
- /** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel;
-
- /**
- * Create a new supervised user list item.
- * @param {Object} entry The supervised user this item represents.
- * It has the following form:
- * supervisedUser = {
- * id: "Supervised User ID",
- * name: "Supervised User Name",
- * iconURL: "chrome://path/to/icon/image",
- * onCurrentDevice: true or false,
- * needAvatar: true or false
- * }
- * @constructor
- * @extends {cr.ui.ListItem}
- */
- function SupervisedUserListItem(entry) {
- var el = cr.doc.createElement('div');
- el.className = 'list-item';
- el.supervisedUser_ = entry;
- el.__proto__ = SupervisedUserListItem.prototype;
- el.decorate();
- return el;
- }
-
- SupervisedUserListItem.prototype = {
- __proto__: ListItem.prototype,
-
- /**
- * @type {string} the ID of this supervised user list item.
- */
- get id() {
- return this.supervisedUser_.id;
- },
-
- /**
- * @type {string} the name of this supervised user list item.
- */
- get name() {
- return this.supervisedUser_.name;
- },
-
- /**
- * @type {string} the path to the avatar icon of this supervised
- * user list item.
- */
- get iconURL() {
- return this.supervisedUser_.iconURL;
- },
-
- /** @override */
- decorate: function() {
- ListItem.prototype.decorate.call(this);
- var supervisedUser = this.supervisedUser_;
-
- // Add the avatar.
- var iconElement = this.ownerDocument.createElement('img');
- iconElement.className = 'profile-img';
- iconElement.style.content = cr.icon.getImage(supervisedUser.iconURL);
- this.appendChild(iconElement);
-
- // Add the profile name.
- var nameElement = this.ownerDocument.createElement('div');
- nameElement.className = 'profile-name';
- nameElement.textContent = supervisedUser.name;
- this.appendChild(nameElement);
-
- if (supervisedUser.onCurrentDevice) {
- iconElement.className += ' profile-img-disabled';
- nameElement.className += ' profile-name-disabled';
-
- // Add "(already on this device)" message.
- var alreadyOnDeviceElement = this.ownerDocument.createElement('div');
- alreadyOnDeviceElement.className =
- 'profile-name-disabled already-on-this-device';
- alreadyOnDeviceElement.textContent =
- loadTimeData.getString('supervisedUserAlreadyOnThisDevice');
- this.appendChild(alreadyOnDeviceElement);
- }
- },
- };
-
- /**
- * Create a new supervised users list.
- * @constructor
- * @extends {cr.ui.List}
- */
- var SupervisedUserList = cr.ui.define('list');
-
- SupervisedUserList.prototype = {
- __proto__: List.prototype,
-
- /**
- * @override
- * @param {Object} entry
- */
- createItem: function(entry) {
- return new SupervisedUserListItem(entry);
- },
-
- /** @override */
- decorate: function() {
- List.prototype.decorate.call(this);
- this.selectionModel = new ListSingleSelectionModel();
- this.autoExpands = true;
- },
- };
-
- return {
- SupervisedUserListItem: SupervisedUserListItem,
- SupervisedUserList: SupervisedUserList,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/supervised_user_list_data.js b/chromium/chrome/browser/resources/options/supervised_user_list_data.js
deleted file mode 100644
index 78967ca3e8a..00000000000
--- a/chromium/chrome/browser/resources/options/supervised_user_list_data.js
+++ /dev/null
@@ -1,150 +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.
-
-cr.define('options', function() {
- /**
- * SupervisedUserListData class.
- * Handles requests for retrieving a list of existing supervised users which
- * are supervised by the current profile. For each request a promise is
- * returned, which is cached in order to reuse the retrieved supervised users
- * for future requests. The first request will be handled asynchronously.
- * @constructor
- * @class
- */
- function SupervisedUserListData() {
- this.observers_ = [];
- }
-
- cr.addSingletonGetter(SupervisedUserListData);
-
- /**
- * Receives a list of supervised users and resolves the promise.
- * @param {Array<Object>} supervisedUsers Array of supervised user objects.
- * Each object is of the form:
- * supervisedUser = {
- * id: "Supervised User ID",
- * name: "Supervised User Name",
- * iconURL: "chrome://path/to/icon/image",
- * onCurrentDevice: true or false,
- * needAvatar: true or false
- * }
- * @private
- */
- SupervisedUserListData.prototype.receiveExistingSupervisedUsers_ =
- function(supervisedUsers) {
- if (!this.promise_) {
- this.onDataChanged_(supervisedUsers);
- return;
- }
- this.resolve_(supervisedUsers);
- };
-
- /**
- * Called when there is a signin error when retrieving the list of supervised
- * users. Rejects the promise and resets the cached promise to null.
- * @private
- */
- SupervisedUserListData.prototype.onSigninError_ = function() {
- if (!this.promise_) {
- return;
- }
- this.reject_();
- this.resetPromise_();
- };
-
- /**
- * Handles the request for the list of existing supervised users by returning
- * a promise for the requested data. If there is no cached promise yet, a new
- * one will be created.
- * @return {Promise} The promise containing the list of supervised users.
- * @private
- */
- SupervisedUserListData.prototype.requestExistingSupervisedUsers_ =
- function() {
- if (this.promise_)
- return this.promise_;
- this.promise_ = this.createPromise_();
- chrome.send('requestSupervisedUserImportUpdate');
- return this.promise_;
- };
-
- /**
- * Creates the promise containing the list of supervised users. The promise is
- * resolved in receiveExistingSupervisedUsers_() or rejected in
- * onSigninError_(). The promise is cached, so that for future requests it can
- * be resolved immediately.
- * @return {Promise} The promise containing the list of supervised users.
- * @private
- */
- SupervisedUserListData.prototype.createPromise_ = function() {
- var self = this;
- return new Promise(function(resolve, reject) {
- self.resolve_ = resolve;
- self.reject_ = reject;
- });
- };
-
- /**
- * Resets the promise to null in order to avoid stale data. For the next
- * request, a new promise will be created.
- * @private
- */
- SupervisedUserListData.prototype.resetPromise_ = function() {
- this.promise_ = null;
- };
-
- /**
- * Initializes |promise| with the new data and also passes the new data to
- * observers.
- * @param {Array<Object>} supervisedUsers Array of supervised user objects.
- * For the format of the objects, see receiveExistingSupervisedUsers_().
- * @private
- */
- SupervisedUserListData.prototype.onDataChanged_ = function(supervisedUsers) {
- this.promise_ = this.createPromise_();
- this.resolve_(supervisedUsers);
- for (var i = 0; i < this.observers_.length; ++i)
- this.observers_[i].receiveExistingSupervisedUsers_(supervisedUsers);
- };
-
- /**
- * Adds an observer to the list of observers.
- * @param {Object} observer The observer to be added.
- * @private
- */
- SupervisedUserListData.prototype.addObserver_ = function(observer) {
- for (var i = 0; i < this.observers_.length; ++i)
- assert(this.observers_[i] != observer);
- this.observers_.push(observer);
- };
-
- /**
- * Removes an observer from the list of observers.
- * @param {Object} observer The observer to be removed.
- * @private
- */
- SupervisedUserListData.prototype.removeObserver_ = function(observer) {
- for (var i = 0; i < this.observers_.length; ++i) {
- if (this.observers_[i] == observer) {
- this.observers_.splice(i, 1);
- return;
- }
- }
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(SupervisedUserListData, [
- 'addObserver',
- 'onSigninError',
- 'receiveExistingSupervisedUsers',
- 'removeObserver',
- 'requestExistingSupervisedUsers',
- 'resetPromise',
- ]);
-
- // Export
- return {
- SupervisedUserListData: SupervisedUserListData,
- };
-});
diff --git a/chromium/chrome/browser/resources/options/sync_section.html b/chromium/chrome/browser/resources/options/sync_section.html
deleted file mode 100644
index 375601e2235..00000000000
--- a/chromium/chrome/browser/resources/options/sync_section.html
+++ /dev/null
@@ -1,74 +0,0 @@
-<if expr="not chromeos">
-<section id="sync-section">
- <h3>$i18n{sectionTitleSync}</h3>
-</if>
-<if expr="chromeos">
-<div id="sync-section">
-</if>
-
- <div id="sync-overview" class="settings-row" hidden>
- <p>$i18n{syncOverview}</p>
- <a href="$i18nRaw{syncLearnMoreURL}" target="_blank">$i18n{learnMore}</a>
- </div>
-
-<if expr="chromeos">
- <div id="account-picture-wrapper">
- <div id="account-picture-control">
- <input type="image" id="account-picture" tabindex="0" alt=""
- aria-label="$i18n{changePicture}">
- <div id="change-picture-caption">$i18n{changePicture}</div>
- </div>
- <span id="account-picture-indicator" class="controlled-setting-indicator">
- </span>
- </div>
- <div id="sync-general">
-</if> <!-- chromeos -->
-
- <div id="sync-status" class="settings-row" hidden>
- <span id="account-info" hidden></span>
- <span id="sync-status-text"></span>
- <a is="action-link" id="sync-action-link"></a>
- </div>
-
-<if expr="chromeos">
- <div class="checkbox controlled-setting-with-label"
- public-account-visibility="hidden">
- <label>
- <input type="checkbox"
- metric="Options_ScreenLock"
- pref="settings.enable_screen_lock">
- <span>
- <span>$i18n{enableScreenlock}</span>
- <span class="controlled-setting-indicator"
- textshared="$i18n{screenLockShared}"
- pref="settings.enable_screen_lock"></span>
- </span>
- </label>
- <a is="action-link" id="manage-screenlock" hidden>
- $i18n{manageScreenlock}
- </a>
- </div>
- </div>
-</if> <!-- chromeos -->
-
- <div id="sync-buttons" class="settings-row">
- <button id="start-stop-sync" hidden></button>
- <span id="start-stop-sync-indicator"
- class="controlled-setting-indicator" hidden>
- </span>
- <button id="customize-sync" pref="sync.managed" hidden>
- $i18n{customizeSync}
- </button>
-<if expr="chromeos">
- <button id="manage-accounts-button" public-account-visibility="hidden">
- $i18n{manageAccountsButtonTitle}
- </button>
-</if> <!-- chromeos -->
- </div>
-
-<if expr="not chromeos">
-</section>
-</if>
-<if expr="chromeos">
-</div>
-</if>
diff --git a/chromium/chrome/browser/resources/options/sync_setup_overlay.css b/chromium/chrome/browser/resources/options/sync_setup_overlay.css
deleted file mode 100644
index 9d18c7ba842..00000000000
--- a/chromium/chrome/browser/resources/options/sync_setup_overlay.css
+++ /dev/null
@@ -1,215 +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. */
-
-/* TODO(jhawkins): Organize these by page. */
-
-#sync-setup-overlay * h4 {
- margin: 15px 0 5px;
-}
-
-#sync-setup-overlay * form {
- -webkit-user-select: none;
-}
-
-#sync-setup-overlay * .content-area {
- padding: 10px 15px;
-}
-
-.action-area-link-container {
- -webkit-box-flex: 1;
-}
-
-.sync-customize-section-container {
- margin: 5px 0 10px 0;
-}
-
-#sync-custom-passphrase {
- margin: 0 25px;
-}
-
-#sync-passphrase-message {
- color: gray;
-}
-
-.sync-custom-passphrase-input {
- margin: 10px 0;
-}
-
-#sync-existing-passphrase-container {
- background: rgb(255, 242, 158);
- border: 1px solid rgb(212, 205, 173);
- padding: 10px;
-}
-
-#sync-instructions-container {
- line-height: 1.8em;
- margin-bottom: 30px;
-}
-
-#choose-data-types-body {
- -webkit-column-count: 3;
- margin: 10px 0 0 0;
-}
-
-#choose-data-types-body > .checkbox:first-child {
- margin-top: 0;
-}
-
-#choose-data-types-body > .checkbox:last-child {
- margin-bottom: 0;
-}
-
-#sync-setup-overlay {
- -webkit-user-select: none;
- background-color: white;
- margin-bottom: 6px;
- margin-top: 6px;
- width: 500px;
-}
-
-#sync-setup-overlay * a:link {
- color: rgb(0, 0, 204);
-}
-
-#sync-setup-overlay * a:visited {
- color: rgb(85, 26, 139);
-}
-
-#sync-setup-overlay * a:active {
- color: rgb(255, 0, 0);
-}
-
-#sync-setup-delete-profile {
- margin: 10px 0 0 0;
-}
-
-#email-readonly {
- font-size: 15px;
- height: 29px;
- line-height: 29px;
- margin: 0;
-}
-
-#encryption-section-message {
- color: gray;
- margin-bottom: 5px;
-}
-
-#basic-encryption-body,
-#full-encryption-body {
- display: table;
-}
-
-#customize-sync-encryption-new,
-#personalize-google-services {
- border-top: 1px solid #ddd;
- margin-top: 5px;
-}
-
-#personalize-google-services {
- line-height: 1.6em;
-}
-
-#personalize-google-services .title {
- align-items: center;
- display: flex;
- justify-content: space-between;
-}
-
-#googleg-logo {
- background-image: url(../../../../ui/webui/resources/images/200-logo_googleg.png);
- background-size: cover;
- height: 20px;
- width: 20px;
-}
-
-#passphrase-input {
- margin-bottom: 5px;
- margin-top: 5px;
-}
-
-#incorrect-passphrase {
- margin-top: 5px;
-}
-
-#sync-setup-overlay * .error {
- color: red;
-}
-
-.overlay-warning {
- background: white;
- border: 2px solid #888;
- border-radius: 8px;
- box-shadow: 0.2em 0.2em 0.5em #888;
- left: 25px;
- padding: 15px;
- position: absolute;
- right: 25px;
- top: 100px;
-}
-
-#cancel-warning-header {
- font-weight: bold;
- margin-bottom: 8px;
-}
-
-.overlay-warning input {
- float: right;
- margin-left: 5px;
- margin-top: 12px;
-}
-
-#sync-passphrase-warning {
- margin-bottom: 5px;
-}
-
-#asp-warning-div {
- text-align: left;
-}
-
-#logging-in-throbber {
- margin: 0 10px;
-}
-
-#password-row {
- margin-bottom: 0;
- margin-top: 2px;
-}
-
-#action-area {
- margin: 1em 0;
-}
-
-#sync-setup-configure {
- background: white;
-}
-
-#choose-data-types-form {
- -webkit-user-select: none;
-}
-
-#chooseDataTypesRadio {
- vertical-align: top;
-}
-
-#chooseDataTypes > div {
- display: inline-block;
-}
-
-.sync-data-types {
- margin-left: 5px;
-}
-
-#learn-more-link {
- float: right;
-}
-
-html[dir='rtl'] #learn-more-link {
- float: left;
-}
-
-#customize-link,
-#use-default-link {
- transition: opacity 250ms;
-}
diff --git a/chromium/chrome/browser/resources/options/sync_setup_overlay.html b/chromium/chrome/browser/resources/options/sync_setup_overlay.html
deleted file mode 100644
index ab179c1a2f7..00000000000
--- a/chromium/chrome/browser/resources/options/sync_setup_overlay.html
+++ /dev/null
@@ -1,246 +0,0 @@
-<div id="sync-setup-overlay" class="page" hidden>
- <div class="close-button"></div>
- <div id="sync-setup-configure" hidden>
- <div id="confirm-sync-preferences">
- <h1 i18n-content="confirmSyncPreferences"></h1>
- <div id="sync-instructions-container" class="content-area">
- <span i18n-content="chooseDataTypesInstructions"></span>
- <a id="encryption-help-link" target="_blank"
- i18n-values="href:syncEverythingHelpURL" i18n-content="learnMore">
- </a>
- </div>
- <div>
- <div class="action-area">
- <div class="action-area-link-container">
- <a is="action-link" id="customize-link"
- i18n-content="customizeLinkLabel"></a>
- </div>
- <div id="confirm-everything-throbber" class="throbber"></div>
- <div class="button-strip">
- <button id="confirm-everything-cancel" i18n-content="cancel">
- <button id="confirm-everything-ok" class="default-button"
- i18n-content="syncEverything">
- </div>
- </div>
- </div>
- </div>
- <div id="customize-sync-preferences" hidden>
- <h1 i18n-content="syncSetupConfigureTitle"></h1>
- <form id="choose-data-types-form">
- <div id="sync-configure-content" class="content-area">
- <div id="sync-select-container">
- <select id="sync-select-datatypes"
- metric="Options_SyncSelectDataTypes">
- <option i18n-content="syncAllDataTypes" selected></option>
- <option i18n-content="chooseDataTypes"></option>
- </select>
- <div id="choose-data-types-body">
- <div id="apps-item" class="sync-type-checkbox checkbox">
- <label>
- <input id="apps-checkbox" type="checkbox">
- <span i18n-content="apps" i18n-values="title:apps"></span>
- </label>
- </div>
- <div id="autofill-item" class="sync-type-checkbox checkbox">
- <label>
- <input id="autofill-checkbox" type="checkbox">
- <span i18n-content="autofill" i18n-values="title:autofill">
- </span>
- </label>
- </div>
- <div class="sync-type-checkbox checkbox">
- <label>
- <input id="bookmarks-checkbox" type="checkbox">
- <span i18n-content="bookmarks"
- i18n-values="title:bookmarks"></span>
- </label>
- </div>
- <div id="extensions-item" class="sync-type-checkbox checkbox">
- <label>
- <input id="extensions-checkbox" type="checkbox">
- <span i18n-content="extensions"
- i18n-values="title:extensions"></span>
- </label>
- </div>
- <div id="omnibox-item" class="sync-type-checkbox checkbox">
- <label>
- <input id="typed-urls-checkbox" type="checkbox">
- <span i18n-content="typedURLs"
- i18n-values="title:typedURLs"></span>
- </label>
- </div>
- <div id="passwords-item" class="sync-type-checkbox checkbox">
- <label>
- <input id="passwords-checkbox" type="checkbox">
- <span i18n-content="passwords"
- i18n-values="title:passwords"></span>
- </label>
- </div>
- <div class="sync-type-checkbox checkbox">
- <label>
- <input id="preferences-checkbox" type="checkbox">
- <span i18n-content="preferences"
- i18n-values="title:preferences"></span>
- </label>
- </div>
- <div class="sync-type-checkbox checkbox">
- <label>
- <input id="themes-checkbox" type="checkbox">
- <span i18n-content="themes" i18n-values="title:themes">
- </span>
- </label>
- </div>
- <div id="tabs-item" class="sync-type-checkbox checkbox">
- <label>
- <input id="tabs-checkbox" type="checkbox">
- <span i18n-content="openTabs" il8n-values="title:tabs">
- </span>
- </label>
- </div>
- </div>
- </div>
- <div id="payments-integration-setting-area" class="checkbox">
- <label>
- <input id="payments-integration-checkbox" type="checkbox">
- <span i18n-content="enablePaymentsIntegration"></span>
- </label>
- <a i18n-values="href:autofillHelpURL" target="_blank"
- i18n-content="learnMore"></a>
- </div>
- <div id="customize-sync-encryption-new">
- <h4 i18n-content="encryptionSectionTitle"></h4>
- <div id="encryption-section-message"
- i18n-content="encryptionSectionMessage"></div>
- <div id="sync-new-encryption-section-container">
- <div class="radio">
- <label>
- <input id="basic-encryption-option" name="encrypt-new"
- type="radio" value="full">
- <span id="basic-encryption-body"
- i18n-content="basicEncryptionOption"></span>
- </label>
- </div>
- <div class="radio">
- <label>
- <input id="full-encryption-option" name="encrypt-new"
- type="radio" value="full">
- <span id="full-encryption-body"
- i18n-content="fullEncryptionOption"></span>
- </label>
- <a i18n-values="href:encryptionHelpURL" target="_blank"
- i18n-content="learnMore"></a>
- </div>
- </div>
- </div>
- <div id="sync-custom-passphrase-container"
- class="sync-customize-section-container">
- <div id="sync-custom-passphrase"
- class="reset-hidden" hidden>
- <div id="sync-passphrase-message">
- <span i18n-content="sectionExplicitMessagePrefix"></span>
- <a href="https://www.google.com/settings/chrome/sync/"
- target="_blank"
- i18n-content="sectionExplicitMessagePostfix"></a>
- <span>.</span>
- </div>
- <div class="sync-custom-passphrase-input">
- <input id="custom-passphrase" type="password"
- class="reset-value"
- i18n-values="placeholder:passphraseLabel">
- </div>
- <div class="sync-custom-passphrase-input">
- <input id="confirm-passphrase" type="password"
- class="reset-value"
- i18n-values="placeholder:confirmLabel">
- </div>
- <div id="empty-error" class="error"
- i18n-content="emptyErrorMessage" hidden></div>
- <div id="mismatch-error" class="error"
- i18n-content="mismatchErrorMessage" hidden></div>
- </div>
- </div>
- <div id="sync-existing-passphrase-container" hidden>
- <div id="enter-passphrase">
- <span id="normal-body" i18n-content="enterPassphraseBody" hidden>
- </span>
- <span id="google-passphrase-needed-body"
- i18n-content="enterGooglePassphraseBody" hidden>
- </span>
- <a id="passphrase-learn-more" i18n-content="learnMore"
- i18n-values="href:syncErrorHelpURL" class="reset-hidden"
- target="_blank" hidden>
- </a>
- </div>
- <div id="passphrase-input">
- <input id="passphrase" name="passphrase" type="password"
- class="reset-value"
- i18n-values="placeholder:passphraseLabel">
- <div id="incorrect-passphrase" class="error"
- i18n-content="incorrectPassphrase" hidden>
- </div>
- </div>
- <div id="sync-passphrase-warning"
- i18n-values=".innerHTML:passphraseRecover" hidden>
- </div>
- </div>
- <div id="personalize-google-services">
- <div class="title">
- <h4 i18n-content="personalizeGoogleServicesTitle"></h4>
- <div id="googleg-logo" class="logo"></div>
- </div>
- <div i18n-values=".innerHTML:personalizeGoogleServicesMessage">
- </div>
- </div>
- </div>
- <div class="action-area">
- <div class="action-area-link-container">
- <a is="action-link" id="use-default-link"
- i18n-content="useDefaultSettings"></a>
- </div>
- <div id="choose-datatypes-throbber" class="throbber"></div>
- <div class="button-strip">
- <input id="choose-datatypes-cancel" type="button"
- i18n-values="value:cancel">
- <input id="choose-datatypes-ok" type="submit" class="default-button"
- i18n-values="value:ok">
- </div>
- </div>
- </form>
- </div>
- </div>
- <div id="sync-setup-spinner" hidden>
- <h1 i18n-content="syncSetupSpinnerTitle"></h1>
- <div class="action-area button-strip">
- <button id="sync-spinner-cancel" class="default-button"
- i18n-content="cancel">
- </div>
- </div>
- <div id="sync-setup-timeout" hidden>
- <h1 i18n-content="syncSetupTimeoutTitle"></h1>
- <div class="content-area">
- <span i18n-content="syncSetupTimeoutContent"></span>
- </div>
- <div class="action-area button-strip">
- <button id="timeout-ok" i18n-content="ok" class="default-button"></button>
- </div>
- </div>
- <div id="sync-setup-stop-syncing" hidden>
- <h1 i18n-content="stopSyncingTitle"></h1>
- <div class="content-area">
- <span i18n-values=".innerHTML:stopSyncingExplanation"></span>
-<if expr="(not chromeos and is_posix) or is_win or is_macosx">
- <div id="sync-setup-delete-profile" class="checkbox">
- <label>
- <input id="delete-profile" type="checkbox">
- <span i18n-content="deleteProfileLabel"></span>
- </label>
- </div>
-</if>
- </div>
- <div class="action-area button-strip">
- <button id="stop-syncing-cancel" i18n-content="cancel">
- <button id="stop-syncing-ok" class="default-button"
- i18n-content="stopSyncingConfirm">
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/options/sync_setup_overlay.js b/chromium/chrome/browser/resources/options/sync_setup_overlay.js
deleted file mode 100644
index 12dc97d09a2..00000000000
--- a/chromium/chrome/browser/resources/options/sync_setup_overlay.js
+++ /dev/null
@@ -1,833 +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.
-
-cr.exportPath('options');
-
-/** @typedef {{appsEnforced: boolean,
- * appsRegistered: boolean,
- * appsSynced: boolean,
- * autofillEnforced: boolean,
- * autofillRegistered: boolean,
- * autofillSynced: boolean,
- * bookmarksEnforced: boolean,
- * bookmarksRegistered: boolean,
- * bookmarksSynced: boolean,
- * encryptAllData: boolean,
- * encryptAllDataAllowed: boolean,
- * enterGooglePassphraseBody: (string|undefined),
- * enterPassphraseBody: (string|undefined),
- * extensionsEnforced: boolean,
- * extensionsRegistered: boolean,
- * extensionsSynced: boolean,
- * fullEncryptionBody: string,
- * passphraseFailed: boolean,
- * passwordsEnforced: boolean,
- * passwordsRegistered: boolean,
- * passwordsSynced: boolean,
- * paymentsIntegrationEnabled: boolean,
- * preferencesEnforced: boolean,
- * preferencesRegistered: boolean,
- * preferencesSynced: boolean,
- * showPassphrase: boolean,
- * syncAllDataTypes: boolean,
- * tabsEnforced: boolean,
- * tabsRegistered: boolean,
- * tabsSynced: boolean,
- * themesEnforced: boolean,
- * themesRegistered: boolean,
- * themesSynced: boolean,
- * typedUrlsEnforced: boolean,
- * typedUrlsRegistered: boolean,
- * typedUrlsSynced: boolean,
- * usePassphrase: boolean}}
- */
-var SyncConfig;
-
-/**
- * The user's selection in the synced data type drop-down menu, as an index.
- * @enum {number}
- * @const
- */
-options.DataTypeSelection = {
- SYNC_EVERYTHING: 0,
- CHOOSE_WHAT_TO_SYNC: 1,
-};
-
-cr.define('options', function() {
- /** @const */ var Page = cr.ui.pageManager.Page;
- /** @const */ var PageManager = cr.ui.pageManager.PageManager;
-
- /**
- * SyncSetupOverlay class
- * Encapsulated handling of the 'Sync Setup' overlay page.
- * @class
- */
- function SyncSetupOverlay() {
- Page.call(this, 'syncSetup',
- loadTimeData.getString('syncSetupOverlayTabTitle'),
- 'sync-setup-overlay');
- }
-
- cr.addSingletonGetter(SyncSetupOverlay);
-
- SyncSetupOverlay.prototype = {
- __proto__: Page.prototype,
-
- /**
- * True if the synced account uses a custom passphrase.
- * @private {boolean}
- */
- usePassphrase_: false,
-
- /**
- * True if the synced account uses 'encrypt everything'.
- * @private {boolean}
- */
- useEncryptEverything_: false,
-
- /**
- * An object used as a cache of the arguments passed in while initially
- * displaying the advanced sync settings dialog. Used to switch between the
- * options in the main drop-down menu. Reset when the dialog is closed.
- * @private {?SyncConfig}
- */
- syncConfigureArgs_: null,
-
- /**
- * A dictionary that maps the sync data type checkbox names to their checked
- * state. Initialized when the advanced settings dialog is first brought up,
- * updated any time a box is checked / unchecked, and reset when the dialog
- * is closed. Used to restore checkbox state while switching between the
- * options in the main drop-down menu. All checkboxes are checked and
- * disabled when the "Sync everything" menu-item is selected, and unchecked
- * and disabled when "Sync nothing" is selected. When "Choose what to sync"
- * is selected, the boxes are restored to their most recent checked state
- * from this cache.
- * @private {Object}
- */
- dataTypeBoxesChecked_: {},
-
- /**
- * A dictionary that maps the sync data type checkbox names to their
- * disabled state (when a data type is enabled programmatically without user
- * choice). Initialized when the advanced settings dialog is first brought
- * up, and reset when the dialog is closed.
- * @private {Object}
- */
- dataTypeBoxesDisabled_: {},
-
- /** @override */
- initializePage: function() {
- Page.prototype.initializePage.call(this);
-
- var self = this;
-
- // If 'profilesInfo' doesn't exist, it's forbidden to delete profile.
- // So don't display the delete-profile checkbox.
- if (!loadTimeData.valueExists('profilesInfo') &&
- $('sync-setup-delete-profile')) {
- $('sync-setup-delete-profile').hidden = true;
- }
-
- $('basic-encryption-option').onchange =
- $('full-encryption-option').onchange = function() {
- self.onEncryptionRadioChanged_();
- };
- $('choose-datatypes-cancel').onclick =
- $('confirm-everything-cancel').onclick =
- $('stop-syncing-cancel').onclick =
- $('sync-spinner-cancel').onclick = function() {
- self.closeOverlay_();
- };
- $('activity-controls').onclick = function() {
- chrome.metricsPrivate.recordUserAction(
- 'Signin_AccountSettings_GoogleActivityControlsClicked');
- };
- $('confirm-everything-ok').onclick = function() {
- self.sendConfiguration_();
- };
- $('timeout-ok').onclick = function() {
- chrome.send('CloseTimeout');
- self.closeOverlay_();
- };
- $('stop-syncing-ok').onclick = function() {
- var deleteProfile = $('delete-profile') != undefined &&
- $('delete-profile').checked;
- chrome.send('SyncSetupStopSyncing', [deleteProfile]);
- self.closeOverlay_();
- };
- $('use-default-link').onclick = function() {
- self.showSyncEverythingPage_();
- };
- $('autofill-checkbox').onclick = function() {
- var autofillSyncEnabled = $('autofill-checkbox').checked;
- $('payments-integration-checkbox').checked = autofillSyncEnabled;
- $('payments-integration-checkbox').disabled = !autofillSyncEnabled;
- };
- },
-
- /** @private */
- showOverlay_: function() {
- PageManager.showPageByName('syncSetup');
- },
-
- /** @private */
- closeOverlay_: function() {
- this.syncConfigureArgs_ = null;
- this.dataTypeBoxesChecked_ = {};
- this.dataTypeBoxesDisabled_ = {};
-
- var overlay = $('sync-setup-overlay');
- if (!overlay.hidden)
- PageManager.closeOverlay();
- },
-
- /** @override */
- didShowPage: function() {
- chrome.send('SyncSetupShowSetupUI');
- },
-
- /** @override */
- didClosePage: function() {
- chrome.send('SyncSetupDidClosePage');
- },
-
- /** @private */
- onEncryptionRadioChanged_: function() {
- var visible = $('full-encryption-option').checked;
- // TODO(dbeam): should sync-custom-passphrase-container be hidden instead?
- $('sync-custom-passphrase').hidden = !visible;
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_SyncSetEncryption']);
- },
-
- /**
- * Sets the checked state of the individual sync data type checkboxes in the
- * advanced sync settings dialog.
- * @param {boolean} value True for checked, false for unchecked.
- * @private
- */
- checkAllDataTypeCheckboxes_: function(value) {
- // Only check / uncheck the visible ones (since there's no way to uncheck
- // / check the invisible ones).
- var checkboxes = $('choose-data-types-body').querySelectorAll(
- '.sync-type-checkbox:not([hidden]) input');
- for (var i = 0; i < checkboxes.length; i++) {
- checkboxes[i].checked = value;
- }
- $('payments-integration-checkbox').checked = value;
- },
-
- /**
- * Restores the checked states of the sync data type checkboxes in the
- * advanced sync settings dialog. Called when "Choose what to sync" is
- * selected. Required because all the checkboxes are checked when
- * "Sync everything" is selected, and unchecked when "Sync nothing" is
- * selected. Note: We only restore checkboxes for data types that are
- * actually visible and whose old values are found in the cache, since it's
- * possible for some data types to not be registered, and therefore, their
- * checkboxes remain hidden, and never get cached.
- * @private
- */
- restoreDataTypeCheckboxes_: function() {
- for (var dataType in this.dataTypeBoxesChecked_) {
- $(dataType).checked = this.dataTypeBoxesChecked_[dataType];
- }
- },
-
- /**
- * Enables / grays out the sync data type checkboxes in the advanced
- * settings dialog.
- * @param {boolean} enabled True for enabled, false for grayed out.
- * @private
- */
- setDataTypeCheckboxesEnabled_: function(enabled) {
- for (var dataType in this.dataTypeBoxesDisabled_) {
- $(dataType).disabled =
- !enabled || this.dataTypeBoxesDisabled_[dataType];
- }
- },
-
- /**
- * Sets the state of the sync data type checkboxes based on whether "Sync
- * everything", "Choose what to sync", or "Sync nothing" are selected in the
- * drop-down menu of the advanced settings dialog.
- * @param {options.DataTypeSelection} selectedIndex Index of user's
- * selection.
- * @private
- */
- setDataTypeCheckboxes_: function(selectedIndex) {
- if (selectedIndex == options.DataTypeSelection.CHOOSE_WHAT_TO_SYNC) {
- this.setDataTypeCheckboxesEnabled_(true);
- this.restoreDataTypeCheckboxes_();
- } else {
- this.setDataTypeCheckboxesEnabled_(false);
- this.checkAllDataTypeCheckboxes_(
- selectedIndex == options.DataTypeSelection.SYNC_EVERYTHING);
- }
- },
-
- /** @private */
- checkPassphraseMatch_: function() {
- var emptyError = $('empty-error');
- var mismatchError = $('mismatch-error');
- emptyError.hidden = true;
- mismatchError.hidden = true;
-
- if (!$('full-encryption-option').checked ||
- $('basic-encryption-option').disabled) {
- return true;
- }
-
- var customPassphrase = $('custom-passphrase');
- if (customPassphrase.value.length == 0) {
- emptyError.hidden = false;
- return false;
- }
-
- var confirmPassphrase = $('confirm-passphrase');
- if (confirmPassphrase.value != customPassphrase.value) {
- mismatchError.hidden = false;
- return false;
- }
-
- return true;
- },
-
- /** @private */
- sendConfiguration_: function() {
- var encryptAllData = $('full-encryption-option').checked;
-
- var usePassphrase;
- var customPassphrase;
- var googlePassphrase = false;
- if (!$('sync-existing-passphrase-container').hidden) {
- // If we were prompted for an existing passphrase, use it.
- customPassphrase = getRequiredElement('passphrase').value;
- usePassphrase = true;
- // If we were displaying the 'enter your old google password' prompt,
- // then that means this is the user's google password.
- googlePassphrase = !$('google-passphrase-needed-body').hidden;
- // We allow an empty passphrase, in case the user has disabled
- // all their encrypted datatypes. In that case, the PSS will accept
- // the passphrase and finish configuration. If the user has enabled
- // encrypted datatypes, the PSS will prompt again specifying that the
- // passphrase failed.
- } else if (!$('basic-encryption-option').disabled &&
- $('full-encryption-option').checked) {
- // The user is setting a custom passphrase for the first time.
- if (!this.checkPassphraseMatch_())
- return;
- customPassphrase = $('custom-passphrase').value;
- usePassphrase = true;
- } else {
- // The user is not setting a custom passphrase.
- usePassphrase = false;
- }
-
- // Don't allow the user to tweak the settings once we send the
- // configuration to the backend.
- this.setInputElementsDisabledState_(true);
- $('use-default-link').hidden = true;
-
- // These values need to be kept in sync with where they are read in
- // sync_setup_handler.cc:GetConfiguration().
- var syncAll = $('sync-select-datatypes').selectedIndex ==
- options.DataTypeSelection.SYNC_EVERYTHING;
- var autofillSynced = syncAll || $('autofill-checkbox').checked;
- var result = JSON.stringify({
- 'syncAllDataTypes': syncAll,
- 'bookmarksSynced': syncAll || $('bookmarks-checkbox').checked,
- 'preferencesSynced': syncAll || $('preferences-checkbox').checked,
- 'themesSynced': syncAll || $('themes-checkbox').checked,
- 'passwordsSynced': syncAll || $('passwords-checkbox').checked,
- 'autofillSynced': autofillSynced,
- 'extensionsSynced': syncAll || $('extensions-checkbox').checked,
- 'typedUrlsSynced': syncAll || $('typed-urls-checkbox').checked,
- 'appsSynced': syncAll || $('apps-checkbox').checked,
- 'tabsSynced': syncAll || $('tabs-checkbox').checked,
- 'paymentsIntegrationEnabled': syncAll ||
- (autofillSynced && $('payments-integration-checkbox').checked),
- 'encryptAllData': encryptAllData,
- 'usePassphrase': usePassphrase,
- 'isGooglePassphrase': googlePassphrase,
- 'passphrase': customPassphrase
- });
- chrome.send('SyncSetupConfigure', [result]);
- },
-
- /**
- * Sets the disabled property of all input elements within the 'Customize
- * Sync Preferences' screen. This is used to prohibit the user from changing
- * the inputs after confirming the customized sync preferences, or resetting
- * the state when re-showing the dialog.
- * @param {boolean} disabled True if controls should be set to disabled.
- * @private
- */
- setInputElementsDisabledState_: function(disabled) {
- var self = this;
- var configureElements =
- $('customize-sync-preferences').querySelectorAll('input');
- for (var i = 0; i < configureElements.length; i++)
- configureElements[i].disabled = disabled;
- $('sync-select-datatypes').disabled = disabled;
- $('payments-integration-checkbox').disabled = disabled;
-
- $('customize-link').hidden = disabled;
- $('customize-link').disabled = disabled;
- $('customize-link').onclick = disabled ? null : function() {
- SyncSetupOverlay.showCustomizePage(self.syncConfigureArgs_,
- options.DataTypeSelection.SYNC_EVERYTHING);
- return false;
- };
- },
-
- /**
- * Shows or hides the sync data type checkboxes in the advanced sync
- * settings dialog. Also initializes |this.dataTypeBoxesChecked_| and
- * |this.dataTypeBoxedDisabled_| with their values, and makes their onclick
- * handlers update |this.dataTypeBoxesChecked_|.
- * @param {SyncConfig} args The configuration data used to show/hide UI.
- * @private
- */
- setChooseDataTypesCheckboxes_: function(args) {
- var datatypeSelect = $('sync-select-datatypes');
- datatypeSelect.selectedIndex = args.syncAllDataTypes ?
- options.DataTypeSelection.SYNC_EVERYTHING :
- options.DataTypeSelection.CHOOSE_WHAT_TO_SYNC;
-
- $('bookmarks-checkbox').checked = args.bookmarksSynced;
- this.dataTypeBoxesChecked_['bookmarks-checkbox'] = args.bookmarksSynced;
- this.dataTypeBoxesDisabled_['bookmarks-checkbox'] =
- args.bookmarksEnforced;
-
- $('preferences-checkbox').checked = args.preferencesSynced;
- this.dataTypeBoxesChecked_['preferences-checkbox'] =
- args.preferencesSynced;
- this.dataTypeBoxesDisabled_['preferences-checkbox'] =
- args.preferencesEnforced;
-
- $('themes-checkbox').checked = args.themesSynced;
- this.dataTypeBoxesChecked_['themes-checkbox'] = args.themesSynced;
- this.dataTypeBoxesDisabled_['themes-checkbox'] = args.themesEnforced;
-
- if (args.passwordsRegistered) {
- $('passwords-checkbox').checked = args.passwordsSynced;
- this.dataTypeBoxesChecked_['passwords-checkbox'] = args.passwordsSynced;
- this.dataTypeBoxesDisabled_['passwords-checkbox'] =
- args.passwordsEnforced;
- $('passwords-item').hidden = false;
- } else {
- $('passwords-item').hidden = true;
- }
- if (args.autofillRegistered) {
- $('autofill-checkbox').checked = args.autofillSynced;
- this.dataTypeBoxesChecked_['autofill-checkbox'] = args.autofillSynced;
- this.dataTypeBoxesDisabled_['autofill-checkbox'] =
- args.autofillEnforced;
- this.dataTypeBoxesChecked_['payments-integration-checkbox'] =
- args.autofillSynced && args.paymentsIntegrationEnabled;
- this.dataTypeBoxesDisabled_['payments-integration-checkbox'] =
- !args.autofillSynced;
- $('autofill-item').hidden = false;
- $('payments-integration-setting-area').hidden = false;
- } else {
- $('autofill-item').hidden = true;
- $('payments-integration-setting-area').hidden = true;
- }
- if (args.extensionsRegistered) {
- $('extensions-checkbox').checked = args.extensionsSynced;
- this.dataTypeBoxesChecked_['extensions-checkbox'] =
- args.extensionsSynced;
- this.dataTypeBoxesDisabled_['extensions-checkbox'] =
- args.extensionsEnforced;
- $('extensions-item').hidden = false;
- } else {
- $('extensions-item').hidden = true;
- }
- if (args.typedUrlsRegistered) {
- $('typed-urls-checkbox').checked = args.typedUrlsSynced;
- this.dataTypeBoxesChecked_['typed-urls-checkbox'] =
- args.typedUrlsSynced;
- this.dataTypeBoxesDisabled_['typed-urls-checkbox'] =
- args.typedUrlsEnforced;
- $('omnibox-item').hidden = false;
- } else {
- $('omnibox-item').hidden = true;
- }
- if (args.appsRegistered) {
- $('apps-checkbox').checked = args.appsSynced;
- this.dataTypeBoxesChecked_['apps-checkbox'] = args.appsSynced;
- this.dataTypeBoxesDisabled_['apps-checkbox'] = args.appsEnforced;
- $('apps-item').hidden = false;
- } else {
- $('apps-item').hidden = true;
- }
- if (args.tabsRegistered) {
- $('tabs-checkbox').checked = args.tabsSynced;
- this.dataTypeBoxesChecked_['tabs-checkbox'] = args.tabsSynced;
- this.dataTypeBoxesDisabled_['tabs-checkbox'] = args.tabsEnforced;
- $('tabs-item').hidden = false;
- } else {
- $('tabs-item').hidden = true;
- }
-
- $('choose-data-types-body').onchange =
- this.handleDataTypeChange_.bind(this);
-
- this.setDataTypeCheckboxes_(datatypeSelect.selectedIndex);
- },
-
- /**
- * Updates the cached values of the sync data type checkboxes stored in
- * |this.dataTypeBoxesChecked_|. Used as an onclick handler for each data
- * type checkbox.
- * @param {Event} e The change event.
- * @private
- */
- handleDataTypeChange_: function(e) {
- var input = assertInstanceof(e.target, HTMLInputElement);
- assert(input.type == 'checkbox');
- this.dataTypeBoxesChecked_[input.id] = input.checked;
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_SyncToggleDataType']);
- },
-
- /**
- * @param {SyncConfig} args
- * @private
- */
- setEncryptionRadios_: function(args) {
- if (!args.encryptAllData && !args.usePassphrase) {
- $('basic-encryption-option').checked = true;
- } else {
- $('full-encryption-option').checked = true;
- $('full-encryption-option').disabled = true;
- $('basic-encryption-option').disabled = true;
- }
- },
-
- /**
- * @param {SyncConfig} args
- * @private
- */
- setCheckboxesAndErrors_: function(args) {
- this.setChooseDataTypesCheckboxes_(args);
- this.setEncryptionRadios_(args);
- },
-
- /**
- * @param {SyncConfig} args
- * @private
- */
- showConfigure_: function(args) {
- var datatypeSelect = $('sync-select-datatypes');
- var self = this;
-
- // Cache the sync config args so they can be reused when we transition
- // between the drop-down menu items in the advanced settings dialog.
- if (args)
- this.syncConfigureArgs_ = args;
-
- // Once the advanced sync settings dialog is visible, we transition
- // between its drop-down menu items as follows:
- // "Sync everything": Show encryption and passphrase sections, and disable
- // and check all data type checkboxes.
- // "Choose what to sync": Show encryption and passphrase sections, enable
- // data type checkboxes, and restore their checked state to the last time
- // the "Choose what to sync" was selected while the dialog was still up.
- datatypeSelect.onchange = function() {
- self.showCustomizePage_(self.syncConfigureArgs_, this.selectedIndex);
- if (this.selectedIndex == options.DataTypeSelection.SYNC_EVERYTHING) {
- self.checkAllDataTypeCheckboxes_(true);
- } else {
- self.restoreDataTypeCheckboxes_();
- }
- };
-
- this.resetPage_('sync-setup-configure');
- $('sync-setup-configure').hidden = false;
-
- // onsubmit is changed when submitting a passphrase. Reset it to its
- // default.
- $('choose-data-types-form').onsubmit = function() {
- self.sendConfiguration_();
- return false;
- };
-
- if (args) {
- this.setCheckboxesAndErrors_(args);
-
- this.useEncryptEverything_ = args.encryptAllData;
-
- // Determine whether to display the 'OK, sync everything' confirmation
- // dialog or the advanced sync settings dialog, and assign focus to the
- // OK button, or to the passphrase field if a passphrase is required.
- this.usePassphrase_ = args.usePassphrase;
- var index = args.syncAllDataTypes ?
- options.DataTypeSelection.SYNC_EVERYTHING :
- options.DataTypeSelection.CHOOSE_WHAT_TO_SYNC;
- this.showCustomizePage_(args, index);
- }
- },
-
- /** @private */
- showSpinner_: function() {
- this.resetPage_('sync-setup-spinner');
- $('sync-setup-spinner').hidden = false;
- },
-
- /** @private */
- showTimeoutPage_: function() {
- this.resetPage_('sync-setup-timeout');
- $('sync-setup-timeout').hidden = false;
- },
-
- /** @private */
- showSyncEverythingPage_: function() {
- chrome.send('coreOptionsUserMetricsAction',
- ['Options_SyncSetDefault']);
-
- $('confirm-sync-preferences').hidden = false;
- $('customize-sync-preferences').hidden = true;
-
- // Reset the selection to 'Sync everything'.
- $('sync-select-datatypes').selectedIndex = 0;
-
- // The default state is to sync everything.
- this.setDataTypeCheckboxes_(options.DataTypeSelection.SYNC_EVERYTHING);
-
- // TODO(dbeam): should hide sync-custom-passphrase-container instead?
- if (!this.usePassphrase_)
- $('sync-custom-passphrase').hidden = true;
-
- if (!this.useEncryptEverything_ && !this.usePassphrase_)
- $('basic-encryption-option').checked = true;
- },
-
- /**
- * Reveals the UI for entering a custom passphrase during initial setup.
- * This happens if the user has previously enabled a custom passphrase on a
- * different machine.
- * @param {SyncConfig} args The args that contain the passphrase UI
- * configuration.
- * @private
- */
- showPassphraseContainer_: function(args) {
- // Once we require a passphrase, we prevent the user from returning to
- // the Sync Everything pane.
- $('use-default-link').hidden = true;
- $('sync-custom-passphrase-container').hidden = true;
- $('sync-existing-passphrase-container').hidden = false;
-
- // Hide the selection options within the new encryption section when
- // prompting for a passphrase.
- $('sync-new-encryption-section-container').hidden = true;
-
- $('normal-body').hidden = true;
- $('google-passphrase-needed-body').hidden = true;
- // Display the correct prompt to the user depending on what type of
- // passphrase is needed.
- if (args.usePassphrase)
- $('normal-body').hidden = false;
- else
- $('google-passphrase-needed-body').hidden = false;
-
- $('passphrase-learn-more').hidden = false;
- // Warn the user about their incorrect passphrase if we need a passphrase
- // and the passphrase field is non-empty (meaning they tried to set it
- // previously but failed).
- $('incorrect-passphrase').hidden =
- !(args.usePassphrase && args.passphraseFailed);
-
- $('sync-passphrase-warning').hidden = false;
- },
-
- /**
- * Displays the advanced sync setting dialog, and pre-selects either the
- * "Sync everything" or the "Choose what to sync" drop-down menu item.
- * @param {SyncConfig} args
- * @param {options.DataTypeSelection} index Index of item to pre-select.
- * @private
- */
- showCustomizePage_: function(args, index) {
- $('confirm-sync-preferences').hidden = true;
- $('customize-sync-preferences').hidden = false;
-
- $('sync-custom-passphrase-container').hidden = false;
- $('sync-new-encryption-section-container').hidden = false;
- $('customize-sync-encryption-new').hidden = !args.encryptAllDataAllowed;
- $('personalize-google-services').hidden = false;
-
- $('sync-existing-passphrase-container').hidden = true;
-
- $('sync-select-datatypes').selectedIndex = index;
- this.setDataTypeCheckboxesEnabled_(
- index == options.DataTypeSelection.CHOOSE_WHAT_TO_SYNC);
-
- if (args.showPassphrase) {
- this.showPassphraseContainer_(args);
- // TODO(dbeam): add an #updatePassphrase and only focus with that hash?
- $('passphrase').focus();
- } else {
- // We only show the 'Use Default' link if we're not prompting for an
- // existing passphrase.
- $('use-default-link').hidden = false;
- }
- },
-
- /**
- * Shows the appropriate sync setup page.
- * @param {string} page A page of the sync setup to show.
- * @param {SyncConfig} args Data from the C++ to forward on to the right
- * section.
- */
- showSyncSetupPage_: function(page, args) {
- // If the user clicks the OK button, dismiss the dialog immediately, and
- // do not go through the process of hiding elements of the overlay.
- // See crbug.com/308873.
- if (page == 'done') {
- this.closeOverlay_();
- return;
- }
-
- this.setThrobbersVisible_(false);
-
- // Hide an existing visible overlay (ensuring the close button is not
- // hidden).
- var children = document.querySelectorAll(
- '#sync-setup-overlay > *:not(.close-button)');
- for (var i = 0; i < children.length; i++)
- children[i].hidden = true;
-
- this.setInputElementsDisabledState_(false);
-
- // If new passphrase bodies are present, overwrite the existing ones.
- if (args && args.enterPassphraseBody != undefined)
- $('normal-body').innerHTML = args.enterPassphraseBody;
- if (args && args.enterGooglePassphraseBody != undefined) {
- $('google-passphrase-needed-body').innerHTML =
- args.enterGooglePassphraseBody;
- }
- if (args && args.fullEncryptionBody != undefined)
- $('full-encryption-body').innerHTML = args.fullEncryptionBody;
-
- // NOTE: Because both showGaiaLogin_() and showConfigure_() change the
- // focus, we need to ensure that the overlay container and dialog aren't
- // [hidden] (as trying to focus() nodes inside of a [hidden] DOM section
- // doesn't work).
- this.showOverlay_();
-
- if (page == 'configure' || page == 'passphrase')
- this.showConfigure_(args);
- else if (page == 'spinner')
- this.showSpinner_();
- else if (page == 'timeout')
- this.showTimeoutPage_();
- },
-
- /**
- * Changes the visibility of throbbers on this page.
- * @param {boolean} visible Whether or not to set all throbber nodes
- * visible.
- */
- setThrobbersVisible_: function(visible) {
- var throbbers = this.pageDiv.getElementsByClassName('throbber');
- for (var i = 0; i < throbbers.length; i++)
- throbbers[i].style.visibility = visible ? 'visible' : 'hidden';
- },
-
- /**
- * Reset the state of all descendant elements of a root element to their
- * initial state.
- * The initial state is specified by adding a class to the descendant
- * element in sync_setup_overlay.html.
- * @param {string} pageElementId The root page element id.
- * @private
- */
- resetPage_: function(pageElementId) {
- var page = $(pageElementId);
- var forEach = function(arr, fn) {
- var length = arr.length;
- for (var i = 0; i < length; i++) {
- fn(arr[i]);
- }
- };
-
- forEach(page.getElementsByClassName('reset-hidden'),
- function(elt) { elt.hidden = true; });
- forEach(page.getElementsByClassName('reset-shown'),
- function(elt) { elt.hidden = false; });
- forEach(page.getElementsByClassName('reset-disabled'),
- function(elt) { elt.disabled = true; });
- forEach(page.getElementsByClassName('reset-enabled'),
- function(elt) { elt.disabled = false; });
- forEach(page.getElementsByClassName('reset-value'),
- function(elt) { elt.value = ''; });
- forEach(page.getElementsByClassName('reset-opaque'),
- function(elt) { elt.classList.remove('transparent'); });
- },
-
- /**
- * Displays the stop syncing dialog.
- * @private
- */
- showStopSyncingUI_: function() {
- // Hide any visible children of the overlay.
- var overlay = $('sync-setup-overlay');
- for (var i = 0; i < overlay.children.length; i++)
- overlay.children[i].hidden = true;
-
- // Bypass PageManager.showPageByName because it will call didShowPage
- // which will set its own visible page, based on the flow state.
- this.visible = true;
-
- $('sync-setup-stop-syncing').hidden = false;
- },
-
- /**
- * Determines the appropriate page to show in the Sync Setup UI based on
- * the state of the Sync backend. Does nothing if the user is not signed in.
- * @private
- */
- showSetupUI_: function() {
- chrome.send('SyncSetupShowSetupUI');
- chrome.send('coreOptionsUserMetricsAction', ['Options_ShowSyncAdvanced']);
- },
-
- /**
- * Starts the signin process for the user. Does nothing if the user is
- * already signed in.
- * @param {boolean} creatingSupervisedUser
- * @private
- */
- startSignIn_: function(creatingSupervisedUser) {
- chrome.send('SyncSetupStartSignIn', [creatingSupervisedUser]);
- },
-
- /**
- * Forces user to sign out of Chrome for Chrome OS.
- * @private
- */
- doSignOutOnAuthError_: function() {
- chrome.send('AttemptUserExit');
- },
- };
-
- // Forward public APIs to private implementations.
- cr.makePublic(SyncSetupOverlay, [
- 'closeOverlay',
- 'showSetupUI',
- 'startSignIn',
- 'doSignOutOnAuthError',
- 'showSyncSetupPage',
- 'showCustomizePage',
- 'showStopSyncingUI',
- ]);
-
- // Export
- return {
- SyncSetupOverlay: SyncSetupOverlay
- };
-});
diff --git a/chromium/chrome/browser/resources/options/yellow_gear.png b/chromium/chrome/browser/resources/options/yellow_gear.png
deleted file mode 100644
index 4134d3d2ad9..00000000000
--- a/chromium/chrome/browser/resources/options/yellow_gear.png
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/options_resources.grd b/chromium/chrome/browser/resources/options_resources.grd
deleted file mode 100644
index 4ddc0f1a382..00000000000
--- a/chromium/chrome/browser/resources/options_resources.grd
+++ /dev/null
@@ -1,163 +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/options_resources.h" type="rc_header">
- <emit emit_type='prepend'></emit>
- </output>
- <output filename="options_resources.pak" type="data_package" />
- </outputs>
- <release seq="1">
- <structures>
- <structure name="IDR_OPTIONS_BUNDLE_JS"
- file="options/options_bundle.js"
- flattenhtml="true"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_HTML"
- file="options/options.html"
- flattenhtml="true"
- allowexternalscript="true"
- type="chrome_html" />
- <if expr="chromeos">
- <structure name="IDR_OPTIONS_ICONS_HTML"
- file="settings/icons.html"
- type="chrome_html"
- preprocess="true" />
- <structure name="IDR_OPTIONS_PIN_KEYBOARD_HTML"
- file="chromeos/quick_unlock/pin_keyboard.html"
- type="chrome_html"
- preprocess="true" />
- <structure name="IDR_OPTIONS_PIN_KEYBOARD_JS"
- file="chromeos/quick_unlock/pin_keyboard.js"
- type="chrome_html"
- preprocess="true" />
- <structure name="IDR_OPTIONS_PASSWORD_PROMPT_DIALOG_JS"
- file="settings/people_page/password_prompt_dialog.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_PASSWORD_PROMPT_DIALOG_HTML"
- file="settings/people_page/password_prompt_dialog.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_LOCK_SCREEN_CONSTANTS_JS"
- file="settings/people_page/lock_screen_constants.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_LOCK_SCREEN_CONSTANTS_HTML"
- file="settings/people_page/lock_screen_constants.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_LOCK_STATE_BEHAVIOR_JS"
- file="settings/people_page/lock_state_behavior.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_LOCK_STATE_BEHAVIOR_HTML"
- file="settings/people_page/lock_state_behavior.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_SETUP_PIN_DIALOG_JS"
- file="settings/people_page/setup_pin_dialog.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_SETUP_PIN_DIALOG_HTML"
- file="settings/people_page/setup_pin_dialog.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_EASY_UNLOCK_BROWSER_PROXY_JS"
- file="settings/people_page/easy_unlock_browser_proxy.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_EASY_UNLOCK_BROWSER_PROXY_HTML"
- file="settings/people_page/easy_unlock_browser_proxy.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_EASY_UNLOCK_TURN_OFF_DIALOG_JS"
- file="settings/people_page/easy_unlock_turn_off_dialog.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_EASY_UNLOCK_TURN_OFF_DIALOG_HTML"
- file="settings/people_page/easy_unlock_turn_off_dialog.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_FINGERPRINT_LIST_JS"
- file="settings/people_page/fingerprint_list.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_FINGERPRINT_LIST_HTML"
- file="settings/people_page/fingerprint_list.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_SETUP_FINGERPRINT_DIALOG_JS"
- file="settings/people_page/setup_fingerprint_dialog.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_SETUP_FINGERPRINT_DIALOG_HTML"
- file="settings/people_page/setup_fingerprint_dialog.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_FINGERPRINT_PROGRESS_ARC_JS"
- file="settings/people_page/fingerprint_progress_arc.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_FINGERPRINT_PROGRESS_ARC_HTML"
- file="settings/people_page/fingerprint_progress_arc.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_FINGERPRINT_BROWSER_PROXY_JS"
- file="settings/people_page/fingerprint_browser_proxy.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_FINGERPRINT_BROWSER_PROXY_HTML"
- file="settings/people_page/fingerprint_browser_proxy.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_LOCK_SCREEN_JS"
- file="settings/people_page/lock_screen.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_LOCK_SCREEN_HTML"
- file="settings/people_page/lock_screen.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_ROUTE_HTML"
- file="settings/route.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_ROUTE_JS"
- file="settings/route.js"
- type="chrome_html"
- preprocess="true" />
- <structure name="IDR_SETTINGS_SHARED_CSS_HTML"
- file="settings/settings_shared_css.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_SLIDER_HTML"
- file="settings/controls/settings_slider.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_SLIDER_JS"
- file="settings/controls/settings_slider.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_TOGGLE_BUTTON_HTML"
- file="settings/controls/settings_toggle_button.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_TOGGLE_BUTTON_JS"
- file="settings/controls/settings_toggle_button.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_BOOLEAN_CONTROL_BEHAVIOR_HTML"
- file="settings/controls/settings_boolean_control_behavior.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_BOOLEAN_CONTROL_BEHAVIOR_JS"
- file="settings/controls/settings_boolean_control_behavior.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREF_CONTROL_BEHAVIOR_HTML"
- file="settings/controls/pref_control_behavior.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREF_CONTROL_BEHAVIOR_JS"
- file="settings/controls/pref_control_behavior.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_VARS_CSS_HTML"
- file="settings/settings_vars_css.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREFS_BEHAVIOR_HTML"
- file="settings/prefs/prefs_behavior.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREFS_BEHAVIOR_JS"
- file="settings/prefs/prefs_behavior.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREFS_TYPES_HTML"
- file="settings/prefs/prefs_types.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREFS_TYPES_JS"
- file="settings/prefs/prefs_types.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREFS_HTML"
- file="settings/prefs/prefs.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_PREFS_JS"
- file="settings/prefs/prefs.js"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_I18N_SETUP_HTML"
- file="options/i18n_setup.html"
- type="chrome_html" />
- <structure name="IDR_OPTIONS_POLYMER_ELEMENTS_HTML"
- file="options/options_polymer.html"
- type="chrome_html" />
- </if>
- </structures>
- </release>
-</grit>
diff --git a/chromium/chrome/browser/resources/pdf/browser_api.js b/chromium/chrome/browser/resources/pdf/browser_api.js
index 85822de29c1..34da975c46c 100644
--- a/chromium/chrome/browser/resources/pdf/browser_api.js
+++ b/chromium/chrome/browser/resources/pdf/browser_api.js
@@ -49,7 +49,6 @@ function lookupInitialZoom(streamInfo) {
*/
class BrowserApi {
/**
- * @constructor
* @param {!Object} streamInfo The stream object which points to the data
* contained in the PDF.
* @param {number} defaultZoom The default browser zoom.
@@ -104,9 +103,9 @@ class BrowserApi {
setZoom(zoom) {
if (this.zoomBehavior_ != BrowserApi.ZoomBehavior.MANAGE)
return Promise.reject(new Error('Viewer does not manage browser zoom.'));
- return new Promise(function(resolve, reject) {
+ return new Promise((resolve, reject) => {
chrome.tabs.setZoom(this.streamInfo_.tabId, zoom, resolve);
- }.bind(this));
+ });
}
/**
@@ -143,13 +142,13 @@ class BrowserApi {
this.zoomBehavior_ == BrowserApi.ZoomBehavior.PROPAGATE_PARENT))
return;
- chrome.tabs.onZoomChange.addListener(function(info) {
+ chrome.tabs.onZoomChange.addListener(info => {
var zoomChangeInfo =
/** @type {{tabId: number, newZoomFactor: number}} */ (info);
if (zoomChangeInfo.tabId != this.streamInfo_.tabId)
return;
listener(zoomChangeInfo.newZoomFactor);
- }.bind(this));
+ });
}
}
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html
index 10a850ee4d3..6844a004b41 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html
@@ -7,14 +7,13 @@
<template>
<style include="cr-shared-style"></style>
<dialog is="cr-dialog" id="dialog" no-cancel>
- <div class="title" slot="title">
+ <div slot="title">
[[strings.errorDialogTitle]]
</div>
- <div class="body" slot="body">
+ <div slot="body">
[[strings.pageLoadFailed]]
</div>
- <div class="button-container" slot="button-container"
- hidden$="[[!reloadFn]]">
+ <div slot="button-container" hidden$="[[!reloadFn]]">
<paper-button class="action-button" on-click="reload">
[[strings.pageReload]]
</paper-button>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
index 96f7f3d07f4..48631d854d1 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
@@ -47,10 +47,10 @@ Polymer({
this.style.opacity = 1;
clearTimeout(this.timerId);
- this.timerId = setTimeout(function() {
+ this.timerId = setTimeout(() => {
this.style.opacity = 0;
this.timerId = undefined;
- }.bind(this), displayTime);
+ }, displayTime);
},
pageLabelsChanged: function() {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html
index 76351c2eda9..485a061243c 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html
@@ -16,8 +16,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" no-cancel>
- <div class="title" slot="title">[[strings.passwordDialogTitle]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[strings.passwordDialogTitle]]</div>
+ <div slot="body">
<div id="message">[[strings.passwordPrompt]]</div>
<paper-input id="password"
type="password"
@@ -27,7 +27,7 @@
autofocus>
</paper-input>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="submit" class="action-button" on-click="submit">
[[strings.passwordSubmit]]
</paper-button>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html
index 3935b7625f3..bc6553aab56 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html
@@ -48,8 +48,8 @@
#buttons {
@apply(--layout-flex-5);
- -webkit-user-select: none;
text-align: end;
+ user-select: none;
}
paper-icon-button {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html
index f36fcc9a3bd..83947a3e12f 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html
@@ -75,7 +75,7 @@
<div id="dropdown" style="display: none">
<h1>{{header}}</h1>
<div id="scroll-container">
- <content></content>
+ <slot></slot>
</div>
</div>
</div>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js
index 53e9acc5318..f1751dd3306 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js
@@ -93,11 +93,11 @@ Polymer({
*/
playAnimation_: function(isEntry) {
this.animation_ = isEntry ? this.animateEntry_() : this.animateExit_();
- this.animation_.onfinish = function() {
+ this.animation_.onfinish = () => {
this.animation_ = null;
if (!this.dropdownOpen)
this.$.dropdown.style.display = 'none';
- }.bind(this);
+ };
},
animateEntry_: function() {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html
index 757c24ef859..aba9da429c1 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html
@@ -7,11 +7,11 @@
<template>
<style>
:host {
- -webkit-user-select: none;
bottom: 0;
padding: 48px 0;
position: fixed;
right: 0;
+ user-select: none;
z-index: 3;
}
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
index 6a4af8f4aa3..f76c8cb596b 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
@@ -56,6 +56,17 @@ Polymer({
},
/**
+ * Handle forcing zoom to fit-to-page via scripting.
+ */
+ forceFitToPage: function() {
+ this.fire('fit-to-page');
+
+ // Set the button state since there was no mouse click. Since the zoom is
+ // set to fit-to-page, the button should do fit-to-width on the next click.
+ this.$['fit-button'].activeIndex = FIT_TO_WIDTH;
+ },
+
+ /**
* Handle clicks of the zoom-in-button.
*/
zoomIn: function() {
diff --git a/chromium/chrome/browser/resources/pdf/pdf.js b/chromium/chrome/browser/resources/pdf/pdf.js
index 46c54bea404..ffc2a4907c9 100644
--- a/chromium/chrome/browser/resources/pdf/pdf.js
+++ b/chromium/chrome/browser/resources/pdf/pdf.js
@@ -123,9 +123,9 @@ function PDFViewer(browserApi) {
this.errorScreen_ = $('error-screen');
// Can only reload if we are in a normal tab.
if (chrome.tabs && this.browserApi_.getStreamInfo().tabId != -1) {
- this.errorScreen_.reloadFn = function() {
+ this.errorScreen_.reloadFn = () => {
chrome.tabs.reload(this.browserApi_.getStreamInfo().tabId);
- }.bind(this);
+ };
}
// Create the viewport.
@@ -147,7 +147,8 @@ function PDFViewer(browserApi) {
// according to the scroll position of the window.
this.plugin_ = document.createElement('embed');
// NOTE: The plugin's 'id' field must be set to 'plugin' since
- // chrome/renderer/printing/print_web_view_helper.cc actually references it.
+ // chrome/renderer/printing/print_render_frame_helper.cc actually
+ // references it.
this.plugin_.id = 'plugin';
this.plugin_.type = 'application/x-google-chrome-pdf';
this.plugin_.addEventListener(
@@ -215,16 +216,16 @@ function PDFViewer(browserApi) {
this.toolbar_.docTitle = getFilenameFromURL(this.originalUrl_);
}
- document.body.addEventListener('change-page', function(e) {
+ document.body.addEventListener('change-page', e => {
this.viewport_.goToPage(e.detail.page);
- }.bind(this));
+ });
- document.body.addEventListener('navigate', function(e) {
+ document.body.addEventListener('navigate', e => {
var disposition = e.detail.newtab ?
Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB :
Navigator.WindowOpenDisposition.CURRENT_TAB;
this.navigator_.navigate(e.detail.uri, disposition);
- }.bind(this));
+ });
this.toolbarManager_ =
new ToolbarManager(window, this.toolbar_, this.zoomToolbar_);
@@ -273,7 +274,7 @@ PDFViewer.prototype = {
this.toolbarManager_.hideToolbarsAfterTimeout(e);
- var pageUpHandler = function() {
+ var pageUpHandler = () => {
// Go to the previous page if we are fit-to-page.
if (this.viewport_.fittingType == Viewport.FittingType.FIT_TO_PAGE) {
this.viewport_.goToPage(this.viewport_.getMostVisiblePage() - 1);
@@ -283,8 +284,8 @@ PDFViewer.prototype = {
position.y -= this.viewport.size.height;
this.viewport.position = position;
}
- }.bind(this);
- var pageDownHandler = function() {
+ };
+ var pageDownHandler = () => {
// Go to the next page if we are fit-to-page.
if (this.viewport_.fittingType == Viewport.FittingType.FIT_TO_PAGE) {
this.viewport_.goToPage(this.viewport_.getMostVisiblePage() + 1);
@@ -294,7 +295,7 @@ PDFViewer.prototype = {
position.y += this.viewport.size.height;
this.viewport.position = position;
}
- }.bind(this);
+ };
switch (e.keyCode) {
case 9: // Tab key.
@@ -717,10 +718,10 @@ PDFViewer.prototype = {
// Throttle number of pinch events to one per frame.
if (!this.sentPinchEvent_) {
this.sentPinchEvent_ = true;
- window.requestAnimationFrame(function() {
+ window.requestAnimationFrame(() => {
this.sentPinchEvent_ = false;
this.viewport_.pinchZoom(e);
- }.bind(this));
+ });
}
},
@@ -732,9 +733,9 @@ PDFViewer.prototype = {
onPinchEnd_: function(e) {
// Using rAF for pinch end prevents pinch updates scheduled by rAF getting
// sent after the pinch end.
- window.requestAnimationFrame(function() {
+ window.requestAnimationFrame(() => {
this.viewport_.pinchZoomEnd(e);
- }.bind(this));
+ });
},
/**
@@ -849,7 +850,7 @@ PDFViewer.prototype = {
this.loadState_ = LoadState.LOADING;
if (!this.inPrintPreviewMode_) {
this.inPrintPreviewMode_ = true;
- this.viewport_.fitToPage();
+ this.zoomToolbar_.forceFitToPage();
}
// Stash the scroll location so that it can be restored when the new
diff --git a/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js b/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js
index fd5e2e1559c..a133b5268f5 100644
--- a/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js
+++ b/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js
@@ -53,7 +53,7 @@ function PDFScriptingAPI(window, plugin) {
this.pendingScriptingMessages_ = [];
this.setPlugin(plugin);
- window.addEventListener('message', function(event) {
+ window.addEventListener('message', event => {
if (event.origin != 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai' &&
event.origin != 'chrome://print') {
console.error(
@@ -95,7 +95,7 @@ function PDFScriptingAPI(window, plugin) {
this.keyEventCallback_(DeserializeKeyEvent(event.data.keyEvent));
break;
}
- }.bind(this), false);
+ }, false);
}
PDFScriptingAPI.prototype = {
diff --git a/chromium/chrome/browser/resources/pdf/toolbar_manager.js b/chromium/chrome/browser/resources/pdf/toolbar_manager.js
index 958b9ee3946..6fa82bf92d9 100644
--- a/chromium/chrome/browser/resources/pdf/toolbar_manager.js
+++ b/chromium/chrome/browser/resources/pdf/toolbar_manager.js
@@ -233,9 +233,9 @@ ToolbarManager.prototype = {
return;
this.toolbar_.hide();
this.sideToolbarAllowedOnly_ = true;
- this.sideToolbarAllowedOnlyTimer_ = this.window_.setTimeout(function() {
+ this.sideToolbarAllowedOnlyTimer_ = this.window_.setTimeout(() => {
this.sideToolbarAllowedOnlyTimer_ = null;
- }.bind(this), FORCE_HIDE_TIMEOUT);
+ }, FORCE_HIDE_TIMEOUT);
},
/**
diff --git a/chromium/chrome/browser/resources/pdf/viewport.js b/chromium/chrome/browser/resources/pdf/viewport.js
index 54f166bc6d4..358922c606b 100644
--- a/chromium/chrome/browser/resources/pdf/viewport.js
+++ b/chromium/chrome/browser/resources/pdf/viewport.js
@@ -397,10 +397,10 @@ Viewport.prototype = {
newZoom = Math.max(
Viewport.ZOOM_FACTOR_RANGE.min,
Math.min(newZoom, Viewport.ZOOM_FACTOR_RANGE.max));
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.setZoomInternal_(newZoom);
this.updateViewport_();
- }.bind(this));
+ });
},
/**
@@ -409,7 +409,7 @@ Viewport.prototype = {
* @param {number} oldBrowserZoom the previous value of the browser zoom.
*/
updateZoomFromBrowserChange: function(oldBrowserZoom) {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
// Record the scroll position (relative to the top-left of the window).
var oldZoom = oldBrowserZoom * this.internalZoom_;
var currentScrollPos = {
@@ -423,7 +423,7 @@ Viewport.prototype = {
y: currentScrollPos.y * this.zoom
};
this.updateViewport_();
- }.bind(this));
+ });
},
/**
@@ -565,7 +565,7 @@ Viewport.prototype = {
* Zoom the viewport so that the page-width consumes the entire viewport.
*/
fitToWidth: function() {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.fittingType_ = Viewport.FittingType.FIT_TO_WIDTH;
if (!this.documentDimensions_)
return;
@@ -575,7 +575,7 @@ Viewport.prototype = {
this.computeFittingZoom_(this.documentDimensions_, true));
var page = this.getMostVisiblePage();
this.updateViewport_();
- }.bind(this));
+ });
},
/**
@@ -586,7 +586,7 @@ Viewport.prototype = {
* should remain at the current scroll position.
*/
fitToPageInternal_: function(scrollToTopOfPage) {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.fittingType_ = Viewport.FittingType.FIT_TO_PAGE;
if (!this.documentDimensions_)
return;
@@ -601,7 +601,7 @@ Viewport.prototype = {
this.position = {x: 0, y: this.pageDimensions_[page].y * this.zoom};
}
this.updateViewport_();
- }.bind(this));
+ });
},
/**
@@ -616,7 +616,7 @@ Viewport.prototype = {
* Zoom out to the next predefined zoom level.
*/
zoomOut: function() {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.fittingType_ = Viewport.FittingType.NONE;
var nextZoom = Viewport.ZOOM_FACTORS[0];
for (var i = 0; i < Viewport.ZOOM_FACTORS.length; i++) {
@@ -625,14 +625,14 @@ Viewport.prototype = {
}
this.setZoomInternal_(nextZoom);
this.updateViewport_();
- }.bind(this));
+ });
},
/**
* Zoom in to the next predefined zoom level.
*/
zoomIn: function() {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.fittingType_ = Viewport.FittingType.NONE;
var nextZoom = Viewport.ZOOM_FACTORS[Viewport.ZOOM_FACTORS.length - 1];
for (var i = Viewport.ZOOM_FACTORS.length - 1; i >= 0; i--) {
@@ -641,7 +641,7 @@ Viewport.prototype = {
}
this.setZoomInternal_(nextZoom);
this.updateViewport_();
- }.bind(this));
+ });
},
/**
@@ -649,7 +649,7 @@ Viewport.prototype = {
* @param {!Object} e The pinch event.
*/
pinchZoom: function(e) {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.pinchPhase_ = e.direction == 'out' ?
Viewport.PinchPhase.PINCH_UPDATE_ZOOM_OUT :
Viewport.PinchPhase.PINCH_UPDATE_ZOOM_IN;
@@ -684,7 +684,7 @@ Viewport.prototype = {
this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center));
this.updateViewport_();
this.prevScale_ = e.startScaleRatio;
- }.bind(this));
+ });
},
pinchZoomStart: function(e) {
@@ -701,14 +701,14 @@ Viewport.prototype = {
},
pinchZoomEnd: function(e) {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
this.pinchPhase_ = Viewport.PinchPhase.PINCH_END;
var scaleDelta = e.startScaleRatio / this.prevScale_;
this.pinchCenter_ = e.center;
this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center));
this.updateViewport_();
- }.bind(this));
+ });
this.pinchPhase_ = Viewport.PinchPhase.PINCH_NONE;
this.pinchPanVector_ = null;
@@ -721,7 +721,7 @@ Viewport.prototype = {
* @param {number} page the index of the page to go to. zero-based.
*/
goToPage: function(page) {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
if (this.pageDimensions_.length === 0)
return;
if (page < 0)
@@ -740,7 +740,7 @@ Viewport.prototype = {
y: dimensions.y * this.zoom - toolbarOffset
};
this.updateViewport_();
- }.bind(this));
+ });
},
/**
@@ -748,7 +748,7 @@ Viewport.prototype = {
* @param {Object} documentDimensions the dimensions of the document
*/
setDocumentDimensions: function(documentDimensions) {
- this.mightZoom_(function() {
+ this.mightZoom_(() => {
var initialDimensions = !this.documentDimensions_;
this.documentDimensions_ = documentDimensions;
this.pageDimensions_ = this.documentDimensions_.pageDimensions;
@@ -760,7 +760,7 @@ Viewport.prototype = {
}
this.contentSizeChanged_();
this.resize_();
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/pdf/zoom_manager.js b/chromium/chrome/browser/resources/pdf/zoom_manager.js
index eec9115cd84..3ca81814d94 100644
--- a/chromium/chrome/browser/resources/pdf/zoom_manager.js
+++ b/chromium/chrome/browser/resources/pdf/zoom_manager.js
@@ -145,16 +145,15 @@ class ActiveZoomManager extends ZoomManager {
if (this.floatingPointEquals(this.browserZoom_, zoom))
return;
- this.changingBrowserZoom_ =
- this.setBrowserZoomFunction_(zoom).then(function() {
- this.browserZoom_ = zoom;
- this.changingBrowserZoom_ = null;
-
- // The extension's zoom level may have changed while the browser zoom
- // change was in progress. We call back into onPdfZoomChange to ensure
- // the browser zoom is up to date.
- this.onPdfZoomChange();
- }.bind(this));
+ this.changingBrowserZoom_ = this.setBrowserZoomFunction_(zoom).then(() => {
+ this.browserZoom_ = zoom;
+ this.changingBrowserZoom_ = null;
+
+ // The extension's zoom level may have changed while the browser zoom
+ // change was in progress. We call back into onPdfZoomChange to ensure
+ // the browser zoom is up to date.
+ this.onPdfZoomChange();
+ });
}
/**
diff --git a/chromium/chrome/browser/resources/plugin_metadata/plugins_chromeos.json b/chromium/chrome/browser/resources/plugin_metadata/plugins_chromeos.json
index a920c7e0c99..d13829659a3 100644
--- a/chromium/chrome/browser/resources/plugin_metadata/plugins_chromeos.json
+++ b/chromium/chrome/browser/resources/plugin_metadata/plugins_chromeos.json
@@ -1,5 +1,5 @@
{
- "x-version": 3,
+ "x-version": 4,
"google-talk": {
"mime_types": [
],
@@ -55,5 +55,31 @@
],
"name": "Chromium PDF Viewer",
"group_name_matcher": "*Chromium PDF Viewer*"
+ },
+ "google-chrome-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Google Chrome PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chrome PDF Plugin",
+ "group_name_matcher": "*Chrome PDF Plugin*"
+ },
+ "chromium-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Chromium PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chromium PDF Plugin",
+ "group_name_matcher": "*Chromium PDF Plugin*"
}
}
diff --git a/chromium/chrome/browser/resources/plugin_metadata/plugins_linux.json b/chromium/chrome/browser/resources/plugin_metadata/plugins_linux.json
index 070130ee4ae..f337af402a5 100644
--- a/chromium/chrome/browser/resources/plugin_metadata/plugins_linux.json
+++ b/chromium/chrome/browser/resources/plugin_metadata/plugins_linux.json
@@ -1,5 +1,5 @@
{
- "x-version": 23,
+ "x-version": 25,
"google-talk": {
"mime_types": [
],
@@ -80,9 +80,9 @@
],
"versions": [
{
- "version": "26.0.0.126",
+ "version": "27.0.0.170",
"status": "up_to_date",
- "reference": "https://helpx.adobe.com/security/products/flash-player/apsb17-17.html"
+ "reference": "https://helpx.adobe.com/security/products/flash-player/apsb17-32.html"
}
],
"lang": "en-US",
@@ -136,5 +136,31 @@
],
"name": "Chromium PDF Viewer",
"group_name_matcher": "*Chromium PDF Viewer*"
+ },
+ "google-chrome-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Google Chrome PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chrome PDF Plugin",
+ "group_name_matcher": "*Chrome PDF Plugin*"
+ },
+ "chromium-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Chromium PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chromium PDF Plugin",
+ "group_name_matcher": "*Chromium PDF Plugin*"
}
}
diff --git a/chromium/chrome/browser/resources/plugin_metadata/plugins_mac.json b/chromium/chrome/browser/resources/plugin_metadata/plugins_mac.json
index e5239be3682..fc04e3f285e 100644
--- a/chromium/chrome/browser/resources/plugin_metadata/plugins_mac.json
+++ b/chromium/chrome/browser/resources/plugin_metadata/plugins_mac.json
@@ -1,5 +1,5 @@
{
- "x-version": 29,
+ "x-version": 31,
"google-talk": {
"mime_types": [
],
@@ -115,9 +115,9 @@
],
"versions": [
{
- "version": "26.0.0.126",
+ "version": "27.0.0.170",
"status": "requires_authorization",
- "reference": "https://helpx.adobe.com/security/products/flash-player/apsb17-17.html"
+ "reference": "https://helpx.adobe.com/security/products/flash-player/apsb17-32.html"
}
],
"lang": "en-US",
@@ -297,6 +297,32 @@
"name": "Chromium PDF Viewer",
"group_name_matcher": "*Chromium PDF Viewer*"
},
+ "google-chrome-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Google Chrome PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chrome PDF Plugin",
+ "group_name_matcher": "*Chrome PDF Plugin*"
+ },
+ "chromium-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Chromium PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chromium PDF Plugin",
+ "group_name_matcher": "*Chromium PDF Plugin*"
+ },
"facebook-video-calling": {
"mime_types": [
"application/skypesdk-plugin"
diff --git a/chromium/chrome/browser/resources/plugin_metadata/plugins_win.json b/chromium/chrome/browser/resources/plugin_metadata/plugins_win.json
index 0ad1506bbec..7dc26f683ac 100644
--- a/chromium/chrome/browser/resources/plugin_metadata/plugins_win.json
+++ b/chromium/chrome/browser/resources/plugin_metadata/plugins_win.json
@@ -1,5 +1,5 @@
{
- "x-version": 38,
+ "x-version": 40,
"google-talk": {
"mime_types": [
],
@@ -137,9 +137,9 @@
],
"versions": [
{
- "version": "26.0.0.126",
+ "version": "27.0.0.170",
"status": "requires_authorization",
- "reference": "https://helpx.adobe.com/security/products/flash-player/apsb17-17.html"
+ "reference": "https://helpx.adobe.com/security/products/flash-player/apsb17-32.html"
}
],
"lang": "en-US",
@@ -359,6 +359,32 @@
"name": "Chromium PDF Viewer",
"group_name_matcher": "*Chromium PDF Viewer*"
},
+ "google-chrome-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Google Chrome PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chrome PDF Plugin",
+ "group_name_matcher": "*Chrome PDF Plugin*"
+ },
+ "chromium-pdf-plugin": {
+ "mime_types": [
+ ],
+ "versions": [
+ {
+ "version": "0",
+ "status": "fully_trusted",
+ "comment": "Chromium PDF Plugin has no version information."
+ }
+ ],
+ "name": "Chromium PDF Plugin",
+ "group_name_matcher": "*Chromium PDF Plugin*"
+ },
"google-update": {
"mime-types": [
],
diff --git a/chromium/chrome/browser/resources/policy.css b/chromium/chrome/browser/resources/policy.css
index eb4f5439af8..d9b74acf519 100644
--- a/chromium/chrome/browser/resources/policy.css
+++ b/chromium/chrome/browser/resources/policy.css
@@ -2,33 +2,7 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-body {
- -webkit-margin-start: 23px;
-}
-
-body > .page {
- -webkit-margin-end: 0;
- -webkit-padding-end: 24px;
-}
-
-#filter-overlay {
- padding-bottom: 0;
- position: fixed;
- z-index: 4;
-}
-
-body header {
- left: 23px;
- max-width: none;
-}
-
-html[dir='rtl'] body header {
- right: 23px;
-}
-
-body section {
- max-width: none;
-}
+@import 'policy_common.css';
#status-box-container {
display: -webkit-flex;
@@ -54,26 +28,11 @@ div.status-entry:last-child {
margin-bottom: 0;
}
-div.label {
- -webkit-margin-end: 1em;
- white-space: nowrap;
-}
-
-#show-unset-container {
- float: right;
- text-align: right;
-}
-
-html[dir='rtl'] #show-unset-container {
+div.left-aligned-button {
float: left;
- text-align: left;
}
-div.reload-policies-button {
- float: left;
-}
-
-html[dir='rtl'] div.reload-policies-button {
+html[dir='rtl'] div.left-aligned-button {
float: right;
}
@@ -82,102 +41,6 @@ div.chrome-for-work {
display: inline-block;
}
-div.show-unset-checkbox {
- float: right;
-}
-
-html[dir='rtl'] div.show-unset-checkbox {
- float: left;
-}
-
-section.reload-show-unset-section {
- padding-bottom: 30px;
- padding-top: 15px;
-}
-
section.status-box-section {
clear: both;
-}
-
-div.table-description {
- color: rgb(100, 100, 100);
-}
-
-div.no-policies-set {
- color: rgb(180, 180, 180);
- font-size: 125%;
- margin-bottom: 10px;
- margin-top: 20px;
- text-align: center;
-}
-
-table {
- border-collapse: collapse;
- margin-bottom: 5px;
- margin-top: 17px;
- table-layout: fixed;
- width: 100%
-}
-
-section.empty > table {
- display: none;
-}
-
-section:not(.empty) > div.no-policies-set {
- display: none;
-}
-
-#main-section {
- -webkit-padding-start: 0;
-}
-
-section.policy-table-section {
- padding-bottom: 10px;
-}
-
-th,
-td {
- border: 1px solid rgb(217, 217, 217);
- padding: 7px;
-}
-
-th {
- background-color: rgb(240, 240, 240);
- font-weight: normal;
-}
-
-div.elide,
-span.value {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.toggle-expanded-value {
- padding: 0;
-}
-
-tbody.has-overflowed-value span.value {
- display: none;
-}
-
-tbody:not(.has-overflowed-value) .toggle-expanded-value {
- display: none;
-}
-
-tbody:not(.has-overflowed-value) > tr.expanded-value-container,
-tbody:not(.show-overflowed-value) > tr.expanded-value-container {
- display: none;
-}
-
-td.expanded-value {
- white-space: pre;
- word-wrap: break-word;
-}
-
-html:not(.focus-outline-visible)
-:enabled:focus:-webkit-any(input[type='checkbox'],
- input[type='radio'], button) {
- /* Cancel border-color for :focus specified in widgets.css. */
- border-color: rgba(0, 0, 0, 0.25);
-}
+} \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/policy.html b/chromium/chrome/browser/resources/policy.html
index dbf20f29c73..480bdc9d88c 100644
--- a/chromium/chrome/browser/resources/policy.html
+++ b/chromium/chrome/browser/resources/policy.html
@@ -23,7 +23,6 @@
<input id="filter" class="search-field-container" type="search"
i18n-values="placeholder:filterPlaceholder;
aria-label:filterPlaceholder" incremental>
- </input>
</header>
</div>
<div class="page">
@@ -31,16 +30,20 @@
<h1 i18n-content="title"></h1>
</header>
<section class="reload-show-unset-section">
- <div class="reload-policies-button">
+ <div class="left-aligned-button">
<button id="reload-policies" i18n-content="reloadPolicies"></button>
</div>
+ <div class="left-aligned-button">
+ <button id="export-policies" i18n-content="exportPoliciesJSON">
+ </button>
+ </div>
<div class="chrome-for-work">
<a href="http://g.co/chromeent/learn" target="_blank">
<span i18n-content="chromeForWork"></span></a>
</div>
<div id="show-unset-container" class="show-unset-checkbox">
<label>
- <input id="show-unset" type="checkbox"></input>
+ <input id="show-unset" type="checkbox">
<span i18n-content="showUnset"></span>
</label>
</div>
@@ -132,5 +135,6 @@
<script src="chrome://policy/strings.js"></script>
<script src="chrome://resources/js/i18n_template.js"></script>
+<script src="chrome://policy/policy_base.js"></script>
<script src="chrome://policy/policy.js"></script>
</html>
diff --git a/chromium/chrome/browser/resources/policy.js b/chromium/chrome/browser/resources/policy.js
index a46ff41aad9..7f9a6344911 100644
--- a/chromium/chrome/browser/resources/policy.js
+++ b/chromium/chrome/browser/resources/policy.js
@@ -1,579 +1,6 @@
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('policy', function() {
-
- /**
- * A hack to check if we are displaying the mobile version of this page by
- * checking if the first column is hidden.
- * @return {boolean} True if this is the mobile version.
- */
- var isMobilePage = function() {
- return document.defaultView
- .getComputedStyle(document.querySelector('.scope-column'))
- .display == 'none';
- };
-
- /**
- * A box that shows the status of cloud policy for a device or user.
- * @constructor
- * @extends {HTMLFieldSetElement}
- */
- var StatusBox = cr.ui.define(function() {
- var node = $('status-box-template').cloneNode(true);
- node.removeAttribute('id');
- return node;
- });
-
- StatusBox.prototype = {
- // Set up the prototype chain.
- __proto__: HTMLFieldSetElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {},
-
- /**
- * Populate the box with the given cloud policy status.
- * @param {string} scope The policy scope, either "device" or "user".
- * @param {Object} status Dictionary with information about the status.
- */
- initialize: function(scope, status) {
- if (scope == 'device') {
- // For device policy, set the appropriate title and populate the topmost
- // status item with the domain the device is enrolled into.
- this.querySelector('.legend').textContent =
- loadTimeData.getString('statusDevice');
- var enrollmentDomain =
- this.querySelector('.enterprise-enrollment-domain');
- enrollmentDomain.textContent = status.enterpriseEnrollmentDomain;
- enrollmentDomain.parentElement.hidden = false;
- var displayDomain = this.querySelector('.enterprise-display-domain');
- displayDomain.textContent = status.enterpriseDisplayDomain;
- displayDomain.parentElement.hidden = false;
-
- // Populate the device naming information.
- // Populate the asset identifier.
- var assetId = this.querySelector('.asset-id');
- assetId.textContent =
- status.assetId || loadTimeData.getString('notSpecified');
- assetId.parentElement.hidden = false;
-
- // Populate the device location.
- var location = this.querySelector('.location');
- location.textContent =
- status.location || loadTimeData.getString('notSpecified');
- location.parentElement.hidden = false;
-
- // Populate the directory API ID.
- var directoryApiId = this.querySelector('.directory-api-id');
- directoryApiId.textContent =
- status.directoryApiId || loadTimeData.getString('notSpecified');
- directoryApiId.parentElement.hidden = false;
- } else {
- // For user policy, set the appropriate title and populate the topmost
- // status item with the username that policies apply to.
- this.querySelector('.legend').textContent =
- loadTimeData.getString('statusUser');
- // Populate the topmost item with the username.
- var username = this.querySelector('.username');
- username.textContent = status.username;
- username.parentElement.hidden = false;
- }
- // Populate all remaining items.
- this.querySelector('.client-id').textContent = status.clientId || '';
- this.querySelector('.time-since-last-refresh').textContent =
- status.timeSinceLastRefresh || '';
- this.querySelector('.refresh-interval').textContent =
- status.refreshInterval || '';
- this.querySelector('.status').textContent = status.status || '';
- },
- };
-
- /**
- * A single policy's entry in the policy table.
- * @constructor
- * @extends {HTMLTableSectionElement}
- */
- var Policy = cr.ui.define(function() {
- var node = $('policy-template').cloneNode(true);
- node.removeAttribute('id');
- return node;
- });
-
- Policy.prototype = {
- // Set up the prototype chain.
- __proto__: HTMLTableSectionElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- this.updateToggleExpandedValueText_();
- this.querySelector('.toggle-expanded-value')
- .addEventListener('click', this.toggleExpandedValue_.bind(this));
- },
-
- /**
- * Populate the table columns with information about the policy name, value
- * and status.
- * @param {string} name The policy name.
- * @param {Object} value Dictionary with information about the policy value.
- * @param {boolean} unknown Whether the policy name is not recognized.
- */
- initialize: function(name, value, unknown) {
- this.name = name;
- this.unset = !value;
-
- // Populate the name column.
- this.querySelector('.name').textContent = name;
-
- // Populate the remaining columns with policy scope, level and value if a
- // value has been set. Otherwise, leave them blank.
- if (value) {
- this.querySelector('.scope').textContent = loadTimeData.getString(
- value.scope == 'user' ? 'scopeUser' : 'scopeDevice');
- this.querySelector('.level').textContent = loadTimeData.getString(
- value.level == 'recommended' ? 'levelRecommended' :
- 'levelMandatory');
- this.querySelector('.source').textContent =
- loadTimeData.getString(value.source);
- this.querySelector('.value').textContent = value.value;
- this.querySelector('.expanded-value').textContent = value.value;
- }
-
- // Populate the status column.
- var status;
- if (!value) {
- // If the policy value has not been set, show an error message.
- status = loadTimeData.getString('unset');
- } else if (unknown) {
- // If the policy name is not recognized, show an error message.
- status = loadTimeData.getString('unknown');
- } else if (value.error) {
- // If an error occurred while parsing the policy value, show the error
- // message.
- status = value.error;
- } else {
- // Otherwise, indicate that the policy value was parsed correctly.
- status = loadTimeData.getString('ok');
- }
- this.querySelector('.status').textContent = status;
-
- if (isMobilePage()) {
- // The number of columns which are hidden by the css file for the mobile
- // (Android) version of this page.
- /** @const */ var HIDDEN_COLUMNS_IN_MOBILE_VERSION = 2;
-
- var expandedValue = this.querySelector('.expanded-value');
- expandedValue.setAttribute(
- 'colspan',
- expandedValue.colSpan - HIDDEN_COLUMNS_IN_MOBILE_VERSION);
- }
- },
-
- /**
- * Check the table columns for overflow. Most columns are automatically
- * elided when overflow occurs. The only action required is to add a tooltip
- * that shows the complete content. The value column is an exception. If
- * overflow occurs here, the contents is replaced with a link that toggles
- * the visibility of an additional row containing the complete value.
- */
- checkOverflow: function() {
- // Set a tooltip on all overflowed columns except the value column.
- var divs = this.querySelectorAll('div.elide');
- for (var i = 0; i < divs.length; i++) {
- var div = divs[i];
- div.title = div.offsetWidth < div.scrollWidth ? div.textContent : '';
- }
-
- // Cache the width of the value column's contents when it is first shown.
- // This is required to be able to check whether the contents would still
- // overflow the column once it has been hidden and replaced by a link.
- var valueContainer = this.querySelector('.value-container');
- if (valueContainer.valueWidth == undefined) {
- valueContainer.valueWidth =
- valueContainer.querySelector('.value').offsetWidth;
- }
-
- // Determine whether the contents of the value column overflows. The
- // visibility of the contents, replacement link and additional row
- // containing the complete value that depend on this are handled by CSS.
- if (valueContainer.offsetWidth < valueContainer.valueWidth)
- this.classList.add('has-overflowed-value');
- else
- this.classList.remove('has-overflowed-value');
- },
-
- /**
- * Update the text of the link that toggles the visibility of an additional
- * row containing the complete policy value, depending on the toggle state.
- * @private
- */
- updateToggleExpandedValueText_: function(event) {
- this.querySelector('.toggle-expanded-value').textContent =
- loadTimeData.getString(
- this.classList.contains('show-overflowed-value') ?
- 'hideExpandedValue' :
- 'showExpandedValue');
- },
-
- /**
- * Toggle the visibility of an additional row containing the complete policy
- * value.
- * @private
- */
- toggleExpandedValue_: function() {
- this.classList.toggle('show-overflowed-value');
- this.updateToggleExpandedValueText_();
- },
- };
-
- /**
- * A table of policies and their values.
- * @constructor
- * @extends {HTMLTableElement}
- */
- var PolicyTable = cr.ui.define('tbody');
-
- PolicyTable.prototype = {
- // Set up the prototype chain.
- __proto__: HTMLTableElement.prototype,
-
- /**
- * Initialization function for the cr.ui framework.
- */
- decorate: function() {
- this.policies_ = {};
- this.filterPattern_ = '';
- window.addEventListener('resize', this.checkOverflow_.bind(this));
- },
-
- /**
- * Initialize the list of all known policies.
- * @param {Object} names Dictionary containing all known policy names.
- */
- setPolicyNames: function(names) {
- this.policies_ = names;
- this.setPolicyValues({});
- },
-
- /**
- * Populate the table with the currently set policy values and any errors
- * detected while parsing these.
- * @param {Object} values Dictionary containing the current policy values.
- */
- setPolicyValues: function(values) {
- // Remove all policies from the table.
- var policies = this.getElementsByTagName('tbody');
- while (policies.length > 0)
- this.removeChild(policies.item(0));
-
- // First, add known policies whose value is currently set.
- var unset = [];
- for (var name in this.policies_) {
- if (name in values)
- this.setPolicyValue_(name, values[name], false);
- else
- unset.push(name);
- }
-
- // Second, add policies whose value is currently set but whose name is not
- // recognized.
- for (var name in values) {
- if (!(name in this.policies_))
- this.setPolicyValue_(name, values[name], true);
- }
-
- // Finally, add known policies whose value is not currently set.
- for (var i = 0; i < unset.length; i++)
- this.setPolicyValue_(unset[i], undefined, false);
-
- // Filter the policies.
- this.filter();
- },
-
- /**
- * Set the filter pattern. Only policies whose name contains |pattern| are
- * shown in the policy table. The filter is case insensitive. It can be
- * disabled by setting |pattern| to an empty string.
- * @param {string} pattern The filter pattern.
- */
- setFilterPattern: function(pattern) {
- this.filterPattern_ = pattern.toLowerCase();
- this.filter();
- },
-
- /**
- * Filter policies. Only policies whose name contains the filter pattern are
- * shown in the table. Furthermore, policies whose value is not currently
- * set are only shown if the corresponding checkbox is checked.
- */
- filter: function() {
- var showUnset = $('show-unset').checked;
- var policies = this.getElementsByTagName('tbody');
- for (var i = 0; i < policies.length; i++) {
- var policy = policies[i];
- policy.hidden = policy.unset && !showUnset ||
- policy.name.toLowerCase().indexOf(this.filterPattern_) == -1;
- }
- if (this.querySelector('tbody:not([hidden])'))
- this.parentElement.classList.remove('empty');
- else
- this.parentElement.classList.add('empty');
- setTimeout(this.checkOverflow_.bind(this), 0);
- },
-
- /**
- * Check the table columns for overflow.
- * @private
- */
- checkOverflow_: function() {
- var policies = this.getElementsByTagName('tbody');
- for (var i = 0; i < policies.length; i++) {
- if (!policies[i].hidden)
- policies[i].checkOverflow();
- }
- },
-
- /**
- * Add a policy with the given |name| and |value| to the table.
- * @param {string} name The policy name.
- * @param {Object} value Dictionary with information about the policy value.
- * @param {boolean} unknown Whether the policy name is not recoginzed.
- * @private
- */
- setPolicyValue_: function(name, value, unknown) {
- var policy = new Policy;
- policy.initialize(name, value, unknown);
- this.appendChild(policy);
- },
- };
-
- /**
- * A singelton object that handles communication between browser and WebUI.
- * @constructor
- */
- function Page() {}
-
- // Make Page a singleton.
- cr.addSingletonGetter(Page);
-
- /**
- * Provide a list of all known policies to the UI. Called by the browser on
- * page load.
- * @param {Object} names Dictionary containing all known policy names.
- */
- Page.setPolicyNames = function(names) {
- var page = this.getInstance();
-
- // Clear all policy tables.
- page.mainSection.innerHTML = '';
- page.policyTables = {};
-
- // Create tables and set known policy names for Chrome and extensions.
- if (names.hasOwnProperty('chromePolicyNames')) {
- var table = page.appendNewTable('chrome', 'Chrome policies', '');
- table.setPolicyNames(names.chromePolicyNames);
- }
-
- if (names.hasOwnProperty('extensionPolicyNames')) {
- for (var ext in names.extensionPolicyNames) {
- var table = page.appendNewTable(
- 'extension-' + ext, names.extensionPolicyNames[ext].name,
- 'ID: ' + ext);
- table.setPolicyNames(names.extensionPolicyNames[ext].policyNames);
- }
- }
- };
-
- /**
- * Provide a list of the currently set policy values and any errors detected
- * while parsing these to the UI. Called by the browser on page load and
- * whenever policy values change.
- * @param {Object} values Dictionary containing the current policy values.
- */
- Page.setPolicyValues = function(values) {
- var page = this.getInstance();
- if (values.hasOwnProperty('chromePolicies')) {
- var table = page.policyTables['chrome'];
- table.setPolicyValues(values.chromePolicies);
- }
-
- if (values.hasOwnProperty('extensionPolicies')) {
- for (var extensionId in values.extensionPolicies) {
- var table = page.policyTables['extension-' + extensionId];
- if (table)
- table.setPolicyValues(values.extensionPolicies[extensionId]);
- }
- }
- };
-
- /**
- * Provide the current cloud policy status to the UI. Called by the browser on
- * page load if cloud policy is present and whenever the status changes.
- * @param {Object} status Dictionary containing the current policy status.
- */
- Page.setStatus = function(status) {
- this.getInstance().setStatus(status);
- };
-
- /**
- * Notify the UI that a request to reload policy values has completed. Called
- * by the browser after a request to reload policy has been sent by the UI.
- */
- Page.reloadPoliciesDone = function() {
- this.getInstance().reloadPoliciesDone();
- };
-
- Page.prototype = {
- /**
- * Main initialization function. Called by the browser on page load.
- */
- initialize: function() {
- cr.ui.FocusOutlineManager.forDocument(document);
-
- this.mainSection = $('main-section');
- this.policyTables = {};
-
- // Place the initial focus on the filter input field.
- $('filter').focus();
-
- var self = this;
- $('filter').onsearch = function(event) {
- for (policyTable in self.policyTables) {
- self.policyTables[policyTable].setFilterPattern(this.value);
- }
- };
- $('reload-policies').onclick = function(event) {
- this.disabled = true;
- chrome.send('reloadPolicies');
- };
-
- $('show-unset').onchange = function() {
- for (policyTable in self.policyTables) {
- self.policyTables[policyTable].filter();
- }
- };
-
- // Notify the browser that the page has loaded, causing it to send the
- // list of all known policies, the current policy values and the cloud
- // policy status.
- chrome.send('initialized');
- },
-
- /**
- * Creates a new policy table section, adds the section to the page,
- * and returns the new table from that section.
- * @param {string} id The key for storing the new table in policyTables.
- * @param {string} label_title Title for this policy table.
- * @param {string} label_content Description for the policy table.
- * @return {Element} The newly created table.
- */
- appendNewTable: function(id, label_title, label_content) {
- var newSection =
- this.createPolicyTableSection(id, label_title, label_content);
- this.mainSection.appendChild(newSection);
- return this.policyTables[id];
- },
-
- /**
- * Creates a new section containing a title, description and table of
- * policies.
- * @param {id} id The key for storing the new table in policyTables.
- * @param {string} label_title Title for this policy table.
- * @param {string} label_content Description for the policy table.
- * @return {Element} The newly created section.
- */
- createPolicyTableSection: function(id, label_title, label_content) {
- var section = document.createElement('section');
- section.setAttribute('class', 'policy-table-section');
-
- // Add title and description.
- var title = window.document.createElement('h3');
- title.textContent = label_title;
- section.appendChild(title);
-
- if (label_content) {
- var description = window.document.createElement('div');
- description.classList.add('table-description');
- description.textContent = label_content;
- section.appendChild(description);
- }
-
- // Add 'No Policies Set' element.
- var noPolicies = window.document.createElement('div');
- noPolicies.classList.add('no-policies-set');
- noPolicies.textContent = loadTimeData.getString('noPoliciesSet');
- section.appendChild(noPolicies);
-
- // Add table of policies.
- var newTable = this.createPolicyTable();
- this.policyTables[id] = newTable;
- section.appendChild(newTable);
-
- return section;
- },
-
- /**
- * Creates a new table for displaying policies.
- * @return {Element} The newly created table.
- */
- createPolicyTable: function() {
- var newTable = window.document.createElement('table');
- var tableHead = window.document.createElement('thead');
- var tableRow = window.document.createElement('tr');
- var tableHeadings =
- ['Scope', 'Level', 'Source', 'Name', 'Value', 'Status'];
- for (var i = 0; i < tableHeadings.length; i++) {
- var tableHeader = window.document.createElement('th');
- tableHeader.classList.add(tableHeadings[i].toLowerCase() + '-column');
- tableHeader.textContent =
- loadTimeData.getString('header' + tableHeadings[i]);
- tableRow.appendChild(tableHeader);
- }
- tableHead.appendChild(tableRow);
- newTable.appendChild(tableHead);
- cr.ui.decorate(newTable, PolicyTable);
- return newTable;
- },
-
- /**
- * Update the status section of the page to show the current cloud policy
- * status.
- * @param {Object} status Dictionary containing the current policy status.
- */
- setStatus: function(status) {
- // Remove any existing status boxes.
- var container = $('status-box-container');
- while (container.firstChild)
- container.removeChild(container.firstChild);
- // Hide the status section.
- var section = $('status-section');
- section.hidden = true;
-
- // Add a status box for each scope that has a cloud policy status.
- for (var scope in status) {
- var box = new StatusBox;
- box.initialize(scope, status[scope]);
- container.appendChild(box);
- // Show the status section.
- section.hidden = false;
- }
- },
-
- /**
- * Re-enable the reload policies button when the previous request to reload
- * policies values has completed.
- */
- reloadPoliciesDone: function() {
- $('reload-policies').disabled = false;
- },
- };
-
- return {Page: Page};
-});
// Have the main initialization function be called when the page finishes
// loading.
diff --git a/chromium/chrome/browser/resources/policy_base.js b/chromium/chrome/browser/resources/policy_base.js
new file mode 100644
index 00000000000..8994b97bea4
--- /dev/null
+++ b/chromium/chrome/browser/resources/policy_base.js
@@ -0,0 +1,581 @@
+// Copyright (c) 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('policy', function() {
+
+ /**
+ * A hack to check if we are displaying the mobile version of this page by
+ * checking if the first column is hidden.
+ * @return {boolean} True if this is the mobile version.
+ */
+ var isMobilePage = function() {
+ return document.defaultView
+ .getComputedStyle(document.querySelector('.scope-column'))
+ .display == 'none';
+ };
+
+ /**
+ * A box that shows the status of cloud policy for a device or user.
+ * @constructor
+ * @extends {HTMLFieldSetElement}
+ */
+ var StatusBox = cr.ui.define(function() {
+ var node = $('status-box-template').cloneNode(true);
+ node.removeAttribute('id');
+ return node;
+ });
+
+ StatusBox.prototype = {
+ // Set up the prototype chain.
+ __proto__: HTMLFieldSetElement.prototype,
+
+ /**
+ * Initialization function for the cr.ui framework.
+ */
+ decorate: function() {},
+
+ /**
+ * Populate the box with the given cloud policy status.
+ * @param {string} scope The policy scope, either "device" or "user".
+ * @param {Object} status Dictionary with information about the status.
+ */
+ initialize: function(scope, status) {
+ if (scope == 'device') {
+ // For device policy, set the appropriate title and populate the topmost
+ // status item with the domain the device is enrolled into.
+ this.querySelector('.legend').textContent =
+ loadTimeData.getString('statusDevice');
+ var enrollmentDomain =
+ this.querySelector('.enterprise-enrollment-domain');
+ enrollmentDomain.textContent = status.enterpriseEnrollmentDomain;
+ enrollmentDomain.parentElement.hidden = false;
+ var displayDomain = this.querySelector('.enterprise-display-domain');
+ displayDomain.textContent = status.enterpriseDisplayDomain;
+ displayDomain.parentElement.hidden = false;
+
+ // Populate the device naming information.
+ // Populate the asset identifier.
+ var assetId = this.querySelector('.asset-id');
+ assetId.textContent =
+ status.assetId || loadTimeData.getString('notSpecified');
+ assetId.parentElement.hidden = false;
+
+ // Populate the device location.
+ var location = this.querySelector('.location');
+ location.textContent =
+ status.location || loadTimeData.getString('notSpecified');
+ location.parentElement.hidden = false;
+
+ // Populate the directory API ID.
+ var directoryApiId = this.querySelector('.directory-api-id');
+ directoryApiId.textContent =
+ status.directoryApiId || loadTimeData.getString('notSpecified');
+ directoryApiId.parentElement.hidden = false;
+ } else {
+ // For user policy, set the appropriate title and populate the topmost
+ // status item with the username that policies apply to.
+ this.querySelector('.legend').textContent =
+ loadTimeData.getString('statusUser');
+ // Populate the topmost item with the username.
+ var username = this.querySelector('.username');
+ username.textContent = status.username;
+ username.parentElement.hidden = false;
+ }
+ // Populate all remaining items.
+ this.querySelector('.client-id').textContent = status.clientId || '';
+ this.querySelector('.time-since-last-refresh').textContent =
+ status.timeSinceLastRefresh || '';
+ this.querySelector('.refresh-interval').textContent =
+ status.refreshInterval || '';
+ this.querySelector('.status').textContent = status.status || '';
+ },
+ };
+
+ /**
+ * A single policy's entry in the policy table.
+ * @constructor
+ * @extends {HTMLTableSectionElement}
+ */
+ var Policy = cr.ui.define(function() {
+ var node = $('policy-template').cloneNode(true);
+ node.removeAttribute('id');
+ return node;
+ });
+
+ Policy.prototype = {
+ // Set up the prototype chain.
+ __proto__: HTMLTableSectionElement.prototype,
+
+ /**
+ * Initialization function for the cr.ui framework.
+ */
+ decorate: function() {
+ this.updateToggleExpandedValueText_();
+ this.querySelector('.toggle-expanded-value')
+ .addEventListener('click', this.toggleExpandedValue_.bind(this));
+ },
+
+ /**
+ * Populate the table columns with information about the policy name, value
+ * and status.
+ * @param {string} name The policy name.
+ * @param {Object} value Dictionary with information about the policy value.
+ * @param {boolean} unknown Whether the policy name is not recognized.
+ */
+ initialize: function(name, value, unknown) {
+ this.name = name;
+ this.unset = !value;
+
+ // Populate the name column.
+ this.querySelector('.name').textContent = name;
+
+ // Populate the remaining columns with policy scope, level and value if a
+ // value has been set. Otherwise, leave them blank.
+ if (value) {
+ this.querySelector('.scope').textContent = loadTimeData.getString(
+ value.scope == 'user' ? 'scopeUser' : 'scopeDevice');
+ this.querySelector('.level').textContent = loadTimeData.getString(
+ value.level == 'recommended' ? 'levelRecommended' :
+ 'levelMandatory');
+ this.querySelector('.source').textContent =
+ loadTimeData.getString(value.source);
+ this.querySelector('.value').textContent = value.value;
+ this.querySelector('.expanded-value').textContent = value.value;
+ }
+
+ // Populate the status column.
+ var status;
+ if (!value) {
+ // If the policy value has not been set, show an error message.
+ status = loadTimeData.getString('unset');
+ } else if (unknown) {
+ // If the policy name is not recognized, show an error message.
+ status = loadTimeData.getString('unknown');
+ } else if (value.error) {
+ // If an error occurred while parsing the policy value, show the error
+ // message.
+ status = value.error;
+ } else {
+ // Otherwise, indicate that the policy value was parsed correctly.
+ status = loadTimeData.getString('ok');
+ }
+ this.querySelector('.status').textContent = status;
+
+ if (isMobilePage()) {
+ // The number of columns which are hidden by the css file for the mobile
+ // (Android) version of this page.
+ /** @const */ var HIDDEN_COLUMNS_IN_MOBILE_VERSION = 2;
+
+ var expandedValue = this.querySelector('.expanded-value');
+ expandedValue.setAttribute(
+ 'colspan',
+ expandedValue.colSpan - HIDDEN_COLUMNS_IN_MOBILE_VERSION);
+ }
+ },
+
+ /**
+ * Check the table columns for overflow. Most columns are automatically
+ * elided when overflow occurs. The only action required is to add a tooltip
+ * that shows the complete content. The value column is an exception. If
+ * overflow occurs here, the contents is replaced with a link that toggles
+ * the visibility of an additional row containing the complete value.
+ */
+ checkOverflow: function() {
+ // Set a tooltip on all overflowed columns except the value column.
+ var divs = this.querySelectorAll('div.elide');
+ for (var i = 0; i < divs.length; i++) {
+ var div = divs[i];
+ div.title = div.offsetWidth < div.scrollWidth ? div.textContent : '';
+ }
+
+ // Cache the width of the value column's contents when it is first shown.
+ // This is required to be able to check whether the contents would still
+ // overflow the column once it has been hidden and replaced by a link.
+ var valueContainer = this.querySelector('.value-container');
+ if (valueContainer.valueWidth == undefined) {
+ valueContainer.valueWidth =
+ valueContainer.querySelector('.value').offsetWidth;
+ }
+
+ // Determine whether the contents of the value column overflows. The
+ // visibility of the contents, replacement link and additional row
+ // containing the complete value that depend on this are handled by CSS.
+ if (valueContainer.offsetWidth < valueContainer.valueWidth)
+ this.classList.add('has-overflowed-value');
+ else
+ this.classList.remove('has-overflowed-value');
+ },
+
+ /**
+ * Update the text of the link that toggles the visibility of an additional
+ * row containing the complete policy value, depending on the toggle state.
+ * @private
+ */
+ updateToggleExpandedValueText_: function(event) {
+ this.querySelector('.toggle-expanded-value').textContent =
+ loadTimeData.getString(
+ this.classList.contains('show-overflowed-value') ?
+ 'hideExpandedValue' :
+ 'showExpandedValue');
+ },
+
+ /**
+ * Toggle the visibility of an additional row containing the complete policy
+ * value.
+ * @private
+ */
+ toggleExpandedValue_: function() {
+ this.classList.toggle('show-overflowed-value');
+ this.updateToggleExpandedValueText_();
+ },
+ };
+
+ /**
+ * A table of policies and their values.
+ * @constructor
+ * @extends {HTMLTableElement}
+ */
+ var PolicyTable = cr.ui.define('tbody');
+
+ PolicyTable.prototype = {
+ // Set up the prototype chain.
+ __proto__: HTMLTableElement.prototype,
+
+ /**
+ * Initialization function for the cr.ui framework.
+ */
+ decorate: function() {
+ this.policies_ = {};
+ this.filterPattern_ = '';
+ window.addEventListener('resize', this.checkOverflow_.bind(this));
+ },
+
+ /**
+ * Initialize the list of all known policies.
+ * @param {Object} names Dictionary containing all known policy names.
+ */
+ setPolicyNames: function(names) {
+ this.policies_ = names;
+ this.setPolicyValues({});
+ },
+
+ /**
+ * Populate the table with the currently set policy values and any errors
+ * detected while parsing these.
+ * @param {Object} values Dictionary containing the current policy values.
+ */
+ setPolicyValues: function(values) {
+ // Remove all policies from the table.
+ var policies = this.getElementsByTagName('tbody');
+ while (policies.length > 0)
+ this.removeChild(policies.item(0));
+
+ // First, add known policies whose value is currently set.
+ var unset = [];
+ for (var name in this.policies_) {
+ if (name in values)
+ this.setPolicyValue_(name, values[name], false);
+ else
+ unset.push(name);
+ }
+
+ // Second, add policies whose value is currently set but whose name is not
+ // recognized.
+ for (var name in values) {
+ if (!(name in this.policies_))
+ this.setPolicyValue_(name, values[name], true);
+ }
+
+ // Finally, add known policies whose value is not currently set.
+ for (var i = 0; i < unset.length; i++)
+ this.setPolicyValue_(unset[i], undefined, false);
+
+ // Filter the policies.
+ this.filter();
+ },
+
+ /**
+ * Set the filter pattern. Only policies whose name contains |pattern| are
+ * shown in the policy table. The filter is case insensitive. It can be
+ * disabled by setting |pattern| to an empty string.
+ * @param {string} pattern The filter pattern.
+ */
+ setFilterPattern: function(pattern) {
+ this.filterPattern_ = pattern.toLowerCase();
+ this.filter();
+ },
+
+ /**
+ * Filter policies. Only policies whose name contains the filter pattern are
+ * shown in the table. Furthermore, policies whose value is not currently
+ * set are only shown if the corresponding checkbox is checked.
+ */
+ filter: function() {
+ var showUnset = $('show-unset').checked;
+ var policies = this.getElementsByTagName('tbody');
+ for (var i = 0; i < policies.length; i++) {
+ var policy = policies[i];
+ policy.hidden = policy.unset && !showUnset ||
+ policy.name.toLowerCase().indexOf(this.filterPattern_) == -1;
+ }
+ if (this.querySelector('tbody:not([hidden])'))
+ this.parentElement.classList.remove('empty');
+ else
+ this.parentElement.classList.add('empty');
+ setTimeout(this.checkOverflow_.bind(this), 0);
+ },
+
+ /**
+ * Check the table columns for overflow.
+ * @private
+ */
+ checkOverflow_: function() {
+ var policies = this.getElementsByTagName('tbody');
+ for (var i = 0; i < policies.length; i++) {
+ if (!policies[i].hidden)
+ policies[i].checkOverflow();
+ }
+ },
+
+ /**
+ * Add a policy with the given |name| and |value| to the table.
+ * @param {string} name The policy name.
+ * @param {Object} value Dictionary with information about the policy value.
+ * @param {boolean} unknown Whether the policy name is not recoginzed.
+ * @private
+ */
+ setPolicyValue_: function(name, value, unknown) {
+ var policy = new Policy;
+ policy.initialize(name, value, unknown);
+ this.appendChild(policy);
+ },
+ };
+
+ /**
+ * A singelton object that handles communication between browser and WebUI.
+ * @constructor
+ */
+ function Page() {}
+
+ // Make Page a singleton.
+ cr.addSingletonGetter(Page);
+
+ /**
+ * Provide a list of all known policies to the UI. Called by the browser on
+ * page load.
+ * @param {Object} names Dictionary containing all known policy names.
+ */
+ Page.setPolicyNames = function(names) {
+ var page = this.getInstance();
+
+ // Clear all policy tables.
+ page.mainSection.innerHTML = '';
+ page.policyTables = {};
+
+ // Create tables and set known policy names for Chrome and extensions.
+ if (names.hasOwnProperty('chromePolicyNames')) {
+ var table = page.appendNewTable('chrome', 'Chrome policies', '');
+ table.setPolicyNames(names.chromePolicyNames);
+ }
+
+ if (names.hasOwnProperty('extensionPolicyNames')) {
+ for (var ext in names.extensionPolicyNames) {
+ var table = page.appendNewTable(
+ 'extension-' + ext, names.extensionPolicyNames[ext].name,
+ 'ID: ' + ext);
+ table.setPolicyNames(names.extensionPolicyNames[ext].policyNames);
+ }
+ }
+ };
+
+ /**
+ * Provide a list of the currently set policy values and any errors detected
+ * while parsing these to the UI. Called by the browser on page load and
+ * whenever policy values change.
+ * @param {Object} values Dictionary containing the current policy values.
+ */
+ Page.setPolicyValues = function(values) {
+ var page = this.getInstance();
+ if (values.hasOwnProperty('chromePolicies')) {
+ var table = page.policyTables['chrome'];
+ table.setPolicyValues(values.chromePolicies);
+ }
+
+ if (values.hasOwnProperty('extensionPolicies')) {
+ for (var extensionId in values.extensionPolicies) {
+ var table = page.policyTables['extension-' + extensionId];
+ if (table)
+ table.setPolicyValues(values.extensionPolicies[extensionId]);
+ }
+ }
+ };
+
+ /**
+ * Provide the current cloud policy status to the UI. Called by the browser on
+ * page load if cloud policy is present and whenever the status changes.
+ * @param {Object} status Dictionary containing the current policy status.
+ */
+ Page.setStatus = function(status) {
+ this.getInstance().setStatus(status);
+ };
+
+ /**
+ * Notify the UI that a request to reload policy values has completed. Called
+ * by the browser after a request to reload policy has been sent by the UI.
+ */
+ Page.reloadPoliciesDone = function() {
+ this.getInstance().reloadPoliciesDone();
+ };
+
+ Page.prototype = {
+ /**
+ * Main initialization function. Called by the browser on page load.
+ */
+ initialize: function() {
+ cr.ui.FocusOutlineManager.forDocument(document);
+
+ this.mainSection = $('main-section');
+ this.policyTables = {};
+
+ // Place the initial focus on the filter input field.
+ $('filter').focus();
+
+ var self = this;
+ $('filter').onsearch = function(event) {
+ for (policyTable in self.policyTables) {
+ self.policyTables[policyTable].setFilterPattern(this.value);
+ }
+ };
+ $('reload-policies').onclick = function(event) {
+ this.disabled = true;
+ chrome.send('reloadPolicies');
+ };
+
+ $('export-policies').onclick = function(event) {
+ chrome.send('exportPoliciesJSON');
+ };
+
+ $('show-unset').onchange = function() {
+ for (policyTable in self.policyTables) {
+ self.policyTables[policyTable].filter();
+ }
+ };
+
+ // Notify the browser that the page has loaded, causing it to send the
+ // list of all known policies, the current policy values and the cloud
+ // policy status.
+ chrome.send('initialized');
+ },
+
+ /**
+ * Creates a new policy table section, adds the section to the page,
+ * and returns the new table from that section.
+ * @param {string} id The key for storing the new table in policyTables.
+ * @param {string} label_title Title for this policy table.
+ * @param {string} label_content Description for the policy table.
+ * @return {Element} The newly created table.
+ */
+ appendNewTable: function(id, label_title, label_content) {
+ var newSection =
+ this.createPolicyTableSection(id, label_title, label_content);
+ this.mainSection.appendChild(newSection);
+ return this.policyTables[id];
+ },
+
+ /**
+ * Creates a new section containing a title, description and table of
+ * policies.
+ * @param {id} id The key for storing the new table in policyTables.
+ * @param {string} label_title Title for this policy table.
+ * @param {string} label_content Description for the policy table.
+ * @return {Element} The newly created section.
+ */
+ createPolicyTableSection: function(id, label_title, label_content) {
+ var section = document.createElement('section');
+ section.setAttribute('class', 'policy-table-section');
+
+ // Add title and description.
+ var title = window.document.createElement('h3');
+ title.textContent = label_title;
+ section.appendChild(title);
+
+ if (label_content) {
+ var description = window.document.createElement('div');
+ description.classList.add('table-description');
+ description.textContent = label_content;
+ section.appendChild(description);
+ }
+
+ // Add 'No Policies Set' element.
+ var noPolicies = window.document.createElement('div');
+ noPolicies.classList.add('no-policies-set');
+ noPolicies.textContent = loadTimeData.getString('noPoliciesSet');
+ section.appendChild(noPolicies);
+
+ // Add table of policies.
+ var newTable = this.createPolicyTable();
+ this.policyTables[id] = newTable;
+ section.appendChild(newTable);
+
+ return section;
+ },
+
+ /**
+ * Creates a new table for displaying policies.
+ * @return {Element} The newly created table.
+ */
+ createPolicyTable: function() {
+ var newTable = window.document.createElement('table');
+ var tableHead = window.document.createElement('thead');
+ var tableRow = window.document.createElement('tr');
+ var tableHeadings =
+ ['Scope', 'Level', 'Source', 'Name', 'Value', 'Status'];
+ for (var i = 0; i < tableHeadings.length; i++) {
+ var tableHeader = window.document.createElement('th');
+ tableHeader.classList.add(tableHeadings[i].toLowerCase() + '-column');
+ tableHeader.textContent =
+ loadTimeData.getString('header' + tableHeadings[i]);
+ tableRow.appendChild(tableHeader);
+ }
+ tableHead.appendChild(tableRow);
+ newTable.appendChild(tableHead);
+ cr.ui.decorate(newTable, PolicyTable);
+ return newTable;
+ },
+
+ /**
+ * Update the status section of the page to show the current cloud policy
+ * status.
+ * @param {Object} status Dictionary containing the current policy status.
+ */
+ setStatus: function(status) {
+ // Remove any existing status boxes.
+ var container = $('status-box-container');
+ while (container.firstChild)
+ container.removeChild(container.firstChild);
+ // Hide the status section.
+ var section = $('status-section');
+ section.hidden = true;
+
+ // Add a status box for each scope that has a cloud policy status.
+ for (var scope in status) {
+ var box = new StatusBox;
+ box.initialize(scope, status[scope]);
+ container.appendChild(box);
+ // Show the status section.
+ section.hidden = false;
+ }
+ },
+
+ /**
+ * Re-enable the reload policies button when the previous request to reload
+ * policies values has completed.
+ */
+ reloadPoliciesDone: function() {
+ $('reload-policies').disabled = false;
+ },
+ };
+
+ return {Page: Page, PolicyTable: PolicyTable, Policy: Policy};
+});
diff --git a/chromium/chrome/browser/resources/policy_common.css b/chromium/chrome/browser/resources/policy_common.css
new file mode 100644
index 00000000000..b455641d75a
--- /dev/null
+++ b/chromium/chrome/browser/resources/policy_common.css
@@ -0,0 +1,142 @@
+/* Copyright (c) 2017 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file. */
+
+body {
+ -webkit-margin-start: 23px;
+}
+
+body > .page {
+ -webkit-margin-end: 0;
+ -webkit-padding-end: 24px;
+}
+
+#filter-overlay {
+ padding-bottom: 0;
+ position: fixed;
+ z-index: 4;
+}
+
+body header {
+ left: 23px;
+ max-width: none;
+}
+
+html[dir='rtl'] body header {
+ right: 23px;
+}
+
+body section {
+ max-width: none;
+}
+
+div.label {
+ -webkit-margin-end: 1em;
+ white-space: nowrap;
+}
+
+#show-unset-container {
+ float: right;
+ text-align: right;
+}
+
+html[dir='rtl'] #show-unset-container {
+ float: left;
+ text-align: left;
+}
+
+div.show-unset-checkbox {
+ float: right;
+}
+
+html[dir='rtl'] div.show-unset-checkbox {
+ float: left;
+}
+
+section.reload-show-unset-section {
+ padding-bottom: 30px;
+ padding-top: 15px;
+}
+
+div.table-description {
+ color: rgb(100, 100, 100);
+}
+
+div.no-policies-set {
+ color: rgb(180, 180, 180);
+ font-size: 125%;
+ margin-bottom: 10px;
+ margin-top: 20px;
+ text-align: center;
+}
+
+table {
+ border-collapse: collapse;
+ margin-bottom: 5px;
+ margin-top: 17px;
+ table-layout: fixed;
+ width: 100%
+}
+
+section.empty > table {
+ display: none;
+}
+
+section:not(.empty) > div.no-policies-set {
+ display: none;
+}
+
+#main-section {
+ -webkit-padding-start: 0;
+}
+
+section.policy-table-section {
+ padding-bottom: 10px;
+}
+
+th,
+td {
+ border: 1px solid rgb(217, 217, 217);
+ padding: 7px;
+}
+
+th {
+ background-color: rgb(240, 240, 240);
+ font-weight: normal;
+}
+
+div.elide,
+span.value {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.toggle-expanded-value {
+ padding: 0;
+}
+
+tbody.has-overflowed-value span.value {
+ display: none;
+}
+
+tbody:not(.has-overflowed-value) .toggle-expanded-value {
+ display: none;
+}
+
+tbody:not(.has-overflowed-value) > tr.expanded-value-container,
+tbody:not(.show-overflowed-value) > tr.expanded-value-container {
+ display: none;
+}
+
+td.expanded-value {
+ white-space: pre;
+ word-wrap: break-word;
+}
+
+html:not(.focus-outline-visible)
+:enabled:focus:-webkit-any(input[type='checkbox'],
+ input[type='radio'], button) {
+ /* Cancel border-color for :focus specified in widgets.css. */
+ border-color: rgba(0, 0, 0, 0.25);
+}
diff --git a/chromium/chrome/browser/resources/polymer_css_build_gn.py b/chromium/chrome/browser/resources/polymer_css_build_gn.py
deleted file mode 100755
index 14fe7c55389..00000000000
--- a/chromium/chrome/browser/resources/polymer_css_build_gn.py
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/usr/bin/env python
-# 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.
-
-import argparse
-import os
-import sys
-
-_HERE_PATH = os.path.dirname(__file__)
-_SRC_PATH = os.path.normpath(os.path.join(_HERE_PATH, '..', '..', '..'))
-_CWD = os.getcwd()
-
-sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'node'))
-import node
-import node_modules
-
-def _css_build(out_folder, input_files, output_files):
- out_path = os.path.join(_CWD, out_folder)
- in_paths = map(lambda f: os.path.join(out_path, f), input_files)
- out_paths = map(lambda f: os.path.join(out_path, f), output_files)
-
- args = ['--no-inline-includes', '-f'] + in_paths + ['-o'] + out_paths
- node.RunNode([node_modules.PathToPolymerCssBuild()] + args)
-
-
-def main():
- parser = argparse.ArgumentParser()
- parser.add_argument('--out_folder')
- parser.add_argument('--input_files', nargs='+')
- parser.add_argument('--output_files', nargs='+')
- args = parser.parse_args()
-
- _css_build(
- args.out_folder,
- input_files=args.input_files,
- output_files=args.output_files)
-
-
-if __name__ == '__main__':
- main()
diff --git a/chromium/chrome/browser/resources/print_preview/common/overlay.js b/chromium/chrome/browser/resources/print_preview/common/overlay.js
index dc083062fee..2680aad2853 100644
--- a/chromium/chrome/browser/resources/print_preview/common/overlay.js
+++ b/chromium/chrome/browser/resources/print_preview/common/overlay.js
@@ -71,9 +71,9 @@ cr.define('print_preview', function() {
return;
if (isVisible) {
setIsVisible(this.getElement(), true);
- setTimeout(function(element) {
- element.classList.remove('transparent');
- }.bind(this, this.getElement()), 0);
+ setTimeout(() => {
+ this.getElement().classList.remove('transparent');
+ }, 0);
} else {
this.getElement().classList.add('transparent');
}
diff --git a/chromium/chrome/browser/resources/print_preview/common/search_box.css b/chromium/chrome/browser/resources/print_preview/common/search_box.css
index bbc82e1b976..a3c7b5fba0d 100644
--- a/chromium/chrome/browser/resources/print_preview/common/search_box.css
+++ b/chromium/chrome/browser/resources/print_preview/common/search_box.css
@@ -3,18 +3,18 @@
* found in the LICENSE file. */
.search-box {
- -webkit-user-select: none;
position: relative;
+ user-select: none;
}
.search-box-icon {
- -webkit-user-select: none;
display: inline-block;
height: 1em;
left: 8px;
position: absolute;
right: 8px;
top: 6px;
+ user-select: none;
width: 1em;
}
diff --git a/chromium/chrome/browser/resources/print_preview/data/app_state.js b/chromium/chrome/browser/resources/print_preview/data/app_state.js
index 2cef90c6b76..06541447351 100644
--- a/chromium/chrome/browser/resources/print_preview/data/app_state.js
+++ b/chromium/chrome/browser/resources/print_preview/data/app_state.js
@@ -11,7 +11,6 @@ cr.exportPath('print_preview');
print_preview.AppStateField = {
VERSION: 'version',
RECENT_DESTINATIONS: 'recentDestinations',
- IS_GCP_PROMO_DISMISSED: 'isGcpPromoDismissed',
DPI: 'dpi',
MEDIA_SIZE: 'mediaSize',
MARGINS_TYPE: 'marginsType',
@@ -90,7 +89,6 @@ cr.define('print_preview', function() {
*/
this.state_ = {};
this.state_[print_preview.AppStateField.VERSION] = AppState.VERSION_;
- this.state_[print_preview.AppStateField.IS_GCP_PROMO_DISMISSED] = true;
this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] = [];
/**
@@ -150,11 +148,6 @@ cr.define('print_preview', function() {
return this.state_[print_preview.AppStateField.RECENT_DESTINATIONS];
},
- /** @return {boolean} Whether the GCP promotion has been dismissed. */
- get isGcpPromoDismissed() {
- return this.state_[print_preview.AppStateField.IS_GCP_PROMO_DISMISSED];
- },
-
/**
* @param {!print_preview.AppStateField} field App state field to check if
* set.
@@ -196,7 +189,6 @@ cr.define('print_preview', function() {
}
} else {
// Set some state defaults.
- this.state_[print_preview.AppStateField.IS_GCP_PROMO_DISMISSED] = false;
this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] = [];
}
if (!this.state_[print_preview.AppStateField.RECENT_DESTINATIONS]) {
@@ -286,19 +278,6 @@ cr.define('print_preview', function() {
},
/**
- * Persists whether the GCP promotion has been dismissed.
- * @param {boolean} isGcpPromoDismissed Whether the GCP promotion has been
- * dismissed.
- */
- persistIsGcpPromoDismissed: function(isGcpPromoDismissed) {
- if (!this.isInitialized_)
- return;
- this.state_[print_preview.AppStateField.IS_GCP_PROMO_DISMISSED] =
- isGcpPromoDismissed;
- this.persist_();
- },
-
- /**
* Calls into the native layer to persist the application state.
* @private
*/
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 236ea49e8ba..8ef5101ccb1 100644
--- a/chromium/chrome/browser/resources/print_preview/data/destination_store.js
+++ b/chromium/chrome/browser/resources/print_preview/data/destination_store.js
@@ -907,18 +907,6 @@ cr.define('print_preview', function() {
},
/**
- * @return {boolean} Whether only default cloud destinations have been
- * loaded.
- */
- hasOnlyDefaultCloudDestinations: function() {
- // TODO: Move the logic to print_preview.
- return this.destinations_.every(function(dest) {
- return dest.isLocal ||
- dest.id == print_preview.Destination.GooglePromotedId.DOCS;
- });
- },
-
- /**
* @param {print_preview.Destination} destination Destination to select.
*/
selectDestination: function(destination) {
@@ -1017,35 +1005,33 @@ cr.define('print_preview', function() {
destination.provisionalType ==
print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION,
'Provisional type cannot be resolved.');
- this.nativeLayer_.grantExtensionPrinterAccess(destination.id).then(
- /**
- * @param {!print_preview.ProvisionalDestinationInfo}
- * destinationInfo Information about the resolved printer.
- */
- function(destinationInfo) {
- /**
- * Removes the destination from the store and replaces it with a
- * destination created from the resolved destination properties, if
- * any are reported. Then sends a PROVISIONAL_DESTINATION_RESOLVED
- * event.
- */
- this.removeProvisionalDestination_(destination.id);
- var parsedDestination =
- print_preview.ExtensionDestinationParser.parse(destinationInfo);
- this.insertIntoStore_(parsedDestination);
- this.dispatchProvisionalDestinationResolvedEvent_(
- destination.id, parsedDestination);
- }.bind(this),
- function() {
- /**
- * The provisional destination is removed from the store and a
- * PROVISIONAL_DESTINATION_RESOLVED event is dispatched with a null
- * destination.
- */
- this.removeProvisionalDestination_(destination.id);
- this.dispatchProvisionalDestinationResolvedEvent_(destination.id,
- null);
- }.bind(this));
+ this.nativeLayer_.grantExtensionPrinterAccess(destination.id)
+ .then(
+ destinationInfo => {
+ /**
+ * Removes the destination from the store and replaces it with a
+ * destination created from the resolved destination properties,
+ * if any are reported. Then sends a
+ * PROVISIONAL_DESTINATION_RESOLVED event.
+ */
+ this.removeProvisionalDestination_(destination.id);
+ var parsedDestination =
+ print_preview.ExtensionDestinationParser.parse(
+ destinationInfo);
+ this.insertIntoStore_(parsedDestination);
+ this.dispatchProvisionalDestinationResolvedEvent_(
+ destination.id, parsedDestination);
+ },
+ () => {
+ /**
+ * The provisional destination is removed from the store and a
+ * PROVISIONAL_DESTINATION_RESOLVED event is dispatched with a
+ * null destination.
+ */
+ this.removeProvisionalDestination_(destination.id);
+ this.dispatchProvisionalDestinationResolvedEvent_(
+ destination.id, null);
+ });
},
/**
@@ -1099,11 +1085,11 @@ cr.define('print_preview', function() {
return;
this.isPrivetDestinationSearchInProgress_ = true;
this.nativeLayer_.getPrivetPrinters().then(
- this.endPrivetPrinterSearch_.bind(this), function() {
+ this.endPrivetPrinterSearch_.bind(this), () => {
// Rejected by C++, indicating privet printing is disabled.
this.hasLoadedAllPrivetDestinations_ = true;
this.isPrivetDestinationSearchInProgress_ = false;
- }.bind(this));
+ });
cr.dispatchSimpleEvent(
this, DestinationStore.EventType.DESTINATION_SEARCH_STARTED);
},
diff --git a/chromium/chrome/browser/resources/print_preview/data/print_ticket_store.js b/chromium/chrome/browser/resources/print_preview/data/print_ticket_store.js
index 8b8f16b1ea8..63a42bc086f 100644
--- a/chromium/chrome/browser/resources/print_preview/data/print_ticket_store.js
+++ b/chromium/chrome/browser/resources/print_preview/data/print_ticket_store.js
@@ -420,10 +420,11 @@ cr.define('print_preview', function() {
/** @return {boolean} Whether the ticket is valid for preview generation. */
isTicketValidForPreview: function() {
return (
- !this.marginsType_.isCapabilityAvailable() ||
- !this.marginsType_.isValueEqual(
- print_preview.ticket_items.MarginsTypeValue.CUSTOM) ||
- this.customMargins_.isValid());
+ (!this.marginsType_.isCapabilityAvailable() ||
+ !this.marginsType_.isValueEqual(
+ print_preview.ticket_items.MarginsTypeValue.CUSTOM) ||
+ this.customMargins_.isValid()) &&
+ (!this.scaling_.isCapabilityAvailable() || this.scaling_.isValid()));
},
/**
diff --git a/chromium/chrome/browser/resources/print_preview/data/ticket_items/scaling.js b/chromium/chrome/browser/resources/print_preview/data/ticket_items/scaling.js
index e1099dadf36..e51252fce26 100644
--- a/chromium/chrome/browser/resources/print_preview/data/ticket_items/scaling.js
+++ b/chromium/chrome/browser/resources/print_preview/data/ticket_items/scaling.js
@@ -28,12 +28,12 @@ cr.define('print_preview.ticket_items', function() {
/** @override */
wouldValueBeValid: function(value) {
- return true;
+ return value != '';
},
/** @override */
isValueEqual: function(value) {
- return this.getValueAsNumber() == value;
+ return this.getValue() == value;
},
/** @override */
@@ -51,7 +51,9 @@ cr.define('print_preview.ticket_items', function() {
/** @return {number} The scaling percentage indicated by the ticket item. */
getValueAsNumber: function() {
- return parseInt(this.getValue(), 10);
+ var value = this.getValue() == '' ? 0 : parseInt(this.getValue(), 10);
+ assert(!isNaN(value));
+ return value;
},
/** @override */
diff --git a/chromium/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js b/chromium/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js
index 753c5164f2b..ce3da11b16e 100644
--- a/chromium/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js
+++ b/chromium/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js
@@ -145,7 +145,9 @@ cr.define('print_preview.ticket_items', function() {
var sendUpdateEvent = !this.isValueEqual(value);
// Don't lose requested value if capability is not available.
this.updateValueInternal(value);
- if (this.appState_ && (this.field_ != null)) {
+ if (this.appState_ && (this.field_ != null) &&
+ (this.field_ != print_preview.AppStateField.SCALING ||
+ this.wouldValueBeValid(value))) {
this.appState_.persistField(this.field_, value);
}
if (sendUpdateEvent)
@@ -155,7 +157,6 @@ cr.define('print_preview.ticket_items', function() {
/**
* @return {?} Default value of the ticket item if no value was set by
* the user.
- * @abstract
* @protected
*/
getDefaultValueInternal: function() {
@@ -165,7 +166,6 @@ cr.define('print_preview.ticket_items', function() {
/**
* @return {?} Default value of the ticket item if the capability is
* not available.
- * @abstract
* @protected
*/
getCapabilityNotAvailableValueInternal: function() {
diff --git a/chromium/chrome/browser/resources/print_preview/metrics.js b/chromium/chrome/browser/resources/print_preview/metrics.js
index d9b84cbc67f..30d0a7d01d9 100644
--- a/chromium/chrome/browser/resources/print_preview/metrics.js
+++ b/chromium/chrome/browser/resources/print_preview/metrics.js
@@ -54,25 +54,6 @@ cr.define('print_preview', function() {
};
/**
- * Enumeration of buckets that a user can enter while using the Google Cloud
- * Print promotion.
- * @enum {number}
- */
- Metrics.GcpPromoBucket = {
- // Used when the Google Cloud Print promotion (shown above the PDF preview
- // plugin) is shown to the user.
- PROMO_SHOWN: 0,
- // Used when the user clicks the "Get started" link in the promotion shown
- // in CLOUDPRINT_BIG_PROMO_SHOWN.
- PROMO_CLICKED: 1,
- // Used when the user dismisses the promotion shown in
- // CLOUDPRINT_BIG_PROMO_SHOWN.
- PROMO_CLOSED: 2,
- // Max value.
- GCP_PROMO_MAX_BUCKET: 3
- };
-
- /**
* Print settings UI usage metrics buckets.
* @enum {number}
*/
@@ -140,19 +121,6 @@ cr.define('print_preview', function() {
};
/**
- * GCP promotion specific usage statistics context.
- * @constructor
- * @extends {print_preview.MetricsContext}
- */
- function GcpPromoMetricsContext() {
- MetricsContext.call(
- this, 'PrintPreview.GcpPromo',
- Metrics.GcpPromoBucket.GCP_PROMO_MAX_BUCKET);
- }
-
- GcpPromoMetricsContext.prototype = {__proto__: MetricsContext.prototype};
-
- /**
* Print settings UI specific usage statistics context.
* @constructor
* @extends {print_preview.MetricsContext}
@@ -172,7 +140,6 @@ cr.define('print_preview', function() {
Metrics: Metrics,
MetricsContext: MetricsContext,
DestinationSearchMetricsContext: DestinationSearchMetricsContext,
- GcpPromoMetricsContext: GcpPromoMetricsContext,
PrintSettingsUiMetricsContext: PrintSettingsUiMetricsContext
};
});
diff --git a/chromium/chrome/browser/resources/print_preview/native_layer.js b/chromium/chrome/browser/resources/print_preview/native_layer.js
index 5a863b1c0b3..05072dc29e0 100644
--- a/chromium/chrome/browser/resources/print_preview/native_layer.js
+++ b/chromium/chrome/browser/resources/print_preview/native_layer.js
@@ -77,73 +77,55 @@ print_preview.PrinterSetupResponse;
*/
print_preview.ProvisionalDestinationInfo;
+/**
+ * Printer types for capabilities and printer list requests.
+ * Should match PrinterType in print_preview_handler.h
+ * @enum {number}
+ */
+print_preview.PrinterType = {
+ PRIVET_PRINTER: 0,
+ EXTENSION_PRINTER: 1,
+};
+
cr.define('print_preview', function() {
'use strict';
/**
* An interface to the native Chromium printing system layer.
- * @constructor
- */
- function NativeLayer() {
- }
-
- /** @private {?print_preview.NativeLayer} */
- var currentInstance = null;
-
- /**
- * @return {!print_preview.NativeLayer} The singleton instance.
- * Creates a new NativeLayer if the current instance is not set.
- */
- NativeLayer.getInstance = function() {
- if (currentInstance == null)
- currentInstance = new NativeLayer();
- return assert(currentInstance);
- };
-
- /**
- * @param {!print_preview.NativeLayer} instance The NativeLayer instance
- * to set for print preview construction.
- */
- NativeLayer.setInstance = function(instance) {
- currentInstance = instance;
- };
-
- /**
- * Constant values matching printing::DuplexMode enum.
- * @enum {number}
- */
- NativeLayer.DuplexMode = {SIMPLEX: 0, LONG_EDGE: 1, UNKNOWN_DUPLEX_MODE: -1};
-
- /**
- * Enumeration of color modes used by Chromium.
- * @enum {number}
- * @private
*/
- NativeLayer.ColorMode_ = {GRAY: 1, COLOR: 2};
+ class NativeLayer {
+ /**
+ * Creates a new NativeLayer if the current instance is not set.
+ * @return {!print_preview.NativeLayer} The singleton instance.
+ */
+ static getInstance() {
+ if (currentInstance == null)
+ currentInstance = new NativeLayer();
+ return assert(currentInstance);
+ }
- /**
- * Version of the serialized state of the print preview.
- * @type {number}
- * @const
- * @private
- */
- NativeLayer.SERIALIZED_STATE_VERSION_ = 1;
+ /**
+ * @param {!print_preview.NativeLayer} instance The NativeLayer instance
+ * to set for print preview construction.
+ */
+ static setInstance(instance) {
+ currentInstance = instance;
+ }
- NativeLayer.prototype = {
/**
* Requests access token for cloud print requests.
* @param {string} authType type of access token.
* @return {!Promise<string>}
*/
- getAccessToken: function(authType) {
+ getAccessToken(authType) {
return cr.sendWithPromise('getAccessToken', authType);
- },
+ }
/**
* Gets the initial settings to initialize the print preview with.
* @return {!Promise<!print_preview.NativeInitialSettings>}
*/
- getInitialSettings: function() {
+ getInitialSettings() {
return cr.sendWithPromise('getInitialSettings')
.then(
/**
@@ -172,16 +154,16 @@ cr.define('print_preview', function() {
initialSettings['defaultDestinationSelectionRules'] ||
null);
});
- },
+ }
/**
* Requests the system's local print destinations. The promise will be
* resolved with a list of the local destinations.
* @return {!Promise<!Array<print_preview.LocalDestinationInfo>>}
*/
- getPrinters: function() {
+ getPrinters() {
return cr.sendWithPromise('getPrinters');
- },
+ }
/**
* Requests the network's privet print destinations. After this is called,
@@ -189,9 +171,11 @@ cr.define('print_preview', function() {
* @return {!Promise} Resolves when privet printer search is completed.
* Rejected if privet printers are not enabled.
*/
- getPrivetPrinters: function() {
- return cr.sendWithPromise('getPrivetPrinters');
- },
+ getPrivetPrinters() {
+ return cr.sendWithPromise(
+ 'getExtensionOrPrivetPrinters',
+ print_preview.PrinterType.PRIVET_PRINTER);
+ }
/**
* Request a list of extension printers. Printers are reported as they are
@@ -199,9 +183,11 @@ cr.define('print_preview', function() {
* @return {!Promise} Will be resolved when all extension managed printers
* have been sent.
*/
- getExtensionPrinters: function() {
- return cr.sendWithPromise('getExtensionPrinters');
- },
+ getExtensionPrinters() {
+ return cr.sendWithPromise(
+ 'getExtensionOrPrivetPrinters',
+ print_preview.PrinterType.EXTENSION_PRINTER);
+ }
/**
* Requests the destination's printing capabilities. Returns a promise that
@@ -209,33 +195,36 @@ cr.define('print_preview', function() {
* @param {string} destinationId ID of the destination.
* @return {!Promise<!print_preview.PrinterCapabilitiesResponse>}
*/
- getPrinterCapabilities: function(destinationId) {
+ getPrinterCapabilities(destinationId) {
return cr.sendWithPromise('getPrinterCapabilities', destinationId);
- },
+ }
/**
* Requests the privet destination's printing capabilities. Returns a
* promise that will be resolved with capabilities and printer information
* if capabilities are obtained successfully.
- * @param {string} destinationId ID of the destination.
+ * @param {string} destinationId The ID of the destination
* @return {!Promise<!print_preview.PrivetPrinterCapabilitiesResponse>}
*/
- getPrivetPrinterCapabilities: function(destinationId) {
- return cr.sendWithPromise('getPrivetPrinterCapabilities', destinationId);
- },
+ getPrivetPrinterCapabilities(destinationId) {
+ return cr.sendWithPromise(
+ 'getExtensionOrPrivetPrinterCapabilities', destinationId,
+ print_preview.PrinterType.PRIVET_PRINTER);
+ }
/**
* Requests the extension destination's printing capabilities. Returns a
- * promise that will be resolved with the ID and capabilities if
- * capabilities are obtained successfully.
+ * promise that will be resolved with the capabilities if capabilities are
+ * obtained successfully.
* @param {string} destinationId The ID of the destination whose
* capabilities are requested.
* @return {!Promise<!print_preview.Cdd>}
*/
- getExtensionPrinterCapabilities: function(destinationId) {
+ getExtensionPrinterCapabilities(destinationId) {
return cr.sendWithPromise(
- 'getExtensionPrinterCapabilities', destinationId);
- },
+ 'getExtensionOrPrivetPrinterCapabilities', destinationId,
+ print_preview.PrinterType.EXTENSION_PRINTER);
+ }
/**
* Requests Chrome to resolve provisional extension destination by granting
@@ -243,19 +232,19 @@ cr.define('print_preview', function() {
* @param {string} provisionalDestinationId
* @return {!Promise<!print_preview.ProvisionalDestinationInfo>}
*/
- grantExtensionPrinterAccess: function(provisionalDestinationId) {
+ grantExtensionPrinterAccess(provisionalDestinationId) {
return cr.sendWithPromise('grantExtensionPrinterAccess',
provisionalDestinationId);
- },
+ }
/**
* Requests that Chrome peform printer setup for the given printer.
* @param {string} printerId
* @return {!Promise<!print_preview.PrinterSetupResponse>}
*/
- setupPrinter: function(printerId) {
+ setupPrinter(printerId) {
return cr.sendWithPromise('setupPrinter', printerId);
- },
+ }
/**
* @param {!print_preview.Destination} destination Destination to print to.
@@ -263,7 +252,7 @@ cr.define('print_preview', function() {
* @return {number} Native layer color model.
* @private
*/
- getNativeColorModel_: function(destination, color) {
+ getNativeColorModel_(destination, color) {
// For non-local printers native color model is ignored anyway.
var option = destination.isLocal ? color.getSelectedOption() : null;
var nativeColorModel = parseInt(option ? option.vendor_id : null, 10);
@@ -272,7 +261,7 @@ cr.define('print_preview', function() {
NativeLayer.ColorMode_.GRAY;
}
return nativeColorModel;
- },
+ }
/**
* Requests that a preview be generated. The following Web UI events may
@@ -290,7 +279,7 @@ cr.define('print_preview', function() {
* @return {!Promise<number>} Promise that resolves with the unique ID of
* the preview UI when the preview has been generated.
*/
- getPreview: function(
+ getPreview(
destination, printTicketStore, documentInfo, generateDraft, requestId) {
assert(
printTicketStore.isTicketValidForPreview(),
@@ -356,7 +345,7 @@ cr.define('print_preview', function() {
return cr.sendWithPromise(
'getPreview', JSON.stringify(ticket),
requestId > 0 ? documentInfo.pageCount : -1);
- },
+ }
/**
* Requests that the document be printed.
@@ -373,7 +362,7 @@ cr.define('print_preview', function() {
* @return {!Promise} Promise that will resolve when the print request is
* finished or rejected.
*/
- print: function(
+ print(
destination, printTicketStore, cloudPrintInterface, documentInfo,
opt_isOpenPdfInPreview, opt_showSystemDialog) {
assert(
@@ -450,26 +439,26 @@ cr.define('print_preview', function() {
}
return cr.sendWithPromise('print', JSON.stringify(ticket));
- },
+ }
/** Requests that the current pending print request be cancelled. */
- cancelPendingPrintRequest: function() {
+ cancelPendingPrintRequest() {
chrome.send('cancelPendingPrintRequest');
- },
+ }
/**
* Sends the app state to be saved in the sticky settings.
* @param {string} appStateStr JSON string of the app state to persist
*/
- saveAppState: function(appStateStr) {
+ saveAppState(appStateStr) {
chrome.send('saveAppState', [appStateStr]);
- },
+ }
/** Shows the system's native printing dialog. */
- showSystemDialog: function() {
+ showSystemDialog() {
assert(!cr.isWindows);
chrome.send('showSystemDialog');
- },
+ }
/**
* Closes the print preview dialog.
@@ -478,16 +467,16 @@ cr.define('print_preview', function() {
* @param {boolean} isCancel whether this was called due to the user
* closing the dialog without printing.
*/
- dialogClose: function(isCancel) {
+ dialogClose(isCancel) {
if (isCancel)
chrome.send('closePrintPreviewDialog');
chrome.send('dialogClose');
- },
+ }
/** Hide the print preview dialog and allow the native layer to close it. */
- hidePreview: function() {
+ hidePreview() {
chrome.send('hidePreview');
- },
+ }
/**
* Opens the Google Cloud Print sign-in tab. The DESTINATIONS_RELOAD event
@@ -497,14 +486,14 @@ cr.define('print_preview', function() {
* @return {!Promise} Promise that resolves when the sign in tab has been
* closed and the destinations should be reloaded.
*/
- signIn: function(addAccount) {
+ signIn(addAccount) {
return cr.sendWithPromise('signIn', addAccount);
- },
+ }
/** Navigates the user to the system printer settings interface. */
- manageLocalPrinters: function() {
+ manageLocalPrinters() {
chrome.send('manageLocalPrinters');
- },
+ }
/**
* Navigates the user to the Google Cloud Print management page.
@@ -512,39 +501,39 @@ cr.define('print_preview', function() {
* page for (user must be currently logged in, indeed) or {@code null}
* to open this page for the primary user.
*/
- manageCloudPrinters: function(user) {
+ manageCloudPrinters(user) {
chrome.send('manageCloudPrinters', [user || '']);
- },
+ }
/** Forces browser to open a new tab with the given URL address. */
- forceOpenNewTab: function(url) {
+ forceOpenNewTab(url) {
chrome.send('forceOpenNewTab', [url]);
- },
+ }
/**
* 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: function() {
+ uiLoadedForTest() {
chrome.send('UILoadedForTest');
- },
+ }
/**
* Notifies the test that the option it tried to change
* had not been changed successfully.
*/
- uiFailedLoadingForTest: function() {
+ uiFailedLoadingForTest() {
chrome.send('UIFailedLoadingForTest');
- },
+ }
/**
* Notifies the metrics handler to record an action.
* @param {string} action The action to record.
*/
- recordAction: function(action) {
+ recordAction(action) {
chrome.send('metricsHandler:recordAction', [action]);
- },
+ }
/**
* Notifies the metrics handler to record a histogram value.
@@ -552,122 +541,149 @@ cr.define('print_preview', function() {
* @param {number} bucket The bucket to record
* @param {number} maxBucket The maximum bucket value in the histogram.
*/
- recordInHistogram: function(histogram, bucket, maxBucket) {
+ recordInHistogram(histogram, bucket, maxBucket) {
chrome.send(
'metricsHandler:recordInHistogram', [histogram, bucket, maxBucket]);
- },
- };
+ }
+ }
+
+ /** @private {?print_preview.NativeLayer} */
+ var currentInstance = null;
/**
- * Initial settings retrieved from the native layer.
- * @param {boolean} isInKioskAutoPrintMode Whether the print preview should be
- * in auto-print mode.
- * @param {boolean} isInAppKioskMode Whether the print preview is in App Kiosk
- * mode.
- * @param {string} thousandsDelimeter Character delimeter of thousands digits.
- * @param {string} decimalDelimeter Character delimeter of the decimal point.
- * @param {!print_preview.MeasurementSystemUnitType} unitType Unit type of
- * local machine's measurement system.
- * @param {boolean} isDocumentModifiable Whether the document to print is
- * modifiable.
- * @param {string} documentTitle Title of the document.
- * @param {boolean} documentHasSelection Whether the document has selected
- * content.
- * @param {boolean} selectionOnly Whether only selected content should be
- * printed.
- * @param {?string} systemDefaultDestinationId ID of the system default
- * destination.
- * @param {?string} serializedAppStateStr Serialized app state.
- * @param {?string} serializedDefaultDestinationSelectionRulesStr Serialized
- * default destination selection rules.
- * @constructor
+ * Constant values matching printing::DuplexMode enum.
+ * @enum {number}
*/
- function NativeInitialSettings(
- isInKioskAutoPrintMode, isInAppKioskMode, thousandsDelimeter,
- decimalDelimeter, unitType, isDocumentModifiable, documentTitle,
- documentHasSelection, selectionOnly, systemDefaultDestinationId,
- serializedAppStateStr, serializedDefaultDestinationSelectionRulesStr) {
- /**
- * Whether the print preview should be in auto-print mode.
- * @private {boolean}
- */
- this.isInKioskAutoPrintMode_ = isInKioskAutoPrintMode;
-
- /**
- * Whether the print preview should switch to App Kiosk mode.
- * @private {boolean}
- */
- this.isInAppKioskMode_ = isInAppKioskMode;
-
- /**
- * Character delimeter of thousands digits.
- * @private {string}
- */
- this.thousandsDelimeter_ = thousandsDelimeter;
-
- /**
- * Character delimeter of the decimal point.
- * @private {string}
- */
- this.decimalDelimeter_ = decimalDelimeter;
-
- /**
- * Unit type of local machine's measurement system.
- * @private {print_preview.MeasurementSystemUnitType}
- */
- this.unitType_ = unitType;
-
- /**
- * Whether the document to print is modifiable.
- * @private {boolean}
- */
- this.isDocumentModifiable_ = isDocumentModifiable;
-
- /**
- * Title of the document.
- * @private {string}
- */
- this.documentTitle_ = documentTitle;
-
- /**
- * Whether the document has selection.
- * @private {boolean}
- */
- this.documentHasSelection_ = documentHasSelection;
-
- /**
- * Whether selection only should be printed.
- * @private {boolean}
- */
- this.selectionOnly_ = selectionOnly;
+ NativeLayer.DuplexMode = {SIMPLEX: 0, LONG_EDGE: 1, UNKNOWN_DUPLEX_MODE: -1};
- /**
- * ID of the system default destination.
- * @private {?string}
- */
- this.systemDefaultDestinationId_ = systemDefaultDestinationId;
+ /**
+ * Enumeration of color modes used by Chromium.
+ * @enum {number}
+ * @private
+ */
+ NativeLayer.ColorMode_ = {GRAY: 1, COLOR: 2};
- /**
- * Serialized app state.
- * @private {?string}
- */
- this.serializedAppStateStr_ = serializedAppStateStr;
+ /**
+ * Version of the serialized state of the print preview.
+ * @type {number}
+ * @const
+ * @private
+ */
+ NativeLayer.SERIALIZED_STATE_VERSION_ = 1;
- /**
- * Serialized default destination selection rules.
- * @private {?string}
- */
- this.serializedDefaultDestinationSelectionRulesStr_ =
- serializedDefaultDestinationSelectionRulesStr;
- }
+ /**
+ * Initial settings retrieved from the native layer.
+ */
+ class NativeInitialSettings {
+ /**
+ * @param {boolean} isInKioskAutoPrintMode Whether the print preview should
+ * be in auto-print mode.
+ * @param {boolean} isInAppKioskMode Whether the print preview is in App
+ * Kiosk mode.
+ * @param {string} thousandsDelimeter Character delimeter of thousands
+ * digits.
+ * @param {string} decimalDelimeter Character delimeter of the decimal
+ * point.
+ * @param {!print_preview.MeasurementSystemUnitType} unitType Unit type of
+ * local machine's measurement system.
+ * @param {boolean} isDocumentModifiable Whether the document to print is
+ * modifiable.
+ * @param {string} documentTitle Title of the document.
+ * @param {boolean} documentHasSelection Whether the document has selected
+ * content.
+ * @param {boolean} selectionOnly Whether only selected content should be
+ * printed.
+ * @param {?string} systemDefaultDestinationId ID of the system default
+ * destination.
+ * @param {?string} serializedAppStateStr Serialized app state.
+ * @param {?string} serializedDefaultDestinationSelectionRulesStr Serialized
+ * default destination selection rules.
+ */
+ constructor(
+ isInKioskAutoPrintMode, isInAppKioskMode, thousandsDelimeter,
+ decimalDelimeter, unitType, isDocumentModifiable, documentTitle,
+ documentHasSelection, selectionOnly, systemDefaultDestinationId,
+ serializedAppStateStr, serializedDefaultDestinationSelectionRulesStr) {
+ /**
+ * Whether the print preview should be in auto-print mode.
+ * @private {boolean}
+ */
+ this.isInKioskAutoPrintMode_ = isInKioskAutoPrintMode;
+
+ /**
+ * Whether the print preview should switch to App Kiosk mode.
+ * @private {boolean}
+ */
+ this.isInAppKioskMode_ = isInAppKioskMode;
+
+ /**
+ * Character delimeter of thousands digits.
+ * @private {string}
+ */
+ this.thousandsDelimeter_ = thousandsDelimeter;
+
+ /**
+ * Character delimeter of the decimal point.
+ * @private {string}
+ */
+ this.decimalDelimeter_ = decimalDelimeter;
+
+ /**
+ * Unit type of local machine's measurement system.
+ * @private {print_preview.MeasurementSystemUnitType}
+ */
+ this.unitType_ = unitType;
+
+ /**
+ * Whether the document to print is modifiable.
+ * @private {boolean}
+ */
+ this.isDocumentModifiable_ = isDocumentModifiable;
+
+ /**
+ * Title of the document.
+ * @private {string}
+ */
+ this.documentTitle_ = documentTitle;
+
+ /**
+ * Whether the document has selection.
+ * @private {boolean}
+ */
+ this.documentHasSelection_ = documentHasSelection;
+
+ /**
+ * Whether selection only should be printed.
+ * @private {boolean}
+ */
+ this.selectionOnly_ = selectionOnly;
+
+ /**
+ * ID of the system default destination.
+ * @private {?string}
+ */
+ this.systemDefaultDestinationId_ = systemDefaultDestinationId;
+
+ /**
+ * Serialized app state.
+ * @private {?string}
+ */
+ this.serializedAppStateStr_ = serializedAppStateStr;
+
+ /**
+ * Serialized default destination selection rules.
+ * @private {?string}
+ */
+ this.serializedDefaultDestinationSelectionRulesStr_ =
+ serializedDefaultDestinationSelectionRulesStr;
+ }
- NativeInitialSettings.prototype = {
/**
* @return {boolean} Whether the print preview should be in auto-print mode.
*/
get isInKioskAutoPrintMode() {
return this.isInKioskAutoPrintMode_;
- },
+ }
/**
* @return {boolean} Whether the print preview should switch to App Kiosk
@@ -675,17 +691,17 @@ cr.define('print_preview', function() {
*/
get isInAppKioskMode() {
return this.isInAppKioskMode_;
- },
+ }
/** @return {string} Character delimeter of thousands digits. */
get thousandsDelimeter() {
return this.thousandsDelimeter_;
- },
+ }
/** @return {string} Character delimeter of the decimal point. */
get decimalDelimeter() {
return this.decimalDelimeter_;
- },
+ }
/**
* @return {!print_preview.MeasurementSystemUnitType} Unit type of local
@@ -693,43 +709,43 @@ cr.define('print_preview', function() {
*/
get unitType() {
return this.unitType_;
- },
+ }
/** @return {boolean} Whether the document to print is modifiable. */
get isDocumentModifiable() {
return this.isDocumentModifiable_;
- },
+ }
/** @return {string} Document title. */
get documentTitle() {
return this.documentTitle_;
- },
+ }
/** @return {boolean} Whether the document has selection. */
get documentHasSelection() {
return this.documentHasSelection_;
- },
+ }
/** @return {boolean} Whether selection only should be printed. */
get selectionOnly() {
return this.selectionOnly_;
- },
+ }
/** @return {?string} ID of the system default destination. */
get systemDefaultDestinationId() {
return this.systemDefaultDestinationId_;
- },
+ }
/** @return {?string} Serialized app state. */
get serializedAppStateStr() {
return this.serializedAppStateStr_;
- },
+ }
/** @return {?string} Serialized default destination selection rules. */
get serializedDefaultDestinationSelectionRulesStr() {
return this.serializedDefaultDestinationSelectionRulesStr_;
}
- };
+ }
// Export
return {
diff --git a/chromium/chrome/browser/resources/print_preview/no_destinations_promo.css b/chromium/chrome/browser/resources/print_preview/no_destinations_promo.css
deleted file mode 100644
index f1d8de8e74d..00000000000
--- a/chromium/chrome/browser/resources/print_preview/no_destinations_promo.css
+++ /dev/null
@@ -1,20 +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. */
-
-#no-destinations-promo {
- z-index: 2;
-}
-
-#no-destinations-promo .page {
- width: 510px;
-}
-
-.hbox {
- -webkit-box-orient: horizontal;
- display: -webkit-box;
-}
-
-.stretch {
- -webkit-box-flex: 1;
-}
diff --git a/chromium/chrome/browser/resources/print_preview/no_destinations_promo.html b/chromium/chrome/browser/resources/print_preview/no_destinations_promo.html
deleted file mode 100644
index 27ac4d65b2f..00000000000
--- a/chromium/chrome/browser/resources/print_preview/no_destinations_promo.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<div id="no-destinations-promo" class="overlay" hidden>
- <div class="page">
- <div class="close-button"></div>
- <h1>$i18n{noDestsPromoTitle}</h1>
- <div class="content-area">
- <div>$i18n{noDestsPromoBody}</div>
- </div>
- <div class="content-area">
- <div>$i18n{noDestsPromoGcpDesc}</div>
- </div>
- <div class="action-area">
- <div class="hbox stretch">
- <a target="_blank" i18n-values="href:noDestsPromoLearnMoreUrl">
- $i18n{learnMore}
- </a>
- </div>
- <div class="action-area-right">
- <div class="button-strip">
- <button
- class="add-printer-button default-button">
- $i18n{noDestsPromoAddPrinterButtonLabel}
- </button>
- <button
- class="not-now-button">
- $i18n{noDestsPromoNotNowButtonLabel}
- </button>
- </div>
- </div>
- </div>
- </div>
-</div>
diff --git a/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.css b/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.css
index b6131a6afa1..f54fe8aeaa6 100644
--- a/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.css
+++ b/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.css
@@ -4,10 +4,10 @@
#preview-area.preview-area {
-webkit-box-flex: 1;
- -webkit-user-select: none;
background-color: #e6e6e6;
overflow: hidden;
position: relative;
+ user-select: none;
}
.preview-area-plugin-wrapper {
@@ -37,7 +37,6 @@
}
#preview-area .preview-area-overlay-layer {
- -webkit-user-select: none;
background: #e6e6e6;
height: 100%;
margin: 0;
@@ -47,6 +46,7 @@
/* overlayFadeInTransitionDelay = pluginFadeOutTransitionDelay +
* pluginFadeOutTransitionDuration = 350ms */
transition-delay: 350ms;
+ user-select: none;
width: 100%;
z-index: 1;
}
diff --git a/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.js b/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.js
index 8d41ff9e6c2..3ef1805c88b 100644
--- a/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.js
+++ b/chromium/chrome/browser/resources/print_preview/previewarea/preview_area.js
@@ -320,11 +320,11 @@ cr.define('print_preview', function() {
var TicketStoreEvent = print_preview.PrintTicketStore.EventType;
[TicketStoreEvent.INITIALIZE, TicketStoreEvent.TICKET_CHANGE,
TicketStoreEvent.CAPABILITIES_CHANGE, TicketStoreEvent.DOCUMENT_CHANGE]
- .forEach(function(eventType) {
+ .forEach(eventType => {
this.tracker.add(
this.printTicketStore_, eventType,
this.onTicketChange_.bind(this));
- }.bind(this));
+ });
[this.printTicketStore_.color, this.printTicketStore_.cssBackground,
this.printTicketStore_.customMargins, this.printTicketStore_.fitToPage,
@@ -332,11 +332,11 @@ cr.define('print_preview', function() {
this.printTicketStore_.marginsType, this.printTicketStore_.pageRange,
this.printTicketStore_.rasterize, this.printTicketStore_.selectionOnly,
this.printTicketStore_.scaling]
- .forEach(function(setting) {
+ .forEach(setting => {
this.tracker.add(
setting, print_preview.ticket_items.TicketItem.EventType.CHANGE,
this.onTicketChange_.bind(this));
- }.bind(this));
+ });
if (this.checkPluginCompatibility_()) {
this.previewGenerator_ = new print_preview.PreviewGenerator(
@@ -474,8 +474,8 @@ cr.define('print_preview', function() {
this.plugin_.setAttribute('aria-live', 'polite');
this.plugin_.setAttribute('aria-atomic', 'true');
// NOTE: The plugin's 'id' field must be set to 'pdf-viewer' since
- // chrome/renderer/printing/print_web_view_helper.cc actually references
- // it.
+ // chrome/renderer/printing/print_render_frame_helper.cc actually
+ // references it.
this.plugin_.setAttribute('id', 'pdf-viewer');
this.getChildElement('.preview-area-plugin-wrapper')
.appendChild(/** @type {Node} */ (this.plugin_));
@@ -534,16 +534,11 @@ cr.define('print_preview', function() {
PreviewArea.LOADING_TIMEOUT_);
}
previewRequest.request.then(
- /** @param {number} previewUid The unique id of the preview. */
- function(previewUid) {
+ previewUid => {
this.previewGenerator_.onPreviewGenerationDone(
previewRequest.id, previewUid);
- }.bind(this),
- /**
- * @param {*} type The type of print preview failure that
- * occurred.
- */
- function(type) {
+ },
+ type => {
if (/** @type{string} */ (type) == 'CANCELLED')
return; // overriden by a new request, do nothing.
if (/** @type{string} */ (type) == 'SETTINGS_INVALID') {
@@ -555,7 +550,7 @@ cr.define('print_preview', function() {
} else {
this.onPreviewGenerationFail_();
}
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/print_preview/print_header.js b/chromium/chrome/browser/resources/print_preview/print_header.js
index 901718c22af..810e286d16f 100644
--- a/chromium/chrome/browser/resources/print_preview/print_header.js
+++ b/chromium/chrome/browser/resources/print_preview/print_header.js
@@ -133,6 +133,10 @@ cr.define('print_preview', function() {
this.printTicketStore_.pageRange,
print_preview.ticket_items.TicketItem.EventType.CHANGE,
this.onTicketChange_.bind(this));
+ this.tracker.add(
+ this.printTicketStore_.scaling,
+ print_preview.ticket_items.TicketItem.EventType.CHANGE,
+ this.updatePrintButtonEnabledState_.bind(this));
},
/**
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview.css b/chromium/chrome/browser/resources/print_preview/print_preview.css
index fe76b9f991c..bb69ab6e9ed 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview.css
+++ b/chromium/chrome/browser/resources/print_preview/print_preview.css
@@ -25,10 +25,10 @@ header {
#print-preview #navbar-container {
-webkit-border-end: 1px solid #c8c8c8;
-webkit-box-orient: vertical;
- -webkit-user-select: none;
background-color: white;
display: -webkit-box;
position: relative;
+ user-select: none;
width: 310px;
z-index: 2;
}
@@ -104,6 +104,11 @@ header {
padding-top: 5px;
}
+.two-column.visible .left-column.multirow {
+ padding-top: 16px;
+ vertical-align: top;
+}
+
.two-column:not(.visible) .left-column,
.two-column:not(.visible) .right-column {
padding-bottom: 0;
@@ -163,7 +168,6 @@ span.hint {
}
span.hint.visible {
- -webkit-user-select: text;
animation-duration: 200ms;
animation-fill-mode: forwards;
color: rgb(140, 20, 20);
@@ -171,6 +175,7 @@ span.hint.visible {
margin-bottom: -5px;
margin-top: 5px;
padding-bottom: 5px;
+ user-select: text;
}
span.hint.closing {
@@ -208,7 +213,7 @@ select {
}
label {
- -webkit-user-select: none;
+ user-select: none;
}
.hidden-section {
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview.html b/chromium/chrome/browser/resources/print_preview/print_preview.html
index df7bc9fafa8..3373d046f4c 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview.html
+++ b/chromium/chrome/browser/resources/print_preview/print_preview.html
@@ -22,7 +22,7 @@
<link rel="stylesheet" href="settings/media_size_settings.css">
<link rel="stylesheet" href="settings/layout_settings.css">
<link rel="stylesheet" href="settings/dpi_settings.css">
- <link rel="stylesheet" href="settings/other_options_settings.css">
+ <link rel="stylesheet" href="settings/scaling_settings.css">
<link rel="stylesheet" href="settings/advanced_options_settings.css">
<link rel="stylesheet" href="settings/advanced_settings/advanced_settings.css">
<link rel="stylesheet" href="settings/advanced_settings/advanced_settings_item.css">
@@ -31,7 +31,6 @@
<link rel="stylesheet" href="previewarea/margin_control_container.css">
<link rel="stylesheet" href="previewarea/margin_control.css">
<link rel="stylesheet" href="chrome://resources/css/overlay.css">
- <link rel="stylesheet" href="no_destinations_promo.css">
<link rel="stylesheet" href="search/destination_list.css">
<link rel="stylesheet" href="search/destination_list_item.css">
@@ -97,7 +96,6 @@
</div>
<include src="search/destination_search.html">
<include src="settings/advanced_settings/advanced_settings.html">
- <include src="no_destinations_promo.html">
<div id="main-container">
<include src="previewarea/preview_area.html">
</div>
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview.js b/chromium/chrome/browser/resources/print_preview/print_preview.js
index df6e199fb7f..00a9b0e427a 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview.js
+++ b/chromium/chrome/browser/resources/print_preview/print_preview.js
@@ -206,8 +206,7 @@ cr.define('print_preview', function() {
* @private
*/
this.otherOptionsSettings_ = new print_preview.OtherOptionsSettings(
- this.printTicketStore_.duplex, this.printTicketStore_.fitToPage,
- this.printTicketStore_.cssBackground,
+ this.printTicketStore_.duplex, this.printTicketStore_.cssBackground,
this.printTicketStore_.selectionOnly,
this.printTicketStore_.headerFooter, this.printTicketStore_.rasterize);
this.addChild(this.otherOptionsSettings_);
@@ -393,10 +392,6 @@ cr.define('print_preview', function() {
this.destinationStore_,
print_preview.DestinationStore.EventType.DESTINATION_SELECT,
this.onDestinationSelect_.bind(this));
- this.tracker.add(
- this.destinationStore_,
- print_preview.DestinationStore.EventType.DESTINATION_SEARCH_DONE,
- this.onDestinationSearchDone_.bind(this));
this.tracker.add(
this.printHeader_,
@@ -440,18 +435,6 @@ cr.define('print_preview', function() {
this.advancedOptionsSettings_,
print_preview.AdvancedOptionsSettings.EventType.BUTTON_ACTIVATED,
this.onAdvancedOptionsButtonActivated_.bind(this));
-
- // TODO(rltoscano): Move no-destinations-promo into its own component
- // instead being part of PrintPreview.
- this.tracker.add(
- this.getChildElement('#no-destinations-promo .close-button'), 'click',
- this.onNoDestinationsPromoClose_.bind(this));
- this.tracker.add(
- this.getChildElement('#no-destinations-promo .not-now-button'),
- 'click', this.onNoDestinationsPromoClose_.bind(this));
- this.tracker.add(
- this.getChildElement('#no-destinations-promo .add-printer-button'),
- 'click', this.onNoDestinationsPromoClick_.bind(this));
},
/** @override */
@@ -579,9 +562,9 @@ cr.define('print_preview', function() {
print_preview.Destination.GooglePromotedId.SAVE_AS_PDF)) {
// Local printers resolve when print is ready to start. Hide the
// dialog. Mac "Open in Preview" is treated as a local printer.
- var boundHideDialog = function() {
+ var boundHideDialog = () => {
this.nativeLayer_.hidePreview();
- }.bind(this);
+ };
whenPrintDone.then(boundHideDialog, boundHideDialog);
} else if (!destination.isLocal) {
// Cloud print resolves when print data is returned to submit to cloud
@@ -1237,53 +1220,6 @@ cr.define('print_preview', function() {
this.onPrintButtonClick_();
}
},
-
- /**
- * Called when the destination store loads a group of destinations. Shows
- * a promo on Chrome OS if the user has no print destinations promoting
- * Google Cloud Print.
- * @private
- */
- onDestinationSearchDone_: function() {
- var isPromoVisible = cr.isChromeOS && this.cloudPrintInterface_ &&
- this.userInfo_.activeUser && !this.appState_.isGcpPromoDismissed &&
- !this.destinationStore_.isLocalDestinationSearchInProgress &&
- !this.destinationStore_.isCloudDestinationSearchInProgress &&
- this.destinationStore_.hasOnlyDefaultCloudDestinations();
- setIsVisible(
- this.getChildElement('#no-destinations-promo'), isPromoVisible);
- if (isPromoVisible) {
- new print_preview.GcpPromoMetricsContext().record(
- print_preview.Metrics.GcpPromoBucket.PROMO_SHOWN);
- }
- },
-
- /**
- * Called when the close button on the no-destinations-promotion is clicked.
- * Hides the promotion.
- * @private
- */
- onNoDestinationsPromoClose_: function() {
- new print_preview.GcpPromoMetricsContext().record(
- print_preview.Metrics.GcpPromoBucket.PROMO_CLOSED);
- setIsVisible(this.getChildElement('#no-destinations-promo'), false);
- this.appState_.persistIsGcpPromoDismissed(true);
- },
-
- /**
- * Called when the no-destinations promotion link is clicked. Opens the
- * Google Cloud Print management page and closes the print preview.
- * @private
- */
- onNoDestinationsPromoClick_: function() {
- new print_preview.GcpPromoMetricsContext().record(
- print_preview.Metrics.GcpPromoBucket.PROMO_CLICKED);
- this.appState_.persistIsGcpPromoDismissed(true);
- window.open(
- this.cloudPrintInterface_.baseUrl +
- '?authuser=' + this.userInfo_.activeUser + '#printers');
- this.close_(false);
- }
};
// Export
diff --git a/chromium/chrome/browser/resources/print_preview/search/destination_list.css b/chromium/chrome/browser/resources/print_preview/search/destination_list.css
index 2ebdb9ac55c..c20cfed6c83 100644
--- a/chromium/chrome/browser/resources/print_preview/search/destination_list.css
+++ b/chromium/chrome/browser/resources/print_preview/search/destination_list.css
@@ -26,14 +26,15 @@
}
.destination-list .throbber-container {
- display: inline;
- padding: 0 16px 0 8px;
+ -webkit-padding-end: 16px;
+ -webkit-padding-start: 8px;
+ display: inline-block;
position: relative;
+ vertical-align: middle;
}
.destination-list .throbber {
- position: absolute;
- top: -1px;
+ vertical-align: middle;
}
.destination-list .no-destinations-message {
diff --git a/chromium/chrome/browser/resources/print_preview/search/destination_list.js b/chromium/chrome/browser/resources/print_preview/search/destination_list.js
index 5d0d6664d91..9c1a2ef0144 100644
--- a/chromium/chrome/browser/resources/print_preview/search/destination_list.js
+++ b/chromium/chrome/browser/resources/print_preview/search/destination_list.js
@@ -287,12 +287,12 @@ cr.define('print_preview', function() {
setIsVisible(this.getChildElement('.destination-list > footer'), true);
}
// Remove obsolete list items (those with no corresponding destinations).
- this.listItems_ = this.listItems_.filter(function(item) {
+ this.listItems_ = this.listItems_.filter(item => {
var isValid = this.destinationIds_.hasOwnProperty(item.destination.id);
if (!isValid)
this.removeChild(item);
return isValid;
- }.bind(this));
+ });
// Prepare id -> list item cache for visible destinations.
var visibleListItems = {};
for (var i = 0; i < numItems; i++)
diff --git a/chromium/chrome/browser/resources/print_preview/search/destination_search.css b/chromium/chrome/browser/resources/print_preview/search/destination_search.css
index 2ff197aa7e4..fd7fa54103b 100644
--- a/chromium/chrome/browser/resources/print_preview/search/destination_search.css
+++ b/chromium/chrome/browser/resources/print_preview/search/destination_search.css
@@ -24,11 +24,11 @@
}
#destination-search .account-select-label {
- -webkit-user-select: none;
height: 2em;
line-height: 2em;
overflow: hidden;
text-overflow: ellipsis;
+ user-select: none;
white-space: nowrap;
}
@@ -42,8 +42,8 @@
}
#destination-search .search-box {
- -webkit-user-select: none;
margin: 14px;
+ user-select: none;
}
#destination-search .lists {
@@ -52,8 +52,8 @@
}
#destination-search .lists > * {
- -webkit-user-select: none;
padding: 0 14px 18px;
+ user-select: none;
}
#destination-search .lists > :last-child {
@@ -95,7 +95,7 @@
#destination-search .cloudprint-promo {
-webkit-box-align: center;
- -webkit-user-select: none;
+ user-select: none;
}
#destination-search .cloudprint-promo .sign-in[is='action-link'] {
diff --git a/chromium/chrome/browser/resources/print_preview/search/destination_search.js b/chromium/chrome/browser/resources/print_preview/search/destination_search.js
index 741d3c5e547..7876776fc9a 100644
--- a/chromium/chrome/browser/resources/print_preview/search/destination_search.js
+++ b/chromium/chrome/browser/resources/print_preview/search/destination_search.js
@@ -222,10 +222,10 @@ cr.define('print_preview', function() {
this.tracker.add(
this,
print_preview.DestinationListItem.EventType.REGISTER_PROMO_CLICKED,
- function() {
+ () => {
this.metrics_.record(print_preview.Metrics.DestinationSearchBucket
.REGISTER_PROMO_SELECTED);
- }.bind(this));
+ });
this.tracker.add(
this.destinationStore_,
@@ -608,20 +608,17 @@ cr.define('print_preview', function() {
this.destinationInConfiguring_ = destination;
this.destinationStore_.resolveCrosDestination(destination)
.then(
- /**
- * @param {!print_preview.PrinterSetupResponse} response
- */
- function(response) {
+ response => {
this.destinationInConfiguring_ = null;
this.localList_.getDestinationItem(destination.id)
.onConfigureResolved(response);
- }.bind(this),
- function() {
+ },
+ () => {
this.destinationInConfiguring_ = null;
this.localList_.getDestinationItem(destination.id)
.onConfigureResolved(
{printerId: destination.id, success: false});
- }.bind(this));
+ });
},
/**
@@ -656,21 +653,15 @@ cr.define('print_preview', function() {
var lastFocusedElement = document.activeElement;
this.addChild(this.provisionalDestinationResolver_);
this.provisionalDestinationResolver_.run(this.getElement())
- .then(
- /**
- * @param {!print_preview.Destination} resolvedDestination
- * Destination to which the provisional destination was
- * resolved.
- */
- function(resolvedDestination) {
- this.handleOnDestinationSelect_(resolvedDestination);
- }.bind(this))
+ .then(resolvedDestination => {
+ this.handleOnDestinationSelect_(resolvedDestination);
+ })
.catch(function() {
console.error(
'Failed to resolve provisional destination: ' +
destination.id);
})
- .then(function() {
+ .then(() => {
this.removeChild(assert(this.provisionalDestinationResolver_));
this.provisionalDestinationResolver_ = null;
@@ -681,7 +672,7 @@ cr.define('print_preview', function() {
this.getElement().contains(lastFocusedElement)) {
lastFocusedElement.focus();
}
- }.bind(this));
+ });
return;
}
diff --git a/chromium/chrome/browser/resources/print_preview/settings/advanced_options_settings.js b/chromium/chrome/browser/resources/print_preview/settings/advanced_options_settings.js
index 2469dbe006e..0bc41f4b6c0 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/advanced_options_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/advanced_options_settings.js
@@ -60,10 +60,10 @@ cr.define('print_preview', function() {
enterDocument: function() {
print_preview.SettingsSection.prototype.enterDocument.call(this);
- this.tracker.add(this.getButton_(), 'click', function() {
+ this.tracker.add(this.getButton_(), 'click', () => {
cr.dispatchSimpleEvent(
this, AdvancedOptionsSettings.EventType.BUTTON_ACTIVATED);
- }.bind(this));
+ });
this.tracker.add(
this.destinationStore_,
print_preview.DestinationStore.EventType.DESTINATION_SELECT,
diff --git a/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.css b/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.css
index 756c1cb5ba1..2db6286bb2c 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.css
+++ b/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.css
@@ -25,7 +25,7 @@
}
#advanced-settings .search-box {
- -webkit-user-select: none;
+ user-select: none;
}
#advanced-settings .no-settings-match-hint {
diff --git a/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js b/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js
index 42edd3a98d1..799f206980a 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js
@@ -163,9 +163,9 @@ cr.define('print_preview', function() {
*/
renderSettings_: function() {
// Remove all children settings elements.
- this.items_.forEach(function(item) {
+ this.items_.forEach(item => {
this.removeChild(item);
- }.bind(this));
+ });
this.items_ = [];
var extraPadding = this.element_.querySelector(
@@ -182,13 +182,13 @@ cr.define('print_preview', function() {
containerEl.style.maxHeight = availableHeight + 'px';
var settingsEl = this.getChildElement('.settings');
- vendorCapabilities.forEach(function(capability) {
+ vendorCapabilities.forEach(capability => {
var item = new print_preview.AdvancedSettingsItem(
this.printTicketStore_, capability);
this.addChild(item);
item.render(settingsEl);
this.items_.push(item);
- }.bind(this));
+ });
var searchBoxArea = this.getChildElement('.search-box-area');
if (this.items_.length <= 1) {
@@ -222,10 +222,10 @@ cr.define('print_preview', function() {
this.setIsVisible(false);
var values = {};
- this.items_.forEach(function(item) {
+ this.items_.forEach(item => {
if (item.isModified())
values[item.id] = item.selectedValue;
- }.bind(this));
+ });
this.printTicketStore_.vendorItems.updateValue(values);
}
diff --git a/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.html b/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.html
index e315a4049e2..da8415d43ad 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.html
+++ b/chromium/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.html
@@ -7,7 +7,6 @@
</span>
<span class="advanced-settings-item-value-text" hidden>
<input type="text" class="advanced-settings-item-value-text-control">
- </input>
</span>
</span>
</div>
diff --git a/chromium/chrome/browser/resources/print_preview/settings/copies_settings.js b/chromium/chrome/browser/resources/print_preview/settings/copies_settings.js
index 6aaab6ed74d..1dbcc74d6ba 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/copies_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/copies_settings.js
@@ -189,11 +189,9 @@ cr.define('print_preview', function() {
// No need to update the ticket, but change the display to match.
this.inputField_.value = '1';
} else {
- setTimeout(
- (function() {
- this.copiesTicketItem_.updateValue('1');
- }).bind(this),
- 0);
+ setTimeout(() => {
+ this.copiesTicketItem_.updateValue('1');
+ }, 0);
}
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/settings/more_settings.js b/chromium/chrome/browser/resources/print_preview/settings/more_settings.js
index 25bb73933a8..3c044fd4efc 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/more_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/more_settings.js
@@ -9,7 +9,7 @@ cr.define('print_preview', function() {
* Toggles visibility of the specified printing options sections.
* @param {!print_preview.DestinationStore} destinationStore To listen for
* destination changes.
- * @param {!Array<print_preview.SettingsSection>} settingsSections Sections
+ * @param {!Array<!print_preview.SettingsSection>} settingsSections Sections
* to toggle by this component.
* @constructor
* @extends {print_preview.Component}
@@ -20,7 +20,7 @@ cr.define('print_preview', function() {
/** @private {!print_preview.DestinationStore} */
this.destinationStore_ = destinationStore;
- /** @private {!Array<print_preview.SettingsSection>} */
+ /** @private {!Array<!print_preview.SettingsSection>} */
this.settingsSections_ = settingsSections;
/** @private {boolean} */
@@ -61,12 +61,12 @@ cr.define('print_preview', function() {
print_preview.DestinationStore.EventType
.SELECTED_DESTINATION_CAPABILITIES_READY,
this.onDestinationCapabilitiesReady_.bind(this));
- this.settingsSections_.forEach(function(section) {
+ this.settingsSections_.forEach(section => {
this.tracker.add(
section,
print_preview.SettingsSection.EventType.COLLAPSIBLE_CONTENT_CHANGED,
this.updateState_.bind(this));
- }.bind(this));
+ });
this.updateState_(true);
},
diff --git a/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.css b/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.css
deleted file mode 100644
index a155d625274..00000000000
--- a/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.css
+++ /dev/null
@@ -1,8 +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. */
-
-#other-options-settings .left-column {
- padding-top: 16px;
- vertical-align: top;
-} \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.html b/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.html
index 0514368ca56..e6906cdd002 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.html
@@ -1,6 +1,6 @@
<div id="other-options-settings"
class="other-options-settings two-column" hidden>
- <div class="left-column">
+ <div class="left-column multirow">
<h1>$i18n{optionsLabel}</h1>
</div>
<div class="right-column checkbox">
@@ -11,12 +11,6 @@
<span>$i18n{optionHeaderFooter}</span>
</label>
</div>
- <div id="fit-to-page-container">
- <label aria-live="polite">
- <input class="checkbox" type="checkbox">
- <span>$i18n{optionFitToPage}</span>
- </label>
- </div>
<div id="duplex-container">
<label aria-live="polite">
<input class="checkbox" type="checkbox">
diff --git a/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.js b/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.js
index 24e04b266ef..56c10e26bd8 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/other_options_settings.js
@@ -120,8 +120,6 @@ cr.define('print_preview', function() {
/**
* UI component that renders checkboxes for various print options.
* @param {!print_preview.ticket_items.Duplex} duplex Duplex ticket item.
- * @param {!print_preview.ticket_items.FitToPage} fitToPage Fit-to-page ticket
- * item.
* @param {!print_preview.ticket_items.CssBackground} cssBackground CSS
* background ticket item.
* @param {!print_preview.ticket_items.SelectionOnly} selectionOnly Selection
@@ -134,8 +132,7 @@ cr.define('print_preview', function() {
* @extends {print_preview.SettingsSection}
*/
function OtherOptionsSettings(
- duplex, fitToPage, cssBackground, selectionOnly, headerFooter,
- rasterize) {
+ duplex, cssBackground, selectionOnly, headerFooter, rasterize) {
print_preview.SettingsSection.call(this);
/**
* @private {boolean} rasterizeEnabled Whether the print as image feature is
@@ -152,7 +149,6 @@ cr.define('print_preview', function() {
this.elements_ = [
new CheckboxTicketItemElement(
headerFooter, true, 'header-footer-container'),
- new CheckboxTicketItemElement(fitToPage, false, 'fit-to-page-container'),
new CheckboxTicketItemElement(duplex, false, 'duplex-container'),
new CheckboxTicketItemElement(
cssBackground, true, 'css-background-container'),
@@ -161,7 +157,7 @@ cr.define('print_preview', function() {
];
if (this.rasterizeEnabled_) {
this.elements_.splice(
- 4, 0,
+ this.elements_.length - 1, 0,
new CheckboxTicketItemElement(
rasterize, true, 'rasterize-container'));
}
diff --git a/chromium/chrome/browser/resources/print_preview/settings/page_settings.css b/chromium/chrome/browser/resources/print_preview/settings/page_settings.css
index e239f939ae3..2e3b0a541d5 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/page_settings.css
+++ b/chromium/chrome/browser/resources/print_preview/settings/page_settings.css
@@ -2,11 +2,6 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-#page-settings .left-column {
- padding-top: 16px;
- vertical-align: top;
-}
-
#page-settings .page-settings-print-pages-div {
-webkit-box-align: center;
display: -webkit-box;
diff --git a/chromium/chrome/browser/resources/print_preview/settings/page_settings.html b/chromium/chrome/browser/resources/print_preview/settings/page_settings.html
index cbb91cad52e..cad226ede8d 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/page_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/settings/page_settings.html
@@ -1,5 +1,5 @@
<div id="page-settings" class="two-column page-settings" hidden>
- <div class="left-column">
+ <div class="left-column multirow">
<h1>$i18n{pagesLabel}</h1>
</div>
<div class="right-column">
@@ -9,7 +9,7 @@
</label></div>
<div class="radio">
<label class="page-settings-print-pages-div"
- for="page-settings-custom-input">
+ for="page-settings-custom-input" tabindex=-1>
<input class="page-settings-custom-radio" name="pages" type="radio"
i18n-values="aria-label:printPagesLabel;">
<div class="page-settings-custom-input-wrapper">
diff --git a/chromium/chrome/browser/resources/print_preview/settings/page_settings.js b/chromium/chrome/browser/resources/print_preview/settings/page_settings.js
index f8f70eea821..fe589e1ad3f 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/page_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/page_settings.js
@@ -193,8 +193,18 @@ cr.define('print_preview', function() {
*/
onCustomInputBlur_: function(event) {
if (this.customInput_.value == '' &&
+ event.relatedTarget !=
+ this.getElement().querySelector(
+ '.page-settings-print-pages-div') &&
event.relatedTarget != this.customRadio_) {
this.allRadio_.checked = true;
+ if (!this.pageRangeTicketItem_.isValueEqual(this.customInput_.value)) {
+ // Update ticket item to match, set timeout to avoid losing focus
+ // when the preview regenerates.
+ setTimeout(() => {
+ this.pageRangeTicketItem_.updateValue(this.customInput_.value);
+ });
+ }
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.css b/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.css
new file mode 100644
index 00000000000..e39db53edd7
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.css
@@ -0,0 +1,7 @@
+/* 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. */
+
+#scaling-settings .settings-box {
+ padding-top: 5px;
+}
diff --git a/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.html b/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.html
index 668f765f023..e2ee53f3718 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.html
@@ -1,8 +1,14 @@
<div id="scaling-settings" class="two-column" hidden>
- <div class="left-column">
+ <div class="left-column multirow">
<h1 id="scaling-label">$i18n{scalingLabel}</h1>
</div>
- <div class="right-column">
+ <div class="right-column checkbox">
+ <div id="fit-to-page-container">
+ <label aria-live="polite">
+ <input class="checkbox" type="checkbox">
+ <span>$i18n{optionFitToPage}</span>
+ </label>
+ </div>
<div class="settings-box">
<!-- The max and min value should match the ones in
headless_devtools_manager_delegate.cc.
diff --git a/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.js b/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.js
index 99d752c8409..2b12f418253 100644
--- a/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/settings/scaling_settings.js
@@ -48,10 +48,23 @@ cr.define('print_preview', function() {
this.isEnabled_ = true;
/**
+ * Last valid scaling value. Used to restore value when fit to page is
+ * unchecked. Must always be a valid scaling value.
+ * @private {string}
+ */
+ this.lastValidScaling_ = '100';
+
+ /**
* The textfield input element
- * @private {HTMLElement}
+ * @private {?HTMLElement}
*/
this.inputField_ = null;
+
+ /**
+ * The fit to page checkbox.
+ * @private {?HTMLElement}
+ */
+ this.fitToPageCheckbox_ = null;
}
/**
@@ -66,25 +79,36 @@ cr.define('print_preview', function() {
/** @override */
isAvailable: function() {
- return this.scalingTicketItem_.isCapabilityAvailable();
+ return this.scalingTicketItem_.isCapabilityAvailable() ||
+ this.fitToPageTicketItem_.isCapabilityAvailable();
},
/** @override */
hasCollapsibleContent: function() {
- return this.isAvailable();
+ return this.scalingTicketItem_.isCapabilityAvailable();
},
/** @override */
set isEnabled(isEnabled) {
this.inputField_.disabled = !isEnabled;
+ this.fitToPageCheckbox_.disabled = !isEnabled;
this.isEnabled_ = isEnabled;
- if (isEnabled)
- this.updateState_();
+ },
+
+ /**
+ * @return {boolean} Whether fit to page is available and selected.
+ * @private
+ */
+ isFitToPageSelected_: function() {
+ return this.fitToPageTicketItem_.isCapabilityAvailable() &&
+ /** @type {boolean} */ (this.fitToPageTicketItem_.getValue());
},
/** @override */
enterDocument: function() {
this.inputField_ = assert(this.getChildElement('input.user-value'));
+ this.fitToPageCheckbox_ =
+ assert(this.getChildElement('input[type=checkbox]'));
print_preview.SettingsSection.prototype.enterDocument.call(this);
this.tracker.add(
this.inputField_, 'keydown', this.onTextfieldKeyDown_.bind(this));
@@ -93,49 +117,28 @@ cr.define('print_preview', function() {
this.tracker.add(
this.inputField_, 'blur', this.onTextfieldBlur_.bind(this));
this.tracker.add(
+ this.fitToPageCheckbox_, 'click',
+ this.onFitToPageClicked_.bind(this));
+ this.tracker.add(
this.scalingTicketItem_,
print_preview.ticket_items.TicketItem.EventType.CHANGE,
- this.updateState_.bind(this));
+ this.updateState_.bind(this, false));
this.tracker.add(
this.fitToPageTicketItem_,
print_preview.ticket_items.TicketItem.EventType.CHANGE,
- this.onFitToPageChange_.bind(this));
- },
-
- /**
- * @return {boolean} true if fit to page is available and selected.
- * @private
- */
- isFitToPageSelected: function() {
- return this.fitToPageTicketItem_.isCapabilityAvailable() &&
- !!this.fitToPageTicketItem_.getValue();
- },
-
- /**
- * @return {number} The current input field value as an integer.
- * @private
- */
- getInputAsNumber: function() {
- return this.inputField_.valueAsNumber;
+ this.updateState_.bind(this, true));
},
/**
* Display the fit to page scaling in the scaling field if there is a valid
- * fit to page scaling value. If not, make the field blank.
+ * fit to page scaling value. If not, make the field blank. The fit to page
+ * value is always considered valid, so remove the hint if it is displayed.
* @private
*/
displayFitToPageScaling: function() {
+ this.fitToPageCheckbox_.checked = true;
this.inputField_.value = this.fitToPageScaling_ || '';
- },
-
- /**
- * Whether the displayed scaling value matches the fit to page scaling.
- * @private
- */
- displayMatchesFitToPage: function() {
- return (
- this.getInputAsNumber() == this.fitToPageScaling_ ||
- (this.inputField_.value == '' && !this.fitToPageScaling_));
+ this.removeHint_();
},
/**
@@ -145,56 +148,73 @@ cr.define('print_preview', function() {
*/
updateFitToPageScaling: function(fitToPageScaling) {
this.fitToPageScaling_ = fitToPageScaling;
- // Display the new value if fit to page is checked.
- if (this.isFitToPageSelected())
+ if (this.isFitToPageSelected_())
this.displayFitToPageScaling();
},
/**
- * Updates the state of the scaling settings UI controls.
+ * Removes the error message and red background from the input.
* @private
*/
- updateState_: function() {
- if (this.isAvailable()) {
- var displayedValue = this.getInputAsNumber();
- // If fit to page is selected and the display matches, mark valid
- // and return.
- if (this.isFitToPageSelected() && this.displayMatchesFitToPage()) {
- this.inputField_.classList.remove('invalid');
- fadeOutElement(this.getChildElement('.hint'));
- this.updateUiStateInternal();
- return;
- }
+ removeHint_: function() {
+ this.inputField_.classList.remove('invalid');
+ fadeOutElement(this.getChildElement('.hint'));
+ },
- if (!this.inputField_.validity.valid) {
- this.inputField_.classList.add('invalid');
- fadeInElement(this.getChildElement('.hint'));
- this.updateUiStateInternal();
- return;
- }
+ /** @override */
+ updateUiStateInternal: function() {
+ setIsVisible(
+ this.getChildElement('#fit-to-page-container'),
+ this.fitToPageTicketItem_.isCapabilityAvailable());
+ setIsVisible(
+ this.getChildElement('.settings-box'),
+ this.scalingTicketItem_.isCapabilityAvailable() &&
+ !this.collapseContent);
+ print_preview.SettingsSection.prototype.updateUiStateInternal.call(this);
+ },
- this.inputField_.value = this.scalingTicketItem_.getValue();
- this.inputField_.classList.remove('invalid');
- fadeOutElement(this.getChildElement('.hint'));
- }
- this.updateUiStateInternal();
+ /** @override */
+ isSectionVisibleInternal: function() {
+ return this.fitToPageTicketItem_.isCapabilityAvailable() ||
+ (!this.collapseContent_ &&
+ this.scalingTicketItem_.isCapabilityAvailable());
},
/**
- * Helper function to adjust the scaling display if fit to page is checked
- * by the user.
+ * Updates the state of the scaling settings UI controls.
+ * @param {boolean} fitToPageChange Whether this update is due to a change
+ * to the fit to page ticket item.
* @private
*/
- onFitToPageChange_: function() {
- if (this.isFitToPageSelected()) {
- // Fit to page was checked. Set scaling to the fit to page scaling.
- this.displayFitToPageScaling();
- } else if (
- this.fitToPageTicketItem_.isCapabilityAvailable() &&
- this.displayMatchesFitToPage()) {
- // Fit to page unchecked. Return to last scaling.
- this.inputField_.value = this.scalingTicketItem_.getValue();
+ updateState_: function(fitToPageChange) {
+ if (this.isAvailable()) {
+ if (fitToPageChange && this.isFitToPageSelected_()) {
+ // Fit to page was checked. Set scaling to the fit to page scaling.
+ this.displayFitToPageScaling();
+ this.scalingTicketItem_.updateValue(this.lastValidScaling_);
+ } else if (
+ fitToPageChange &&
+ this.fitToPageTicketItem_.isCapabilityAvailable()) {
+ // Fit to page unchecked. Return to last valid scaling.
+ this.fitToPageCheckbox_.checked = false;
+ if (this.scalingTicketItem_.getValue() == this.lastValidScaling_)
+ this.inputField_.value = this.lastValidScaling_;
+ else
+ this.scalingTicketItem_.updateValue(this.lastValidScaling_);
+ } else if (!this.scalingTicketItem_.isValid()) {
+ // User entered invalid scaling value, display error message.
+ this.inputField_.classList.add('invalid');
+ fadeInElement(this.getChildElement('.hint'));
+ } else {
+ // User entered valid scaling. Update the field and last valid.
+ if (!this.isFitToPageSelected_())
+ this.inputField_.value = this.scalingTicketItem_.getValue();
+ this.lastValidScaling_ =
+ /** @type {string} */ (this.scalingTicketItem_.getValue());
+ this.removeHint_();
+ }
}
+ this.updateUiStateInternal();
},
/**
@@ -203,25 +223,17 @@ cr.define('print_preview', function() {
*/
onTextfieldTimeout_: function() {
this.textfieldTimeout_ = null;
- if (!this.inputField_.validity.valid) {
- this.updateState_();
- return;
- }
- if (this.isFitToPageSelected() && !this.displayMatchesFitToPage()) {
- // User modified value away from fit to page.
- this.fitToPageTicketItem_.updateValue(false);
- }
- // Check this after checking for fit to page in case the user went
- // back to their old value.
- if (this.inputField_.valueAsNumber.toString() ===
- this.scalingTicketItem_.getValue()) {
- this.updateState_();
- return;
- }
if (this.inputField_.value == '')
return;
- this.scalingTicketItem_.updateValue(
- this.inputField_.valueAsNumber.toString());
+ // Convert value to a valid number or ''. The scaling ticket item assumes
+ // the only invalid value is ''.
+ var value =
+ (this.inputField_.validity.valid && this.inputField_.value != '') ?
+ this.inputField_.valueAsNumber.toString() :
+ '';
+ if (value != '' && this.isFitToPageSelected_())
+ this.fitToPageTicketItem_.updateValue(false);
+ this.scalingTicketItem_.updateValue(value);
},
/**
@@ -240,10 +252,12 @@ cr.define('print_preview', function() {
/**
* Called when a input event occurs on the textfield. Starts an input
- * timeout.
+ * timeout and unchecks fit to page.
* @private
*/
onTextfieldInput_: function() {
+ this.fitToPageCheckbox_.checked = false;
+
if (this.textfieldTimeout_) {
clearTimeout(this.textfieldTimeout_);
}
@@ -259,19 +273,33 @@ cr.define('print_preview', function() {
* @private
*/
onTextfieldBlur_: function() {
- if (this.inputField_.value == '' && this.inputField_.validity.valid) {
- if (this.isFitToPageSelected()) {
- this.displayFitToPageScaling();
+ if (this.inputField_.value == '') {
+ if (this.isFitToPageSelected_() && this.fitToPageCheckbox_.checked)
+ return;
+ if (this.isFitToPageSelected_() && this.inputField_.validity.valid)
+ this.fitToPageTicketItem_.updateValue(false);
+ if (this.scalingTicketItem_.getValue() == '100') {
+ // No need to update the ticket, but change the display to match.
+ this.updateState_(false);
} else {
- if (this.scalingTicketItem_.getValue() == '100')
- // No need to update the ticket, but change the display to match.
- this.inputField_.value = '100';
- else
- this.scalingTicketItem_.updateValue('100');
+ this.scalingTicketItem_.updateValue('100');
}
}
},
+ /**
+ * Called when the fit to page checkbox is clicked. Updates the fit to page
+ * ticket item and the display.
+ * @private
+ */
+ onFitToPageClicked_: function() {
+ if (this.fitToPageTicketItem_.getValue() ==
+ this.fitToPageCheckbox_.checked) {
+ this.updateState_(true);
+ } else {
+ this.fitToPageTicketItem_.updateValue(this.fitToPageCheckbox_.checked);
+ }
+ },
};
// Export
diff --git a/chromium/chrome/browser/resources/safe_browsing/download_file_types.asciipb b/chromium/chrome/browser/resources/safe_browsing/download_file_types.asciipb
index f98530a99be..5f61c4745d6 100644
--- a/chromium/chrome/browser/resources/safe_browsing/download_file_types.asciipb
+++ b/chromium/chrome/browser/resources/safe_browsing/download_file_types.asciipb
@@ -8,7 +8,7 @@
##
## Top level settings
##
-version_id: 11
+version_id: 12
sampled_ping_probability: 0.01
default_file_type {
uma_value: 18
@@ -2281,6 +2281,7 @@ file_types {
platform: PLATFORM_MAC
danger_level: ALLOW_ON_USER_GESTURE
auto_open_hint: DISALLOW_AUTO_OPEN
+ max_file_size_to_analyze: 52428800 # 50MB
}
}
file_types {
diff --git a/chromium/chrome/browser/resources/set_as_default_browser.css b/chromium/chrome/browser/resources/set_as_default_browser.css
index ec59b09b924..1d492637e45 100644
--- a/chromium/chrome/browser/resources/set_as_default_browser.css
+++ b/chromium/chrome/browser/resources/set_as_default_browser.css
@@ -21,7 +21,6 @@
/* The page block within the outer container. */
#metro-setup-outer-container .page {
-webkit-box-orient: vertical;
- -webkit-user-select: none;
background: white;
background-color: white;
border-radius: 3px;
@@ -30,6 +29,7 @@
min-width: 40px;
padding-top: 90px;
position: relative;
+ user-select: none;
width: 500px;
}
@@ -83,7 +83,6 @@
#metro-action-box button {
-webkit-margin-end: 0.4em;
-webkit-margin-start: 0;
- -webkit-user-select: none;
border-radius: 2px;
display: inline-block;
font-size: 13px;
@@ -92,6 +91,7 @@
margin-top: 0;
min-width: 80px;
transition: all 218ms;
+ user-select: none;
}
#metro-action-box button:hover {
diff --git a/chromium/chrome/browser/resources/set_as_default_browser.html b/chromium/chrome/browser/resources/set_as_default_browser.html
index 945ec326dd5..92865ee5ad4 100644
--- a/chromium/chrome/browser/resources/set_as_default_browser.html
+++ b/chromium/chrome/browser/resources/set_as_default_browser.html
@@ -33,7 +33,7 @@
</div>
</div>
<div id="chrome-logo-box">
- <img src="chrome-logo-faded.png" i18n-values="alt:chromeLogoString"></img>
+ <img src="chrome-logo-faded.png" i18n-values="alt:chromeLogoString">
</div>
</div>
</body>
diff --git a/chromium/chrome/browser/resources/settings/BUILD.gn b/chromium/chrome/browser/resources/settings/BUILD.gn
index 72ce39094c8..af4bf1d57d2 100644
--- a/chromium/chrome/browser/resources/settings/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/BUILD.gn
@@ -2,33 +2,25 @@ import("../vulcanize.gni")
import("//tools/grit/grit_rule.gni")
import("//chrome/common/features.gni")
-app_unbuilt = "vulcanized.unbuilt.html"
-lazy_load_unbuilt = "lazy_load.vulcanized.unbuilt.html"
settings_pak_file = "settings_resources.pak"
unpak_folder = "settings_resources.unpak"
-vulcanize("vulcanize_app") {
- host = "md-settings"
- html_in_file = "settings.html"
- html_out_file = app_unbuilt
- insert_in_head = "<base href=\"chrome://\$i18n{hostname}\">"
- input = rebase_path("$target_gen_dir/$unpak_folder", root_build_dir)
- js_out_file = "crisper.js"
-
- deps = [
- ":unpak",
+vulcanize("build") {
+ host = "settings"
+ html_in_files = [
+ "settings.html",
+ "lazy_load.html",
+ ]
+ html_out_files = [
+ "vulcanized.html",
+ "lazy_load.vulcanized.html",
]
-}
-
-vulcanize("vulcanize_lazy_load") {
- host = "md-settings"
- html_in_file = "lazy_load.html"
- html_out_file = lazy_load_unbuilt
insert_in_head = "<base href=\"chrome://\$i18n{hostname}\">"
input = rebase_path("$target_gen_dir/$unpak_folder", root_build_dir)
- js_out_file = "lazy_load.crisper.js"
-
- excludes = [ "/settings.html" ]
+ js_out_files = [
+ "crisper.js",
+ "lazy_load.crisper.js",
+ ]
deps = [
":unpak",
@@ -44,21 +36,6 @@ unpak("unpak") {
]
}
-polymer_css_build("build") {
- input_files = [
- app_unbuilt,
- lazy_load_unbuilt,
- ]
- output_files = [
- "vulcanized.html",
- "lazy_load.vulcanized.html",
- ]
- deps = [
- ":vulcanize_app",
- ":vulcanize_lazy_load",
- ]
-}
-
grit("flattened_resources") {
source = "settings_resources.grd"
diff --git a/chromium/chrome/browser/resources/settings/OWNERS b/chromium/chrome/browser/resources/settings/OWNERS
index a34bf8b5f11..387901fc052 100644
--- a/chromium/chrome/browser/resources/settings/OWNERS
+++ b/chromium/chrome/browser/resources/settings/OWNERS
@@ -1,8 +1,8 @@
-dbeam@chromium.org
dpapad@chromium.org
dschuyler@chromium.org
hcarmona@chromium.org
michaelpg@chromium.org
+scottchen@chromium.org
stevenjb@chromium.org
tommycli@chromium.org
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html
index 7fa89cf8bc0..8e9979679bd 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html
+++ b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html
@@ -19,12 +19,10 @@
<settings-animated-pages id="pages" current-route="{{currentRoute}}"
section="a11y" focus-config="[[focusConfig_]]">
<neon-animatable route-path="default">
- <div class="settings-box">
- <settings-toggle-button id="optionsInMenuToggle" class="start"
- label="$i18n{optionsInMenuLabel}"
- pref="{{prefs.settings.a11y.enable_menu}}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="optionsInMenuToggle"
+ label="$i18n{optionsInMenuLabel}"
+ pref="{{prefs.settings.a11y.enable_menu}}">
+ </settings-toggle-button>
<div id="subpage-trigger" class="settings-box two-line"
on-tap="onManageAccessibilityFeaturesTap_" actionable>
<div class="start">
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html b/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
index bae7631d2f4..08720eb78c2 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
+++ b/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
@@ -25,7 +25,9 @@
}
h2 ~ .settings-box,
- iron-collapse .settings-box {
+ h2 ~ settings-toggle-button,
+ iron-collapse .settings-box,
+ iron-collapse settings-toggle-button {
-webkit-margin-end: var(--settings-box-row-padding);
-webkit-margin-start: var(--settings-box-row-indent);
-webkit-padding-end: 0;
@@ -42,12 +44,10 @@
</div>
<h2>$i18n{textToSpeechHeading}</h2>
- <div class="settings-box first">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.accessibility}}"
- label="$i18n{chromeVoxLabel}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.accessibility}}"
+ label="$i18n{chromeVoxLabel}">
+ </settings-toggle-button>
<iron-collapse opened="[[prefs.settings.accessibility.value]]">
<div class="settings-box"
on-tap="onChromeVoxSettingsTap_" actionable>
@@ -56,13 +56,11 @@
aria-label="$i18n{chromeVoxOptionsLabel}"></button>
</div>
</iron-collapse>
- <div class="settings-box block">
- <settings-toggle-button
- pref="{{prefs.settings.a11y.select_to_speak}}"
- label="$i18n{selectToSpeakTitle}"
- sub-label="$i18n{selectToSpeakDescription}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.settings.a11y.select_to_speak}}"
+ label="$i18n{selectToSpeakTitle}"
+ sub-label="$i18n{selectToSpeakDescription}">
+ </settings-toggle-button>
<iron-collapse opened="[[prefs.settings.a11y.select_to_speak.value]]">
<div class="settings-box"
on-tap="onSelectToSpeakSettingsTap_" actionable>
@@ -73,22 +71,18 @@
</iron-collapse>
<h2>$i18n{displayHeading}</h2>
- <div class="settings-box block first">
- <settings-toggle-button
- pref="{{prefs.settings.a11y.high_contrast_enabled}}"
- label="$i18n{highContrastLabel}">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.settings.a11y.screen_magnifier}}"
- label="$i18n{screenMagnifierLabel}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.a11y.high_contrast_enabled}}"
+ label="$i18n{highContrastLabel}">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.a11y.screen_magnifier}}"
+ label="$i18n{screenMagnifierLabel}">
+ </settings-toggle-button>
<div class="settings-box two-line" on-tap="onDisplayTap_" actionable>
<div class="start">
$i18n{displaySettingsTitle}
- <div class="secondary" id="deisplaySettingsSecondary">
- $i18n{displaySettingsDescription}
- </div>
+ <div class="secondary">$i18n{displaySettingsDescription}</div>
</div>
<button class="subpage-arrow" is="paper-icon-button-light"
aria-label="$i18n{displaySettingsTitle}"
@@ -107,37 +101,33 @@
</div>
<h2>$i18n{keyboardHeading}</h2>
- <div class="settings-box block first">
- <settings-toggle-button
- pref="{{prefs.settings.a11y.sticky_keys_enabled}}"
- label="$i18n{stickyKeysLabel}">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.settings.a11y.virtual_keyboard}}"
- label="$i18n{onScreenKeyboardLabel}">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.settings.a11y.focus_highlight}}"
- label="$i18n{focusHighlightLabel}">
- </settings-toggle-button>
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.a11y.sticky_keys_enabled}}"
+ label="$i18n{stickyKeysLabel}">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.a11y.virtual_keyboard}}"
+ label="$i18n{onScreenKeyboardLabel}">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.a11y.focus_highlight}}"
+ label="$i18n{focusHighlightLabel}">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.a11y.caret_highlight}}"
+ label="$i18n{caretHighlightLabel}">
+ </settings-toggle-button>
+ <template is="dom-if" if="[[showExperimentalFeatures_]]">
<settings-toggle-button
- pref="{{prefs.settings.a11y.caret_highlight}}"
- label="$i18n{caretHighlightLabel}">
+ pref="{{prefs.settings.a11y.switch_access}}"
+ label="$i18n{switchAccessLabel}">
+ <button is="paper-icon-button-light"
+ class="icon-settings" slot="more-actions"
+ on-tap="onSwitchAccessSettingsTap_"
+ hidden="[[!prefs.settings.a11y.switch_access.value]]"
+ aria-label="$i18n{selectToSpeakOptionsLabel}">
+ </button>
</settings-toggle-button>
- </div>
- <template is="dom-if" if="[[showExperimentalFeatures_]]">
- <div class="settings-box block" actionable>
- <settings-toggle-button
- pref="{{prefs.settings.a11y.switch_access}}"
- label="$i18n{switchAccessLabel}">
- <button is="paper-icon-button-light"
- class="icon-settings more-actions"
- on-tap="onSwitchAccessSettingsTap_"
- hidden="[[!prefs.settings.a11y.switch_access.value]]"
- aria-label="$i18n{selectToSpeakOptionsLabel}">
- </button>
- </settings-toggle-button>
- </div>
</template>
<div class="settings-box two-line" on-tap="onKeyboardTap_" actionable>
<div class="start">
@@ -152,42 +142,44 @@
</div>
<h2>$i18n{mouseAndTouchpadHeading}</h2>
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.a11y.autoclick}}"
+ label="$i18n{clickOnStopLabel}">
+ </settings-toggle-button>
<div class="settings-box block first">
- <settings-toggle-button
- pref="{{prefs.settings.a11y.autoclick}}"
- label="$i18n{clickOnStopLabel}">
- </settings-toggle-button>
- <div class="list-item settings-toggle-button-spacer">
- <div>$i18n{delayBeforeClickLabel}</div>
+ <div class="list-item sub-item">
+ <div class="start">$i18n{delayBeforeClickLabel}</div>
<settings-dropdown-menu label="$i18n{delayBeforeClickLabel}"
pref="{{prefs.settings.a11y.autoclick_delay_ms}}"
menu-options="[[autoClickDelayOptions_]]"
disabled="[[!prefs.settings.a11y.autoclick.value]]">
</settings-dropdown-menu>
</div>
- <settings-toggle-button
- pref="{{prefs.settings.touchpad.enable_tap_dragging}}"
- label="$i18n{tapDraggingLabel}">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.settings.a11y.large_cursor_enabled}}"
- label="$i18n{largeMouseCursorLabel}">
- </settings-toggle-button>
- <div class="list-item sub-item"
- hidden$="[[!prefs.settings.a11y.large_cursor_enabled.value]]">
+ </div>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.touchpad.enable_tap_dragging}}"
+ label="$i18n{tapDraggingLabel}">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.a11y.large_cursor_enabled}}"
+ label="$i18n{largeMouseCursorLabel}">
+ </settings-toggle-button>
+ <div class="settings-box block continuation"
+ hidden$="[[!prefs.settings.a11y.large_cursor_enabled.value]]">
+ <div class="list-item sub-item">
<div class="start">$i18n{largeMouseCursorSizeLabel}</div>
<settings-slider
- pref="{{prefs.settings.a11y.large_cursor_dip_size}}"
- min="25" max="64"
- label-min="$i18n{largeMouseCursorSizeDefaultLabel}"
- label-max="$i18n{largeMouseCursorSizeLargeLabel}">
+ pref="{{prefs.settings.a11y.large_cursor_dip_size}}"
+ min="25" max="64"
+ label-min="$i18n{largeMouseCursorSizeDefaultLabel}"
+ label-max="$i18n{largeMouseCursorSizeLargeLabel}">
</settings-slider>
</div>
- <settings-toggle-button
- pref="{{prefs.settings.a11y.cursor_highlight}}"
- label="$i18n{cursorHighlightLabel}">
- </settings-toggle-button>
</div>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.a11y.cursor_highlight}}"
+ label="$i18n{cursorHighlightLabel}">
+ </settings-toggle-button>
<div class="settings-box two-line" on-tap="onMouseTap_" actionable>
<div class="start">
$i18n{mouseSettingsTitle}
@@ -201,12 +193,10 @@
</div>
<h2>$i18n{audioHeading}</h2>
- <div class="settings-box block first">
- <settings-toggle-button
- pref="{{prefs.settings.a11y.mono_audio}}"
- label="$i18n{monoAudioLabel}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.a11y.mono_audio}}"
+ label="$i18n{monoAudioLabel}">
+ </settings-toggle-button>
<template is="dom-if" if="[[!isGuest_]]">
<a class="settings-box two-line inherit-color no-outline" tabindex="-1"
diff --git a/chromium/chrome/browser/resources/settings/about_page/about_page.html b/chromium/chrome/browser/resources/settings/about_page/about_page.html
index 3e050878b50..903457b27f5 100644
--- a/chromium/chrome/browser/resources/settings/about_page/about_page.html
+++ b/chromium/chrome/browser/resources/settings/about_page/about_page.html
@@ -60,7 +60,7 @@
}
iron-icon[icon='settings:check-circle'] {
- fill: var(--paper-blue-600);
+ fill: var(--google-blue-500);
}
iron-icon[icon='settings:error'] {
@@ -77,7 +77,7 @@
<if expr="_google_chrome and is_macosx">
#promoteUpdater[disabled] {
- @apply(--settings-secondary);
+ @apply(--cr-secondary-text);
}
</if>
</style>
diff --git a/chromium/chrome/browser/resources/settings/about_page/about_page.js b/chromium/chrome/browser/resources/settings/about_page/about_page.js
index c9842d519b7..4270abf92a8 100644
--- a/chromium/chrome/browser/resources/settings/about_page/about_page.js
+++ b/chromium/chrome/browser/resources/settings/about_page/about_page.js
@@ -136,19 +136,19 @@ Polymer({
settings.LifetimeBrowserProxyImpl.getInstance();
// <if expr="chromeos">
- this.addEventListener('target-channel-changed', function(e) {
+ this.addEventListener('target-channel-changed', e => {
this.targetChannel_ = e.detail;
- }.bind(this));
+ });
- this.aboutBrowserProxy_.getChannelInfo().then(function(info) {
+ this.aboutBrowserProxy_.getChannelInfo().then(info => {
this.currentChannel_ = info.currentChannel;
this.targetChannel_ = info.targetChannel;
this.startListening_();
- }.bind(this));
+ });
- this.aboutBrowserProxy_.getRegulatoryInfo().then(function(info) {
+ this.aboutBrowserProxy_.getRegulatoryInfo().then(info => {
this.regulatoryInfo_ = info;
- }.bind(this));
+ });
// </if>
// <if expr="not chromeos">
this.startListening_();
diff --git a/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js b/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
index beb4b67e2ec..df85fd8c99e 100644
--- a/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
@@ -18,8 +18,8 @@ var RegulatoryInfo;
/**
* @typedef {{
- * currentChannel: string,
- * targetChannel: string,
+ * currentChannel: BrowserChannel,
+ * targetChannel: BrowserChannel,
* canChangeChannel: boolean,
* }}
*/
@@ -48,6 +48,7 @@ var AboutPageUpdateInfo;
*/
var BrowserChannel = {
BETA: 'beta-channel',
+ CANARY: 'canary-channel',
DEV: 'dev-channel',
STABLE: 'stable-channel',
};
@@ -102,6 +103,8 @@ cr.define('settings', function() {
switch (channel) {
case BrowserChannel.BETA:
return 'aboutChannelBeta';
+ case BrowserChannel.CANARY:
+ return 'aboutChannelCanary';
case BrowserChannel.DEV:
return 'aboutChannelDev';
case BrowserChannel.STABLE:
@@ -120,6 +123,7 @@ cr.define('settings', function() {
function isTargetChannelMoreStable(currentChannel, targetChannel) {
// List of channels in increasing stability order.
var channelList = [
+ BrowserChannel.CANARY,
BrowserChannel.DEV,
BrowserChannel.BETA,
BrowserChannel.STABLE,
diff --git a/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html b/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html
index 11845c1d0da..7f48dba4db3 100644
--- a/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html
+++ b/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html
@@ -12,8 +12,8 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{aboutChangeChannel}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{aboutChangeChannel}</div>
+ <div slot="body">
<!-- TODO(dbeam): this can be policy-controlled. Show this in the UI.
https://www.chromium.org/administrators/policy-list-3#ChromeOsReleaseChannel
-->
@@ -34,7 +34,7 @@
<div>[[warning_.description]]</div>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelTap_"
id="cancel">$i18n{cancel}</paper-button>
<paper-button id="changeChannel" class="action-button"
diff --git a/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js b/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js
index ceb0322b676..0892b22220b 100644
--- a/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js
+++ b/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js
@@ -48,14 +48,14 @@ Polymer({
/** @override */
ready: function() {
this.browserProxy_ = settings.AboutPageBrowserProxyImpl.getInstance();
- this.browserProxy_.getChannelInfo().then(function(info) {
+ this.browserProxy_.getChannelInfo().then(info => {
this.currentChannel_ = info.currentChannel;
this.targetChannel_ = info.targetChannel;
// Pre-populate radio group with target channel.
var radioGroup = this.$$('paper-radio-group');
radioGroup.select(this.targetChannel_);
radioGroup.focus();
- }.bind(this));
+ });
},
/** @override */
diff --git a/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js b/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js
index 8a5842bf2b8..471263b7ec3 100644
--- a/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js
+++ b/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js
@@ -31,9 +31,9 @@ Polymer({
var browserProxy = settings.AboutPageBrowserProxyImpl.getInstance();
browserProxy.pageReady();
- browserProxy.getVersionInfo().then(function(versionInfo) {
+ browserProxy.getVersionInfo().then(versionInfo => {
this.versionInfo_ = versionInfo;
- }.bind(this));
+ });
this.updateChannelInfo_();
},
@@ -41,13 +41,13 @@ Polymer({
/** @private */
updateChannelInfo_: function() {
var browserProxy = settings.AboutPageBrowserProxyImpl.getInstance();
- browserProxy.getChannelInfo().then(function(info) {
+ browserProxy.getChannelInfo().then(info => {
// Display the target channel for the 'Currently on' message.
this.currentlyOnChannelText_ = this.i18n(
'aboutCurrentlyOnChannel',
this.i18n(settings.browserChannelToI18nId(info.targetChannel)));
this.canChangeChannel_ = info.canChangeChannel;
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html b/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html
index 1ad1bd610ef..3a336109f1f 100644
--- a/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html
+++ b/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html
@@ -10,11 +10,11 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{aboutUpdateWarningTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{aboutUpdateWarningTitle}</div>
+ <div slot="body">
<div id="update-warning-message"></div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="cancel" class="cancel-button"
on-tap="onCancelTap_">$i18n{cancel}</paper-button>
<paper-button id="continue" class="action-button"
diff --git a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.js b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.js
index 580849a8348..8c21abab017 100644
--- a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.js
+++ b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.js
@@ -53,7 +53,11 @@ Polymer({
},
/** @private */
- onSubpageTap_: function() {
+ onSubpageTap_: function(event) {
+ if (event.target && event.target.tagName == 'A') {
+ // Filter out events coming from 'Learn more' link
+ return;
+ }
if (this.androidAppsInfo.playStoreEnabled)
settings.navigateTo(settings.routes.ANDROID_APPS_DETAILS);
},
diff --git a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html
index 87b6511ae99..58cc44902e0 100644
--- a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html
+++ b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html
@@ -33,9 +33,9 @@
<dialog is="cr-dialog" id="confirmDisableDialog" close-text="$i18n{close}"
on-cancel="onConfirmDisableDialogCancel_"
on-close="onConfirmDisableDialogClose_">
- <div class="title" slot="title">$i18n{androidAppsDisableDialogTitle}</div>
- <div class="body" slot="body" inner-h-t-m-l="[[dialogBody_]]"></div>
- <div class="button-container" slot="button-container">
+ <div slot="title">$i18n{androidAppsDisableDialogTitle}</div>
+ <div slot="body" inner-h-t-m-l="[[dialogBody_]]"></div>
+ <div slot="button-container">
<paper-button class="cancel-button"
on-tap="onConfirmDisableDialogCancel_">
$i18n{cancel}
diff --git a/chromium/chrome/browser/resources/settings/animation/animation.js b/chromium/chrome/browser/resources/settings/animation/animation.js
index 8f369ce9865..bd8c2a74da9 100644
--- a/chromium/chrome/browser/resources/settings/animation/animation.js
+++ b/chromium/chrome/browser/resources/settings/animation/animation.js
@@ -80,10 +80,10 @@ cr.define('settings.animation', function() {
* @private
*/
queueDispatch_: function(e) {
- setTimeout(function() {
+ setTimeout(() => {
this.dispatchEvent(e);
this.animation_ = undefined;
- }.bind(this));
+ });
},
};
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js b/chromium/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js
index 779818bd13a..c75464dc66e 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js
@@ -17,6 +17,17 @@ cr.define('settings', function() {
/** @return {boolean} Whether the current profile is supervised. */
isSupervised() {}
+ /**
+ * @return {!Promise<boolean>} Whether the wallpaper setting row should be
+ * visible.
+ */
+ isWallpaperSettingVisible() {}
+
+ /**
+ * @return {!Promise<boolean>} Whether the wallpaper is policy controlled.
+ */
+ isWallpaperPolicyControlled() {}
+
// <if expr="chromeos">
openWallpaperManager() {}
@@ -61,6 +72,16 @@ cr.define('settings', function() {
// <if expr="chromeos">
/** @override */
+ isWallpaperSettingVisible() {
+ return cr.sendWithPromise('isWallpaperSettingVisible');
+ }
+
+ /** @override */
+ isWallpaperPolicyControlled() {
+ return cr.sendWithPromise('isWallpaperPolicyControlled');
+ }
+
+ /** @override */
openWallpaperManager() {
chrome.send('openWallpaperManager');
}
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js b/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
index b50fe910da4..99d2c1e7c7f 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
@@ -118,9 +118,8 @@ Polymer({
*/
setFontsData_: function(response) {
var fontMenuOptions = [];
- for (var i = 0; i < response.fontList.length; ++i) {
- fontMenuOptions.push(
- {value: response.fontList[i][0], name: response.fontList[i][1]});
+ for (var fontData of response.fontList) {
+ fontMenuOptions.push({value: fontData[0], name: fontData[1]});
}
this.fontOptions_ = fontMenuOptions;
this.advancedExtensionUrl_ = response.extensionUrl;
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html
index 0e7f31afb9f..da28035f148 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html
@@ -50,9 +50,16 @@
$i18n{openWallpaperApp}
</div>
</div>
- <button class="icon-external" is="paper-icon-button-light"
- aria-label="$i18n{setWallpaper}"
- aria-describedby="wallpaperSecondary"></button>
+ <template is="dom-if" if="[[isWallpaperPolicyControlled_]]">
+ <cr-policy-indicator id="wallpaperPolicyIndicator"
+ indicator-type="devicePolicy">
+ </cr-policy-indicator>
+ </template>
+ <button class="icon-external" id="showWallpaperManager"
+ is="paper-icon-button-light" aria-label="$i18n{setWallpaper}"
+ disabled="[[isWallpaperPolicyControlled_]]"
+ aria-describedby="wallpaperSecondary">
+ </button>
</div>
<div class="settings-box two-line"
hidden="[[!pageVisibility.setTheme]]">
@@ -71,7 +78,8 @@
</div>
<button class="icon-external" is="paper-icon-button-light"
actionable aria-label="$i18n{themes}"
- aria-describedby="themesSecondary"></button>
+ aria-describedby="themesSecondary">
+ </button>
</a>
<if expr="not is_linux or chromeos">
<template is="dom-if" if="[[prefs.extensions.theme.id.value]]">
@@ -104,17 +112,15 @@
</div>
</if>
</div>
- <div class="settings-box"
- hidden="[[!pageVisibility.homeButton]]">
- <settings-toggle-button class="start" elide-label
- pref="{{prefs.browser.show_home_button}}"
- label="$i18n{showHomeButton}"
- sub-label="[[getShowHomeSubLabel_(
- prefs.browser.show_home_button.value,
- prefs.homepage_is_newtabpage.value,
- prefs.homepage.value)]]">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button elide-label
+ hidden="[[!pageVisibility.homeButton]]"
+ pref="{{prefs.browser.show_home_button}}"
+ label="$i18n{showHomeButton}"
+ sub-label="[[getShowHomeSubLabel_(
+ prefs.browser.show_home_button.value,
+ prefs.homepage_is_newtabpage.value,
+ prefs.homepage.value)]]">
+ </settings-toggle-button>
<template is="dom-if" if="[[prefs.browser.show_home_button.value]]">
<div class="list-frame" hidden="[[!pageVisibility.homeButton]]">
<settings-radio-group pref="{{prefs.homepage_is_newtabpage}}">
@@ -144,23 +150,19 @@
</settings-radio-group>
</div>
</template>
- <div class="settings-box"
- hidden="[[!pageVisibility.bookmarksBar]]">
- <settings-toggle-button class="start"
- pref="{{prefs.bookmark_bar.show_on_all_tabs}}"
- label="$i18n{showBookmarksBar}">
- </settings-toggle-button>
- </div>
- <div class$="settings-box [[getFirst_(pageVisibility.bookmarksBar)]]">
+ <settings-toggle-button hidden="[[!pageVisibility.bookmarksBar]]"
+ pref="{{prefs.bookmark_bar.show_on_all_tabs}}"
+ label="$i18n{showBookmarksBar}">
+ </settings-toggle-button>
<if expr="is_linux and not chromeos">
- <settings-toggle-button class="start"
- pref="{{prefs.browser.custom_chrome_frame}}"
- label="$i18n{showWindowDecorations}"
- inverted>
- </settings-toggle-button>
- </div>
- <div class="settings-box">
+ <settings-toggle-button
+ class$="[[getFirst_(pageVisibility.bookmarksBar)]]"
+ pref="{{prefs.browser.custom_chrome_frame}}"
+ label="$i18n{showWindowDecorations}"
+ inverted>
+ </settings-toggle-button>
</if>
+ <div class="settings-box">
<div class="start">$i18n{fontSize}</div>
<settings-dropdown-menu id="defaultFontSize" label="$i18n{fontSize}"
pref="{{prefs.webkit.webprefs.default_font_size}}"
@@ -191,12 +193,9 @@
</div>
</div>
<if expr="is_macosx">
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.webkit.webprefs.tabs_to_links}}"
- label="$i18n{tabsToLinks}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button pref="{{prefs.webkit.webprefs.tabs_to_links}}"
+ label="$i18n{tabsToLinks}">
+ </settings-toggle-button>
</if>
</neon-animatable>
<template is="dom-if" route-path="/fonts">
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js
index 8b22e8fe6d8..be01b65fc12 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js
@@ -14,14 +14,6 @@ var SIZE_DIFFERENCE_FIXED_STANDARD_ = 3;
/**
* 'settings-appearance-page' is the settings page containing appearance
* settings.
- *
- * Example:
- *
- * <iron-animated-pages>
- * <settings-appearance-page prefs="{{prefs}}">
- * </settings-appearance-page>
- * ... other pages ...
- * </iron-animated-pages>
*/
Polymer({
is: 'settings-appearance-page',
@@ -43,6 +35,9 @@ Polymer({
/** @private */
defaultZoom_: Number,
+ /** @private */
+ isWallpaperPolicyControlled_: {type: Boolean, value: true},
+
/**
* List of options for the font size drop-down menu.
* @type {!DropdownMenuOptionList}
@@ -140,9 +135,20 @@ Polymer({
this.$.defaultFontSize.menuOptions = this.fontSizeOptions_;
// TODO(dschuyler): Look into adding a listener for the
// default zoom percent.
- this.browserProxy_.getDefaultZoom().then(function(zoom) {
+ this.browserProxy_.getDefaultZoom().then(zoom => {
this.defaultZoom_ = zoom;
- }.bind(this));
+ });
+ // <if expr="chromeos">
+ this.browserProxy_.isWallpaperSettingVisible().then(
+ isWallpaperSettingVisible => {
+ assert(this.pageVisibility);
+ this.pageVisibility.setWallpaper = isWallpaperSettingVisible;
+ });
+ this.browserProxy_.isWallpaperPolicyControlled().then(
+ isPolicyControlled => {
+ this.isWallpaperPolicyControlled_ = isPolicyControlled;
+ });
+ // </if>
},
/**
@@ -271,9 +277,9 @@ Polymer({
if (themeId) {
assert(!useSystemTheme);
- this.browserProxy_.getThemeInfo(themeId).then(function(info) {
+ this.browserProxy_.getThemeInfo(themeId).then(info => {
this.themeSublabel_ = info.name;
- }.bind(this));
+ });
this.themeUrl_ = 'https://chrome.google.com/webstore/detail/' + themeId;
return;
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/fonts_browser_proxy.js b/chromium/chrome/browser/resources/settings/appearance_page/fonts_browser_proxy.js
index d513b3ad19e..306c3839b09 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/fonts_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/appearance_page/fonts_browser_proxy.js
@@ -4,7 +4,10 @@
/**
* @typedef {{
- * fontList: Array<{0: string, 1: (string|undefined), 2: (string|undefined)}>,
+ * fontList: !Array<{
+ * 0: string,
+ * 1: (string|undefined),
+ * 2: (string|undefined)}>,
* extensionUrl: string
* }}
*/
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.js b/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.js
index 95faaa58fdf..42c751b8793 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.js
+++ b/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.js
@@ -134,8 +134,8 @@ Polymer({
return;
}
- this.browserProxy_.validateStartupPage(this.value).then(function(isValid) {
+ this.browserProxy_.validateStartupPage(this.value).then(isValid => {
this.invalid = !isValid;
- }.bind(this));
+ });
},
});
diff --git a/chromium/chrome/browser/resources/settings/basic_page/basic_page.html b/chromium/chrome/browser/resources/settings/basic_page/basic_page.html
index 26f5b266b49..f622ff71a9e 100644
--- a/chromium/chrome/browser/resources/settings/basic_page/basic_page.html
+++ b/chromium/chrome/browser/resources/settings/basic_page/basic_page.html
@@ -3,6 +3,7 @@
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="../appearance_page/appearance_page.html">
+<link rel="import" href="../change_password_page/change_password_page.html">
<link rel="import" href="../controls/settings_idle_load.html">
<link rel="import" href="../on_startup_page/on_startup_page.html">
<link rel="import" href="../people_page/people_page.html">
@@ -130,6 +131,11 @@
</settings-section>
</template>
</if>
+ <template is="dom-if" if="[[showChangePassword]]" restamp>
+ <settings-section section="changePassword">
+ <settings-change-password-page></settings-change-password-page>
+ </settings-section>
+ </template>
<template is="dom-if" if="[[showPage_(pageVisibility.people)]]" restamp>
<settings-section page-title="$i18n{peoplePageTitle}"
section="people">
diff --git a/chromium/chrome/browser/resources/settings/basic_page/basic_page.js b/chromium/chrome/browser/resources/settings/basic_page/basic_page.js
index d2c1e42107a..da7f5f65ebe 100644
--- a/chromium/chrome/browser/resources/settings/basic_page/basic_page.js
+++ b/chromium/chrome/browser/resources/settings/basic_page/basic_page.js
@@ -37,6 +37,14 @@ Polymer({
},
},
+ showChangePassword: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.valueExists('changePasswordEnabled') &&
+ loadTimeData.getBoolean('changePasswordEnabled');
+ },
+ },
+
/**
* Dictionary defining page visibility.
* @type {!GuestModePageVisibility}
@@ -99,9 +107,13 @@ Polymer({
attached: function() {
this.currentRoute_ = settings.getCurrentRoute();
- this.addEventListener('chrome-cleanup-dismissed', function(e) {
+ this.addEventListener('chrome-cleanup-dismissed', e => {
this.showChromeCleanup = false;
- }.bind(this));
+ });
+
+ this.addEventListener('change-password-clicked', e => {
+ this.showChangePassword = false;
+ });
if (settings.AndroidAppsBrowserProxyImpl) {
cr.addWebUIListener(
@@ -247,9 +259,9 @@ Polymer({
*/
advancedToggleExpandedChanged_: function() {
if (this.advancedToggleExpanded) {
- this.async(function() {
+ this.async(() => {
this.$$('#advancedPageTemplate').get();
- }.bind(this));
+ });
}
},
diff --git a/chromium/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp
index 4af32638dfe..a984890d1c0 100644
--- a/chromium/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp
@@ -9,6 +9,7 @@
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'../android_apps_page/compiled_resources2.gyp:android_apps_browser_proxy',
+ '../change_password_page/compiled_resources2.gyp:change_password_browser_proxy',
'../chrome_cleanup_page/compiled_resources2.gyp:chrome_cleanup_proxy',
'../compiled_resources2.gyp:route',
'../compiled_resources2.gyp:search_settings',
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.html b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.html
deleted file mode 100644
index 7c27747542f..00000000000
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.html
+++ /dev/null
@@ -1,140 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
-<link rel="import" href="../bluetooth_page/bluetooth_device_list_item.html">
-<link rel="import" href="../settings_shared_css.html">
-
-<dom-module id="bluetooth-device-dialog">
- <template>
- <style include="settings-shared iron-flex">
- #pairing {
- margin-bottom: 10px;
- }
-
- #pairing paper-input {
- text-align: center;
- }
-
- #pinDiv {
- margin-top: 10px;
- }
-
- .dialog-message {
- margin-bottom: 10px;
- }
-
- div.contents {
- height: 250px;
- }
-
- /* .display indicates a displayed pin code or passkey. */
- span.display {
- border: 1px solid #ccc;
- border-radius: 4px;
- box-shadow: 0 0 0 1px #222;
- color: #222;
- font-size: 123.08%; /* 16px / 13px */
- height: 38px;
- line-height: 38px;
- margin: 0 5px;
- padding: 0 15px;
- text-align: center;
- text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
- }
-
- span.display.next {
- background: rgb(77, 144, 254);
- border: 2px solid rgb(77, 144, 254);
- box-shadow: none;
- color: #fff;
- }
-
- span.display.untyped {
- border: 1px solid #d4d4d4;
- box-shadow: 0 0 0 1px #888;
- color: #666;
- }
-
- /* .confirm indicates a confirmation passkey. */
- span.confirm {
- color: #999;
- font-size: 153.85%; /* 20px / 13px */
- font-weight: 600; /* semibold */
- margin: 0 20px;
- }
- </style>
- <dialog is="cr-dialog" id="dialog" on-cancel="onDialogCanceled_"
- close-text="$i18n{close}" on-closed="onDialogCanceled_">
- <div class="title" slot="title">$i18n{bluetoothPairDevicePageTitle}</div>
- <div class="body" slot="body">
- <div class="contents layout vertical center center-justified">
- <template is="dom-if" if="[[isDialogType_(dialogId, 'pairDevice')]]">
- <div id="pairing" class="settings-box first layout vertical center
- center-justified">
- <div class="dialog-message">
- [[getMessage_(pairingDevice, pairingEvent_)]]
- </div>
- <div hidden$="[[!showEnterPincode_(pairingEvent_)]]">
- <paper-input id="pincode" minlength="1" maxlength="16"
- type="text" auto-validate value="{{pinOrPass}}">
- </paper-input>
- </div>
- <div hidden$="[[!showEnterPasskey_(pairingEvent_)]]">
- <paper-input id="passkey" minlength="6" maxlength="6"
- type="text" auto-validate value="{{pinOrPass}}">
- </paper-input>
- </div>
- <div id="pinDiv" class="layout horizontal center center-justified"
- hidden="[[!showDisplayPassOrPin_(pairingEvent_)]]">
- <template is="dom-repeat" items="[[digits]]">
- <span class$="[[getPinClass_(index, pairingEvent_)]]">
- [[getPinDigit_(index, pairingEvent_)]]
- </span>
- </template>
- <span class$="[[getPinClass_(-1, pairingEvent_)]]"
- hidden="[[showAcceptReject_(pairingEvent_)]]">
- $i18n{bluetoothEnterKey}
- </span>
- </div>
- </div>
- </template>
- <template is="dom-if"
- if="[[isDialogType_('connectError', dialogId)]]">
- <div class="settings-box first layout vertical center
- center-justified">
- <div class="dialog-message">[[errorMessage]]</div>
- </div>
- </template>
- </div>
- </div>
- <div class="button-container" slot="button-container">
- <template is="dom-if" if="[[isDialogType_('pairDevice', dialogId)]]">
- <paper-button hidden$="[[!showAcceptReject_(pairingEvent_)]]"
- on-tap="onAcceptTap_">$i18n{bluetoothAccept}</paper-button>
- <paper-button hidden$="[[!showAcceptReject_(pairingEvent_)]]"
- on-tap="onRejectTap_">$i18n{bluetoothReject}</paper-button>
- <paper-button hidden$="[[!showConnect_(pairingEvent_)]]"
- disabled="[[!enableConnect_(pairingEvent_, pinOrPass)]]"
- on-tap="onConnectTap_">$i18n{bluetoothPair}</paper-button>
- <paper-button
- hidden$="[[!showDismiss_(pairingDevice, pairingEvent_)]]"
- on-tap="close">$i18n{bluetoothDismiss}</paper-button>
- <paper-button hidden$="[[showDismiss_(pairingDevice, pairingEvent_)]]"
- on-tap="onCancelTap_">
- $i18n{cancel}
- </paper-button>
- </template>
- <template is="dom-if" if="[[isDialogType_('connectError', dialogId)]]">
- <paper-button on-tap="close">$i18n{bluetoothDismiss}
- </paper-button>
- </template>
- </div>
- </dialog>
- </template>
- <script src="bluetooth_device_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.js b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.js
deleted file mode 100644
index 674f161c4d3..00000000000
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_dialog.js
+++ /dev/null
@@ -1,395 +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.
-
-cr.exportPath('settings');
-
-var PairingEventType = chrome.bluetoothPrivate.PairingEventType;
-
-// NOTE(dbeam): even though this behavior is only used privately, it must
-// be globally accessible for Closure's --polymer_pass to compile happily.
-
-/** @polymerBehavior */
-settings.BluetoothPairDeviceBehavior = {
- properties: {
- /**
- * Current Pairing device.
- * @type {!chrome.bluetooth.Device|undefined}
- */
- pairingDevice: Object,
-
- /**
- * Current Pairing event.
- * @type {?chrome.bluetoothPrivate.PairingEvent}
- */
- pairingEvent_: {
- type: Object,
- value: null,
- },
-
- /** Pincode or passkey value, used to trigger connect enabled changes. */
- pinOrPass: String,
-
- /**
- * Interface for bluetoothPrivate calls. Set in bluetooth-page.
- * @type {BluetoothPrivate}
- * @private
- */
- bluetoothPrivate: {
- type: Object,
- value: chrome.bluetoothPrivate,
- },
-
- /**
- * @const
- * @type {!Array<number>}
- */
- digits: {
- type: Array,
- readOnly: true,
- value: [0, 1, 2, 3, 4, 5],
- },
- },
-
- observers: [
- 'pairingChanged_(pairingDevice, pairingEvent_)',
- ],
-
- /**
- * Listener for chrome.bluetoothPrivate.onPairing events.
- * @type {?function(!chrome.bluetoothPrivate.PairingEvent)}
- * @private
- */
- bluetoothPrivateOnPairingListener_: null,
-
- /** Called when the dialog is opened. Starts listening for pairing events. */
- startPairing: function() {
- if (!this.bluetoothPrivateOnPairingListener_) {
- this.bluetoothPrivateOnPairingListener_ =
- this.onBluetoothPrivateOnPairing_.bind(this);
- this.bluetoothPrivate.onPairing.addListener(
- this.bluetoothPrivateOnPairingListener_);
- }
- },
-
- /** Called when the dialog is closed. */
- endPairing: function() {
- if (this.bluetoothPrivateOnPairingListener_) {
- this.bluetoothPrivate.onPairing.removeListener(
- this.bluetoothPrivateOnPairingListener_);
- this.bluetoothPrivateOnPairingListener_ = null;
- }
- this.pairingEvent_ = null;
- },
-
- /**
- * Process bluetoothPrivate.onPairing events.
- * @param {!chrome.bluetoothPrivate.PairingEvent} event
- * @private
- */
- onBluetoothPrivateOnPairing_: function(event) {
- if (!this.pairingDevice ||
- event.device.address != this.pairingDevice.address) {
- return;
- }
- if (event.pairing == PairingEventType.KEYS_ENTERED &&
- event.passkey === undefined && this.pairingEvent_) {
- // 'keysEntered' event might not include the updated passkey so preserve
- // the current one.
- event.passkey = this.pairingEvent_.passkey;
- }
- this.pairingEvent_ = event;
- },
-
- /** @private */
- pairingChanged_: function() {
- // Auto-close the dialog when pairing completes.
- if (this.pairingDevice.paired && !this.pairingDevice.connecting &&
- this.pairingDevice.connected) {
- this.close();
- return;
- }
- this.pinOrPass = '';
- },
-
- /**
- * @return {string}
- * @private
- */
- getMessage_: function() {
- var message;
- if (!this.pairingEvent_)
- message = 'bluetoothStartConnecting';
- else
- message = this.getEventDesc_(this.pairingEvent_.pairing);
- return this.i18n(message, this.pairingDevice.name);
- },
-
- /**
- * @return {boolean}
- * @private
- */
- showEnterPincode_: function() {
- return !!this.pairingEvent_ &&
- this.pairingEvent_.pairing == PairingEventType.REQUEST_PINCODE;
- },
-
- /**
- * @return {boolean}
- * @private
- */
- showEnterPasskey_: function() {
- return !!this.pairingEvent_ &&
- this.pairingEvent_.pairing == PairingEventType.REQUEST_PASSKEY;
- },
-
- /**
- * @return {boolean}
- * @private
- */
- showDisplayPassOrPin_: function() {
- if (!this.pairingEvent_)
- return false;
- var pairing = this.pairingEvent_.pairing;
- return (
- pairing == PairingEventType.DISPLAY_PINCODE ||
- pairing == PairingEventType.DISPLAY_PASSKEY ||
- pairing == PairingEventType.CONFIRM_PASSKEY ||
- pairing == PairingEventType.KEYS_ENTERED);
- },
-
- /**
- * @return {boolean}
- * @private
- */
- showAcceptReject_: function() {
- return !!this.pairingEvent_ &&
- this.pairingEvent_.pairing == PairingEventType.CONFIRM_PASSKEY;
- },
-
- /**
- * @return {boolean}
- * @private
- */
- showConnect_: function() {
- if (!this.pairingEvent_)
- return false;
- var pairing = this.pairingEvent_.pairing;
- return pairing == PairingEventType.REQUEST_PINCODE ||
- pairing == PairingEventType.REQUEST_PASSKEY;
- },
-
- /**
- * @return {boolean}
- * @private
- */
- enableConnect_: function() {
- if (!this.showConnect_())
- return false;
- var inputId =
- (this.pairingEvent_.pairing == PairingEventType.REQUEST_PINCODE) ?
- '#pincode' :
- '#passkey';
- var paperInput = /** @type {!PaperInputElement} */ (this.$$(inputId));
- assert(paperInput);
- /** @type {string} */ var value = paperInput.value;
- return !!value && paperInput.validate();
- },
-
- /**
- * @return {boolean}
- * @private
- */
- showDismiss_: function() {
- return this.pairingDevice.paired ||
- (!!this.pairingEvent_ &&
- this.pairingEvent_.pairing == PairingEventType.COMPLETE);
- },
-
- /** @private */
- onAcceptTap_: function() {
- this.sendResponse_(chrome.bluetoothPrivate.PairingResponse.CONFIRM);
- },
-
- /** @private */
- onConnectTap_: function() {
- this.sendResponse_(chrome.bluetoothPrivate.PairingResponse.CONFIRM);
- },
-
- /** @private */
- onRejectTap_: function() {
- this.sendResponse_(chrome.bluetoothPrivate.PairingResponse.REJECT);
- },
-
- /**
- * @param {!chrome.bluetoothPrivate.PairingResponse} response
- * @private
- */
- sendResponse_: function(response) {
- if (!this.pairingDevice)
- return;
- var options =
- /** @type {!chrome.bluetoothPrivate.SetPairingResponseOptions} */ {
- device: this.pairingDevice,
- response: response
- };
- if (response == chrome.bluetoothPrivate.PairingResponse.CONFIRM) {
- var pairing = this.pairingEvent_.pairing;
- if (pairing == PairingEventType.REQUEST_PINCODE)
- options.pincode = this.$$('#pincode').value;
- else if (pairing == PairingEventType.REQUEST_PASSKEY)
- options.passkey = parseInt(this.$$('#passkey').value, 10);
- }
- this.bluetoothPrivate.setPairingResponse(options, function() {
- if (chrome.runtime.lastError) {
- // TODO(stevenjb): Show error.
- console.error(
- 'Error setting pairing response: ' + options.device.name +
- ': Response: ' + options.response +
- ': Error: ' + chrome.runtime.lastError.message);
- }
- this.close();
- }.bind(this));
-
- this.fire('response', options);
- },
-
- /**
- * @param {!PairingEventType} eventType
- * @return {string}
- * @private
- */
- getEventDesc_: function(eventType) {
- assert(eventType);
- if (eventType == PairingEventType.COMPLETE ||
- eventType == PairingEventType.KEYS_ENTERED ||
- eventType == PairingEventType.REQUEST_AUTHORIZATION) {
- return 'bluetoothStartConnecting';
- }
- return 'bluetooth_' + /** @type {string} */ (eventType);
- },
-
- /**
- * @param {number} index
- * @return {string}
- * @private
- */
- getPinDigit_: function(index) {
- if (!this.pairingEvent_)
- return '';
- var digit = '0';
- var pairing = this.pairingEvent_.pairing;
- if (pairing == PairingEventType.DISPLAY_PINCODE &&
- this.pairingEvent_.pincode &&
- index < this.pairingEvent_.pincode.length) {
- digit = this.pairingEvent_.pincode[index];
- } else if (
- this.pairingEvent_.passkey &&
- (pairing == PairingEventType.DISPLAY_PASSKEY ||
- pairing == PairingEventType.KEYS_ENTERED ||
- pairing == PairingEventType.CONFIRM_PASSKEY)) {
- var passkeyString = String(this.pairingEvent_.passkey);
- if (index < passkeyString.length)
- digit = passkeyString[index];
- }
- return digit;
- },
-
- /**
- * @param {number} index
- * @return {string}
- * @private
- */
- getPinClass_: function(index) {
- if (!this.pairingEvent_)
- return '';
- if (this.pairingEvent_.pairing == PairingEventType.CONFIRM_PASSKEY)
- return 'confirm';
- var cssClass = 'display';
- if (this.pairingEvent_.pairing == PairingEventType.DISPLAY_PASSKEY) {
- if (index == 0)
- cssClass += ' next';
- else
- cssClass += ' untyped';
- } else if (
- this.pairingEvent_.pairing == PairingEventType.KEYS_ENTERED &&
- this.pairingEvent_.enteredKey) {
- var enteredKey = this.pairingEvent_.enteredKey; // 1-7
- var lastKey = this.digits.length; // 6
- if ((index == -1 && enteredKey > lastKey) || (index + 1 == enteredKey))
- cssClass += ' next';
- else if (index > enteredKey)
- cssClass += ' untyped';
- }
- return cssClass;
- },
-};
-
-Polymer({
- is: 'bluetooth-device-dialog',
-
- behaviors: [I18nBehavior, settings.BluetoothPairDeviceBehavior],
-
- properties: {
- /**
- * The version of this dialog to show: 'pairDevice', or 'connectError'.
- * Must be set before the dialog is opened.
- */
- dialogId: String,
- },
-
- observers: [
- 'dialogUpdated_(dialogId, pairingEvent_)',
- ],
-
- open: function() {
- this.startPairing();
- this.pinOrPass = '';
- this.getDialog_().showModal();
- this.itemWasFocused_ = false;
- },
-
- close: function() {
- this.endPairing();
- var dialog = this.getDialog_();
- if (dialog.open)
- dialog.close();
- },
-
- /** @private */
- dialogUpdated_: function() {
- if (this.showEnterPincode_())
- this.$$('#pincode').focus();
- else if (this.showEnterPasskey_())
- this.$$('#passkey').focus();
- },
-
- /**
- * @return {!CrDialogElement}
- * @private
- */
- getDialog_: function() {
- return /** @type {!CrDialogElement} */ (this.$.dialog);
- },
-
- /**
- * @param {string} desiredDialogType
- * @return {boolean}
- * @private
- */
- isDialogType_: function(desiredDialogType, currentDialogType) {
- return currentDialogType == desiredDialogType;
- },
-
- /** @private */
- onCancelTap_: function() {
- this.getDialog_().cancel();
- },
-
- /** @private */
- onDialogCanceled_: function() {
- if (this.dialogId == 'pairDevice')
- this.sendResponse_(chrome.bluetoothPrivate.PairingResponse.CANCEL);
- this.endPairing();
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html
index 117ddbbae3f..b7134f661f3 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html
@@ -37,11 +37,10 @@
title="$i18n{moreActions}" on-keydown="ignoreEnterKey_">
</button>
<dialog id="dotsMenu" is="cr-action-menu">
- <button class="dropdown-item" role="option"
- on-tap="onConnectActionTap_">
+ <button class="dropdown-item" on-tap="onConnectActionTap_">
[[getConnectActionText_(device.connected)]]
</button>
- <button class="dropdown-item" role="option" on-tap="onRemoveTap_">
+ <button class="dropdown-item" on-tap="onRemoveTap_">
$i18n{bluetoothRemove}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js
index a626139e025..2a6445caf7c 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js
@@ -168,7 +168,6 @@ Polymer({
this.adapterState_ = state;
this.bluetoothToggleState_ = state.powered;
this.bluetoothToggleDisabled_ = !state.available;
- this.setPrefValue('ash.user.bluetooth.adapter_enabled', state.powered);
},
/** @private */
@@ -206,12 +205,15 @@ Polymer({
}
this.bluetoothToggleDisabled_ = true;
this.bluetoothPrivate.setAdapterState(
- {powered: this.bluetoothToggleState_}, function() {
- if (chrome.runtime.lastError) {
- console.error(
- 'Error enabling bluetooth: ' +
- chrome.runtime.lastError.message);
+ {powered: this.bluetoothToggleState_}, () => {
+ var error = chrome.runtime.lastError;
+ if (error && error != 'Error setting adapter properties: powered') {
+ console.error('Error enabling bluetooth: ' + error.message);
+ return;
}
+ this.setPrefValue(
+ 'ash.user.bluetooth.adapter_enabled',
+ this.bluetoothToggleState_);
});
},
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.html b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.html
index 21352c70c0b..7a782eeb0e5 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.html
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/bluetooth_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_scrollable_behavior.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
@@ -8,7 +9,6 @@
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="bluetooth_device_dialog.html">
<link rel="import" href="bluetooth_device_list_item.html">
<dom-module id="settings-bluetooth-subpage">
@@ -35,7 +35,7 @@
}
#onOff[on] {
- color: var(--settings-toggle-color);
+ color: var(--cr-toggle-color);
}
</style>
@@ -99,14 +99,13 @@
</iron-list>
</div>
- <bluetooth-device-dialog id="deviceDialog"
+ <bluetooth-dialog id="deviceDialog"
+ bluetooth="[[bluetooth]]"
bluetooth-private="[[bluetoothPrivate]]"
- dialog-id="[[dialogId_]]"
- error-message="[[errorMessage_]]"
+ title="$i18n{bluetoothPairDevicePageTitle}"
on-close="onDialogClose_"
- on-device-event="onDeviceEvent_"
pairing-device="[[pairingDevice_]]">
- </bluetooth-device-dialog>
+ </bluetooth-dialog>
</template>
<script src="bluetooth_subpage.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js
index 731f9d523d4..54876622ff1 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js
@@ -8,9 +8,6 @@
* properties and devices.
*/
-// NOTE(dbeam): even though this behavior is only used privately, it must
-// be globally accessible for Closure's --polymer_pass to compile happily.
-
Polymer({
is: 'settings-bluetooth-subpage',
@@ -40,7 +37,7 @@ Polymer({
showSpinner_: {
type: Boolean,
notify: true,
- computed: 'computeShowSpinner_(adapterState.*, dialogId_)',
+ computed: 'computeShowSpinner_(adapterState.*, dialogShown_)',
},
/**
@@ -97,16 +94,12 @@ Polymer({
},
/**
- * Set to the name of the dialog to show. This page uses a single
- * dialog to host one of two dialog elements: 'pairDevice' or
- * 'connectError'. This allows a seamless transition between dialogs.
- * Note: This property should be set before opening the dialog and setting
- * the property will not itself cause the dialog to open.
+ * Whether or not the dialog is shown.
* @private
*/
- dialogId_: {
- type: String,
- value: '',
+ dialogShown_: {
+ type: Boolean,
+ value: false,
},
/**
@@ -117,12 +110,6 @@ Polymer({
pairingDevice_: Object,
/**
- * The translated error message to show when a connect error occurs.
- * @private
- */
- errorMessage_: String,
-
- /**
* Interface for bluetooth calls. Set in bluetooth-page.
* @type {Bluetooth}
* @private
@@ -200,7 +187,7 @@ Polymer({
/** @private */
computeShowSpinner_: function() {
- return !this.dialogId_ && this.get('adapterState.discovering');
+ return !this.dialogShown_ && this.get('adapterState.discovering');
},
/** @private */
@@ -256,9 +243,9 @@ Polymer({
this.deviceList_ = [];
return;
}
- this.bluetooth.getDevices(function(devices) {
+ this.bluetooth.getDevices(devices => {
this.deviceList_ = devices;
- }.bind(this));
+ });
},
/**
@@ -268,7 +255,7 @@ Polymer({
*/
onBluetoothDeviceUpdated_: function(device) {
var address = device.address;
- if (this.dialogId_ && this.pairingDevice_ &&
+ if (this.dialogShown_ && this.pairingDevice_ &&
this.pairingDevice_.address == address) {
this.pairingDevice_ = device;
}
@@ -382,41 +369,23 @@ Polymer({
// If the device is not paired, show the pairing dialog before connecting.
if (!device.paired) {
this.pairingDevice_ = device;
- this.openDialog_('pairDevice');
+ this.openDialog_();
}
- this.bluetoothPrivate.connect(device.address, function(result) {
- var error;
- if (chrome.runtime.lastError) {
- error = chrome.runtime.lastError.message;
- } else {
- switch (result) {
- case chrome.bluetoothPrivate.ConnectResultType.IN_PROGRESS:
- return; // Do not close the dialog
- case chrome.bluetoothPrivate.ConnectResultType.ALREADY_CONNECTED:
- case chrome.bluetoothPrivate.ConnectResultType.AUTH_CANCELED:
- case chrome.bluetoothPrivate.ConnectResultType.SUCCESS:
- break;
- default:
- error = result;
- }
- }
-
- if (!error) {
- this.$.deviceDialog.close();
+ var address = device.address;
+ this.bluetoothPrivate.connect(address, result => {
+ // If |pairingDevice_| has changed, ignore the connect result.
+ if (this.pairingDevice_ && address != this.pairingDevice_.address)
return;
+ // Let the dialog handle any errors, otherwise close the dialog.
+ var dialog = this.$.deviceDialog;
+ if (dialog.handleError(device, chrome.runtime.lastError, result)) {
+ this.openDialog_();
+ } else if (
+ result != chrome.bluetoothPrivate.ConnectResultType.IN_PROGRESS) {
+ this.$.deviceDialog.close();
}
-
- var name = device.name || device.address;
- var id = 'bluetooth_connect_' + error;
- if (this.i18nExists(id)) {
- this.errorMessage_ = this.i18n(id, name);
- } else {
- this.errorMessage_ = error;
- console.error('Unexpected error connecting to: ' + name + ': ' + error);
- }
- this.openDialog_('connectError');
- }.bind(this));
+ });
},
/**
@@ -438,35 +407,29 @@ Polymer({
* @private
*/
forgetDevice_: function(device) {
- this.bluetoothPrivate.forgetDevice(device.address, function() {
+ this.bluetoothPrivate.forgetDevice(device.address, () => {
if (chrome.runtime.lastError) {
console.error(
'Error forgetting: ' + device.name + ': ' +
chrome.runtime.lastError.message);
}
this.updateDeviceList_();
- }.bind(this));
+ });
},
- /**
- * @param {string} dialogId
- * @private
- */
- openDialog_: function(dialogId) {
- if (this.dialogId_) {
- // Dialog already opened, just update the contents.
- this.dialogId_ = dialogId;
+ /** @private */
+ openDialog_: function() {
+ if (this.dialogShown_)
return;
- }
- this.dialogId_ = dialogId;
// Call flush so that the dialog gets sized correctly before it is opened.
Polymer.dom.flush();
this.$.deviceDialog.open();
+ this.dialogShown_ = true;
},
/** @private */
onDialogClose_: function() {
- this.dialogId_ = '';
+ this.dialogShown_ = false;
this.pairingDevice_ = undefined;
// The list is dynamic so focus the first item.
var device = this.$$('#unpairedContainer bluetooth-device-list-item');
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp
index 733b6c23190..975856e1a61 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp
@@ -33,21 +33,6 @@
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
- 'target_name': 'bluetooth_device_dialog',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-resizable-behavior/compiled_resources2.gyp:iron-resizable-behavior-extracted',
- '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-input/compiled_resources2.gyp:paper-input-extracted',
- '<(EXTERNS_GYP):bluetooth',
- '<(EXTERNS_GYP):bluetooth_private',
- '<(INTERFACES_GYP):bluetooth_private_interface',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
'target_name': 'bluetooth_device_list_item',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.html
deleted file mode 100644
index 59062f7844b..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-checkbox/paper-checkbox.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="certificates_browser_proxy.html">
-
-<dom-module id="settings-ca-trust-edit-dialog">
- <template>
- <style include="settings-shared">
- paper-checkbox {
- display: block;
- }
-
- paper-checkbox,
- #description {
- margin: 15px 0;
- }
- </style>
-
- <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
- $i18n{certificateManagerCaTrustEditDialogTitle}
- </div>
- <div class="body" slot="body">
- <div>[[explanationText_]]</div>
- <div id="description">
- $i18n{certificateManagerCaTrustEditDialogDescription}
- </div>
- <paper-checkbox id="ssl" checked="[[trustInfo_.ssl]]">
- $i18n{certificateManagerCaTrustEditDialogSsl}
- </paper-checkbox>
- <paper-checkbox id="email" checked="[[trustInfo_.email]]">
- $i18n{certificateManagerCaTrustEditDialogEmail}
- </paper-checkbox>
- <paper-checkbox id="objSign" checked="[[trustInfo_.objSign]]">
- $i18n{certificateManagerCaTrustEditDialogObjSign}
- </paper-checkbox>
- </div>
- <div class="button-container" slot="button-container">
- <paper-spinner id="spinner"></paper-spinner>
- <paper-button class="cancel-button" on-tap="onCancelTap_">
- $i18n{cancel}
- </paper-button>
- <paper-button id="ok" class="action-button" on-tap="onOkTap_">
- $i18n{ok}
- </paper-button>
- </div>
- </dialog>
- </template>
- <script src="ca_trust_edit_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js
deleted file mode 100644
index 92d2f241103..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js
+++ /dev/null
@@ -1,80 +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.
-
-/**
- * @fileoverview 'settings-ca-trust-edit-dialog' allows the user to
- * - specify the trust level of a certificate authority that is being
- * imported.
- * - edit the trust level of an already existing certificate authority.
- */
-Polymer({
- is: 'settings-ca-trust-edit-dialog',
-
- properties: {
- /** @type {!CertificateSubnode|!NewCertificateSubNode} */
- model: Object,
-
- /** @private {?CaTrustInfo} */
- trustInfo_: Object,
-
- /** @private {string} */
- explanationText_: String,
- },
-
- /** @private {?settings.CertificatesBrowserProxy} */
- browserProxy_: null,
-
- /** @override */
- ready: function() {
- this.browserProxy_ = settings.CertificatesBrowserProxyImpl.getInstance();
- },
-
- /** @override */
- attached: function() {
- this.explanationText_ = loadTimeData.getStringF(
- 'certificateManagerCaTrustEditDialogExplanation', this.model.name);
-
- // A non existing |model.id| indicates that a new certificate is being
- // imported, otherwise an existing certificate is being edited.
- if (this.model.id) {
- this.browserProxy_.getCaCertificateTrust(this.model.id)
- .then(
- /** @param {!CaTrustInfo} trustInfo */
- function(trustInfo) {
- this.trustInfo_ = trustInfo;
- this.$.dialog.showModal();
- }.bind(this));
- } else {
- /** @type {!CrDialogElement} */ (this.$.dialog).showModal();
- }
- },
-
- /** @private */
- onCancelTap_: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- },
-
- /** @private */
- onOkTap_: function() {
- this.$.spinner.active = true;
-
- var whenDone = this.model.id ?
- this.browserProxy_.editCaCertificateTrust(
- this.model.id, this.$.ssl.checked, this.$.email.checked,
- this.$.objSign.checked) :
- this.browserProxy_.importCaCertificateTrustSelected(
- this.$.ssl.checked, this.$.email.checked, this.$.objSign.checked);
-
- whenDone.then(
- function() {
- this.$.spinner.active = false;
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- }.bind(this),
- /** @param {!CertificatesError} error */
- function(error) {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- this.fire('certificates-error', {error: error, anchor: null});
- }.bind(this));
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.html
deleted file mode 100644
index e27c9db1a0d..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="certificates_browser_proxy.html">
-
-<dom-module id="settings-certificate-delete-confirmation-dialog">
- <template>
- <style include="settings-shared"></style>
- <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
- [[getTitleText_(model, certificateType)]]
- </div>
- <div class="body" slot="body">
- <div>[[getDescriptionText_(model, certificateType)]]</div>
- </div>
- <div class="button-container" slot="button-container">
- <paper-button class="cancel-button" on-tap="onCancelTap_">
- $i18n{cancel}
- </paper-button>
- <paper-button id="ok" class="action-button" on-tap="onOkTap_">
- $i18n{ok}
- </paper-button>
- </div>
- </dialog>
- </template>
- <script src="certificate_delete_confirmation_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js
deleted file mode 100644
index 6abeecef1d9..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js
+++ /dev/null
@@ -1,96 +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.
-
-/**
- * @fileoverview A confirmation dialog allowing the user to delete various types
- * of certificates.
- */
-Polymer({
- is: 'settings-certificate-delete-confirmation-dialog',
-
- properties: {
- /** @type {!CertificateSubnode} */
- model: Object,
-
- /** @type {!CertificateType} */
- certificateType: String,
- },
-
- /** @private {?settings.CertificatesBrowserProxy} */
- browserProxy_: null,
-
- /** @override */
- ready: function() {
- this.browserProxy_ = settings.CertificatesBrowserProxyImpl.getInstance();
- },
-
- /** @override */
- attached: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).showModal();
- },
-
- /**
- * @private
- * @return {string}
- */
- getTitleText_: function() {
- /**
- * @param {string} localizedMessageId
- * @return {string}
- */
- var getString = function(localizedMessageId) {
- return loadTimeData.getStringF(localizedMessageId, this.model.name);
- }.bind(this);
-
- switch (this.certificateType) {
- case CertificateType.PERSONAL:
- return getString('certificateManagerDeleteUserTitle');
- case CertificateType.SERVER:
- return getString('certificateManagerDeleteServerTitle');
- case CertificateType.CA:
- return getString('certificateManagerDeleteCaTitle');
- case CertificateType.OTHER:
- return getString('certificateManagerDeleteOtherTitle');
- }
- assertNotReached();
- },
-
- /**
- * @private
- * @return {string}
- */
- getDescriptionText_: function() {
- var getString = loadTimeData.getString.bind(loadTimeData);
- switch (this.certificateType) {
- case CertificateType.PERSONAL:
- return getString('certificateManagerDeleteUserDescription');
- case CertificateType.SERVER:
- return getString('certificateManagerDeleteServerDescription');
- case CertificateType.CA:
- return getString('certificateManagerDeleteCaDescription');
- case CertificateType.OTHER:
- return '';
- }
- assertNotReached();
- },
-
- /** @private */
- onCancelTap_: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- },
-
- /** @private */
- onOkTap_: function() {
- this.browserProxy_.deleteCertificate(this.model.id)
- .then(
- function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- }.bind(this),
- /** @param {!CertificatesError} error */
- function(error) {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- this.fire('certificates-error', {error: error, anchor: null});
- }.bind(this));
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.html
deleted file mode 100644
index 531ff6bcd9e..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
-<link rel="import" href="certificates_browser_proxy.html">
-<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="certificate_subentry.html">
-
-<dom-module id="settings-certificate-entry">
- <template>
- <style include="settings-shared"></style>
- <div class="settings-box">
- <div class="start">[[model.id]]</div>
- <cr-expand-button expanded="{{expanded_}}"
- alt="$i18n{certificateManagerExpandA11yLabel}">
- </cr-expand-button>
- </div>
- <template is="dom-if" if="[[expanded_]]">
- <div class="list-frame">
- <template is="dom-repeat" items="[[model.subnodes]]">
- <settings-certificate-subentry model="[[item]]"
- certificate-type="[[certificateType]]"
- is-last$="[[isLast_(index, model)]]">
- </settings-certificate-subentry>
- </template>
- </div>
- </template>
- </template>
- <script src="certificate_entry.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.js
deleted file mode 100644
index 74496dcb2fb..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_entry.js
+++ /dev/null
@@ -1,27 +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.
-
-/**
- * @fileoverview An element that represents an SSL certificate entry.
- */
-Polymer({
- is: 'settings-certificate-entry',
-
- properties: {
- /** @type {!Certificate} */
- model: Object,
-
- /** @type {!CertificateType} */
- certificateType: String,
- },
-
- /**
- * @param {number} index
- * @return {boolean} Whether the given index corresponds to the last sub-node.
- * @private
- */
- isLast_: function(index) {
- return index == this.model.subnodes.length - 1;
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.html
deleted file mode 100644
index 7017e4209fc..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="certificate_entry.html">
-<link rel="import" href="certificate_manager_types.html">
-<link rel="import" href="certificates_browser_proxy.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../settings_shared_css.html">
-
-<dom-module id="settings-certificate-list">
- <template>
- <style include="settings-shared">
- .settings-box {
- margin-bottom: 24px;
- }
- </style>
- <div class="settings-box first">
- <span class="start">
- [[getDescription_(certificateType, certificates)]]</span>
- <paper-button id="import" on-tap="onImportTap_"
- hidden="[[!canImport_(certificateType)]]">
- $i18n{certificateManagerImport}</paper-button>
-<if expr="chromeos">
- <paper-button id="importAndBind" on-tap="onImportAndBindTap_"
- hidden="[[!canImportAndBind_(certificateType, isGuest_)]]">
- $i18n{certificateManagerImportAndBind}</paper-button>
-</if>
- </div>
- <template is="dom-repeat" items="[[certificates]]">
- <settings-certificate-entry model="[[item]]"
- certificate-type="[[certificateType]]">
- </settings-certificate-entry>
- </template>
- </template>
- <script src="certificate_list.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js
deleted file mode 100644
index 83cedff7d92..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js
+++ /dev/null
@@ -1,156 +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.
-
-/**
- * @fileoverview 'settings-certificate-list' is an element that displays a list
- * of certificates.
- */
-Polymer({
- is: 'settings-certificate-list',
-
- properties: {
- /** @type {!Array<!Certificate>} */
- certificates: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /** @type {!CertificateType} */
- certificateType: String,
-
- // <if expr="chromeos">
- /** @private */
- isGuest_: {
- type: Boolean,
- value: function() {
- return loadTimeData.getBoolean('isGuest');
- }
- },
- // </if>
- },
-
- behaviors: [I18nBehavior],
-
- /**
- * @return {string}
- * @private
- */
- getDescription_: function() {
- if (this.certificates.length == 0)
- return this.i18n('certificateManagerNoCertificates');
-
- switch (this.certificateType) {
- case CertificateType.PERSONAL:
- return this.i18n('certificateManagerYourCertificatesDescription');
- case CertificateType.SERVER:
- return this.i18n('certificateManagerServersDescription');
- case CertificateType.CA:
- return this.i18n('certificateManagerAuthoritiesDescription');
- case CertificateType.OTHER:
- return this.i18n('certificateManagerOthersDescription');
- }
-
- assertNotReached();
- },
-
- /**
- * @return {boolean}
- * @private
- */
- canImport_: function() {
- return this.certificateType != CertificateType.OTHER;
- },
-
- // <if expr="chromeos">
- /**
- * @return {boolean}
- * @private
- */
- canImportAndBind_: function() {
- return !this.isGuest_ && this.certificateType == CertificateType.PERSONAL;
- },
- // </if>
-
- /**
- * Handles a rejected Promise returned from |browserProxy_|.
- * @param {!HTMLElement} anchor
- * @param {*} error Expects {!CertificatesError|!CertificatesImportError}.
- * @private
- */
- onRejected_: function(anchor, error) {
- if (error === null) {
- // Nothing to do here. Null indicates that the user clicked "cancel" on
- // a native file chooser dialog.
- return;
- }
-
- // Otherwise propagate the error to the parents, such that a dialog
- // displaying the error will be shown.
- this.fire('certificates-error', {error: error, anchor: anchor});
- },
-
-
- /**
- * @param {?NewCertificateSubNode} subnode
- * @param {!HTMLElement} anchor
- * @private
- */
- dispatchImportActionEvent_: function(subnode, anchor) {
- this.fire(
- settings.CertificateActionEvent,
- /** @type {!CertificateActionEventDetail} */ ({
- action: CertificateAction.IMPORT,
- subnode: subnode,
- certificateType: this.certificateType,
- anchor: anchor,
- }));
- },
-
- /**
- * @param {!Event} e
- * @private
- */
- onImportTap_: function(e) {
- this.handleImport_(
- false, /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget));
- },
-
- // <if expr="chromeos">
- /**
- * @private
- * @param {!Event} e
- */
- onImportAndBindTap_: function(e) {
- this.handleImport_(
- true, /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget));
- },
- // </if>
-
- /**
- * @param {boolean} useHardwareBacked
- * @param {!HTMLElement} anchor
- * @private
- */
- handleImport_: function(useHardwareBacked, anchor) {
- var browserProxy = settings.CertificatesBrowserProxyImpl.getInstance();
- if (this.certificateType == CertificateType.PERSONAL) {
- browserProxy.importPersonalCertificate(useHardwareBacked)
- .then(function(showPasswordPrompt) {
- if (showPasswordPrompt)
- this.dispatchImportActionEvent_(null, anchor);
- }.bind(this), this.onRejected_.bind(this, anchor));
- } else if (this.certificateType == CertificateType.CA) {
- browserProxy.importCaCertificate().then(function(certificateName) {
- this.dispatchImportActionEvent_({name: certificateName}, anchor);
- }.bind(this), this.onRejected_.bind(this, anchor));
- } else if (this.certificateType == CertificateType.SERVER) {
- browserProxy.importServerCertificate().catch(
- this.onRejected_.bind(this, anchor));
- } else {
- assertNotReached();
- }
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.html
deleted file mode 100644
index 3f97ff66273..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.html
+++ /dev/null
@@ -1,105 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
-<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-tabs/paper-tabs.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html">
-<link rel="import" href="ca_trust_edit_dialog.html">
-<link rel="import" href="certificate_delete_confirmation_dialog.html">
-<link rel="import" href="certificate_list.html">
-<link rel="import" href="certificate_manager_types.html">
-<link rel="import" href="certificate_password_decryption_dialog.html">
-<link rel="import" href="certificate_password_encryption_dialog.html">
-<link rel="import" href="certificates_browser_proxy.html">
-<link rel="import" href="certificates_error_dialog.html">
-
-<dom-module id="settings-certificate-manager-page">
- <template>
- <style>
- :host {
- --paper-tabs-selection-bar-color: var(--paper-blue-500);
- }
-
- paper-tabs {
- font-size: inherit;
- height: 40px;
- margin-bottom: 24px;
- }
-
- paper-tab {
- --paper-tab-content: {
- color: var(--paper-grey-800);
- };
- --paper-tab-content-unselected: {
- color: var(--paper-grey-600);
- };
- text-transform: uppercase;
- }
- </style>
-
- <template is="dom-if" if="[[showCaTrustEditDialog_]]" restamp>
- <settings-ca-trust-edit-dialog model="[[dialogModel_]]">
- </settings-ca-trust-edit-dialog>
- </template>
- <template is="dom-if" if="[[showDeleteConfirmationDialog_]]" restamp>
- <settings-certificate-delete-confirmation-dialog
- model="[[dialogModel_]]"
- certificate-type="[[dialogModelCertificateType_]]">
- </settings-certificate-delete-confirmation-dialog>
- </template>
- <template is="dom-if" if="[[showPasswordEncryptionDialog_]]" restamp>
- <settings-certificate-password-encryption-dialog
- model="[[dialogModel_]]">
- </settings-certificate-password-encryption-dialog>
- </template>
- <template is="dom-if" if="[[showPasswordDecryptionDialog_]]" restamp>
- <settings-certificate-password-decryption-dialog>
- </settings-certificate-password-decryption-dialog>
- </template>
- <template is="dom-if" if="[[showErrorDialog_]]" restamp>
- <settings-certificates-error-dialog model="[[errorDialogModel_]]">
- </settings-certificates-error-dialog>
- </template>
-
- <paper-tabs noink selected="{{selected}}">
- <paper-tab>$i18n{certificateManagerYourCertificates}</paper-tab>
- <paper-tab>$i18n{certificateManagerServers}</paper-tab>
- <paper-tab>$i18n{certificateManagerAuthorities}</paper-tab>
- <paper-tab>$i18n{certificateManagerOthers}</paper-tab>
- </paper-tabs>
- <iron-pages selected="[[selected]]">
- <div>
- <settings-certificate-list id="personalCerts"
- certificates="[[personalCerts]]"
- certificate-type="[[certificateTypeEnum_.PERSONAL]]">
- </settings-certificate-list>
- </div>
- <div>
- <template is="dom-if" if="[[isTabSelected_(selected, 1)]]">
- <settings-certificate-list id="serverCerts"
- certificates="[[serverCerts]]"
- certificate-type="[[certificateTypeEnum_.SERVER]]">
- </settings-certificate-list>
- </template>
- </div>
- <div>
- <template is="dom-if" if="[[isTabSelected_(selected, 2)]]">
- <settings-certificate-list id="caCerts"
- certificates="[[caCerts]]"
- certificate-type="[[certificateTypeEnum_.CA]]">
- </settings-certificate-list>
- </template>
- </div>
- <div>
- <template is="dom-if" if="[[isTabSelected_(selected, 3)]]">
- <settings-certificate-list id="otherCerts"
- certificates="[[otherCerts]]"
- certificate-type="[[certificateTypeEnum_.OTHER]]">
- </settings-certificate-list>
- </template>
- </div>
- </iron-pages>
- </template>
- <script src="certificate_manager_page.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js
deleted file mode 100644
index 9433f7c3dcf..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js
+++ /dev/null
@@ -1,190 +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.
-
-/**
- * @fileoverview 'settings-certificate-manager-page' is the settings page
- * containing SSL certificate settings.
- */
-Polymer({
- is: 'settings-certificate-manager-page',
-
- behaviors: [WebUIListenerBehavior],
-
- properties: {
- /** @type {number} */
- selected: {
- type: Number,
- value: 0,
- },
-
- /** @type {!Array<!Certificate>} */
- personalCerts: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /** @type {!Array<!Certificate>} */
- serverCerts: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /** @type {!Array<!Certificate>} */
- caCerts: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /** @type {!Array<!Certificate>} */
- otherCerts: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /** @private */
- certificateTypeEnum_: {
- type: Object,
- value: CertificateType,
- readOnly: true,
- },
-
- /** @private */
- showCaTrustEditDialog_: Boolean,
-
- /** @private */
- showDeleteConfirmationDialog_: Boolean,
-
- /** @private */
- showPasswordEncryptionDialog_: Boolean,
-
- /** @private */
- showPasswordDecryptionDialog_: Boolean,
-
- /** @private */
- showErrorDialog_: Boolean,
-
- /**
- * The model to be passed to dialogs that refer to a given certificate.
- * @private {?CertificateSubnode}
- */
- dialogModel_: Object,
-
- /**
- * The certificate type to be passed to dialogs that refer to a given
- * certificate.
- * @private {?CertificateType}
- */
- dialogModelCertificateType_: String,
-
- /**
- * The model to be passed to the error dialog.
- * @private {null|!CertificatesError|!CertificatesImportError}
- */
- errorDialogModel_: Object,
-
- /**
- * The element to return focus to, when the currently shown dialog is
- * closed.
- * @private {?HTMLElement}
- */
- activeDialogAnchor_: Object,
- },
-
- /** @override */
- attached: function() {
- this.addWebUIListener('certificates-changed', this.set.bind(this));
- settings.CertificatesBrowserProxyImpl.getInstance().refreshCertificates();
- },
-
- /**
- * @param {number} selectedIndex
- * @param {number} tabIndex
- * @return {boolean} Whether to show tab at |tabIndex|.
- * @private
- */
- isTabSelected_: function(selectedIndex, tabIndex) {
- return selectedIndex == tabIndex;
- },
-
- /** @override */
- ready: function() {
- this.addEventListener(settings.CertificateActionEvent, function(event) {
- this.dialogModel_ = event.detail.subnode;
- this.dialogModelCertificateType_ = event.detail.certificateType;
-
- if (event.detail.action == CertificateAction.IMPORT) {
- if (event.detail.certificateType == CertificateType.PERSONAL) {
- this.openDialog_(
- 'settings-certificate-password-decryption-dialog',
- 'showPasswordDecryptionDialog_', event.detail.anchor);
- } else if (event.detail.certificateType == CertificateType.CA) {
- this.openDialog_(
- 'settings-ca-trust-edit-dialog', 'showCaTrustEditDialog_',
- event.detail.anchor);
- }
- } else {
- if (event.detail.action == CertificateAction.EDIT) {
- this.openDialog_(
- 'settings-ca-trust-edit-dialog', 'showCaTrustEditDialog_',
- event.detail.anchor);
- } else if (event.detail.action == CertificateAction.DELETE) {
- this.openDialog_(
- 'settings-certificate-delete-confirmation-dialog',
- 'showDeleteConfirmationDialog_', event.detail.anchor);
- } else if (event.detail.action == CertificateAction.EXPORT_PERSONAL) {
- this.openDialog_(
- 'settings-certificate-password-encryption-dialog',
- 'showPasswordEncryptionDialog_', event.detail.anchor);
- }
- }
-
- event.stopPropagation();
- }.bind(this));
-
- this.addEventListener('certificates-error', function(event) {
- var detail = /** @type {!CertificatesErrorEventDetail} */ (event.detail);
- this.errorDialogModel_ = detail.error;
- this.openDialog_(
- 'settings-certificates-error-dialog', 'showErrorDialog_',
- detail.anchor);
- event.stopPropagation();
- }.bind(this));
- },
-
- /**
- * Opens a dialog and registers a listener for removing the dialog from the
- * DOM once is closed. The listener is destroyed when the dialog is removed
- * (because of 'restamp').
- *
- * @param {string} dialogTagName The tag name of the dialog to be shown.
- * @param {string} domIfBooleanName The name of the boolean variable
- * corresponding to the dialog.
- * @param {?HTMLElement} anchor The element to focus when the dialog is
- * closed. If null, the previous anchor element should be reused. This
- * happens when a 'settings-certificates-error-dialog' is opened,
- * which when closed should focus the anchor of the previous dialog (the
- * one that generated the error).
- * @private
- */
- openDialog_: function(dialogTagName, domIfBooleanName, anchor) {
- if (anchor)
- this.activeDialogAnchor_ = anchor;
- this.set(domIfBooleanName, true);
- this.async(function() {
- var dialog = this.$$(dialogTagName);
- dialog.addEventListener('close', function() {
- this.set(domIfBooleanName, false);
- cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_));
- }.bind(this));
- }.bind(this));
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.html
deleted file mode 100644
index 271b2666939..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.html
+++ /dev/null
@@ -1 +0,0 @@
-<script src="certificate_manager_types.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.js
deleted file mode 100644
index 6063848b6a0..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_types.js
+++ /dev/null
@@ -1,38 +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.
-
-/**
- * @fileoverview Closure compiler typedefs.
- */
-
-/**
- * The payload of the 'certificate-action' event.
- * @typedef {{
- * action: !CertificateAction,
- * subnode: (null|CertificateSubnode|NewCertificateSubNode),
- * certificateType: !CertificateType,
- * anchor: !HTMLElement
- * }}
- */
-var CertificateActionEventDetail;
-
-/**
- * The payload of the 'certificates-error' event.
- * @typedef {{
- * error: (null|CertificatesError|CertificatesImportError),
- * anchor: ?HTMLElement
- * }}
- */
-var CertificatesErrorEventDetail;
-
-/**
- * Enumeration of actions that require a popup menu to be shown to the user.
- * @enum {number}
- */
-var CertificateAction = {
- DELETE: 0,
- EDIT: 1,
- EXPORT_PERSONAL: 2,
- IMPORT: 3,
-};
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.html
deleted file mode 100644
index 6dffa38e0dc..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="certificates_browser_proxy.html">
-
-<dom-module id="settings-certificate-password-decryption-dialog">
- <template>
- <style include="settings-shared"></style>
- <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
- $i18n{certificateManagerDecryptPasswordTitle}
- </div>
- <div class="body" slot="body">
- <paper-input type="password" id="password"
- label="$i18n{certificateManagerPassword}" value="{{password_}}">
- </paper-input>
- </div>
- <div class="button-container" slot="button-container">
- <paper-button class="cancel-button" on-tap="onCancelTap_">
- $i18n{cancel}
- </paper-button>
- <paper-button id="ok" class="action-button" on-tap="onOkTap_">
- $i18n{ok}
- </paper-button>
- </div>
- </dialog>
- </template>
- <script src="certificate_password_decryption_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js
deleted file mode 100644
index cdc846e93b4..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js
+++ /dev/null
@@ -1,51 +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.
-
-/**
- * @fileoverview A dialog prompting the user for a decryption password such that
- * a previously exported personal certificate can be imported.
- */
-Polymer({
- is: 'settings-certificate-password-decryption-dialog',
-
- properties: {
- /** @private */
- password_: {
- type: String,
- value: '',
- },
- },
-
- /** @private {?settings.CertificatesBrowserProxy} */
- browserProxy_: null,
-
- /** @override */
- ready: function() {
- this.browserProxy_ = settings.CertificatesBrowserProxyImpl.getInstance();
- },
-
- /** @override */
- attached: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).showModal();
- },
-
- /** @private */
- onCancelTap_: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- },
-
- /** @private */
- onOkTap_: function() {
- this.browserProxy_.importPersonalCertificatePasswordSelected(this.password_)
- .then(
- function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- }.bind(this),
- /** @param {!CertificatesError} error */
- function(error) {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- this.fire('certificates-error', {error: error, anchor: null});
- }.bind(this));
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.html
deleted file mode 100644
index 035727e2e96..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.html
+++ /dev/null
@@ -1,44 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="certificates_browser_proxy.html">
-
-<dom-module id="settings-certificate-password-encryption-dialog">
- <template>
- <style include="settings-shared">
- .password-buttons {
- margin-bottom: 20px;
- }
- </style>
- <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
- $i18n{certificateManagerEncryptPasswordTitle}
- </div>
- <div class="body" slot="body">
- <div>$i18n{certificateManagerEncryptPasswordDescription}</div>
- <div class="password-buttons">
- <paper-input type="password" value="{{password_}}" id="password"
- label="$i18n{certificateManagerPassword}"
- on-input="validate_"></paper-input>
- <paper-input type="password"
- value="{{confirmPassword_}}" id="confirmPassword"
- label="$i18n{certificateManagerConfirmPassword}"
- on-input="validate_"></paper-input>
- </div>
- </div>
- <div class="button-container" slot="button-container">
- <paper-button class="cancel-button" on-tap="onCancelTap_">
- $i18n{cancel}
- </paper-button>
- <paper-button id="ok" class="action-button" on-tap="onOkTap_" disabled>
- $i18n{ok}
- </paper-button>
- </div>
- </dialog>
- </template>
- <script src="certificate_password_encryption_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js
deleted file mode 100644
index ed74927c56a..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/**
- * @fileoverview A dialog prompting the user to encrypt a personal certificate
- * before it is exported to disk.
- */
-Polymer({
- is: 'settings-certificate-password-encryption-dialog',
-
- properties: {
- /** @type {!CertificateSubnode} */
- model: Object,
-
- /** @private */
- password_: {
- type: String,
- value: '',
- },
-
- /** @private */
- confirmPassword_: {
- type: String,
- value: '',
- },
- },
-
- /** @private {?settings.CertificatesBrowserProxy} */
- browserProxy_: null,
-
- /** @override */
- ready: function() {
- this.browserProxy_ = settings.CertificatesBrowserProxyImpl.getInstance();
- },
-
- /** @override */
- attached: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).showModal();
- },
-
- /** @private */
- onCancelTap_: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- },
-
- /** @private */
- onOkTap_: function() {
- this.browserProxy_.exportPersonalCertificatePasswordSelected(this.password_)
- .then(
- function() {
- this.$.dialog.close();
- }.bind(this),
- /** @param {!CertificatesError} error */
- function(error) {
- this.$.dialog.close();
- this.fire('certificates-error', {error: error, anchor: null});
- }.bind(this));
- },
-
- /** @private */
- validate_: function() {
- var isValid =
- this.password_ != '' && this.password_ == this.confirmPassword_;
- this.$.ok.disabled = !isValid;
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.html
deleted file mode 100644
index 8286ba0d820..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.html
+++ /dev/null
@@ -1,61 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html">
-<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
-<link rel="import" href="certificate_manager_types.html">
-<link rel="import" href="certificates_browser_proxy.html">
-<link rel="import" href="../settings_shared_css.html">
-
-<dom-module id="settings-certificate-subentry">
- <template>
- <style include="settings-shared">
- .name {
- flex: auto;
- }
-
- .untrusted {
- -webkit-margin-end: 16px;
- color: var(--settings-error-color);
- font-weight: 500;
- text-transform: uppercase;
- }
-
- :host([is-last]) .list-item {
- border-bottom: none;
- }
- </style>
- <div class="list-item underbar">
- <div class="untrusted" hidden$="[[!model.untrusted]]">
- $i18n{certificateManagerUntrusted}
- </div>
- <div class="name">[[model.name]]</div>
- <button is="paper-icon-button-light" class="icon-more-vert" id="dots"
- title="$i18n{moreActions}" on-tap="onDotsTap_"></button>
- <template is="cr-lazy-render" id="menu">
- <dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" id="view"
- on-tap="onViewTap_">
- $i18n{certificateManagerView}
- </button>
- <button class="dropdown-item" role="option" id="edit"
- hidden$="[[!canEdit_(certificateType, model)]]"
- on-tap="onEditTap_">
- $i18n{edit}
- </button>
- <button class="dropdown-item" role="option" id="export"
- hidden$="[[!canExport_(certificateType, model)]]"
- on-tap="onExportTap_">
- $i18n{certificateManagerExport}
- </button>
- <button class="dropdown-item" role="option" id="delete"
- hidden$="[[!canDelete_(model)]]" on-tap="onDeleteTap_">
- $i18n{certificateManagerDelete}
- </button>
- </dialog>
- </template>
- <div>
- </template>
- <script src="certificate_subentry.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js
deleted file mode 100644
index 9c858be8b98..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js
+++ /dev/null
@@ -1,162 +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.
-
-/**
- * @fileoverview settings-certificate-subentry represents an SSL certificate
- * sub-entry.
- */
-
-cr.define('settings', function() {
- /**
- * The name of the event that is fired when a menu item is tapped.
- * @type {string}
- */
- var CertificateActionEvent = 'certificate-action';
-
- return {
- CertificateActionEvent: CertificateActionEvent,
- };
-});
-
-Polymer({
- is: 'settings-certificate-subentry',
-
- properties: {
- /** @type {!CertificateSubnode} */
- model: Object,
-
- /** @type {!CertificateType} */
- certificateType: String,
- },
-
- /** @private {settings.CertificatesBrowserProxy} */
- browserProxy_: null,
-
- /** @override */
- created: function() {
- this.browserProxy_ = settings.CertificatesBrowserProxyImpl.getInstance();
- },
-
- /**
- * Dispatches an event indicating which certificate action was tapped. It is
- * used by the parent of this element to display a modal dialog accordingly.
- * @param {!CertificateAction} action
- * @private
- */
- dispatchCertificateActionEvent_: function(action) {
- this.fire(
- settings.CertificateActionEvent,
- /** @type {!CertificateActionEventDetail} */ ({
- action: action,
- subnode: this.model,
- certificateType: this.certificateType,
- anchor: this.$.dots,
- }));
- },
-
- /**
- * Handles the case where a call to the browser resulted in a rejected
- * promise.
- * @param {*} error Expects {?CertificatesError}.
- * @private
- */
- onRejected_: function(error) {
- if (error === null) {
- // Nothing to do here. Null indicates that the user clicked "cancel" on
- // the native file chooser dialog.
- return;
- }
-
- // Otherwise propagate the error to the parents, such that a dialog
- // displaying the error will be shown.
- this.fire('certificates-error', {error: error, anchor: this.$.dots});
- },
-
- /**
- * @param {!Event} event
- * @private
- */
- onViewTap_: function(event) {
- this.closePopupMenu_();
- this.browserProxy_.viewCertificate(this.model.id);
- },
-
- /**
- * @param {!Event} event
- * @private
- */
- onEditTap_: function(event) {
- this.closePopupMenu_();
- this.dispatchCertificateActionEvent_(CertificateAction.EDIT);
- },
-
- /**
- * @param {!Event} event
- * @private
- */
- onDeleteTap_: function(event) {
- this.closePopupMenu_();
- this.dispatchCertificateActionEvent_(CertificateAction.DELETE);
- },
-
- /**
- * @param {!Event} event
- * @private
- */
- onExportTap_: function(event) {
- this.closePopupMenu_();
- if (this.certificateType == CertificateType.PERSONAL) {
- this.browserProxy_.exportPersonalCertificate(this.model.id)
- .then(function() {
- this.dispatchCertificateActionEvent_(
- CertificateAction.EXPORT_PERSONAL);
- }.bind(this), this.onRejected_.bind(this));
- } else {
- this.browserProxy_.exportCertificate(this.model.id);
- }
- },
-
- /**
- * @param {!CertificateType} certificateType
- * @param {!CertificateSubnode} model
- * @return {boolean} Whether the certificate can be edited.
- * @private
- */
- canEdit_: function(certificateType, model) {
- return certificateType == CertificateType.CA && !model.policy;
- },
-
- /**
- * @param {!CertificateType} certificateType
- * @param {!CertificateSubnode} model
- * @return {boolean} Whether the certificate can be exported.
- * @private
- */
- canExport_: function(certificateType, model) {
- if (certificateType == CertificateType.PERSONAL) {
- return model.extractable;
- }
- return true;
- },
-
- /**
- * @param {!CertificateSubnode} model
- * @return {boolean} Whether the certificate can be deleted.
- * @private
- */
- canDelete_: function(model) {
- return !model.readonly && !model.policy;
- },
-
- /** @private */
- closePopupMenu_: function() {
- this.$$('dialog[is=cr-action-menu]').close();
- },
-
- /** @private */
- onDotsTap_: function() {
- var actionMenu = /** @type {!CrActionMenuElement} */ (this.$.menu.get());
- actionMenu.showAt(this.$.dots);
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.html
deleted file mode 100644
index 0dc7c572ff1..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.html
+++ /dev/null
@@ -1 +0,0 @@
-<script src="certificates_browser_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.js
deleted file mode 100644
index 3501b77acc1..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_browser_proxy.js
+++ /dev/null
@@ -1,271 +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.
-
-/**
- * @fileoverview A helper object used from the "Manage certificates" section
- * to interact with the browser.
- */
-
-/**
- * @typedef {{
- * extractable: boolean,
- * id: string,
- * name: string,
- * policy: boolean,
- * readonly: boolean,
- * untrusted: boolean,
- * }}
- * @see chrome/browser/ui/webui/settings/certificates_handler.cc
- */
-var CertificateSubnode;
-
-/**
- * A data structure describing a certificate that is currently being imported,
- * therefore it has no ID yet, but it has a name. Used within JS only.
- * @typedef {{
- * name: string,
- * }}
- */
-var NewCertificateSubNode;
-
-/**
- * @typedef {{
- * id: string,
- * name: string,
- * subnodes: !Array<!CertificateSubnode>
- * }}
- * @see chrome/browser/ui/webui/settings/certificates_handler.cc
- */
-var Certificate;
-
-/**
- * @typedef {{
- * ssl: boolean,
- * email: boolean,
- * objSign: boolean
- * }}
- */
-var CaTrustInfo;
-
-/**
- * Generic error returned from C++ via a Promise reject callback.
- * @typedef {{
- * title: string,
- * description: string
- * }}
- * @see chrome/browser/ui/webui/settings/certificates_handler.cc
- */
-var CertificatesError;
-
-/**
- * Enumeration of all possible certificate types.
- * @enum {string}
- */
-var CertificateType = {
- CA: 'ca',
- OTHER: 'other',
- PERSONAL: 'personal',
- SERVER: 'server',
-};
-
-
-/**
- * Error returned from C++ via a Promise reject callback, when some certificates
- * fail to be imported.
- * @typedef {{
- * title: string,
- * description: string,
- * certificateErrors: !Array<{name: string, error: string}>
- * }}
- * @see chrome/browser/ui/webui/settings/certificates_handler.cc
- */
-var CertificatesImportError;
-
-cr.define('settings', function() {
- /** @interface */
- class CertificatesBrowserProxy {
- /**
- * Triggers 5 events in the following order
- * 1x 'certificates-model-ready' event.
- * 4x 'certificates-changed' event, one for each certificate category.
- */
- refreshCertificates() {}
-
- /** @param {string} id */
- viewCertificate(id) {}
-
- /** @param {string} id */
- exportCertificate(id) {}
-
- /**
- * @param {string} id
- * @return {!Promise} A promise resolved when the certificate has been
- * deleted successfully or rejected with a CertificatesError.
- */
- deleteCertificate(id) {}
-
- /**
- * @param {string} id
- * @return {!Promise<!CaTrustInfo>}
- */
- getCaCertificateTrust(id) {}
-
- /**
- * @param {string} id
- * @param {boolean} ssl
- * @param {boolean} email
- * @param {boolean} objSign
- * @return {!Promise}
- */
- editCaCertificateTrust(id, ssl, email, objSign) {}
-
- cancelImportExportCertificate() {}
-
- /**
- * @param {string} id
- * @return {!Promise} A promise firing once the user has selected
- * the export location. A prompt should be shown to asking for a
- * password to use for encrypting the file. The password should be
- * passed back via a call to
- * exportPersonalCertificatePasswordSelected().
- */
- exportPersonalCertificate(id) {}
-
- /**
- * @param {string} password
- * @return {!Promise}
- */
- exportPersonalCertificatePasswordSelected(password) {}
-
- /**
- * @param {boolean} useHardwareBacked
- * @return {!Promise<boolean>} A promise firing once the user has selected
- * the file to be imported. If true a password prompt should be shown to
- * the user, and the password should be passed back via a call to
- * importPersonalCertificatePasswordSelected().
- */
- importPersonalCertificate(useHardwareBacked) {}
-
- /**
- * @param {string} password
- * @return {!Promise}
- */
- importPersonalCertificatePasswordSelected(password) {}
-
- /**
- * @return {!Promise} A promise firing once the user has selected
- * the file to be imported, or failing with CertificatesError.
- * Upon success, a prompt should be shown to the user to specify the
- * trust levels, and that information should be passed back via a call
- * to importCaCertificateTrustSelected().
- */
- importCaCertificate() {}
-
- /**
- * @param {boolean} ssl
- * @param {boolean} email
- * @param {boolean} objSign
- * @return {!Promise} A promise firing once the trust level for the imported
- * certificate has been successfully set. The promise is rejected if an
- * error occurred with either a CertificatesError or
- * CertificatesImportError.
- */
- importCaCertificateTrustSelected(ssl, email, objSign) {}
-
- /**
- * @return {!Promise} A promise firing once the certificate has been
- * imported. The promise is rejected if an error occurred, with either
- * a CertificatesError or CertificatesImportError.
- */
- importServerCertificate() {}
- }
-
- /**
- * @implements {settings.CertificatesBrowserProxy}
- */
- class CertificatesBrowserProxyImpl {
- /** @override */
- refreshCertificates() {
- chrome.send('refreshCertificates');
- }
-
- /** @override */
- viewCertificate(id) {
- chrome.send('viewCertificate', [id]);
- }
-
- /** @override */
- exportCertificate(id) {
- chrome.send('exportCertificate', [id]);
- }
-
- /** @override */
- deleteCertificate(id) {
- return cr.sendWithPromise('deleteCertificate', id);
- }
-
- /** @override */
- exportPersonalCertificate(id) {
- return cr.sendWithPromise('exportPersonalCertificate', id);
- }
-
- /** @override */
- exportPersonalCertificatePasswordSelected(password) {
- return cr.sendWithPromise(
- 'exportPersonalCertificatePasswordSelected', password);
- }
-
- /** @override */
- importPersonalCertificate(useHardwareBacked) {
- return cr.sendWithPromise('importPersonalCertificate', useHardwareBacked);
- }
-
- /** @override */
- importPersonalCertificatePasswordSelected(password) {
- return cr.sendWithPromise(
- 'importPersonalCertificatePasswordSelected', password);
- }
-
- /** @override */
- getCaCertificateTrust(id) {
- return cr.sendWithPromise('getCaCertificateTrust', id);
- }
-
- /** @override */
- editCaCertificateTrust(id, ssl, email, objSign) {
- return cr.sendWithPromise(
- 'editCaCertificateTrust', id, ssl, email, objSign);
- }
-
- /** @override */
- importCaCertificateTrustSelected(ssl, email, objSign) {
- return cr.sendWithPromise(
- 'importCaCertificateTrustSelected', ssl, email, objSign);
- }
-
- /** @override */
- cancelImportExportCertificate() {
- chrome.send('cancelImportExportCertificate');
- }
-
- /** @override */
- importCaCertificate() {
- return cr.sendWithPromise('importCaCertificate');
- }
-
- /** @override */
- importServerCertificate() {
- return cr.sendWithPromise('importServerCertificate');
- }
- }
-
- // The singleton instance_ is replaced with a test version of this wrapper
- // during testing.
- cr.addSingletonGetter(CertificatesBrowserProxyImpl);
-
- return {
- CertificatesBrowserProxy: CertificatesBrowserProxy,
- CertificatesBrowserProxyImpl: CertificatesBrowserProxyImpl,
- };
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.html b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.html
deleted file mode 100644
index b7d519de92c..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../settings_shared_css.html">
-
-<dom-module id="settings-certificates-error-dialog">
- <template>
- <style include="settings-shared"></style>
- <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">[[model.title]]</div>
- <div class="body" slot="body">
- <div>[[model.description]]</div>
- <template is="dom-if" if="[[model.certificateErrors]]">
- <template is="dom-repeat" items="[[model.certificateErrors]]">
- <div>[[getCertificateErrorText_(item)]]</div>
- </template>
- </template>
- </div>
- <div class="button-container" slot="button-container">
- <paper-button id="ok" class="action-button" on-tap="onOkTap_">
- $i18n{ok}
- </paper-button>
- </div>
- </dialog>
- </template>
- <script src="certificates_error_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.js b/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.js
deleted file mode 100644
index dcb10593914..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/certificates_error_dialog.js
+++ /dev/null
@@ -1,36 +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.
-
-/**
- * @fileoverview A dialog for showing SSL certificate related error messages.
- * The user can only close the dialog, there is no other possible interaction.
- */
-Polymer({
- is: 'settings-certificates-error-dialog',
-
- properties: {
- /** @type {!CertificatesError|!CertificatesImportError} */
- model: Object,
- },
-
- /** @override */
- attached: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).showModal();
- },
-
- /** @private */
- onOkTap_: function() {
- /** @type {!CrDialogElement} */ (this.$.dialog).close();
- },
-
- /**
- * @param {{name: string, error: string}} importError
- * @return {string}
- * @private
- */
- getCertificateErrorText_: function(importError) {
- return loadTimeData.getStringF(
- 'certificateImportErrorFormat', importError.name, importError.error);
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/certificate_manager_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/certificate_manager_page/compiled_resources2.gyp
deleted file mode 100644
index af373ecda43..00000000000
--- a/chromium/chrome/browser/resources/settings/certificate_manager_page/compiled_resources2.gyp
+++ /dev/null
@@ -1,118 +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.
-{
- 'targets': [
- {
- 'target_name': 'certificates_browser_proxy',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_list',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
- 'certificate_manager_types',
- 'certificate_subentry',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_manager_page',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
- '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_without_ink',
- 'certificate_list',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_manager_types',
- 'dependencies': [
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_subentry',
- 'dependencies': [
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_action_menu/compiled_resources2.gyp:cr_action_menu',
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_lazy_render/compiled_resources2.gyp:cr_lazy_render',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'ca_trust_edit_dialog',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_delete_confirmation_dialog',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_entry',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_password_decryption_dialog',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificate_password_encryption_dialog',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'certificates_error_dialog',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
- 'certificate_manager_types',
- 'certificates_browser_proxy',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- ],
-}
diff --git a/chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.html b/chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.html
new file mode 100644
index 00000000000..583ede1657f
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.html
@@ -0,0 +1,3 @@
+<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/cr.html">
+<script src="change_password_browser_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.js b/chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.js
new file mode 100644
index 00000000000..d7b545532fb
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/change_password_page/change_password_browser_proxy.js
@@ -0,0 +1,43 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('settings', function() {
+ /** @interface */
+ class ChangePasswordBrowserProxy {
+ /**
+ * Inform PasswordProtectionService that the change password card is
+ * showing.
+ */
+ onChangePasswordPageShown() {}
+
+ /**
+ * Initiate the change password process. e.g., for Gmail users, it
+ * navigates to accounts.google.com; for GSuite users, it navigates to the
+ * corresponding change password URLs.
+ */
+ changePassword() {}
+ }
+
+ /**
+ * @implements {settings.ChangePasswordBrowserProxy}
+ */
+ class ChangePasswordBrowserProxyImpl {
+ /** @override */
+ onChangePasswordPageShown() {
+ chrome.send('onChangePasswordPageShown');
+ }
+
+ /** @override */
+ changePassword() {
+ chrome.send('changePassword');
+ }
+ }
+
+ cr.addSingletonGetter(ChangePasswordBrowserProxyImpl);
+
+ return {
+ ChangePasswordBrowserProxy: ChangePasswordBrowserProxy,
+ ChangePasswordBrowserProxyImpl: ChangePasswordBrowserProxyImpl,
+ };
+});
diff --git a/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html b/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html
new file mode 100644
index 00000000000..8efd4112cde
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html
@@ -0,0 +1,54 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="change_password_browser_proxy.html">
+<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
+<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="chrome://resources/html/util.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
+
+<dom-module id="settings-change-password-page">
+ <template>
+ <style include="settings-shared">
+ .icon-container {
+ -webkit-padding-end: var(--settings-box-row-padding);
+ }
+
+ .change-password-icon {
+ vertical-align: top;
+ }
+
+ iron-icon[icon='cr:warning'] {
+ --iron-icon-fill-color: var(--settings-error-color);
+ }
+
+ .top-aligned-settings-box {
+ align-items: start;
+ min-height: 0;
+ padding: 12px var(--settings-box-row-padding);
+ }
+ </style>
+ <div class="settings-box first top-aligned-settings-box">
+ <div class="icon-container">
+ <iron-icon icon="$i18n{changePasswordPageIcon}"
+ class="change-password-icon"></iron-icon>
+ </div>
+ <div class="start">
+ <div>$i18n{changePasswordPageTitle}</div>
+ <div class="secondary">
+ $i18n{changePasswordPageDetails}
+ </div>
+ </div>
+ <div class="separator"></div>
+ <paper-button class="primary-button" id="changePassword"
+ on-tap="changePassword_">
+ $i18n{changePasswordPageButton}
+ </paper-button>
+ </div>
+ </template>
+ <script src="change_password_page.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.js b/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.js
new file mode 100644
index 00000000000..a17ece0fecc
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.js
@@ -0,0 +1,39 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview
+ * 'change-password-page' is the settings page containing change password
+ * settings.
+ */
+Polymer({
+ is: 'settings-change-password-page',
+
+ properties: {
+ /**
+ * Preferences state.
+ */
+ prefs: {
+ type: Object,
+ notify: true,
+ },
+ },
+
+ /** @private {?settings.ChangePasswordBrowserProxy} */
+ browserProxy_: null,
+
+ /** @override */
+ attached: function() {
+ this.browserProxy_ = settings.ChangePasswordBrowserProxyImpl.getInstance();
+ this.browserProxy_.onChangePasswordPageShown();
+ },
+
+ /** @private */
+ changePassword_: function() {
+ listenOnce(this, 'transitionend', () => {
+ this.browserProxy_.changePassword();
+ });
+ this.fire('change-password-clicked');
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/change_password_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/change_password_page/compiled_resources2.gyp
new file mode 100644
index 00000000000..fea6ac8f461
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/change_password_page/compiled_resources2.gyp
@@ -0,0 +1,26 @@
+# 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.
+{
+ 'targets': [
+ {
+ 'target_name': 'change_password_browser_proxy',
+ 'dependencies': [
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
+ ],
+ 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
+ },
+ {
+ 'target_name': 'change_password_page',
+ 'dependencies': [
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
+ '<(EXTERNS_GYP):settings_private',
+ 'change_password_browser_proxy',
+ ],
+ 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
+ },
+ ],
+}
diff --git a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
index cec56678904..cc7eee42195 100644
--- a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
+++ b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
@@ -53,10 +53,8 @@
/* Used by |chromeCleanupPoweredByHTML| */
#powered-by-logo {
- -webkit-padding-end: 2px;
- -webkit-padding-start: 5px;
content: url(chrome://settings/partner-logo.svg);
- height: 13px;
+ height: 22px;
}
#status-icon {
@@ -97,16 +95,20 @@
class$="[[statusIconClassName_]]" id="status-icon"></iron-icon>
</div>
<div class="start">
- <div>[[title_]]</div>
- <div class="secondary">
- <span hidden="[[!showDetails_]]">
+ <span>[[title_]]</span>
+ <template is="dom-if" if="[[showDetails_]]">
+ <!-- Force line break to display learn-more inlined with
+ chromeCleanupExplanation or with the title_ (if showDetails_ is
+ false) despite these two elements being on different lines. -->
+ <div></div>
+ <span class="secondary">
$i18n{chromeCleanupExplanation}
</span>
- <a id="learn-more" href="$i18n{chromeCleanupLearnMoreUrl}"
- target="_blank" hidden="[[!showLearnMore_]]">
- $i18n{learnMore}
- </a>
- </div>
+ </template>
+ <a id="learn-more" href="$i18n{chromeCleanupLearnMoreUrl}"
+ on-tap="learnMore_" target="_blank" hidden="[[!showLearnMore_]]">
+ $i18n{learnMore}
+ </a>
</div>
<template is="dom-if" if="[[showActionButton_]]">
<div class="separator"></div>
@@ -116,14 +118,12 @@
</paper-button>
</template>
</div>
- <div class="settings-box" hidden="[[!showLogsPermission_]]">
- <settings-toggle-button class="start"
- id="chromeCleanupLogsUploadControl"
- label="$i18n{chromeCleanupLogsUploadPermission}"
- pref="[[logsUploadPref_]]"
- on-settings-boolean-control-change="changeLogsPermission_">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button hidden="[[!showLogsPermission_]]"
+ id="chromeCleanupLogsUploadControl"
+ label="$i18n{chromeCleanupLogsUploadPermission}"
+ pref="[[logsUploadPref_]]"
+ on-settings-boolean-control-change="changeLogsPermission_">
+ </settings-toggle-button>
<div id="show-files-button" class="settings-box" actionable
on-tap="toggleExpandButton_" hidden="[[!showDetails_]]">
<div class="start">
diff --git a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js
index 3ecbfeb3d01..9ff10384a20 100644
--- a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js
+++ b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js
@@ -18,6 +18,19 @@ settings.ChromeCleanupIdleReason = {
};
/**
+ * The source of the dismiss action. Used when reporting metrics about how the
+ * card was dismissed. The numeric values must be kept in sync with the
+ * definition of ChromeCleanerDismissSource in
+ * src/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc.
+ * @enum {number}
+ */
+settings.ChromeCleanupDismissSource = {
+ OTHER: 0,
+ CLEANUP_SUCCESS_DONE_BUTTON: 1,
+ CLEANUP_FAILURE_DONE_BUTTON: 2,
+};
+
+/**
* @fileoverview
* 'settings-chrome-cleanup-page' is the settings page containing Chrome
* Cleanup settings.
@@ -85,6 +98,7 @@ Polymer({
showFilesToRemove_: {
type: Boolean,
value: false,
+ observer: 'showFilesToRemoveChanged_',
},
/** @private */
@@ -147,7 +161,6 @@ Polymer({
this.addWebUIListener(
'chrome-cleanup-upload-permission-change',
this.onUploadPermissionChange_.bind(this));
-
this.browserProxy_.registerChromeCleanerObserver();
},
@@ -182,6 +195,24 @@ Polymer({
},
/**
+ * Notify Chrome that the details section was opened or closed.
+ * @private
+ */
+ showFilesToRemoveChanged_: function() {
+ if (this.browserProxy_)
+ this.browserProxy_.notifyShowDetails(this.showFilesToRemove_);
+ },
+
+
+ /**
+ * Notfies Chrome that the "learn more" link was clicked.
+ * @private
+ */
+ learnMore_: function() {
+ this.browserProxy_.notifyLearnMoreClicked();
+ },
+
+ /**
* @return {boolean}
* @private
*/
@@ -198,17 +229,23 @@ Polymer({
if (idleReason == settings.ChromeCleanupIdleReason.CLEANING_SUCCEEDED) {
this.title_ = this.i18n('chromeCleanupTitleRemoved');
this.enableActionButton_(
- this.i18n('chromeCleanupDoneButtonLabel'), this.dismiss_.bind(this));
+ this.i18n('chromeCleanupDoneButtonLabel'),
+ this.dismiss_.bind(
+ this,
+ settings.ChromeCleanupDismissSource.CLEANUP_SUCCESS_DONE_BUTTON));
this.setIconDone_();
this.showLearnMore_ = false;
} else if (idleReason == settings.ChromeCleanupIdleReason.INITIAL) {
- this.dismiss_();
+ this.dismiss_(settings.ChromeCleanupDismissSource.OTHER);
} else {
// Scanning-related idle reasons are unexpected. Show an error message for
// all reasons other than |CLEANING_SUCCEEDED| and |INITIAL|.
this.title_ = this.i18n('chromeCleanupTitleErrorCantRemove');
this.enableActionButton_(
- this.i18n('chromeCleanupDoneButtonLabel'), this.dismiss_.bind(this));
+ this.i18n('chromeCleanupDoneButtonLabel'),
+ this.dismiss_.bind(
+ this,
+ settings.ChromeCleanupDismissSource.CLEANUP_FAILURE_DONE_BUTTON));
this.setIconWarning_();
this.showLearnMore_ = true;
}
@@ -311,10 +348,11 @@ Polymer({
/**
* Dismiss the card.
+ * @param {number} source
* @private
*/
- dismiss_: function() {
- this.browserProxy_.dismissCleanupPage();
+ dismiss_: function(source) {
+ this.browserProxy_.dismissCleanupPage(source);
},
/**
diff --git a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_proxy.js b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_proxy.js
index 135379ae9ff..bbfcb45d290 100644
--- a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_proxy.js
+++ b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_proxy.js
@@ -24,14 +24,26 @@ cr.define('settings', function() {
/**
* Hides the Cleanup page from the settings menu.
+ * @param {number} source
*/
- dismissCleanupPage() {}
+ dismissCleanupPage(source) {}
/**
* Updates the cleanup logs upload permission status.
* @param {boolean} enabled
*/
setLogsUploadPermission(enabled) {}
+
+ /**
+ * Notfies Chrome that the state of the details section changed.
+ * @param {boolean} enabled
+ */
+ notifyShowDetails(enabled) {}
+
+ /**
+ * Notfies Chrome that the "learn more" link was clicked.
+ */
+ notifyLearnMoreClicked() {}
}
/**
@@ -54,14 +66,24 @@ cr.define('settings', function() {
}
/** @override */
- dismissCleanupPage() {
- chrome.send('dismissCleanupPage');
+ dismissCleanupPage(source) {
+ chrome.send('dismissCleanupPage', [source]);
}
/** @override */
setLogsUploadPermission(enabled) {
chrome.send('setLogsUploadPermission', [enabled]);
}
+
+ /** @override */
+ notifyShowDetails(enabled) {
+ chrome.send('notifyShowDetails', [enabled]);
+ }
+
+ /** @override */
+ notifyLearnMoreClicked() {
+ chrome.send('notifyChromeCleanupLearnMoreClicked');
+ }
}
cr.addSingletonGetter(ChromeCleanupProxyImpl);
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_browser_proxy.js b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_browser_proxy.js
index 24bdd364009..f855f46579f 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_browser_proxy.js
@@ -28,11 +28,15 @@ cr.define('settings', function() {
/** @interface */
class ClearBrowsingDataBrowserProxy {
/**
+ * @param {!Array<string>} dataTypes
+ * @param {number} timePeriod
* @param {!Array<!ImportantSite>} importantSites
- * @return {!Promise<void>}
- * A promise resolved when data clearing has completed.
+ * @return {!Promise<boolean>}
+ * A promise resolved when data clearing has completed. The boolean
+ * indicates whether an additional dialog should be shown, informing the
+ * user about other forms of browsing history.
*/
- clearBrowsingData(importantSites) {}
+ clearBrowsingData(dataTypes, timePeriod, importantSites) {}
/**
* @return {!Promise<!Array<!ImportantSite>>}
@@ -52,8 +56,9 @@ cr.define('settings', function() {
*/
class ClearBrowsingDataBrowserProxyImpl {
/** @override */
- clearBrowsingData(importantSites) {
- return cr.sendWithPromise('clearBrowsingData', importantSites);
+ clearBrowsingData(dataTypes, timePeriod, importantSites) {
+ return cr.sendWithPromise(
+ 'clearBrowsingData', dataTypes, timePeriod, importantSites);
}
/** @override */
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
index 347d949b5e9..7c592698f2d 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
@@ -13,6 +13,8 @@
<link rel="import" href="../icons.html">
<link rel="import" href="../settings_shared_css.html">
+<!-- This file is forked as clear_browsing_data_dialog_tabs.html until the new
+ CBD UI is launched. -->
<dom-module id="settings-clear-browsing-data-dialog">
<template>
<style include="settings-shared">
@@ -20,7 +22,7 @@
visibility: hidden;
}
- #clearBrowsingDataDialog .footer {
+ #clearBrowsingDataDialog [slot=footer] {
color: var(--paper-grey-600);
}
@@ -66,6 +68,10 @@
width: 16px;
}
+ [slot=footer] iron-icon {
+ margin: auto;
+ }
+
.clear-browsing-data-footer {
-webkit-padding-start: 4px;
align-items: flex-start;
@@ -93,7 +99,7 @@
margin-top: 3px;
}
- .title .secondary {
+ [slot=title] .secondary {
font-size: calc(13 / 15 * 100%);
padding-top: 8px;
}
@@ -114,8 +120,8 @@
<dialog is="cr-dialog" id="clearBrowsingDataDialog"
on-close="onClearBrowsingDataDialogClose_"
close-text="$i18n{close}" ignore-popstate>
- <div class="title" slot="title">$i18n{clearBrowsingData}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{clearBrowsingData}</div>
+ <div slot="body">
<div class="row">
$i18n{clearFollowingItemsFrom}
<settings-dropdown-menu id="clearFrom"
@@ -128,58 +134,58 @@
history is disabled (i.e. supervised users, policy), so it's OK to
have a hidden checkbox that's also checked (as the C++ accounts for
whether a user is allowed to delete history independently). -->
- <settings-checkbox id="browsingCheckbox"
+ <settings-checkbox id="browsingCheckbox" class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.browsing_history}}"
label="$i18n{clearBrowsingHistory}"
sub-label="[[counters_.browsing_history]]"
disabled="[[clearingInProgress_]]"
hidden="[[isSupervised_]]">
</settings-checkbox>
- <settings-checkbox id="downloadCheckbox"
+ <settings-checkbox id="downloadCheckbox" class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.download_history}}"
label="$i18n{clearDownloadHistory}"
sub-label="[[counters_.download_history]]"
disabled="[[clearingInProgress_]]"
hidden="[[isSupervised_]]">
</settings-checkbox>
- <settings-checkbox id="cacheCheckbox"
+ <settings-checkbox id="cacheCheckbox" class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.cache}}"
label="$i18n{clearCache}"
sub-label="[[counters_.cache]]"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
- <settings-checkbox id="cookiesCheckbox"
+ <settings-checkbox id="cookiesCheckbox" class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.cookies}}"
label="$i18n{clearCookies}"
sub-label="$i18n{clearCookiesCounter}"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
- <settings-checkbox
+ <settings-checkbox class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.passwords}}"
label="$i18n{clearPasswords}"
sub-label="[[counters_.passwords]]"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
- <settings-checkbox
+ <settings-checkbox class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.form_data}}"
label="$i18n{clearFormData}"
sub-label="[[counters_.form_data]]"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
- <settings-checkbox
+ <settings-checkbox class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.hosted_apps_data}}"
label="$i18n{clearHostedAppData}"
sub-label="[[counters_.hosted_apps_data]]"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
- <settings-checkbox
+ <settings-checkbox class="browsing-data-checkbox"
pref="{{prefs.browser.clear_data.media_licenses}}"
label="$i18n{clearMediaLicenses}"
sub-label="[[counters_.media_licenses]]"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-spinner active="[[clearingInProgress_]]"></paper-spinner>
<paper-button class="cancel-button" disabled="[[clearingInProgress_]]"
on-tap="onCancelTap_">$i18n{cancel}</paper-button>
@@ -189,7 +195,7 @@
$i18n{clearBrowsingData}
</paper-button>
</div>
- <div class="footer" slot="footer">
+ <div slot="footer">
<div id="googleFooter" class="clear-browsing-data-footer">
<iron-icon icon="settings:googleg"></iron-icon>
<div class="footer-text">$i18nRaw{otherFormsOfBrowsingHistory}</div>
@@ -210,7 +216,7 @@
<template is="dom-if" if="[[showImportantSitesDialog_]]">
<dialog is="cr-dialog" id="importantSitesDialog" close-text="$i18n{close}"
show-scroll-borders ignore-popstate>
- <div class="title" slot="title">
+ <div slot="title">
$i18n{clearBrowsingData}
<div class="secondary">
<template is="dom-if"
@@ -222,7 +228,7 @@
</template>
</div>
</div>
- <div class="body" slot="body">
+ <div slot="body">
<template is="dom-repeat" items="[[importantSites_]]">
<div class="row">
<important-site-checkbox
@@ -232,7 +238,7 @@
</div>
</template>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-spinner active="[[clearingInProgress_]]"></paper-spinner>
<paper-button class="cancel-button" disabled="[[clearingInProgress_]]"
on-tap="onImportantSitesCancelTap_">$i18n{cancel}</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
index cc194f286a9..c78b9dd84d7 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
@@ -5,6 +5,9 @@
/**
* @fileoverview 'settings-clear-browsing-data-dialog' allows the user to delete
* browsing data that has been cached by Chromium.
+ *
+ * This file is forked as clear_browsing_data_dialog_tabs.js until the new
+ * CBD UI is launched.
*/
Polymer({
is: 'settings-clear-browsing-data-dialog',
@@ -105,14 +108,14 @@ Polymer({
attached: function() {
this.browserProxy_ =
settings.ClearBrowsingDataBrowserProxyImpl.getInstance();
- this.browserProxy_.initialize().then(function() {
+ this.browserProxy_.initialize().then(() => {
this.$.clearBrowsingDataDialog.showModal();
- }.bind(this));
+ });
if (this.importantSitesFlagEnabled_) {
- this.browserProxy_.getImportantSites().then(function(sites) {
+ this.browserProxy_.getImportantSites().then(sites => {
this.importantSites_ = sites;
- }.bind(this));
+ });
}
},
@@ -196,19 +199,23 @@ Polymer({
clearBrowsingData_: function() {
this.clearingInProgress_ = true;
- this.browserProxy_.clearBrowsingData(this.importantSites_)
- .then(
- /**
- * @param {boolean} shouldShowNotice Whether we should show the
- * notice about other forms of browsing history before closing the
- * dialog.
- */
- function(shouldShowNotice) {
- this.clearingInProgress_ = false;
- this.showHistoryDeletionDialog_ = shouldShowNotice;
- if (!shouldShowNotice)
- this.closeDialogs_();
- }.bind(this));
+ var checkboxes = this.root.querySelectorAll('.browsing-data-checkbox');
+ var dataTypes = [];
+ checkboxes.forEach((checkbox) => {
+ if (checkbox.checked)
+ dataTypes.push(checkbox.pref.key);
+ });
+
+ var timePeriod = this.$.clearFrom.pref.value;
+
+ this.browserProxy_
+ .clearBrowsingData(dataTypes, timePeriod, this.importantSites_)
+ .then(shouldShowNotice => {
+ this.clearingInProgress_ = false;
+ this.showHistoryDeletionDialog_ = shouldShowNotice;
+ if (!shouldShowNotice)
+ this.closeDialogs_();
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.html b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.html
new file mode 100644
index 00000000000..b991c9986fe
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.html
@@ -0,0 +1,261 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner.html">
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="clear_browsing_data_browser_proxy.html">
+<link rel="import" href="history_deletion_dialog.html">
+<link rel="import" href="../controls/important_site_checkbox.html">
+<link rel="import" href="../controls/settings_checkbox.html">
+<link rel="import" href="../controls/settings_dropdown_menu.html">
+<link rel="import" href="../icons.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<!-- This file is a fork of clear_browsing_data_dialog.html until the new CBD
+ UI is launched. -->
+<dom-module id="settings-clear-browsing-data-dialog-tabs">
+ <template>
+ <style include="settings-shared">
+ #clearBrowsingDataDialog:not(.fully-rendered) {
+ visibility: hidden;
+ }
+
+ #clearBrowsingDataDialog [slot=footer] {
+ color: var(--paper-grey-600);
+ }
+
+ .row {
+ align-items: center;
+ display: flex;
+ min-height: 40px;
+ }
+
+ paper-spinner {
+ -webkit-margin-end: 16px;
+ margin-bottom: auto;
+ margin-top: auto;
+ }
+
+ settings-checkbox,
+ important-site-checkbox {
+ --settings-row-two-line-min-height: 48px;
+ --settings-checkbox-label: {
+ line-height: 1.25rem;
+ };
+ }
+
+ #generalFooter {
+ margin: 0;
+ min-height: 18px;
+ }
+
+ #generalFooter iron-icon {
+ height: 18px;
+ padding: 1px;
+ width: 18px;
+ }
+
+ #googleFooter {
+ margin: 0 0 0.8em 0;
+ min-height: 16px;
+ }
+
+ #googleFooter iron-icon {
+ height: 16px;
+ padding: 2px;
+ width: 16px;
+ }
+
+ [slot=footer] iron-icon {
+ margin: auto;
+ }
+
+ .clear-browsing-data-footer {
+ -webkit-padding-start: 4px;
+ align-items: flex-start;
+ display: flex;
+ line-height: 1.538em; /* 20px/13px */
+ }
+
+ .clear-browsing-data-footer .footer-text {
+ -webkit-margin-start: 16px;
+ }
+
+ .clear-browsing-data-footer iron-icon {
+ flex-shrink: 0;
+ }
+
+ .clear-browsing-data-footer a {
+ text-decoration: none;
+ }
+
+ #clearFrom {
+ -webkit-margin-start: 0.5em;
+ /* Adjust for md-select-underline and 1px additional bottom padding
+ * to keep md-select's text (without the underline) aligned with
+ * neighboring text that does not have an underline. */
+ margin-top: 3px;
+ }
+
+ [slot=title] .secondary {
+ font-size: calc(13 / 15 * 100%);
+ padding-top: 8px;
+ }
+
+ /* Cap the height on smaller screens to avoid unfavorable clipping.
+ * Replace the bottom margin with padding to avoid the gap between
+ * the scrollbar and the bottom separator. */
+ @media all and (max-height: 724px) {
+ #clearBrowsingDataDialog {
+ /* crbug.com/652027: Show four and a *half* items in the list. */
+ --cr-dialog-body-container: {
+ max-height: 280px;
+ };
+ }
+ }
+ </style>
+
+ <dialog is="cr-dialog" id="clearBrowsingDataDialog"
+ on-close="onClearBrowsingDataDialogClose_"
+ close-text="$i18n{close}" ignore-popstate>
+ <div slot="title">$i18n{clearBrowsingData} - NEW UI</div>
+ <div slot="body">
+ <div class="row">
+ $i18n{clearFollowingItemsFrom}
+ <settings-dropdown-menu id="clearFrom"
+ label="$i18n{clearFollowingItemsFrom}"
+ pref="{{prefs.browser.clear_data.time_period}}"
+ menu-options="[[clearFromOptions_]]">
+ </settings-dropdown-menu>
+ </div>
+ <!-- Note: whether these checkboxes are checked are ignored if deleting
+ history is disabled (i.e. supervised users, policy), so it's OK to
+ have a hidden checkbox that's also checked (as the C++ accounts for
+ whether a user is allowed to delete history independently). -->
+ <settings-checkbox id="browsingCheckbox" class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.browsing_history}}"
+ label="$i18n{clearBrowsingHistory}"
+ sub-label="[[counters_.browsing_history]]"
+ disabled="[[clearingInProgress_]]"
+ hidden="[[isSupervised_]]">
+ </settings-checkbox>
+ <settings-checkbox id="downloadCheckbox" class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.download_history}}"
+ label="$i18n{clearDownloadHistory}"
+ sub-label="[[counters_.download_history]]"
+ disabled="[[clearingInProgress_]]"
+ hidden="[[isSupervised_]]">
+ </settings-checkbox>
+ <settings-checkbox id="cacheCheckbox" class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.cache}}"
+ label="$i18n{clearCache}"
+ sub-label="[[counters_.cache]]"
+ disabled="[[clearingInProgress_]]">
+ </settings-checkbox>
+ <settings-checkbox id="cookiesCheckbox" class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.cookies}}"
+ label="$i18n{clearCookies}"
+ sub-label="$i18n{clearCookiesCounter}"
+ disabled="[[clearingInProgress_]]">
+ </settings-checkbox>
+ <settings-checkbox class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.passwords}}"
+ label="$i18n{clearPasswords}"
+ sub-label="[[counters_.passwords]]"
+ disabled="[[clearingInProgress_]]">
+ </settings-checkbox>
+ <settings-checkbox class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.form_data}}"
+ label="$i18n{clearFormData}"
+ sub-label="[[counters_.form_data]]"
+ disabled="[[clearingInProgress_]]">
+ </settings-checkbox>
+ <settings-checkbox class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.hosted_apps_data}}"
+ label="$i18n{clearHostedAppData}"
+ sub-label="[[counters_.hosted_apps_data]]"
+ disabled="[[clearingInProgress_]]">
+ </settings-checkbox>
+ <settings-checkbox class="browsing-data-checkbox"
+ pref="{{prefs.browser.clear_data.media_licenses}}"
+ label="$i18n{clearMediaLicenses}"
+ sub-label="[[counters_.media_licenses]]"
+ disabled="[[clearingInProgress_]]">
+ </settings-checkbox>
+ </div>
+ <div slot="button-container">
+ <paper-spinner active="[[clearingInProgress_]]"></paper-spinner>
+ <paper-button class="cancel-button" disabled="[[clearingInProgress_]]"
+ on-tap="onCancelTap_">$i18n{cancel}</paper-button>
+ <paper-button id="clearBrowsingDataConfirm"
+ class="action-button" disabled="[[clearingInProgress_]]"
+ on-tap="onClearBrowsingDataTap_">
+ $i18n{clearBrowsingData}
+ </paper-button>
+ </div>
+ <div slot="footer">
+ <div id="googleFooter" class="clear-browsing-data-footer">
+ <iron-icon icon="settings:googleg"></iron-icon>
+ <div class="footer-text">$i18nRaw{otherFormsOfBrowsingHistory}</div>
+ </div>
+ <div id="generalFooter" class="clear-browsing-data-footer">
+ <iron-icon icon="settings:info"></iron-icon>
+ <div class="footer-text">
+ <span id="syncedDataSentence">$i18n{clearsSyncedData}</span>
+ <span>$i18n{warnAboutNonClearedData}</span>
+ <a id="clear-browser-data-old-learn-more-link"
+ href="$i18n{clearBrowsingDataLearnMoreUrl}"
+ target="_blank">$i18n{learnMore}</a>
+ </div>
+ </div>
+ </div>
+ </dialog>
+
+ <template is="dom-if" if="[[showImportantSitesDialog_]]">
+ <dialog is="cr-dialog" id="importantSitesDialog" close-text="$i18n{close}"
+ show-scroll-borders ignore-popstate>
+ <div slot="title">
+ $i18n{clearBrowsingData}
+ <div class="secondary">
+ <template is="dom-if"
+ if="[[!prefs.browser.clear_data.cache.value]]">
+ $i18n{importantSitesSubtitleCookies}
+ </template>
+ <template is="dom-if" if="[[prefs.browser.clear_data.cache.value]]">
+ $i18n{importantSitesSubtitleCookiesAndCache}
+ </template>
+ </div>
+ </div>
+ <div slot="body">
+ <template is="dom-repeat" items="[[importantSites_]]">
+ <div class="row">
+ <important-site-checkbox
+ site="[[item]]"
+ disabled="[[clearingInProgress_]]">
+ </important-site-checkbox>
+ </div>
+ </template>
+ </div>
+ <div slot="button-container">
+ <paper-spinner active="[[clearingInProgress_]]"></paper-spinner>
+ <paper-button class="cancel-button" disabled="[[clearingInProgress_]]"
+ on-tap="onImportantSitesCancelTap_">$i18n{cancel}</paper-button>
+ <paper-button id="importantSitesConfirm"
+ class="action-button" disabled="[[clearingInProgress_]]"
+ on-tap="onImportantSitesConfirmTap_">
+ $i18n{importantSitesConfirm}
+ </paper-button>
+ </div>
+ </dialog>
+ </template>
+
+ <template is="dom-if" if="[[showHistoryDeletionDialog_]]" restamp>
+ <settings-history-deletion-dialog id="notice"
+ on-close="onHistoryDeletionDialogClose_">
+ </settings-history-deletion-dialog>
+ </template>
+ </template>
+ <script src="clear_browsing_data_dialog_tabs.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.js b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.js
new file mode 100644
index 00000000000..b0c9479add2
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.js
@@ -0,0 +1,258 @@
+// 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.
+
+/**
+ * @fileoverview 'settings-clear-browsing-data-dialog-tabs' allows the user to
+ * delete browsing data that has been cached by Chromium.
+ *
+ * This file is a fork of clear_browsing_data_dialog.js until the new CBD UI is
+ * launched.
+ */
+Polymer({
+ is: 'settings-clear-browsing-data-dialog-tabs',
+
+ behaviors: [WebUIListenerBehavior],
+
+ properties: {
+ /**
+ * Preferences state.
+ */
+ prefs: {
+ type: Object,
+ notify: true,
+ },
+
+ /**
+ * Results of browsing data counters, keyed by the suffix of
+ * the corresponding data type deletion preference, as reported
+ * by the C++ side.
+ * @private {!Object<string>}
+ */
+ counters_: {
+ type: Object,
+ // Will be filled as results are reported.
+ value: function() {
+ return {};
+ }
+ },
+
+ /**
+ * List of options for the dropdown menu.
+ * @private {!DropdownMenuOptionList}
+ */
+ clearFromOptions_: {
+ readOnly: true,
+ type: Array,
+ value: [
+ {value: 0, name: loadTimeData.getString('clearDataHour')},
+ {value: 1, name: loadTimeData.getString('clearDataDay')},
+ {value: 2, name: loadTimeData.getString('clearDataWeek')},
+ {value: 3, name: loadTimeData.getString('clearData4Weeks')},
+ {value: 4, name: loadTimeData.getString('clearDataEverything')},
+ ],
+ },
+
+ /** @private */
+ clearingInProgress_: {
+ type: Boolean,
+ value: false,
+ },
+
+ /** @private */
+ isSupervised_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('isSupervised');
+ },
+ },
+
+ /** @private */
+ showHistoryDeletionDialog_: {
+ type: Boolean,
+ value: false,
+ },
+
+ /** @private {!Array<ImportantSite>} */
+ importantSites_: {
+ type: Array,
+ value: function() {
+ return [];
+ }
+ },
+
+ /** @private */
+ importantSitesFlagEnabled_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('importantSitesInCbd');
+ },
+ },
+
+ /** @private */
+ showImportantSitesDialog_: {type: Boolean, value: false},
+ },
+
+ /** @private {settings.ClearBrowsingDataBrowserProxy} */
+ browserProxy_: null,
+
+ /** @override */
+ ready: function() {
+ this.$.clearFrom.menuOptions = this.clearFromOptions_;
+ this.addWebUIListener('update-footer', this.updateFooter_.bind(this));
+ this.addWebUIListener(
+ 'update-counter-text', this.updateCounterText_.bind(this));
+ },
+
+ /** @override */
+ attached: function() {
+ this.browserProxy_ =
+ settings.ClearBrowsingDataBrowserProxyImpl.getInstance();
+ this.browserProxy_.initialize().then(() => {
+ this.$.clearBrowsingDataDialog.showModal();
+ });
+
+ if (this.importantSitesFlagEnabled_) {
+ this.browserProxy_.getImportantSites().then(sites => {
+ this.importantSites_ = sites;
+ });
+ }
+ },
+
+ /**
+ * Updates the footer to show only those sentences that are relevant to this
+ * user.
+ * @param {boolean} syncing Whether the user is syncing data.
+ * @param {boolean} otherFormsOfBrowsingHistory Whether the user has other
+ * forms of browsing history in their account.
+ * @private
+ */
+ updateFooter_: function(syncing, otherFormsOfBrowsingHistory) {
+ this.$.googleFooter.hidden = !otherFormsOfBrowsingHistory;
+ this.$.syncedDataSentence.hidden = !syncing;
+ this.$.clearBrowsingDataDialog.classList.add('fully-rendered');
+ },
+
+ /**
+ * Updates the text of a browsing data counter corresponding to the given
+ * preference.
+ * @param {string} prefName Browsing data type deletion preference.
+ * @param {string} text The text with which to update the counter
+ * @private
+ */
+ updateCounterText_: function(prefName, text) {
+ // Data type deletion preferences are named "browser.clear_data.<datatype>".
+ // Strip the common prefix, i.e. use only "<datatype>".
+ var matches = prefName.match(/^browser\.clear_data\.(\w+)$/);
+ this.set('counters_.' + assert(matches[1]), text);
+ },
+
+ /**
+ * @return {boolean} Whether the ImportantSites dialog should be shown.
+ * @private
+ */
+ shouldShowImportantSites_: function() {
+ if (!this.importantSitesFlagEnabled_)
+ return false;
+ if (!this.$.cookiesCheckbox.checked)
+ return false;
+
+ var haveImportantSites = this.importantSites_.length > 0;
+ chrome.send(
+ 'metricsHandler:recordBooleanHistogram',
+ ['History.ClearBrowsingData.ImportantDialogShown', haveImportantSites]);
+ return haveImportantSites;
+ },
+
+ /**
+ * Handles the tap on the Clear Data button.
+ * @private
+ */
+ onClearBrowsingDataTap_: function() {
+ if (this.shouldShowImportantSites_()) {
+ this.showImportantSitesDialog_ = true;
+ this.$.clearBrowsingDataDialog.close();
+ // Show important sites dialog after dom-if is applied.
+ this.async(function() {
+ this.$$('#importantSitesDialog').showModal();
+ });
+ } else {
+ this.clearBrowsingData_();
+ }
+ },
+
+ /**
+ * Handles closing of the clear browsing data dialog. Stops the close
+ * event from propagating if another dialog is shown to prevent the
+ * privacy-page from closing this dialog.
+ * @private
+ */
+ onClearBrowsingDataDialogClose_: function(event) {
+ if (this.showImportantSitesDialog_)
+ event.stopPropagation();
+ },
+
+ /**
+ * Clears browsing data and maybe shows a history notice.
+ * @private
+ */
+ clearBrowsingData_: function() {
+ this.clearingInProgress_ = true;
+
+ var checkboxes = this.root.querySelectorAll('.browsing-data-checkbox');
+ var dataTypes = [];
+ checkboxes.forEach((checkbox) => {
+ if (checkbox.checked)
+ dataTypes.push(checkbox.pref.key);
+ });
+
+ var timePeriod = this.$.clearFrom.pref.value;
+
+ this.browserProxy_
+ .clearBrowsingData(dataTypes, timePeriod, this.importantSites_)
+ .then(shouldShowNotice => {
+ this.clearingInProgress_ = false;
+ this.showHistoryDeletionDialog_ = shouldShowNotice;
+ if (!shouldShowNotice)
+ this.closeDialogs_();
+ });
+ },
+
+ /**
+ * Closes the clear browsing data or important site dialog if they are open.
+ * @private
+ */
+ closeDialogs_: function() {
+ if (this.$.clearBrowsingDataDialog.open)
+ this.$.clearBrowsingDataDialog.close();
+ if (this.showImportantSitesDialog_)
+ this.$$('#importantSitesDialog').close();
+ },
+
+ /** @private */
+ onCancelTap_: function() {
+ this.$.clearBrowsingDataDialog.cancel();
+ },
+
+ /**
+ * Handles the tap confirm button in important sites.
+ * @private
+ */
+ onImportantSitesConfirmTap_: function() {
+ this.clearBrowsingData_();
+ },
+
+ /** @private */
+ onImportantSitesCancelTap_: function() {
+ /** @type {!CrDialogElement} */ (this.$$('#importantSitesDialog')).cancel();
+ },
+
+ /**
+ * Handles the closing of the notice about other forms of browsing history.
+ * @private
+ */
+ onHistoryDeletionDialogClose_: function() {
+ this.showHistoryDeletionDialog_ = false;
+ this.closeDialogs_();
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html
index eee0badbca2..a17572fb569 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html
@@ -8,9 +8,9 @@
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{historyDeletionDialogTitle}</div>
- <div class="body" slot="body">$i18nRaw{historyDeletionDialogBody}</div>
- <div class="button-container" slot="button-container">
+ <div slot="title">$i18n{historyDeletionDialogTitle}</div>
+ <div slot="body">$i18nRaw{historyDeletionDialogBody}</div>
+ <div slot="button-container">
<paper-button class="action-button" on-tap="onOkTap_">
$i18n{historyDeletionDialogOK}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/compiled_resources2.gyp
index f655815f2fa..bec907b35a0 100644
--- a/chromium/chrome/browser/resources/settings/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/compiled_resources2.gyp
@@ -48,6 +48,7 @@
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
+ '<(EXTERNS_GYP):metrics_private',
'page_visibility'
],
'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'],
@@ -78,7 +79,7 @@
'appearance_page/compiled_resources2.gyp:*',
'basic_page/compiled_resources2.gyp:*',
'bluetooth_page/compiled_resources2.gyp:*',
- 'certificate_manager_page/compiled_resources2.gyp:*',
+ 'change_password_page/compiled_resources2.gyp:*',
'chrome_cleanup_page/compiled_resources2.gyp:*',
'clear_browsing_data_dialog/compiled_resources2.gyp:*',
'controls/compiled_resources2.gyp:*',
diff --git a/chromium/chrome/browser/resources/settings/controls/controlled_radio_button.js b/chromium/chrome/browser/resources/settings/controls/controlled_radio_button.js
index 15e60dda7e8..ca55d6b2bb1 100644
--- a/chromium/chrome/browser/resources/settings/controls/controlled_radio_button.js
+++ b/chromium/chrome/browser/resources/settings/controls/controlled_radio_button.js
@@ -13,6 +13,7 @@ Polymer({
properties: {
checked: {
type: Boolean,
+ value: false,
reflectToAttribute: true,
observer: 'checkedChanged_',
},
diff --git a/chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js b/chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js
index dd3e55b4cfe..d7597657387 100644
--- a/chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js
+++ b/chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js
@@ -29,7 +29,7 @@ var PrefControlBehavior = {
* @private
*/
validatePref_: function() {
- CrSettingsPrefs.initialized.then(function() {
+ CrSettingsPrefs.initialized.then(() => {
if (!this.pref) {
var error = 'Pref not found for element ' + this.tagName;
if (this.id)
@@ -37,6 +37,6 @@ var PrefControlBehavior = {
error += ' in ' + this.domHost.tagName;
console.error(error);
}
- }.bind(this));
+ });
},
};
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_checkbox.html b/chromium/chrome/browser/resources/settings/controls/settings_checkbox.html
index 3274746ca4c..4dca0444b47 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_checkbox.html
+++ b/chromium/chrome/browser/resources/settings/controls/settings_checkbox.html
@@ -20,6 +20,12 @@
}
paper-checkbox {
+ /* Handle overflow of subLabel when it is larger than one line. */
+ align-items: center;
+ display: flex;
+ /* Additional margin in case subLabel needs more than one line. */
+ margin-bottom: 4px;
+ margin-top: 4px;
width: 100%;
}
@@ -35,12 +41,15 @@
@apply(--settings-checkbox-label);
}
</style>
- <div id="outerRow" noSubLabel$="[[!subLabel]]">
+ <div id="outerRow" noSubLabel$="[[!hasSubLabel_(subLabel, subLabelHtml)]]">
<paper-checkbox id="checkbox" checked="{{checked}}"
on-change="notifyChangedByUserInteraction"
disabled="[[controlDisabled_(disabled, pref.*)]]">
<div class="label">[[label]] <slot></slot></div>
- <div class="secondary label">[[subLabel]]</div>
+ <div class="secondary label">
+ <div inner-h-t-m-l="[[subLabelHtml]]"></div>
+ [[subLabel]]
+ </div>
</paper-checkbox>
<template is="dom-if" if="[[pref.controlledBy]]">
<cr-policy-pref-indicator pref="[[pref]]" icon-aria-label="[[label]]">
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_checkbox.js b/chromium/chrome/browser/resources/settings/controls/settings_checkbox.js
index 6528fec6279..8596d6a1fc9 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_checkbox.js
+++ b/chromium/chrome/browser/resources/settings/controls/settings_checkbox.js
@@ -10,4 +10,49 @@ Polymer({
is: 'settings-checkbox',
behaviors: [SettingsBooleanControlBehavior],
+
+ properties: {
+ /**
+ * Alternative source for the sub-label that can contain html markup.
+ * Only use with trusted input.
+ */
+ subLabelHtml: {
+ type: String,
+ value: '',
+ },
+ },
+
+ observers: [
+ 'subLabelHtmlChanged_(subLabelHtml)',
+ ],
+
+ /**
+ * Don't let clicks on a link inside the secondary label reach the checkbox.
+ * @private
+ */
+ subLabelHtmlChanged_: function() {
+ var links = this.root.querySelectorAll('.secondary.label a');
+ links.forEach((link) => {
+ link.addEventListener('tap', this.stopPropagation);
+ });
+ },
+
+ /**
+ * @param {!Event} event
+ * @private
+ */
+ stopPropagation: function(event) {
+ event.stopPropagation();
+ },
+
+ /**
+ * @param {string} subLabel
+ * @param {string} subLabelHtml
+ * @return {boolean} Whether there is a subLabel
+ * @private
+ */
+ hasSubLabel_: function(subLabel, subLabelHtml) {
+ return !!subLabel || !!subLabelHtml;
+ },
+
});
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.js b/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.js
index e3fddcf7fc3..d043b4bbc71 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.js
+++ b/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.js
@@ -97,11 +97,11 @@ Polymer({
// Wait for the dom-repeat to populate the <select> before setting
// <select>#value so the correct option gets selected.
- this.async(function() {
+ this.async(() => {
this.$.dropdownMenu.value = option == undefined ?
this.notFoundValue_ :
Settings.PrefUtil.prefToString(assert(this.pref));
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_idle_load.js b/chromium/chrome/browser/resources/settings/controls/settings_idle_load.js
index 3d741adb2cd..bd9f7a0c744 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_idle_load.js
+++ b/chromium/chrome/browser/resources/settings/controls/settings_idle_load.js
@@ -47,8 +47,8 @@ Polymer({
if (this.loading_)
return this.loading_;
- this.loading_ = new Promise(function(resolve, reject) {
- this.importHref(this.url, function() {
+ this.loading_ = new Promise((resolve, reject) => {
+ this.importHref(this.url, () => {
assert(!this.ctor);
this.templatize(this);
assert(this.ctor);
@@ -62,8 +62,8 @@ Polymer({
resolve(this.child_);
this.fire('lazy-loaded');
- }.bind(this), reject, true);
- }.bind(this));
+ }, reject, true);
+ });
return this.loading_;
},
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.html b/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.html
index b2087e32293..7776cccd157 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.html
+++ b/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.html
@@ -9,6 +9,19 @@
<dom-module id="settings-toggle-button">
<template>
<style include="settings-shared iron-flex">
+ :host {
+ @apply(--cr-section);
+ }
+
+ :host(.first),
+ :host(.continuation) {
+ border-top: none;
+ }
+
+ :host(.three-line) {
+ min-height: var(--settings-row-three-line-min-height);
+ }
+
:host([elide-label]),
:host([elide-label]) #outerRow,
:host([elide-label]) #outerRow > div.flex {
@@ -31,7 +44,7 @@
}
#labelWrapper,
- ::content .more-actions {
+ ::slotted([slot='more-actions']) {
-webkit-margin-end: var(--settings-control-label-spacing);
}
@@ -40,13 +53,11 @@
}
</style>
<div id="outerRow" noSubLabel$="[[!subLabel]]">
- <div class="flex" id="labelWrapper" on-tap="onLabelWrapperTap_"
- actionable$="[[!controlDisabled_(disabled, pref.*)]]"
- hidden="[[!label]]">
+ <div class="flex" id="labelWrapper" hidden="[[!label]]">
<div id="label" class="label">[[label]]</div>
<div id="subLabel" class="secondary label">[[subLabel]]</div>
</div>
- <content select=".more-actions"></content>
+ <slot name="more-actions"></slot>
<template is="dom-if" if="[[hasPrefPolicyIndicator(pref.*)]]">
<cr-policy-pref-indicator pref="[[pref]]" icon-aria-label="[[label]]">
</cr-policy-pref-indicator>
@@ -54,7 +65,8 @@
<paper-toggle-button id="control" checked="{{checked}}"
on-change="notifyChangedByUserInteraction" aria-labelledby="label"
aria-describedby="subLabel" on-up="resetTrackLock_"
- disabled="[[controlDisabled_(disabled, pref)]]">
+ disabled="[[controlDisabled_(disabled, pref)]]"
+ on-tap="onToggleTap_">
</paper-toggle-button>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.js b/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.js
index 5b4c77f1537..1ac827c9fd8 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.js
+++ b/chromium/chrome/browser/resources/settings/controls/settings_toggle_button.js
@@ -18,18 +18,53 @@ Polymer({
},
},
+ listeners: {
+ 'tap': 'onHostTap_',
+ },
+
+ observers: [
+ 'onDisableOrPrefChange_(disabled, pref.*)',
+ ],
+
/** @override */
focus: function() {
this.$.control.focus();
},
+ /**
+ * Handle taps directly on the toggle (see: onLabelWrapperTap_ for non-toggle
+ * taps).
+ * @param {!Event} e
+ * @private
+ */
+ onToggleTap_: function(e) {
+ // Stop the event from propagating to avoid firing two 'changed' events.
+ e.stopPropagation();
+ },
+
/** @private */
- onLabelWrapperTap_: function() {
+ onDisableOrPrefChange_: function() {
+ if (this.controlDisabled_()) {
+ this.removeAttribute('actionable');
+ } else {
+ this.setAttribute('actionable', '');
+ }
+ },
+
+ /**
+ * Handle non-toggle button taps (see: onToggleTap_ for toggle taps).
+ * @param {!Event} e
+ * @private
+ */
+ onHostTap_: function(e) {
+ // Stop the event from propagating to avoid firing two 'changed' events.
+ e.stopPropagation();
if (this.controlDisabled_())
return;
this.checked = !this.checked;
this.notifyChangedByUserInteraction();
+ this.fire('change');
},
/**
@@ -38,6 +73,7 @@ Polymer({
* @private
*/
resetTrackLock_: function() {
- Polymer.Gestures.gestures.tap.reset();
+ // Run tap.reset in next run-loop to avoid reversing the current tap event.
+ setTimeout(() => Polymer.Gestures.gestures.tap.reset());
},
});
diff --git a/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.html b/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.html
index b40d20261b9..40a923df826 100644
--- a/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.html
+++ b/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.html
@@ -15,8 +15,8 @@
<dom-module id="settings-date-time-page">
<template>
<style include="settings-shared">
- .embedded {
- -webkit-padding-start: var(--settings-box-row-indent);
+ #timeZoneAutoDetect {
+ padding: 0;
}
settings-dropdown-menu {
@@ -35,32 +35,66 @@
<div id="timezoneGeolocateToggleLabel" class="start">
$i18n{timeZoneGeolocation}
</div>
- <template is="dom-if" if="[[hasTimeZoneAutoDetectPolicy_]]" restamp>
- <cr-policy-indicator indicator-type="devicePolicy"
- icon-aria-label="$i18n{timeZoneGeolocation}">
- </cr-policy-indicator>
+ <template is="dom-if" restamp
+ if="[[!prefs.cros.flags.per_user_timezone_enabled.value]]">
+ <template is="dom-if" if="[[hasTimeZoneAutoDetectPolicy_]]" restamp>
+ <cr-policy-indicator indicator-type="devicePolicy"
+ icon-aria-label="$i18n{timeZoneGeolocation}">
+ </cr-policy-indicator>
+ </template>
+ <paper-toggle-button
+ id="timeZoneAutoDetect"
+ aria-labelledby="timezoneGeolocateToggleLabel"
+ checked="[[timeZoneAutoDetect_]]"
+ disabled="[[hasTimeZoneAutoDetectPolicy_]]"
+ on-change="onTimeZoneAutoDetectChange_">
+ </paper-toggle-button>
+ </template>
+ <template is="dom-if" restamp
+ if="[[prefs.cros.flags.per_user_timezone_enabled.value]]">
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.resolve_timezone_by_geolocation}}"
+ id="timeZoneAutoDetect"
+ aria-labelledby="timezoneGeolocateToggleLabel">
+ </settings-toggle-button>
</template>
- <paper-toggle-button
- id="timeZoneAutoDetect"
- aria-labelledby="timezoneGeolocateToggleLabel"
- checked="[[timeZoneAutoDetect_]]"
- disabled="[[hasTimeZoneAutoDetectPolicy_]]"
- on-change="onTimeZoneAutoDetectChange_">
- </paper-toggle-button>
</div>
<div class="settings-box continuation embedded">
- <settings-dropdown-menu pref="{{prefs.cros.system.timezone}}"
- label="$i18n{timeZone}"
- menu-options="[[timeZoneList_]]"
- disabled="[[timeZoneAutoDetect_]]">
- </settings-dropdown-menu>
- </div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.clock.use_24hour_clock}}"
- label="$i18n{use24HourClock}">
- </settings-toggle-button>
+ <template is="dom-if" restamp
+ if="[[!prefs.cros.flags.per_user_timezone_enabled.value]]">
+ <settings-dropdown-menu pref="{{prefs.cros.system.timezone}}"
+ label="$i18n{timeZone}"
+ menu-options="[[timeZoneList_]]"
+ disabled="[[timeZoneAutoDetect_]]">
+ </settings-dropdown-menu>
+ </template>
+ <template is="dom-if" restamp
+ if="[[prefs.cros.flags.per_user_timezone_enabled.value]]">
+ <template is="dom-if" if="[[!isUserTimeZoneSelectorHidden_(
+ prefs.settings.timezone,
+ prefs.settings.resolve_timezone_by_geolocation.value)]]" restamp>
+ <settings-dropdown-menu id="userTimeZoneSelector"
+ pref="{{prefs.settings.timezone}}"
+ label="$i18n{timeZone}"
+ menu-options="[[timeZoneList_]]">
+ </settings-dropdown-menu>
+ </template>
+ <template is="dom-if" if="[[isUserTimeZoneSelectorHidden_(
+ prefs.settings.timezone,
+ prefs.settings.resolve_timezone_by_geolocation.value)]]" restamp>
+ <settings-dropdown-menu id="systemTimezoneSelector"
+ pref="{{prefs.cros.system.timezone}}"
+ label="$i18n{timeZone}"
+ menu-options="[[timeZoneList_]]"
+ disabled>
+ </settings-dropdown-menu>
+ </template>
+ </template>
</div>
+ <settings-toggle-button
+ pref="{{prefs.settings.clock.use_24hour_clock}}"
+ label="$i18n{use24HourClock}">
+ </settings-toggle-button>
<div class="settings-box" id="setDateTime" actionable
on-tap="onSetDateTimeTap_" hidden$="[[!canSetDateTime_]]">
<div class="start">$i18n{setDateTime}</div>
diff --git a/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js b/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js
index 3b004f22eab..ef378947636 100644
--- a/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js
+++ b/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js
@@ -90,7 +90,9 @@ Polymer({
},
observers: [
- 'maybeGetTimeZoneList_(' +
+ 'maybeGetTimeZoneListPerUser_(' +
+ 'prefs.settings.timezone.value, timeZoneAutoDetect_)',
+ 'maybeGetTimeZoneListPerSystem_(' +
'prefs.cros.system.timezone.value, timeZoneAutoDetect_)',
],
@@ -174,24 +176,54 @@ Polymer({
/**
* Fetches the list of time zones if necessary.
+ * @param {boolean=} perUserTimeZoneMode Expected value of per-user time zone.
* @private
*/
- maybeGetTimeZoneList_: function() {
+ maybeGetTimeZoneList_: function(perUserTimeZoneMode) {
+ if (typeof(perUserTimeZoneMode) !== 'undefined') {
+ /* This method is called as observer. Skip if if current mode does not
+ * match expected.
+ */
+ if (perUserTimeZoneMode !=
+ this.getPref('cros.flags.per_user_timezone_enabled').value) {
+ return;
+ }
+ }
// Only fetch the list once.
if (this.timeZoneList_.length > 1 || !CrSettingsPrefs.isInitialized)
return;
// If auto-detect is enabled, we only need the current time zone.
- if (this.timeZoneAutoDetect_ &&
- this.getPref('cros.system.timezone').value ==
- this.timeZoneList_[0].value) {
- return;
+ if (this.timeZoneAutoDetect_) {
+ var isPerUserTimezone =
+ this.getPref('cros.flags.per_user_timezone_enabled').value;
+ if (this.timeZoneList_[0].value ==
+ (isPerUserTimezone ? this.getPref('settings.timezone').value :
+ this.getPref('cros.system.timezone').value)) {
+ return;
+ }
}
cr.sendWithPromise('getTimeZones').then(this.setTimeZoneList_.bind(this));
},
/**
+ * Prefs observer for Per-user time zone enabled mode.
+ * @private
+ */
+ maybeGetTimeZoneListPerUser_: function() {
+ this.maybeGetTimeZoneList_(true);
+ },
+
+ /**
+ * Prefs observer for Per-user time zone disabled mode.
+ * @private
+ */
+ maybeGetTimeZoneListPerSystem_: function() {
+ this.maybeGetTimeZoneList_(false);
+ },
+
+ /**
* Converts the C++ response into an array of menu options.
* @param {!Array<!Array<string>>} timeZones C++ time zones response.
* @private
@@ -204,4 +236,17 @@ Polymer({
};
});
},
+
+ /**
+ * Computes visibility of user timezone preference.
+ * @param {?chrome.settingsPrivate.PrefObject} prefUserTimezone
+ * pref.settings.timezone
+ * @param {boolean} prefResolveValue
+ * prefs.settings.resolve_timezone_by_geolocation.value
+ * @private
+ */
+ isUserTimeZoneSelectorHidden_: function(prefUserTimezone, prefResolveValue) {
+ return (prefUserTimezone && prefUserTimezone.controlledBy != null) ||
+ prefResolveValue;
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/device_page/device_page_browser_proxy.js b/chromium/chrome/browser/resources/settings/device_page/device_page_browser_proxy.js
index 29d311905c1..0344e145e0b 100644
--- a/chromium/chrome/browser/resources/settings/device_page/device_page_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/device_page/device_page_browser_proxy.js
@@ -25,6 +25,7 @@ settings.PowerSource;
/**
* @typedef {{
+ * present: boolean,
* charging: boolean,
* calculating: boolean,
* percent: number,
diff --git a/chromium/chrome/browser/resources/settings/device_page/display.html b/chromium/chrome/browser/resources/settings/device_page/display.html
index e28512cea44..6d2b3abf188 100644
--- a/chromium/chrome/browser/resources/settings/device_page/display.html
+++ b/chromium/chrome/browser/resources/settings/device_page/display.html
@@ -21,7 +21,7 @@
<dom-module id="settings-display">
<template>
<style include="settings-shared md-select iron-flex iron-flex-alignment">
- .settings-box.embedded {
+ .settings-box.indented {
-webkit-margin-start: 20px;
align-self: stretch;
padding: 0;
@@ -91,7 +91,7 @@
<template is="dom-if" if="[[showMirror_(unifiedDesktopMode_, displays)]]"
restamp>
- <div class="settings-box embedded two-line">
+ <div class="settings-box indented two-line">
<div class="start">
<div id="displayMirrorCheckboxLabel">$i18n{displayMirror}</div>
<div class="secondary">[[getDisplayMirrorText_(displays)]]</div>
@@ -105,7 +105,7 @@
<template is="dom-if" if="[[showUnifiedDesktop_(unifiedDesktopAvailable_,
unifiedDesktopMode_, displays)]]" restamp>
- <div class="settings-box embedded two-line">
+ <div class="settings-box indented two-line">
<div class="start">
<div id="displayUnifiedDesktopCheckboxLabel">
$i18n{displayUnfiedDesktop}
@@ -123,7 +123,7 @@
<template is="dom-if" restamp
if="[[showDisplaySelectMenu_(displays, selectedDisplay)]]">
- <div class="settings-box embedded">
+ <div class="settings-box indented">
<div id="displayScreenTitle" class="start">
$i18n{displayScreenTitle}
</div>
@@ -140,7 +140,7 @@
</div>
</template>
- <div class="settings-box embedded two-line">
+ <div class="settings-box indented two-line">
<div class="start textarea layout vertical">
<div>$i18n{displayResolutionTitle}</div>
<div class="secondary layout self-start">
@@ -154,7 +154,7 @@
</div>
<template is="dom-if" if="[[!unifiedDesktopMode_]]" restamp>
- <div class="settings-box embedded">
+ <div class="settings-box indented">
<div id="displayOrientation" class="start textarea">
$i18n{displayOrientation}
</div>
@@ -172,7 +172,7 @@
</div>
</template>
- <div id="overscan" class="settings-box embedded two-line"
+ <div id="overscan" class="settings-box indented two-line"
on-tap="onOverscanTap_" hidden$="[[selectedDisplay.isInternal]]"
actionable>
<div class="start">
@@ -191,7 +191,7 @@
on-close="onCloseOverscanDialog_">
</settings-display-overscan-dialog>
- <div class="settings-box embedded two-line"
+ <div class="settings-box indented two-line"
on-tap="onTouchCalibrationTap_"
hidden$="[[!showTouchCalibrationSetting_(selectedDisplay)]]"
actionable>
@@ -209,21 +209,16 @@
<!-- Night Light Settings -->
<template is="dom-if" if="[[nightLightFeatureEnabled_]]" restamp>
- <div class="settings-box">
- <div class="start">
- <h2 id="nightLightLabel">$i18n{displayNightLightLabel}</h2>
- <div class="secondary">$i18n{displayNightLightText}</div>
- </div>
- <settings-toggle-button
- id="nightLightToggleButton"
- pref="{{prefs.ash.night_light.enabled}}"
- aria-labelledby="nightLightLabel">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ id="nightLightToggleButton"
+ label="$i18n{displayNightLightLabel}"
+ pref="{{prefs.ash.night_light.enabled}}"
+ sub-label="$i18n{displayNightLightText}">
+ </settings-toggle-button>
<div id="nightLightSettingsDiv"
class="settings-box continuation start layout vertical">
<!-- Color temperature slider -->
- <div class="settings-box embedded continuation">
+ <div class="settings-box indented continuation">
<div class="start textarea" id="colorTemperatureLabel">
$i18n{displayNightLightTemperatureLabel}
</div>
@@ -235,7 +230,7 @@
</settings-slider>
</div>
<!-- Schedule settings -->
- <div class="settings-box embedded">
+ <div class="settings-box indented">
<div id="nightLightScheduleLabel" class="start textarea">
$i18n{displayNightLightScheduleLabel}
</div>
@@ -247,11 +242,11 @@
</settings-dropdown-menu>
</div>
<!-- Custom schedule slider -->
- <div class="settings-box embedded continuation">
+ <div class="settings-box indented continuation">
<iron-collapse id="nightLightCustomScheduleCollapse"
class="start textarea layout vertical"
opened="[[shouldOpenCustomScheduleCollapse_]]">
- <div class="settings-box embedded continuation">
+ <div class="settings-box indented continuation">
<night-light-slider id="nightLightSlider" prefs="{{prefs}}">
</night-light-slider>
</div>
diff --git a/chromium/chrome/browser/resources/settings/device_page/display.js b/chromium/chrome/browser/resources/settings/device_page/display.js
index d5eea9360e0..a29d2615c60 100644
--- a/chromium/chrome/browser/resources/settings/device_page/display.js
+++ b/chromium/chrome/browser/resources/settings/device_page/display.js
@@ -461,7 +461,7 @@ Polymer({
/**
* Triggered when the 'change' event for the selected mode slider is
- * triggered. This only occurs when the value is comitted (i.e. not while
+ * triggered. This only occurs when the value is committed (i.e. not while
* the slider is being dragged).
* @private
*/
diff --git a/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html b/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html
index d4f6cf4142c..08e263c7738 100644
--- a/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html
+++ b/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html
@@ -45,8 +45,8 @@
</style>
<dialog is="cr-dialog" id="dialog" on-close="close"
close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{displayOverscanPageTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{displayOverscanPageTitle}</div>
+ <div slot="body">
<div class="subtitle" >$i18n{displayOverscanSubtitle}</div>
<div class="instructions" >$i18n{displayOverscanInstructions}</div>
<div class="details layout horizontal around-justified self-stretch">
@@ -73,7 +73,7 @@
</div>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="reset" class="cancel-button" on-tap="onResetTap_">
$i18n{displayOverscanReset}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html b/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html
index b142f5601c0..696cbad5190 100644
--- a/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html
+++ b/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html
@@ -9,13 +9,13 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
+ <div slot="title">
$i18n{storageClearDriveCacheDialogTitle}
</div>
- <div class="body" slot="body">
+ <div slot="body">
<span>$i18n{storageClearDriveCacheDialogDescription}</span>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="cancelButton" class="cancel-button"
on-tap="onCancelTap_">
$i18n{cancel}
diff --git a/chromium/chrome/browser/resources/settings/device_page/keyboard.html b/chromium/chrome/browser/resources/settings/device_page/keyboard.html
index 45cd22e1f9c..cabf3ca8e43 100644
--- a/chromium/chrome/browser/resources/settings/device_page/keyboard.html
+++ b/chromium/chrome/browser/resources/settings/device_page/keyboard.html
@@ -66,22 +66,18 @@
menu-options="[[keyMapTargets_]]">
</settings-dropdown-menu>
</div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.language.send_function_keys}}"
- label="$i18n{keyboardSendFunctionKeys}"
- sub-label="$i18n{keyboardSendFunctionKeysDescription}">
- </settings-toggle-button>
- </div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.language.xkb_auto_repeat_enabled_r2}}"
- label="$i18n{keyboardEnableAutoRepeat}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.settings.language.send_function_keys}}"
+ label="$i18n{keyboardSendFunctionKeys}"
+ sub-label="$i18n{keyboardSendFunctionKeysDescription}">
+ </settings-toggle-button>
+ <settings-toggle-button
+ pref="{{prefs.settings.language.xkb_auto_repeat_enabled_r2}}"
+ label="$i18n{keyboardEnableAutoRepeat}">
+ </settings-toggle-button>
<iron-collapse
opened="[[prefs.settings.language.xkb_auto_repeat_enabled_r2.value]]">
- <div class="settings-box continuation settings-checkbox-spacer">
+ <div class="settings-box continuation embedded">
<div class="start" id="repeatDelayLabel">$i18n{keyRepeatDelay}</div>
<settings-slider id="delaySlider"
pref="{{prefs.settings.language.xkb_auto_repeat_delay_r2}}"
@@ -93,7 +89,7 @@
label-max="$i18n{keyRepeatDelayShort}">
</settings-slider>
</div>
- <div class="settings-box continuation settings-checkbox-spacer">
+ <div class="settings-box continuation embedded">
<div class="start" id="repeatRateLabel">$i18n{keyRepeatRate}</div>
<settings-slider id="repeatRateSlider"
pref="{{
diff --git a/chromium/chrome/browser/resources/settings/device_page/layout_behavior.js b/chromium/chrome/browser/resources/settings/device_page/layout_behavior.js
index d1665050e38..0d1219102c8 100644
--- a/chromium/chrome/browser/resources/settings/device_page/layout_behavior.js
+++ b/chromium/chrome/browser/resources/settings/device_page/layout_behavior.js
@@ -293,7 +293,7 @@ var LayoutBehavior = {
*/
findChildren_: function(parentId, recurse) {
var children = [];
- this.displayLayoutMap_.forEach(function(value, key) {
+ this.displayLayoutMap_.forEach((value, key) => {
var childId = key;
if (childId != parentId && value.parentId == parentId) {
// Insert immediate children at the front of the array.
@@ -303,7 +303,7 @@ var LayoutBehavior = {
children = children.concat(this.findChildren_(childId, true));
}
}
- }.bind(this));
+ });
return children;
},
diff --git a/chromium/chrome/browser/resources/settings/device_page/pointers.html b/chromium/chrome/browser/resources/settings/device_page/pointers.html
index fa34e0223ff..d93db637cf5 100644
--- a/chromium/chrome/browser/resources/settings/device_page/pointers.html
+++ b/chromium/chrome/browser/resources/settings/device_page/pointers.html
@@ -19,6 +19,7 @@
-webkit-padding-start: var(--settings-box-row-indent);
}
+ .subsection > settings-toggle-button,
.subsection > .settings-box {
padding-left: 0;
padding-right: 0;
@@ -28,17 +29,19 @@
<!-- Subsection title only appears if both mouse and touchpad exist. -->
<h2 hidden$="[[!hasTouchpad]]">$i18n{mouseTitle}</h2>
<div class$="[[getSubsectionClass_(hasMouse, hasTouchpad)]]">
- <div class="settings-box first">
- <!-- Do not change the mouse button pref before the mouse is released.
- See crbug.com/686949 -->
- <settings-toggle-button id="mouseSwapButton" class="start"
- pref="{{prefs.settings.mouse.primary_right}}"
- label="$i18n{mouseSwapButtons}"
- on-settings-boolean-control-change="onMouseSwapButtonsChange_"
- on-down="onMouseSwapButtonsDown_" on-up="onMouseSwapButtonsUp_"
- no-set-pref>
- </settings-toggle-button>
- </div>
+ <!-- Do not change the mouse button pref before the mouse is released.
+ See crbug.com/686949 -->
+ <settings-toggle-button id="mouseSwapButton" class="first"
+ pref="{{prefs.settings.mouse.primary_right}}"
+ label="$i18n{mouseSwapButtons}"
+ on-settings-boolean-control-change="onMouseSwapButtonsChange_"
+ on-down="onMouseSwapButtonsDown_" on-up="onMouseSwapButtonsUp_"
+ no-set-pref>
+ </settings-toggle-button>
+ <settings-toggle-button id="mouseReverseScroll"
+ pref="{{prefs.settings.mouse.reverse_scroll}}"
+ label="$i18n{mouseReverseScroll}">
+ </settings-toggle-button>
<div class="settings-box">
<div class="start" id="mouseSpeedLabel">$i18n{mouseSpeed}</div>
<settings-slider pref="{{prefs.settings.mouse.sensitivity2}}"
@@ -54,18 +57,14 @@
<!-- Subsection title only appears if both mouse and touchpad exist. -->
<h2 hidden$="[[!hasMouse]]">$i18n{touchpadTitle}</h2>
<div class$="[[getSubsectionClass_(hasMouse, hasTouchpad)]]">
- <div class="settings-box first">
- <settings-toggle-button id="enableTapToClick" class="start"
- pref="{{prefs.settings.touchpad.enable_tap_to_click}}"
- label="$i18n{touchpadTapToClickEnabledLabel}">
- </settings-toggle-button>
- </div>
- <div class="settings-box">
- <settings-toggle-button id="enableTapDragging" class="start"
- pref="{{prefs.settings.touchpad.enable_tap_dragging}}"
- label="$i18n{tapDraggingLabel}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="enableTapToClick" class="first"
+ pref="{{prefs.settings.touchpad.enable_tap_to_click}}"
+ label="$i18n{touchpadTapToClickEnabledLabel}">
+ </settings-toggle-button>
+ <settings-toggle-button id="enableTapDragging"
+ pref="{{prefs.settings.touchpad.enable_tap_dragging}}"
+ label="$i18n{tapDraggingLabel}">
+ </settings-toggle-button>
<div class="settings-box">
<div class="start" id="touchpadSpeedLabel">$i18n{touchpadSpeed}</div>
<settings-slider id="touchpadSensitivity"
diff --git a/chromium/chrome/browser/resources/settings/device_page/power.html b/chromium/chrome/browser/resources/settings/device_page/power.html
index f0ee3e457ac..66fa7d291c9 100644
--- a/chromium/chrome/browser/resources/settings/device_page/power.html
+++ b/chromium/chrome/browser/resources/settings/device_page/power.html
@@ -12,7 +12,8 @@
<dom-module id="settings-power">
<template>
<style include="settings-shared md-select"></style>
- <div id="powerSourceRow" class="settings-box first two-line">
+ <div id="powerSourceRow" class="settings-box first two-line"
+ hidden$="[[!batteryStatus_.present]]">
<div class="start">
<div>[[powerSourceLabel_]]</div>
<div class="secondary">[[batteryStatus_.statusText]]</div>
@@ -38,7 +39,7 @@
</div>
</div>
- <div class="settings-box">
+ <div class$="settings-box [[getFirst_(batteryStatus_.present)]]">
<div class="start">$i18n{powerIdleLabel}</div>
<template is="dom-if" if="[[idleControlled_]]" restamp>
<cr-policy-indicator id="idleControlledIndicator"
@@ -58,14 +59,12 @@
</div>
</div>
- <div id="lidClosedRow" class="settings-box continuation"
- hidden$="[[!hasLid_]]">
- <settings-toggle-button class="start" id="lidClosedToggle"
- pref="[[lidClosedPref_]]" label="[[lidClosedLabel_]]"
- on-settings-boolean-control-change="onLidClosedToggleChange_"
- no-set-pref>
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="continuation" hidden$="[[!hasLid_]]"
+ id="lidClosedToggle"
+ pref="[[lidClosedPref_]]" label="[[lidClosedLabel_]]"
+ on-settings-boolean-control-change="onLidClosedToggleChange_"
+ no-set-pref>
+ </settings-toggle-button>
</template>
<script src="power.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/device_page/power.js b/chromium/chrome/browser/resources/settings/device_page/power.js
index 842ab2dcce7..c74a978bcb1 100644
--- a/chromium/chrome/browser/resources/settings/device_page/power.js
+++ b/chromium/chrome/browser/resources/settings/device_page/power.js
@@ -264,6 +264,15 @@ Polymer({
},
/**
+ * @param {boolean} batteryPresent if battery is present
+ * @return {string} 'first' if idle/lid settings are first visible div
+ * @private
+ */
+ getFirst_: function(batteryPresent) {
+ return !batteryPresent ? 'first' : '';
+ },
+
+ /**
* @param {*} lhs
* @param {*} rhs
* @return {boolean}
diff --git a/chromium/chrome/browser/resources/settings/device_page/storage.js b/chromium/chrome/browser/resources/settings/device_page/storage.js
index 0e592fc1b49..99a959df779 100644
--- a/chromium/chrome/browser/resources/settings/device_page/storage.js
+++ b/chromium/chrome/browser/resources/settings/device_page/storage.js
@@ -246,13 +246,13 @@ Polymer({
startPeriodicUpdate_: function() {
// We update the storage usage every 5 seconds.
if (this.updateTimerId_ == -1) {
- this.updateTimerId_ = window.setInterval(function() {
+ this.updateTimerId_ = window.setInterval(() => {
if (settings.getCurrentRoute() != settings.routes.STORAGE) {
this.stopPeriodicUpdate_();
return;
}
chrome.send('updateStorageInfo');
- }.bind(this), 5000);
+ }, 5000);
}
},
diff --git a/chromium/chrome/browser/resources/settings/device_page/stylus.html b/chromium/chrome/browser/resources/settings/device_page/stylus.html
index b0ace6ae19c..4c50c21298c 100644
--- a/chromium/chrome/browser/resources/settings/device_page/stylus.html
+++ b/chromium/chrome/browser/resources/settings/device_page/stylus.html
@@ -15,10 +15,6 @@
margin-top: 0;
}
- settings-toggle-button {
- width: 100%;
- }
-
paper-spinner {
margin-left: 12px;
@apply(--cr-icon-height-width);
@@ -33,21 +29,17 @@
}
</style>
- <div class="settings-box continuation">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.enable_stylus_tools}}"
- label="$i18n{stylusEnableStylusTools}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.enable_stylus_tools}}"
+ label="$i18n{stylusEnableStylusTools}">
+ </settings-toggle-button>
<template is="dom-if" if="[[hasInternalStylus_]]">
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.launch_palette_on_eject_event}}"
- label="$i18n{stylusAutoOpenStylusTools}"
- disabled="[[!prefs.settings.enable_stylus_tools.value]]">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.settings.launch_palette_on_eject_event}}"
+ label="$i18n{stylusAutoOpenStylusTools}"
+ disabled="[[!prefs.settings.enable_stylus_tools.value]]">
+ </settings-toggle-button>
</template>
<div class="settings-box">
@@ -120,12 +112,10 @@
</div>
<template is="dom-if" if="[[lockScreenSupportEnabled_(selectedApp_)]]">
- <div class="settings-box">
- <settings-toggle-button id="keep-last-note-on-lock-screen-toggle"
- pref="{{prefs.settings.restore_last_lock_screen_note}}"
- label="$i18n{stylusNoteTakingAppKeepsLastNoteOnLockScreen}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="keep-last-note-on-lock-screen-toggle"
+ pref="{{prefs.settings.restore_last_lock_screen_note}}"
+ label="$i18n{stylusNoteTakingAppKeepsLastNoteOnLockScreen}">
+ </settings-toggle-button>
</template>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html b/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html
index 7132c9e0d09..2f213e62e6a 100644
--- a/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html
+++ b/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html
@@ -34,19 +34,17 @@
end-justified>
</controlled-button>
</div>
- <div class="settings-box block">
- <settings-toggle-button
- pref="{{prefs.download.prompt_for_download}}"
- label="$i18n{promptForDownload}">
- </settings-toggle-button>
+ <settings-toggle-button
+ pref="{{prefs.download.prompt_for_download}}"
+ label="$i18n{promptForDownload}">
+ </settings-toggle-button>
<if expr="chromeos">
- <settings-toggle-button
- pref="{{prefs.gdata.disabled}}"
- label="$i18n{disconnectGoogleDriveAccount}"
- hidden="[[!pageVisibility.googleDrive]]">
- </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.gdata.disabled}}"
+ label="$i18n{disconnectGoogleDriveAccount}"
+ hidden="[[!pageVisibility.googleDrive]]">
+ </settings-toggle-button>
</if>
- </div>
<template is="dom-if" if="[[autoOpenDownloads_]]" restamp>
<div class="settings-box">
<div class="start">
diff --git a/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.js b/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.js
index 76bb8d7108f..fcc2039113c 100644
--- a/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.js
+++ b/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.js
@@ -49,18 +49,18 @@ Polymer({
attached: function() {
this.browserProxy_ = settings.DownloadsBrowserProxyImpl.getInstance();
- this.addWebUIListener('auto-open-downloads-changed', function(autoOpen) {
+ this.addWebUIListener('auto-open-downloads-changed', autoOpen => {
this.autoOpenDownloads_ = autoOpen;
- }.bind(this));
+ });
this.browserProxy_.initializeDownloads();
},
/** @private */
selectDownloadLocation_: function() {
- listenOnce(this, 'transitionend', function() {
+ listenOnce(this, 'transitionend', () => {
this.browserProxy_.selectDownloadLocation();
- }.bind(this));
+ });
},
// <if expr="chromeos">
diff --git a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html
index fec7261d939..b96f029582e 100644
--- a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html
+++ b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html
@@ -1,34 +1,35 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
<link rel="import" href="google_assistant_browser_proxy.html">
+<link rel="import" href="../controls/settings_toggle_button.html">
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="../prefs/prefs.html">
<link rel="import" href="../prefs/prefs_behavior.html">
<link rel="import" href="../settings_shared_css.html">
<dom-module id="settings-google-assistant-page">
<template>
<style include="settings-shared"></style>
- <div class="settings-box first">
- <settings-toggle-button id="googleAssistantEnable"
- class="start primary-toggle"
- pref="{{prefs.settings.voice_interaction.enabled}}"
- label="[[getAssistantOnOffLabel_(
- prefs.settings.voice_interaction.enabled.value)]]"
- on-change="onGoogleAssistantEnableChange_">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="googleAssistantEnable"
+ class="first primary-toggle"
+ pref="{{prefs.settings.voice_interaction.enabled}}"
+ label="[[getAssistantOnOffLabel_(
+ prefs.settings.voice_interaction.enabled.value)]]"
+ on-change="onGoogleAssistantEnableChange_">
+ </settings-toggle-button>
<template is="dom-if"
- if="{{prefs.settings.voice_interaction.enabled.value}}">
- <div class="settings-box continuation indented">
- <settings-toggle-button id="googleAssistantContextEnable" class="start"
- pref="{{prefs.settings.voice_interaction.context.enabled}}"
- label="$i18n{googleAssistantEnableContext}"
- sub-label="$i18n{googleAssistantEnableContextDescription}"
- on-change="onGoogleAssistantContextEnableChange_">
- </settings-toggle-button>
- </div>
- <div class="settings-box"
+ if="[[prefs.settings.voice_interaction.enabled.value]]">
+ <settings-toggle-button id="googleAssistantContextEnable"
+ class="continuation indented"
+ pref="{{prefs.settings.voice_interaction.context.enabled}}"
+ label="$i18n{googleAssistantEnableContext}"
+ sub-label="$i18n{googleAssistantEnableContextDescription}"
+ on-change="onGoogleAssistantContextEnableChange_">
+ </settings-toggle-button>
+ <div id="googleAssistantSettings" class="settings-box"
on-tap="onGoogleAssistantSettingsTapped_" actionable>
<div class="start">
$i18n{googleAssistantSettings}
diff --git a/chromium/chrome/browser/resources/settings/i18n_setup.html b/chromium/chrome/browser/resources/settings/i18n_setup.html
index 1f7a929deeb..19b135b4d0c 100644
--- a/chromium/chrome/browser/resources/settings/i18n_setup.html
+++ b/chromium/chrome/browser/resources/settings/i18n_setup.html
@@ -1,2 +1,2 @@
<script src="chrome://resources/js/load_time_data.js"></script>
-<script src="/strings.js"></script>
+<script src="strings.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/images/settings_icon_arrow_back.svg b/chromium/chrome/browser/resources/settings/images/settings_icon_arrow_back.svg
deleted file mode 100644
index 838eb43618d..00000000000
--- a/chromium/chrome/browser/resources/settings/images/settings_icon_arrow_back.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#757575" preserveAspectRatio="xMidYMid meet"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"></path></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp
index 06972b358cf..8cbb7f9805e 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp
@@ -71,13 +71,6 @@
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
- 'target_name': 'network_apnlist',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
'target_name': 'network_config_input',
'dependencies': [],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
@@ -91,37 +84,13 @@
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
- 'target_name': 'network_ip_config',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'network_nameservers',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'network_property_list',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
- '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_network_behavior',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
- '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'network_proxy',
+ 'target_name': 'network_proxy_section',
'dependencies': [
'../compiled_resources2.gyp:route',
'../controls/compiled_resources2.gyp:settings_checkbox',
'../prefs/compiled_resources2.gyp:prefs_behavior',
+ '<(DEPTH)/ui/webui/resources/cr_components/chromeos/network/compiled_resources2.gyp:network_proxy',
'<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
- '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_network_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_without_ink',
@@ -129,17 +98,6 @@
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
- 'target_name': 'network_proxy_input',
- 'dependencies': [
- '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types',
- ],
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
- 'target_name': 'network_proxy_exclusions',
- 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
- },
- {
'target_name': 'network_siminfo',
'dependencies': [
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-input/compiled_resources2.gyp:paper-input-extracted',
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_config.html b/chromium/chrome/browser/resources/settings/internet_page/internet_config.html
index 92d222ed9fc..6c2a1f2fdd1 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_config.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_config.html
@@ -1,7 +1,8 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html">
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html
index 9bc0a37dbfd..1caee855099 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html
@@ -1,5 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_apnlist.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_ip_config.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_nameservers.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_property_list.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
@@ -17,11 +21,7 @@
<link rel="import" href="../prefs/prefs.html">
<link rel="import" href="../route.html">
<link rel="import" href="internet_shared_css.html">
-<link rel="import" href="network_apnlist.html">
-<link rel="import" href="network_ip_config.html">
-<link rel="import" href="network_nameservers.html">
-<link rel="import" href="network_property_list.html">
-<link rel="import" href="network_proxy.html">
+<link rel="import" href="network_proxy_section.html">
<link rel="import" href="network_siminfo.html">
<link rel="import" href="tether_connection_dialog.html">
@@ -58,7 +58,7 @@
}
</style>
<!-- Title section: Icon + name + connection state. -->
- <div class="settings-box first">
+ <div id="titleDiv" class="settings-box first">
<div class="start layout horizontal center">
<cr-network-icon network-state="[[networkProperties]]">
</cr-network-icon>
@@ -169,12 +169,10 @@
</template>
<!-- Data roaming (Cellular only). -->
<template is="dom-if" if="[[isCellular_(networkProperties)]]">
- <div class="settings-box">
- <settings-toggle-button id="allowDataRoaming" class="start"
- pref="{{prefs.cros.signed.data_roaming_enabled}}"
- label="$i18n{networkAllowDataRoaming}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="allowDataRoaming"
+ pref="{{prefs.cros.signed.data_roaming_enabled}}"
+ label="$i18n{networkAllowDataRoaming}">
+ </settings-toggle-button>
</template>
<!-- SIM Info (Cellular only). -->
<template is="dom-if" if="[[showCellularSim_(networkProperties)]]">
@@ -187,10 +185,11 @@
</div>
</template>
<!-- IP Address. -->
- <template is="dom-if" if="[[IPAddress_]]">
+ <template is="dom-if"
+ if="[[showIpAddress_(ipAddress_, networkProperties)]]">
<div class="settings-box two-line single-column stretch">
<div>$i18n{networkIPAddress}</div>
- <div class="secondary">[[IPAddress_]]</div>
+ <div class="secondary">[[ipAddress_]]</div>
</div>
</template>
<!-- Properties to always show if present. -->
@@ -244,7 +243,7 @@
</div>
<iron-collapse opened="[[networkExpanded_]]">
- <div class="settings-box single-column stretch">
+ <div class="settings-box single-column stretch indented">
<!-- APN -->
<template is="dom-if" if="[[isCellular_(networkProperties)]]">
<network-apnlist editable on-apn-change="onNetworkPropertyChange_"
@@ -275,12 +274,10 @@
</div>
<iron-collapse opened="[[proxyExpanded_]]">
- <div class="settings-box single-column stretch">
- <network-proxy editable prefs="{{prefs}}"
- on-proxy-change="onProxyChange_"
- network-properties="[[networkProperties]]">
- </network-proxy>
- </div>
+ <network-proxy-section prefs="{{prefs}}"
+ on-proxy-change="onProxyChange_"
+ network-properties="[[networkProperties]]">
+ </network-proxy-section>
</iron-collapse>
</template>
</template>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js
index 84dfabc12ef..598a2369ff2 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js
@@ -105,7 +105,7 @@ Polymer({
* The network IP Address.
* @private
*/
- IPAddress_: {
+ ipAddress_: {
type: String,
value: '',
},
@@ -219,19 +219,19 @@ Polymer({
// Set the IPAddress property to the IPV4 Address.
var ipv4 =
CrOnc.getIPConfigForType(this.networkProperties, CrOnc.IPType.IPV4);
- this.IPAddress_ = (ipv4 && ipv4.IPAddress) || '';
+ this.ipAddress_ = (ipv4 && ipv4.IPAddress) || '';
// Update the detail page title.
this.parentNode.pageTitle = CrOnc.getNetworkName(this.networkProperties);
Polymer.dom.flush();
- if (this.didSetFocus_) {
+ if (!this.didSetFocus_) {
// Focus a button once the initial state is set.
this.didSetFocus_ = true;
- var button = this.$$('#buttonDiv .primary-button:not([hidden])');
+ var button = this.$$('#titleDiv .primary-button:not([hidden])');
if (!button)
- button = this.$$('#buttonDiv .secondary-button:not([hidden])');
+ button = this.$$('#titleDiv paper-button:not([hidden])');
assert(button); // At least one button will always be visible.
button.focus();
}
@@ -346,13 +346,13 @@ Polymer({
return;
assert(!!this.guid);
- this.networkingPrivate.setProperties(this.guid, onc, function() {
+ this.networkingPrivate.setProperties(this.guid, onc, () => {
if (chrome.runtime.lastError) {
// An error typically indicates invalid input; request the properties
// to update any invalid fields.
this.getNetworkDetails_();
}
- }.bind(this));
+ });
},
/**
@@ -1023,6 +1023,16 @@ Polymer({
},
/**
+ * @param {string} ipAddress
+ * @param {!CrOnc.NetworkProperties} networkProperties
+ * @return {boolean}
+ * @private
+ */
+ showIpAddress_: function(ipAddress, networkProperties) {
+ return !!ipAddress && this.isConnectedState_(networkProperties);
+ },
+
+ /**
* @param {!Object} curValue
* @param {!Object} newValue
* @return {boolean} True if all properties set in |newValue| are equal to
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html
index 5a555b14dc8..6d2f1357614 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html
@@ -76,15 +76,15 @@
</div>
<dialog id="dotsMenu" is="cr-action-menu">
- <button class="dropdown-item" role="option"
- hidden="[[!showAddPreferred_]]" on-tap="onAddPreferredTap_">
+ <button class="dropdown-item" hidden="[[!showAddPreferred_]]"
+ on-tap="onAddPreferredTap_">
$i18n{knownNetworksMenuAddPreferred}
</button>
- <button class="dropdown-item" role="option"
- hidden="[[!showRemovePreferred_]]" on-tap="onRemovePreferredTap_">
+ <button class="dropdown-item" hidden="[[!showRemovePreferred_]]"
+ on-tap="onRemovePreferredTap_">
$i18n{knownNetworksMenuRemovePreferred}
</button>
- <button class="dropdown-item" role="option" disabled="[[!enableForget_]]"
+ <button class="dropdown-item" disabled="[[!enableForget_]]"
on-tap="onForgetTap_">
$i18n{knownNetworksMenuForget}
</button>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js
index 30e4aadfb85..5ec39d7469b 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js
@@ -104,9 +104,9 @@ Polymer({
visible: false,
configured: true
};
- this.networkingPrivate.getNetworks(filter, function(states) {
+ this.networkingPrivate.getNetworks(filter, states => {
this.networkStateList_ = states;
- }.bind(this));
+ });
},
/**
@@ -133,9 +133,8 @@ Polymer({
* @private
*/
havePreferred_: function() {
- return this.networkStateList_.find(function(state) {
- return this.networkIsPreferred_(state);
- }.bind(this)) !== undefined;
+ return this.networkStateList_.find(
+ state => this.networkIsPreferred_(state)) !== undefined;
},
/**
@@ -143,9 +142,8 @@ Polymer({
* @private
*/
haveNotPreferred_: function() {
- return this.networkStateList_.find(function(state) {
- return this.networkIsNotPreferred_(state);
- }.bind(this)) !== undefined;
+ return this.networkStateList_.find(
+ state => this.networkIsNotPreferred_(state)) !== undefined;
},
/**
@@ -161,7 +159,7 @@ Polymer({
// properties for the network. The delay is not noticeable (~5ms) and is
// preferable to initiating a query for every known network at load time.
this.networkingPrivate.getManagedProperties(
- this.selectedGuid_, function(properties) {
+ this.selectedGuid_, properties => {
if (chrome.runtime.lastError || !properties) {
console.error(
'Unexpected error: ' + chrome.runtime.lastError.message);
@@ -177,7 +175,7 @@ Polymer({
}
this.enableForget_ = !this.isPolicySource(properties.Source);
/** @type {!CrActionMenuElement} */ (this.$.dotsMenu).showAt(button);
- }.bind(this));
+ });
event.stopPropagation();
},
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_page.js
index 529d9c31adb..50000efea86 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_page.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_page.js
@@ -139,9 +139,9 @@ Polymer({
chrome.management.getAll(this.onGetAllExtensions_.bind(this));
- this.networkingPrivate.getGlobalPolicy(function(policy) {
+ this.networkingPrivate.getGlobalPolicy(policy => {
this.globalPolicy_ = policy;
- }.bind(this));
+ });
},
/** @override */
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_shared_css.html b/chromium/chrome/browser/resources/settings/internet_page/internet_shared_css.html
index 83858c7c304..8a9fbd27179 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_shared_css.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_shared_css.html
@@ -22,11 +22,11 @@
margin-top: -9px;
}
- .settings-box.indented {
+ .indented {
-webkit-margin-start: var(--settings-box-row-padding);
}
- .settings-box.stretch {
+ .stretch {
align-items: stretch;
}
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html
index 4316d2080aa..3d0116aba06 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html
@@ -29,7 +29,7 @@
}
#onOff[on] {
- color: var(--settings-toggle-color);
+ color: var(--cr-toggle-color);
}
.vpn-header {
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js
index 24a5887f26e..92870ea7316 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js
@@ -182,9 +182,9 @@ Polymer({
return;
/** @const */ var INTERVAL_MS = 10 * 1000;
this.networkingPrivate.requestNetworkScan();
- this.scanIntervalId_ = window.setInterval(function() {
+ this.scanIntervalId_ = window.setInterval(() => {
this.networkingPrivate.requestNetworkScan();
- }.bind(this), INTERVAL_MS);
+ }, INTERVAL_MS);
},
/** @private */
@@ -231,9 +231,9 @@ Polymer({
visible: true,
configured: false
};
- this.networkingPrivate.getNetworks(filter, function(tetherNetworkStates) {
+ this.networkingPrivate.getNetworks(filter, tetherNetworkStates => {
this.networkStateList_ = networkStates.concat(tetherNetworkStates);
- }.bind(this));
+ });
return;
}
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_apnlist.html b/chromium/chrome/browser/resources/settings/internet_page/network_apnlist.html
deleted file mode 100644
index 2f72355c93f..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_apnlist.html
+++ /dev/null
@@ -1,43 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="../settings_vars_css.html">
-<link rel="import" href="internet_shared_css.html">
-<link rel="import" href="network_property_list.html">
-
-<dom-module id="network-apnlist">
- <template>
- <style include="internet-shared md-select">
- paper-button {
- margin: 4px 0 20px;
- }
- </style>
- <div class="settings-box first">
- <div class="start">$i18n{networkSectionAccessPoint}</div>
- <div class="md-select-wrapper">
- <select id="selectApn" class="md-select" on-change="onSelectApnChange_"
- value="[[selectedApn_]]"
- aria-label="$i18n{networkSectionAccessPoint}">
- <template is="dom-repeat" items="[[apnSelectList_]]">
- <option value="[[item.AccessPointName]]">[[apnDesc_(item)]]</option>
- </template>
- </select>
- <span class="md-select-underline"></span>
- </div>
- </div>
-
- <div class="settings-box continuation single-column"
- hidden$="[[!isOtherSelected_(selectedApn_, networkProperties)]]">
- <network-property-list on-property-change="onOtherApnChange_"
- fields="[[otherApnFields_]]" property-dict="[[otherApn_]]"
- edit-field-types="[[otherApnEditTypes_]]" prefix="Cellular.APN.">
- </network-property-list>
- <paper-button class="action-button" on-tap="onSaveOtherTap_">
- $i18n{save}
- </paper-button>
- </div>
- </template>
- <script src="network_apnlist.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_apnlist.js b/chromium/chrome/browser/resources/settings/internet_page/network_apnlist.js
deleted file mode 100644
index b81f6cecccf..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_apnlist.js
+++ /dev/null
@@ -1,269 +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.
-
-/**
- * @fileoverview Polymer element for displaying and modifying a list of cellular
- * access points.
- */
-Polymer({
- is: 'network-apnlist',
-
- properties: {
- /**
- * The current set of properties for the network matching |guid|.
- * @type {!CrOnc.NetworkProperties|undefined}
- */
- networkProperties: {
- type: Object,
- observer: 'networkPropertiesChanged_',
- },
-
- /**
- * The CrOnc.APNProperties.AccessPointName value of the selected APN.
- * @private
- */
- selectedApn_: {
- type: String,
- value: '',
- },
-
- /**
- * Selectable list of APN dictionaries for the UI. Includes an entry
- * corresponding to |otherApn| (see below).
- * @private {!Array<!CrOnc.APNProperties>}
- */
- apnSelectList_: {
- type: Array,
- value: function() {
- return [];
- }
- },
-
- /**
- * The user settable properties for a new ('other') APN. The values for
- * AccessPointName, Username, and Password will be set to the currently
- * active APN if it does not match an existing list entry.
- * @private {CrOnc.APNProperties|undefined}
- */
- otherApn_: {
- type: Object,
- },
-
- /**
- * Array of property names to pass to the Other APN property list.
- * @private {!Array<string>}
- */
- otherApnFields_: {
- type: Array,
- value: function() {
- return ['AccessPointName', 'Username', 'Password'];
- },
- readOnly: true
- },
-
- /**
- * Array of edit types to pass to the Other APN property list.
- * @private
- */
- otherApnEditTypes_: {
- type: Object,
- value: function() {
- return {
- 'AccessPointName': 'String',
- 'Username': 'String',
- 'Password': 'Password'
- };
- },
- readOnly: true
- },
- },
-
- /** @const */
- DefaultAccessPointName: 'none',
-
- /**
- * Polymer networkProperties changed method.
- */
- networkPropertiesChanged_: function() {
- if (!this.networkProperties || !this.networkProperties.Cellular)
- return;
-
- /** @type {!CrOnc.APNProperties|undefined} */ var activeApn;
- var cellular = this.networkProperties.Cellular;
- /** @type {!chrome.networkingPrivate.ManagedAPNProperties|undefined} */ var
- apn = cellular.APN;
- if (apn && apn.AccessPointName) {
- activeApn = /** @type {!CrOnc.APNProperties|undefined} */ (
- CrOnc.getSimpleActiveProperties(apn));
- } else if (cellular.LastGoodAPN && cellular.LastGoodAPN.AccessPointName) {
- activeApn = cellular.LastGoodAPN;
- }
- this.setApnSelectList_(activeApn);
- },
-
- /**
- * Sets the list of selectable APNs for the UI. Appends an 'Other' entry
- * (see comments for |otherApn_| above).
- * @param {CrOnc.APNProperties|undefined} activeApn The currently active APN
- * properties.
- * @private
- */
- setApnSelectList_: function(activeApn) {
- // Copy the list of APNs from this.networkProperties.
- var result = this.getApnList_().slice();
-
- // Test whether |activeApn| is in the current APN list in networkProperties.
- var activeApnInList = activeApn && result.some(function(a) {
- return a.AccessPointName == activeApn.AccessPointName;
- });
-
- // If |activeApn| is specified and not in the list, use the active
- // properties for 'other'. Otherwise use any existing 'other' properties.
- var otherApnProperties =
- (activeApn && !activeApnInList) ? activeApn : this.otherApn_;
- var otherApn = this.createApnObject_(otherApnProperties);
-
- // Always use 'Other' for the name of custom APN entries (the name does
- // not get saved).
- otherApn.Name = 'Other';
-
- // If no 'active' or 'other' AccessPointName was provided, use the default.
- otherApn.AccessPointName =
- otherApn.AccessPointName || this.DefaultAccessPointName;
-
- // Save the 'other' properties.
- this.otherApn_ = otherApn;
-
- // Append 'other' to the end of the list of APNs.
- result.push(otherApn);
-
- this.apnSelectList_ = result;
- // Set selectedApn_ after dom-repeat has been stamped.
- this.async(function() {
- this.selectedApn_ =
- (activeApn && activeApn.AccessPointName) || otherApn.AccessPointName;
- }.bind(this));
- },
-
- /**
- * @param {!CrOnc.APNProperties|undefined=} apnProperties
- * @return {!CrOnc.APNProperties} A new APN object with properties from
- * |apnProperties| if provided.
- * @private
- */
- createApnObject_: function(apnProperties) {
- var newApn = {AccessPointName: ''};
- if (apnProperties)
- Object.assign(newApn, apnProperties);
- return newApn;
- },
-
- /**
- * @return {!Array<!CrOnc.APNProperties>} The list of APN properties in
- * |networkProperties| or an empty list if the property is not set.
- * @private
- */
- getApnList_: function() {
- if (!this.networkProperties || !this.networkProperties.Cellular)
- return [];
- /** @type {!chrome.networkingPrivate.ManagedAPNList|undefined} */ var
- apnlist = this.networkProperties.Cellular.APNList;
- if (!apnlist)
- return [];
- return /** @type {!Array<!CrOnc.APNProperties>} */ (
- CrOnc.getActiveValue(apnlist));
- },
-
- /**
- * Event triggered when the selectApn selection changes.
- * @param {!Event} event
- * @private
- */
- onSelectApnChange_: function(event) {
- var target = /** @type {!HTMLSelectElement} */ (event.target);
- var accessPointName = target.value;
- // When selecting 'Other', don't set a change event unless a valid
- // non-default value has been set for Other.
- if (this.isOtherSelected_(accessPointName) &&
- (!this.otherApn_ || !this.otherApn_.AccessPointName ||
- this.otherApn_.AccessPointName == this.DefaultAccessPointName)) {
- this.selectedApn_ = accessPointName;
- return;
- }
- this.sendApnChange_(accessPointName);
- },
-
- /**
- * Event triggered when any 'Other' APN network property changes.
- * @param {!{detail: {field: string, value: string}}} event
- * @private
- */
- onOtherApnChange_: function(event) {
- this.set('otherApn_.' + event.detail.field, event.detail.value);
- // Don't send a change event for 'Other' until the 'Save' button is tapped.
- },
-
- /**
- * Event triggered when the Other APN 'Save' button is tapped.
- * @param {!Event} event
- * @private
- */
- onSaveOtherTap_: function(event) {
- this.sendApnChange_(this.selectedApn_);
- },
-
- /**
- * Send the apn-change event.
- * @param {string} accessPointName
- * @private
- */
- sendApnChange_: function(accessPointName) {
- var apnList = this.getApnList_();
- var apn = this.findApnInList(apnList, accessPointName);
- if (apn == undefined) {
- apn = this.createApnObject_();
- if (this.otherApn_) {
- apn.AccessPointName = this.otherApn_.AccessPointName;
- apn.Username = this.otherApn_.Username;
- apn.Password = this.otherApn_.Password;
- }
- }
- this.fire('apn-change', {field: 'APN', value: apn});
- },
-
- /**
- * @param {string} accessPointName
- * @return {boolean} True if the 'other' APN is currently selected.
- * @private
- */
- isOtherSelected_: function(accessPointName) {
- if (!this.networkProperties || !this.networkProperties.Cellular)
- return false;
- var apnList = this.getApnList_();
- var apn = this.findApnInList(apnList, accessPointName);
- return apn == undefined;
- },
-
- /**
- * @param {!CrOnc.APNProperties} apn
- * @return {string} The most descriptive name for the access point.
- * @private
- */
- apnDesc_: function(apn) {
- return apn.LocalizedName || apn.Name || apn.AccessPointName;
- },
-
- /**
- * @param {!Array<!CrOnc.APNProperties>} apnList
- * @param {string} accessPointName
- * @return {CrOnc.APNProperties|undefined} The entry in |apnList| matching
- * |accessPointName| if it exists, or undefined.
- * @private
- */
- findApnInList: function(apnList, accessPointName) {
- return apnList.find(function(a) {
- return a.AccessPointName == accessPointName;
- });
- }
-});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_ip_config.html b/chromium/chrome/browser/resources/settings/internet_page/network_ip_config.html
deleted file mode 100644
index f8fb2f9b70f..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_ip_config.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html">
-<link rel="import" href="internet_shared_css.html">
-<link rel="import" href="network_property_list.html">
-
-<dom-module id="network-ip-config">
- <template>
- <style include="internet-shared"></style>
- <div class="settings-box first">
- <div id="autoIPConfigLabel" class="start">$i18n{networkIPConfigAuto}</div>
- <paper-toggle-button checked="{{automatic_}}" disabled="[[!editable]]"
- aria-labelledby="autoIPConfigLabel">
- </paper-toggle-button>
- </div>
- <div class="settings-box single-column continuation indented stretch"
- hidden$="[[!ipConfig_]]">
- <network-property-list
- fields="[[ipConfigFields_]]" property-dict="[[ipConfig_]]"
- edit-field-types="[[getIPEditFields_(editable, automatic_)]]"
- on-property-change="onIPChange_">
- </network-property-list>
- </div>
- </template>
- <script src="network_ip_config.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_ip_config.js b/chromium/chrome/browser/resources/settings/internet_page/network_ip_config.js
deleted file mode 100644
index d8143ddbfa0..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_ip_config.js
+++ /dev/null
@@ -1,212 +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.
-
-/**
- * @fileoverview Polymer element for displaying the IP Config properties for
- * a network state. TODO(stevenjb): Allow editing of static IP configurations
- * when 'editable' is true.
- */
-Polymer({
- is: 'network-ip-config',
-
- properties: {
- /**
- * The network properties dictionary containing the IP Config properties to
- * display and modify.
- * @type {!CrOnc.NetworkProperties|undefined}
- */
- networkProperties: {
- type: Object,
- observer: 'networkPropertiesChanged_',
- },
-
- /**
- * Whether or not the IP Address can be edited.
- */
- editable: {
- type: Boolean,
- value: false,
- },
-
- /**
- * State of 'Configure IP Addresses Automatically'.
- * @private
- */
- automatic_: {
- type: Boolean,
- value: true,
- observer: 'automaticChanged_',
- },
-
- /**
- * The currently visible IP Config property dictionary. The 'RoutingPrefix'
- * property is a human-readable mask instead of a prefix length.
- * @private {?{
- * ipv4: !CrOnc.IPConfigUIProperties,
- * ipv6: (!CrOnc.IPConfigUIProperties|undefined)
- * }}
- */
- ipConfig_: {
- type: Object,
- value: null,
- },
-
- /**
- * Array of properties to pass to the property list.
- * @private {!Array<string>}
- */
- ipConfigFields_: {
- type: Array,
- value: function() {
- return [
- 'ipv4.IPAddress',
- 'ipv4.RoutingPrefix',
- 'ipv4.Gateway',
- 'ipv6.IPAddress',
- ];
- },
- readOnly: true
- },
- },
-
- /**
- * Saved static IP configuration properties when switching to 'automatic'.
- * @private {!CrOnc.IPConfigUIProperties|undefined}
- */
- savedStaticIp_: undefined,
-
- /**
- * Polymer networkProperties changed method.
- */
- networkPropertiesChanged_: function(newValue, oldValue) {
- if (!this.networkProperties)
- return;
-
- if (newValue.GUID != (oldValue && oldValue.GUID))
- this.savedStaticIp_ = undefined;
-
- // Update the 'automatic' property.
- if (this.networkProperties.IPAddressConfigType) {
- var ipConfigType =
- CrOnc.getActiveValue(this.networkProperties.IPAddressConfigType);
- this.automatic_ = (ipConfigType != CrOnc.IPConfigType.STATIC);
- }
-
- if (this.networkProperties.IPConfigs) {
- // Update the 'ipConfig' property.
- var ipv4 =
- CrOnc.getIPConfigForType(this.networkProperties, CrOnc.IPType.IPV4);
- var ipv6 =
- CrOnc.getIPConfigForType(this.networkProperties, CrOnc.IPType.IPV6);
- this.ipConfig_ = {
- ipv4: this.getIPConfigUIProperties_(ipv4),
- ipv6: this.getIPConfigUIProperties_(ipv6)
- };
- }
- },
-
- /** @private */
- automaticChanged_: function() {
- if (!this.automatic_) {
- // Ensure that there is a valid IPConfig object.
- this.ipConfig_ = this.ipConfig_ || {
- ipv4: {
- Gateway: '192.168.1.1',
- IPAddress: '192.168.1.1',
- RoutingPrefix: '255.255.255.0',
- Type: CrOnc.IPType.IPV4,
- },
- };
- this.sendStaticIpConfig_();
- return;
- }
-
- // Save the static IP configuration when switching to automatic.
- if (this.ipConfig_)
- this.savedStaticIp_ = this.ipConfig_.ipv4;
- // Send the change.
- this.fire('ip-change', {
- field: 'IPAddressConfigType',
- value: CrOnc.IPConfigType.DHCP,
- });
- },
-
- /**
- * @param {!CrOnc.IPConfigProperties|undefined} ipconfig
- * @return {!CrOnc.IPConfigUIProperties} A new IPConfigUIProperties object
- * with RoutingPrefix expressed as a string mask instead of a prefix
- * length. Returns an empty object if |ipconfig| is undefined.
- * @private
- */
- getIPConfigUIProperties_: function(ipconfig) {
- var result = {};
- if (!ipconfig)
- return result;
- for (var key in ipconfig) {
- var value = ipconfig[key];
- if (key == 'RoutingPrefix')
- result.RoutingPrefix = CrOnc.getRoutingPrefixAsNetmask(value);
- else
- result[key] = value;
- }
- return result;
- },
-
- /**
- * @param {!CrOnc.IPConfigUIProperties} ipconfig The IP Config UI properties.
- * @return {!CrOnc.IPConfigProperties} A new IPConfigProperties object with
- * RoutingPrefix expressed as a a prefix length.
- * @private
- */
- getIPConfigProperties_: function(ipconfig) {
- var result = {};
- for (var key in ipconfig) {
- var value = ipconfig[key];
- if (key == 'RoutingPrefix')
- result.RoutingPrefix = CrOnc.getRoutingPrefixAsLength(value);
- else
- result[key] = value;
- }
- return result;
- },
-
- /**
- * @return {Object} An object with the edit type for each editable field.
- * @private
- */
- getIPEditFields_: function() {
- if (!this.editable || this.automatic_)
- return {};
- return {
- 'ipv4.IPAddress': 'String',
- 'ipv4.RoutingPrefix': 'String',
- 'ipv4.Gateway': 'String'
- };
- },
-
- /**
- * Event triggered when the network property list changes.
- * @param {!{detail: {field: string, value: string}}} event The
- * network-property-list change event.
- * @private
- */
- onIPChange_: function(event) {
- if (!this.ipConfig_)
- return;
- var field = event.detail.field;
- var value = event.detail.value;
- // Note: |field| includes the 'ipv4.' prefix.
- this.set('ipConfig_.' + field, value);
- this.sendStaticIpConfig_();
- },
-
- /** @private */
- sendStaticIpConfig_: function() {
- // This will also set IPAddressConfigType to STATIC.
- this.fire('ip-change', {
- field: 'StaticIPConfig',
- value: this.getIPConfigProperties_(this.ipConfig_.ipv4)
- });
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_nameservers.html b/chromium/chrome/browser/resources/settings/internet_page/network_nameservers.html
deleted file mode 100644
index a26ed366d45..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_nameservers.html
+++ /dev/null
@@ -1,43 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input-container.html">
-<link rel="import" href="../settings_vars_css.html">
-<link rel="import" href="internet_shared_css.html">
-
-<dom-module id="network-nameservers">
- <template>
- <style include="internet-shared md-select">
- paper-input-container {
- -webkit-padding-start: 4px;
- }
- </style>
-
- <div class="settings-box first">
- <div class="start">$i18n{networkSectionNameservers}</div>
- <div class="md-select-wrapper">
- <select id="nameserverType" class="md-select" on-change="onTypeChange_"
- value="[[nameserversType_]]"
- aria-label="$i18n{networkSectionNameservers}">
- <template is="dom-repeat" items="[[nameserverTypeNames_]]">
- <option value="[[item]]">[[nameserverTypeDesc_(item)]]</option>
- </template>
- </select>
- <span class="md-select-underline"></span>
- </div>
- </div>
-
- <div class="settings-box continuation single-column indented"
- hidden$="[[!nameservers_.length]]">
- <template is="dom-repeat" items="[[nameservers_]]">
- <paper-input-container no-label-float>
- <input id="nameserver[[index]]" is="iron-input" value="[[item]]"
- disabled="[[!canEdit_(editable, nameserversType_)]]"
- on-change="onValueChange_">
- </paper-input-container>
- </template>
- </div>
- </template>
- <script src="network_nameservers.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_nameservers.js b/chromium/chrome/browser/resources/settings/internet_page/network_nameservers.js
deleted file mode 100644
index 1429517cf9f..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_nameservers.js
+++ /dev/null
@@ -1,212 +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.
-
-/**
- * @fileoverview Polymer element for displaying network nameserver options.
- */
-Polymer({
- is: 'network-nameservers',
-
- properties: {
- /**
- * The network properties dictionary containing the nameserver properties to
- * display and modify.
- * @type {!CrOnc.NetworkProperties|undefined}
- */
- networkProperties: {
- type: Object,
- observer: 'networkPropertiesChanged_',
- },
-
- /** Whether or not the nameservers can be edited. */
- editable: {
- type: Boolean,
- value: false,
- },
-
- /**
- * Array of nameserver addresses stored as strings.
- * @private {!Array<string>}
- */
- nameservers_: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /**
- * The selected nameserver type.
- * @private
- */
- nameserversType_: {
- type: String,
- value: 'automatic',
- },
-
- /**
- * Array of nameserver types.
- * @private
- */
- nameserverTypeNames_: {
- type: Array,
- value: ['automatic', 'google', 'custom'],
- readOnly: true,
- },
- },
-
- /** @const */
- GOOGLE_NAMESERVERS: [
- '8.8.4.4',
- '8.8.8.8',
- ],
-
- /** @const */
- MAX_NAMESERVERS: 4,
-
- /**
- * Saved nameservers when switching to 'automatic'.
- * @private {!Array<string>}
- */
- savedNameservers_: [],
-
- /** @private */
- networkPropertiesChanged_: function(newValue, oldValue) {
- if (!this.networkProperties)
- return;
-
- if (!oldValue || newValue.GUID != oldValue.GUID)
- this.savedNameservers_ = [];
-
- // Update the 'nameservers' property.
- var nameservers = [];
- var ipv4 =
- CrOnc.getIPConfigForType(this.networkProperties, CrOnc.IPType.IPV4);
- if (ipv4 && ipv4.NameServers)
- nameservers = ipv4.NameServers;
-
- // Update the 'nameserversType' property.
- var configType =
- CrOnc.getActiveValue(this.networkProperties.NameServersConfigType);
- var type;
- if (configType == CrOnc.IPConfigType.STATIC) {
- if (nameservers.join(',') == this.GOOGLE_NAMESERVERS.join(',')) {
- type = 'google';
- } else {
- type = 'custom';
- }
- } else {
- type = 'automatic';
- }
- this.setNameservers_(type, nameservers);
- },
-
- /**
- * @param {string} nameserversType
- * @param {!Array<string>} nameservers
- * @private
- */
- setNameservers_: function(nameserversType, nameservers) {
- if (nameserversType == 'custom') {
- // Add empty entries for unset custom nameservers.
- for (var i = nameservers.length; i < this.MAX_NAMESERVERS; ++i)
- nameservers[i] = '';
- }
- this.nameservers_ = nameservers;
- // Set nameserversType_ after dom-repeat has been stamped.
- this.async(function() {
- this.nameserversType_ = nameserversType;
- }.bind(this));
- },
-
- /**
- * @param {string} type The nameservers type.
- * @return {string} The description for |type|.
- * @private
- */
- nameserverTypeDesc_: function(type) {
- // TODO(stevenjb): Translate.
- if (type == 'custom')
- return 'Custom name servers';
- if (type == 'google')
- return 'Google name servers';
- return 'Automatic name servers';
- },
-
- /**
- * @param {boolean} editable
- * @param {string} nameserversType
- * @return {boolean} True if the nameservers are editable.
- * @private
- */
- canEdit_: function(editable, nameserversType) {
- return editable && nameserversType == 'custom';
- },
-
- /**
- * Event triggered when the selected type changes. Updates nameservers and
- * sends the change value if necessary.
- * @param {!Event} event
- * @private
- */
- onTypeChange_: function(event) {
- if (this.nameserversType_ == 'custom')
- this.savedNameservers_ = this.nameservers_;
- var target = /** @type {!HTMLSelectElement} */ (event.target);
- var type = target.value;
- this.nameserversType_ = type;
- if (type == 'custom') {
- // Restore the saved nameservers.
- this.setNameservers_(type, this.savedNameservers_);
- // Only send custom nameservers if they are not empty.
- if (this.savedNameservers_.length == 0)
- return;
- }
- this.sendNameServers_();
- },
-
- /**
- * Event triggered when a nameserver value changes.
- * @private
- */
- onValueChange_: function() {
- if (this.nameserversType_ != 'custom') {
- // If a user inputs Google nameservers in the custom nameservers fields,
- // |nameserversType| will change to 'google' so don't send the values.
- return;
- }
- this.sendNameServers_();
- },
-
- /**
- * Sends the current nameservers type (for automatic) or value.
- * @private
- */
- sendNameServers_: function() {
- var type = this.nameserversType_;
-
- if (type == 'custom') {
- var nameservers = new Array(this.MAX_NAMESERVERS);
- for (var i = 0; i < this.MAX_NAMESERVERS; ++i) {
- var nameserverInput = this.$$('#nameserver' + i);
- nameservers[i] = nameserverInput ? nameserverInput.value : '';
- }
- this.fire('nameservers-change', {
- field: 'NameServers',
- value: nameservers,
- });
- } else if (type == 'google') {
- this.fire('nameservers-change', {
- field: 'NameServers',
- value: this.GOOGLE_NAMESERVERS,
- });
- } else {
- // automatic
- this.fire('nameservers-change', {
- field: 'NameServersConfigType',
- value: CrOnc.IPConfigType.DHCP,
- });
- }
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_property_list.html b/chromium/chrome/browser/resources/settings/internet_page/network_property_list.html
deleted file mode 100644
index b3778cfec47..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_property_list.html
+++ /dev/null
@@ -1,71 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_indicator.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input-container.html">
-<link rel="import" href="internet_shared_css.html">
-
-<dom-module id="network-property-list">
- <template>
- <style include="internet-shared iron-flex">
- paper-input-container {
- margin-bottom: -12px;
- margin-top: -8px;
- }
-
- /* Property lists are embedded; stretch the box and remove the padding. */
- .settings-box {
- align-items: stretch;
- padding: 0;
- }
-
- .settings-box:first-of-type {
- border-top: none;
- }
-
- cr-policy-network-indicator {
- -webkit-margin-start: var(--settings-controlled-by-spacing);
- }
- </style>
- <template is="dom-repeat" items="[[fields]]"
- filter="[[computeFilter_(prefix, propertyDict, editFieldTypes)]]">
- <div class="settings-box single-column two-line">
- <!-- Property label -->
- <div>[[getPropertyLabel_(item, prefix)]]</div>
- <!-- Uneditable property value -->
- <div class="layout horizontal"
- hidden="[[isEditable_(item, '', propertyDict, editFieldTypes)]]">
- <div class="secondary">
- [[getPropertyValue_(item, prefix, propertyDict)]]
- </div>
- <cr-policy-network-indicator
- property="[[getProperty_(item, propertyDict)]]">
- </cr-policy-network-indicator>
- </div>
- <!-- Editable String property value -->
- <template is="dom-if" if="[[isEditable_(
- item, 'String', propertyDict, editFieldTypes)]]">
- <paper-input-container no-label-float>
- <input id="[[item]]" is="iron-input"
- value="[[getPropertyValue_(item, prefix, propertyDict)]]"
- on-change="onValueChange_">
- </paper-input-container>
- </template>
- <!-- Editable Password property value -->
- <template is="dom-if" if="[[isEditable_(
- item, 'Password', propertyDict, editFieldTypes)]]">
- <paper-input-container no-label-float>
- <input id="[[item]]" is="iron-input" type="password"
- value="[[getPropertyValue_(item, prefix, propertyDict)]]"
- on-change="onValueChange_">
- </paper-input-container>
- </template>
- <!-- TODO(stevenjb): Support other types. -->
- </div>
- </template>
- </template>
- <script src="network_property_list.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_property_list.js b/chromium/chrome/browser/resources/settings/internet_page/network_property_list.js
deleted file mode 100644
index 006feca4d5a..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_property_list.js
+++ /dev/null
@@ -1,214 +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.
-
-/**
- * @fileoverview Polymer element for displaying a list of network properties
- * in a list. This also supports editing fields inline for fields listed in
- * editFieldTypes.
- */
-Polymer({
- is: 'network-property-list',
-
- behaviors: [I18nBehavior, CrPolicyNetworkBehavior],
-
- properties: {
- /**
- * The dictionary containing the properties to display.
- * @type {!Object|undefined}
- */
- propertyDict: {type: Object},
-
- /**
- * Fields to display.
- * @type {!Array<string>}
- */
- fields: {
- type: Array,
- value: function() {
- return [];
- },
- },
-
- /**
- * Edit type of editable fields. May contain a property for any field in
- * |fields|. Other properties will be ignored. Property values can be:
- * 'String' - A text input will be displayed.
- * 'Password' - A string with input type = password.
- * TODO(stevenjb): Support types with custom validation, e.g. IPAddress.
- * TODO(stevenjb): Support 'Number'.
- * When a field changes, the 'property-change' event will be fired with
- * the field name and the new value provided in the event detail.
- */
- editFieldTypes: {
- type: Object,
- value: function() {
- return {};
- },
- },
-
- /** Prefix used to look up property key translations. */
- prefix: {
- type: String,
- value: '',
- },
- },
-
- /**
- * Event triggered when an input field changes. Fires a 'property-change'
- * event with the field (property) name set to the target id, and the value
- * set to the target input value.
- * @param {!Event} event The input change event.
- * @private
- */
- onValueChange_: function(event) {
- if (!this.propertyDict)
- return;
- var field = event.target.id;
- var curValue = this.get(field, this.propertyDict);
- if (typeof curValue == 'object') {
- // Extract the property from an ONC managed dictionary.
- curValue = CrOnc.getActiveValue(
- /** @type {!CrOnc.ManagedProperty} */ (curValue));
- }
- var newValue = event.target.value;
- if (newValue == curValue)
- return;
- this.fire('property-change', {field: field, value: newValue});
- },
-
- /**
- * @param {string} key The property key.
- * @param {string} prefix
- * @return {string} The text to display for the property label.
- * @private
- */
- getPropertyLabel_: function(key, prefix) {
- var oncKey = 'Onc' + prefix + key;
- oncKey = oncKey.replace(/\./g, '-');
- if (this.i18nExists(oncKey))
- return this.i18n(oncKey);
- // We do not provide translations for every possible network property key.
- // For keys specific to a type, strip the type prefix.
- var result = prefix + key;
- for (var entry in chrome.networkingPrivate.NetworkType) {
- var type = chrome.networkingPrivate.NetworkType[entry];
- if (result.startsWith(type + '.')) {
- result = result.substr(type.length + 1);
- break;
- }
- }
- return result;
- },
-
- /**
- * Generates a filter function dependent on propertyDict and editFieldTypes.
- * @param {string} prefix
- * @param {!Object} propertyDict
- * @param {!Object} editFieldTypes
- * @private
- */
- computeFilter_: function(prefix, propertyDict, editFieldTypes) {
- return function(key) {
- if (editFieldTypes.hasOwnProperty(key))
- return true;
- var value = this.getPropertyValue_(key, prefix, propertyDict);
- return value !== undefined && value !== '';
- }.bind(this);
- },
-
- /**
- * @param {string} key The property key.
- * @param {string} type The field type.
- * @param {!Object} propertyDict
- * @param {!Object} editFieldTypes
- * @return {boolean}
- * @private
- */
- isEditable_: function(key, type, propertyDict, editFieldTypes) {
- var property = /** @type {!CrOnc.ManagedProperty|undefined} */ (
- this.get(key, propertyDict));
- if (this.isNetworkPolicyEnforced(property))
- return false;
- var editType = editFieldTypes[key];
- return editType !== undefined && (type == '' || editType == type);
- },
-
- /**
- * @param {string} key The property key.
- * @param {!Object} propertyDict
- * @return {*} The managed property dictionary associated with |key|.
- * @private
- */
- getProperty_: function(key, propertyDict) {
- return this.get(key, propertyDict);
- },
-
- /**
- * @param {string} key The property key.
- * @param {string} prefix
- * @param {!Object} propertyDict
- * @return {string} The text to display for the property value.
- * @private
- */
- getPropertyValue_: function(key, prefix, propertyDict) {
- var value = this.get(key, propertyDict);
- if (value === undefined)
- return '';
- if (typeof value == 'object') {
- // Extract the property from an ONC managed dictionary
- value =
- CrOnc.getActiveValue(/** @type {!CrOnc.ManagedProperty} */ (value));
- }
- var customValue = this.getCustomPropertyValue_(key, value);
- if (customValue)
- return customValue;
- if (typeof value == 'number' || typeof value == 'boolean')
- return value.toString();
- assert(typeof value == 'string');
- var valueStr = /** @type {string} */ (value);
- var oncKey = 'Onc' + prefix + key;
- oncKey = oncKey.replace(/\./g, '-');
- oncKey += '_' + valueStr;
- if (this.i18nExists(oncKey))
- return this.i18n(oncKey);
- return valueStr;
- },
-
- /**
- * @param {string} key The property key.
- * @param {*} value The property value.
- * @return {string} The text to display for the property value. If the key
- * does not correspond to a custom property, an empty string is returned.
- */
- getCustomPropertyValue_: function(key, value) {
- if (key == 'Tether.BatteryPercentage') {
- assert(typeof value == 'number');
- return this.i18n('OncTether-BatteryPercentage_Value', value.toString());
- }
-
- if (key == 'Tether.SignalStrength') {
- assert(typeof value == 'number');
- // Possible |signalStrength| values should be 0, 25, 50, 75, and 100. Add
- // <= checks for robustness.
- if (value <= 24)
- return this.i18n('OncTether-SignalStrength_Weak');
- if (value <= 49)
- return this.i18n('OncTether-SignalStrength_Okay');
- if (value <= 74)
- return this.i18n('OncTether-SignalStrength_Good');
- if (value <= 99)
- return this.i18n('OncTether-SignalStrength_Strong');
- return this.i18n('OncTether-SignalStrength_VeryStrong');
- }
-
- if (key == 'Tether.Carrier') {
- assert(typeof value == 'string');
- return (!value || value == 'unknown-carrier') ?
- this.i18n('tetherUnknownCarrier') :
- value;
- }
-
- return '';
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy.html b/chromium/chrome/browser/resources/settings/internet_page/network_proxy.html
deleted file mode 100644
index e6f9e298397..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy.html
+++ /dev/null
@@ -1,232 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_indicator.html">
-<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-keys/iron-a11y-keys.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input-container.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html">
-<link rel="import" href="../controls/extension_controlled_indicator.html">
-<link rel="import" href="../controls/settings_toggle_button.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../prefs/prefs_behavior.html">
-<link rel="import" href="../settings_vars_css.html">
-<link rel="import" href="internet_shared_css.html">
-link rel="import" href="network_proxy_exclusions.html">
-<link rel="import" href="network_proxy_input.html">
-
-<dom-module id="network-proxy">
- <template>
- <style include="internet-shared md-select cr-hidden-style iron-flex iron-flex-alignment">
- cr-policy-network-indicator {
- -webkit-margin-end: 10px;
- }
-
- extension-controlled-indicator {
- -webkit-margin-start: 0;
- width: 100%;
- }
-
- network-proxy-input {
- margin-bottom: 10px;
- }
-
- network-proxy-exclusions {
- margin: 10px 0;
- }
-
- .settings-box:first-of-type {
- border-top: none;
- }
-
- #manualProxy {
- @apply(--settings-list-frame-padding);
- }
- </style>
-
- <!-- Policy indicator. Only one dom-if below will be shown. -->
- <template is="dom-if"
- if="[[shouldShowNetworkPolicyIndicator_(networkProperties)]]">
- <div class="settings-box">
- <div class="layout horizontal center">
- <cr-policy-network-indicator
- property="[[networkProperties.ProxySettings.Type]]"
- no-extension-indicator>
- </cr-policy-network-indicator>
- <div>$i18n{networkProxyEnforcedPolicy}</div>
- </div>
- </div>
- </template>
- <template is="dom-if"
- if="[[shouldShowExtensionIndicator_(networkProperties)]]">
- <div class="settings-box">
- <extension-controlled-indicator
- extension-id="[[prefs.proxy.extensionId]]"
- extension-name="[[prefs.proxy.controlledByName]]"
- extension-can-be-disabled="[[prefs.proxy.extensionCanBeDisabled]]">
- </extension-controlled-indicator>
- </div>
- </template>
-
- <!-- Allow shared proxies -->
- <div class="settings-box continuation"
- hidden$="[[!shouldShowAllowShared_(
- networkProperties.ProxySettings.Type)]]">
- <settings-toggle-button id="allowShared" class="start"
- pref="{{prefs.settings.use_shared_proxies}}"
- label="$i18n{networkProxyAllowShared}"
- on-settings-boolean-control-change="onAllowSharedProxiesChange_"
- no-set-pref>
- </settings-toggle-button>
- </div>
-
- <!-- Proxy type dropdown -->
- <div class="settings-box continuation">
- <div class="start">$i18n{networkProxyConnectionType}</div>
- <div class="md-select-wrapper">
- <select id="proxyType" class="md-select" on-change="onTypeChange_"
- value="[[proxy_.Type]]"
- disabled="[[!isEditable_('Type', networkProperties, editable,
- useSharedProxies_)]]"
- aria-label="$i18n{networkProxyConnectionType}">
- <template is="dom-repeat" items="[[proxyTypes_]]">
- <option value="[[item]]">[[getProxyTypeDesc_(item)]]</option>
- </template>
- </select>
- <span class="md-select-underline"></span>
- </div>
- </div>
-
- <!-- Autoconfiguration (PAC) -->
- <div class="settings-box continuation"
- hidden$="[[!matches_(proxy_.Type, ProxySettingsType_.PAC)]]">
- <div>$i18n{networkProxyAutoConfig}</div>
- <paper-input no-label-float class="middle" value="{{proxy_.PAC}}"
- disabled="[[!isEditable_('PAC', networkProperties, editable,
- useSharedProxies_)]]"
- on-change="onPACChange_">
- </paper-input>
- </div>
-
- <!-- Web Proxy Auto Discovery (WPAD) -->
- <div class="settings-box continuation"
- hidden$="[[!matches_(proxy_.Type, ProxySettingsType_.WPAD)]]">
- <div>$i18n{networkSectionWpad}</div>
- <div class="middle">[[WPAD_]]</div>
- </div>
-
- <!-- Manual -->
- <div class="settings-box continuation"
- hidden$="[[!matches_(proxy_.Type, ProxySettingsType_.MANUAL)]]">
- <div id="networkProxyToggleLabel" class="flex">
- $i18n{networkProxyUseSame}
- </div>
- <paper-toggle-button checked="{{useSameProxy_}}"
- disabled="[[!isEditable_('Type', networkProperties, editable,
- useSharedProxies_)]]"
- aria-labelledby="networkProxyToggleLabel">
- </paper-toggle-button>
- </div>
-
- <div id="manualProxy" class="layout vertical start"
- hidden$="[[!matches_(proxy_.Type, ProxySettingsType_.MANUAL)]]">
- <div hidden$="[[!useSameProxy_]]" class="layout vertical">
- <network-proxy-input
- on-proxy-change="onProxyInputChange_"
- editable="[[isEditable_('Manual.HTTPProxy.Host', networkProperties,
- editable, useSharedProxies_)]]"
- value="{{proxy_.Manual.HTTPProxy}}"
- label="$i18n{networkProxy}">
- </network-proxy-input>
- </div>
- <div hidden$="[[useSameProxy_]]" class="layout vertical">
- <network-proxy-input
- on-proxy-change="onProxyInputChange_"
- editable="[[isEditable_('Manual.HTTPProxy.Host', networkProperties,
- editable, useSharedProxies_)]]"
- value="{{proxy_.Manual.HTTPProxy}}"
- label="$i18n{networkProxyHttp}">
- </network-proxy-input>
- <network-proxy-input
- on-proxy-change="onProxyInputChange_"
- editable="[[isEditable_('Manual.SecureHTTPProxy.Host',
- networkProperties, editable, useSharedProxies_)]]"
- value="{{proxy_.Manual.SecureHTTPProxy}}"
- label="$i18n{networkProxyShttp}">
- </network-proxy-input>
- <network-proxy-input
- on-proxy-change="onProxyInputChange_"
- editable="[[isEditable_('Manual.FTPProxy.Host', networkProperties,
- editable, useSharedProxies_)]]"
- value="{{proxy_.Manual.FTPProxy}}"
- label="$i18n{networkProxyFtp}">
- </network-proxy-input>
- <network-proxy-input
- on-proxy-change="onProxyInputChange_"
- editable="[[isEditable_('Manual.SOCKS.Host', networkProperties,
- editable, useSharedProxies_)]]"
- value="{{proxy_.Manual.SOCKS}}"
- label="$i18n{networkProxySocks}">
- </network-proxy-input>
- </div>
-
- <div hidden="[[!isEditable_('Type', networkProperties, editable,
- useSharedProxies_)]]">
- <div>$i18n{networkProxyExceptionList}</div>
- <network-proxy-exclusions on-proxy-change="onProxyExclusionsChange_"
- exclusions="{{proxy_.ExcludeDomains}}">
- </network-proxy-exclusions>
- <div class="layout horizontal">
- <paper-input-container no-label-float class="flex">
- <input id="proxyExclusion" is="iron-input">
- <iron-a11y-keys keys="enter"
- on-keys-pressed="onAddProxyExclusionTap_">
- </iron-a11y-keys>
- </paper-input-container>
- <paper-button on-tap="onAddProxyExclusionTap_">
- $i18n{networkProxyAddException}
- </paper-button>
- </div>
- </div>
-
- <paper-button id="saveManualProxy"
- on-tap="onSaveProxyTap_" class="action-button"
- disabled="[[!isSaveManualProxyEnabled_(networkProperties,
- proxyModified_, proxy_.*)]]">
- $i18n{save}
- </paper-button>
- </div>
-
- <!-- Confirm Allow shared proxies dialog -->
- <dialog is="cr-dialog" id="confirmAllowSharedDialog"
- close-text="$i18n{close}" on-cancel="onAllowSharedDialogCancel_"
- on-close="onAllowSharedDialogClose_">
- <div class="title" slot="title">
- $i18n{networkProxyAllowSharedWarningTitle}
- </div>
- <div class="body" slot="body">
- $i18n{networkProxyAllowSharedWarningMessage}
- </div>
- <div class="button-container" slot="button-container">
- <paper-button class="cancel-button"
- on-tap="onAllowSharedDialogCancel_">
- $i18n{cancel}
- </paper-button>
- <paper-button class="action-button"
- on-tap="onAllowSharedDialogConfirm_">
- $i18n{confirm}
- </paper-button>
- </div>
- </dialog>
- </template>
- <script src="network_proxy.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy.js b/chromium/chrome/browser/resources/settings/internet_page/network_proxy.js
deleted file mode 100644
index 52e7e02fc01..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy.js
+++ /dev/null
@@ -1,497 +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.
-
-/**
- * @fileoverview Polymer element for displaying and editing network proxy
- * values.
- */
-Polymer({
- is: 'network-proxy',
-
- behaviors: [
- CrPolicyNetworkBehavior,
- I18nBehavior,
- PrefsBehavior,
- settings.RouteObserverBehavior,
- ],
-
- properties: {
- /**
- * The network properties dictionary containing the proxy properties to
- * display and modify.
- * @type {!CrOnc.NetworkProperties|undefined}
- */
- networkProperties: {
- type: Object,
- observer: 'networkPropertiesChanged_',
- },
-
- /** Whether or not the proxy values can be edited. */
- editable: {
- type: Boolean,
- value: false,
- },
-
- /**
- * UI visible / edited proxy configuration.
- * @private {!CrOnc.ProxySettings}
- */
- proxy_: {
- type: Object,
- value: function() {
- return this.createDefaultProxySettings_();
- },
- },
-
- /**
- * The Web Proxy Auto Discovery URL extracted from networkProperties.
- * @private
- */
- WPAD_: {
- type: String,
- value: '',
- },
-
- /**
- * Whether or not to use the same manual proxy for all protocols.
- * @private
- */
- useSameProxy_: {
- type: Boolean,
- value: false,
- observer: 'useSameProxyChanged_',
- },
-
- /**
- * Reflects prefs.settings.use_shared_proxies for data binding.
- * @private
- */
- useSharedProxies_: Boolean,
-
- /**
- * Array of proxy configuration types.
- * @private {!Array<string>}
- * @const
- */
- proxyTypes_: {
- type: Array,
- value: [
- CrOnc.ProxySettingsType.DIRECT,
- CrOnc.ProxySettingsType.PAC,
- CrOnc.ProxySettingsType.WPAD,
- CrOnc.ProxySettingsType.MANUAL,
- ],
- readOnly: true
- },
-
- /**
- * Object providing proxy type values for data binding.
- * @private {!Object}
- * @const
- */
- ProxySettingsType_: {
- type: Object,
- value: {
- DIRECT: CrOnc.ProxySettingsType.DIRECT,
- PAC: CrOnc.ProxySettingsType.PAC,
- MANUAL: CrOnc.ProxySettingsType.MANUAL,
- WPAD: CrOnc.ProxySettingsType.WPAD,
- },
- readOnly: true,
- },
- },
-
- observers: [
- 'useSharedProxiesChanged_(prefs.settings.use_shared_proxies.value)',
- ],
-
- /**
- * Saved Manual properties so that switching to another type does not loose
- * any set properties while the UI is open.
- * @private {!CrOnc.ManualProxySettings|undefined}
- */
- savedManual_: undefined,
-
- /**
- * Saved ExcludeDomains properties so that switching to a non-Manual type does
- * not loose any set exclusions while the UI is open.
- * @private {!Array<string>|undefined}
- */
- savedExcludeDomains_: undefined,
-
- /**
- * Set to true while modifying proxy values so that an update does not
- * override the edited values.
- * @private {boolean}
- */
- proxyModified_: false,
-
- /** @protected settings.RouteObserverBehavior */
- currentRouteChanged: function(newRoute) {
- this.proxyModified_ = false;
- this.proxy_ = this.createDefaultProxySettings_();
- if (newRoute == settings.routes.NETWORK_DETAIL)
- this.updateProxy_();
- },
-
- /** @private */
- networkPropertiesChanged_: function() {
- if (this.proxyModified_)
- return; // Ignore update.
- this.updateProxy_();
- },
-
- /** @private */
- updateProxy_: function() {
- if (!this.networkProperties)
- return;
-
- /** @type {!CrOnc.ProxySettings} */
- var proxy = this.createDefaultProxySettings_();
-
- // For shared networks with unmanaged proxy settings, ignore any saved
- // proxy settings (use the default values).
- if (this.isShared_()) {
- var property = this.getProxySettingsTypeProperty_();
- if (!this.isControlled(property) && !this.useSharedProxies_) {
- this.setProxyAsync_(proxy);
- return; // Proxy settings will be ignored.
- }
- }
-
- /** @type {!chrome.networkingPrivate.ManagedProxySettings|undefined} */
- var proxySettings = this.networkProperties.ProxySettings;
- if (proxySettings) {
- proxy.Type = /** @type {!CrOnc.ProxySettingsType} */ (
- CrOnc.getActiveValue(proxySettings.Type));
- if (proxySettings.Manual) {
- proxy.Manual.HTTPProxy = /** @type {!CrOnc.ProxyLocation|undefined} */ (
- CrOnc.getSimpleActiveProperties(
- proxySettings.Manual.HTTPProxy)) ||
- {Host: '', Port: 80};
- proxy.Manual.SecureHTTPProxy =
- /** @type {!CrOnc.ProxyLocation|undefined} */ (
- CrOnc.getSimpleActiveProperties(
- proxySettings.Manual.SecureHTTPProxy)) ||
- {Host: '', Port: 80};
- proxy.Manual.FTPProxy =
- /** @type {!CrOnc.ProxyLocation|undefined} */ (
- CrOnc.getSimpleActiveProperties(
- proxySettings.Manual.FTPProxy)) ||
- {Host: '', Port: 80};
- proxy.Manual.SOCKS =
- /** @type {!CrOnc.ProxyLocation|undefined} */ (
- CrOnc.getSimpleActiveProperties(proxySettings.Manual.SOCKS)) ||
- {Host: '', Port: 80};
- var jsonHttp = proxy.Manual.HTTPProxy;
- this.useSameProxy_ =
- (CrOnc.proxyMatches(jsonHttp, proxy.Manual.SecureHTTPProxy) &&
- CrOnc.proxyMatches(jsonHttp, proxy.Manual.FTPProxy) &&
- CrOnc.proxyMatches(jsonHttp, proxy.Manual.SOCKS)) ||
- (!proxy.Manual.SecureHTTPProxy.Host &&
- !proxy.Manual.FTPProxy.Host && !proxy.Manual.SOCKS.Host);
- }
- if (proxySettings.ExcludeDomains) {
- proxy.ExcludeDomains = /** @type {!Array<string>|undefined} */ (
- CrOnc.getActiveValue(proxySettings.ExcludeDomains));
- }
- proxy.PAC = /** @type {string|undefined} */ (
- CrOnc.getActiveValue(proxySettings.PAC));
- }
- // Use saved ExcludeDomains and Manual if not defined.
- proxy.ExcludeDomains = proxy.ExcludeDomains || this.savedExcludeDomains_;
- proxy.Manual = proxy.Manual || this.savedManual_;
-
- // Set the Web Proxy Auto Discovery URL.
- var ipv4 =
- CrOnc.getIPConfigForType(this.networkProperties, CrOnc.IPType.IPV4);
- this.WPAD_ = (ipv4 && ipv4.WebProxyAutoDiscoveryUrl) || '';
-
- this.setProxyAsync_(proxy);
- },
-
- /**
- * @param {!CrOnc.ProxySettings} proxy
- * @private
- */
- setProxyAsync_: function(proxy) {
- // Set this.proxy_ after dom-repeat has been stamped.
- this.async(function() {
- this.proxy_ = proxy;
- this.proxyModified_ = false;
- }.bind(this));
- },
-
- /** @private */
- useSameProxyChanged_: function() {
- this.proxyModified_ = true;
- },
-
- /** @private */
- useSharedProxiesChanged_: function() {
- var pref = this.getPref('settings.use_shared_proxies');
- this.useSharedProxies_ = !!pref && !!pref.value;
- this.updateProxy_();
- },
-
- /**
- * @return {CrOnc.ProxySettings} An empty/default proxy settings object.
- * @private
- */
- createDefaultProxySettings_: function() {
- return {
- Type: CrOnc.ProxySettingsType.DIRECT,
- ExcludeDomains: [],
- Manual: {
- HTTPProxy: {Host: '', Port: 80},
- SecureHTTPProxy: {Host: '', Port: 80},
- FTPProxy: {Host: '', Port: 80},
- SOCKS: {Host: '', Port: 1080}
- },
- PAC: ''
- };
- },
-
- /**
- * Called when the proxy changes in the UI.
- * @private
- */
- sendProxyChange_: function() {
- var proxy =
- /** @type {!CrOnc.ProxySettings} */ (Object.assign({}, this.proxy_));
- if (proxy.Type == CrOnc.ProxySettingsType.MANUAL) {
- var manual = proxy.Manual;
- var defaultProxy = manual.HTTPProxy || {Host: '', Port: 80};
- if (this.useSameProxy_) {
- proxy.Manual.SecureHTTPProxy = /** @type {!CrOnc.ProxyLocation} */ (
- Object.assign({}, defaultProxy));
- proxy.Manual.FTPProxy = /** @type {!CrOnc.ProxyLocation} */ (
- Object.assign({}, defaultProxy));
- proxy.Manual.SOCKS = /** @type {!CrOnc.ProxyLocation} */ (
- Object.assign({}, defaultProxy));
- } else {
- // Remove properties with empty hosts to unset them.
- if (manual.HTTPProxy && !manual.HTTPProxy.Host)
- delete manual.HTTPProxy;
- if (manual.SecureHTTPProxy && !manual.SecureHTTPProxy.Host)
- delete manual.SecureHTTPProxy;
- if (manual.FTPProxy && !manual.FTPProxy.Host)
- delete manual.FTPProxy;
- if (manual.SOCKS && !manual.SOCKS.Host)
- delete manual.SOCKS;
- }
- this.savedManual_ = Object.assign({}, manual);
- this.savedExcludeDomains_ = proxy.ExcludeDomains;
- } else if (proxy.Type == CrOnc.ProxySettingsType.PAC) {
- if (!proxy.PAC)
- return;
- }
- this.fire('proxy-change', {field: 'ProxySettings', value: proxy});
- this.proxyModified_ = false;
- },
-
- /**
- * Event triggered when the selected proxy type changes.
- * @param {!Event} event
- * @private
- */
- onTypeChange_: function(event) {
- var target = /** @type {!HTMLSelectElement} */ (event.target);
- var type = /** @type {chrome.networkingPrivate.ProxySettingsType} */ (
- target.value);
- this.set('proxy_.Type', type);
- if (type == CrOnc.ProxySettingsType.MANUAL)
- this.proxyModified_ = true;
- else
- this.sendProxyChange_();
- },
-
- /** @private */
- onPACChange_: function() {
- this.sendProxyChange_();
- },
-
- /** @private */
- onProxyInputChange_: function() {
- this.proxyModified_ = true;
- },
-
- /**
- * Event triggered when a proxy exclusion is added.
- * @param {!Event} event The add proxy exclusion event.
- * @private
- */
- onAddProxyExclusionTap_: function(event) {
- var value = this.$.proxyExclusion.value;
- if (!value)
- return;
- this.push('proxy_.ExcludeDomains', value);
- // Clear input.
- this.$.proxyExclusion.value = '';
- this.proxyModified_ = true;
- },
-
- /**
- * Event triggered when the proxy exclusion list changes.
- * @param {!Event} event The remove proxy exclusions change event.
- * @private
- */
- onProxyExclusionsChange_: function(event) {
- this.proxyModified_ = true;
- },
-
- /** @private */
- onSaveProxyTap_: function() {
- this.sendProxyChange_();
- },
-
- /**
- * @param {string} proxyType The proxy type.
- * @return {string} The description for |proxyType|.
- * @private
- */
- getProxyTypeDesc_: function(proxyType) {
- if (proxyType == CrOnc.ProxySettingsType.MANUAL)
- return this.i18n('networkProxyTypeManual');
- if (proxyType == CrOnc.ProxySettingsType.PAC)
- return this.i18n('networkProxyTypePac');
- if (proxyType == CrOnc.ProxySettingsType.WPAD)
- return this.i18n('networkProxyTypeWpad');
- return this.i18n('networkProxyTypeDirect');
- },
-
- /**
- * @return {!CrOnc.ManagedProperty|undefined}
- * @private
- */
- getProxySettingsTypeProperty_: function() {
- return /** @type {!CrOnc.ManagedProperty|undefined} */ (
- this.get('ProxySettings.Type', this.networkProperties));
- },
-
- /**
- * @return {boolean}
- * @private
- */
- shouldShowNetworkPolicyIndicator_: function() {
- var property = this.getProxySettingsTypeProperty_();
- return !!property && !this.isExtensionControlled(property) &&
- this.isNetworkPolicyEnforced(property);
- },
-
- /**
- * @return {boolean}
- * @private
- */
- shouldShowExtensionIndicator_: function() {
- var property = this.getProxySettingsTypeProperty_();
- return !!property && this.isExtensionControlled(property);
- },
-
- /**
- * @param {!CrOnc.ManagedProperty} property
- * @return {boolean}
- * @private
- */
- shouldShowAllowShared_: function(property) {
- return !this.isControlled(property) && this.isShared_();
- },
-
- /**
- * @param {string} propertyName
- * @return {boolean} Whether the named property setting is editable.
- * @private
- */
- isEditable_: function(propertyName) {
- if (!this.editable || (this.isShared_() && !this.useSharedProxies_))
- return false;
- if (!this.networkProperties.hasOwnProperty('ProxySettings'))
- return true; // No proxy settings defined, so not enforced.
- var property = /** @type {!CrOnc.ManagedProperty|undefined} */ (
- this.get('ProxySettings.' + propertyName, this.networkProperties));
- if (!property)
- return true;
- return this.isPropertyEditable_(property);
- },
-
- /**
- * @param {!CrOnc.ManagedProperty|undefined} property
- * @return {boolean} Whether |property| is editable.
- * @private
- */
- isPropertyEditable_: function(property) {
- return !this.isNetworkPolicyEnforced(property) &&
- !this.isExtensionControlled(property);
- },
-
- /**
- * @return {boolean}
- * @private
- */
- isShared_: function() {
- return this.networkProperties.Source == 'Device' ||
- this.networkProperties.Source == 'DevicePolicy';
- },
-
- /**
- * @return {boolean}
- * @private
- */
- isSaveManualProxyEnabled_: function() {
- if (!this.proxyModified_)
- return false;
- var manual = this.proxy_.Manual;
- var httpHost = this.get('HTTPProxy.Host', manual);
- if (this.useSameProxy_)
- return !!httpHost;
- return !!httpHost || !!this.get('SecureHTTPProxy.Host', manual) ||
- !!this.get('FTPProxy.Host', manual) || !!this.get('SOCKS.Host', manual);
- },
-
- /**
- * @param {string} property The property to test
- * @param {string} value The value to test against
- * @return {boolean} True if property == value
- * @private
- */
- matches_: function(property, value) {
- return property == value;
- },
-
- /**
- * Handles the change event for the shared proxy checkbox. Shows a
- * confirmation dialog.
- * @param {!Event} event
- * @private
- */
- onAllowSharedProxiesChange_: function(event) {
- this.$.confirmAllowSharedDialog.showModal();
- },
-
- /**
- * Handles the shared proxy confirmation dialog 'Confirm' button.
- * @private
- */
- onAllowSharedDialogConfirm_: function() {
- /** @type {!SettingsCheckboxElement} */ (this.$.allowShared)
- .sendPrefChange();
- this.$.confirmAllowSharedDialog.close();
- },
-
- /**
- * Handles the shared proxy confirmation dialog 'Cancel' button or a cancel
- * event.
- * @private
- */
- onAllowSharedDialogCancel_: function() {
- /** @type {!SettingsCheckboxElement} */ (this.$.allowShared)
- .resetToPrefValue();
- this.$.confirmAllowSharedDialog.close();
- },
-
- /** @private */
- onAllowSharedDialogClose_: function() {
- cr.ui.focusWithoutInk(assert(this.$$('#allowShared')));
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.html b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.html
deleted file mode 100644
index 7d7233ec260..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="internet_shared_css.html">
-
-<dom-module id="network-proxy-exclusions">
- <template>
- <style include="internet-shared cr-hidden-style iron-flex">
- iron-icon {
- @apply(--settings-actionable);
- margin: 5px;
- }
-
- #container {
- align-self: stretch;
- border: 1px solid lightgrey;
- height: 100px;
- margin-top: 10px;
- overflow-y: auto;
- padding: 5px;
- }
- </style>
- <div id="container">
- <template is="dom-repeat" items="[[exclusions]]">
- <div class="layout horizontal center" tabindex="0" >
- <div class="flex">[[item]]</div>
- <iron-icon class="favicon-image" icon="cr:clear"
- on-tap="onRemoveTap_" tabindex="0" hidden="[[!editable]]">
- </iron-icon>
- </div>
- </template>
- </div>
- </template>
- <script src="network_proxy_exclusions.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js
deleted file mode 100644
index 347b22980d3..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js
+++ /dev/null
@@ -1,46 +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.
-
-/**
- * @fileoverview Polymer element for displaying a list of proxy exclusions.
- * Includes UI for adding, changing, and removing entries.
- */
-
-(function() {
-
-Polymer({
- is: 'network-proxy-exclusions',
-
- properties: {
- /** Whether or not the proxy values can be edited. */
- editable: {
- type: Boolean,
- value: false,
- },
-
- /**
- * The list of exclusions.
- * @type {!Array<string>}
- */
- exclusions: {
- type: Array,
- value: function() {
- return [];
- },
- notify: true
- }
- },
-
- /**
- * Event triggered when an item is removed.
- * @param {!{model: !{index: number}}} event
- * @private
- */
- onRemoveTap_: function(event) {
- var index = event.model.index;
- this.splice('exclusions', index, 1);
- this.fire('proxy-change');
- }
-});
-})();
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.html b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.html
deleted file mode 100644
index 2516d1ef6f6..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.html
+++ /dev/null
@@ -1,49 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-input/iron-input.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input-container.html">
-<link rel="import" href="internet_shared_css.html">
-
-<dom-module id="network-proxy-input">
- <template>
- <style include="internet-shared">
- paper-input-container {
- -webkit-margin-start: 10px;
- margin-bottom: -12px;
- margin-top: -8px;
- }
-
- #container {
- align-items: center;
- display: flex;
- flex: 0 1 auto;
- flex-direction: row;
- }
-
- #label {
- flex: 1;
- }
-
- #host {
- width: 200px;
- }
-
- #port {
- width: 50px;
- }
- </style>
- <div id="container">
- <div id="label">[[label]]</div>
- <paper-input-container id="host" no-label-float>
- <input is="iron-input" bind-value="{{value.Host}}"
- disabled="[[!editable]]" on-change="onValueChange_">
- </paper-input-container>
- <div>$i18n{networkProxyPort}</div>
- <paper-input-container id="port" no-label-float>
- <input is="iron-input" bind-value="{{value.Port}}"
- disabled="[[!editable]]" on-change="onValueChange_">
- </paper-input-container>
- </div>
- </template>
- <script src="network_proxy_input.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.js b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.js
deleted file mode 100644
index 131b480655b..00000000000
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_input.js
+++ /dev/null
@@ -1,55 +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.
-
-/**
- * @fileoverview Polymer element for displaying and editing a single
- * network proxy value. When the URL or port changes, a 'proxy-change' event is
- * fired with the combined url and port values passed as a single string,
- * url:port.
- */
-Polymer({
- is: 'network-proxy-input',
-
- properties: {
- /**
- * Whether or not the proxy value can be edited.
- */
- editable: {
- type: Boolean,
- value: false,
- },
-
- /**
- * A label for the proxy value.
- */
- label: {
- type: String,
- value: 'Proxy',
- },
-
- /**
- * The proxy object.
- * @type {!CrOnc.ProxyLocation}
- */
- value: {
- type: Object,
- value: function() {
- return {Host: '', Port: 80};
- },
- notify: true,
- },
- },
-
- /**
- * Event triggered when an input value changes.
- * @private
- */
- onValueChange_: function() {
- var port = parseInt(this.value.Port, 10);
- if (isNaN(port))
- port = 80;
- this.value.Port = port;
- this.fire('proxy-change', {value: this.value});
- }
-});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html
new file mode 100644
index 00000000000..f4cddf4cd3d
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html
@@ -0,0 +1,103 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_proxy.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_indicator.html">
+<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="../controls/extension_controlled_indicator.html">
+<link rel="import" href="../controls/settings_toggle_button.html">
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="../prefs/prefs_behavior.html">
+<link rel="import" href="../settings_vars_css.html">
+<link rel="import" href="internet_shared_css.html">
+
+<dom-module id="network-proxy-section">
+ <template>
+ <style include="internet-shared md-select cr-hidden-style iron-flex iron-flex-alignment">
+ cr-policy-network-indicator {
+ -webkit-margin-end: 10px;
+ }
+
+ extension-controlled-indicator {
+ -webkit-margin-start: 0;
+ width: 100%;
+ }
+
+ .settings-box:first-of-type {
+ border-top: none;
+ }
+ </style>
+
+ <!-- Policy indicator. Only one dom-if below will be shown. -->
+ <template is="dom-if"
+ if="[[shouldShowNetworkPolicyIndicator_(networkProperties)]]">
+ <div class="settings-box">
+ <div class="layout horizontal center">
+ <cr-policy-network-indicator
+ property="[[networkProperties.ProxySettings.Type]]"
+ no-extension-indicator>
+ </cr-policy-network-indicator>
+ <div>$i18n{networkProxyEnforcedPolicy}</div>
+ </div>
+ </div>
+ </template>
+ <template is="dom-if"
+ if="[[shouldShowExtensionIndicator_(networkProperties)]]">
+ <div class="settings-box">
+ <extension-controlled-indicator
+ extension-id="[[prefs.proxy.extensionId]]"
+ extension-name="[[prefs.proxy.controlledByName]]"
+ extension-can-be-disabled="[[prefs.proxy.extensionCanBeDisabled]]">
+ </extension-controlled-indicator>
+ </div>
+ </template>
+
+ <!-- Allow shared proxies -->
+ <settings-toggle-button id="allowShared" class="continuation indented"
+ hidden$="[[!shouldShowAllowShared_(
+ networkProperties.ProxySettings.Type)]]"
+ pref="{{prefs.settings.use_shared_proxies}}"
+ label="$i18n{networkProxyAllowShared}"
+ on-settings-boolean-control-change="onAllowSharedProxiesChange_"
+ no-set-pref>
+ </settings-toggle-button>
+
+ <div class="settings-box single-column stretch continuation indented">
+ <network-proxy editable
+ network-properties="[[networkProperties]]"
+ use-shared-proxies="[[useSharedProxies_]]">
+ </network-proxy>
+ </div>
+
+ <!-- Confirm Allow shared proxies dialog -->
+ <dialog is="cr-dialog" id="confirmAllowSharedDialog"
+ close-text="$i18n{close}" on-cancel="onAllowSharedDialogCancel_"
+ on-close="onAllowSharedDialogClose_">
+ <div slot="title">
+ $i18n{networkProxyAllowSharedWarningTitle}
+ </div>
+ <div slot="body">
+ $i18n{networkProxyAllowSharedWarningMessage}
+ </div>
+ <div slot="button-container">
+ <paper-button class="cancel-button"
+ on-tap="onAllowSharedDialogCancel_">
+ $i18n{cancel}
+ </paper-button>
+ <paper-button class="action-button"
+ on-tap="onAllowSharedDialogConfirm_">
+ $i18n{confirm}
+ </paper-button>
+ </div>
+ </dialog>
+ </template>
+ <script src="network_proxy_section.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.js b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.js
new file mode 100644
index 00000000000..4a637c97d29
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.js
@@ -0,0 +1,132 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview Polymer element hosting <network-proxy> in the internet
+ * detail page. This element is responsible for setting 'Allow proxies for
+ * shared networks'.
+ */
+Polymer({
+ is: 'network-proxy-section',
+
+ behaviors: [
+ CrPolicyNetworkBehavior,
+ I18nBehavior,
+ PrefsBehavior,
+ settings.RouteObserverBehavior,
+ ],
+
+ properties: {
+ /**
+ * The network properties dictionary containing the proxy properties to
+ * display and modify.
+ * @type {!CrOnc.NetworkProperties|undefined}
+ */
+ networkProperties: Object,
+
+ /**
+ * Reflects prefs.settings.use_shared_proxies for data binding.
+ * @private
+ */
+ useSharedProxies_: Boolean,
+ },
+
+ observers: [
+ 'useSharedProxiesChanged_(prefs.settings.use_shared_proxies.value)',
+ ],
+
+ /** @protected settings.RouteObserverBehavior */
+ currentRouteChanged: function(newRoute) {
+ if (newRoute == settings.routes.NETWORK_DETAIL)
+ /** @type {NetworkProxyElement} */ (this.$$('network-proxy')).reset();
+ },
+
+ /** @private */
+ useSharedProxiesChanged_: function() {
+ var pref = this.getPref('settings.use_shared_proxies');
+ this.useSharedProxies_ = !!pref && !!pref.value;
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ isShared_: function() {
+ return this.networkProperties.Source == 'Device' ||
+ this.networkProperties.Source == 'DevicePolicy';
+ },
+
+ /**
+ * @return {!CrOnc.ManagedProperty|undefined}
+ * @private
+ */
+ getProxySettingsTypeProperty_: function() {
+ return /** @type {!CrOnc.ManagedProperty|undefined} */ (
+ this.get('ProxySettings.Type', this.networkProperties));
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ shouldShowNetworkPolicyIndicator_: function() {
+ var property = this.getProxySettingsTypeProperty_();
+ return !!property && !this.isExtensionControlled(property) &&
+ this.isNetworkPolicyEnforced(property);
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ shouldShowExtensionIndicator_: function() {
+ var property = this.getProxySettingsTypeProperty_();
+ return !!property && this.isExtensionControlled(property);
+ },
+
+ /**
+ * @param {!CrOnc.ManagedProperty} property
+ * @return {boolean}
+ * @private
+ */
+ shouldShowAllowShared_: function(property) {
+ return !this.isControlled(property) && this.isShared_();
+ },
+
+ /**
+ * Handles the change event for the shared proxy checkbox. Shows a
+ * confirmation dialog.
+ * @param {!Event} event
+ * @private
+ */
+ onAllowSharedProxiesChange_: function(event) {
+ this.$.confirmAllowSharedDialog.showModal();
+ },
+
+ /**
+ * Handles the shared proxy confirmation dialog 'Confirm' button.
+ * @private
+ */
+ onAllowSharedDialogConfirm_: function() {
+ /** @type {!SettingsCheckboxElement} */ (this.$.allowShared)
+ .sendPrefChange();
+ this.$.confirmAllowSharedDialog.close();
+ },
+
+ /**
+ * Handles the shared proxy confirmation dialog 'Cancel' button or a cancel
+ * event.
+ * @private
+ */
+ onAllowSharedDialogCancel_: function() {
+ /** @type {!SettingsCheckboxElement} */ (this.$.allowShared)
+ .resetToPrefValue();
+ this.$.confirmAllowSharedDialog.close();
+ },
+
+ /** @private */
+ onAllowSharedDialogClose_: function() {
+ cr.ui.focusWithoutInk(assert(this.$$('#allowShared')));
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.html b/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.html
index 071e045c55d..8f4df0be364 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.html
@@ -96,8 +96,8 @@
<dialog is="cr-dialog" id="enterPinDialog" close-text="$i18n{close}"
on-cancel="onEnterPinDialogCancel_"
on-close="onEnterPinDialogClose_">
- <div class="title" slot="title">$i18n{networkSimEnterPinTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{networkSimEnterPinTitle}</div>
+ <div slot="body">
<paper-input id="enterPin" class="pin" no-label-float autofocus
label="$i18n{networkSimEnterPin}">
<iron-a11y-keys keys="enter" on-keys-pressed="sendEnterPin_">
@@ -107,7 +107,7 @@
[[getErrorMsg_(error_, networkProperties)]]
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button on-tap="sendEnterPin_">
$i18n{networkSimEnter}
</paper-button>
@@ -117,8 +117,8 @@
<!-- Change PIN dialog -->
<dialog is="cr-dialog" id="changePinDialog" close-text="$i18n{close}"
on-close="onChangePinDialogClose_">
- <div class="title" slot="title">$i18n{networkSimChangePinTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{networkSimChangePinTitle}</div>
+ <div slot="body">
<paper-input id="changePinOld" class="pin" no-label-float autofocus
label="$i18n{networkSimEnterOldPin}">
</paper-input>
@@ -134,7 +134,7 @@
[[getErrorMsg_(error_, networkProperties)]]
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button on-tap="sendChangePin_">
$i18n{networkSimChange}
</paper-button>
@@ -144,8 +144,8 @@
<!-- Unlock PIN dialog -->
<dialog is="cr-dialog" id="unlockPinDialog" close-text="$i18n{close}"
on-close="onUnlockPinDialogClose_">
- <div class="title" slot="title">$i18n{networkSimLockedTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{networkSimLockedTitle}</div>
+ <div slot="body">
<paper-input id="unlockPin" class="pin" no-label-float autofocus
label="$i18n{networkSimEnterPin}">
<iron-a11y-keys keys="enter" on-keys-pressed="sendUnlockPin_">
@@ -155,7 +155,7 @@
[[getErrorMsg_(error_, networkProperties)]]
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button on-tap="sendUnlockPin_">
$i18n{networkSimUnlock}
</paper-button>
@@ -165,8 +165,8 @@
<!-- Unlock PUK dialog -->
<dialog is="cr-dialog" id="unlockPukDialog" close-text="$i18n{close}"
on-close="onUnlockPinDialogClose_">
- <div class="title" slot="title">$i18n{networkSimLockedTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{networkSimLockedTitle}</div>
+ <div slot="body">
<div>
Enter the 8-digit PIN Unblocking Key provided by your carrier
</div>
@@ -188,7 +188,7 @@
[[getErrorMsg_(error_, networkProperties)]]
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button on-tap="sendUnlockPuk_">
$i18n{networkSimUnlock}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.js b/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.js
index 06a1c3c312d..cb0eb9cbd05 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_siminfo.js
@@ -78,7 +78,7 @@ Polymer({
var simLockStatus = this.networkProperties.Cellular.SIMLockStatus;
this.pukRequired_ =
!!simLockStatus && simLockStatus.LockType == CrOnc.LockType.PUK;
- this.lockEnabled_ = simLockStatus.LockEnabled;
+ this.lockEnabled_ = !!simLockStatus && simLockStatus.LockEnabled;
},
/** @private */
@@ -145,7 +145,7 @@ Polymer({
currentPin: pin,
requirePin: this.sendSimLockEnabled_,
});
- this.networkingPrivate.setCellularSimState(guid, simState, function() {
+ this.networkingPrivate.setCellularSimState(guid, simState, () => {
if (chrome.runtime.lastError) {
this.error_ = ErrorType.INCORRECT_PIN;
this.$.enterPin.inputElement.select();
@@ -153,7 +153,7 @@ Polymer({
this.error_ = ErrorType.NONE;
this.$.enterPinDialog.close();
}
- }.bind(this));
+ });
},
/**
@@ -164,7 +164,7 @@ Polymer({
onChangePinTap_: function(event) {
if (!this.networkProperties || !this.networkProperties.Cellular)
return;
- event.preventDefault();
+ event.stopPropagation();
this.error_ = ErrorType.NONE;
this.$.changePinOld.value = '';
this.$.changePinNew1.value = '';
@@ -188,7 +188,7 @@ Polymer({
currentPin: this.$.changePinOld.value,
newPin: newPin
});
- this.networkingPrivate.setCellularSimState(guid, simState, function() {
+ this.networkingPrivate.setCellularSimState(guid, simState, () => {
if (chrome.runtime.lastError) {
this.error_ = ErrorType.INCORRECT_PIN;
this.$.changePinOld.inputElement.select();
@@ -196,19 +196,21 @@ Polymer({
this.error_ = ErrorType.NONE;
this.$.changePinDialog.close();
}
- }.bind(this));
+ });
},
/**
- * Opens the Unlock PIN dialog.
+ * Opens the Unlock PIN / PUK dialog.
* @param {!Event} event
* @private
*/
onUnlockPinTap_: function(event) {
- event.preventDefault();
- this.error_ = ErrorType.NONE;
- this.$.unlockPin.value = '';
- this.$.unlockPinDialog.showModal();
+ event.stopPropagation();
+ if (this.pukRequired_) {
+ this.showUnlockPukDialog_();
+ } else {
+ this.showUnlockPinDialog_();
+ }
},
/**
@@ -222,7 +224,7 @@ Polymer({
if (!this.validatePin_(pin))
return;
- this.networkingPrivate.unlockCellularSim(guid, pin, '', function() {
+ this.networkingPrivate.unlockCellularSim(guid, pin, '', () => {
if (chrome.runtime.lastError) {
this.error_ = ErrorType.INCORRECT_PIN;
this.$.unlockPin.inputElement.select();
@@ -230,7 +232,14 @@ Polymer({
this.error_ = ErrorType.NONE;
this.$.unlockPinDialog.close();
}
- }.bind(this));
+ });
+ },
+
+ /** @private */
+ showUnlockPinDialog_: function() {
+ this.error_ = ErrorType.NONE;
+ this.$.unlockPin.value = '';
+ this.$.unlockPinDialog.showModal();
},
/** @private */
@@ -256,7 +265,7 @@ Polymer({
if (!this.validatePin_(pin, this.$.unlockPin2.value))
return;
- this.networkingPrivate.unlockCellularSim(guid, pin, puk, function() {
+ this.networkingPrivate.unlockCellularSim(guid, pin, puk, () => {
if (chrome.runtime.lastError) {
this.error_ = ErrorType.INCORRECT_PUK;
this.$.unlockPuk.inputElement.select();
@@ -264,7 +273,7 @@ Polymer({
this.error_ = ErrorType.NONE;
this.$.unlockPukDialog.close();
}
- }.bind(this));
+ });
},
/**
@@ -310,10 +319,10 @@ Polymer({
else
return 'UNKNOWN ERROR';
var retriesLeft =
- this.get(
- 'Cellular.SIMLockStatus.RetriesLeft', this.networkProperties) ||
- 0;
- msg += ' Retries left: ' + retriesLeft.toString();
+ this.get('Cellular.SIMLockStatus.RetriesLeft', this.networkProperties);
+ if (retriesLeft) {
+ msg += ' Retries left: ' + retriesLeft.toString();
+ }
return msg;
},
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary.js b/chromium/chrome/browser/resources/settings/internet_page/network_summary.js
index 3f83c7af26a..a1c6dea2665 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_summary.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary.js
@@ -223,10 +223,10 @@ Polymer({
*/
getNetworkLists_: function() {
// First get the device states.
- this.networkingPrivate.getDeviceStates(function(deviceStates) {
+ this.networkingPrivate.getDeviceStates(deviceStates => {
// Second get the network states.
this.getNetworkStates_(deviceStates);
- }.bind(this));
+ });
},
/**
@@ -242,9 +242,9 @@ Polymer({
visible: true,
configured: false
};
- this.networkingPrivate.getNetworks(filter, function(networkStates) {
+ this.networkingPrivate.getNetworks(filter, networkStates => {
this.updateNetworkStates_(networkStates, deviceStates);
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js
index 2cafa7b7dbc..656d66606cd 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js
@@ -72,18 +72,25 @@ Polymer({
var name = CrOnc.getNetworkName(activeNetworkState);
if (state)
return this.getConnectionStateText_(state, name);
+ // No network state, use device state.
if (deviceState) {
- if (deviceState.State == CrOnc.DeviceState.ENABLING)
- return this.i18n('internetDeviceEnabling');
- if (deviceState.Type == CrOnc.Type.CELLULAR && deviceState.Scanning)
- return this.i18n('internetMobileSearching');
- if (deviceState.Type == CrOnc.Type.TETHER &&
- deviceState.State == CrOnc.DeviceState.UNINITIALIZED) {
- return this.i18n('tetherEnableBluetooth');
+ // Type specific scanning or initialization states.
+ if (deviceState.Type == CrOnc.Type.CELLULAR) {
+ if (deviceState.Scanning)
+ return this.i18n('internetMobileSearching');
+ if (deviceState.State == CrOnc.DeviceState.UNINITIALIZED)
+ return this.i18n('internetDeviceInitializing');
+ } else if (deviceState.Type == CrOnc.Type.TETHER) {
+ if (deviceState.State == CrOnc.DeviceState.UNINITIALIZED)
+ return this.i18n('tetherEnableBluetooth');
}
+ // Enabled or enabling states.
if (deviceState.State == CrOnc.DeviceState.ENABLED)
return CrOncStrings.networkListItemNotConnected;
+ if (deviceState.State == CrOnc.DeviceState.ENABLING)
+ return this.i18n('internetDeviceEnabling');
}
+ // No device or unknown device state, use 'off'.
return this.i18n('deviceOff');
},
@@ -131,9 +138,12 @@ Polymer({
this.deviceIsEnabled_(deviceState)) {
return false;
}
- return deviceState.SimPresent === false ||
- deviceState.SimLockType == CrOnc.LockType.PIN ||
- deviceState.SimLockType == CrOnc.LockType.PUK;
+ if (deviceState.SIMPresent === false)
+ return true;
+ var simLockType =
+ deviceState.SIMLockStatus ? deviceState.SIMLockStatus.LockType : '';
+ return simLockType == CrOnc.LockType.PIN ||
+ simLockType == CrOnc.LockType.PUK;
},
/**
@@ -150,11 +160,8 @@ Polymer({
GUID: '',
Type: CrOnc.Type.CELLULAR,
Cellular: {
- SIMLockStatus: {
- LockType: deviceState.SimLockType || '',
- LockEnabled: deviceState.SimLockType != CrOnc.LockType.NONE,
- },
- SIMPresent: deviceState.SimPresent,
+ SIMLockStatus: deviceState.SIMLockStatus,
+ SIMPresent: deviceState.SIMPresent,
},
};
},
diff --git a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html
index 637c6b0425e..67d7e60dba4 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html
@@ -10,21 +10,15 @@
<dom-module id="tether-connection-dialog">
<template>
<style include="settings-shared">
- /*
- Add extra properties to the .title class originally part of cr-dialog
- */
- .title {
+ [slot=title] {
margin-top: 9px;
}
- /*
- Add extra properties to the .body class originally part of cr-dialog
- */
- .body {
+ [slot=body] {
border-top: solid 2px rgba(0, 0, 0, .14);
}
- .body > * {
+ [slot=body] > * {
margin-left: 5px;
}
@@ -66,8 +60,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{tetherConnectionDialogTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{tetherConnectionDialogTitle}</div>
+ <div slot="body">
<span id="availability-title">
$i18n{tetherConnectionAvailableDeviceTitle}
</span>
@@ -101,7 +95,7 @@
</li>
</ul>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onNotNowTap_">
$i18n{tetherConnectionNotNowButton}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html b/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html
index d3591ddfa97..6a6a1512872 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html
+++ b/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html
@@ -12,7 +12,7 @@
<dom-module id="settings-add-languages-dialog">
<template>
<style include="settings-shared">
- .body {
+ [slot=body] {
-webkit-padding-end: 0 !important;
display: flex;
flex-direction: column;
@@ -40,12 +40,12 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{addLanguagesDialogTitle}</div>
- <div class="body" slot="body" scrollable>
+ <div slot="title">$i18n{addLanguagesDialogTitle}</div>
+ <div slot="body" scrollable>
<settings-subpage-search label="[[searchLabel]]"
on-search-changed="onSearchChanged_" autofocus>
</settings-subpage-search>
- <iron-list class="ripple-padding" scroll-target="[[$$('.body')]]"
+ <iron-list class="ripple-padding" scroll-target="[[$$('[slot=body]')]]"
items="[[getLanguages_(
languages.supported, languages.enabled.*, filterValue_)]]">
<template>
@@ -58,16 +58,14 @@
</template>
</iron-list>
</div>
- <div class="button-container" slot="button-container">
- <div class="action-buttons">
- <paper-button class="cancel-button" on-tap="onCancelButtonTap_">
- $i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-tap="onActionButtonTap_"
- disabled="[[disableActionButton_]]">
- $i18n{add}
- </paper-button>
- </div>
+ <div slot="button-container">
+ <paper-button class="cancel-button" on-tap="onCancelButtonTap_">
+ $i18n{cancel}
+ </paper-button>
+ <paper-button class="action-button" on-tap="onActionButtonTap_"
+ disabled="[[disableActionButton_]]">
+ $i18n{add}
+ </paper-button>
</div>
</dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.js b/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.js
index d3fda59dc77..d4bc264f1b1 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.js
@@ -65,7 +65,7 @@ Polymer({
getLanguages_: function() {
var filterValue =
this.filterValue_ ? this.filterValue_.toLowerCase() : null;
- return this.languages.supported.filter(function(language) {
+ return this.languages.supported.filter(language => {
var isAvailableLanguage =
!this.languageHelper.isLanguageEnabled(language.code);
@@ -77,7 +77,7 @@ Polymer({
return language.displayName.toLowerCase().includes(filterValue) ||
language.nativeDisplayName.toLowerCase().includes(filterValue);
- }.bind(this));
+ });
},
/**
@@ -134,8 +134,8 @@ Polymer({
*/
onActionButtonTap_: function() {
this.$.dialog.close();
- this.languagesToAdd_.forEach(function(languageCode) {
+ this.languagesToAdd_.forEach(languageCode => {
this.languageHelper.enableLanguage(languageCode);
- }.bind(this));
+ });
},
});
diff --git a/chromium/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp
index eb2d4790659..446e9c3a2b0 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp
@@ -42,7 +42,6 @@
'<(DEPTH)/ui/webui/resources/cr_elements/cr_action_menu/compiled_resources2.gyp:cr_action_menu',
'<(DEPTH)/ui/webui/resources/cr_elements/cr_expand_button/compiled_resources2.gyp:cr_expand_button',
'<(DEPTH)/ui/webui/resources/cr_elements/cr_lazy_render/compiled_resources2.gyp:cr_lazy_render',
- '<(DEPTH)/ui/webui/resources/js/chromeos/compiled_resources2.gyp:ui_account_tweaks',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
diff --git a/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js b/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
index bfe73dbdeeb..4587d0322d6 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
@@ -42,9 +42,9 @@ Polymer({
/** @type {!LanguageSettingsPrivate} */
(chrome.languageSettingsPrivate);
- this.languageSettingsPrivate.getSpellcheckWords(function(words) {
+ this.languageSettingsPrivate.getSpellcheckWords(words => {
this.words_ = words;
- }.bind(this));
+ });
this.languageSettingsPrivate.onCustomDictionaryChanged.addListener(
this.onCustomDictionaryChanged_.bind(this));
diff --git a/chromium/chrome/browser/resources/settings/languages_page/languages.js b/chromium/chrome/browser/resources/settings/languages_page/languages.js
index e7bf247360b..36da86dce34 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/languages.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/languages.js
@@ -180,39 +180,39 @@ Polymer({
promises[0] = CrSettingsPrefs.initialized;
// Get the language list.
- promises[1] = new Promise(function(resolve) {
+ promises[1] = new Promise(resolve => {
this.languageSettingsPrivate_.getLanguageList(resolve);
- }.bind(this));
+ });
// Get the translate target language.
- promises[2] = new Promise(function(resolve) {
+ promises[2] = new Promise(resolve => {
this.languageSettingsPrivate_.getTranslateTargetLanguage(resolve);
- }.bind(this));
+ });
if (cr.isChromeOS) {
- promises[3] = new Promise(function(resolve) {
+ promises[3] = new Promise(resolve => {
this.languageSettingsPrivate_.getInputMethodLists(function(lists) {
resolve(lists.componentExtensionImes.concat(
lists.thirdPartyExtensionImes));
});
- }.bind(this));
+ });
- promises[4] = new Promise(function(resolve) {
+ promises[4] = new Promise(resolve => {
this.inputMethodPrivate_.getCurrentInputMethod(resolve);
- }.bind(this));
+ });
}
if (cr.isWindows || cr.isChromeOS) {
// Fetch the starting UI language, which affects which actions should be
// enabled.
promises.push(this.browserProxy_.getProspectiveUILanguage().then(
- function(prospectiveUILanguage) {
+ prospectiveUILanguage => {
this.originalProspectiveUILanguage_ =
prospectiveUILanguage || window.navigator.language;
- }.bind(this)));
+ }));
}
- Promise.all(promises).then(function(results) {
+ Promise.all(promises).then(results => {
if (!this.isConnected) {
// Return early if this element was detached from the DOM before this
// async callback executes (can happen during testing).
@@ -223,7 +223,7 @@ Polymer({
// which only exist for ChromeOS.
this.createModel_(results[1], results[2], results[3], results[4]);
this.resolver_.resolve();
- }.bind(this));
+ });
if (cr.isChromeOS) {
this.boundOnInputMethodChanged_ = this.onInputMethodChanged_.bind(this);
@@ -444,9 +444,7 @@ Polymer({
// Return only supported input methods.
return enabledInputMethodIds
- .map(function(id) {
- return this.supportedInputMethodMap_.get(id);
- }.bind(this))
+ .map(id => this.supportedInputMethodMap_.get(id))
.filter(function(inputMethod) {
return !!inputMethod;
});
@@ -565,11 +563,9 @@ Polymer({
var inputMethods = this.languageInputMethods_.get(languageCode) || [];
for (var i = 0; i < inputMethods.length; i++) {
var inputMethod = inputMethods[i];
- var supportsOtherEnabledLanguages =
- inputMethod.languageCodes.some(function(otherLanguageCode) {
- return otherLanguageCode != languageCode &&
- this.isLanguageEnabled(otherLanguageCode);
- }.bind(this));
+ var supportsOtherEnabledLanguages = inputMethod.languageCodes.some(
+ otherLanguageCode => otherLanguageCode != languageCode &&
+ this.isLanguageEnabled(otherLanguageCode));
if (!supportsOtherEnabledLanguages)
this.removeInputMethod(inputMethod.id);
}
diff --git a/chromium/chrome/browser/resources/settings/languages_page/languages_page.html b/chromium/chrome/browser/resources/settings/languages_page/languages_page.html
index ed0b0c0dc61..cfa11d4a722 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/languages_page.html
+++ b/chromium/chrome/browser/resources/settings/languages_page/languages_page.html
@@ -28,7 +28,6 @@
</if>
<if expr="chromeos">
-<link rel="import" href="chrome://resources/html/chromeos/ui_account_tweaks.html">
<link rel="import" href="manage_input_methods_page.html">
</if>
@@ -63,7 +62,7 @@
}
paper-checkbox.dropdown-item {
- --checkbox-margin-start: 0;
+ -webkit-margin-start: 0;
}
button[is='paper-icon-button-light'].icon-external {
@@ -145,12 +144,10 @@
</a>
</div>
</div>
- <div class="settings-box first">
- <settings-toggle-button id="offerTranslateOtherLangs" class="start"
- pref="{{prefs.translate.enabled}}"
- label="$i18n{offerToEnableTranslate}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="offerTranslateOtherLanguages"
+ class="first" pref="{{prefs.translate.enabled}}"
+ label="$i18n{offerToEnableTranslate}">
+ </settings-toggle-button>
</iron-collapse>
<if expr="chromeos">
<div id="manageInputMethodsSubpageTrigger"
@@ -198,12 +195,10 @@
aria-describedby="customSpelling"></button>
</div>
</div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.language.ime_menu_activated}}"
- label="$i18n{showImeMenu}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.settings.language.ime_menu_activated}}"
+ label="$i18n{showImeMenu}">
+ </settings-toggle-button>
</iron-collapse>
</if>
<if expr="not is_macosx">
diff --git a/chromium/chrome/browser/resources/settings/languages_page/languages_page.js b/chromium/chrome/browser/resources/settings/languages_page/languages_page.js
index fa248dd9e77..4c0782d2f48 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/languages_page.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/languages_page.js
@@ -14,6 +14,12 @@ cr.exportPath('settings');
*/
settings.kMenuCloseDelay = 100;
+/**
+ * Name of the language setting is shown uma histogram.
+ * @type {string}
+ */
+const LANGUAGE_SETTING_IS_SHOWN_UMA_NAME = 'Translate.LanguageSettingsIsShown';
+
(function() {
'use strict';
@@ -58,6 +64,15 @@ Polymer({
*/
detailLanguage_: Object,
+ /**
+ * Whether the language settings list is opened.
+ * @private
+ */
+ languagesOpened_: {
+ type: Boolean,
+ observer: 'onLanguagesOpenedChanged_',
+ },
+
/** @private */
showAddLanguagesDialog_: Boolean,
@@ -96,10 +111,10 @@ Polymer({
this.showAddLanguagesDialog_ = true;
this.async(function() {
var dialog = this.$$('settings-add-languages-dialog');
- dialog.addEventListener('close', function() {
+ dialog.addEventListener('close', () => {
this.showAddLanguagesDialog_ = false;
cr.ui.focusWithoutInk(assert(this.$.addLanguages));
- }.bind(this));
+ });
});
},
@@ -162,10 +177,8 @@ Polymer({
menu.querySelector('#uiLanguageItem').hidden = true;
// The UI language choice doesn't persist for guests.
- if (uiAccountTweaks.UIAccountTweaks.loggedInAsGuest() ||
- uiAccountTweaks.UIAccountTweaks.loggedInAsPublicAccount()) {
+ if (loadTimeData.getBoolean('isGuest'))
menu.querySelector('#uiLanguageItem').hidden = true;
- }
},
/**
@@ -526,6 +539,19 @@ Polymer({
},
/**
+ * @param {boolean} newVal The new value of languagesOpened_.
+ * @param {boolean} oldVal The old value of languagesOpened_.
+ * @private
+ */
+ onLanguagesOpenedChanged_: function(newVal, oldVal) {
+ if (!oldVal && newVal) {
+ chrome.send(
+ 'metricsHandler:recordBooleanHistogram',
+ [LANGUAGE_SETTING_IS_SHOWN_UMA_NAME, true]);
+ }
+ },
+
+ /**
* Closes the shared action menu after a short delay, so when a checkbox is
* tapped it can be seen to change state before disappearing.
* @private
diff --git a/chromium/chrome/browser/resources/settings/lazy_load.html b/chromium/chrome/browser/resources/settings/lazy_load.html
index 2853b3c1eae..d5582b2f6f7 100644
--- a/chromium/chrome/browser/resources/settings/lazy_load.html
+++ b/chromium/chrome/browser/resources/settings/lazy_load.html
@@ -1,15 +1,20 @@
-<link rel="import" href="a11y_page/a11y_page.html">
-<link rel="import" href="downloads_page/downloads_page.html">
-<link rel="import" href="languages_page/languages_page.html">
-<link rel="import" href="passwords_and_forms_page/passwords_and_forms_page.html">
-<link rel="import" href="printing_page/printing_page.html">
-<link rel="import" href="privacy_page/privacy_page.html">
-<link rel="import" href="reset_page/reset_page.html">
+<html>
+<head></head>
+<body>
+ <link rel="import" href="a11y_page/a11y_page.html">
+ <link rel="import" href="downloads_page/downloads_page.html">
+ <link rel="import" href="languages_page/languages_page.html">
+ <link rel="import" href="passwords_and_forms_page/passwords_and_forms_page.html">
+ <link rel="import" href="printing_page/printing_page.html">
+ <link rel="import" href="privacy_page/privacy_page.html">
+ <link rel="import" href="reset_page/reset_page.html">
-<if expr="chromeos">
-<link rel="import" href="date_time_page/date_time_page.html">
-</if>
+ <if expr="chromeos">
+ <link rel="import" href="date_time_page/date_time_page.html">
+ </if>
-<if expr="not chromeos">
-<link rel="import" href="system_page/system_page.html">
-</if>
+ <if expr="not chromeos">
+ <link rel="import" href="system_page/system_page.html">
+ </if>
+</body>
+</html>
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp
index 725d084e002..e68bb1a34a6 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp
@@ -14,7 +14,8 @@
{
'target_name': 'on_startup_page',
'dependencies': [
- '../compiled_resources2.gyp:route',
+ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
+ 'on_startup_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -27,7 +28,6 @@
'<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_without_ink',
'<(DEPTH)/ui/webui/resources/cr_elements/compiled_resources2.gyp:cr_scrollable_behavior',
'<(EXTERNS_GYP):settings_private',
- 'on_startup_browser_proxy',
'startup_urls_page_browser_proxy',
'startup_url_entry',
],
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html b/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html
index e5cac2098c2..40bfadfde9d 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html
@@ -1,34 +1,52 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="../controls/controlled_radio_button.html">
+<link rel="import" href="../controls/extension_controlled_indicator.html">
+<link rel="import" href="../controls/settings_radio_group.html">
+<link rel="import" href="on_startup_browser_proxy.html">
<link rel="import" href="startup_urls_page.html">
+<link rel="import" href="../settings_shared_css.html">
<dom-module id="settings-on-startup-page">
<template>
- <style include="settings-shared"></style>
- <settings-animated-pages id="pages" section="onStartup"
- focus-config="[[focusConfig_]]">
- <neon-animatable route-path="default">
- <div class="settings-box first two-line"
- id="manage-startup-urls-subpage-trigger"
- on-tap="onManageStartupUrls_" actionable>
- <div class="start">
- $i18n{onStartupManage}
- <div class="secondary">$i18n{onStartupDescription}</div>
- </div>
- <button class="subpage-arrow" is="paper-icon-button-light"
- aria-label="$i18n{onStartupManage}"></button>
- </div>
- </neon-animatable>
- <template is="dom-if" route-path="/startupUrls">
- <settings-subpage
- associated-control="[[$$('#manage-startup-urls-subpage-trigger')]]"
- page-title="$i18n{onStartupManage}">
- <settings-startup-urls-page prefs="{{prefs}}">
- </settings-startup-urls-page>
- </settings-subpage>
- </template>
- </settings-animated-pages>
+ <style include="settings-shared">
+ .block {
+ display: block;
+ }
+ </style>
+ <div class="settings-box block first">
+ <settings-radio-group id="onStartupRadioGroup"
+ pref="{{prefs.session.restore_on_startup}}">
+ <controlled-radio-button name="[[prefValues_.OPEN_NEW_TAB]]"
+ pref="[[prefs.session.restore_on_startup]]"
+ label="$i18n{onStartupOpenNewTab}"
+ no-extension-indicator>
+ </controlled-radio-button>
+ <template is="dom-if" if="[[showIndicator_(
+ ntpExtension_, prefs.session.restore_on_startup.value)]]">
+ <extension-controlled-indicator
+ extension-id="[[ntpExtension_.id]]"
+ extension-name="[[ntpExtension_.name]]"
+ extension-can-be-disabled="[[ntpExtension_.canBeDisabled]]"
+ on-extension-disable="getNtpExtension_">
+ </extension-controlled-indicator>
+ </template>
+ <controlled-radio-button name="[[prefValues_.CONTINUE]]"
+ pref="[[prefs.session.restore_on_startup]]"
+ label="$i18n{onStartupContinue}">
+ </controlled-radio-button>
+ <controlled-radio-button name="[[prefValues_.OPEN_SPECIFIC]]"
+ pref="[[prefs.session.restore_on_startup]]"
+ label="$i18n{onStartupOpenSpecific}">
+ </controlled-radio-button>
+ </settings-radio-group>
+ </div>
+ <template is="dom-if"
+ if="[[showStartupUrls_(prefs.session.restore_on_startup.value)]]">
+ <settings-startup-urls-page prefs="[[prefs]]">
+ </settings-startup-urls-page>
+ </template>
</template>
<script src="on_startup_page.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.js b/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.js
index 38cdc3ccf60..26484951dcf 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.js
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.js
@@ -9,12 +9,66 @@
Polymer({
is: 'settings-on-startup-page',
+ behaviors: [WebUIListenerBehavior],
+
properties: {
- prefs: Object,
+ prefs: {
+ type: Object,
+ notify: true,
+ },
+
+ /** @private {?NtpExtension} */
+ ntpExtension_: Object,
+
+ /**
+ * Enum values for the 'session.restore_on_startup' preference.
+ * @private {!Object<string, number>}
+ */
+ prefValues_: {
+ readOnly: true,
+ type: Object,
+ value: {
+ CONTINUE: 1,
+ OPEN_NEW_TAB: 5,
+ OPEN_SPECIFIC: 4,
+ },
+ },
+ },
+
+ /** @override */
+ attached: function() {
+ this.getNtpExtension_();
+ this.addWebUIListener('update-ntp-extension', ntpExtension => {
+ // Note that |ntpExtension| is empty if there is no NTP extension.
+ this.ntpExtension_ = ntpExtension;
+ });
},
/** @private */
- onManageStartupUrls_: function() {
- settings.navigateTo(settings.routes.STARTUP_URLS);
+ getNtpExtension_: function() {
+ settings.OnStartupBrowserProxyImpl.getInstance().getNtpExtension().then(
+ function(ntpExtension) {
+ this.ntpExtension_ = ntpExtension;
+ }.bind(this));
+ },
+
+ /**
+ * @param {?NtpExtension} ntpExtension
+ * @param {number} restoreOnStartup Value of prefs.session.restore_on_startup.
+ * @return {boolean}
+ * @private
+ */
+ showIndicator_: function(ntpExtension, restoreOnStartup) {
+ return !!ntpExtension && restoreOnStartup == this.prefValues_.OPEN_NEW_TAB;
+ },
+
+ /**
+ * Determine whether to show the user defined startup pages.
+ * @param {number} restoreOnStartup Enum value from prefValues_.
+ * @return {boolean} Whether the open specific pages is selected.
+ * @private
+ */
+ showStartupUrls_: function(restoreOnStartup) {
+ return restoreOnStartup == this.prefValues_.OPEN_SPECIFIC;
},
});
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html
index dc36820b20d..7fb4e0bb955 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html
@@ -10,19 +10,17 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">[[dialogTitle_]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[dialogTitle_]]</div>
+ <div slot="body">
<paper-input always-float-label id="url" label="$i18n{onStartupSiteUrl}"
- value="{{url_}}" on-input="validate_" autofocus>
+ value="{{url_}}" on-input="validate_" spellcheck="false" autofocus>
</paper-input>
</div>
- <div class="button-container" slot="button-container">
- <div class="action-buttons">
- <paper-button class="cancel-button" on-tap="onCancelTap_"
- id="cancel">$i18n{cancel}</paper-button>
- <paper-button id="actionButton" class="action-button"
- on-tap="onActionButtonTap_">[[actionButtonText_]]</paper-button>
- </div>
+ <div slot="button-container">
+ <paper-button class="cancel-button" on-tap="onCancelTap_"
+ id="cancel">$i18n{cancel}</paper-button>
+ <paper-button id="actionButton" class="action-button"
+ on-tap="onActionButtonTap_">[[actionButtonText_]]</paper-button>
</div>
</dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.js b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.js
index 706bf18fcb5..bed14109cdb 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.js
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.js
@@ -59,18 +59,18 @@ Polymer({
this.browserProxy_.editStartupPage(this.model.modelIndex, this.url_) :
this.browserProxy_.addStartupPage(this.url_);
- whenDone.then(function(success) {
+ whenDone.then(success => {
if (success)
this.$.dialog.close();
// If the URL was invalid, there is nothing to do, just leave the dialog
// open and let the user fix the URL or cancel.
- }.bind(this));
+ });
},
/** @private */
validate_: function() {
- this.browserProxy_.validateStartupPage(this.url_).then(function(isValid) {
+ this.browserProxy_.validateStartupPage(this.url_).then(isValid => {
this.$.actionButton.disabled = !isValid;
- }.bind(this));
+ });
},
});
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_entry.html b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_entry.html
index 92d1993e99c..cf1a7a9cf81 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_entry.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_entry.html
@@ -31,11 +31,10 @@
</button>
<template is="cr-lazy-render" id="menu">
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" on-tap="onEditTap_">
+ <button class="dropdown-item" on-tap="onEditTap_">
$i18n{edit}
</button>
- <button class="dropdown-item" role="option" id="remove"
- on-tap="onRemoveTap_">
+ <button class="dropdown-item" id="remove" on-tap="onRemoveTap_">
$i18n{onStartupRemove}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html b/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
index d1f8e9a3e15..0fc0746165b 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
@@ -8,11 +8,8 @@
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_scrollable_behavior.html">
-<link rel="import" href="../controls/controlled_radio_button.html">
<link rel="import" href="../controls/extension_controlled_indicator.html">
-<link rel="import" href="../controls/settings_radio_group.html">
<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="on_startup_browser_proxy.html">
<link rel="import" href="startup_url_dialog.html">
<link rel="import" href="startup_url_entry.html">
<link rel="import" href="startup_urls_page_browser_proxy.html">
@@ -33,79 +30,44 @@
cursor: default;
}
</style>
- <div class="settings-box first">
- <h2>$i18n{onStartupPages}</h2>
- </div>
- <div class="settings-box first">
- <div class="start">
- <settings-radio-group id="onStartupRadioGroup"
- pref="{{prefs.session.restore_on_startup}}">
- <controlled-radio-button name="[[prefValues_.OPEN_NEW_TAB]]"
- pref="[[prefs.session.restore_on_startup]]"
- label="$i18n{onStartupOpenNewTab}"
- no-extension-indicator>
- </controlled-radio-button>
- <template is="dom-if" if="[[showIndicator_(
- ntpExtension_, prefs.session.restore_on_startup.value)]]">
- <extension-controlled-indicator
- extension-id="[[ntpExtension_.id]]"
- extension-name="[[ntpExtension_.name]]"
- extension-can-be-disabled="[[ntpExtension_.canBeDisabled]]"
- on-extension-disable="getNtpExtension_">
- </extension-controlled-indicator>
+ <div id="outer" class="layout vertical flex vertical-list">
+ <div id="container" class="scroll-container" scrollable>
+ <iron-list items="[[startupPages_]]" scroll-target="container"
+ preserve-focus risk-selection>
+ <template>
+ <settings-startup-url-entry model="[[item]]"
+ tabindex$="[[tabIndex]]" iron-list-tab-index="[[tabIndex]]"
+ last-focused="{{lastFocused_}}"
+ editable="[[shouldAllowUrlsEdit_(
+ prefs.session.startup_urls.enforcement)]]">
+ </settings-startup-url-entry>
</template>
- <controlled-radio-button name="[[prefValues_.CONTINUE]]"
- pref="[[prefs.session.restore_on_startup]]"
- label="$i18n{onStartupContinue}">
- </controlled-radio-button>
- <controlled-radio-button name="[[prefValues_.OPEN_SPECIFIC]]"
- pref="[[prefs.session.restore_on_startup]]"
- label="$i18n{onStartupOpenSpecific}">
- </controlled-radio-button>
- </settings-radio-group>
+ </iron-list>
</div>
- </div>
- <template is="dom-if"
- if="[[showStartupUrls_(prefs.session.restore_on_startup.value)]]">
- <div id="outer" class="layout vertical flex vertical-list">
- <div id="container" class="scroll-container" scrollable>
- <iron-list items="[[startupPages_]]" scroll-target="container"
- preserve-focus>
- <template>
- <settings-startup-url-entry model="[[item]]"
- tabindex$="[[tabIndex]]" iron-list-tab-index="[[tabIndex]]"
- last-focused="{{lastFocused_}}"
- editable="[[shouldAllowUrlsEdit_(
- prefs.session.startup_urls.enforcement)]]">
- </settings-startup-url-entry>
- </template>
- </iron-list>
+ <template is="dom-if" if="[[shouldAllowUrlsEdit_(
+ prefs.session.startup_urls.enforcement)]]" restamp>
+ <div class="list-item" id="addPage">
+ <a is="action-link" class="list-button" on-tap="onAddPageTap_">
+ $i18n{onStartupAddNewPage}
+ </a>
</div>
- <template is="dom-if" if="[[shouldAllowUrlsEdit_(
- prefs.session.startup_urls.enforcement)]]" restamp>
- <div class="list-item" id="addPage">
- <a is="action-link" class="list-button" on-tap="onAddPageTap_">
- $i18n{onStartupAddNewPage}
- </a>
- </div>
- <div class="list-item" id="useCurrentPages">
- <a is="action-link" class="list-button"
- on-tap="onUseCurrentPagesTap_">
- $i18n{onStartupUseCurrent}
- </a>
- </div>
- </template>
- <template is="dom-if" if="[[prefs.session.startup_urls.extensionId]]"
- restamp>
- <extension-controlled-indicator
- extension-id="[[prefs.session.startup_urls.extensionId]]"
- extension-name="[[prefs.session.startup_urls.controlledByName]]"
- extension-can-be-disabled="[[
- prefs.session.startup_urls.extensionCanBeDisabled]]">
- </extension-controlled-indicator>
- </template>
- </div>
- </template>
+ <div class="list-item" id="useCurrentPages">
+ <a is="action-link" class="list-button"
+ on-tap="onUseCurrentPagesTap_">
+ $i18n{onStartupUseCurrent}
+ </a>
+ </div>
+ </template>
+ <template is="dom-if" if="[[prefs.session.startup_urls.extensionId]]"
+ restamp>
+ <extension-controlled-indicator
+ extension-id="[[prefs.session.startup_urls.extensionId]]"
+ extension-name="[[prefs.session.startup_urls.controlledByName]]"
+ extension-can-be-disabled="[[
+ prefs.session.startup_urls.extensionCanBeDisabled]]">
+ </extension-controlled-indicator>
+ </template>
+ </div>
<template is="dom-if" if="[[showStartupUrlDialog_]]" restamp>
<settings-startup-url-dialog model="[[startupUrlDialogModel_]]"
on-close="destroyUrlDialog_">
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js b/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js
index 289ed08330f..c526302dee2 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js
@@ -13,10 +13,7 @@ Polymer({
behaviors: [CrScrollableBehavior, WebUIListenerBehavior],
properties: {
- prefs: {
- type: Object,
- notify: true,
- },
+ prefs: Object,
/**
* Pages to load upon browser startup.
@@ -32,23 +29,6 @@ Polymer({
/** @private {Object}*/
lastFocused_: Object,
-
- /** @private {?NtpExtension} */
- ntpExtension_: Object,
-
- /**
- * Enum values for the 'session.restore_on_startup' preference.
- * @private {!Object<string, number>}
- */
- prefValues_: {
- readOnly: true,
- type: Object,
- value: {
- CONTINUE: 1,
- OPEN_NEW_TAB: 5,
- OPEN_SPECIFIC: 4,
- },
- },
},
/** @private {?settings.StartupUrlsPageBrowserProxy} */
@@ -62,37 +42,23 @@ Polymer({
/** @override */
attached: function() {
- this.getNtpExtension_();
- this.addWebUIListener('update-ntp-extension', function(ntpExtension) {
- // Note that |ntpExtension| is empty if there is no NTP extension.
- this.ntpExtension_ = ntpExtension;
- }.bind(this));
-
this.browserProxy_ = settings.StartupUrlsPageBrowserProxyImpl.getInstance();
- this.addWebUIListener('update-startup-pages', function(startupPages) {
+ this.addWebUIListener('update-startup-pages', startupPages => {
// If an "edit" URL dialog was open, close it, because the underlying page
// might have just been removed (and model indices have changed anyway).
if (this.startupUrlDialogModel_)
this.destroyUrlDialog_();
this.startupPages_ = startupPages;
this.updateScrollableContents();
- }.bind(this));
+ });
this.browserProxy_.loadStartupPages();
- this.addEventListener(settings.EDIT_STARTUP_URL_EVENT, function(event) {
+ this.addEventListener(settings.EDIT_STARTUP_URL_EVENT, event => {
this.startupUrlDialogModel_ = event.detail.model;
this.startupUrlDialogAnchor_ = event.detail.anchor;
this.showStartupUrlDialog_ = true;
event.stopPropagation();
- }.bind(this));
- },
-
- /** @private */
- getNtpExtension_: function() {
- settings.OnStartupBrowserProxyImpl.getInstance().getNtpExtension().then(
- function(ntpExtension) {
- this.ntpExtension_ = ntpExtension;
- }.bind(this));
+ });
},
/**
@@ -130,24 +96,4 @@ Polymer({
return this.get('prefs.session.startup_urls.enforcement') !=
chrome.settingsPrivate.Enforcement.ENFORCED;
},
-
- /**
- * @param {?NtpExtension} ntpExtension
- * @param {number} restoreOnStartup Value of prefs.session.restore_on_startup.
- * @return {boolean}
- * @private
- */
- showIndicator_: function(ntpExtension, restoreOnStartup) {
- return !!ntpExtension && restoreOnStartup == this.prefValues_.OPEN_NEW_TAB;
- },
-
- /**
- * Determine whether to show the user defined startup pages.
- * @param {number} restoreOnStartup Enum value from prefValues_.
- * @return {boolean} Whether the open specific pages is selected.
- * @private
- */
- showStartupUrls_: function(restoreOnStartup) {
- return restoreOnStartup == this.prefValues_.OPEN_SPECIFIC;
- },
});
diff --git a/chromium/chrome/browser/resources/settings/page_visibility.js b/chromium/chrome/browser/resources/settings/page_visibility.js
index 80d9b2017db..e55a55b5a3e 100644
--- a/chromium/chrome/browser/resources/settings/page_visibility.js
+++ b/chromium/chrome/browser/resources/settings/page_visibility.js
@@ -56,8 +56,6 @@ var PrivacyPageVisibility;
cr.define('settings', function() {
/**
* Dictionary defining page visibility.
- * This is only set when in guest mode. All pages are visible when not set
- * because polymer only notifies after a property is set.
* @type {!GuestModePageVisibility}
*/
var pageVisibility;
@@ -100,6 +98,33 @@ cr.define('settings', function() {
multidevice: false,
};
// </if>
+ } else {
+ // All pages are visible when not in chromeos. Since polymer only notifies
+ // after a property is set.
+ // <if expr="chromeos">
+ pageVisibility = {
+ passwordsAndForms: true,
+ people: true,
+ onStartup: true,
+ reset: true,
+ appearance: {
+ setWallpaper: true,
+ setTheme: true,
+ homeButton: true,
+ bookmarksBar: true,
+ pageZoom: true,
+ },
+ advancedSettings: true,
+ privacy: {
+ searchPrediction: true,
+ networkPrediction: true,
+ },
+ downloads: {
+ googleDrive: true,
+ },
+ multidevice: true,
+ };
+ // </if>
}
return {pageVisibility: pageVisibility};
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.html
index 32684422139..37c189b5231 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.html
@@ -54,6 +54,10 @@
@apply(--paper-input-container-label-floating);
}
+ :host-context([dir=rtl]) #select-label {
+ transform-origin: right;
+ }
+
.long {
width: var(--paper-input-max-width);
}
@@ -89,8 +93,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">[[title_]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[title_]]</div>
+ <div slot="body">
<template is="dom-repeat" items="[[addressWrapper_]]">
<div class="address-row">
<template is="dom-repeat" items="[[item]]">
@@ -138,7 +142,7 @@
</paper-input>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="cancelButton" class="cancel-button"
on-tap="onCancelTap_">
$i18n{cancel}
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js
index ed4ac4370a6..66174c825d1 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js
@@ -51,7 +51,7 @@ Polymer({
/** @override */
attached: function() {
this.countryInfo = settings.address.CountryDetailManagerImpl.getInstance();
- this.countryInfo.getCountryList().then(function(countryList) {
+ this.countryInfo.getCountryList().then(countryList => {
this.countries_ = countryList;
this.title_ =
@@ -64,13 +64,13 @@ Polymer({
this.email_ =
this.address.emailAddresses ? this.address.emailAddresses[0] : '';
- this.async(function() {
+ this.async(() => {
if (this.countryCode_ == this.address.countryCode)
this.updateAddressWrapper_();
else
this.countryCode_ = this.address.countryCode;
- }.bind(this));
- }.bind(this));
+ });
+ });
// Open is called on the dialog after the address wrapper has been updated.
},
@@ -91,12 +91,10 @@ Polymer({
updateAddressWrapper_: function() {
// Default to the last country used if no country code is provided.
var countryCode = this.countryCode_ || this.countries_[0].countryCode;
- this.countryInfo.getAddressFormat(countryCode).then(function(format) {
- this.addressWrapper_ = format.components.map(function(component) {
- return component.row.map(function(c) {
- return new settings.address.AddressComponentUI(this.address, c);
- }.bind(this));
- }.bind(this));
+ this.countryInfo.getAddressFormat(countryCode).then(format => {
+ this.addressWrapper_ = format.components.map(
+ component => component.row.map(
+ c => new settings.address.AddressComponentUI(this.address, c)));
// Flush dom before resize and savability updates.
Polymer.dom.flush();
@@ -108,7 +106,7 @@ Polymer({
var dialog = /** @type {HTMLDialogElement} */ (this.$.dialog);
if (!dialog.open)
dialog.showModal();
- }.bind(this));
+ });
},
updateCanSave_: function() {
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html
index fe28ea4c028..f6e65e7231b 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html
@@ -58,13 +58,12 @@
white-space: nowrap;
}
</style>
- <div class="settings-box first">
- <settings-toggle-button id="autofillToggle" class="start primary-toggle"
- aria-label="$i18n{autofill}" no-extension-indicator
- label="[[getOnOffLabel_(prefs.autofill.enabled.value)]]"
- pref="{{prefs.autofill.enabled}}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="autofillToggle"
+ class="first primary-toggle"
+ aria-label="$i18n{autofill}" no-extension-indicator
+ label="[[getOnOffLabel_(prefs.autofill.enabled.value)]]"
+ pref="{{prefs.autofill.enabled}}">
+ </settings-toggle-button>
<template is="dom-if" if="[[prefs.autofill.enabled.extensionId]]">
<div class="settings-box continuation">
<extension-controlled-indicator class="start"
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js
index 76f7afaece4..ffad7d4c01e 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js
@@ -213,14 +213,14 @@ Polymer({
attached: function() {
// Create listener functions.
/** @type {function(!Array<!AutofillManager.AddressEntry>)} */
- var setAddressesListener = function(list) {
+ var setAddressesListener = list => {
this.addresses = list;
- }.bind(this);
+ };
/** @type {function(!Array<!AutofillManager.CreditCardEntry>)} */
- var setCreditCardsListener = function(list) {
+ var setCreditCardsListener = list => {
this.creditCards = list;
- }.bind(this);
+ };
// Remember the bound reference in order to detach.
this.setAddressesListener_ = setAddressesListener;
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp
index 6d0df4cf61a..b61b25173ec 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp
@@ -52,7 +52,7 @@
'target_name': 'password_list_item',
'dependencies': [
'../compiled_resources2.gyp:focus_row_behavior',
- '<(EXTERNS_GYP):passwords_private',
+ 'show_password_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
@@ -74,6 +74,13 @@
'target_name': 'password_edit_dialog',
'dependencies': [
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-input/compiled_resources2.gyp:paper-input-extracted',
+ 'show_password_behavior',
+ ],
+ 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
+ },
+ {
+ 'target_name': 'show_password_behavior',
+ 'dependencies': [
'<(EXTERNS_GYP):passwords_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html
index abd53aef981..041413545b9 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html
@@ -50,8 +50,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">[[title_]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[title_]]</div>
+ <div slot="body">
<paper-input id="nameInput" label="$i18n{creditCardName}"
value="{{creditCard.name}}" always-float-label autofocus
on-input="onCreditCardNameOrNumberChanged_">
@@ -87,7 +87,7 @@
$i18n{creditCardExpired}
</span>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="cancelButton" class="cancel-button"
on-tap="onCancelButtonTap_">$i18n{cancel}</paper-button>
<paper-button id="saveButton" class="action-button"
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js
index 922c08eb137..363f5aeef2d 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js
@@ -98,11 +98,11 @@ Polymer({
}
this.yearList_ = yearList;
- this.async(function() {
+ this.async(() => {
this.expirationYear_ = selectedYear.toString();
this.expirationMonth_ = this.creditCard.expirationMonth;
this.$.dialog.showModal();
- }.bind(this));
+ });
},
/** Closes the dialog. */
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.html
index 4c8f585aad5..f84bd884948 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.html
@@ -6,6 +6,7 @@
<link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="show_password_behavior.html">
<dom-module id="password-edit-dialog">
<template>
@@ -39,8 +40,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{passwordDetailsTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{passwordDetailsTitle}</div>
+ <div slot="body">
<paper-input id="websiteInput" label="$i18n{editPasswordWebsiteLabel}"
value="[[item.loginPair.urls.link]]" readonly always-float-label
on-tap="onReadonlyInputTap_">
@@ -65,7 +66,7 @@
</button>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="action-button" on-tap="onActionButtonTap_">
$i18n{passwordsDone}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.js
index 6d76f1b8f80..e0f1de2c410 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.js
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_edit_dialog.js
@@ -13,20 +13,10 @@
Polymer({
is: 'password-edit-dialog',
- properties: {
- /**
- * The password that is being displayed.
- * @type {!chrome.passwordsPrivate.PasswordUiEntry}
- */
- item: Object,
-
- /** Holds the plaintext password when requested. */
- password: String,
- },
+ behaviors: [ShowPasswordBehavior],
/** @override */
attached: function() {
- this.password = '';
this.$.dialog.showModal();
},
@@ -36,61 +26,6 @@ Polymer({
},
/**
- * Gets the password input's type. Should be 'text' when password is visible
- * or when there's federated text otherwise 'password'.
- * @private
- */
- getPasswordInputType_: function() {
- return this.password || this.item.federationText ? 'text' : 'password';
- },
-
- /**
- * Gets the title text for the show/hide icon.
- * @param {string} password
- * @param {string} hide The i18n text to use for 'Hide'
- * @param {string} show The i18n text to use for 'Show'
- * @private
- */
- showPasswordTitle_: function(password, hide, show) {
- return password ? hide : show;
- },
-
- /**
- * Get the right icon to display when hiding/showing a password.
- * @return {string}
- * @private
- */
- getIconClass_: function() {
- return this.password ? 'icon-visibility-off' : 'icon-visibility';
- },
-
- /**
- * Gets the text of the password. Will use the value of |password| unless it
- * cannot be shown, in which case it will be spaces. It can also be the
- * federated text.
- * @private
- */
- getPassword_: function() {
- if (!this.item)
- return '';
-
- return this.item.federationText || this.password ||
- ' '.repeat(this.item.numCharactersInPassword);
- },
-
- /**
- * Handler for tapping the show/hide button. Will fire an event to request the
- * password for this login pair.
- * @private
- */
- onShowPasswordButtonTap_: function() {
- if (this.password)
- this.password = '';
- else
- this.fire('show-password', this.item.loginPair); // Request the password.
- },
-
- /**
* Handler for tapping the 'done' button. Should just dismiss the dialog.
* @private
*/
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.html
index e7dd128c311..2bde5b23f8a 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.html
@@ -5,6 +5,7 @@
<link rel="import" href="../focus_row_behavior.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="passwords_shared_css.html">
+<link rel="import" href="show_password_behavior.html">
<dom-module id="password-list-item">
<template>
@@ -18,6 +19,15 @@
direction: rtl;
display: flex;
}
+
+ #password {
+ /* Since #password is an input element this is necessary to prevent
+ * Chrome from using the operating system's font instead of the Material
+ * Design font.
+ */
+ font-family: inherit;
+ font-size: inherit;
+ }
</style>
<div class="list-item" focus-row-container>
<div class="website-column no-min-width"
@@ -25,28 +35,41 @@
<a id="originUrl" target="_blank" class="no-min-width"
href="[[item.loginPair.urls.link]]"
focus-row-control focus-type="originUrl">
- <span class="text-elide">[[item.loginPair.urls.shown]]</span>
+ <span class="text-elide">
+ <!-- This bdo tag is necessary to fix the display of domains
+ starting with numbers. -->
+ <bdo dir="ltr">[[item.loginPair.urls.shown]]</bdo>
+ </span>
</a>
</div>
<div class="username-column text-elide"
id="username">[[item.loginPair.username]]</div>
<div class="password-column">
<template is="dom-if" if="[[!item.federationText]]">
- <!-- Password type and disabled in order to match mock. -->
<input id="password" aria-label=$i18n{editPasswordPasswordLabel}
- type="password" class="password-field text-elide" disabled
- value="[[getEmptyPassword_(item.numCharactersInPassword)]]">
- </input>
+ type="[[getPasswordInputType_(item, password)]]"
+ on-tap="onReadonlyInputTap_" class="password-field" readonly
+ disabled$="[[!password]]"
+ value="[[getPassword_(item, password)]]">
+ <button is="paper-icon-button-light" id="showPasswordButton"
+ class$="[[getIconClass_(item, password)]]"
+ on-tap="onShowPasswordButtonTap_"
+ title="[[showPasswordTitle_(password,
+ '$i18nPolymer{hidePassword}','$i18nPolymer{showPassword}')]]"
+ focus-row-control focus-type="showPassword">
+ </button>
</template>
<template is="dom-if" if="[[item.federationText]]">
- <span class="password-field text-elide">[[item.federationText]]</span>
+ <span class="password-field text-elide" id="federated">
+ [[item.federationText]]
+ </span>
</template>
- <button is="paper-icon-button-light" id="passwordMenu"
- class="icon-more-vert" on-tap="onPasswordMenuTap_"
- title="$i18n{moreActions}" focus-row-control
- focus-type="passwordMenu">
- </button>
</div>
+ <button is="paper-icon-button-light" id="passwordMenu"
+ class="icon-more-vert" on-tap="onPasswordMenuTap_"
+ title="$i18n{moreActions}" focus-row-control
+ focus-type="passwordMenu">
+ </button>
</div>
</template>
<script src="password_list_item.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.js
index 688d934e0be..1ade2576b1b 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.js
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/password_list_item.js
@@ -10,24 +10,15 @@
Polymer({
is: 'password-list-item',
- behaviors: [FocusRowBehavior],
-
- properties: {
- /**
- * The password whose info should be displayed.
- * @type {!chrome.passwordsPrivate.PasswordUiEntry}
- */
- item: Array,
- },
+ behaviors: [FocusRowBehavior, ShowPasswordBehavior],
/**
- * Creates an empty password of specified length.
- * @param {number} length
- * @return {string} password
+ * Selects the password on tap if revealed.
* @private
*/
- getEmptyPassword_: function(length) {
- return ' '.repeat(length);
+ onReadonlyInputTap_: function() {
+ if (this.password)
+ this.$$('#password').select();
},
/**
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html
index cd9e905252c..e9cdd80c0ee 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html
@@ -18,14 +18,22 @@
<dom-module id="passwords-section">
<template>
- <style include="settings-shared passwords-shared"></style>
- <div class="settings-box first">
- <settings-toggle-button id="passwordToggle" class="start primary-toggle"
- aria-label="$i18n{passwords}" no-extension-indicator
- label="[[getOnOffLabel_(prefs.credentials_enable_service.value)]]"
- pref="{{prefs.credentials_enable_service}}">
- </settings-toggle-button>
- </div>
+ <style include="settings-shared passwords-shared">
+ #savedPasswordsHeading {
+ /* This adds enough padding so that the labels are aligned with the
+ * columns. It is necessary due to the absence of the "more actions"
+ * button in the heading.
+ */
+ -webkit-padding-end: calc(
+ var(--cr-icon-ripple-size) + var(--cr-icon-button-margin-start));
+ }
+ </style>
+ <settings-toggle-button id="passwordToggle"
+ class="first primary-toggle"
+ aria-label="$i18n{passwords}" no-extension-indicator
+ label="[[getOnOffLabel_(prefs.credentials_enable_service.value)]]"
+ pref="{{prefs.credentials_enable_service}}">
+ </settings-toggle-button>
<template is="dom-if"
if="[[prefs.credentials_enable_service.extensionId]]">
<div class="settings-box continuation">
@@ -39,13 +47,12 @@
</extension-controlled-indicator>
</div>
</template>
- <div class="settings-box three-line">
- <settings-toggle-button id="autosigninCheckbox" class="start"
- pref="{{prefs.credentials_enable_autosignin}}"
- label="$i18n{passwordsAutosigninLabel}"
- sub-label="$i18n{passwordsAutosigninDescription}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="autosigninCheckbox"
+ class="three-line"
+ pref="{{prefs.credentials_enable_autosignin}}"
+ label="$i18n{passwordsAutosigninLabel}"
+ sub-label="$i18n{passwordsAutosigninDescription}">
+ </settings-toggle-button>
<div id="manageLink" class="settings-box first two-line">
<!-- This span lays out the url correctly, relative to the label. -->
<span>$i18nRaw{managePasswordsLabel}</span>
@@ -67,7 +74,7 @@
<iron-list id="passwordList" preserve-focus
items="[[getFilteredPasswords_(savedPasswords, filter)]]"
class="vertical-list list-with-header"
- scroll-target="[[subpageScrollTarget]]">
+ scroll-target="[[subpageScrollTarget]]" risk-selection>
<template>
<password-list-item item="[[item]]" tabindex$="[[tabIndex]]"
iron-list-tab-index="[[tabIndex]]"
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js
index 5d02de6314a..b426a015a25 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js
@@ -241,13 +241,13 @@ Polymer({
/** @override */
attached: function() {
// Create listener functions.
- var setSavedPasswordsListener = function(list) {
+ var setSavedPasswordsListener = list => {
this.savedPasswords = list;
- }.bind(this);
+ };
- var setPasswordExceptionsListener = function(list) {
+ var setPasswordExceptionsListener = list => {
this.passwordExceptions = list;
- }.bind(this);
+ };
this.setSavedPasswordsListener_ = setSavedPasswordsListener;
this.setPasswordExceptionsListener_ = setPasswordExceptionsListener;
@@ -277,19 +277,6 @@ Polymer({
},
/**
- * Sets the password in the current password dialog if the loginPair matches.
- * @param {!chrome.passwordsPrivate.LoginPair} loginPair
- * @param {string} password
- */
- setPassword: function(loginPair, password) {
- if (this.activePassword &&
- this.activePassword.loginPair.urls.origin == loginPair.urls.origin &&
- this.activePassword.loginPair.username == loginPair.username) {
- this.$$('password-edit-dialog').password = password;
- }
- },
-
- /**
* Shows the edit password dialog.
* @param {!Event} e
* @private
@@ -317,9 +304,9 @@ Polymer({
if (!filter)
return savedPasswords;
- return savedPasswords.filter(function(password) {
- return password.loginPair.urls.shown.includes(filter) ||
- password.loginPair.username.includes(filter);
+ return savedPasswords.filter(p => {
+ return [p.loginPair.urls.shown, p.loginPair.username].some(
+ term => term.toLowerCase().includes(filter.toLowerCase()));
});
},
@@ -330,7 +317,7 @@ Polymer({
*/
passwordExceptionFilter_: function(filter) {
return function(exception) {
- return exception.urls.shown.includes(filter);
+ return exception.urls.shown.toLowerCase().includes(filter.toLowerCase());
};
},
@@ -385,10 +372,10 @@ Polymer({
*/
showPassword_: function(event) {
this.passwordManager_.getPlaintextPassword(
- /** @type {!PasswordManager.LoginPair} */ (event.detail),
- function(item) {
- this.setPassword(item.loginPair, item.plaintextPassword);
- }.bind(this));
+ /** @type {!PasswordManager.LoginPair} */ (event.detail.item.loginPair),
+ item => {
+ event.detail.password = item.plaintextPassword;
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_shared_css.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_shared_css.html
index 0933fe0fffc..5bcd1e903f9 100644
--- a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_shared_css.html
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/passwords_shared_css.html
@@ -13,18 +13,18 @@
.website-column {
display: flex;
- flex: 3;
+ flex: 1;
}
.username-column {
- flex: 2;
+ flex: 1;
margin: 0 8px;
}
.password-column {
align-items: center;
display: flex;
- flex: 2;
+ flex: 1;
}
.password-field {
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.html b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.html
new file mode 100644
index 00000000000..73ee8c03754
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.html
@@ -0,0 +1,2 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+<script src="show_password_behavior.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.js b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.js
new file mode 100644
index 00000000000..8c4a54bf5b0
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/passwords_and_forms_page/show_password_behavior.js
@@ -0,0 +1,85 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * This behavior bundles functionality required to show a password to the user.
+ * It is used by both <password-list-item> and <password-edit-dialog>.
+ *
+ * @polymerBehavior
+ */
+var ShowPasswordBehavior = {
+
+ properties: {
+ /**
+ * The password that is being displayed.
+ * @type {!chrome.passwordsPrivate.PasswordUiEntry}
+ */
+ item: Object,
+
+ /**
+ * Holds the plaintext password when requested.
+ * Initializing it to the empty string is necessary to indicate that the
+ * password hasn't been fetched yet.
+ */
+ password: {
+ type: String,
+ value: '',
+ },
+ },
+
+ /**
+ * Gets the password input's type. Should be 'text' when password is visible
+ * or when there's federated text otherwise 'password'.
+ * @private
+ */
+ getPasswordInputType_: function() {
+ return this.password || this.item.federationText ? 'text' : 'password';
+ },
+
+ /**
+ * Gets the title text for the show/hide icon.
+ * @param {string} password
+ * @param {string} hide The i18n text to use for 'Hide'
+ * @param {string} show The i18n text to use for 'Show'
+ * @private
+ */
+ showPasswordTitle_: function(password, hide, show) {
+ return password ? hide : show;
+ },
+
+ /**
+ * Get the right icon to display when hiding/showing a password.
+ * @return {string}
+ * @private
+ */
+ getIconClass_: function() {
+ return this.password ? 'icon-visibility-off' : 'icon-visibility';
+ },
+
+ /**
+ * Gets the text of the password. Will use the value of |password| unless it
+ * cannot be shown, in which case it will be spaces. It can also be the
+ * federated text.
+ * @private
+ */
+ getPassword_: function() {
+ if (!this.item)
+ return '';
+
+ return this.item.federationText || this.password ||
+ ' '.repeat(this.item.numCharactersInPassword);
+ },
+
+ /**
+ * Handler for tapping the show/hide button. Will fire an event to request the
+ * password for this login pair.
+ * @private
+ */
+ onShowPasswordButtonTap_: function() {
+ if (this.password)
+ this.password = '';
+ else
+ this.fire('show-password', this); // Request the password.
+ },
+};
diff --git a/chromium/chrome/browser/resources/settings/people_page/change_picture.html b/chromium/chrome/browser/resources/settings/people_page/change_picture.html
index 0bae5f15d4a..2b642c9f527 100644
--- a/chromium/chrome/browser/resources/settings/people_page/change_picture.html
+++ b/chromium/chrome/browser/resources/settings/people_page/change_picture.html
@@ -103,7 +103,6 @@
choose-file-label="$i18n{chooseFile}"
old-image-label="$i18n{oldPhoto}"
profile-image-label="$i18n{profilePhoto}"
- profile-image-loading-label="$i18n{profilePhotoLoading}"
take-photo-label="$i18n{takePhoto}">
</cr-picture-list>
</div>
diff --git a/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.html b/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.html
index 0bc4943fbf8..b4acc33bb43 100644
--- a/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.html
@@ -13,11 +13,11 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">[[getTitleText_(status_)]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[getTitleText_(status_)]]</div>
+ <div slot="body">
[[getDescriptionText_(status_)]]
</div>
- <div class="button-container" slot="button-container"
+ <div slot="button-container"
hidden="[[isButtonBarHidden_(status_)]]">
<paper-spinner active="[[isSpinnerActive_(status_)]]">
</paper-spinner>
diff --git a/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js b/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js
index 76d2d6968af..79cd7beede0 100644
--- a/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js
@@ -47,16 +47,16 @@ Polymer({
'easy-unlock-enabled-status',
this.handleEasyUnlockEnabledStatusChanged_.bind(this));
- this.addWebUIListener('easy-unlock-turn-off-flow-status', function(status) {
+ this.addWebUIListener('easy-unlock-turn-off-flow-status', status => {
this.status_ = status;
- }.bind(this));
+ });
// Since the dialog text depends on the status, defer opening until we have
// retrieved the turn off status to prevent UI flicker.
- this.getTurnOffStatus_().then(function(status) {
+ this.getTurnOffStatus_().then(status => {
this.status_ = status;
this.$.dialog.showModal();
- }.bind(this));
+ });
},
/**
@@ -77,7 +77,7 @@ Polymer({
* @private
*/
handleEasyUnlockEnabledStatusChanged_: function(easyUnlockEnabled) {
- var dialog = /** @type {!CrDialogElement} */ this.$.dialog;
+ var dialog = /** @type {!CrDialogElement} */ (this.$.dialog);
if (!easyUnlockEnabled && dialog.open)
this.onCancelTap_();
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js b/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js
index d6c142e0868..1cb0239a67d 100644
--- a/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js
+++ b/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js
@@ -126,10 +126,10 @@ Polymer({
* @private
*/
onFingerprintDeleteTapped_: function(e) {
- this.browserProxy_.removeEnrollment(e.model.index).then(function(success) {
+ this.browserProxy_.removeEnrollment(e.model.index).then(success => {
if (success)
this.updateFingerprintsList_();
- }.bind(this));
+ });
},
/**
@@ -138,10 +138,10 @@ Polymer({
*/
onFingerprintLabelChanged_: function(e) {
this.browserProxy_.changeEnrollmentLabel(e.model.index, e.model.item)
- .then(function(success) {
+ .then(success => {
if (success)
this.updateFingerprintsList_();
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html b/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html
index df42eaab86a..9b214de84ff 100644
--- a/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html
@@ -37,15 +37,15 @@
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}"
ignore-popstate>
- <div class="title" slot="title">$i18n{importTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{importTitle}</div>
+ <div slot="body">
<div hidden$="[[!hasImportStatus_(
importStatusEnum_.SUCCEEDED, importStatus_)]]">
<iron-icon id="successIcon" icon="settings:check-circle">
</iron-icon>
<div hidden$="[[!prefs.import_dialog_bookmarks.value]]">
<div class="description">$i18n{importSuccess}</div>
- <settings-toggle-button class="start"
+ <settings-toggle-button class="first"
label="$i18n{showBookmarksBar}"
pref="{{prefs.bookmark_bar.show_on_all_tabs}}">
</settings-toggle-button>
@@ -92,7 +92,7 @@
</settings-checkbox>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-spinner
active="[[hasImportStatus_(
importStatusEnum_.IN_PROGRESS, importStatus_)]]"
diff --git a/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.js b/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.js
index 83099cd0cd8..d12dfee24b9 100644
--- a/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.js
@@ -53,25 +53,20 @@ Polymer({
/** @override */
attached: function() {
this.browserProxy_ = settings.ImportDataBrowserProxyImpl.getInstance();
- this.browserProxy_.initializeImportDialog().then(
- /** @param {!Array<!settings.BrowserProfile>} data */
- function(data) {
- this.browserProfiles_ = data;
- this.selected_ = this.browserProfiles_[0];
-
- // Show the dialog only after the browser profiles data is populated
- // to avoid UI flicker.
- this.$.dialog.showModal();
- }.bind(this));
-
- this.addWebUIListener(
- 'import-data-status-changed',
- /** @param {settings.ImportDataStatus} importStatus */
- function(importStatus) {
- this.importStatus_ = importStatus;
- if (this.hasImportStatus_(settings.ImportDataStatus.FAILED))
- this.closeDialog_();
- }.bind(this));
+ this.browserProxy_.initializeImportDialog().then(data => {
+ this.browserProfiles_ = data;
+ this.selected_ = this.browserProfiles_[0];
+
+ // Show the dialog only after the browser profiles data is populated
+ // to avoid UI flicker.
+ this.$.dialog.showModal();
+ });
+
+ this.addWebUIListener('import-data-status-changed', importStatus => {
+ this.importStatus_ = importStatus;
+ if (this.hasImportStatus_(settings.ImportDataStatus.FAILED))
+ this.closeDialog_();
+ });
},
/** @private */
diff --git a/chromium/chrome/browser/resources/settings/people_page/lock_screen.html b/chromium/chrome/browser/resources/settings/people_page/lock_screen.html
index e03aaea348d..94cf67553e4 100644
--- a/chromium/chrome/browser/resources/settings/people_page/lock_screen.html
+++ b/chromium/chrome/browser/resources/settings/people_page/lock_screen.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
@@ -19,10 +20,18 @@
<link rel="import" href="../prefs/prefs.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="../settings_vars_css.html">
<dom-module id="settings-lock-screen">
<template>
<style include="settings-shared">
+ cr-policy-indicator {
+ -webkit-margin-start: auto;
+ /* Align the indicator with the h2 that it is associated with. */
+ padding-bottom: 12px;
+ padding-top: 24px;
+ }
+
#easyUnlock .start {
/* When the easy unlock toggle is shown, the easy unlock section's
* content becomes squashed to the top and bottom edges. Use padding to
@@ -49,10 +58,15 @@
margin: auto;
}
- #easyUnlockSettingsCollapsable {
+ #easyUnlockSettingsCollapsible {
@apply(--settings-list-frame-padding);
}
+ .list-frame[disabled] {
+ opacity: var(--settings-disabled-opacity);
+ pointer-events: none;
+ }
+
.no-padding {
padding: 0;
}
@@ -63,19 +77,21 @@
</style>
<div>
- <div id="screenLockDiv" class="settings-box first">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.enable_screen_lock}}"
- label="$i18n{enableScreenlock}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="screenLockDiv" class="first"
+ pref="{{prefs.settings.enable_screen_lock}}"
+ label="$i18n{enableScreenlock}">
+ </settings-toggle-button>
<template is="dom-if" if="[[quickUnlockEnabled_]]">
<div id="lockOptionsDiv">
<div class="settings-box">
<h2>$i18n{lockScreenOptions}</h2>
+ <template is="dom-if" if="[[quickUnlockDisabledByPolicy_]]">
+ <cr-policy-indicator indicator-type="userPolicy">
+ </cr-policy-indicator>
+ </template>
</div>
- <div class="list-frame">
+ <div class="list-frame" disabled$="[[quickUnlockDisabledByPolicy_]]">
<paper-radio-group id="unlockType"
selected="{{selectedUnlockType}}">
<paper-radio-button name="password" class="list-item underbar">
@@ -107,12 +123,10 @@
<template is="dom-if" if="[[fingerprintUnlockEnabled_]]">
<div id="fingerprintDiv">
- <div class="settings-box continuation">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.enable_quick_unlock_fingerprint}}"
- label="$i18n{lockScreenFingerprintEnable}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.settings.enable_quick_unlock_fingerprint}}"
+ label="$i18n{lockScreenFingerprintEnable}">
+ </settings-toggle-button>
<iron-collapse
opened="[[prefs.settings.enable_quick_unlock_fingerprint.value]]">
<div class="settings-box continuation">
@@ -164,14 +178,12 @@
</template>
</div>
<iron-collapse opened="[[easyUnlockEnabled_]]"
- id="easyUnlockSettingsCollapsable">
- <div class="settings-box continuation no-padding underbar">
- <settings-toggle-button
- class="start"
+ id="easyUnlockSettingsCollapsible">
+ <settings-toggle-button
+ class="continuation no-padding underbar"
pref="{{prefs.proximity_auth.is_chromeos_login_enabled}}"
label="$i18n{easyUnlockAllowSignInLabel}">
- </settings-toggle-button>
- </div>
+ </settings-toggle-button>
<div class="settings-box continuation no-padding">
<div class="start">
$i18n{easyUnlockProximityThresholdLabel}
diff --git a/chromium/chrome/browser/resources/settings/people_page/lock_screen.js b/chromium/chrome/browser/resources/settings/people_page/lock_screen.js
index ddec1fb4c18..b8d3d02ff26 100644
--- a/chromium/chrome/browser/resources/settings/people_page/lock_screen.js
+++ b/chromium/chrome/browser/resources/settings/people_page/lock_screen.js
@@ -80,6 +80,18 @@ Polymer({
},
/**
+ * True if quick unlock settings are disabled by policy.
+ * @private
+ */
+ quickUnlockDisabledByPolicy_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('quickUnlockDisabledByPolicy');
+ },
+ readOnly: true,
+ },
+
+ /**
* True if fingerprint unlock settings should be displayed on this machine.
* @private
*/
@@ -199,9 +211,9 @@ Polymer({
if (newRoute == settings.routes.LOCK_SCREEN &&
this.fingerprintUnlockEnabled_ && this.fingerprintBrowserProxy_) {
this.fingerprintBrowserProxy_.getNumFingerprints().then(
- function(numFingerprints) {
+ numFingerprints => {
this.numFingerprints_ = numFingerprints;
- }.bind(this));
+ });
}
if (this.shouldAskForPassword_(newRoute)) {
diff --git a/chromium/chrome/browser/resources/settings/people_page/lock_state_behavior.js b/chromium/chrome/browser/resources/settings/people_page/lock_state_behavior.js
index ac6762b2e65..d40f58e59fc 100644
--- a/chromium/chrome/browser/resources/settings/people_page/lock_state_behavior.js
+++ b/chromium/chrome/browser/resources/settings/people_page/lock_state_behavior.js
@@ -63,7 +63,7 @@ var LockStateBehavior = {
* @private
*/
updateUnlockType_: function() {
- this.quickUnlockPrivate_.getActiveModes(function(modes) {
+ this.quickUnlockPrivate_.getActiveModes(modes => {
if (modes.includes(chrome.quickUnlockPrivate.QuickUnlockMode.PIN)) {
this.hasPin = true;
this.selectedUnlockType = LockScreenUnlockType.PIN_PASSWORD;
@@ -71,6 +71,6 @@ var LockStateBehavior = {
this.hasPin = false;
this.selectedUnlockType = LockScreenUnlockType.PASSWORD;
}
- }.bind(this));
+ });
},
};
diff --git a/chromium/chrome/browser/resources/settings/people_page/manage_profile.js b/chromium/chrome/browser/resources/settings/people_page/manage_profile.js
index 91e46daeb08..0db9c24a317 100644
--- a/chromium/chrome/browser/resources/settings/people_page/manage_profile.js
+++ b/chromium/chrome/browser/resources/settings/people_page/manage_profile.js
@@ -67,9 +67,9 @@ Polymer({
/** @override */
attached: function() {
- var setIcons = function(icons) {
+ var setIcons = icons => {
this.availableIcons = icons;
- }.bind(this);
+ };
this.addWebUIListener('available-icons-changed', setIcons);
this.browserProxy_.getAvailableIcons().then(setIcons);
@@ -81,7 +81,7 @@ Polymer({
this.$.name.value = this.profileName;
if (loadTimeData.getBoolean('profileShortcutsEnabled')) {
- this.browserProxy_.getProfileShortcutStatus().then(function(status) {
+ this.browserProxy_.getProfileShortcutStatus().then(status => {
if (status == ProfileShortcutStatus.PROFILE_SHORTCUT_SETTING_HIDDEN) {
this.isProfileShortcutSettingVisible_ = false;
return;
@@ -90,7 +90,7 @@ Polymer({
this.isProfileShortcutSettingVisible_ = true;
this.hasProfileShortcut_ =
status == ProfileShortcutStatus.PROFILE_SHORTCUT_FOUND;
- }.bind(this));
+ });
}
}
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.html b/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.html
index ca3cc858a64..9a7dac7a58c 100644
--- a/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.html
@@ -20,8 +20,8 @@
<dialog is="cr-dialog" id="dialog" on-close="onClose_"
close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{passwordPromptTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{passwordPromptTitle}</div>
+ <div slot="body">
<div class="settings-box first">$i18n{passwordPromptEnterPassword}</div>
@@ -33,7 +33,7 @@
aria-disabled="false">
</paper-input>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.js b/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.js
index c9ee712d9f2..2d3035ada0d 100644
--- a/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/password_prompt_dialog.js
@@ -99,9 +99,9 @@ Polymer({
attached: function() {
this.writeUma_(LockScreenProgress.START_SCREEN_LOCK);
this.$.dialog.showModal();
- this.async(function() {
+ this.async(() => {
this.$.passwordInput.focus();
- }.bind(this));
+ });
},
/** @private */
@@ -143,10 +143,10 @@ Polymer({
var password = this.password_;
this.password_ = '';
- this.setModes = function(modes, credentials, onComplete) {
+ this.setModes = (modes, credentials, onComplete) => {
this.quickUnlockPrivate_.setModes(
password, modes, credentials, onComplete);
- }.bind(this);
+ };
function clearSetModes() {
// Reset the password so that any cached references to this.setModes
@@ -187,12 +187,12 @@ Polymer({
checkAccountPassword_: function(onCheck) {
// We check the account password by trying to update the active set of quick
// unlock modes without changing any credentials.
- this.quickUnlockPrivate_.getActiveModes(function(modes) {
+ this.quickUnlockPrivate_.getActiveModes(modes => {
var credentials =
/** @type {!Array<string>} */ (Array(modes.length).fill(''));
this.quickUnlockPrivate_.setModes(
this.password_, modes, credentials, onCheck);
- }.bind(this));
+ });
}
});
diff --git a/chromium/chrome/browser/resources/settings/people_page/people_page.html b/chromium/chrome/browser/resources/settings/people_page/people_page.html
index 4879ebdb742..bcb99fcf3de 100644
--- a/chromium/chrome/browser/resources/settings/people_page/people_page.html
+++ b/chromium/chrome/browser/resources/settings/people_page/people_page.html
@@ -81,16 +81,22 @@
width: 40px;
}
- #disconnectDialog .footer .settings-box {
+ #disconnectDialog [slot=footer] .settings-box {
--settings-box-row-padding: 0;
}
.delete-profile-warning {
+ -webkit-padding-end: var(--cr-section-padding);
/* In order to line up with the checkbox text. */
- -webkit-padding-start: 36px;
+ -webkit-padding-start: var(--cr-section-indent-padding);
padding-bottom: 10px;
padding-top: 10px;
}
+
+ #wideFooter {
+ /* Override the cr-dialog footer padding. */
+ padding: 16px 0;
+ }
</style>
<settings-animated-pages id="pages" section="people"
focus-config="[[focusConfig_]]">
@@ -98,7 +104,7 @@
<div id="picture-subpage-trigger" class="settings-box first two-line">
<template is="dom-if" if="[[syncStatus]]">
<div id="profile-icon" on-tap="onPictureTap_" actionable
- style="background-image: [[getIconImageset_(profileIconUrl_)]]">
+ style="background-image: [[getIconImageSet_(profileIconUrl_)]]">
</div>
<if expr="not chromeos">
<div class="middle two-line no-min-width"
@@ -144,15 +150,21 @@
</if>
</template>
</div>
- <div class="settings-box two-line"
- hidden="[[!showSignin_(syncStatus)]]">
- <div>
- $i18n{syncOverview}
- <a target="_blank" href="$i18n{syncLearnMoreUrl}">
- $i18n{learnMore}
- </a>
+
+ <template is="dom-if" if="[[!syncStatus.signedIn]]">
+ <div class="settings-box two-line"
+ hidden="[[!syncStatus.signinAllowed]]">
+ <div class="start">
+ $i18n{syncOverview}
+ <a target="_blank" href="$i18n{syncLearnMoreUrl}">
+ $i18n{learnMore}
+ </a>
+ </div>
</div>
- </div>
+ <div class="settings-box" hidden="[[syncStatus.signinAllowed]]">
+ $i18n{syncDisabledByAdministrator}
+ </div>
+ </template>
<if expr="not chromeos">
<template is="dom-if" if="[[syncStatus.domain]]">
@@ -289,13 +301,13 @@
<dialog is="cr-dialog" id="disconnectDialog"
ignore-popstate ignore-enter-key
on-close="onDisconnectClosed_" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{syncDisconnectTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{syncDisconnectTitle}</div>
+ <div slot="body">
<div inner-h-t-m-l="[[
getDisconnectExplanationHtml_(syncStatus.domain)]]">
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button on-tap="onDisconnectCancel_" class="cancel-button">
$i18n{cancel}
</paper-button>
@@ -311,7 +323,7 @@
</div>
<if expr="(not chromeos and is_posix) or is_win or is_macosx">
<template is="dom-if" if="[[!syncStatus.domain]]">
- <div class="footer" slot="footer">
+ <div id="wideFooter" slot="footer">
<div class="settings-box first">
<paper-checkbox id="deleteProfile" class="start"
checked="{{deleteProfile_}}">
diff --git a/chromium/chrome/browser/resources/settings/people_page/people_page.js b/chromium/chrome/browser/resources/settings/people_page/people_page.js
index 35b743b750f..1b1dec616e9 100644
--- a/chromium/chrome/browser/resources/settings/people_page/people_page.js
+++ b/chromium/chrome/browser/resources/settings/people_page/people_page.js
@@ -163,9 +163,9 @@ Polymer({
settings.navigateToPreviousRoute();
} else {
this.showDisconnectDialog_ = true;
- this.async(function() {
+ this.async(() => {
this.$$('#disconnectDialog').showModal();
- }.bind(this));
+ });
}
} else if (this.showDisconnectDialog_) {
this.$$('#disconnectDialog').close();
@@ -291,9 +291,9 @@ Polymer({
// browser is closed after the sign out. Otherwise, the navigation will be
// finshed during session restore if the browser is closed before the async
// callback executed.
- listenOnce(this, 'signout-dialog-closed', function() {
+ listenOnce(this, 'signout-dialog-closed', () => {
this.syncBrowserProxy_.signOut(deleteProfile);
- }.bind(this));
+ });
this.$$('#disconnectDialog').close();
},
@@ -454,10 +454,10 @@ Polymer({
/**
* @param {string} iconUrl
- * @return {string} A CSS imageset for multiple scale factors.
+ * @return {string} A CSS image-set for multiple scale factors.
* @private
*/
- getIconImageset_: function(iconUrl) {
+ getIconImageSet_: function(iconUrl) {
return cr.icon.getImage(iconUrl);
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html
index a81533429f6..2df6f373cff 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html
@@ -54,8 +54,8 @@
<dialog is="cr-dialog" id="dialog" on-close="close"
close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{configureFingerprintTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{configureFingerprintTitle}</div>
+ <div slot="body">
<div class="settings-box first">
<span class="middle">[[getInstructionMessage_(step_)]]</span>
</div>
@@ -71,7 +71,7 @@
<span class="middle">[[problemMessage_]]</span>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button id="addAnotherButton" on-tap="onAddAnotherFingerprint_"
hidden$="[[hideAddAnother_(step_)]]">
$i18n{configureFingerprintAddAnotherButton}
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
index e1922890789..1f98c6dcf5e 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
@@ -221,9 +221,9 @@ Polymer({
switch (scanResult) {
case settings.FingerprintResultType.SUCCESS:
this.problemMessage_ = '';
- this.tapSensorMessageTimeoutId_ = setTimeout(function() {
+ this.tapSensorMessageTimeoutId_ = setTimeout(() => {
this.problemMessage_ = this.i18n('configureFingerprintLiftFinger');
- }.bind(this), SHOW_TAP_SENSOR_MESSAGE_DELAY_MS);
+ }, SHOW_TAP_SENSOR_MESSAGE_DELAY_MS);
break;
case settings.FingerprintResultType.PARTIAL:
this.problemMessage_ = this.i18n('configureFingerprintPartialData');
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
index 801dc1e94fe..bdee32b9efe 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
@@ -45,8 +45,8 @@
<dialog is="cr-dialog" id="dialog" on-close="close"
close-text="$i18n{close}">
- <div class="title" slot="title">[[getTitleMessage_(isConfirmStep_)]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[getTitleMessage_(isConfirmStep_)]]</div>
+ <div slot="body">
<!-- Pin keyboard -->
<div id="pinKeyboardDiv" class="settings-box continuation">
<pin-keyboard id="pinKeyboard" on-pin-change="onPinChange_"
@@ -61,7 +61,7 @@
</pin-keyboard>
</div>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
index 4056aab0e77..924be4a26d0 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
@@ -256,10 +256,7 @@ Polymer({
}
this.hideProblem_();
- if (this.canSubmit_()) {
- this.enableSubmit_ = true;
- return;
- }
+ this.enableSubmit_ = this.pinKeyboardValue_.length > 0;
},
/** @private */
@@ -277,6 +274,9 @@ Polymer({
// The PIN is not guaranteed to be valid in that case.
if (!this.canSubmit_()) {
this.showProblem_(MessageType.MISMATCH, ProblemType.ERROR);
+ this.enableSubmit_ = false;
+ // Focus the PIN keyboard and highlight the entire PIN.
+ this.$.pinKeyboard.focus(0, this.pinKeyboardValue_.length + 1);
return;
}
diff --git a/chromium/chrome/browser/resources/settings/people_page/sync_page.js b/chromium/chrome/browser/resources/settings/people_page/sync_page.js
index 18102cfbfe4..88c71faa758 100644
--- a/chromium/chrome/browser/resources/settings/people_page/sync_page.js
+++ b/chromium/chrome/browser/resources/settings/people_page/sync_page.js
@@ -217,11 +217,11 @@ Polymer({
// Focus the password input box if password is needed to start sync.
if (this.syncPrefs.passphraseRequired) {
// Wait for the dom-if templates to render and subpage to become visible.
- listenOnce(document, 'show-container', function() {
+ listenOnce(document, 'show-container', () => {
var input = /** @type {!PaperInputElement} */ (
this.$$('#existingPassphraseInput'));
input.inputElement.focus();
- }.bind(this));
+ });
}
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/user_list.html b/chromium/chrome/browser/resources/settings/people_page/user_list.html
index 928f18a6606..0873990c000 100644
--- a/chromium/chrome/browser/resources/settings/people_page/user_list.html
+++ b/chromium/chrome/browser/resources/settings/people_page/user_list.html
@@ -39,10 +39,10 @@
<template is="dom-repeat" items="[[users_]]">
<div class="user layout horizontal center two-line">
<img class="user-icon" src="[[getProfilePictureUrl_(item)]]">
- <div class="flex user-info">
- <div>[[getUserName_(item)]]</div>
+ <div class="flex layout vertical user-info no-min-width">
+ <div class="text-elide">[[getUserName_(item)]]</div>
<template is="dom-if" if="[[shouldShowEmail_(item)]]">
- <div class="secondary">[[item.displayEmail]]</div>
+ <div class="secondary text-elide">[[item.displayEmail]]</div>
</template>
</div>
<button is="paper-icon-button-light" class="icon-clear"
diff --git a/chromium/chrome/browser/resources/settings/people_page/user_list.js b/chromium/chrome/browser/resources/settings/people_page/user_list.js
index f1cbc795b48..f897fc9ba59 100644
--- a/chromium/chrome/browser/resources/settings/people_page/user_list.js
+++ b/chromium/chrome/browser/resources/settings/people_page/user_list.js
@@ -47,23 +47,23 @@ Polymer({
/** @override */
ready: function() {
- chrome.settingsPrivate.onPrefsChanged.addListener(function(prefs) {
+ chrome.settingsPrivate.onPrefsChanged.addListener(prefs => {
prefs.forEach(function(pref) {
if (pref.key == 'cros.accounts.users') {
- chrome.usersPrivate.getWhitelistedUsers(function(users) {
+ chrome.usersPrivate.getWhitelistedUsers(users => {
this.setUsers_(users);
- }.bind(this));
+ });
}
}, this);
- }.bind(this));
+ });
},
/** @protected */
currentRouteChanged: function() {
if (settings.getCurrentRoute() == settings.routes.ACCOUNTS) {
- chrome.usersPrivate.getWhitelistedUsers(function(users) {
+ chrome.usersPrivate.getWhitelistedUsers(users => {
this.setUsers_(users);
- }.bind(this));
+ });
}
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html b/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html
index 9fd1e6c4bfb..99850568bff 100644
--- a/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html
@@ -18,13 +18,13 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{addUsers}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{addUsers}</div>
+ <div slot="body">
<paper-input id="addUserInput" label="$i18n{addUsersEmail}" autofocus
on-input="validate_" invalid="[[!isValid_]]">
</paper-input>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/people_page/users_page.html b/chromium/chrome/browser/resources/settings/people_page/users_page.html
index d89306f9377..a2fea7f100f 100644
--- a/chromium/chrome/browser/resources/settings/people_page/users_page.html
+++ b/chromium/chrome/browser/resources/settings/people_page/users_page.html
@@ -34,30 +34,28 @@
<div class="settings-box">$i18n{usersModifiedByOwnerLabel}</div>
</template>
</template>
- <div class="settings-box block">
- <settings-toggle-button
- pref="{{prefs.cros.accounts.allowBWSI}}"
- label="$i18n{guestBrowsingLabel}"
- disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.cros.accounts.supervisedUsersEnabled}}"
- label="$i18n{supervisedUsersLabel}"
- disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.cros.accounts.showUserNamesOnSignIn}}"
- label="$i18n{showOnSigninLabel}"
- disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]">
- </settings-toggle-button>
- <settings-toggle-button
- pref="{{prefs.cros.accounts.allowGuest}}"
- id="restrictSignIn"
- label="$i18n{restrictSigninLabel}"
- disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]"
- inverted>
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="first"
+ pref="{{prefs.cros.accounts.allowBWSI}}"
+ label="$i18n{guestBrowsingLabel}"
+ disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.cros.accounts.supervisedUsersEnabled}}"
+ label="$i18n{supervisedUsersLabel}"
+ disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.cros.accounts.showUserNamesOnSignIn}}"
+ label="$i18n{showOnSigninLabel}"
+ disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]">
+ </settings-toggle-button>
+ <settings-toggle-button class="continuation"
+ pref="{{prefs.cros.accounts.allowGuest}}"
+ id="restrictSignIn"
+ label="$i18n{restrictSigninLabel}"
+ disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]"
+ inverted>
+ </settings-toggle-button>
<div class="list-frame">
<settings-user-list prefs="[[prefs]]"
disabled="[[isEditingUsersDisabled_(isOwner_, isWhitelistManaged_,
diff --git a/chromium/chrome/browser/resources/settings/people_page/users_page.js b/chromium/chrome/browser/resources/settings/people_page/users_page.js
index 4fa1d5a34b8..2d14833a0dc 100644
--- a/chromium/chrome/browser/resources/settings/people_page/users_page.js
+++ b/chromium/chrome/browser/resources/settings/people_page/users_page.js
@@ -34,13 +34,13 @@ Polymer({
/** @override */
created: function() {
- chrome.usersPrivate.isCurrentUserOwner(function(isOwner) {
+ chrome.usersPrivate.isCurrentUserOwner(isOwner => {
this.isOwner_ = isOwner;
- }.bind(this));
+ });
- chrome.usersPrivate.isWhitelistManaged(function(isWhitelistManaged) {
+ chrome.usersPrivate.isWhitelistManaged(isWhitelistManaged => {
this.isWhitelistManaged_ = isWhitelistManaged;
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/prefs/prefs.js b/chromium/chrome/browser/resources/settings/prefs/prefs.js
index 537da2e7529..b089c1007e4 100644
--- a/chromium/chrome/browser/resources/settings/prefs/prefs.js
+++ b/chromium/chrome/browser/resources/settings/prefs/prefs.js
@@ -245,9 +245,9 @@ Polymer({
* @param {string} key
*/
refresh: function(key) {
- this.settingsApi_.getPref(key, function(pref) {
+ this.settingsApi_.getPref(key, pref => {
this.updatePrefs_([pref]);
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.html
index bef47a9e07a..468899577b2 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.html
@@ -15,12 +15,10 @@
</a>
</span>
</div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.local_discovery.notifications_enabled}}"
- label="$i18n{printingNotificationsLabel}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.local_discovery.notifications_enabled}}"
+ label="$i18n{printingNotificationsLabel}">
+ </settings-toggle-button>
<a class="settings-box inherit-color no-outline" tabindex="-1"
target="_blank" href="$i18n{devicesUrl}">
<div class="start">
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.js
index 1de17f79f66..b7dcbd2a9b7 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cloud_printers.js
@@ -4,7 +4,7 @@
/**
* @fileoverview 'settings-cloud-printers' is a component for showing Google
- * Cloud Printer settings subpage (chrome://md-settings/cloudPrinters).
+ * Cloud Printer settings subpage (chrome://settings/cloudPrinters).
*/
// TODO(xdai): Rename it to 'settings-cloud-printers-page'.
Polymer({
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html
index cde64e7785d..5ca6f7e45de 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html
@@ -35,8 +35,8 @@
}
</style>
<add-printer-dialog>
- <div class="dialog-title">$i18n{addPrintersNearbyTitle}</div>
- <div class="dialog-body">
+ <div slot="dialog-title">$i18n{addPrintersNearbyTitle}</div>
+ <div slot="dialog-body">
<add-printer-list printers="[[discoveredPrinters]]"
selected-printer="{{selectedPrinter}}">
</add-printer-list>
@@ -48,7 +48,7 @@
<span>$i18n{searchingNearbyPrinters}</span>
</div>
</div>
- <div class="dialog-buttons">
+ <div slot="dialog-buttons">
<div> <!-- Left group -->
<paper-button id="manuallyAddPrinterButton" class="secondary-button"
on-tap="switchToManualAddDialog_">
@@ -105,8 +105,8 @@
}
</style>
<add-printer-dialog>
- <div class="dialog-title">$i18n{addPrintersManuallyTitle}</div>
- <div class="dialog-body">
+ <div slot="dialog-title">$i18n{addPrintersManuallyTitle}</div>
+ <div slot="dialog-body">
<div class="settings-box first two-line">
<div class="start">
<div class="label">$i18n{printerName}</div>
@@ -171,7 +171,7 @@
<span>$i18n{printerFound}</span>
</div>
</div>
- <div class="dialog-buttons">
+ <div slot="dialog-buttons">
<div> <!-- Left group -->
<paper-button class="secondary-button"
on-tap="switchToDiscoveryDialog_">
@@ -205,8 +205,8 @@
}
</style>
<add-printer-dialog>
- <div class="dialog-title">$i18n{selectManufacturerAndModelTitle}</div>
- <div class="dialog-body">
+ <div slot="dialog-title">$i18n{selectManufacturerAndModelTitle}</div>
+ <div slot="dialog-body">
<div class="settings-box two-line">
<div class="start">
<div class="label">$i18n{printerManufacturer}</div>
@@ -245,7 +245,7 @@
Driver not found (exact error message TBD)
</div>
</div>
- <div class="dialog-buttons">
+ <div slot="dialog-buttons">
<paper-button class="cancel-button secondary-button"
on-tap="onCancelTap_">
$i18n{cancelButtonText}
@@ -265,18 +265,18 @@
<dom-module id="add-printer-configuring-dialog">
<template>
<style include="cups-printer-shared">
- .dialog-body {
+ [slot='dialog-body'] {
padding-top: 140px;
text-align: center;
}
</style>
<add-printer-dialog>
- <div class="dialog-title">[[dialogTitle]]</div>
- <div class="dialog-body">
+ <div slot="dialog-title">[[dialogTitle]]</div>
+ <div slot="dialog-body">
<paper-spinner active></paper-spinner>
<div id="configuringMessage">$i18n{printerConfiguringMessage}</div>
</div>
- <div class="dialog-buttons">
+ <div slot="dialog-buttons">
<paper-button class="cancel-button secondary-button"
on-tap="onCancelConfiguringTap_">
$i18n{cancelButtonText}
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
index cc4df13e0ed..3b298a30f59 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
@@ -474,9 +474,9 @@ Polymer({
this.set(domIfBooleanName, true);
this.async(function() {
var dialog = this.$$(toDialog);
- dialog.addEventListener('close', function() {
+ dialog.addEventListener('close', () => {
this.set(domIfBooleanName, false);
- }.bind(this));
+ });
});
},
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_util.html b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_util.html
index 9ab2bee9442..797f6fe0f76 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_util.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_util.html
@@ -87,7 +87,7 @@
border-bottom: 1px solid var(--paper-grey-300) !important;
};
}
- #dialog .body {
+ #dialog [slot=body] {
-webkit-padding-end: 0;
-webkit-padding-start: 0;
height: 350px;
@@ -95,14 +95,14 @@
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">
- <content select=".dialog-title"></content>
+ <div slot="title">
+ <slot name="dialog-title"></slot>
</div>
- <div class="body" slot="body" scrollable>
- <content select=".dialog-body"></content>
+ <div slot="body" scrollable>
+ <slot name="dialog-body"></slot>
</div>
- <div class="button-container" slot="button-container">
- <content select=".dialog-buttons"></content>
+ <div slot="button-container">
+ <slot name="dialog-buttons"></slot>
</div>
</dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html
index f98aa2d4d5d..9fd71be3631 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html
@@ -11,8 +11,8 @@
<template>
<style include="cups-printer-shared"></style>
<add-printer-dialog>
- <div class="dialog-title">$i18n{editPrinterDialogTitle}</div>
- <div class="dialog-body">
+ <div slot="dialog-title">$i18n{editPrinterDialogTitle}</div>
+ <div slot="dialog-body">
<div class="settings-box first two-line">
<div class="start">
<div class="label">$i18n{printerName}</div>
@@ -109,7 +109,7 @@
</div>
</div>
</div>
- <div class="dialog-buttons">
+ <div slot="dialog-buttons">
<paper-button class="cancel-button secondary-button"
on-tap="onCancelTap_">
$i18n{cancelButtonText}
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
index 097523c1a5a..029074eb08d 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
@@ -6,40 +6,40 @@
<dom-module id="cups-printer-shared">
<template>
<style include="settings-shared md-select">
- .dialog-body .settings-box {
+ [slot='dialog-body'] .settings-box {
border-top: none;
margin-bottom: 10px;
}
- .dialog-body .settings-box .two-line {
+ [slot='dialog-body'] .settings-box .two-line {
min-height: 72px;
}
- .dialog-body .settings-box .start .label {
+ [slot='dialog-body'] .settings-box .start .label {
color: var(--google-grey-700);
}
- .dialog-body .settings-box paper-input {
+ [slot='dialog-body'] .settings-box paper-input {
--paper-input-container-input: {
font-size: inherit;
};
width: 270px;
}
- .dialog-body .settings-box .md-select-wrapper {
+ [slot='dialog-body'] .settings-box .md-select-wrapper {
-webkit-margin-start: calc(-1 * var(--md-select-side-padding));
margin-top: 8px;
}
- .dialog-body .settings-box .md-select {
+ [slot='dialog-body'] .settings-box .md-select {
width: calc(270px + calc(2* var(--md-select-side-padding)));
}
- .dialog-body .settings-box .printer-name-input {
+ [slot='dialog-body'] .settings-box .printer-name-input {
width: 450px;
}
- .dialog-body .settings-box .browse-file-input {
+ [slot='dialog-body'] .settings-box .browse-file-input {
--paper-input-container-input: {
border: 1px solid lightgray;
font-size: inherit;
@@ -56,16 +56,16 @@
width: 340px;
}
- .dialog-body .settings-box .browse-button {
+ [slot='dialog-body'] .settings-box .browse-button {
-webkit-margin-start: 5px;
color: black;
}
- .dialog-body .last {
+ [slot='dialog-body'] .last {
margin-top: 20px;
}
- .dialog-body .center {
+ [slot='dialog-body'] .center {
display: flex;
justify-content: center;
position: absolute;
@@ -73,7 +73,7 @@
width: 100%;
}
- .dialog-buttons {
+ [slot='dialog-buttons'] {
display: flex;
justify-content: space-between;
width: 100%;
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js
index 9f12f02571a..b1e36c367b3 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js
@@ -4,7 +4,7 @@
/**
* @fileoverview 'settings-cups-printers' is a component for showing CUPS
- * Printer settings subpage (chrome://md-settings/cupsPrinters). It is used to
+ * Printer settings subpage (chrome://settings/cupsPrinters). It is used to
* set up legacy & non-CloudPrint printers on ChromeOS by leveraging CUPS (the
* unix printing system) and the many open source drivers built for CUPS.
*/
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html
index 1a332d50761..8c4a1d51ac0 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html
@@ -15,10 +15,10 @@
</style>
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" on-tap="onEditTap_">
+ <button class="dropdown-item" on-tap="onEditTap_">
$i18n{editPrinter}
</button>
- <button class="dropdown-item" role="option" on-tap="onRemoveTap_">
+ <button class="dropdown-item" on-tap="onRemoveTap_">
$i18n{removePrinter}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/printing_page.html b/chromium/chrome/browser/resources/settings/printing_page/printing_page.html
index 43600892348..77eddcbbdfc 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/printing_page.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/printing_page.html
@@ -16,9 +16,6 @@
<style include="settings-shared"></style>
<settings-animated-pages id="pages" section="printing"
focus-config="[[focusConfig_]]">
- <array-selector id="arraySelector" items="{{cupsPrinters}}"
- selected="{{detailPrinter_}}">
- </array-selector>
<neon-animatable route-path="default">
<if expr="chromeos">
<div id="cupsPrinters" class="settings-box first"
@@ -32,8 +29,7 @@
on-tap="onTapCloudPrinters_" actionable>
<div class="start">$i18n{cloudPrintersTitle}</div>
<button class="subpage-arrow" is="paper-icon-button-light"
- aria-label="$i18n{cloudPrintersTitle}"
- aria-describedby="cloudPrintersSecondary"></button>
+ aria-label="$i18n{cloudPrintersTitle}"></button>
</div>
</neon-animatable>
<if expr="chromeos">
@@ -43,8 +39,7 @@
page-title="$i18n{cupsPrintersTitle}"
search-label="$i18n{searchLabel}"
search-term="{{searchTerm}}">
- <settings-cups-printers printers="{{cupsPrinters}}"
- search-term="{{searchTerm}}">
+ <settings-cups-printers search-term="{{searchTerm}}">
</settings-cups-printers>
</settings-subpage>
</template>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/printing_page.js b/chromium/chrome/browser/resources/settings/printing_page/printing_page.js
index 227e0146e87..8c8e14b2934 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/printing_page.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/printing_page.js
@@ -12,12 +12,6 @@ Polymer({
notify: true,
},
- /** @type {!Array<!CupsPrinterInfo>} */
- cupsPrinters: {
- type: Array,
- notify: true,
- },
-
searchTerm: {
type: String,
},
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html
index e4555fd9825..9485e7c1659 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html
+++ b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -1,7 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
@@ -10,6 +9,7 @@
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html">
<link rel="import" href="../clear_browsing_data_dialog/clear_browsing_data_dialog.html">
+<link rel="import" href="../clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../lifetime_browser_proxy.html">
<link rel="import" href="../route.html">
@@ -31,7 +31,7 @@
<link rel="import" href="../site_settings_page/site_settings_page.html">
<if expr="use_nss_certs">
-<link rel="import" href="../certificate_manager_page/certificate_manager_page.html">
+ <link rel="import" href="chrome://resources/cr_components/certificate_manager/certificate_manager.html">
</if>
<link rel="import" href="privacy_page_browser_proxy.html">
@@ -40,18 +40,25 @@
<style include="settings-shared">
</style>
<template is="dom-if" if="[[showClearBrowsingDataDialog_]]" restamp>
- <settings-clear-browsing-data-dialog prefs="{{prefs}}"
- on-close="onDialogClosed_">
- </settings-clear-browsing-data-dialog>
+ <template is="dom-if" if="[[!tabsInCbd_]]" restamp>
+ <settings-clear-browsing-data-dialog prefs="{{prefs}}"
+ on-close="onDialogClosed_">
+ </settings-clear-browsing-data-dialog>
+ </template>
+ <template is="dom-if" if="[[tabsInCbd_]]" restamp>
+ <settings-clear-browsing-data-dialog-tabs prefs="{{prefs}}"
+ on-close="onDialogClosed_">
+ </settings-clear-browsing-data-dialog-tabs>
+ </template>
</template>
<template id="doNotTrackDialogIf" is="dom-if"
if="[[showDoNotTrackDialog_]]" notify-dom-change>
<dialog is="cr-dialog" id="confirmDoNotTrackDialog"
close-text="$i18n{close}" on-cancel="onDoNotTrackDialogCancel_"
on-close="onDoNotTrackDialogClosed_">
- <div class="title" slot="title">$i18n{doNotTrackDialogTitle}</div>
- <div class="body" slot="body">$i18nRaw{doNotTrackDialogMessage}</div>
- <div class="button-container" slot="button-container">
+ <div slot="title">$i18n{doNotTrackDialogTitle}</div>
+ <div slot="body">$i18nRaw{doNotTrackDialogMessage}</div>
+ <div slot="button-container">
<paper-button class="cancel-button"
on-tap="onDoNotTrackDialogCancel_">
$i18n{cancel}
@@ -69,97 +76,68 @@
<div class="settings-box first">
<p class="privacy-explanation">$i18nRaw{improveBrowsingExperience}</p>
</div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.alternate_error_pages.enabled}}"
- label="$i18n{linkDoctorPref}">
- </settings-toggle-button>
- </div>
- <div class="settings-box" hidden="[[!pageVisibility.searchPrediction]]">
- <settings-toggle-button class="start"
- pref="{{prefs.search.suggest_enabled}}"
- label="$i18n{searchSuggestPref}">
- </settings-toggle-button>
- </div>
- <div class="settings-box"
- hidden="[[!pageVisibility.networkPrediction]]">
- <settings-toggle-button class="start"
- pref="{{prefs.net.network_prediction_options}}"
- label="$i18n{networkPredictionEnabled}"
- numeric-unchecked-value="[[networkPredictionEnum_.NEVER]]">
- </settings-toggle-button>
- </div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- id="safeBrowsingExtendedReportingControl"
- pref="[[safeBrowsingExtendedReportingPref_]]"
- label="$i18n{safeBrowsingEnableExtendedReporting}"
- on-settings-boolean-control-change="onSberChange_"
- no-set-pref>
- </settings-toggle-button>
- </div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.safebrowsing.enabled}}"
- label="$i18n{safeBrowsingEnableProtection}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button pref="{{prefs.alternate_error_pages.enabled}}"
+ label="$i18n{linkDoctorPref}">
+ </settings-toggle-button>
+ <settings-toggle-button hidden="[[!pageVisibility.searchPrediction]]"
+ pref="{{prefs.search.suggest_enabled}}"
+ label="$i18n{searchSuggestPref}">
+ </settings-toggle-button>
+ <settings-toggle-button hidden="[[!pageVisibility.networkPrediction]]"
+ pref="{{prefs.net.network_prediction_options}}"
+ label="$i18n{networkPredictionEnabled}"
+ numeric-unchecked-value="[[networkPredictionEnum_.NEVER]]">
+ </settings-toggle-button>
+ <settings-toggle-button id="safeBrowsingExtendedReportingControl"
+ pref="[[safeBrowsingExtendedReportingPref_]]"
+ label="$i18n{safeBrowsingEnableExtendedReporting}"
+ on-settings-boolean-control-change="onSberChange_"
+ no-set-pref>
+ </settings-toggle-button>
+ <settings-toggle-button pref="{{prefs.safebrowsing.enabled}}"
+ label="$i18n{safeBrowsingEnableProtection}">
+ </settings-toggle-button>
<if expr="_google_chrome">
<if expr="chromeos">
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.cros.metrics.reportingEnabled}}"
- label="$i18n{enableLogging}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button pref="{{prefs.cros.metrics.reportingEnabled}}"
+ label="$i18n{enableLogging}">
+ </settings-toggle-button>
</if><!-- chromeos -->
<if expr="not chromeos">
- <div class="settings-box">
- <settings-toggle-button class="start"
- id="metricsReportingControl"
- pref="[[metricsReportingPref_]]"
- label="$i18n{enableLogging}"
- on-settings-boolean-control-change="onMetricsReportingChange_"
- no-set-pref>
- <template is="dom-if" if="[[showRestart_]]" restamp>
- <paper-button on-tap="onRestartTap_" id="restart"
- class="more-actions">
- $i18n{restart}
- </paper-button>
- </template>
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="metricsReportingControl"
+ pref="[[metricsReportingPref_]]" label="$i18n{enableLogging}"
+ on-settings-boolean-control-change="onMetricsReportingChange_"
+ no-set-pref>
+ <template is="dom-if" if="[[showRestart_]]" restamp>
+ <paper-button on-tap="onRestartTap_" id="restart"
+ slot="more-actions">
+ $i18n{restart}
+ </paper-button>
+ </template>
+ </settings-toggle-button>
</if><!-- not chromeos -->
</if><!-- _google_chrome -->
- <div class="settings-box">
- <settings-toggle-button id="doNotTrack" class="start"
- pref="{{prefs.enable_do_not_track}}" label="$i18n{doNotTrack}"
- on-settings-boolean-control-change="onDoNotTrackChange_"
- no-set-pref>
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="doNotTrack"
+ pref="{{prefs.enable_do_not_track}}" label="$i18n{doNotTrack}"
+ on-settings-boolean-control-change="onDoNotTrackChange_"
+ no-set-pref>
+ </settings-toggle-button>
<if expr="chromeos">
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.cros.device.attestation_for_content_protection_enabled}}"
- label="$i18n{enableContentProtectionAttestation}">
- </settings-toggle-button>
- </div>
- <div class="settings-box">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.internet.wake_on_wifi_darkconnect}}"
- label="$i18n{wakeOnWifi}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.cros.device.attestation_for_content_protection_enabled}}"
+ label="$i18n{enableContentProtectionAttestation}">
+ </settings-toggle-button>
+ <settings-toggle-button
+ pref="{{prefs.settings.internet.wake_on_wifi_darkconnect}}"
+ label="$i18n{wakeOnWifi}">
+ </settings-toggle-button>
</if>
<if expr="_google_chrome">
- <div class="settings-box two-line">
- <settings-toggle-button class="start"
- pref="{{prefs.spellcheck.use_spelling_service}}"
- label="$i18n{spellingPref}"
- sub-label="$i18n{spellingDescription}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button
+ pref="{{prefs.spellcheck.use_spelling_service}}"
+ label="$i18n{spellingPref}"
+ sub-label="$i18n{spellingDescription}">
+ </settings-toggle-button>
</if>
<if expr="use_nss_certs or is_win or is_macosx">
<div id="manageCertificates" class="settings-box two-line"
@@ -213,8 +191,7 @@
<settings-subpage
associated-control="[[$$('#manageCertificates')]]"
page-title="$i18n{manageCertificates}">
- <settings-certificate-manager-page>
- </settings-certificate-manager-page>
+ <certificate-manager></certificate-manager>
</settings-subpage>
</template>
</if>
@@ -280,17 +257,31 @@
toggle-on-label="$i18n{siteSettingsCookiesAllowedRecommended}"
sub-option-label="$i18n{deleteDataPostSession}">
</category-default-setting>
- <div class="settings-box two-line">
- <settings-toggle-button class="start"
- pref="{{prefs.profile.block_third_party_cookies}}"
- label="$i18n{thirdPartyCookie}"
- sub-label="$i18n{thirdPartyCookieSublabel}">
- </settings-toggle-button>
+ <settings-toggle-button
+ pref="{{prefs.profile.block_third_party_cookies}}"
+ label="$i18n{thirdPartyCookie}"
+ sub-label="$i18n{thirdPartyCookieSublabel}">
+ </settings-toggle-button>
+ <div class="settings-box" actionable on-tap="onSiteDataTap_">
+ <div class="start" id="cookiesLink">
+ $i18n{siteSettingsCookieLink}
+ </div>
+ <button class="subpage-arrow" is="paper-icon-button-light"
+ aria-labelledby="cookiesLink">
+ </button>
</div>
<category-setting-exceptions
category="{{ContentSettingsTypes.COOKIES}}">
</category-setting-exceptions>
- <site-data focus-config="[[focusConfig_]]"></site-data>
+ </settings-subpage>
+ </template>
+ <template is="dom-if" route-path="/siteData" no-search>
+ <settings-subpage page-title="$i18n{siteSettingsCookieHeader}"
+ search-label="$i18n{siteSettingsCookieSearch}"
+ search-term="{{siteDataFilter_}}">
+ <site-data filter="[[siteDataFilter_]]"
+ focus-config="[[focusConfig_]]">
+ </site-data>
</settings-subpage>
</template>
<template is="dom-if" route-path="/content/images" no-search>
@@ -346,6 +337,21 @@
</category-setting-exceptions>
</settings-subpage>
</template>
+ <template is="dom-if" if="[[enableSoundContentSetting_]]"
+ no-search>
+ <template is="dom-if" route-path="/content/sound" no-search>
+ <settings-subpage page-title="$i18n{siteSettingsSound}">
+ <category-default-setting
+ toggle-off-label="$i18n{siteSettingsBlocked}"
+ toggle-on-label="$i18n{siteSettingsAllowedRecommended}"
+ category="{{ContentSettingsTypes.SOUND}}">
+ </category-default-setting>
+ <category-setting-exceptions
+ category="{{ContentSettingsTypes.SOUND}}">
+ </category-setting-exceptions>
+ </settings-subpage>
+ </template>
+ </template>
<template is="dom-if" route-path="/content/microphone" no-search>
<settings-subpage page-title="$i18n{siteSettingsCategoryMicrophone}">
<media-picker label="$i18n{siteSettingsMicrophoneLabel}" type="mic">
@@ -376,9 +382,7 @@
<settings-subpage page-title="$i18n{siteSettingsFlash}">
<category-default-setting category="{{ContentSettingsTypes.PLUGINS}}"
toggle-off-label="$i18n{siteSettingsFlashBlock}"
- toggle-on-label="$i18n{siteSettingsFlashAllow}"
- sub-option-label="$i18n{siteSettingsFlashAskBefore}"
- sub-option-secondary="$i18n{siteSettingsFlashAskBeforeSubtitle}">
+ toggle-on-label="$i18n{siteSettingsFlashAskFirstRecommended}">
</category-default-setting>
<if expr="chromeos">
<a class="settings-box inherit-color no-outline" tabindex="-1"
@@ -453,13 +457,13 @@
</settings-subpage>
</template>
<template is="dom-if" route-path="/content/siteDetails" no-search>
- <settings-subpage page-title="$i18n{siteSettingsSiteDetails}">
- <site-details></site-details>
+ <settings-subpage page-title="[[pageTitle]]">
+ <site-details page-title="{{pageTitle}}"></site-details>
</settings-subpage>
</template>
<template is="dom-if" route-path="/cookies/detail" no-search>
<settings-subpage page-title="[[pageTitle]]">
- <paper-button class="subpage-title-extra secondary-button"
+ <paper-button slot="subpage-title-extra" class="secondary-button"
on-tap="onRemoveAllCookiesFromSite_">
$i18n{siteSettingsCookieRemoveAll}
</paper-button>
@@ -469,26 +473,22 @@
</template>
<template is="dom-if" route-path="/content/protectedContent" no-search>
<settings-subpage page-title="$i18n{siteSettingsProtectedContent}">
- <div class="settings-box first">
- <settings-toggle-button class="start"
- pref="{{prefs.webkit.webprefs.encrypted_media_enabled}}"
- label="[[getProtectedContentLabel_(
- prefs.webkit.webprefs.encrypted_media_enabled.value)]]"
- disabled$="[[isGuest_]]">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="first"
+ pref="{{prefs.webkit.webprefs.encrypted_media_enabled}}"
+ label="[[getProtectedContentLabel_(
+ prefs.webkit.webprefs.encrypted_media_enabled.value)]]"
+ disabled$="[[isGuest_]]">
+ </settings-toggle-button>
<if expr="chromeos or is_win">
<div class="settings-box first two-line">
$i18n{siteSettingsProtectedContentIdentifiersExplanation}
</div>
- <div class="settings-box first">
- <settings-toggle-button class="start"
- pref="{{prefs.settings.privacy.drm_enabled}}"
- label="[[getProtectedContentIdentifiersLabel_(
- prefs.settings.privacy.drm_enabled.value)]]"
- disabled$="[[isGuest_]]">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button class="first"
+ pref="{{prefs.settings.privacy.drm_enabled}}"
+ label="[[getProtectedContentIdentifiersLabel_(
+ prefs.settings.privacy.drm_enabled.value)]]"
+ disabled$="[[isGuest_]]">
+ </settings-toggle-button>
</if>
<if expr="chromeos">
<template is="dom-if"
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js
index 1aff5845e17..cb15fd06ff5 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js
+++ b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js
@@ -75,6 +75,14 @@ Polymer({
showClearBrowsingDataDialog_: Boolean,
/** @private */
+ tabsInCbd_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('tabsInCbd');
+ }
+ },
+
+ /** @private */
showDoNotTrackDialog_: {
type: Boolean,
value: false,
@@ -99,6 +107,14 @@ Polymer({
}
},
+ /** @private */
+ enableSoundContentSetting_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('enableSoundContentSetting');
+ }
+ },
+
/** @private {!Map<string, string>} */
focusConfig_: {
type: Object,
@@ -237,6 +253,11 @@ Polymer({
},
/** @private */
+ onSiteDataTap_: function() {
+ settings.navigateTo(settings.routes.SITE_SETTINGS_SITE_DATA);
+ },
+
+ /** @private */
onSiteSettingsTap_: function() {
settings.navigateTo(settings.routes.SITE_SETTINGS);
},
diff --git a/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html b/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
index bd4237500dd..1459a9afe0e 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
+++ b/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
@@ -12,8 +12,8 @@
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}"
ignore-enter-key>
- <div class="title" slot="title">$i18n{powerwashDialogTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{powerwashDialogTitle}</div>
+ <div slot="body">
<span>
$i18n{powerwashDialogExplanation}
<a href="$i18nRaw{powerwashLearnMoreUrl}" target="_blank">
@@ -21,7 +21,7 @@
</a>
</span>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelTap_"
id="cancel">$i18n{cancel}</paper-button>
<paper-button class="action-button" id="powerwash"
diff --git a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html
index 31741b41452..3f49fa4eb03 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html
+++ b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html
@@ -9,8 +9,8 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}" ignore-popstate>
- <div class="title" slot="title">$i18n{resetAutomatedDialogTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{resetAutomatedDialogTitle}</div>
+ <div slot="body">
<span id="description">
$i18n{resetProfileBannerDescription}
<a id="learnMore"
@@ -18,7 +18,7 @@
target="_blank">$i18n{learnMore}</a>
</span>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onOkTap_" id="ok">
$i18n{ok}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
index 670b2646484..b46a992b0d0 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
+++ b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
@@ -21,10 +21,10 @@
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}"
ignore-popstate ignore-enter-key>
- <div class="title" slot="title">
+ <div slot="title">
[[getPageTitle_(isTriggered_, triggeredResetToolName_)]]
</div>
- <div class="body" slot="body">
+ <div slot="body">
<span>
[[getExplanationText_(isTriggered_, triggeredResetToolName_)]]
<a href="$i18nRaw{resetPageLearnMoreUrl}" target="_blank">
@@ -32,7 +32,7 @@
</a>
</span>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-spinner id="resetSpinner" active="[[clearingInProgress_]]">
</paper-spinner>
<paper-button class="cancel-button" on-tap="onCancelTap_"
@@ -44,7 +44,7 @@
$i18n{resetPageCommit}
</paper-button>
</div>
- <div class="footer" slot="footer">
+ <div slot="footer">
<paper-checkbox id="sendSettings" checked>
$i18nRaw{resetPageFeedback}</paper-checkbox>
</div>
diff --git a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js
index ccbe17a0328..40827a89e20 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js
+++ b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js
@@ -72,9 +72,9 @@ Polymer({
ready: function() {
this.browserProxy_ = settings.ResetBrowserProxyImpl.getInstance();
- this.addEventListener('cancel', function() {
+ this.addEventListener('cancel', () => {
this.browserProxy_.onHideResetProfileDialog();
- }.bind(this));
+ });
this.$$('paper-checkbox a')
.addEventListener('tap', this.onShowReportedSettingsTap_.bind(this));
@@ -96,11 +96,11 @@ Polymer({
this.isTriggered_ =
settings.getCurrentRoute() == settings.routes.TRIGGERED_RESET_DIALOG;
if (this.isTriggered_) {
- this.browserProxy_.getTriggeredResetToolName().then(function(name) {
+ this.browserProxy_.getTriggeredResetToolName().then(name => {
this.resetRequestOrigin_ = 'triggeredreset';
this.triggeredResetToolName_ = name;
this.showDialog_();
- }.bind(this));
+ });
} else {
// For the non-triggered reset dialog, a '#cct' hash indicates that the
// reset request came from the Chrome Cleanup Tool by launching Chrome
@@ -124,12 +124,12 @@ Polymer({
this.browserProxy_
.performResetProfileSettings(
this.$.sendSettings.checked, this.resetRequestOrigin_)
- .then(function() {
+ .then(() => {
this.clearingInProgress_ = false;
if (this.$.dialog.open)
this.$.dialog.close();
this.fire('reset-done');
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/route.js b/chromium/chrome/browser/resources/settings/route.js
index d7782489646..d4dee7d83f3 100644
--- a/chromium/chrome/browser/resources/settings/route.js
+++ b/chromium/chrome/browser/resources/settings/route.js
@@ -71,6 +71,7 @@
* SITE_SETTINGS_HANDLERS: (undefined|!settings.Route),
* SITE_SETTINGS_IMAGES: (undefined|!settings.Route),
* SITE_SETTINGS_JAVASCRIPT: (undefined|!settings.Route),
+ * SITE_SETTINGS_SOUND: (undefined|!settings.Route),
* SITE_SETTINGS_LOCATION: (undefined|!settings.Route),
* SITE_SETTINGS_MICROPHONE: (undefined|!settings.Route),
* SITE_SETTINGS_MIDI_DEVICES: (undefined|!settings.Route),
@@ -78,6 +79,7 @@
* SITE_SETTINGS_PDF_DOCUMENTS: (undefined|!settings.Route),
* SITE_SETTINGS_POPUPS: (undefined|!settings.Route),
* SITE_SETTINGS_PROTECTED_CONTENT: (undefined|!settings.Route),
+ * SITE_SETTINGS_SITE_DATA: (undefined|!settings.Route),
* SITE_SETTINGS_SITE_DETAILS: (undefined|!settings.Route),
* SITE_SETTINGS_UNSANDBOXED_PLUGINS: (undefined|!settings.Route),
* SITE_SETTINGS_USB_DEVICES: (undefined|!settings.Route),
@@ -235,7 +237,7 @@ cr.define('settings', function() {
if (pageVisibility.onStartup !== false) {
r.ON_STARTUP = r.BASIC.createSection('/onStartup', 'onStartup');
- r.STARTUP_URLS = r.ON_STARTUP.createChild('/startupUrls');
+ r.STARTUP_PAGES = r.ON_STARTUP.createChild('/startupPages');
}
if (pageVisibility.people !== false) {
@@ -262,7 +264,7 @@ cr.define('settings', function() {
r.POWER = r.DEVICE.createChild('/power');
// </if>
- // Advacned Routes
+ // Advanced Routes
if (pageVisibility.advancedSettings !== false) {
r.ADVANCED = new Route('/advanced');
@@ -298,10 +300,13 @@ cr.define('settings', function() {
r.SITE_SETTINGS.createChild('backgroundSync');
r.SITE_SETTINGS_CAMERA = r.SITE_SETTINGS.createChild('camera');
r.SITE_SETTINGS_COOKIES = r.SITE_SETTINGS.createChild('cookies');
+ r.SITE_SETTINGS_SITE_DATA =
+ r.SITE_SETTINGS_COOKIES.createChild('/siteData');
r.SITE_SETTINGS_DATA_DETAILS =
- r.SITE_SETTINGS_COOKIES.createChild('/cookies/detail');
+ r.SITE_SETTINGS_SITE_DATA.createChild('/cookies/detail');
r.SITE_SETTINGS_IMAGES = r.SITE_SETTINGS.createChild('images');
r.SITE_SETTINGS_JAVASCRIPT = r.SITE_SETTINGS.createChild('javascript');
+ r.SITE_SETTINGS_SOUND = r.SITE_SETTINGS.createChild('sound');
r.SITE_SETTINGS_LOCATION = r.SITE_SETTINGS.createChild('location');
r.SITE_SETTINGS_MICROPHONE = r.SITE_SETTINGS.createChild('microphone');
r.SITE_SETTINGS_NOTIFICATIONS =
@@ -426,13 +431,15 @@ cr.define('settings', function() {
* @param {boolean} isPopstate
*/
setCurrentRoute(route, queryParameters, isPopstate) {
+ this.recordMetrics(route.path);
+
var oldRoute = this.currentRoute;
this.currentRoute = route;
this.currentQueryParameters_ = queryParameters;
this.wasLastRouteChangePopstate_ = isPopstate;
- routeObservers.forEach(function(observer) {
+ new Set(routeObservers).forEach((observer) => {
observer.currentRouteChanged(this.currentRoute, oldRoute);
- }.bind(this));
+ });
}
/** @return {!settings.Route} */
@@ -461,9 +468,9 @@ cr.define('settings', function() {
var canonicalPath = path.replace(CANONICAL_PATH_REGEX, '$1$2');
// TODO(tommycli): Use Object.values once Closure compilation supports it.
- var matchingKey = Object.keys(this.routes_).find(function(key) {
- return this.routes_[key].path == canonicalPath;
- }.bind(this));
+ var matchingKey =
+ Object.keys(this.routes_)
+ .find((key) => this.routes_[key].path == canonicalPath);
return !!matchingKey ? this.routes_[matchingKey] : null;
}
@@ -523,6 +530,8 @@ cr.define('settings', function() {
* Initialize the route and query params from the URL.
*/
initializeRouteFromUrl() {
+ this.recordMetrics(window.location.pathname);
+
assert(!this.initializeRouteFromUrlCalled_);
this.initializeRouteFromUrlCalled_ = true;
@@ -537,6 +546,18 @@ cr.define('settings', function() {
}
}
+ /**
+ * Make a UMA note about visiting this URL path.
+ * @param {string} urlPath The url path (only).
+ */
+ recordMetrics(urlPath) {
+ assert(!urlPath.startsWith('chrome://'));
+ assert(!urlPath.startsWith('settings'));
+ assert(urlPath.startsWith('/'));
+ chrome.metricsPrivate.recordSparseHashable(
+ 'WebUI.Settings.PathVisited', urlPath);
+ }
+
resetRouteForTesting() {
this.initializeRouteFromUrlCalled_ = false;
this.wasLastRouteChangePopstate_ = false;
@@ -569,7 +590,6 @@ cr.define('settings', function() {
/**
* @param {!settings.Route|undefined} opt_newRoute
* @param {!settings.Route|undefined} opt_oldRoute
- * @abstract
*/
currentRouteChanged: function(opt_newRoute, opt_oldRoute) {
assertNotReached();
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/omnibox_extension_entry.html b/chromium/chrome/browser/resources/settings/search_engines_page/omnibox_extension_entry.html
index fe15b6acc7d..aa5677369c5 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/omnibox_extension_entry.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/omnibox_extension_entry.html
@@ -39,12 +39,10 @@
focus-type="menu">
</button>
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" on-tap="onManageTap_"
- id="manage">
+ <button class="dropdown-item" on-tap="onManageTap_" id="manage">
$i18n{searchEnginesManageExtension}
</button>
- <button class="dropdown-item" role="option" on-tap="onDisableTap_"
- id="disable">
+ <button class="dropdown-item" on-tap="onDisableTap_" id="disable">
$i18n{disable}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
index f9ee6494df8..a2788c608ec 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
@@ -23,8 +23,8 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">[[dialogTitle_]]</div>
- <div class="body" slot="body">
+ <div slot="title">[[dialogTitle_]]</div>
+ <div slot="body" spellcheck="false">
<paper-input always-float-label id="searchEngine"
label="$i18n{searchEnginesSearchEngine}"
error-message="$i18n{notValid}"
@@ -43,7 +43,7 @@
disabled$="[[model.urlLocked]]">
</paper-input>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="cancel_" id="cancel">
$i18n{cancel}</paper-button>
<paper-button id="actionButton" class="action-button"
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js
index f77d20022fe..465bfa25f34 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js
@@ -66,9 +66,9 @@ Polymer({
this.actionButtonText_ = loadTimeData.getString('add');
}
- this.addEventListener('cancel', function() {
+ this.addEventListener('cancel', () => {
this.browserProxy_.searchEngineEditCancelled();
- }.bind(this));
+ });
},
/** @override */
@@ -108,10 +108,10 @@ Polymer({
this.browserProxy_
.validateSearchEngineInput(inputElement.id, inputElement.value)
- .then(function(isValid) {
+ .then(isValid => {
inputElement.invalid = !isValid;
this.updateActionButtonState_();
- }.bind(this));
+ });
},
/** @private */
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.html b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.html
index 1b3bea51362..f4b23582e1c 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.html
@@ -58,16 +58,18 @@
focus-type="cr-menu-button">
</button>
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" on-tap="onMakeDefaultTap_"
+ <button class="dropdown-item" on-tap="onMakeDefaultTap_"
hidden$="[[!engine.canBeDefault]]" id="makeDefault">
$i18n{searchEnginesMakeDefault}
</button>
- <button class="dropdown-item" role="option" on-tap="onEditTap_"
- hidden$="[[!engine.canBeEdited]]"
- id="edit">$i18n{edit}</button>
- <button class="dropdown-item" role="option" on-tap="onDeleteTap_"
- hidden$="[[!engine.canBeRemoved]]"
- id="delete">$i18n{searchEnginesRemoveFromList}</button>
+ <button class="dropdown-item" on-tap="onEditTap_"
+ hidden$="[[!engine.canBeEdited]]" id="edit">
+ $i18n{edit}
+ </button>
+ <button class="dropdown-item" on-tap="onDeleteTap_"
+ hidden$="[[!engine.canBeRemoved]]" id="delete">
+ $i18n{searchEnginesRemoveFromList}
+ </button>
</dialog>
</div>
<template is="dom-if" if="[[engine.extension]]">
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.js b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.js
index be252d7f506..411cae85301 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.js
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_entry.js
@@ -98,17 +98,17 @@ Polymer({
this.closePopupMenu_();
this.showEditSearchEngineDialog_ = true;
- this.async(function() {
+ this.async(() => {
var dialog = this.$$('settings-search-engine-dialog');
// Register listener to detect when the dialog is closed. Flip the boolean
// once closed to force a restamp next time it is shown such that the
// previous dialog's contents are cleared.
- dialog.addEventListener('close', function() {
+ dialog.addEventListener('close', () => {
this.showEditSearchEngineDialog_ = false;
cr.ui.focusWithoutInk(
assert(this.$$('button[is="paper-icon-button-light"]')));
- }.bind(this));
- }.bind(this));
+ });
+ });
},
/** @private */
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js
index 76642485c21..cd6e4d6f295 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js
@@ -85,9 +85,6 @@ cr.define('settings', function() {
/** @param {boolean} enabled */
setHotwordSearchEnabled(enabled) {}
-
- /** @return {!Promise<boolean>} */
- getGoogleNowAvailability() {}
}
/**
@@ -143,11 +140,6 @@ cr.define('settings', function() {
setHotwordSearchEnabled(enabled) {
chrome.send('setHotwordSearchEnabled', [enabled]);
}
-
- /** @override */
- getGoogleNowAvailability() {
- return cr.sendWithPromise('getGoogleNowAvailability');
- }
}
// The singleton instance_ is replaced with a test version of this wrapper
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.html b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.html
index 0b74c3f50bd..507bf4875ad 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.html
@@ -26,10 +26,6 @@
@apply(--settings-list-frame-padding);
}
- /* TODO(dbeam): this rule results in incorrectly showing a top border for
- * "Other Search Engines", which hides the headers while still adding a
- * dividing line (even though there's no content above the other engines
- * to actually divide). */
settings-search-engine-entry {
border-top: var(--settings-separator-line);
}
@@ -48,7 +44,7 @@
}
</style>
<div id="outer">
- <div id="headers" class="column-header" hidden$="[[hideHeaders]]">
+ <div id="headers" class="column-header">
<div class="name">$i18n{searchEnginesSearchEngine}</div>
<div class="keyword">$i18n{searchEnginesKeyword}</div>
<div class="url">$i18n{searchEnginesQueryURL}</div>
@@ -58,7 +54,7 @@
class$="scroll-container [[getHeightClass(scrollTarget)]]"
scrollable$="[[isScrollable(scrollTarget)]]">
<iron-list items="[[engines]]" scroll-target="[[scrollTarget]]"
- scroll-offset="[[scrollOffset]]" preserve-focus>
+ scroll-offset="[[scrollOffset]]" preserve-focus risk-selection>
<template>
<settings-search-engine-entry engine="[[item]]"
tabindex$="[[tabIndex]]" iron-list-tab-index="[[tabIndex]]"
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.js b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.js
index eb74091ec67..f4e193f85b4 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.js
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_list.js
@@ -13,9 +13,6 @@ Polymer({
/** @type {!Array<!SearchEngine>} */
engines: Array,
- /** Whether column headers should be displayed */
- hideHeaders: Boolean,
-
/**
* The scroll target that this list should use.
* @type {?HTMLElement}
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
index 7323258bf68..eb06d3cd345 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
@@ -17,7 +17,8 @@
<template>
<style include="settings-shared action-link">
.extension-engines,
- #noOtherEngines {
+ #noOtherEngines,
+ .no-search-results {
@apply(--settings-list-frame-padding);
}
@@ -28,7 +29,12 @@
<div class="settings-box first">
<h2>$i18n{searchEnginesDefault}</h2>
</div>
- <settings-search-engines-list engines="[[defaultEngines]]">
+ <div class="no-search-results" hidden="[[matchingDefaultEngines_.length]]">
+ $i18n{searchNoResults}
+ </div>
+ <settings-search-engines-list
+ hidden="[[!matchingDefaultEngines_.length]]"
+ engines="[[matchingDefaultEngines_]]">
</settings-search-engines-list>
<template is="dom-if" if="[[showAddSearchEngineDialog_]]" restamp>
<settings-search-engine-dialog></settings-search-engine-dialog>
@@ -44,15 +50,25 @@
<div id="noOtherEngines" hidden="[[otherEngines.length]]">
$i18n{searchEnginesNoOtherEngines}
</div>
- <settings-search-engines-list id="otherEngines" engines="[[otherEngines]]"
- hide-headers scroll-target="[[subpageScrollTarget]]">
+ <div class="no-search-results"
+ hidden="[[!showNoResultsMessage_(
+ otherEngines, matchingOtherEngines_)]]">
+ $i18n{searchNoResults}
+ </div>
+ <settings-search-engines-list id="otherEngines"
+ hidden="[[!matchingOtherEngines_.length]]"
+ engines="[[matchingOtherEngines_]]"
+ scroll-target="[[subpageScrollTarget]]">
</settings-search-engines-list>
<template is="dom-if" if="[[showExtensionsList_]]">
<div class="settings-box first">
<h2>$i18n{searchEnginesExtension}</h2>
</div>
+ <div class="no-search-results" hidden="[[matchingExtensions_.length]]">
+ $i18n{searchNoResults}
+ </div>
<iron-list id="extensions" class="extension-engines fixed-height-list"
- items="[[extensions]]" preserve-focus>
+ items="[[matchingExtensions_]]" preserve-focus risk-selection>
<template>
<settings-omnibox-extension-entry engine="[[item]]"
tabindex$="[[tabIndex]]" iron-list-tab-index="[[tabIndex]]"
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.js b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.js
index 57cf8a0a8ec..01eb65555c1 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.js
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.js
@@ -13,28 +13,13 @@ Polymer({
properties: {
/** @type {!Array<!SearchEngine>} */
- defaultEngines: {
- type: Array,
- value: function() {
- return [];
- }
- },
+ defaultEngines: Array,
/** @type {!Array<!SearchEngine>} */
- otherEngines: {
- type: Array,
- value: function() {
- return [];
- }
- },
+ otherEngines: Array,
/** @type {!Array<!SearchEngine>} */
- extensions: {
- type: Array,
- value: function() {
- return [];
- }
- },
+ extensions: Array,
/**
* Needed by GlobalScrollTargetBehavior.
@@ -54,6 +39,30 @@ Polymer({
computed: 'computeShowExtensionsList_(extensions)',
},
+ /** Filters out all search engines that do not match. */
+ filter: {
+ type: String,
+ value: '',
+ },
+
+ /** @private {!Array<!SearchEngine>} */
+ matchingDefaultEngines_: {
+ type: Array,
+ computed: 'computeMatchingEngines_(defaultEngines, filter)',
+ },
+
+ /** @private {!Array<!SearchEngine>} */
+ matchingOtherEngines_: {
+ type: Array,
+ computed: 'computeMatchingEngines_(otherEngines, filter)',
+ },
+
+ /** @private {!Array<!SearchEngine>} */
+ matchingExtensions_: {
+ type: Array,
+ computed: 'computeMatchingEngines_(extensions, filter)',
+ },
+
/** @private {HTMLElement} */
omniboxExtensionlastFocused_: Object,
},
@@ -105,20 +114,47 @@ Polymer({
onAddSearchEngineTap_: function(e) {
e.preventDefault();
this.showAddSearchEngineDialog_ = true;
- this.async(function() {
+ this.async(() => {
var dialog = this.$$('settings-search-engine-dialog');
// Register listener to detect when the dialog is closed. Flip the boolean
// once closed to force a restamp next time it is shown such that the
// previous dialog's contents are cleared.
- dialog.addEventListener('close', function() {
+ dialog.addEventListener('close', () => {
this.showAddSearchEngineDialog_ = false;
cr.ui.focusWithoutInk(assert(this.$.addSearchEngine));
- }.bind(this));
- }.bind(this));
+ });
+ });
},
/** @private */
computeShowExtensionsList_: function() {
return this.extensions.length > 0;
},
+
+ /**
+ * Filters the given list based on the currently existing filter string.
+ * @param {!Array<!SearchEngine>} list
+ * @return {!Array<!SearchEngine>}
+ * @private
+ */
+ computeMatchingEngines_: function(list) {
+ if (this.filter == '')
+ return list;
+
+ var filter = this.filter.toLowerCase();
+ return list.filter(e => {
+ return [e.displayName, e.name, e.keyword, e.url].some(
+ term => term.toLowerCase().includes(filter));
+ });
+ },
+
+ /**
+ * @param {!Array<!SearchEngine>} list The original list.
+ * @param {!Array<!SearchEngine>} filteredList The filtered list.
+ * @return {boolean} Whether to show the "no results" message.
+ * @private
+ */
+ showNoResultsMessage_: function(list, filteredList) {
+ return list.length > 0 && filteredList.length == 0;
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/search_page/search_page.html b/chromium/chrome/browser/resources/settings/search_page/search_page.html
index 0d3dede7a8e..ad39252a6b1 100644
--- a/chromium/chrome/browser/resources/settings/search_page/search_page.html
+++ b/chromium/chrome/browser/resources/settings/search_page/search_page.html
@@ -82,33 +82,22 @@
</template>
</div>
- <template is="dom-if" if="[[googleNowAvailable_]]">
- <!-- Google Now cards in the launcher -->
- <div class="settings-box continuation indented">
- <settings-toggle-button id="googleNowEnable" class="start"
- pref="{{prefs.google_now_launcher.enabled}}"
- label="$i18n{searchEnableGoogleNowLabel}">
- </settings-toggle-button>
- </div>
- </template>
-
<template is="dom-if" if="[[hotwordInfo_.allowed]]">
<!-- Hotword (OK Google) -->
- <div class="settings-box two-line continuation indented">
- <settings-toggle-button id="hotwordSearchEnable" class="start"
- pref="{{hotwordSearchEnablePref_}}"
- label="$i18n{searchOkGoogleLabel}"
- sub-label="[[getHotwordSearchEnableSubLabel_(
- hotwordInfo_.alwaysOn)]]"
- on-change="onHotwordSearchEnableChange_">
- </settings-toggle-button>
- <div class="settings-row"
- hidden$="[[!getShowHotwordSearchRetrain_(hotwordInfo_.*)]]">
- <div class="separator"></div>
- <paper-button on-tap="onRetrainTap_" class="secondary-button">
- $i18n{searchOkGoogleRetrain}
- </paper-button>
- </div>
+ <settings-toggle-button id="hotwordSearchEnable"
+ class="continuation indented"
+ pref="{{hotwordSearchEnablePref_}}"
+ label="$i18n{searchOkGoogleLabel}"
+ sub-label="[[getHotwordSearchEnableSubLabel_(
+ hotwordInfo_.alwaysOn)]]"
+ on-change="onHotwordSearchEnableChange_">
+ </settings-toggle-button>
+ <div class="settings-row indented"
+ hidden$="[[!getShowHotwordSearchRetrain_(hotwordInfo_.*)]]">
+ <div class="separator"></div>
+ <paper-button on-tap="onRetrainTap_" class="secondary-button">
+ $i18n{searchOkGoogleRetrain}
+ </paper-button>
</div>
<template is="dom-if"
@@ -162,7 +151,8 @@
<if expr="chromeos">
<!-- Google Assistant -->
<template is="dom-if" if="[[showAssistantSection_(
- voiceInteractionFeatureEnabled_, prefs.arc.enabled.value)]]">
+ voiceInteractionFeatureEnabled_, prefs.arc.enabled.value,
+ prefs.arc.voice_interaction_value_prop.accepted.value)]]">
<div id="assistant-subpage-trigger" class="settings-box two-line"
on-tap="onGoogleAssistantTap_" actionable>
<div class="start">
@@ -181,8 +171,10 @@
<template is="dom-if" route-path="/searchEngines">
<settings-subpage
associated-control="[[$$('#engines-subpage-trigger')]]"
- page-title="$i18n{searchEnginesManage}">
- <settings-search-engines-page></settings-search-engines-page>
+ page-title="$i18n{searchEnginesManage}"
+ search-label="$i18n{searchEnginesSearch}"
+ search-term="{{searchEnginesFilter_}}">
+ <settings-search-engines-page filter="[[searchEnginesFilter_]]">
</settings-subpage>
</template>
<if expr="chromeos">
diff --git a/chromium/chrome/browser/resources/settings/search_page/search_page.js b/chromium/chrome/browser/resources/settings/search_page/search_page.js
index be8e1648d84..0d89eee48c0 100644
--- a/chromium/chrome/browser/resources/settings/search_page/search_page.js
+++ b/chromium/chrome/browser/resources/settings/search_page/search_page.js
@@ -25,6 +25,9 @@ Polymer({
}
},
+ /** @private Filter applied to search engines. */
+ searchEnginesFilter_: String,
+
/** @private {!SearchPageHotwordInfo|undefined} */
hotwordInfo_: Object,
@@ -37,9 +40,6 @@ Polymer({
*/
hotwordSearchEnablePref_: Object,
- /** @private */
- googleNowAvailable_: Boolean,
-
/** @type {?Map<string, string>} */
focusConfig_: Object,
@@ -65,10 +65,10 @@ Polymer({
/** @override */
ready: function() {
// Omnibox search engine
- var updateSearchEngines = function(searchEngines) {
+ var updateSearchEngines = searchEngines => {
this.set('searchEngines_', searchEngines.defaults);
this.requestHotwordInfoUpdate_();
- }.bind(this);
+ };
this.browserProxy_.getSearchEnginesList().then(updateSearchEngines);
cr.addWebUIListener('search-engines-changed', updateSearchEngines);
@@ -76,14 +76,6 @@ Polymer({
cr.addWebUIListener(
'hotword-info-update', this.hotwordInfoUpdate_.bind(this));
- // Google Now cards in the launcher
- cr.addWebUIListener(
- 'google-now-availability-changed',
- this.googleNowAvailabilityUpdate_.bind(this));
- this.browserProxy_.getGoogleNowAvailability().then(function(available) {
- this.googleNowAvailabilityUpdate_(available);
- }.bind(this));
-
this.focusConfig_ = new Map();
if (settings.routes.SEARCH_ENGINES) {
this.focusConfig_.set(
@@ -136,9 +128,9 @@ Polymer({
/** @private */
requestHotwordInfoUpdate_: function() {
- this.browserProxy_.getHotwordInfo().then(function(hotwordInfo) {
+ this.browserProxy_.getHotwordInfo().then(hotwordInfo => {
this.hotwordInfoUpdate_(hotwordInfo);
- }.bind(this));
+ });
},
/**
@@ -155,14 +147,6 @@ Polymer({
},
/**
- * @param {boolean} available
- * @private
- */
- googleNowAvailabilityUpdate_: function(available) {
- this.googleNowAvailable_ = available;
- },
-
- /**
* @return {string}
* @private
*/
@@ -212,8 +196,9 @@ Polymer({
* @return {boolean}
* @private
*/
- showAssistantSection_: function(featureAvailable, arcEnabled) {
- return featureAvailable && arcEnabled;
+ showAssistantSection_: function(
+ featureAvailable, arcEnabled, valuePropAccepted) {
+ return featureAvailable && arcEnabled && valuePropAccepted;
},
// </if>
diff --git a/chromium/chrome/browser/resources/settings/search_settings.js b/chromium/chrome/browser/resources/settings/search_settings.js
index 65c2cc6226c..2fb5a818ce4 100644
--- a/chromium/chrome/browser/resources/settings/search_settings.js
+++ b/chromium/chrome/browser/resources/settings/search_settings.js
@@ -205,7 +205,7 @@ cr.define('settings', function() {
searchBubble = document.createElement('div');
searchBubble.classList.add(SEARCH_BUBBLE_CSS_CLASS);
var innards = document.createElement('div');
- innards.classList.add('search-bubble-innards');
+ innards.classList.add('search-bubble-innards', 'text-elide');
innards.textContent = rawQuery;
searchBubble.appendChild(innards);
element.appendChild(searchBubble);
@@ -304,9 +304,9 @@ cr.define('settings', function() {
assert(!this.node.if);
this.node.if = true;
- return new Promise(function(resolve, reject) {
+ return new Promise((resolve, reject) => {
var parent = this.node.parentNode;
- parent.async(function() {
+ parent.async(() => {
var renderedNode =
parent.querySelector('[route-path="' + routePath + '"]');
// Register a SearchAndHighlightTask for the part of the DOM that was
@@ -314,8 +314,8 @@ cr.define('settings', function() {
this.request.queue_.addSearchAndHighlightTask(
new SearchAndHighlightTask(this.request, assert(renderedNode)));
resolve();
- }.bind(this));
- }.bind(this));
+ });
+ });
}
}
@@ -452,16 +452,16 @@ cr.define('settings', function() {
}
this.running_ = true;
- window.requestIdleCallback(function() {
+ window.requestIdleCallback(() => {
if (!this.request_.canceled) {
- task.exec().then(function() {
+ task.exec().then(() => {
this.running_ = false;
this.consumePending_();
- }.bind(this));
+ });
}
// Nothing to do otherwise. Since the request corresponding to this
// queue was canceled, the queue is disposed along with the request.
- }.bind(this));
+ });
return;
}
}
@@ -496,9 +496,9 @@ cr.define('settings', function() {
/** @private {!TaskQueue} */
this.queue_ = new TaskQueue(this);
- this.queue_.onEmpty(function() {
+ this.queue_.onEmpty(() => {
this.resolver.resolve(this);
- }.bind(this));
+ });
}
/**
@@ -588,11 +588,11 @@ cr.define('settings', function() {
var request = new SearchRequest(text, page);
this.activeRequests_.add(request);
request.start();
- return request.resolver.promise.then(function() {
+ return request.resolver.promise.then(() => {
// Stop tracking requests that finished.
this.activeRequests_.delete(request);
return request;
- }.bind(this));
+ });
}
}
cr.addSingletonGetter(SearchManagerImpl);
diff --git a/chromium/chrome/browser/resources/settings/settings_icons_css.html b/chromium/chrome/browser/resources/settings/settings_icons_css.html
index 8a3722daa1d..6936eac4e18 100644
--- a/chromium/chrome/browser/resources/settings/settings_icons_css.html
+++ b/chromium/chrome/browser/resources/settings/settings_icons_css.html
@@ -4,9 +4,6 @@
<dom-module id="settings-icons">
<template>
<style>
- button[is='paper-icon-button-light'].icon-arrow-back {
- background-image: url(./images/settings_icon_arrow_back.svg);
- }
button[is='paper-icon-button-light'].icon-visibility {
background-image: url(./images/settings_icon_visibility.svg);
}
diff --git a/chromium/chrome/browser/resources/settings/settings_main/settings_main.html b/chromium/chrome/browser/resources/settings/settings_main/settings_main.html
index d5321b5a172..fcbd63786ef 100644
--- a/chromium/chrome/browser/resources/settings/settings_main/settings_main.html
+++ b/chromium/chrome/browser/resources/settings/settings_main/settings_main.html
@@ -26,14 +26,12 @@
}
#noSearchResults {
- align-items: center;
- display: flex;
- flex-direction: column;
margin-top: 80px;
+ text-align: center;
}
#noSearchResults div:first-child {
- font-size: 120%;
+ font-size: 123%; /* Should be 16px when 100% is 13px. */
margin-bottom: 10px;
}
</style>
diff --git a/chromium/chrome/browser/resources/settings/settings_main/settings_main.js b/chromium/chrome/browser/resources/settings/settings_main/settings_main.js
index d81ee241c32..df1eb65bbc8 100644
--- a/chromium/chrome/browser/resources/settings/settings_main/settings_main.js
+++ b/chromium/chrome/browser/resources/settings/settings_main/settings_main.js
@@ -107,10 +107,10 @@ Polymer({
window.removeEventListener('resize', this.boundScroll_);
this.boundScroll_ = null;
} else if (this.overscroll_ && !this.boundScroll_) {
- this.boundScroll_ = function() {
+ this.boundScroll_ = () => {
if (!this.ignoreScroll_)
this.setOverscroll_(0);
- }.bind(this);
+ };
this.offsetParent.addEventListener('scroll', this.boundScroll_);
window.addEventListener('resize', this.boundScroll_);
}
@@ -184,11 +184,11 @@ Polymer({
this.updateOverscrollForPage_();
// Wait for any other changes, then calculate the overflow padding again.
- setTimeout(function() {
+ setTimeout(() => {
// Ensure any dom-if reflects the current properties.
Polymer.dom.flush();
this.updateOverscrollForPage_();
- }.bind(this));
+ });
},
/**
@@ -259,11 +259,11 @@ Polymer({
this.inSearchMode_ = true;
this.toolbarSpinnerActive = true;
- return new Promise(function(resolve, reject) {
- setTimeout(function() {
+ return new Promise((resolve, reject) => {
+ setTimeout(() => {
var whenSearchDone =
assert(this.getPage_(settings.routes.BASIC)).searchContents(query);
- whenSearchDone.then(function(result) {
+ whenSearchDone.then(result => {
resolve();
if (result.canceled) {
// Nothing to do here. A previous search request was canceled
@@ -285,8 +285,8 @@ Polymer({
loadTimeData.getStringF('searchResults', query)
});
}
- }.bind(this));
- }.bind(this), 0);
- }.bind(this));
+ });
+ }, 0);
+ });
},
});
diff --git a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html
index 6f387f2d476..735fdfe0324 100644
--- a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html
+++ b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html
@@ -33,7 +33,6 @@
min-height: 20px;
padding-bottom: 10px;
padding-top: 10px;
- word-break: break-word;
}
a[href].iron-selected {
@@ -97,7 +96,8 @@
<iron-icon icon="cr:person"></iron-icon>
$i18n{peoplePageTitle}
</a>
- <a href="/appearance" hidden="[[!pageVisibility.appearance]]">
+ <a id="appearance" href="/appearance"
+ hidden="[[!pageVisibility.appearance]]">
<iron-icon icon="settings:palette"></iron-icon>
$i18n{appearancePageTitle}
</a>
@@ -118,12 +118,14 @@
</a>
</if>
<if expr="not chromeos">
- <a href="/defaultBrowser" hidden="[[!pageVisibility.defaultBrowser]]">
+ <a id="defaultBrowser" href="/defaultBrowser"
+ hidden="[[!pageVisibility.defaultBrowser]]">
<iron-icon icon="settings:web"></iron-icon>
$i18n{defaultBrowser}
</a>
</if>
- <a href="/onStartup" hidden="[[!pageVisibility.onStartup]]">
+ <a id="onStartup" href="/onStartup"
+ hidden="[[!pageVisibility.onStartup]]">
<iron-icon icon="settings:power-settings-new"></iron-icon>
$i18n{onStartup}
</a>
@@ -146,7 +148,7 @@
<iron-icon icon="settings:security"></iron-icon>
$i18n{privacyPageTitle}
</a>
- <a href="/passwordsAndForms"
+ <a id= "passwordsAndForms" href="/passwordsAndForms"
hidden="[[!pageVisibility.passwordsAndForms]]">
<iron-icon icon="settings:assignment"></iron-icon>
$i18n{passwordsAndAutofillPageTitle}
@@ -179,7 +181,7 @@
$i18n{systemPageTitle}
</a>
</if>
- <a href="/reset" hidden="[[!pageVisibility.reset]]">
+ <a id="reset" href="/reset" hidden="[[!pageVisibility.reset]]">
<iron-icon icon="settings:restore"></iron-icon>
$i18n{resetPageTitle}
</a>
diff --git a/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js b/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js
index 5ff27d50f22..d46d1e64640 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js
+++ b/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js
@@ -93,10 +93,10 @@ var MainPageBehaviorImpl = {
// to render before scrolling to or expanding the section.
if (!oldRoute) {
this.fire('hide-container');
- setTimeout(function() {
+ setTimeout(() => {
this.fire('show-container');
this.tryTransitionToSection_(scrollToSection, true);
- }.bind(this));
+ });
} else if (this.scrollHeight == 0) {
setTimeout(this.tryTransitionToSection_.bind(this, scrollToSection));
} else {
@@ -176,9 +176,9 @@ var MainPageBehaviorImpl = {
// again after the promise resolves.
if (promise) {
promise.then(this.tryTransitionToSection_.bind(this, scrollToSection))
- .then(function() {
+ .then(() => {
this.fire('show-container');
- }.bind(this));
+ });
}
},
@@ -259,19 +259,19 @@ var MainPageBehaviorImpl = {
return this.currentAnimation_.finished
.then(
- function() {
+ () => {
this.finishedExpanding_(section);
- }.bind(this),
- function() {
+ },
+ () => {
// The animation was canceled; restore the section and scroll
// position.
section.setFrozen(false);
this.scroller.scrollTop = this.origScrollTop_;
- }.bind(this))
- .then(function() {
+ })
+ .then(() => {
this.fire('freeze-scroll', false);
this.currentAnimation_ = null;
- }.bind(this));
+ });
},
/** @private */
@@ -324,9 +324,9 @@ var MainPageBehaviorImpl = {
}
// Play the actual collapse animation.
- return new Promise(function(resolve, reject) {
+ return new Promise((resolve, reject) => {
// Wait for the other sections to show up so we can scroll properly.
- setTimeout(function() {
+ setTimeout(() => {
var newSection = settings.getCurrentRoute().section &&
this.getSection(settings.getCurrentRoute().section);
@@ -342,21 +342,21 @@ var MainPageBehaviorImpl = {
/** @type {!HTMLElement} */ (this.scroller));
this.currentAnimation_.finished
- .catch(function() {
+ .catch(() => {
// The collapse was canceled, so the page is showing a subpage
// still.
this.fire('subpage-expand');
- }.bind(this))
- .then(function() {
+ })
+ .then(() => {
// Clean up after the animation succeeds or cancels.
section.setFrozen(false);
section.classList.remove('collapsing');
this.fire('freeze-scroll', false);
this.currentAnimation_ = null;
resolve();
- }.bind(this));
- }.bind(this));
- }.bind(this));
+ });
+ });
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.html b/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.html
index 2facca542b4..5b3e82131ca 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.html
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.html
@@ -25,13 +25,13 @@
position: static;
}
- neon-animated-pages ::content > .iron-selected {
+ neon-animated-pages ::slotted(.iron-selected) {
position: static;
}
</style>
<neon-animated-pages id="animatedPages" attr-for-selected="route-path"
on-iron-select="onIronSelect_">
- <content select="*"></content>
+ <slot></slot>
</neon-animated-pages>
</template>
<script src="settings_animated_pages.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_section.html b/chromium/chrome/browser/resources/settings/settings_page/settings_section.html
index e7a6680204f..17101c8f335 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_section.html
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_section.html
@@ -61,10 +61,11 @@
}
</style>
<div id="header">
- <h2 class="title">{{pageTitle}}</h2>
+ <h2 class="title"
+ aria-hidden$="[[getTitleHiddenStatus_(pageTitle)]]">[[pageTitle]]</h2>
</div>
<div id="card">
- <content id="content"></content>
+ <slot></slot>
</div>
</template>
<script src="settings_section.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_section.js b/chromium/chrome/browser/resources/settings/settings_page/settings_section.js
index 0265b83585f..acf750005e0 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_section.js
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_section.js
@@ -27,8 +27,14 @@ var SettingsSectionElement = Polymer({
*/
section: String,
- /** Title for the section header. */
- pageTitle: String,
+ /**
+ * Title for the section header. Initialize so we can use the
+ * getTitleHiddenStatus_ method for accessibility.
+ */
+ pageTitle: {
+ type: String,
+ value: '',
+ },
/**
* A CSS attribute used for temporarily hiding a SETTINGS-SECTION for the
@@ -91,6 +97,14 @@ var SettingsSectionElement = Polymer({
},
/**
+ * Calling this method fires the 'settings-section-expanded event'.
+ */
+ setExpanded_: function() {
+ this.classList.add('expanded');
+ this.fire('settings-section-expanded');
+ },
+
+ /**
* @return {boolean} True if the section is currently rendered and not
* already expanded or transitioning.
*/
@@ -107,7 +121,7 @@ var SettingsSectionElement = Polymer({
this.$.card.top = containerTop + 'px';
this.$.card.height = 'calc(100% - ' + containerTop + 'px)';
- this.classList.add('expanded');
+ this.setExpanded_();
},
/**
@@ -140,17 +154,13 @@ var SettingsSectionElement = Polymer({
var animation =
this.animateCard_('fixed', startTop, endTop, startHeight, endHeight);
- animation.finished
- .then(
- function() {
- this.classList.add('expanded');
- }.bind(this),
- function() {})
- .then(function() {
- // Unset these changes whether the animation finished or canceled.
- this.classList.remove('expanding');
- this.style.height = '';
- }.bind(this));
+ // The empty onRejected function prevents the promise from skipping forward
+ // to the next then() with a rejection callback.
+ animation.finished.then(this.setExpanded_.bind(this), () => {}).then(() => {
+ // Unset these changes whether the animation finished or canceled.
+ this.classList.remove('expanding');
+ this.style.height = '';
+ });
return animation;
},
@@ -223,15 +233,15 @@ var SettingsSectionElement = Polymer({
animation.finished
.then(
- function() {
+ () => {
this.classList.remove('expanded');
- }.bind(this),
+ },
function() {})
- .then(function() {
+ .then(() => {
// The card now determines the section's height automatically.
this.style.height = '';
this.classList.remove('collapsing');
- }.bind(this));
+ });
return animation;
},
@@ -271,4 +281,16 @@ var SettingsSectionElement = Polymer({
return new settings.animation.Animation(
this.$.card, [startFrame, endFrame], options);
},
+
+ /**
+ * Get the value to which to set the aria-hidden attribute of the section
+ * heading.
+ * @return {boolean|string} A return value of false will not add aria-hidden
+ * while aria-hidden requires a string of 'true' to be hidden as per aria
+ * specs. This function ensures we have the right return type.
+ * @private
+ */
+ getTitleHiddenStatus_: function() {
+ return this.pageTitle ? false : 'true';
+ }
});
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html
index f427d98fff7..ae615482e8b 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html
@@ -21,7 +21,7 @@
#headerLine {
min-height: 40px;
- padding-bottom: 12px;
+ padding-bottom: 24px;
padding-top: 8px;
}
@@ -62,7 +62,7 @@
aria-label="$i18n{back}" class="icon-arrow-back">
</button>
<h1>[[pageTitle]]</h1>
- <content select=".subpage-title-extra"></content>
+ <slot name="subpage-title-extra"></slot>
<template is="dom-if" if="[[learnMoreUrl]]">
<a id="learnMore" aria-label="$i18n{learnMore}"
href="[[learnMoreUrl]]" target="_blank">
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage_search.html b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage_search.html
index 106131e4889..4f4245f7fec 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage_search.html
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage_search.html
@@ -11,13 +11,6 @@
<template>
<style include="cr-shared-style">
:host {
- --subpage-search-underline: {
- margin-bottom: -2px;
- margin-top: -2px;
- }
- }
-
- :host {
--paper-input-container-underline: var(--subpage-search-underline);
--paper-input-container-underline-focus:
var(--subpage-search-underline);
@@ -27,6 +20,11 @@
/* Required to align the icon in |clearSearch| vertically. */
line-height: 0;
};
+ --subpage-search-underline: {
+ margin-bottom: -2px;
+ margin-top: -2px;
+ }
+ user-select: none;
}
#searchIcon {
diff --git a/chromium/chrome/browser/resources/settings/settings_resources.grd b/chromium/chrome/browser/resources/settings/settings_resources.grd
index 0ae60143c73..de0aeb34fa1 100644
--- a/chromium/chrome/browser/resources/settings/settings_resources.grd
+++ b/chromium/chrome/browser/resources/settings/settings_resources.grd
@@ -288,76 +288,20 @@
<structure name="IDR_SETTINGS_FOCUS_ROW_BEHAVIOR_JS"
file="focus_row_behavior.js"
type="chrome_html" />
- <if expr="use_nss_certs">
- <structure name="IDR_SETTINGS_CERTIFICATE_MANAGER_PAGE_HTML"
- file="certificate_manager_page/certificate_manager_page.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_MANAGER_PAGE_JS"
- file="certificate_manager_page/certificate_manager_page.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_LIST_HTML"
- file="certificate_manager_page/certificate_list.html"
- preprocess="true"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_LIST_JS"
- file="certificate_manager_page/certificate_list.js"
- preprocess="true"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_ENTRY_HTML"
- file="certificate_manager_page/certificate_entry.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_ENTRY_JS"
- file="certificate_manager_page/certificate_entry.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_MANAGER_TYPES_HTML"
- file="certificate_manager_page/certificate_manager_types.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_MANAGER_TYPES_JS"
- file="certificate_manager_page/certificate_manager_types.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_SUBENTRY_HTML"
- file="certificate_manager_page/certificate_subentry.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_SUBENTRY_JS"
- file="certificate_manager_page/certificate_subentry.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATES_BROWSER_PROXY_HTML"
- file="certificate_manager_page/certificates_browser_proxy.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATES_BROWSER_PROXY_JS"
- file="certificate_manager_page/certificates_browser_proxy.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CA_TRUST_EDIT_DIALOG_JS"
- file="certificate_manager_page/ca_trust_edit_dialog.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CA_TRUST_EDIT_DIALOG_HTML"
- file="certificate_manager_page/ca_trust_edit_dialog.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_DELETE_CONFIRMATION_DIALOG_JS"
- file="certificate_manager_page/certificate_delete_confirmation_dialog.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_DELETE_CONFIRMATION_DIALOG_HTML"
- file="certificate_manager_page/certificate_delete_confirmation_dialog.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_PASSWORD_ENCRYPTION_DIALOG_JS"
- file="certificate_manager_page/certificate_password_encryption_dialog.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_PASSWORD_ENCRYPTION_DIALOG_HTML"
- file="certificate_manager_page/certificate_password_encryption_dialog.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_PASSWORD_DECRYPTION_DIALOG_JS"
- file="certificate_manager_page/certificate_password_decryption_dialog.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATE_PASSWORD_DECRYPTION_DIALOG_HTML"
- file="certificate_manager_page/certificate_password_decryption_dialog.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATES_ERROR_DIALOG_JS"
- file="certificate_manager_page/certificates_error_dialog.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_CERTIFICATES_ERROR_DIALOG_HTML"
- file="certificate_manager_page/certificates_error_dialog.html"
- type="chrome_html" />
- </if>
+ <structure name="IDR_SETTINGS_CHANGE_PASSWORD_BROWSER_PROXY_HTML"
+ file="change_password_page/change_password_browser_proxy.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CHANGE_PASSWORD_BROWSER_PROXY_JS"
+ file="change_password_page/change_password_browser_proxy.js"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CHANGE_PASSWORD_PAGE_HTML"
+ file="change_password_page/change_password_page.html"
+ type="chrome_html"
+ preprocess="true" />
+ <structure name="IDR_SETTINGS_CHANGE_PASSWORD_PAGE_JS"
+ file="change_password_page/change_password_page.js"
+ type="chrome_html"
+ preprocess="true" />
<if expr="is_win">
<structure name="IDR_SETTINGS_CHROME_CLEANUP_PROXY_HTML"
file="chrome_cleanup_page/chrome_cleanup_proxy.html"
@@ -386,6 +330,12 @@
<structure name="IDR_SETTINGS_CLEAR_BROWSING_DATA_DIALOG_JS"
file="clear_browsing_data_dialog/clear_browsing_data_dialog.js"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_CLEAR_BROWSING_DATA_DIALOG_TABS_HTML"
+ file="clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CLEAR_BROWSING_DATA_DIALOG_TABS_JS"
+ file="clear_browsing_data_dialog/clear_browsing_data_dialog_tabs.js"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_HISTORY_DELETION_DIALOG_HTML"
file="clear_browsing_data_dialog/history_deletion_dialog.html"
type="chrome_html" />
@@ -714,6 +664,12 @@
<structure name="IDR_SETTINGS_ADDRESS_EDIT_DIALOG_JS"
file="passwords_and_forms_page/address_edit_dialog.js"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_SHOW_PASSWORD_BEHAVIOR_HTML"
+ file="passwords_and_forms_page/show_password_behavior.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_SHOW_PASSWORD_BEHAVIOR_JS"
+ file="passwords_and_forms_page/show_password_behavior.js"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_PASSWORD_LIST_ITEM_HTML"
file="passwords_and_forms_page/password_list_item.html"
type="chrome_html" />
@@ -1129,12 +1085,6 @@
<structure name="IDR_SETTINGS_ANDROID_SETTINGS_ELEMENT_JS"
file="android_apps_page/android_settings_element.js"
type="chrome_html" />
- <structure name="IDR_SETTINGS_BLUETOOTH_DEVICE_DIALOG_HTML"
- file="bluetooth_page/bluetooth_device_dialog.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_BLUETOOTH_DEVICE_DIALOG_JS"
- file="bluetooth_page/bluetooth_device_dialog.js"
- type="chrome_html" />
<structure name="IDR_SETTINGS_BLUETOOTH_DEVICE_LIST_ITEM_HTML"
file="bluetooth_page/bluetooth_device_list_item.html"
type="chrome_html" />
@@ -1198,12 +1148,6 @@
<structure name="IDR_SETTINGS_MULTIDEVICE_PAGE_JS"
file="multidevice_page/multidevice_page.js"
type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_APNLIST_HTML"
- file="internet_page/network_apnlist.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_APNLIST_JS"
- file="internet_page/network_apnlist.js"
- type="chrome_html" />
<structure name="IDR_SETTINGS_NETWORK_CONFIG_INPUT_HTML"
file="internet_page/network_config_input.html"
type="chrome_html" />
@@ -1216,41 +1160,11 @@
<structure name="IDR_SETTINGS_NETWORK_CONFIG_SELECT_JS"
file="internet_page/network_config_select.js"
type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_IP_CONFIG_HTML"
- file="internet_page/network_ip_config.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_IP_CONFIG_JS"
- file="internet_page/network_ip_config.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_NAMESERVERS_HTML"
- file="internet_page/network_nameservers.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_NAMESERVERS_JS"
- file="internet_page/network_nameservers.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROPERTY_LIST_HTML"
- file="internet_page/network_property_list.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROPERTY_LIST_JS"
- file="internet_page/network_property_list.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROXY_HTML"
- file="internet_page/network_proxy.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROXY_JS"
- file="internet_page/network_proxy.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROXY_EXCLUSIONS_HTML"
- file="internet_page/network_proxy_exclusions.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROXY_EXCLUSIONS_JS"
- file="internet_page/network_proxy_exclusions.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROXY_INPUT_HTML"
- file="internet_page/network_proxy_input.html"
+ <structure name="IDR_SETTINGS_NETWORK_PROXY_SECTION_HTML"
+ file="internet_page/network_proxy_section.html"
type="chrome_html" />
- <structure name="IDR_SETTINGS_NETWORK_PROXY_INPUT_JS"
- file="internet_page/network_proxy_input.js"
+ <structure name="IDR_SETTINGS_NETWORK_PROXY_SECTION_JS"
+ file="internet_page/network_proxy_section.js"
type="chrome_html" />
<structure name="IDR_SETTINGS_NETWORK_SIMINFO_HTML"
file="internet_page/network_siminfo.html"
diff --git a/chromium/chrome/browser/resources/settings/settings_shared_css.html b/chromium/chrome/browser/resources/settings/settings_shared_css.html
index 279c57dfbe0..4f0c690a92b 100644
--- a/chromium/chrome/browser/resources/settings/settings_shared_css.html
+++ b/chromium/chrome/browser/resources/settings/settings_shared_css.html
@@ -1,17 +1,20 @@
<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_checkbox_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/paper_toggle_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="settings_icons_css.html">
<link rel="import" href="settings_vars_css.html">
+
<!-- Common styles for Material Design settings. -->
<dom-module id="settings-shared">
<template>
- <style include="settings-icons paper-button-style cr-shared-style">
+ <style include="settings-icons paper-button-style paper-checkbox-style paper-toggle-style cr-shared-style">
/* Prevent action-links from being selected to avoid accidental
* selection when trying to click it. */
a[is=action-link] {
- -webkit-user-select: none;
+ user-select: none;
}
/* Use <h2> as the "sub-header" mentioned in the UX design docs. */
@@ -24,7 +27,7 @@
font-weight: 500;
margin: 0;
padding-bottom: 12px;
- padding-top: 24px;
+ padding-top: 32px;
}
iron-icon {
@@ -36,6 +39,25 @@
--iron-icon-fill-color: var(--google-green-500);
}
+ iron-list {
+ --iron-list-items-container: {
+ /* Text selection in an iron-list is problematic because the items are
+ * reused. The result is the selection happens somewhat arbitrarily.
+ * Add a |risk-selection| attribute to enabled selection in an
+ * iron-list. */
+ user-select: none;
+ }
+ }
+
+ iron-list[risk-selection] {
+ --iron-list-items-container: {
+ /* On short lists where selection is likely desired, we'll risk having
+ * text selection enabled. If the list is short enough that items are
+ * not actually reused, the bugs with selection are not evident. */
+ user-select: text;
+ }
+ }
+
.separator + button[is='paper-icon-button-light'] {
-webkit-margin-start: var(--cr-icon-ripple-margin);
}
@@ -79,6 +101,7 @@
paper-toggle-button {
@apply(--settings-actionable);
height: var(--settings-row-min-height);
+ user-select: none; /* Prevents text selection while dragging. */
width: 36px;
}
@@ -108,14 +131,6 @@
color: var(--google-blue-500);
}
- paper-checkbox {
- --paper-checkbox-checked-color: var(--google-blue-500);
- --paper-checkbox-label-spacing: var(--settings-control-label-spacing);
- --paper-checkbox-size: var(--checkbox-size);
- --paper-checkbox-unchecked-color: var(--paper-grey-600);
- -webkit-margin-start: var(--checkbox-margin-start);
- }
-
paper-input {
/* Fix issue with focus animation making labels wiggle. */
transform: translate3d(0, 0, 0);
@@ -221,11 +236,7 @@
/* A settings-box is a horizontal row of text or controls within a
* setting section (page or subpage). */
.settings-box {
- align-items: center;
- border-top: var(--settings-separator-line);
- display: flex;
- min-height: var(--settings-row-min-height);
- padding: 0 var(--settings-box-row-padding);
+ @apply(--cr-section);
}
.settings-box.two-line {
@@ -260,9 +271,15 @@
min-height: 0;
}
+ /* A settings-box that is embedded in another settings-box (e.g. a control
+ * that is associated with a toggle button). */
+ .settings-box.embedded {
+ -webkit-padding-start: var(--settings-box-row-indent);
+ }
+
/* The lower line of text in a two-line row. */
.secondary {
- @apply(--settings-secondary);
+ @apply(--cr-secondary-text);
}
/* The |:empty| CSS selector only works when there is no whitespace.
@@ -345,13 +362,6 @@
2 * var(--settings-separator-gaps));
}
- .settings-checkbox-spacer {
- -webkit-margin-start: calc(
- var(--checkbox-margin-start) +
- var(--checkbox-size) +
- var(--settings-control-label-spacing));
- }
-
.favicon-image {
background-repeat: no-repeat;
background-size: contain;
diff --git a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html
index b66626bf851..27bc50b5909 100644
--- a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html
+++ b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html
@@ -25,12 +25,12 @@
<style include="settings-shared">
:host {
@apply(--layout-fit);
- -webkit-user-select: text;
color: var(--primary-text-color);
display: flex;
flex-direction: column;
line-height: 154%; /* Apply 20px line-height to all texts by default. */
overflow: hidden; /* Prevent double scroll bar bugs. */
+ user-select: text;
}
.last {
diff --git a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js
index 351433de1ff..cb96a4ffd15 100644
--- a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js
+++ b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js
@@ -85,13 +85,13 @@ Polymer({
*/
ready: function() {
// Lazy-create the drawer the first time it is opened or swiped into view.
- listenOnce(this.$.drawer, 'open-changed', function() {
+ listenOnce(this.$.drawer, 'open-changed', () => {
this.$.drawerTemplate.if = true;
- }.bind(this));
+ });
- window.addEventListener('popstate', function(e) {
+ window.addEventListener('popstate', e => {
this.$.drawer.closeDrawer();
- }.bind(this));
+ });
CrPolicyStrings = {
controlledSettingExtension:
@@ -123,6 +123,8 @@ Polymer({
loadTimeData.getString('networkListItemConnecting'),
networkListItemConnectingTo:
loadTimeData.getString('networkListItemConnectingTo'),
+ networkListItemInitializing:
+ loadTimeData.getString('networkListItemInitializing'),
networkListItemNotConnected:
loadTimeData.getString('networkListItemNotConnected'),
vpnNameTemplate: loadTimeData.getString('vpnNameTemplate'),
@@ -137,13 +139,13 @@ Polymer({
this.havePlayStoreApp_ = loadTimeData.valueExists('havePlayStoreApp') &&
loadTimeData.getBoolean('havePlayStoreApp');
- this.addEventListener('show-container', function() {
+ this.addEventListener('show-container', () => {
this.$.container.style.visibility = 'visible';
- }.bind(this));
+ });
- this.addEventListener('hide-container', function() {
+ this.addEventListener('hide-container', () => {
this.$.container.style.visibility = 'hidden';
- }.bind(this));
+ });
},
/** @private {?IntersectionObserver} */
@@ -164,10 +166,10 @@ Polymer({
settings.setGlobalScrollTarget(this.$.container);
// Setup drop shadow logic.
- var callback = function(entries) {
+ var callback = entries => {
this.$.dropShadow.classList.toggle(
'has-shadow', entries[entries.length - 1].intersectionRatio == 0);
- }.bind(this);
+ };
this.intersectionObserver_ = new IntersectionObserver(
callback,
@@ -259,9 +261,9 @@ Polymer({
this.$.container.setAttribute('tabindex', '-1');
this.$.container.focus();
- listenOnce(this.$.container, ['blur', 'pointerdown'], function() {
+ listenOnce(this.$.container, ['blur', 'pointerdown'], () => {
this.$.container.removeAttribute('tabindex');
- }.bind(this));
+ });
},
/** @private */
diff --git a/chromium/chrome/browser/resources/settings/settings_vars_css.html b/chromium/chrome/browser/resources/settings/settings_vars_css.html
index 153aa5ea44c..9efc68e9f65 100644
--- a/chromium/chrome/browser/resources/settings/settings_vars_css.html
+++ b/chromium/chrome/browser/resources/settings/settings_vars_css.html
@@ -14,10 +14,9 @@
--settings-actionable: var(--cr-actionable);
- --settings-box-row-padding: 20px;
- --settings-box-row-indent: calc(
- var(--settings-box-row-padding) + var(--settings-indent-width));
- --settings-indent-width: 40px;
+ --settings-box-row-padding: var(--cr-section-padding);
+ --settings-box-row-indent: var(--cr-section-indent-padding);
+ --settings-indent-width: var(--cr-section-indent-width);
--settings-card-max-width: 680px;
--settings-disabled-opacity: .65;
--settings-error-color: var(--paper-red-700);
@@ -33,12 +32,10 @@
--settings-page-vertical-margin: 21px;
- /* TODO (scottchen): re-implement with paddings instead; */
- /* These are used for row items such as radio buttons, check boxes, list
- * items etc. */
- --settings-row-min-height: 48px;
- --settings-row-two-line-min-height: 64px;
- --settings-row-three-line-min-height: 84px;
+ --settings-row-min-height: var(--cr-section-min-height);
+ --settings-row-two-line-min-height: var(--cr-section-two-line-min-height);
+ --settings-row-three-line-min-height:
+ var(--cr-section-three-line-min-height);
--settings-text-elide: {
overflow: hidden;
@@ -46,36 +43,11 @@
white-space: nowrap;
};
- --settings-secondary: {
- color: var(--paper-grey-600);
- font-weight: 400;
- };
--settings-separator-height: var(--cr-separator-height);
--settings-separator-line: var(--cr-separator-line);
--settings-title-bar-color: rgb(255, 255, 255);
--settings-title-search-color: rgb(192, 199, 205);
- --settings-toggle-bar-size: {
- height: 12px;
- left: 4px;
- width: 28px;
- };
- --settings-toggle-button-size: {
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.4);
- height: 16px;
- top: -2px;
- width: 16px;
- };
- --settings-toggle-ink-size: {
- height: 40px;
- top: -12px;
- left: -12px;
- width: 40px;
- };
- --settings-toggle-color: var(--google-blue-500);
-
- --checkbox-margin-start: 2px;
- --checkbox-size: 16px;
/* Spacing between a control (e.g. checkbox) and its label. */
--settings-control-label-spacing: 20px;
@@ -86,19 +58,18 @@
--iron-icon-fill-color: var(--paper-grey-600);
--iron-icon-height: var(--cr-icon-size);
--iron-icon-width: var(--cr-icon-size);
- --paper-checkbox-label-color: inherit;
--paper-input-container-focus-color: var(--google-blue-500);
--paper-input-container-input: {
color: inherit;
font-size: inherit;
font-weight: inherit;
- line-height: 154%;
+ line-height: 1.54;
vertical-align: baseline;
};
--paper-input-container-label: {
font-size: inherit;
- line-height: 154%;
+ line-height: 1.54;
};
--paper-input-container-label-floating: {
/* Using "rem" to make it easier to equalize with other labels. */
@@ -107,7 +78,7 @@
};
--paper-input-error: {
font-size: 92.31%; /* Should be 12px when 100% is 13px. */
- line-height: 154%;
+ line-height: 1.54;
overflow: visible; /* Half-visible error message is not useful at all. */
};
--paper-input-max-width: 264px;
@@ -116,18 +87,6 @@
--paper-radio-button-size: 16px;
--paper-radio-group-item-padding: 0;
- --paper-toggle-button-checked-bar: var(--settings-toggle-bar-size);
- --paper-toggle-button-checked-bar-color: var(--settings-toggle-color);
- --paper-toggle-button-checked-button: {
- @apply(--settings-toggle-button-size);
- transform: translate(18px, 0);
- };
- --paper-toggle-button-checked-button-color: var(--settings-toggle-color);
- --paper-toggle-button-label-spacing: 0;
- --paper-toggle-button-unchecked-bar: var(--settings-toggle-bar-size);
- --paper-toggle-button-unchecked-button: var(--settings-toggle-button-size);
- --paper-toggle-button-unchecked-ink: var(--settings-toggle-ink-size);
-
--settings-input-underline: {
border-color: var(--paper-grey-300);
};
diff --git a/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html b/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html
index 7e0080cc23d..94157bee5f4 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html
@@ -22,18 +22,19 @@
}
</style>
<dialog is="cr-dialog" id="dialog" close-text="$i18n{close}">
- <div class="title" slot="title">$i18n{addSiteTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{addSiteTitle}</div>
+ <div slot="body">
<paper-input id="site" always-float-label label="$i18n{addSite}"
placeholder="$i18n{addSiteExceptionPlaceholder}"
value="{{site_}}" on-input="validate_"
- error-message="$i18n{notValidWebAddress}" autofocus></paper-input>
+ error-message="$i18n{notValidWebAddress}" spellcheck="false"
+ autofocus></paper-input>
<paper-checkbox id="incognito"
invisible$="[[!showIncognitoSessionOnly_]]">
$i18n{incognitoSiteOnly}
</paper-checkbox>
</div>
- <div class="button-container" slot="button-container">
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCancelTap_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.js b/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.js
index c61483a265f..7536913c81b 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.js
@@ -43,12 +43,12 @@ Polymer({
/** Open the dialog. */
open: function() {
- this.addWebUIListener('onIncognitoStatusChanged', function(hasIncognito) {
+ this.addWebUIListener('onIncognitoStatusChanged', hasIncognito => {
this.$.incognito.checked = false;
this.showIncognitoSessionOnly_ = hasIncognito &&
!loadTimeData.getBoolean('isGuest') &&
this.contentSetting != settings.ContentSetting.SESSION_ONLY;
- }.bind(this));
+ });
this.browserProxy.updateIncognitoStatus();
this.$.dialog.showModal();
},
@@ -66,10 +66,10 @@ Polymer({
return;
}
- this.browserProxy.isPatternValid(this.site_).then(function(isValid) {
+ this.browserProxy.isPatternValid(this.site_).then(isValid => {
this.$.site.invalid = !isValid;
this.$.add.disabled = !isValid;
- }.bind(this));
+ });
},
/** @private */
@@ -85,7 +85,7 @@ Polymer({
onSubmit_: function() {
if (this.$.add.disabled)
return; // Can happen when Enter is pressed.
- this.browserProxy.setCategoryPermissionForOrigin(
+ this.browserProxy.setCategoryPermissionForPattern(
this.site_, this.site_, this.category, this.contentSetting,
this.$.incognito.checked);
this.$.dialog.close();
diff --git a/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.html b/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.html
index cc7f5087089..f39ca2af2e8 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.html
@@ -11,14 +11,14 @@
<template>
<style include="settings-shared"></style>
<settings-toggle-button id="toggle"
- class="settings-box first"
+ class="first"
pref="{{controlParams_}}" label="[[optionLabel_]]"
sub-label="[[optionDescription]]"
disabled$="[[isToggleDisabled_(category)]]">
</settings-toggle-button>
<template is="dom-if" if="[[subOptionLabel]]">
<settings-toggle-button id="subOptionToggle"
- class="settings-box" pref="{{subControlParams_}}"
+ pref="{{subControlParams_}}"
label="[[subOptionLabel]]" sub-label="[[subOptionDescription]]"
disabled$="[[!controlParams_.value]]">
</settings-toggle-button>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.js b/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.js
index aa82e8d568a..316f8bbed74 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/category_default_setting.js
@@ -90,6 +90,7 @@ Polymer({
case settings.ContentSettingsTypes.BACKGROUND_SYNC:
case settings.ContentSettingsTypes.IMAGES:
case settings.ContentSettingsTypes.JAVASCRIPT:
+ case settings.ContentSettingsTypes.SOUND:
case settings.ContentSettingsTypes.POPUPS:
case settings.ContentSettingsTypes.PROTOCOL_HANDLERS:
@@ -124,14 +125,11 @@ Polymer({
this.browserProxy.setDefaultValueForContentType(this.category, value);
break;
case settings.ContentSettingsTypes.PLUGINS:
- // This category is tri-state: "Allow", "Block", "Ask before running".
- var value = settings.ContentSetting.BLOCK;
- if (this.categoryEnabled) {
- value = this.subControlParams_.value ?
- settings.ContentSetting.IMPORTANT_CONTENT :
- settings.ContentSetting.ALLOW;
- }
- this.browserProxy.setDefaultValueForContentType(this.category, value);
+ // "Run important content" vs. "Block".
+ this.browserProxy.setDefaultValueForContentType(
+ this.category,
+ this.categoryEnabled ? settings.ContentSetting.IMPORTANT_CONTENT :
+ settings.ContentSetting.BLOCK);
break;
default:
assertNotReached('Invalid category: ' + this.category);
@@ -170,18 +168,8 @@ Polymer({
this.controlParams_ = /** @type {chrome.settingsPrivate.PrefObject} */ (
Object.assign({'value': prefValue}, basePref));
- var subPrefValue = false;
- if (this.category == settings.ContentSettingsTypes.PLUGINS ||
- this.category == settings.ContentSettingsTypes.COOKIES) {
- if (this.category == settings.ContentSettingsTypes.PLUGINS &&
- update.setting == settings.ContentSetting.IMPORTANT_CONTENT) {
- subPrefValue = true;
- } else if (
- this.category == settings.ContentSettingsTypes.COOKIES &&
- update.setting == settings.ContentSetting.SESSION_ONLY) {
- subPrefValue = true;
- }
- }
+ var subPrefValue = this.category == settings.ContentSettingsTypes.COOKIES &&
+ update.setting == settings.ContentSetting.SESSION_ONLY;
// The subControlParams_ must be replaced (rather than just value changes)
// so that observers will be notified of the change.
this.subControlParams_ = /** @type {chrome.settingsPrivate.PrefObject} */ (
@@ -194,23 +182,14 @@ Polymer({
*/
onCategoryChanged_: function() {
this.browserProxy.getDefaultValueForContentType(this.category)
- .then(function(defaultValue) {
+ .then(defaultValue => {
this.updateControlParams_(defaultValue);
- // Flash only shows ALLOW or BLOCK descriptions on the toggle.
- var setting = defaultValue.setting;
- if (this.category == settings.ContentSettingsTypes.PLUGINS &&
- setting == settings.ContentSetting.IMPORTANT_CONTENT) {
- setting = settings.ContentSetting.ALLOW;
- } else if (
- this.category == settings.ContentSettingsTypes.COOKIES &&
- setting == settings.ContentSetting.SESSION_ONLY) {
- setting = settings.ContentSetting.ALLOW;
- }
- var categoryEnabled = setting != settings.ContentSetting.BLOCK;
+ var categoryEnabled =
+ this.computeIsSettingEnabled(defaultValue.setting);
this.optionLabel_ =
categoryEnabled ? this.toggleOnLabel : this.toggleOffLabel;
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/site_settings/constants.js b/chromium/chrome/browser/resources/settings/site_settings/constants.js
index a494fcb6d0e..163fc33fca4 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/constants.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/constants.js
@@ -16,6 +16,7 @@ settings.ContentSettingsTypes = {
COOKIES: 'cookies',
IMAGES: 'images',
JAVASCRIPT: 'javascript',
+ SOUND: 'sound',
PLUGINS: 'plugins', // AKA Flash.
POPUPS: 'popups',
GEOLOCATION: 'location',
@@ -51,6 +52,22 @@ settings.ContentSetting = {
};
/**
+ * Contains the possible sources of a ContentSetting.
+ * This should be kept in sync with the |SiteSettingSource| enum in
+ * chrome/browser/ui/webui/site_settings_helper.h
+ * @enum {string}
+ */
+settings.SiteSettingSource = {
+ EMBARGO: 'embargo',
+ EXTENSION: 'extension',
+ INSECURE_ORIGIN: 'insecure-origin',
+ KILL_SWITCH: 'kill-switch',
+ POLICY: 'policy',
+ PREFERENCE: 'preference',
+ DEFAULT: 'default',
+};
+
+/**
* A category value to use for the All Sites list.
* @const {string}
*/
diff --git a/chromium/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js b/chromium/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js
index 0b540b9c63a..38d95db2506 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js
@@ -38,7 +38,7 @@ var CookieTreeBehaviorImpl = {
* @private
*/
loadChildren_: function(list) {
- var loadChildrenRecurse = function(childList) {
+ var loadChildrenRecurse = childList => {
var parentId = childList.id;
var children = childList.children;
var prefix = '';
@@ -56,15 +56,15 @@ var CookieTreeBehaviorImpl = {
}
}
return Promise.all(promises);
- }.bind(this);
+ };
// New root being added, clear the list and add the nodes.
this.sites = [];
this.rootCookieNode.addChildNodes(this.rootCookieNode, list.children);
- return loadChildrenRecurse(list).then(function() {
+ return loadChildrenRecurse(list).then(() => {
this.sites = this.rootCookieNode.getSummaryList();
return Promise.resolve();
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html b/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html
index 44430cac709..f6ab56fa94a 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html
@@ -10,23 +10,21 @@
<template>
<style include="settings-shared"></style>
<dialog is="cr-dialog" id="dialog">
- <div class="title" slot="title">$i18n{editSiteTitle}</div>
- <div class="body" slot="body">
+ <div slot="title">$i18n{editSiteTitle}</div>
+ <div slot="body">
<paper-input always-float-label label="$i18n{addSite}"
placeholder="$i18n{addSiteExceptionPlaceholder}" value="{{origin_}}"
on-input="validate_" error-message="$i18n{notValidWebAddress}"
invalid="[[invalid_]]" autofocus>
</paper-input>
</div>
- <div class="button-container" slot="button-container">
- <div class="action-buttons">
- <paper-button class="cancel-button" on-tap="onCancelTap_"
- id="cancel">$i18n{cancel}</paper-button>
- <paper-button id="actionButton" class="action-button"
- on-tap="onActionButtonTap_" disabled="[[invalid_]]">
- $i18n{edit}
- </paper-button>
- </div>
+ <div slot="button-container">
+ <paper-button class="cancel-button" on-tap="onCancelTap_"
+ id="cancel">$i18n{cancel}</paper-button>
+ <paper-button id="actionButton" class="action-button"
+ on-tap="onActionButtonTap_" disabled="[[invalid_]]">
+ $i18n{edit}
+ </paper-button>
</div>
</dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js b/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js
index b4d39aa5b4b..654d2464221 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js
@@ -49,11 +49,11 @@ Polymer({
onActionButtonTap_: function() {
if (this.model.origin != this.origin_) {
// The way to "edit" an exception is to remove it and and a new one.
- this.browserProxy_.resetCategoryPermissionForOrigin(
+ this.browserProxy_.resetCategoryPermissionForPattern(
this.model.origin, this.model.embeddingOrigin, this.model.category,
this.model.incognito);
- this.browserProxy_.setCategoryPermissionForOrigin(
+ this.browserProxy_.setCategoryPermissionForPattern(
this.origin_, this.origin_, this.model.category, this.model.setting,
this.model.incognito);
}
@@ -68,8 +68,8 @@ Polymer({
return;
}
- this.browserProxy_.isPatternValid(this.origin_).then(function(isValid) {
+ this.browserProxy_.isPatternValid(this.origin_).then(isValid => {
this.invalid_ = !isValid;
- }.bind(this));
+ });
},
});
diff --git a/chromium/chrome/browser/resources/settings/site_settings/media_picker.js b/chromium/chrome/browser/resources/settings/site_settings/media_picker.js
index f39f5f9a94c..8c8ca451e36 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/media_picker.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/media_picker.js
@@ -50,9 +50,9 @@ Polymer({
this.devices = devices;
// Wait for <select> to be populated.
- this.async(function() {
+ this.async(() => {
this.$.mediaPicker.value = defaultDevice;
- }.bind(this));
+ });
}
},
diff --git a/chromium/chrome/browser/resources/settings/site_settings/pdf_documents.html b/chromium/chrome/browser/resources/settings/site_settings/pdf_documents.html
index af03778f315..a6a0b7cdcfe 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/pdf_documents.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/pdf_documents.html
@@ -10,12 +10,10 @@
margin-top: 0; /* Cancel separation between main and secondary text. */
}
</style>
- <div class="settings-box first two-line">
- <settings-toggle-button id="toggle" class="start"
- label="$i18n{siteSettingsPdfDownloadPdfs}"
- pref="{{prefs.plugins.always_open_pdf_externally}}">
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="toggle" class="first two-line"
+ label="$i18n{siteSettingsPdfDownloadPdfs}"
+ pref="{{prefs.plugins.always_open_pdf_externally}}">
+ </settings-toggle-button>
</template>
<script src="pdf_documents.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/protocol_handlers.html b/chromium/chrome/browser/resources/settings/site_settings/protocol_handlers.html
index e83967b08a7..04de6344da3 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/protocol_handlers.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/protocol_handlers.html
@@ -59,13 +59,11 @@
</template>
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" on-tap="onDefaultTap_"
- hidden$="[[isModelDefault_(actionMenuModel_)]]"
- id="defaultButton">
+ <button class="dropdown-item" on-tap="onDefaultTap_" id="defaultButton"
+ hidden$="[[isModelDefault_(actionMenuModel_)]]">
$i18n{handlerSetDefault}
</button>
- <button class="dropdown-item" role="option" on-tap="onRemoveTap_"
- id="removeButton">
+ <button class="dropdown-item" on-tap="onRemoveTap_" id="removeButton">
$i18n{handlerRemove}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_data.html b/chromium/chrome/browser/resources/settings/site_settings/site_data.html
index 04d81749fc7..eb8408f3dc5 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_data.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_data.html
@@ -15,6 +15,10 @@
<dom-module id="site-data">
<template>
<style include="settings-shared">
+ [first] {
+ border-top: none;
+ }
+
#removeShowingSites {
-webkit-margin-start: auto;
}
@@ -22,57 +26,44 @@
#removeSecondary {
-webkit-padding-start: 0;
}
-
- .subtitle-row {
- margin-top: 9px; /* With 15px in sub-items == 24px total margin. */
- }
</style>
- <div class="settings-box first subtitle-row">
- <div class="start">
- <h2>$i18n{siteSettingsCookieHeader}</h2>
- </div>
- <settings-subpage-search id="filter" on-search-changed="onSearchChanged_"
- label="$i18n{siteSettingsCookieSearch}">
- </settings-subpage-search>
- </div>
<div class="settings-box continuation">
<paper-button class="secondary-button" id="removeShowingSites"
on-tap="onRemoveShowingSitesTap_"
hidden$="[[!isRemoveButtonVisible_(sites, renderedItemCount)]]">
- [[computeRemoveLabel_(filterString_)]]
+ [[computeRemoveLabel_(filter)]]
</paper-button>
</div>
- <div class="list-frame vertical-list">
- <template is="dom-repeat" id="list" items="[[sites]]" filter="showItem_"
- rendered-item-count="{{renderedItemCount::dom-change}}"
- notify-dom-change>
- <div class="list-item two-line" on-tap="onSiteTap_" actionable>
- <div class="favicon-image" style$="[[computeSiteIcon(item.site)]]">
- </div>
- <div class="middle">
- [[item.site]]
- <div class="secondary" id="siteSecondary">[[item.localData]]</div>
- </div>
- <button class="subpage-arrow" is="paper-icon-button-light"
- aria-label$="[[item.site]]"
- aria-describedby="siteSecondary"></button>
- <div class="separator" id="removeSecondary"></div>
- <button is="paper-icon-button-light" class="icon-delete-gray"
- title$="[[i18n('siteSettingsCookieRemoveSite', item.site)]]"
- on-tap="onRemoveSiteTap_">
- </button>
+ <template is="dom-repeat" id="list" items="[[sites]]" filter="showItem_"
+ rendered-item-count="{{renderedItemCount::dom-change}}"
+ notify-dom-change>
+ <div class="settings-box two-line" first$="[[!index]]" id="siteItem"
+ on-tap="onSiteTap_" actionable>
+ <div class="favicon-image" style$="[[computeSiteIcon(item.site)]]">
</div>
- </template>
- </div>
+ <div class="middle">
+ [[item.site]]
+ <div class="secondary" id="siteSecondary">[[item.localData]]</div>
+ </div>
+ <button class="subpage-arrow" is="paper-icon-button-light"
+ aria-label$="[[item.site]]"
+ aria-describedby="siteSecondary"></button>
+ <div class="separator" id="removeSecondary"></div>
+ <button is="paper-icon-button-light" class="icon-delete-gray"
+ title$="[[i18n('siteSettingsCookieRemoveSite', item.site)]]"
+ on-tap="onRemoveSiteTap_">
+ </button>
+ </div>
+ </template>
<!-- Confirm Delete dialog -->
<dialog is="cr-dialog" id="confirmDeleteDialog" close-text="$i18n{close}"
on-close="onConfirmDeleteDialogClosed_">
- <div class="title" slot="title">
+ <div slot="title">
$i18n{siteSettingsCookieRemoveDialogTitle}
</div>
- <div class="body" slot="body">[[confirmationDeleteMsg_]]</div>
- <div class="button-container" slot="button-container">
+ <div slot="body">[[confirmationDeleteMsg_]]</div>
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCloseDialog_">
$i18n{cancel}
</paper-button>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_data.js b/chromium/chrome/browser/resources/settings/site_settings/site_data.js
index 0d0b1a760a4..d199c4b05c7 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_data.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_data.js
@@ -20,14 +20,17 @@ DomRepeatEvent.prototype.model;
Polymer({
is: 'site-data',
- behaviors: [CookieTreeBehavior, I18nBehavior],
+ behaviors: [
+ CookieTreeBehavior,
+ ],
properties: {
/**
* The current filter applied to the cookie data list.
- * @private
*/
- filterString_: {
+ filter: {
+ observer: 'onSearchChanged_',
+ notify: true,
type: String,
value: '',
},
@@ -42,6 +45,11 @@ Polymer({
},
},
+ /** @override */
+ ready: function() {
+ this.loadCookies();
+ },
+
/**
* @param {!Map<string, string>} newConfig
* @param {?Map<string, string>} oldConfig
@@ -62,11 +70,6 @@ Polymer({
}
},
- /** @override */
- ready: function() {
- this.loadCookies();
- },
-
/**
* A filter function for the list.
* @param {!CookieDataSummaryItem} item The item to possibly filter out.
@@ -74,14 +77,13 @@ Polymer({
* @private
*/
showItem_: function(item) {
- if (this.filterString_.length == 0)
+ if (this.filter.length == 0)
return true;
- return item.site.indexOf(this.filterString_) > -1;
+ return item.site.indexOf(this.filter) > -1;
},
/** @private */
- onSearchChanged_: function(e) {
- this.filterString_ = e.detail;
+ onSearchChanged_: function() {
this.$.list.render();
},
@@ -95,11 +97,11 @@ Polymer({
/**
* Returns the string to use for the Remove label.
- * @return {string} filterString The current filter string.
+ * @return {string} filter The current filter string.
* @private
*/
- computeRemoveLabel_: function(filterString) {
- if (filterString.length == 0)
+ computeRemoveLabel_: function(filter) {
+ if (filter.length == 0)
return loadTimeData.getString('siteSettingsCookieRemoveAll');
return loadTimeData.getString('siteSettingsCookieRemoveAllShown');
},
@@ -133,7 +135,7 @@ Polymer({
onConfirmDelete_: function() {
this.$.confirmDeleteDialog.close();
- if (this.filterString_.length == 0) {
+ if (this.filter.length == 0) {
this.removeAllCookies();
} else {
var items = this.$.list.items;
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.html b/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.html
index 20063068b15..7ab3d55d292 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.html
@@ -26,6 +26,7 @@
<div class="start">[[getEntryDescription_(item)]]</div>
<cr-expand-button expanded="{{item.expanded_}}">
</cr-expand-button>
+ <div class="separator"></div>
<button is="paper-icon-button-light" data-id-path$="[[item.idPath]]"
class="icon-clear" on-tap="onRemove_">
</button>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details.html b/chromium/chrome/browser/resources/settings/site_settings/site_details.html
index e20e43022db..204d19eae53 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details.html
@@ -22,49 +22,61 @@
#storage {
-webkit-padding-end: 0;
}
+
+ /* When 'Usage' is omitted, subheadings are removed. Reduce the start
+ * padding allowed for lists without headings and add back vertical space
+ * that would normally be provided by the subheading. */
+ .list-frame.without-heading {
+ -webkit-padding-start: var(--settings-box-row-padding);
+ margin-top: 12px;
+ }
+
+ #clearAndReset {
+ margin-top: 24px;
+ }
</style>
<!-- Confirm Delete dialog -->
<dialog is="cr-dialog" id="confirmDeleteDialog" close-text="$i18n{close}">
- <div class="title" slot="title">
- $i18n{siteSettingsSiteRemoveDialogTitle}
+ <div slot="title">
+ $i18n{siteSettingsSiteResetDialogTitle}
</div>
- <div class="body" slot="body">[[confirmationDeleteMsg_]]</div>
- <div class="button-container" slot="button-container">
+ <div slot="body">
+ $i18n{siteSettingsSiteResetConfirmation}
+ </div>
+ <div slot="button-container">
<paper-button class="cancel-button" on-tap="onCloseDialog_">
$i18n{cancel}
</paper-button>
- <paper-button class="action-button" on-tap="onClearStorage_">
- $i18n{siteSettingsSiteClearAll}
+ <paper-button class="action-button" on-tap="onClearAndReset_">
+ $i18n{siteSettingsSiteResetAll}
</paper-button>
</div>
</dialog>
- <div class="settings-box first">
- <div class="favicon-image"
- style$="[[computeSiteIcon(origin)]]">
- </div>
- <!-- TODO(patricialor): This should show the origin's display name. -->
- <div class="middle">[[origin]]</div>
- </div>
- <template is="dom-if" if="[[storedData_]]">
+ <template is="dom-if" if="[[enableSiteSettings_]]">
<div id="usage">
<div class="settings-box first">
<h2>$i18n{siteSettingsUsage}</h2>
</div>
<div class="list-frame">
- <div class="list-item" id="storage">
+ <div class="list-item" id="noStorage"
+ hidden$="[[hasUsage_(storedData_)]]">
+ <div class="start">$i18n{siteSettingsUsageNone}</div>
+ </div>
+ <div class="list-item" id="storage" hidden$="[[!storedData_]]">
<div class="start">[[storedData_]]</div>
<button is="paper-icon-button-light" class="icon-delete-gray"
- on-tap="onConfirmClearStorage_"
- alt="$i18n{siteSettingsDelete}"></button>
+ on-tap="onConfirmClearStorage_" alt="$i18n{siteSettingsDelete}">
+ </button>
</div>
</div>
</div>
+
+ <div class="settings-box first">
+ <h2>$i18n{siteSettingsPermissions}</h2>
+ </div>
</template>
- <div class="settings-box first">
- <h2>$i18n{siteSettingsPermissions}</h2>
- </div>
- <div class="list-frame">
+ <div class$="list-frame [[permissionListClass_(enableSiteSettings_)]]">
<site-details-permission category="{{ContentSettingsTypes.GEOLOCATION}}"
icon="settings:location-on" id="geolocation"
label="$i18n{siteSettingsLocation}">
@@ -99,22 +111,37 @@
icon="settings:sync" id="backgroundSync"
label="$i18n{siteSettingsBackgroundSync}">
</site-details-permission>
+ <template is="dom-if" if="[[enableSoundContentSetting_]]" no-search>
+ <site-details-permission category="{{ContentSettingsTypes.SOUND}}"
+ icon="settings:volume-up" id="sound"
+ label="$i18n{siteSettingsSound}">
+ </site-details-permission>
+ </template>
<site-details-permission
category="{{ContentSettingsTypes.AUTOMATIC_DOWNLOADS}}"
icon="cr:file-download" id="automaticDownloads"
label="$i18n{siteSettingsAutomaticDownloads}">
</site-details-permission>
<site-details-permission
+ category="{{ContentSettingsTypes.MIDI_DEVICES}}" icon="settings:midi"
+ id="midiDevices" label="$i18n{siteSettingsMidiDevices}">
+ </site-details-permission>
+ <site-details-permission
category="{{ContentSettingsTypes.UNSANDBOXED_PLUGINS}}"
icon="cr:extension" id="unsandboxedPlugins"
label="$i18n{siteSettingsUnsandboxedPlugins}">
</site-details-permission>
+ </div>
- <div class="list-item">
- <a is="action-link" class="list-button" on-tap="onClearAndReset_" >
- $i18n{siteSettingsClearAndReset}
- </a>
+ <div id="clearAndReset" class="settings-box"
+ on-tap="onConfirmClearSettings_" actionable>
+ <div class="start">
+ $i18n{siteSettingsReset}
</div>
+ <button class="subpage-arrow" is="paper-icon-button-light"
+ aria-label="$i18n{siteSettingsReset}"
+ aria-describedby="clearAndReset">
+ </button>
</div>
<website-usage-private-api id="usageApi"
website-data-usage="{{storedData_}}"
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details.js b/chromium/chrome/browser/resources/settings/site_settings/site_details.js
index 0a08f0c5224..b45b86d5e2f 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details.js
@@ -10,7 +10,9 @@
Polymer({
is: 'site-details',
- behaviors: [SiteSettingsBehavior, settings.RouteObserverBehavior],
+ behaviors: [
+ SiteSettingsBehavior, settings.RouteObserverBehavior, WebUIListenerBehavior
+ ],
properties: {
/**
@@ -23,6 +25,15 @@ Polymer({
},
/**
+ * Use the string representing the origin or extension name as the page
+ * title of the settings-subpage parent.
+ */
+ pageTitle: {
+ type: String,
+ notify: true,
+ },
+
+ /**
* The amount of data stored for the origin.
* @private
*/
@@ -31,14 +42,27 @@ Polymer({
value: '',
},
+ /** @private */
+ enableSiteSettings_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('enableSiteSettings');
+ },
+ },
+
+ /** @private */
+ enableSoundContentSetting_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('enableSoundContentSetting');
+ },
+ },
+
/**
* The type of storage for the origin.
* @private
*/
storageType_: Number,
-
- /** @private */
- confirmationDeleteMsg_: String,
},
listeners: {
@@ -46,6 +70,13 @@ Polymer({
},
/** @override */
+ attached: function() {
+ this.addWebUIListener(
+ 'contentSettingSitePermissionChanged',
+ this.onPermissionChanged_.bind(this));
+ },
+
+ /** @override */
ready: function() {
this.ContentSettingsTypes = settings.ContentSettingsTypes;
},
@@ -67,25 +98,70 @@ Polymer({
* @private
*/
onOriginChanged_: function() {
- this.$.usageApi.fetchUsageTotal(this.toUrl(this.origin).hostname);
+ this.browserProxy.isOriginValid(this.origin).then((valid) => {
+ if (!valid) {
+ settings.navigateToPreviousRoute();
+ } else {
+ if (this.enableSiteSettings_)
+ this.$.usageApi.fetchUsageTotal(this.toUrl(this.origin).hostname);
- var siteDetailsPermissions =
- /** @type{!NodeList<!SiteDetailsPermissionElement>} */
- (this.root.querySelectorAll('site-details-permission'));
- var categoryList =
- /** @type{!Array<!string>} */ (
- Array.prototype.map.call(siteDetailsPermissions, function(element) {
- return element.category;
- }));
+ this.updatePermissions_(this.getCategoryList_());
+ }
+ });
+
+ },
+
+ /**
+ * Called when a site within a category has been changed.
+ * @param {!settings.ContentSettingsTypes} category The category that changed.
+ * @param {string} origin The origin of the site that changed.
+ * @param {string} embeddingOrigin The embedding origin of the site that
+ * changed.
+ * @private
+ */
+ onPermissionChanged_: function(category, origin, embeddingOrigin) {
+ if (this.origin === undefined || this.origin == '' ||
+ origin === undefined || origin == '')
+ return;
+ if (!this.getCategoryList_().includes(category))
+ return;
+
+ // Site details currently doesn't support embedded origins, so ignore it and
+ // just check whether the origins are the same.
+ if (this.toUrl(origin).origin == this.toUrl(this.origin).origin)
+ this.updatePermissions_([category]);
+ },
+
+ /**
+ * Retrieves the permissions listed in |categoryList| from the backend for
+ * |this.origin|.
+ * @param {!Array<!settings.ContentSettingsTypes>} categoryList The list of
+ * categories to update permissions for.
+ * @private
+ */
+ updatePermissions_: function(categoryList) {
+ var permissionsMap =
+ /** @type {!Object<!settings.ContentSettingsTypes,
+ * !SiteDetailsPermissionElement>} */
+ (Array.prototype.reduce.call(
+ this.root.querySelectorAll('site-details-permission'),
+ (map, element) => {
+ if (categoryList.includes(element.category))
+ map[element.category] = element;
+ return map;
+ },
+ {}));
this.browserProxy.getOriginPermissions(this.origin, categoryList)
- .then(function(exceptionList) {
- exceptionList.forEach(function(exception, i) {
- // |exceptionList| should be in the same order as |categoryList|,
- // which is in the same order as |siteDetailsPermissions|.
- siteDetailsPermissions[i].site =
- /** @type {!RawSiteException} */ (exception);
+ .then((exceptionList) => {
+ exceptionList.forEach((exception, i) => {
+ // |exceptionList| should be in the same order as |categoryList|.
+ permissionsMap[categoryList[i]].site = exception;
});
+
+ // The displayName won't change, so just use the first exception.
+ assert(exceptionList.length > 0);
+ this.pageTitle = exceptionList[0].displayName;
});
},
@@ -99,10 +175,8 @@ Polymer({
* @param {!Event} e
* @private
*/
- onConfirmClearStorage_: function(e) {
+ onConfirmClearSettings_: function(e) {
e.preventDefault();
- this.confirmationDeleteMsg_ = loadTimeData.getStringF(
- 'siteSettingsSiteRemoveConfirmation', this.toUrl(this.origin).href);
this.$.confirmDeleteDialog.showModal();
},
@@ -111,7 +185,11 @@ Polymer({
* @private
*/
onClearStorage_: function() {
- this.$.usageApi.clearUsage(this.toUrl(this.origin).href, this.storageType_);
+ // Since usage is only shown when "Site Settings" is enabled, don't clear it
+ // when it's not shown.
+ if (this.enableSiteSettings_)
+ this.$.usageApi.clearUsage(
+ this.toUrl(this.origin).href, this.storageType_);
},
/**
@@ -120,10 +198,8 @@ Polymer({
* @private
*/
onUsageDeleted_: function(event) {
- if (event.detail.origin == this.toUrl(this.origin).href) {
+ if (event.detail.origin == this.toUrl(this.origin).href)
this.storedData_ = '';
- this.navigateBackIfNoData_();
- }
},
/**
@@ -131,35 +207,44 @@ Polymer({
* @private
*/
onClearAndReset_: function() {
- this.root.querySelectorAll('site-details-permission')
- .forEach(function(element) {
- element.resetPermission();
- });
+ this.browserProxy.setOriginPermissions(
+ this.origin, this.getCategoryList_(), settings.ContentSetting.DEFAULT);
if (this.storedData_ != '')
this.onClearStorage_();
- else
- this.navigateBackIfNoData_();
+
+ this.onCloseDialog_();
},
/**
- * Navigate back if the UI is empty (everything been cleared).
+ * Returns list of categories for each permission displayed in <site-details>.
+ * @return {!Array<!settings.ContentSettingsTypes>}
* @private
*/
- navigateBackIfNoData_: function() {
- if (this.storedData_ == '' && !this.permissionShowing_())
- settings.navigateToPreviousRoute();
+ getCategoryList_: function() {
+ return Array.prototype.map.call(
+ this.root.querySelectorAll('site-details-permission'), (element) => {
+ return element.category;
+ });
},
/**
- * Returns true if one or more permission is showing.
+ * Checks whether the permission list is standalone or has a heading.
+ * @return {string} CSS class applied when the permission list has no heading.
* @private
*/
- permissionShowing_: function() {
- return Array.prototype.some.call(
- this.root.querySelectorAll('site-details-permission'),
- function(element) {
- return element.offsetHeight > 0;
- });
+ permissionListClass_: function(hasHeading) {
+ return hasHeading ? '' : 'without-heading';
+ },
+
+ /**
+ * Checks whether this site has any usage information to show.
+ * @return {boolean} Whether there is any usage information to show (e.g.
+ * disk or battery).
+ * @private
+ */
+ hasUsage_: function(storage) {
+ return storage != '';
},
+
});
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html b/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html
index 6e667648b4c..b356f183552 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html
@@ -13,12 +13,28 @@
<template>
<style include="settings-shared md-select"></style>
<div id="details">
- <div class="list-item underbar">
+ <div id="permissionItem" class="list-item">
<div>
<iron-icon icon="[[icon]]">
</iron-icon>
</div>
- <div class="middle" id="permissionHeader">[[label]]</div>
+ <div class="middle" id="permissionHeader">
+ [[label]]
+ <div class="secondary"
+ hidden$="[[!hasPermissionSourceString_(site.source)]]">
+ [[permissionSourceString_(
+ site.source,
+ '$i18nPolymer{siteSettingsSourceEmbargo}',
+ '$i18nPolymer{siteSettingsSourceInsecureOrigin}',
+ '$i18nPolymer{siteSettingsSourceKillSwitch}',
+ '$i18nPolymer{siteSettingsSourceExtensionAllow}',
+ '$i18nPolymer{siteSettingsSourceExtensionBlock}',
+ '$i18nPolymer{siteSettingsSourceExtensionAsk}',
+ '$i18nPolymer{siteSettingsSourcePolicyAllow}',
+ '$i18nPolymer{siteSettingsSourcePolicyBlock}',
+ '$i18nPolymer{siteSettingsSourcePolicyAsk}')]]
+ </div>
+ </div>
<div class="md-select-wrapper">
<select id="permission" class="md-select"
aria-labelledby="permissionHeader"
@@ -36,6 +52,10 @@
<option id="block" value$="[[ContentSetting.BLOCK]]">
$i18n{siteSettingsActionBlock}
</option>
+ <option id="ask" value$="[[ContentSetting.ASK]]"
+ hidden$="[[!isNonDefaultAsk_(site.setting, site.source)]]">
+ $i18n{siteSettingsActionAsk}
+ </option>
</select>
<span class="md-select-underline"></span>
</div>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.js b/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.js
index a590d465ed1..26d8fd7237c 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.js
@@ -27,26 +27,13 @@ Polymer({
defaultSetting_: String,
},
- observers: ['siteChanged_(site, category)'],
+ observers: ['siteChanged_(site)'],
/** @override */
attached: function() {
this.addWebUIListener(
- 'contentSettingSitePermissionChanged',
- this.sitePermissionChanged_.bind(this));
- },
-
- /**
- * Returns true if the origins match, e.g. http://google.com and
- * http://[*.]google.com.
- * @param {string} left The first origin to compare.
- * @param {string} right The second origin to compare.
- * @return {boolean} True if the origins are the same.
- * @private
- */
- sameOrigin_: function(left, right) {
- return this.removePatternWildcard(left) ==
- this.removePatternWildcard(right);
+ 'contentSettingCategoryChanged',
+ this.onDefaultSettingChanged_.bind(this));
},
/**
@@ -55,47 +42,59 @@ Polymer({
* @private
*/
siteChanged_: function(site) {
- if (site.source == 'default') {
+ if (site.source == settings.SiteSettingSource.DEFAULT) {
this.defaultSetting_ = site.setting;
this.$.permission.value = settings.ContentSetting.DEFAULT;
- return;
+ } else {
+ // The default setting is unknown, so consult the C++ backend for it.
+ this.updateDefaultPermission_(site);
+ this.$.permission.value = site.setting;
+ }
+
+ // Handle non-default sources.
+ if (site.source == settings.SiteSettingSource.DEFAULT ||
+ site.source == settings.SiteSettingSource.PREFERENCE) {
+ this.$.permissionItem.classList.remove('two-line');
+ this.$.permission.disabled = false;
+ } else {
+ this.$.permissionItem.classList.add('two-line');
+ // Users are able to override embargo, so leave enabled in that case.
+ this.$.permission.disabled =
+ site.source != settings.SiteSettingSource.EMBARGO;
+ }
+
+ if (this.isNonDefaultAsk_(site.setting, site.source)) {
+ assert(
+ this.$.permission.disabled,
+ 'The \'Ask\' entry is for display-only and cannot be set by the ' +
+ 'user.');
+ assert(
+ this.$.permission.value == settings.ContentSetting.ASK,
+ '\'Ask\' should only show up when it\'s currently selected.');
}
- // The default setting is unknown, so consult the C++ backend for it.
- this.browserProxy.getDefaultValueForContentType(this.category)
- .then((defaultValue) => {
- this.defaultSetting_ = defaultValue.setting;
- });
- this.$.permission.value = site.setting;
},
/**
- * Called when a site within a category has been changed.
- * @param {number} category The category that changed.
- * @param {string} origin The origin of the site that changed.
- * @param {string} embeddingOrigin The embedding origin of the site that
- * changed.
+ * Updates the default permission setting for this permission category.
+ * @param {!RawSiteException} site The site to display.
* @private
*/
- sitePermissionChanged_: function(category, origin, embeddingOrigin) {
- if (this.site === undefined)
- return;
- if (category != this.category)
- return;
-
- if (origin == '' ||
- (origin == this.site.origin &&
- embeddingOrigin == this.site.embeddingOrigin)) {
- this.siteChanged_(this.site);
- }
+ updateDefaultPermission_: function(site) {
+ this.browserProxy.getDefaultValueForContentType(this.category)
+ .then((defaultValue) => {
+ this.defaultSetting_ = defaultValue.setting;
+ });
},
/**
- * Resets the category permission for this origin.
+ * Handles the category permission changing for this origin.
+ * @param {!settings.ContentSettingsTypes} category The permission category
+ * that has changed default permission.
+ * @private
*/
- resetPermission: function() {
- this.browserProxy.resetCategoryPermissionForOrigin(
- this.site.origin, this.site.embeddingOrigin, this.category,
- this.site.incognito);
+ onDefaultSettingChanged_: function(category) {
+ if (category == this.category)
+ this.updateDefaultPermission_(this.site);
},
/**
@@ -103,25 +102,21 @@ Polymer({
* @private
*/
onPermissionSelectionChange_: function() {
- if (this.$.permission.value == settings.ContentSetting.DEFAULT) {
- this.resetPermission();
- return;
- }
- this.browserProxy.setCategoryPermissionForOrigin(
- this.site.origin, this.site.embeddingOrigin, this.category,
- this.$.permission.value, this.site.incognito);
+ this.browserProxy.setOriginPermissions(
+ this.site.origin, [this.category], this.$.permission.value);
},
/**
* Updates the string used for this permission category's default setting.
* @param {!settings.ContentSetting} defaultSetting Value of the default
- * setting for this permission category.
+ * setting for this permission category.
* @param {string} askString 'Ask' label, e.g. 'Ask (default)'.
* @param {string} allowString 'Allow' label, e.g. 'Allow (default)'.
* @param {string} blockString 'Block' label, e.g. 'Blocked (default)'.
* @private
*/
- defaultSettingString_(defaultSetting, askString, allowString, blockString) {
+ defaultSettingString_: function(
+ defaultSetting, askString, allowString, blockString) {
if (defaultSetting == settings.ContentSetting.ASK ||
defaultSetting == settings.ContentSetting.IMPORTANT_CONTENT) {
return askString;
@@ -133,4 +128,97 @@ Polymer({
assertNotReached(
`No string for ${this.category}'s default of ${defaultSetting}`);
},
+
+ /**
+ * Returns true if there's a string to display that describes the source of
+ * this permission's setting. Currently, this only gets called when
+ * |this.site| is updated.
+ * @param {!settings.SiteSettingSource} source The source of the permission.
+ * @private
+ */
+ hasPermissionSourceString_: function(source) {
+ return (
+ source != settings.SiteSettingSource.DEFAULT &&
+ source != settings.SiteSettingSource.PREFERENCE);
+ },
+
+ /**
+ * Returns true if the permission is set to a non-default 'ask'. Currently,
+ * this only gets called when |this.site| is updated.
+ * @param {!settings.ContentSetting} setting The setting of the permission.
+ * @param {!settings.SiteSettingSource} source The source of the permission.
+ * @private
+ */
+ isNonDefaultAsk_: function(setting, source) {
+ if (setting != settings.ContentSetting.ASK ||
+ source == settings.SiteSettingSource.DEFAULT) {
+ return false;
+ }
+
+ assert(
+ source == settings.SiteSettingSource.EXTENSION ||
+ source == settings.SiteSettingSource.POLICY,
+ 'Only extensions or enterprise policy can change the setting to ASK.');
+ return true;
+ },
+
+ /**
+ * Updates the string used to describe the source of this permission setting.
+ * Currently, this only gets called when |this.site| is updated.
+ * @param {!settings.SiteSettingSource} source The source of the permission.
+ * @param {!string} embargoString
+ * @param {!string} insecureOriginString
+ * @param {!string} killSwitchString
+ * @param {!string} extensionAllowString
+ * @param {!string} extensionBlockString
+ * @param {!string} extensionAskString
+ * @param {!string} policyAllowString
+ * @param {!string} policyBlockString
+ * @param {!string} policyAskString
+ * @private
+ */
+ permissionSourceString_: function(
+ source, embargoString, insecureOriginString, killSwitchString,
+ extensionAllowString, extensionBlockString, extensionAskString,
+ policyAllowString, policyBlockString, policyAskString) {
+
+ /** @type {Object<!settings.ContentSetting, string>} */
+ var extensionStrings = {};
+ extensionStrings[settings.ContentSetting.ALLOW] = extensionAllowString;
+ extensionStrings[settings.ContentSetting.BLOCK] = extensionBlockString;
+ extensionStrings[settings.ContentSetting.ASK] = extensionAskString;
+
+ /** @type {Object<!settings.ContentSetting, string>} */
+ var policyStrings = {};
+ policyStrings[settings.ContentSetting.ALLOW] = policyAllowString;
+ policyStrings[settings.ContentSetting.BLOCK] = policyBlockString;
+ policyStrings[settings.ContentSetting.ASK] = policyAskString;
+
+ if (source == settings.SiteSettingSource.EMBARGO) {
+ assert(
+ settings.ContentSetting.BLOCK == this.site.setting,
+ 'Embargo is only used to block permissions.');
+ return embargoString;
+ } else if (source == settings.SiteSettingSource.EXTENSION) {
+ return extensionStrings[this.site.setting];
+ } else if (source == settings.SiteSettingSource.INSECURE_ORIGIN) {
+ assert(
+ settings.ContentSetting.BLOCK == this.site.setting,
+ 'Permissions can only be blocked due to insecure origins.');
+ return insecureOriginString;
+ } else if (source == settings.SiteSettingSource.KILL_SWITCH) {
+ assert(
+ settings.ContentSetting.BLOCK == this.site.setting,
+ 'The permissions kill switch can only be used to block permissions.');
+ return killSwitchString;
+ } else if (source == settings.SiteSettingSource.POLICY) {
+ return policyStrings[this.site.setting];
+ } else if (
+ source == settings.SiteSettingSource.DEFAULT ||
+ source == settings.SiteSettingSource.PREFERENCE) {
+ return '';
+ }
+ assertNotReached(
+ `No string for ${this.category} setting source '${source}'`);
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_list.html b/chromium/chrome/browser/resources/settings/site_settings/site_list.html
index e5a7273fd26..899936a22cb 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_list.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_list.html
@@ -32,25 +32,23 @@
</div>
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" id="allow"
+ <button class="dropdown-item" id="allow"
on-tap="onAllowTap_" hidden$="[[!showAllowAction_]]">
$i18n{siteSettingsActionAllow}
</button>
- <button class="dropdown-item" role="option" id="block"
+ <button class="dropdown-item" id="block"
on-tap="onBlockTap_" hidden$="[[!showBlockAction_]]">
$i18n{siteSettingsActionBlock}
</button>
- <button class="dropdown-item" role="option" id="sessionOnly"
+ <button class="dropdown-item" id="sessionOnly"
on-tap="onSessionOnlyTap_"
hidden$="[[!showSessionOnlyActionForSite_(actionMenuSite_)]]">
$i18n{siteSettingsActionSessionOnly}
</button>
- <button class="dropdown-item" role="option" id="edit"
- on-tap="onEditTap_">
+ <button class="dropdown-item" id="edit" on-tap="onEditTap_">
$i18n{edit}
</button>
- <button class="dropdown-item" role="option" id="reset"
- on-tap="onResetTap_">
+ <button class="dropdown-item" id="reset" on-tap="onResetTap_">
$i18n{siteSettingsActionReset}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_list.js b/chromium/chrome/browser/resources/settings/site_settings/site_list.js
index f53c6193332..f2fd85b0d53 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_list.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_list.js
@@ -215,10 +215,10 @@ Polymer({
dialog.open(this.categorySubtype);
- dialog.addEventListener('close', function() {
+ dialog.addEventListener('close', () => {
cr.ui.focusWithoutInk(assert(this.$.addSite));
dialog.remove();
- }.bind(this));
+ });
},
/**
@@ -226,11 +226,10 @@ Polymer({
* @private
*/
populateList_: function() {
- this.browserProxy_.getExceptionList(this.category)
- .then(function(exceptionList) {
- this.processExceptions_([exceptionList]);
- this.closeActionMenu_();
- }.bind(this));
+ this.browserProxy_.getExceptionList(this.category).then(exceptionList => {
+ this.processExceptions_([exceptionList]);
+ this.closeActionMenu_();
+ });
},
/**
@@ -325,7 +324,7 @@ Polymer({
*/
resetPermissionForOrigin_: function(site) {
assert(site);
- this.browserProxy.resetCategoryPermissionForOrigin(
+ this.browserProxy.resetCategoryPermissionForPattern(
site.origin, site.embeddingOrigin, this.category, site.incognito);
},
@@ -335,7 +334,7 @@ Polymer({
*/
setContentSettingForActionMenuSite_: function(contentSetting) {
assert(this.actionMenuSite_);
- this.browserProxy.setCategoryPermissionForOrigin(
+ this.browserProxy.setCategoryPermissionForPattern(
this.actionMenuSite_.origin, this.actionMenuSite_.embeddingOrigin,
this.category, contentSetting, this.actionMenuSite_.incognito);
},
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_settings_behavior.js b/chromium/chrome/browser/resources/settings/site_settings/site_settings_behavior.js
index 762da0c000c..500344800ba 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_settings_behavior.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_settings_behavior.js
@@ -145,6 +145,8 @@ var SiteSettingsBehaviorImpl = {
var origin = exception.origin;
var embeddingOrigin = exception.embeddingOrigin;
+ // TODO(patricialor): |exception.source| should be one of the values defined
+ // in |settings.SiteSettingSource|.
var enforcement = /** @type {?chrome.settingsPrivate.Enforcement} */ (null);
if (exception.source == 'extension' || exception.source == 'HostedApp' ||
exception.source == 'platform_app' || exception.source == 'policy') {
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js b/chromium/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js
index bac63cd1b5a..0fe74d5f9da 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js
@@ -21,13 +21,12 @@ var ContentSettingProvider = {
/**
* The site exception information passed from the C++ handler.
* See also: SiteException.
- * TODO(patricialor): Investigate making the |source| field an enum type.
* @typedef {{embeddingOrigin: string,
* incognito: boolean,
* origin: string,
* displayName: string,
* setting: !settings.ContentSetting,
- * source: string}}
+ * source: !settings.SiteSettingSource}}
*/
var RawSiteException;
@@ -121,46 +120,68 @@ cr.define('settings', function() {
getExceptionList(contentType) {}
/**
+ * Gets a list of category permissions for a given origin. Note that this
+ * may be different to the results retrieved by getExceptionList(), since it
+ * combines different sources of data to get a permission's value.
+ * @param {string} origin The origin to look up permissions for.
+ * @param {!Array<!settings.ContentSettingsTypes>} contentTypes A list of
+ * categories to retrieve the ContentSetting for.
+ * @return {!Promise<!NodeList<!RawSiteException>>}
+ */
+ getOriginPermissions(origin, contentTypes) {}
+
+ /**
+ * Resets the permissions for a list of categories for a given origin. This
+ * does not support incognito settings or patterns.
+ * @param {string} origin The origin to reset permissions for.
+ * @param {!Array<!settings.ContentSettingsTypes>} contentTypes A list of
+ * categories to set the permission for. Typically this would be a
+ * single category, but sometimes it is useful to clear any permissions
+ * set for all categories.
+ * @param {!settings.ContentSetting} blanketSetting The setting to set all
+ * permissions listed in |contentTypes| to.
+ */
+ setOriginPermissions(origin, contentTypes, blanketSetting) {}
+
+ /**
* Resets the category permission for a given origin (expressed as primary
- * and secondary patterns).
+ * and secondary patterns). Only use this if intending to remove an
+ * exception - use setOriginPermissions() for origin-scoped settings.
* @param {string} primaryPattern The origin to change (primary pattern).
* @param {string} secondaryPattern The embedding origin to change
- * (secondary pattern).
+ * (secondary pattern).
* @param {string} contentType The name of the category to reset.
* @param {boolean} incognito Whether this applies only to a current
* incognito session exception.
*/
- resetCategoryPermissionForOrigin(
+ resetCategoryPermissionForPattern(
primaryPattern, secondaryPattern, contentType, incognito) {}
/**
- * Gets a list of category permissions for a given origin. Note that this
- * may be different to the results retrieved by getExceptionList(), since it
- * combines different sources of data to get a permission's value.
- * @param {string} origin The origin to look up permissions for.
- * @param {!Array<string>} contentTypes A list of categories to retrieve
- * the ContentSetting for.
- * @return {!Promise<!NodeList<!RawSiteException>>}
- */
- getOriginPermissions(origin, contentTypes) {}
-
- /**
- * Sets the category permission for a given origin (expressed as primary
- * and secondary patterns).
+ * Sets the category permission for a given origin (expressed as primary and
+ * secondary patterns). Only use this if intending to set an exception - use
+ * setOriginPermissions() for origin-scoped settings.
* @param {string} primaryPattern The origin to change (primary pattern).
* @param {string} secondaryPattern The embedding origin to change
- * (secondary pattern).
+ * (secondary pattern).
* @param {string} contentType The name of the category to change.
* @param {string} value The value to change the permission to.
* @param {boolean} incognito Whether this rule applies only to the current
* incognito session.
*/
- setCategoryPermissionForOrigin(
+ setCategoryPermissionForPattern(
primaryPattern, secondaryPattern, contentType, value, incognito) {}
/**
+ * Checks whether an origin is valid.
+ * @param {string} origin The origin to check.
+ * @return {!Promise<boolean>} True if the origin is valid.
+ */
+ isOriginValid(origin) {}
+
+ /**
* Checks whether a pattern is valid.
- * @param {string} pattern The pattern to check
+ * @param {string} pattern The pattern to check.
* @return {!Promise<boolean>} True if the pattern is valid.
*/
isPatternValid(pattern) {}
@@ -307,30 +328,41 @@ cr.define('settings', function() {
}
/** @override */
- resetCategoryPermissionForOrigin(
- primaryPattern, secondaryPattern, contentType, incognito) {
+ getOriginPermissions(origin, contentTypes) {
+ return cr.sendWithPromise('getOriginPermissions', origin, contentTypes);
+ }
+
+ /** @override */
+ setOriginPermissions(origin, contentTypes, blanketSetting) {
chrome.send(
- 'resetCategoryPermissionForOrigin',
- [primaryPattern, secondaryPattern, contentType, incognito]);
+ 'setOriginPermissions', [origin, contentTypes, blanketSetting]);
}
/** @override */
- getOriginPermissions(origin, contentTypes) {
- return cr.sendWithPromise('getOriginPermissions', origin, contentTypes);
+ resetCategoryPermissionForPattern(
+ primaryPattern, secondaryPattern, contentType, incognito) {
+ chrome.send(
+ 'resetCategoryPermissionForPattern',
+ [primaryPattern, secondaryPattern, contentType, incognito]);
}
/** @override */
- setCategoryPermissionForOrigin(
+ setCategoryPermissionForPattern(
primaryPattern, secondaryPattern, contentType, value, incognito) {
// TODO(dschuyler): It may be incorrect for JS to send the embeddingOrigin
// pattern. Look into removing this parameter from site_settings_handler.
// Ignoring the |secondaryPattern| and using '' instead is a quick-fix.
chrome.send(
- 'setCategoryPermissionForOrigin',
+ 'setCategoryPermissionForPattern',
[primaryPattern, '', contentType, value, incognito]);
}
/** @override */
+ isOriginValid(origin) {
+ return cr.sendWithPromise('isOriginValid', origin);
+ }
+
+ /** @override */
isPatternValid(pattern) {
return cr.sendWithPromise('isPatternValid', pattern);
}
diff --git a/chromium/chrome/browser/resources/settings/site_settings/usb_devices.html b/chromium/chrome/browser/resources/settings/site_settings/usb_devices.html
index f50308a1a77..7388b9f6fd2 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/usb_devices.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/usb_devices.html
@@ -41,7 +41,7 @@
</template>
<dialog is="cr-action-menu">
- <button class="dropdown-item" role="option" on-tap="onRemoveTap_" id="removeButton">
+ <button id="removeButton" class="dropdown-item" on-tap="onRemoveTap_">
$i18n{handlerRemove}
</button>
</dialog>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/usb_devices.js b/chromium/chrome/browser/resources/settings/site_settings/usb_devices.js
index 28a489875d0..c4e64f3891a 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/usb_devices.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/usb_devices.js
@@ -37,9 +37,9 @@ Polymer({
* @private
*/
fetchUsbDevices_: function() {
- this.browserProxy.fetchUsbDevices().then(function(deviceList) {
+ this.browserProxy.fetchUsbDevices().then(deviceList => {
this.devices_ = deviceList;
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
index 50ef70e2c73..b0d1207994a 100644
--- a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
+++ b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
@@ -143,9 +143,8 @@
<div class="secondary" id="flashSecondary">
[[defaultSettingLabel_(
default_.plugins,
- '$i18nPolymer{siteSettingsFlashAllow}',
- '$i18nPolymer{siteSettingsFlashBlock}',
- '$i18nPolymer{siteSettingsFlashAskBefore}')]]
+ '$i18nPolymer{siteSettingsFlashAskFirst}',
+ '$i18nPolymer{siteSettingsFlashBlock}')]]
</div>
</div>
<button class="subpage-arrow" is="paper-icon-button-light"
@@ -224,6 +223,26 @@
aria-label="$i18n{siteSettingsBackgroundSync}"
aria-describedby="backgroundSyncSecondary"></button>
</div>
+ <template is="dom-if" if="[[enableSoundContentSetting_]]">
+ <div id="sound" class="settings-box two-line"
+ category$="[[ContentSettingsTypes.SOUND]]"
+ data-route="SITE_SETTINGS_SOUND" on-tap="onTapNavigate_"
+ actionable>
+ <iron-icon icon="settings:volume-up"></iron-icon>
+ <div class="middle">
+ $i18n{siteSettingsSound}
+ <div class="secondary" id="soundSecondary">
+ [[defaultSettingLabel_(
+ default_.sound,
+ '$i18nPolymer{siteSettingsAllowed}',
+ '$i18nPolymer{siteSettingsBlocked}')]]
+ </div>
+ </div>
+ <button class="subpage-arrow" is="paper-icon-button-light"
+ aria-label="$i18n{siteSettingsSound}"
+ aria-describedby="soundSecondary"></button>
+ </div>
+ </template>
<div id="automatic-downloads" class="settings-box two-line"
category$="[[ContentSettingsTypes.AUTOMATIC_DOWNLOADS]]"
data-route="SITE_SETTINGS_AUTOMATIC_DOWNLOADS"
diff --git a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
index e07ce92b87c..e41cefd7258 100644
--- a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
+++ b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
@@ -51,6 +51,14 @@ Polymer({
}
},
+ /** @private */
+ enableSoundContentSetting_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('enableSoundContentSetting');
+ }
+ },
+
/** @type {!Map<string, string>} */
focusConfig: {
type: Object,
@@ -77,8 +85,8 @@ Polymer({
[R.SITE_SETTINGS_MICROPHONE, 'microphone'],
[R.SITE_SETTINGS_NOTIFICATIONS, 'notifications'],
[R.SITE_SETTINGS_JAVASCRIPT, 'javascript'],
- [R.SITE_SETTINGS_FLASH, 'flash'], [R.SITE_SETTINGS_IMAGES, 'images'],
- [R.SITE_SETTINGS_POPUPS, 'popups'],
+ [R.SITE_SETTINGS_SOUND, 'sound'], [R.SITE_SETTINGS_FLASH, 'flash'],
+ [R.SITE_SETTINGS_IMAGES, 'images'], [R.SITE_SETTINGS_POPUPS, 'popups'],
[R.SITE_SETTINGS_BACKGROUND_SYNC, 'background-sync'],
[R.SITE_SETTINGS_AUTOMATIC_DOWNLOADS, 'automatic-downloads'],
[R.SITE_SETTINGS_UNSANDBOXED_PLUGINS, 'unsandboxed-plugins'],
@@ -88,11 +96,11 @@ Polymer({
[R.SITE_SETTINGS_USB_DEVICES, 'usb-devices'],
[R.SITE_SETTINGS_PDF_DOCUMENTS, 'pdf-documents'],
[R.SITE_SETTINGS_PROTECTED_CONTENT, 'protected-content'],
- ].forEach(function(pair) {
+ ].forEach(pair => {
var route = pair[0];
var id = pair[1];
this.focusConfig.set(route.path, '* /deep/ #' + id + ' .subpage-arrow');
- }.bind(this));
+ });
},
/** @override */
@@ -146,11 +154,11 @@ Polymer({
*/
updateDefaultValueLabel_: function(category) {
this.browserProxy.getDefaultValueForContentType(category).then(
- function(defaultValue) {
+ defaultValue => {
this.set(
'default_.' + Polymer.CaseMap.dashToCamelCase(category),
defaultValue.setting);
- }.bind(this));
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/settings/system_page/system_page.html b/chromium/chrome/browser/resources/settings/system_page/system_page.html
index 9024b88087b..77bc47816f3 100644
--- a/chromium/chrome/browser/resources/settings/system_page/system_page.html
+++ b/chromium/chrome/browser/resources/settings/system_page/system_page.html
@@ -13,26 +13,22 @@
<dom-module id="settings-system-page">
<template>
<style include="settings-shared"></style>
- <div class="settings-box first">
<if expr="not is_macosx">
- <settings-toggle-button class="start"
- pref="{{prefs.background_mode.enabled}}"
- label="$i18n{backgroundAppsLabel}">
- </settings-toggle-button>
- </div>
- <div class="settings-box">
+ <settings-toggle-button class="first"
+ pref="{{prefs.background_mode.enabled}}"
+ label="$i18n{backgroundAppsLabel}">
+ </settings-toggle-button>
</if>
- <settings-toggle-button class="start" id="hardwareAcceleration"
- pref="{{prefs.hardware_acceleration_mode.enabled}}"
- label="$i18n{hardwareAccelerationLabel}">
- <template is="dom-if" if="[[shouldShowRestart_(
- prefs.hardware_acceleration_mode.enabled.value)]]">
- <paper-button on-tap="onRestartTap_" class="more-actions">
- $i18n{restart}
- </paper-button>
- </template>
- </settings-toggle-button>
- </div>
+ <settings-toggle-button id="hardwareAcceleration"
+ pref="{{prefs.hardware_acceleration_mode.enabled}}"
+ label="$i18n{hardwareAccelerationLabel}">
+ <template is="dom-if" if="[[shouldShowRestart_(
+ prefs.hardware_acceleration_mode.enabled.value)]]">
+ <paper-button on-tap="onRestartTap_" slot="more-actions">
+ $i18n{restart}
+ </paper-button>
+ </template>
+ </settings-toggle-button>
<div id="proxy" class="settings-box" on-tap="onProxyTap_"
actionable$="[[!isProxyEnforcedByPolicy_]]">
<div class="start">$i18n{proxySettingsLabel}</div>
diff --git a/chromium/chrome/browser/resources/settings/system_page/system_page.js b/chromium/chrome/browser/resources/settings/system_page/system_page.js
index b03f680f092..1609c78aa6c 100644
--- a/chromium/chrome/browser/resources/settings/system_page/system_page.js
+++ b/chromium/chrome/browser/resources/settings/system_page/system_page.js
@@ -51,7 +51,9 @@ Polymer({
},
/** @private */
- onRestartTap_: function() {
+ onRestartTap_: function(e) {
+ // Prevent event from bubbling up to the toggle button.
+ e.stopPropagation();
// TODO(dbeam): we should prompt before restarting the browser.
settings.LifetimeBrowserProxyImpl.getInstance().restart();
},
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
index 6f7d2effcaa..99a1e1122d7 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
@@ -37,7 +37,7 @@
<div id="icon-circle-4" class="icon-circle fade-top-right"></div>
</div>
<div class="picture">
- <img id="profile-picture"></img>
+ <img id="profile-picture">
<div id="checkmark-circle">
<svg id="checkmark-check" width="13" height="10" viewBox="0 0 13 10">
<path id="checkmark-path" d="M1 5l3.5 3.5L12 1" stroke="#FFF"
diff --git a/chromium/chrome/browser/resources/snippets_internals.css b/chromium/chrome/browser/resources/snippets_internals.css
index e84d84cc8e5..f5fbe251089 100644
--- a/chromium/chrome/browser/resources/snippets_internals.css
+++ b/chromium/chrome/browser/resources/snippets_internals.css
@@ -89,3 +89,9 @@ button {
max-width: 100px;
min-height: 40px;
}
+
+#contextual-suggestions-section input {
+ box-sizing: border-box;
+ display: block;
+ width: 100%;
+}
diff --git a/chromium/chrome/browser/resources/snippets_internals.html b/chromium/chrome/browser/resources/snippets_internals.html
index 0c2df4eb20e..9519cf97f50 100644
--- a/chromium/chrome/browser/resources/snippets_internals.html
+++ b/chromium/chrome/browser/resources/snippets_internals.html
@@ -12,9 +12,11 @@ found in the LICENSE file.
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<link rel="stylesheet" href="snippets_internals.css">
<script src="chrome://resources/js/cr.js"></script>
+<script src="chrome://resources/js/load_time_data.js"></script>
<script src="chrome://resources/js/jstemplate_compiled.js"></script>
<script src="chrome://resources/js/util.js"></script>
<script src="snippets_internals.js"></script>
+<script src="strings.js"></script>
<div id="info">
<div>
@@ -104,14 +106,25 @@ found in the LICENSE file.
</div>
</div>
- <div id="remote-content-suggestions" class="">
+ <div id="remote-content-suggestions">
<h2>Remote content suggestions</h2>
<div>
<span>Last Background Fetch Time: </span>
<span id="last-background-fetch-time-label"></span>
</div>
<button id="background-fetch-button" type="button">
- Fetch remote suggestions in the background
+ Fetch remote suggestions in the background in 2 seconds
+ </button>
+ <button id="push-dummy-suggestion-10-seconds-button" type="button">
+ Push dummy suggestion in 10 seconds
+ </button>
+ </div>
+
+ <div id="notifications">
+ <h2>Notifications</h2>
+ <div>
+ <button id="reset-notifications-state-button" type="button">
+ Reset notifications state
</button>
</div>
@@ -221,4 +234,49 @@ found in the LICENSE file.
</div>
<div class="detail" id="content-suggestions-empty"></div>
</div>
+
+ <div id="contextual-suggestions-section" class="hidden">
+ <h2>Contextual Suggestions</h2>
+ <h3>Request for URL</h3>
+ <input type="url" id="contextual-url"
+ value="https://en.wikipedia.org/wiki/Persian_language"></input>
+ <button id="fetch-contextual-suggestions-button">
+ Fetch Contextual Suggestions
+ </button>
+
+ <h3>Response status</h3>
+ <div id="contextual-suggestions-request-result">
+ No request sent yet.
+ </div>
+
+ <h3>Contextual Suggestions response</h3>
+ <div id="contextual-suggestions">
+ <table class="section-details">
+ <tr jsselect="list" style="display:none">
+ <td class="title-link">
+ <span class="contextual-hidden-toggler content-suggestion-title"
+ jsvalues="hidden-id:id">
+ <span jscontent="title"></span>&gt;&gt;
+ </span>
+ <div jsvalues="id:id" class="content-suggestion-detail hidden">
+ <table>
+ <tr>
+ <td>ID
+ <td jscontent="idWithinCategory">
+ <tr>
+ <td>URL
+ <td><a class="url" jsvalues="href:url" jscontent="url"></a>
+ <tr>
+ <td>URL with favicon
+ <td>
+ <a class="url" jsvalues="href:urlWithFavicon"
+ jscontent="urlWithFavicon"></a>
+ <tr>
+ <td>Publisher name
+ <td jscontent="publisherName">
+ </table>
+ </div>
+ </table>
+ </div>
+ </div>
</div>
diff --git a/chromium/chrome/browser/resources/snippets_internals.js b/chromium/chrome/browser/resources/snippets_internals.js
index d971832652d..69a4cb5ac14 100644
--- a/chromium/chrome/browser/resources/snippets_internals.js
+++ b/chromium/chrome/browser/resources/snippets_internals.js
@@ -34,10 +34,35 @@ cr.define('chrome.SnippetsInternals', function() {
});
$('background-fetch-button').addEventListener('click', function(event) {
- chrome.send('fetchRemoteSuggestionsInTheBackground');
+ chrome.send('fetchRemoteSuggestionsInTheBackgroundIn2Seconds');
event.preventDefault();
});
+ $('push-dummy-suggestion-10-seconds-button')
+ .addEventListener('click', function(event) {
+ chrome.send('pushDummySuggestionIn10Seconds');
+ event.preventDefault();
+ });
+
+ if (loadTimeData.getBoolean('contextualSuggestionsEnabled')) {
+ $('contextual-suggestions-section').classList.remove('hidden');
+ }
+
+ $('fetch-contextual-suggestions-button')
+ .addEventListener('click', function(event) {
+ let url = $('contextual-url').value;
+ $('contextual-suggestions-request-result').textContent =
+ 'Fetching contextual suggestions for ' + url;
+ chrome.send('fetchContextualSuggestions', [url]);
+ event.preventDefault();
+ });
+
+ $('reset-notifications-state-button')
+ .addEventListener('click', function(event) {
+ chrome.send('resetNotificationsState');
+ event.preventDefault();
+ });
+
window.addEventListener('focus', refreshContent);
window.setInterval(refreshContent, 1000);
@@ -48,6 +73,12 @@ cr.define('chrome.SnippetsInternals', function() {
$(propertyId).textContent = value;
}
+ function receiveContextualSuggestions(suggestions, status_msg) {
+ $('contextual-suggestions-request-result').textContent = status_msg;
+ displayList(
+ suggestions, 'contextual-suggestions', 'contextual-hidden-toggler');
+ }
+
function receiveContentSuggestions(categoriesList) {
lastSuggestions = categoriesList;
displayList(categoriesList, 'content-suggestions', 'hidden-toggler');
@@ -178,6 +209,7 @@ cr.define('chrome.SnippetsInternals', function() {
receiveRankerDebugData: receiveRankerDebugData,
receiveLastRemoteSuggestionsBackgroundFetchTime:
receiveLastRemoteSuggestionsBackgroundFetchTime,
+ receiveContextualSuggestions: receiveContextualSuggestions,
};
});
diff --git a/chromium/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.asciipb b/chromium/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.asciipb
index 27d6f0ed6b3..f98d4385429 100644
--- a/chromium/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.asciipb
+++ b/chromium/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.asciipb
@@ -150,3 +150,8 @@ captive_portal_cert {
captive_portal_cert {
sha256_hash: "sha256/LKtpdq9q7F7msGK0w1+b/gKoDHaQcZKTHIf9PTz2u+U="
}
+
+mitm_software {
+ name: "Kaspersky Internet Security",
+ issuer_common_name_regex: "Kaspersky Anti-Virus Personal Root Certificate"
+}
diff --git a/chromium/chrome/browser/resources/uber/OWNERS b/chromium/chrome/browser/resources/uber/OWNERS
index e8ea397ac47..adf0fa51b92 100644
--- a/chromium/chrome/browser/resources/uber/OWNERS
+++ b/chromium/chrome/browser/resources/uber/OWNERS
@@ -1,3 +1 @@
-dbeam@chromium.org
-
# COMPONENT: UI>Browser>WebUI
diff --git a/chromium/chrome/browser/resources/uber/uber_frame.css b/chromium/chrome/browser/resources/uber/uber_frame.css
index 2e4551d3198..8445c554c7d 100644
--- a/chromium/chrome/browser/resources/uber/uber_frame.css
+++ b/chromium/chrome/browser/resources/uber/uber_frame.css
@@ -31,8 +31,8 @@ ul {
li {
-webkit-border-start: 6px solid transparent;
-webkit-padding-start: 18px;
- -webkit-user-select: none;
cursor: pointer;
+ user-select: none;
}
li:hover {
diff --git a/chromium/chrome/browser/resources/unpack_pak.py b/chromium/chrome/browser/resources/unpack_pak.py
index 46692798eee..cf747600db7 100755
--- a/chromium/chrome/browser/resources/unpack_pak.py
+++ b/chromium/chrome/browser/resources/unpack_pak.py
@@ -13,7 +13,7 @@ _HERE_PATH = os.path.join(os.path.dirname(__file__))
_SRC_PATH = os.path.normpath(os.path.join(_HERE_PATH, '..', '..', '..'))
-sys.path.append(os.path.join(_SRC_PATH, 'tools', 'grit'))
+sys.path.insert(1, os.path.join(_SRC_PATH, 'tools', 'grit'))
from grit.format import data_pack
diff --git a/chromium/chrome/browser/resources/vulcanize.gni b/chromium/chrome/browser/resources/vulcanize.gni
index 69db5294cc8..5555d35f712 100644
--- a/chromium/chrome/browser/resources/vulcanize.gni
+++ b/chromium/chrome/browser/resources/vulcanize.gni
@@ -34,12 +34,16 @@ template("vulcanize") {
]
# This depfile is generated by vulcanize_gn.py
- depfile = "${target_gen_dir}/${invoker.html_out_file}.d"
+ depfile = "${target_gen_dir}/${target_name}.d"
+
+ outputs = []
+ foreach(_out, invoker.html_out_files) {
+ outputs += [ "$target_gen_dir/$_out" ]
+ }
+ foreach(_out, invoker.js_out_files) {
+ outputs += [ "$target_gen_dir/$_out" ]
+ }
- outputs = [
- "$target_gen_dir/${invoker.html_out_file}",
- "$target_gen_dir/${invoker.js_out_file}",
- ]
deps = invoker.deps
# Note that we have to manually pass the sources to our script if the
@@ -47,12 +51,6 @@ template("vulcanize") {
args = [
"--host",
invoker.host,
- "--html_in_file",
- invoker.html_in_file,
- "--html_out_file",
- invoker.html_out_file,
- "--js_out_file",
- invoker.js_out_file,
"--input",
invoker.input,
"--out_folder",
@@ -61,6 +59,10 @@ template("vulcanize") {
rebase_path(depfile, root_build_dir),
]
+ args += [ "--html_in_files" ] + invoker.html_in_files
+ args += [ "--html_out_files" ] + invoker.html_out_files
+ args += [ "--js_out_files" ] + invoker.js_out_files
+
if (defined(invoker.excludes)) {
args += [ "--exclude" ] + invoker.excludes
}
diff --git a/chromium/chrome/browser/resources/vulcanize_gn.py b/chromium/chrome/browser/resources/vulcanize_gn.py
index e6983018f02..f5c48c88d7e 100755
--- a/chromium/chrome/browser/resources/vulcanize_gn.py
+++ b/chromium/chrome/browser/resources/vulcanize_gn.py
@@ -5,9 +5,11 @@
import argparse
import itertools
+import json
import os
import platform
import re
+import shutil
import sys
import tempfile
@@ -27,6 +29,9 @@ _RESOURCES_PATH = os.path.join(_SRC_PATH, 'ui', 'webui', 'resources')
_CR_ELEMENTS_PATH = os.path.join(_RESOURCES_PATH, 'cr_elements')
+_CR_COMPONENTS_PATH = os.path.join(_RESOURCES_PATH, 'cr_components')
+
+
_CSS_RESOURCES_PATH = os.path.join(_RESOURCES_PATH, 'css')
@@ -43,21 +48,26 @@ _POLYMER_PATH = os.path.join(
_VULCANIZE_BASE_ARGS = [
# These files are already combined and minified.
'--exclude', 'chrome://resources/html/polymer.html',
- '--exclude', 'web-animations-next-lite.min.js',
+ '--exclude', 'chrome://resources/polymer/v1_0/polymer/polymer.html',
+ '--exclude', 'chrome://resources/polymer/v1_0/polymer/polymer-micro.html',
+ '--exclude', 'chrome://resources/polymer/v1_0/polymer/polymer-mini.html',
+ '--exclude', 'chrome://resources/polymer/v1_0/web-animations-js/' +
+ 'web-animations-next-lite.min.js',
- # These files are dynamically created by C++.
- '--exclude', 'load_time_data.js',
- '--exclude', 'strings.js',
- '--exclude', 'text_defaults.css',
- '--exclude', 'text_defaults_md.css',
+ '--exclude', 'chrome://resources/css/roboto.css',
+ '--exclude', 'chrome://resources/css/text_defaults.css',
+ '--exclude', 'chrome://resources/css/text_defaults_md.css',
+ '--exclude', 'chrome://resources/js/load_time_data.js',
'--inline-css',
'--inline-scripts',
+ '--rewrite-urls-in-templates',
'--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),
@@ -77,32 +87,24 @@ def _undo_mapping(mappings, url):
# TODO(dbeam): can we make this stricter?
return url
-def _request_list_path(out_path, html_out_file):
- return os.path.join(out_path, html_out_file + '_requestlist.txt')
+def _request_list_path(out_path, host):
+ return os.path.join(out_path, host + '_requestlist.txt')
-# Get a list of all files that were bundled with Vulcanize and update the
-# depfile accordingly such that Ninja knows when to trigger re-vulcanization.
-def _update_dep_file(in_folder, args):
+# Get a list of all files that were bundled with polymer-bundler and update the
+# depfile accordingly such that Ninja knows when to re-trigger.
+def _update_dep_file(in_folder, args, manifest):
in_path = os.path.join(_CWD, in_folder)
- out_path = os.path.join(_CWD, args.out_folder)
- # Prior call to vulcanize already generated the deps list, grab it from there.
- request_list_path = _request_list_path(out_path, args.html_out_file)
- request_list = open(request_list_path, 'r').read().splitlines()
-
- if platform.system() == 'Windows':
- # TODO(dbeam): UGH. For some reason Vulcanize is interpreting the target
- # file path as a URL and using the drive letter (e.g. D:\) as a protocol.
- # This is a little insane, but we're fixing here by normalizing case (which
- # really shouldn't matter, these are all file paths and generally are all
- # lower case) and writing from / to \ (file path) and then back again. This
- # is compounded by NodeJS having a bug in url.resolve() that handles
- # chrome:// protocol URLs poorly as well as us using startswith() to strip
- # file paths (which isn't crazy awesome either). Don't remove unless you
- # really really know what you're doing.
- norm = lambda u: u.lower().replace('/', '\\')
- request_list = [norm(u).replace(norm(in_path), '').replace('\\', '/')
- for u in request_list]
+ # Gather the dependencies of all bundled root HTML files.
+ request_list = []
+ for html_file in manifest:
+ request_list += manifest[html_file]
+
+ # 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,
+ request_list)
# Undo the URL mappings applied by vulcanize to get file paths relative to
# current working directory.
@@ -121,81 +123,93 @@ def _update_dep_file(in_folder, args):
deps = [d for d in deps if not d.startswith(filter_url)]
with open(os.path.join(_CWD, args.depfile), 'w') as f:
- deps_file_header = os.path.join(args.out_folder, args.html_out_file)
+ deps_file_header = os.path.join(args.out_folder, args.html_out_files[0])
f.write(deps_file_header + ': ' + ' '.join(deps))
def _vulcanize(in_folder, args):
in_path = os.path.normpath(os.path.join(_CWD, in_folder))
out_path = os.path.join(_CWD, args.out_folder)
-
- html_out_path = os.path.join(out_path, args.html_out_file)
- js_out_path = os.path.join(out_path, args.js_out_file)
+ manifest_out_path = _request_list_path(out_path, args.host)
exclude_args = []
for f in args.exclude or []:
exclude_args.append('--exclude')
exclude_args.append(f)
- output = node.RunNode(
- [node_modules.PathToVulcanize()] +
- _VULCANIZE_BASE_ARGS + _VULCANIZE_REDIRECT_ARGS + exclude_args +
- ['--out-request-list', _request_list_path(out_path, args.html_out_file),
- '--redirect', '"/|%s"' % in_path,
- '--redirect', '"chrome://%s/|%s"' % (args.host, in_path),
- # TODO(dpapad): Figure out why vulcanize treats the input path
- # differently on Windows VS Linux/Mac.
- os.path.join(
- in_path if platform.system() == 'Windows' else os.sep,
- args.html_in_file)])
-
- # Grit includes are not supported, use HTML imports instead.
- output = output.replace('<include src="', '<include src-disabled="')
-
- if args.insert_in_head:
- assert '<head>' in output
- # NOTE(dbeam): Vulcanize eats <base> tags after processing. This undoes
- # that by adding a <base> tag to the (post-processed) generated output.
- output = output.replace('<head>', '<head>' + args.insert_in_head)
+ in_html_args = []
+ for f in args.html_in_files:
+ in_html_args.append('--in-html')
+ in_html_args.append(f)
- crisper_input = tempfile.NamedTemporaryFile(mode='wt+', delete=False)
- crisper_input.write(output)
- crisper_input.close()
+ tmp_out_dir = os.path.join(out_path, 'bundled')
+ node.RunNode(
+ [node_modules.PathToBundler()] +
+ _VULCANIZE_BASE_ARGS + _VULCANIZE_REDIRECT_ARGS + exclude_args +
+ [# This file is dynamically created by C++. Need to specify an exclusion
+ # URL for both the relative URL and chrome:// URL syntax.
+ '--exclude', 'strings.js',
+ '--exclude', 'chrome://%s/strings.js' % args.host,
- crisper_output = tempfile.NamedTemporaryFile(mode='wt+', delete=False)
- crisper_output.close()
+ '--manifest-out', manifest_out_path,
+ '--root', in_path,
+ '--redirect', '"chrome://%s/|%s"' % (args.host, in_path),
+ '--out-dir', os.path.relpath(tmp_out_dir, _CWD),
+ '--shell', args.html_in_files[0],
+ ] + in_html_args)
+
+ for index, html_file in enumerate(args.html_in_files):
+ with open(
+ os.path.join(os.path.relpath(tmp_out_dir, _CWD), html_file), 'r') as f:
+ output = f.read()
+
+ # Grit includes are not supported, use HTML imports instead.
+ output = output.replace('<include src="', '<include src-disabled="')
+
+ if args.insert_in_head:
+ assert '<head>' in output
+ # NOTE(dbeam): polymer-bundler eats <base> tags after processing. This
+ # undoes that by adding a <base> tag to the (post-processed) generated
+ # output.
+ output = output.replace('<head>', '<head>' + args.insert_in_head)
+
+ # Open file again with 'w' such that the previous contents are overwritten.
+ with open(
+ os.path.join(os.path.relpath(tmp_out_dir, _CWD), html_file), 'w') as f:
+ f.write(output)
+ f.close()
try:
- node.RunNode([node_modules.PathToCrisper(),
- '--source', crisper_input.name,
- '--script-in-head', 'false',
- '--only-split',
- '--html', html_out_path,
- '--js', crisper_output.name])
-
- # Crisper by default inserts a <script> tag with the name of the --js file,
- # but since we are using a temporary file, need to manually insert a
- # <script> tag with the correct final filename (in combination with
- # --only-split flag). There is no way currently to manually specify the
- # <script> tag's path, see https://github.com/PolymerLabs/crisper/issues/46.
- with open(html_out_path, 'r+') as f:
- data = f.read()
- new_data = data.replace(
- '</body></html>',
- '<script src="' + args.js_out_file + '"></script></body></html>')
- assert new_data != data, 'Expected to find </body></html> token.'
- f.seek(0)
- f.write(new_data)
- f.truncate()
-
- node.RunNode([node_modules.PathToUglify(), crisper_output.name,
- '--comments', '"/Copyright|license|LICENSE|\<\/?if/"',
- '--output', js_out_path])
+ crisper_html_out_paths = []
+ for index, html_in_file in enumerate(args.html_in_files):
+ crisper_html_out_paths.append(
+ os.path.join(tmp_out_dir, args.html_out_files[index]))
+ js_out_file = args.js_out_files[index]
+
+ # Run crisper to separate the JS from the HTML file.
+ node.RunNode([node_modules.PathToCrisper(),
+ '--source', os.path.join(tmp_out_dir, html_in_file),
+ '--script-in-head', 'false',
+ '--html', crisper_html_out_paths[index],
+ '--js', os.path.join(tmp_out_dir, js_out_file)])
+
+ # Pass the JS file through Uglify and write the output to its final
+ # destination.
+ node.RunNode([node_modules.PathToUglify(),
+ os.path.join(tmp_out_dir, js_out_file),
+ '--comments', '"/Copyright|license|LICENSE|\<\/?if/"',
+ '--output', os.path.join(out_path, js_out_file)])
+
+ # Run polymer-css-build and write the output HTML files to their final
+ # destination.
+ pcb_html_out_paths = [
+ os.path.join(out_path, f) for f in args.html_out_files]
+ node.RunNode([node_modules.PathToPolymerCssBuild()] +
+ ['--no-inline-includes', '-f'] +
+ crisper_html_out_paths + ['-o'] + pcb_html_out_paths)
finally:
- if os.path.exists(crisper_input.name):
- os.remove(crisper_input.name)
- if os.path.exists(crisper_output.name):
- os.remove(crisper_output.name)
+ shutil.rmtree(tmp_out_dir)
+ return manifest_out_path
def main(argv):
@@ -203,11 +217,11 @@ def main(argv):
parser.add_argument('--depfile', required=True)
parser.add_argument('--exclude', nargs='*')
parser.add_argument('--host', required=True)
- parser.add_argument('--html_in_file', required=True)
- parser.add_argument('--html_out_file', required=True)
+ parser.add_argument('--html_in_files', nargs='*', required=True)
+ parser.add_argument('--html_out_files', nargs='*', required=True)
parser.add_argument('--input', required=True)
parser.add_argument('--insert_in_head')
- parser.add_argument('--js_out_file', required=True)
+ parser.add_argument('--js_out_files', nargs='*', required=True)
parser.add_argument('--out_folder', required=True)
args = parser.parse_args(argv)
@@ -218,8 +232,20 @@ def main(argv):
args.input = os.path.normpath(args.input)
args.out_folder = os.path.normpath(args.out_folder)
- _vulcanize(args.input, args)
- _update_dep_file(args.input, args)
+ manifest_out_path = _vulcanize(args.input, args)
+
+ # Prior call to _vulcanize() generated an output manifest file, containing
+ # information about all files that were bundled. Grab it from there.
+ manifest = json.loads(open(manifest_out_path, 'r').read())
+
+ # polymer-bundler reports any missing files in the output manifest, instead of
+ # directly failing. Ensure that no such files were encountered.
+ if '_missing' in manifest:
+ raise Exception(
+ 'polymer-bundler could not find files for the following URLs:\n' +
+ '\n'.join(manifest['_missing']))
+
+ _update_dep_file(args.input, args, manifest)
if __name__ == '__main__':
diff --git a/chromium/chrome/browser/resources/welcome/welcome.html b/chromium/chrome/browser/resources/welcome/welcome.html
index 198ea7df609..b2b6c1135ec 100644
--- a/chromium/chrome/browser/resources/welcome/welcome.html
+++ b/chromium/chrome/browser/resources/welcome/welcome.html
@@ -4,8 +4,9 @@
<meta charset="utf-8">
<title>$i18n{headerText}</title>
- <link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/polymer.html">
+
+ <link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
diff --git a/chromium/chrome/browser/resources/welcome/win10/inline.html b/chromium/chrome/browser/resources/welcome/win10/inline.html
index ff53572fd57..fa5e6acc374 100644
--- a/chromium/chrome/browser/resources/welcome/win10/inline.html
+++ b/chromium/chrome/browser/resources/welcome/win10/inline.html
@@ -4,11 +4,12 @@
<meta charset="utf-8">
<title>$i18n{headerText}</title>
+ <link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/action_link_css.html">
- <link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
diff --git a/chromium/chrome/browser/resources/welcome/win10/sectioned.html b/chromium/chrome/browser/resources/welcome/win10/sectioned.html
index 565c0e724f7..13b7ff6b059 100644
--- a/chromium/chrome/browser/resources/welcome/win10/sectioned.html
+++ b/chromium/chrome/browser/resources/welcome/win10/sectioned.html
@@ -4,9 +4,10 @@
<meta charset="utf-8">
<title>$i18n{headerText}</title>
+ <link rel="import" href="chrome://resources/html/polymer.html">
+
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/html/cr.html">
- <link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
diff --git a/chromium/chrome/browser/safe_browsing/BUILD.gn b/chromium/chrome/browser/safe_browsing/BUILD.gn
index 613ef4d2bb3..385aec6597b 100644
--- a/chromium/chrome/browser/safe_browsing/BUILD.gn
+++ b/chromium/chrome/browser/safe_browsing/BUILD.gn
@@ -65,6 +65,8 @@ static_library("safe_browsing") {
"settings_reset_prompt/settings_reset_prompt_model.h",
"settings_reset_prompt/settings_reset_prompt_prefs_manager.cc",
"settings_reset_prompt/settings_reset_prompt_prefs_manager.h",
+ "settings_reset_prompt/settings_reset_prompt_util_win.cc",
+ "settings_reset_prompt/settings_reset_prompt_util_win.h",
]
}
@@ -112,6 +114,7 @@ static_library("safe_browsing") {
"//components/safe_browsing/password_protection",
"//components/safe_browsing/triggers:triggers",
"//components/safe_browsing_db:metadata_proto",
+ "//components/safe_browsing_db:whitelist_checker_client",
]
if (safe_browsing_mode == 1) {
# "Safe Browsing Full" files in addition to the "basic" ones to use for
@@ -135,14 +138,30 @@ static_library("safe_browsing") {
"client_side_detection_service.h",
"client_side_model_loader.cc",
"client_side_model_loader.h",
- "disk_image_type_sniffer_mac.cc",
- "disk_image_type_sniffer_mac.h",
- "download_feedback.cc",
- "download_feedback.h",
- "download_feedback_service.cc",
- "download_feedback_service.h",
- "download_protection_service.cc",
- "download_protection_service.h",
+ "download_protection/check_client_download_request.cc",
+ "download_protection/check_client_download_request.h",
+ "download_protection/disk_image_type_sniffer_mac.cc",
+ "download_protection/disk_image_type_sniffer_mac.h",
+ "download_protection/download_feedback.cc",
+ "download_protection/download_feedback.h",
+ "download_protection/download_feedback_service.cc",
+ "download_protection/download_feedback_service.h",
+ "download_protection/download_protection_service.cc",
+ "download_protection/download_protection_service.h",
+ "download_protection/download_protection_util.cc",
+ "download_protection/download_protection_util.h",
+ "download_protection/download_url_sb_client.cc",
+ "download_protection/download_url_sb_client.h",
+ "download_protection/path_sanitizer.cc",
+ "download_protection/path_sanitizer.h",
+ "download_protection/ppapi_download_request.cc",
+ "download_protection/ppapi_download_request.h",
+ "download_protection/sandboxed_dmg_analyzer_mac.cc",
+ "download_protection/sandboxed_dmg_analyzer_mac.h",
+ "download_protection/sandboxed_zip_analyzer.cc",
+ "download_protection/sandboxed_zip_analyzer.h",
+ "download_protection/two_phase_uploader.cc",
+ "download_protection/two_phase_uploader.h",
"incident_reporting/binary_integrity_analyzer.cc",
"incident_reporting/binary_integrity_analyzer.h",
"incident_reporting/binary_integrity_analyzer_mac.cc",
@@ -206,8 +225,6 @@ static_library("safe_browsing") {
"incident_reporting/variations_seed_signature_incident.h",
"local_database_manager.cc",
"local_database_manager.h",
- "path_sanitizer.cc",
- "path_sanitizer.h",
"protocol_manager.cc",
"protocol_manager.h",
"protocol_parser.cc",
@@ -220,22 +237,26 @@ static_library("safe_browsing") {
"safe_browsing_store_file.h",
"safe_browsing_util.cc",
"safe_browsing_util.h",
- "sandboxed_dmg_analyzer_mac.cc",
- "sandboxed_dmg_analyzer_mac.h",
- "sandboxed_zip_analyzer.cc",
- "sandboxed_zip_analyzer.h",
"services_delegate_impl.cc",
"services_delegate_impl.h",
"signature_evaluator_mac.h",
"signature_evaluator_mac.mm",
- "two_phase_uploader.cc",
- "two_phase_uploader.h",
+ "trigger_creator.cc",
+ "trigger_creator.h",
"v4_test_utils.cc",
"v4_test_utils.h",
]
deps += [
+ "//components/content_settings/core/browser:browser",
+ "//components/prefs:prefs",
"//components/safe_browsing/common:safe_browsing_prefs",
+ "//components/safe_browsing/triggers:ad_sampler_trigger",
+ "//components/safe_browsing/triggers:trigger_throttler",
+ "//components/safe_browsing/triggers:triggers",
"//components/safe_browsing_db:safe_browsing_db",
+ "//components/security_interstitials/content:security_interstitial_page",
+ "//content/public/browser:browser",
+ "//net:net",
]
if (is_win) {
deps += [ "//chrome/browser/safe_browsing/incident_reporting:state_store_data_proto" ]
@@ -247,7 +268,7 @@ static_library("safe_browsing") {
"services_delegate_stub.cc",
"services_delegate_stub.h",
]
- deps += [ "//components/safe_browsing_db:safe_browsing_db_mobile" ]
+ deps += [ "//components/safe_browsing/db:safe_browsing_mobile" ]
}
}
}
diff --git a/chromium/chrome/browser/search/BUILD.gn b/chromium/chrome/browser/search/BUILD.gn
index 999e4453790..5422a848f65 100644
--- a/chromium/chrome/browser/search/BUILD.gn
+++ b/chromium/chrome/browser/search/BUILD.gn
@@ -2,14 +2,17 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-input_path = "//chrome/browser/resources/local_ntp/local_ntp.js"
-header_path = "$target_gen_dir/local_ntp_js_integrity.h"
+local_ntp_resources = "//chrome/browser/resources/local_ntp"
action("local_ntp_code_generate") {
script = "tools/generate_integrity_header.py"
+ header_path = "$target_gen_dir/local_ntp_js_integrity.h"
+ local_ntp_js = local_ntp_resources + "/local_ntp.js"
+ voice_js = local_ntp_resources + "/voice.js"
inputs = [
- input_path,
+ local_ntp_js,
+ voice_js,
]
outputs = [
@@ -17,8 +20,9 @@ action("local_ntp_code_generate") {
]
args = [
- rebase_path(input_path, root_build_dir),
- rebase_path(header_path, root_build_dir),
+ "--output_path=" + rebase_path(header_path, root_build_dir),
+ rebase_path(local_ntp_js, root_build_dir),
+ rebase_path(voice_js, root_build_dir),
]
}
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_factory.cc b/chromium/chrome/browser/spellchecker/spellcheck_factory.cc
index a86699386bd..9f9eb3bdd04 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_factory.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_factory.cc
@@ -72,7 +72,7 @@ void SpellcheckServiceFactory::RegisterProfilePrefs(
user_prefs->RegisterListPref(spellcheck::prefs::kSpellCheckDictionaries,
base::MakeUnique<base::ListValue>());
// Continue registering kSpellCheckDictionary for preference migration.
- // TODO(estade): IDS_SPELLCHECK_DICTIONARY should be an ASCII string.
+ // TODO(estade): remove: crbug.com/751275
user_prefs->RegisterStringPref(
spellcheck::prefs::kSpellCheckDictionary,
l10n_util::GetStringUTF8(IDS_SPELLCHECK_DICTIONARY));
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
index 2b731b323d5..536f87cc44f 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
@@ -264,7 +264,7 @@ void SpellcheckHunspellDictionary::DownloadDictionary(GURL url) {
destination: GOOGLE_OWNED_SERVICE
}
policy {
- cookies_allowed: false
+ cookies_allowed: NO
setting:
"You can prevent downloading dictionaries by not selecting 'Use "
"this language for spell checking.' in Chrome's settings under "
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn
index 8084f2caeba..d207627330a 100644
--- a/chromium/chrome/browser/ui/BUILD.gn
+++ b/chromium/chrome/browser/ui/BUILD.gn
@@ -78,6 +78,10 @@ split_static_library("ui") {
"blocked_content/blocked_window_params.h",
"blocked_content/popup_blocker_tab_helper.cc",
"blocked_content/popup_blocker_tab_helper.h",
+ "blocked_content/popup_tracker.cc",
+ "blocked_content/popup_tracker.h",
+ "blocked_content/scoped_visibility_tracker.cc",
+ "blocked_content/scoped_visibility_tracker.h",
"bookmarks/bookmark_bar.h",
"bookmarks/bookmark_bar_constants.h",
"bookmarks/bookmark_bar_instructions_delegate.h",
@@ -215,7 +219,9 @@ split_static_library("ui") {
"webui/chrome_web_ui_controller_factory.cc",
"webui/chrome_web_ui_controller_factory.h",
- # TODO(dbeam): why are all these /chromeos/ files on all platforms?
+ # Chrome OS specific files (filtered out by GN on non chromeos platforms)
+ "webui/chromeos/bluetooth_dialog_localized_strings_provider.cc",
+ "webui/chromeos/bluetooth_dialog_localized_strings_provider.h",
"webui/chromeos/choose_mobile_network_ui.cc",
"webui/chromeos/choose_mobile_network_ui.h",
"webui/chromeos/cryptohome_ui.cc",
@@ -234,6 +240,8 @@ split_static_library("ui") {
"webui/chromeos/image_source.h",
"webui/chromeos/keyboard_overlay_ui.cc",
"webui/chromeos/keyboard_overlay_ui.h",
+ "webui/chromeos/login/active_directory_password_change_screen_handler.cc",
+ "webui/chromeos/login/active_directory_password_change_screen_handler.h",
"webui/chromeos/login/app_launch_splash_screen_handler.cc",
"webui/chromeos/login/app_launch_splash_screen_handler.h",
"webui/chromeos/login/arc_kiosk_splash_screen_handler.cc",
@@ -331,8 +339,6 @@ split_static_library("ui") {
"webui/chromeos/slow_trace_ui.h",
"webui/chromeos/slow_ui.cc",
"webui/chromeos/slow_ui.h",
- "webui/chromeos/ui_account_tweaks.cc",
- "webui/chromeos/ui_account_tweaks.h",
"webui/components_ui.cc",
"webui/components_ui.h",
"webui/constrained_web_dialog_ui.cc",
@@ -369,6 +375,8 @@ split_static_library("ui") {
"webui/log_web_ui_url.h",
"webui/media/media_engagement_ui.cc",
"webui/media/media_engagement_ui.h",
+ "webui/memory_internals_ui.cc",
+ "webui/memory_internals_ui.h",
"webui/metrics_handler.cc",
"webui/metrics_handler.h",
"webui/mojo_web_ui_controller.cc",
@@ -388,8 +396,6 @@ split_static_library("ui") {
"webui/password_manager_internals/password_manager_internals_ui.h",
"webui/physical_web/physical_web_ui.cc",
"webui/physical_web/physical_web_ui.h",
- "webui/policy_material_design_ui.cc",
- "webui/policy_material_design_ui.h",
"webui/policy_ui.cc",
"webui/policy_ui.h",
"webui/policy_ui_handler.cc",
@@ -466,9 +472,8 @@ split_static_library("ui") {
"//content/public/browser",
]
deps = [
- # NOTE: New dependencies should generally be added in the OS!="ios"
- # dependencies block below, rather than here.
"//base",
+ "//base/allocator:features",
"//cc/paint",
"//chrome:extra_resources",
"//chrome:resources",
@@ -482,11 +487,12 @@ split_static_library("ui") {
"//chrome/browser/devtools",
"//chrome/browser/engagement:mojo_bindings",
"//chrome/browser/media:mojo_bindings",
+ "//chrome/browser/profiling_host",
"//chrome/browser/safe_browsing",
"//chrome/browser/ui/webui/omnibox:mojo_bindings",
"//chrome/browser/ui/webui/usb_internals:mojo_bindings",
"//chrome/common",
- "//chrome/common:instant_mojom",
+ "//chrome/common:search_mojom",
"//chrome/common/net",
"//chrome/installer/util:with_no_strings",
"//components/about_ui",
@@ -518,13 +524,13 @@ split_static_library("ui") {
"//components/gcm_driver",
"//components/google/core/browser",
"//components/history/content/browser",
+ "//components/history/core/browser",
"//components/image_fetcher/core",
"//components/infobars/core",
"//components/invalidation/impl",
"//components/keyed_service/content",
"//components/keyed_service/core",
"//components/metrics:profiler",
- "//components/mime_util",
"//components/net_log",
"//components/ntp_snippets",
"//components/ntp_tiles",
@@ -549,6 +555,7 @@ split_static_library("ui") {
"//components/renderer_context_menu",
"//components/resources",
"//components/safe_browsing/common:safe_browsing_prefs",
+ "//components/safe_browsing/password_protection",
"//components/safe_browsing/web_ui",
"//components/safe_json",
"//components/search",
@@ -603,6 +610,7 @@ split_static_library("ui") {
"//skia",
"//storage/browser",
"//storage/common",
+ "//third_party/WebKit/common:blink_common",
"//third_party/WebKit/public:features",
"//third_party/WebKit/public:resources",
"//third_party/adobe/flash:flapper_version_h",
@@ -667,8 +675,8 @@ split_static_library("ui") {
"apps/chrome_app_window_client.h",
"apps/directory_access_confirmation_dialog.cc",
"apps/directory_access_confirmation_dialog.h",
- "blocked_content/app_modal_dialog_helper.cc",
- "blocked_content/app_modal_dialog_helper.h",
+ "blocked_content/popunder_preventer.cc",
+ "blocked_content/popunder_preventer.h",
"bluetooth/bluetooth_chooser_controller.cc",
"bluetooth/bluetooth_chooser_controller.h",
"bluetooth/bluetooth_chooser_desktop.cc",
@@ -745,6 +753,7 @@ split_static_library("ui") {
"content_settings/content_setting_image_model.h",
"exclusive_access/exclusive_access_bubble.cc",
"exclusive_access/exclusive_access_bubble.h",
+ "exclusive_access/exclusive_access_bubble_hide_callback.h",
"exclusive_access/exclusive_access_bubble_type.cc",
"exclusive_access/exclusive_access_bubble_type.h",
"exclusive_access/exclusive_access_context.cc",
@@ -763,6 +772,8 @@ split_static_library("ui") {
"fast_unload_controller.h",
"find_bar/find_bar_controller.cc",
"find_bar/find_bar_controller.h",
+ "first_run_bubble_presenter.cc",
+ "first_run_bubble_presenter.h",
"global_error/global_error.cc",
"global_error/global_error.h",
"global_error/global_error_bubble_view_base.h",
@@ -793,6 +804,8 @@ split_static_library("ui") {
"omnibox/clipboard_utils.cc",
"omnibox/clipboard_utils.h",
"overlay/overlay_window.h",
+ "page_info/page_info_dialog.cc",
+ "page_info/page_info_dialog.h",
"page_info/page_info_infobar_delegate.cc",
"page_info/page_info_infobar_delegate.h",
"page_info/permission_menu_model.cc",
@@ -802,8 +815,6 @@ split_static_library("ui") {
"passwords/manage_passwords_icon_view.h",
"passwords/manage_passwords_ui_controller.cc",
"passwords/manage_passwords_ui_controller.h",
- "passwords/manage_passwords_view_utils_desktop.cc",
- "passwords/manage_passwords_view_utils_desktop.h",
"passwords/password_dialog_controller.h",
"passwords/password_dialog_controller_impl.cc",
"passwords/password_dialog_controller_impl.h",
@@ -829,9 +840,9 @@ split_static_library("ui") {
"search/instant_controller.h",
"search/search_delegate.cc",
"search/search_delegate.h",
- "settings_window_manager.cc",
- "settings_window_manager.h",
- "settings_window_manager_observer.h",
+ "settings_window_manager_chromeos.cc",
+ "settings_window_manager_chromeos.h",
+ "settings_window_manager_observer_chromeos.h",
"singleton_tabs.cc",
"singleton_tabs.h",
"startup/automation_infobar_delegate.cc",
@@ -971,6 +982,8 @@ split_static_library("ui") {
"webui/md_feedback/md_feedback_webui_message_handler.h",
"webui/md_history_ui.cc",
"webui/md_history_ui.h",
+ "webui/ntp/app_icon_webui_handler.cc",
+ "webui/ntp/app_icon_webui_handler.h",
"webui/ntp/app_launcher_handler.cc",
"webui/ntp/app_launcher_handler.h",
"webui/ntp/app_resource_cache_factory.cc",
@@ -999,6 +1012,8 @@ split_static_library("ui") {
"webui/settings/appearance_handler.h",
"webui/settings/browser_lifetime_handler.cc",
"webui/settings/browser_lifetime_handler.h",
+ "webui/settings/change_password_handler.cc",
+ "webui/settings/change_password_handler.h",
"webui/settings/chromeos/accessibility_handler.cc",
"webui/settings/chromeos/accessibility_handler.h",
"webui/settings/chromeos/android_apps_handler.cc",
@@ -1027,6 +1042,8 @@ split_static_library("ui") {
"webui/settings/chromeos/google_assistant_handler.h",
"webui/settings/chromeos/internet_handler.cc",
"webui/settings/chromeos/internet_handler.h",
+ "webui/settings/custom_home_pages_table_model.cc",
+ "webui/settings/custom_home_pages_table_model.h",
"webui/settings/downloads_handler.cc",
"webui/settings/downloads_handler.h",
"webui/settings/extension_control_handler.cc",
@@ -1145,8 +1162,6 @@ split_static_library("ui") {
"hung_plugin_tab_helper.h",
"webui/flash_ui.cc",
"webui/flash_ui.h",
- "webui/options/pepper_flash_content_settings_utils.cc",
- "webui/options/pepper_flash_content_settings_utils.h",
]
deps += [ "//ppapi/proxy:ipc" ]
}
@@ -1207,100 +1222,8 @@ split_static_library("ui") {
"webui/chromeos/proxy_settings_ui.h",
"webui/chromeos/user_image_source.cc",
"webui/chromeos/user_image_source.h",
- "webui/help/help_handler.cc",
- "webui/help/help_handler.h",
"webui/help/help_utils_chromeos.cc",
"webui/help/help_utils_chromeos.h",
- "webui/options/autofill_options_handler.cc",
- "webui/options/autofill_options_handler.h",
- "webui/options/automatic_settings_reset_handler.cc",
- "webui/options/automatic_settings_reset_handler.h",
- "webui/options/browser_options_handler.cc",
- "webui/options/browser_options_handler.h",
- "webui/options/chromeos/accounts_options_handler.cc",
- "webui/options/chromeos/accounts_options_handler.h",
- "webui/options/chromeos/bluetooth_options_handler.cc",
- "webui/options/chromeos/bluetooth_options_handler.h",
- "webui/options/chromeos/change_picture_options_handler.cc",
- "webui/options/chromeos/change_picture_options_handler.h",
- "webui/options/chromeos/core_chromeos_options_handler.cc",
- "webui/options/chromeos/core_chromeos_options_handler.h",
- "webui/options/chromeos/cros_language_options_handler.cc",
- "webui/options/chromeos/cros_language_options_handler.h",
- "webui/options/chromeos/date_time_options_handler.cc",
- "webui/options/chromeos/date_time_options_handler.h",
- "webui/options/chromeos/display_options_handler.cc",
- "webui/options/chromeos/display_options_handler.h",
- "webui/options/chromeos/display_overscan_handler.cc",
- "webui/options/chromeos/display_overscan_handler.h",
- "webui/options/chromeos/internet_options_handler.cc",
- "webui/options/chromeos/internet_options_handler.h",
- "webui/options/chromeos/internet_options_handler_strings.cc",
- "webui/options/chromeos/internet_options_handler_strings.h",
- "webui/options/chromeos/keyboard_handler.cc",
- "webui/options/chromeos/keyboard_handler.h",
- "webui/options/chromeos/options_stylus_handler.cc",
- "webui/options/chromeos/options_stylus_handler.h",
- "webui/options/chromeos/pointer_handler.cc",
- "webui/options/chromeos/pointer_handler.h",
- "webui/options/chromeos/power_handler.cc",
- "webui/options/chromeos/power_handler.h",
- "webui/options/chromeos/proxy_handler.cc",
- "webui/options/chromeos/proxy_handler.h",
- "webui/options/chromeos/stats_options_handler.cc",
- "webui/options/chromeos/stats_options_handler.h",
- "webui/options/chromeos/storage_manager_handler.cc",
- "webui/options/chromeos/storage_manager_handler.h",
- "webui/options/clear_browser_data_handler.cc",
- "webui/options/clear_browser_data_handler.h",
- "webui/options/content_settings_handler.cc",
- "webui/options/content_settings_handler.h",
- "webui/options/cookies_view_handler.cc",
- "webui/options/cookies_view_handler.h",
- "webui/options/core_options_handler.cc",
- "webui/options/core_options_handler.h",
- "webui/options/create_profile_handler.cc",
- "webui/options/create_profile_handler.h",
- "webui/options/easy_unlock_handler.cc",
- "webui/options/easy_unlock_handler.h",
- "webui/options/font_settings_handler.cc",
- "webui/options/font_settings_handler.h",
- "webui/options/handler_options_handler.cc",
- "webui/options/handler_options_handler.h",
- "webui/options/help_overlay_handler.cc",
- "webui/options/help_overlay_handler.h",
- "webui/options/home_page_overlay_handler.cc",
- "webui/options/home_page_overlay_handler.h",
- "webui/options/import_data_handler.cc",
- "webui/options/import_data_handler.h",
- "webui/options/language_dictionary_overlay_handler.cc",
- "webui/options/language_dictionary_overlay_handler.h",
- "webui/options/language_options_handler.cc",
- "webui/options/language_options_handler.h",
- "webui/options/language_options_handler_common.cc",
- "webui/options/language_options_handler_common.h",
- "webui/options/manage_profile_handler.cc",
- "webui/options/manage_profile_handler.h",
- "webui/options/media_devices_selection_handler.cc",
- "webui/options/media_devices_selection_handler.h",
- "webui/options/options_ui.cc",
- "webui/options/options_ui.h",
- "webui/options/password_manager_handler.cc",
- "webui/options/password_manager_handler.h",
- "webui/options/reset_profile_settings_handler.cc",
- "webui/options/reset_profile_settings_handler.h",
- "webui/options/search_engine_manager_handler.cc",
- "webui/options/search_engine_manager_handler.h",
- "webui/options/startup_pages_handler.cc",
- "webui/options/startup_pages_handler.h",
- "webui/options/supervised_user_create_confirm_handler.cc",
- "webui/options/supervised_user_create_confirm_handler.h",
- "webui/options/supervised_user_import_handler.cc",
- "webui/options/supervised_user_import_handler.h",
- "webui/options/supervised_user_learn_more_handler.cc",
- "webui/options/supervised_user_learn_more_handler.h",
- "webui/options/sync_setup_handler.cc",
- "webui/options/sync_setup_handler.h",
]
deps += [
"//chrome/browser/chromeos",
@@ -1375,8 +1298,6 @@ split_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/desktop_shell_launcher_context_menu.cc",
- "ash/launcher/desktop_shell_launcher_context_menu.h",
"ash/launcher/extension_app_window_launcher_controller.cc",
"ash/launcher/extension_app_window_launcher_controller.h",
"ash/launcher/extension_app_window_launcher_item_controller.cc",
@@ -1424,8 +1345,6 @@ split_static_library("ui") {
"ash/session_util.cc",
"ash/session_util.h",
"ash/sort_windows_by_z_index.cc",
- "ash/system_tray_delegate_chromeos.cc",
- "ash/system_tray_delegate_chromeos.h",
"ash/volume_controller.cc",
"ash/volume_controller.h",
"ash/vpn_list_forwarder.cc",
@@ -1532,8 +1451,13 @@ split_static_library("ui") {
"views/extensions/chooser_dialog_view.h",
"views/extensions/extension_install_dialog_view.cc",
"views/extensions/extension_install_dialog_view.h",
+ "views/extensions/extension_installed_bubble_view.cc",
+ "views/extensions/extension_installed_bubble_view.h",
"views/extensions/extension_keybinding_registry_views.cc",
"views/extensions/extension_keybinding_registry_views.h",
+ "views/extensions/extension_uninstall_dialog_view.cc",
+ "views/first_run_bubble.cc",
+ "views/first_run_bubble.h",
"views/frame/native_widget_mac_frameless_nswindow.h",
"views/frame/native_widget_mac_frameless_nswindow.mm",
"views/fullscreen_control/fullscreen_control_host.cc",
@@ -1632,6 +1556,8 @@ split_static_library("ui") {
"views/permission_bubble/chooser_bubble_ui.h",
"views/permission_bubble/permission_prompt_impl.cc",
"views/permission_bubble/permission_prompt_impl.h",
+ "views/safe_browsing/password_reuse_modal_warning_dialog.cc",
+ "views/safe_browsing/password_reuse_modal_warning_dialog.h",
"views/simple_message_box_views.cc",
"views/simple_message_box_views.h",
"views/subtle_notification_view.cc",
@@ -1714,10 +1640,8 @@ split_static_library("ui") {
"views/extensions/extension_dialog.h",
"views/extensions/extension_dialog_observer.cc",
"views/extensions/extension_dialog_observer.h",
- "views/extensions/extension_installed_bubble_view.cc",
"views/extensions/extension_popup.cc",
"views/extensions/extension_popup.h",
- "views/extensions/extension_uninstall_dialog_view.cc",
"views/extensions/extension_view_views.cc",
"views/extensions/extension_view_views.h",
"views/extensions/media_galleries_dialog_views.cc",
@@ -1794,12 +1718,18 @@ split_static_library("ui") {
"views/dropdown_bar_host.cc",
"views/dropdown_bar_host.h",
"views/dropdown_bar_host_delegate.h",
+ "views/feature_promos/bookmark_promo_bubble_view.cc",
+ "views/feature_promos/bookmark_promo_bubble_view.h",
+ "views/feature_promos/feature_promo_bubble_view.cc",
+ "views/feature_promos/feature_promo_bubble_view.h",
+ "views/feature_promos/incognito_window_promo_bubble_view.cc",
+ "views/feature_promos/incognito_window_promo_bubble_view.h",
+ "views/feature_promos/new_tab_promo_bubble_view.cc",
+ "views/feature_promos/new_tab_promo_bubble_view.h",
"views/find_bar_host.cc",
"views/find_bar_host.h",
"views/find_bar_view.cc",
"views/find_bar_view.h",
- "views/first_run_bubble.cc",
- "views/first_run_bubble.h",
"views/frame/browser_command_handler_linux.cc",
"views/frame/browser_command_handler_linux.h",
"views/frame/browser_frame.cc",
@@ -1901,6 +1831,8 @@ split_static_library("ui") {
"views/profiles/user_manager_view.h",
"views/proximity_auth/proximity_auth_error_bubble_view.cc",
"views/proximity_auth/proximity_auth_error_bubble_view.h",
+ "views/sad_tab_view.cc",
+ "views/sad_tab_view.h",
"views/session_crashed_bubble_view.cc",
"views/session_crashed_bubble_view.h",
"views/ssl_client_certificate_selector.cc",
@@ -1927,8 +1859,6 @@ split_static_library("ui") {
"views/tabs/browser_tab_strip_controller.h",
"views/tabs/new_tab_button.cc",
"views/tabs/new_tab_button.h",
- "views/tabs/new_tab_promo.cc",
- "views/tabs/new_tab_promo.h",
"views/tabs/stacked_tab_strip_layout.cc",
"views/tabs/stacked_tab_strip_layout.h",
"views/tabs/tab.cc",
@@ -1985,8 +1915,8 @@ split_static_library("ui") {
if (is_win) {
sources += [
- "views/try_chrome_dialog_view.cc",
- "views/try_chrome_dialog_view.h",
+ "views/try_chrome_dialog.cc",
+ "views/try_chrome_dialog.h",
]
}
@@ -2133,12 +2063,6 @@ split_static_library("ui") {
"webui/signin/signin_dice_internals_ui.h",
]
}
- if (enable_oop_heap_profiling) {
- sources += [
- "webui/memory_internals_ui.cc",
- "webui/memory_internals_ui.h",
- ]
- }
if (is_mac && !mac_views_browser) {
sources -= [
# This is not explicitly excluded in GYP, but I think the static
@@ -2206,8 +2130,6 @@ split_static_library("ui") {
"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/sad_tab_view.cc",
- "views/sad_tab_view.h",
"views/tab_contents/chrome_web_contents_view_delegate_views.cc",
"views/tab_contents/chrome_web_contents_view_delegate_views.h",
"views/theme_profile_key.cc",
@@ -2239,15 +2161,11 @@ split_static_library("ui") {
"crypto_module_delegate_nss.h",
"crypto_module_password_dialog_nss.cc",
"crypto_module_password_dialog_nss.h",
- "webui/settings/certificates_handler.cc",
- "webui/settings/certificates_handler.h",
+ "webui/certificate_manager_localized_strings_provider.cc",
+ "webui/certificate_manager_localized_strings_provider.h",
+ "webui/certificates_handler.cc",
+ "webui/certificates_handler.h",
]
- if (is_chromeos) {
- sources += [
- "webui/options/certificate_manager_handler.cc",
- "webui/options/certificate_manager_handler.h",
- ]
- }
}
if (is_mac || is_win) {
sources += [
@@ -2272,6 +2190,12 @@ split_static_library("ui") {
"webui/print_preview/sticky_settings.h",
]
+ if (enable_service_discovery) {
+ sources += [
+ "webui/print_preview/privet_printer_handler.cc",
+ "webui/print_preview/privet_printer_handler.h",
+ ]
+ }
if (is_chromeos) {
sources += [ "webui/print_preview/printer_backend_proxy_chromeos.cc" ]
} else {
@@ -2462,10 +2386,6 @@ split_static_library("ui") {
"cocoa/bookmarks/bookmark_menu_cocoa_controller.mm",
"cocoa/browser_window_command_handler.h",
"cocoa/browser_window_command_handler.mm",
- "cocoa/bubble_anchor_helper.h",
- "cocoa/bubble_anchor_helper.mm",
- "cocoa/bubble_anchor_helper_views.h",
- "cocoa/bubble_anchor_helper_views.mm",
"cocoa/chrome_command_dispatcher_delegate.h",
"cocoa/chrome_command_dispatcher_delegate.mm",
"cocoa/chrome_style.cc",
@@ -2502,6 +2422,8 @@ split_static_library("ui") {
"cocoa/l10n_util.mm",
"cocoa/last_active_browser_cocoa.cc",
"cocoa/last_active_browser_cocoa.h",
+ "cocoa/md_hover_button.h",
+ "cocoa/md_hover_button.mm",
"cocoa/media_picker/desktop_media_picker_bridge.h",
"cocoa/media_picker/desktop_media_picker_bridge.mm",
"cocoa/media_picker/desktop_media_picker_cocoa.h",
@@ -2526,9 +2448,6 @@ split_static_library("ui") {
"cocoa/status_icons/status_tray_mac.mm",
"cocoa/tab_contents/chrome_web_contents_view_delegate_mac.h",
"cocoa/tab_contents/chrome_web_contents_view_delegate_mac.mm",
- "cocoa/tab_contents/sad_tab_mac.mm",
- "cocoa/tab_contents/sad_tab_view_cocoa.h",
- "cocoa/tab_contents/sad_tab_view_cocoa.mm",
"cocoa/tab_contents/web_drag_bookmark_handler_mac.h",
"cocoa/tab_contents/web_drag_bookmark_handler_mac.mm",
"cocoa/ui_localizer.h",
@@ -2565,6 +2484,8 @@ split_static_library("ui") {
"views/frame/browser_non_client_frame_view_mac.mm",
"views/frame/native_browser_frame_factory_mac.mm",
"views/infobars/legacy_infobars_mac.cc",
+ "views/tab_contents/chrome_web_contents_view_delegate_views_mac.h",
+ "views/tab_contents/chrome_web_contents_view_delegate_views_mac.mm",
"views/tabs/window_finder_mac.mm",
]
deps += [ "//extensions/components/native_app_window" ]
@@ -2607,8 +2528,6 @@ split_static_library("ui") {
"cocoa/autofill/card_unmask_prompt_view_bridge.h",
"cocoa/autofill/card_unmask_prompt_view_bridge.mm",
"cocoa/autofill/card_unmask_prompt_view_views.mm",
- "cocoa/autofill/down_arrow_popup_menu_cell.h",
- "cocoa/autofill/down_arrow_popup_menu_cell.mm",
"cocoa/autofill/layout_view.h",
"cocoa/autofill/layout_view.mm",
"cocoa/autofill/password_generation_popup_view_bridge.h",
@@ -2689,6 +2608,10 @@ split_static_library("ui") {
"cocoa/browser_window_touch_bar.mm",
"cocoa/browser_window_utils.h",
"cocoa/browser_window_utils.mm",
+ "cocoa/bubble_anchor_helper.h",
+ "cocoa/bubble_anchor_helper.mm",
+ "cocoa/bubble_anchor_helper_views.h",
+ "cocoa/bubble_anchor_helper_views.mm",
"cocoa/bubble_anchor_util_views_mac.mm",
"cocoa/bubble_combobox.h",
"cocoa/bubble_combobox.mm",
@@ -2744,8 +2667,6 @@ split_static_library("ui") {
"cocoa/content_settings/cookies_tree_controller_bridge.h",
"cocoa/content_settings/cookies_tree_controller_bridge.mm",
"cocoa/create_native_web_modal_manager_cocoa.mm",
- "cocoa/custom_frame_view.h",
- "cocoa/custom_frame_view.mm",
"cocoa/dev_tools_controller.h",
"cocoa/dev_tools_controller.mm",
"cocoa/device_chooser_content_view_cocoa.h",
@@ -2838,8 +2759,6 @@ split_static_library("ui") {
"cocoa/floating_bar_backing_view.mm",
"cocoa/framed_browser_window.h",
"cocoa/framed_browser_window.mm",
- "cocoa/full_size_content_window.h",
- "cocoa/full_size_content_window.mm",
"cocoa/fullscreen/fullscreen_menubar_tracker.h",
"cocoa/fullscreen/fullscreen_menubar_tracker.mm",
"cocoa/fullscreen/fullscreen_toolbar_animation_controller.h",
@@ -2854,6 +2773,8 @@ split_static_library("ui") {
"cocoa/fullscreen/immersive_fullscreen_controller.mm",
"cocoa/fullscreen_low_power_coordinator.h",
"cocoa/fullscreen_low_power_coordinator.mm",
+ "cocoa/fullscreen_placeholder_view.h",
+ "cocoa/fullscreen_placeholder_view.mm",
"cocoa/fullscreen_window.h",
"cocoa/fullscreen_window.mm",
"cocoa/global_error_bubble_controller.h",
@@ -2861,6 +2782,8 @@ split_static_library("ui") {
"cocoa/global_error_bubble_controller_views.mm",
"cocoa/gradient_button_cell.h",
"cocoa/gradient_button_cell.mm",
+ "cocoa/harmony_button.h",
+ "cocoa/harmony_button.mm",
"cocoa/has_weak_browser_pointer.h",
"cocoa/hover_close_button.h",
"cocoa/hover_close_button.mm",
@@ -2942,6 +2865,8 @@ split_static_library("ui") {
"cocoa/multi_key_equivalent_button.mm",
"cocoa/new_tab_button.h",
"cocoa/new_tab_button.mm",
+ "cocoa/nsview_additions.h",
+ "cocoa/nsview_additions.mm",
"cocoa/omnibox/omnibox_popup_cell.h",
"cocoa/omnibox/omnibox_popup_cell.mm",
"cocoa/omnibox/omnibox_popup_matrix.h",
@@ -3036,6 +2961,8 @@ split_static_library("ui") {
"cocoa/restart_browser.mm",
"cocoa/screen_capture_notification_ui_cocoa.h",
"cocoa/screen_capture_notification_ui_cocoa.mm",
+ "cocoa/separate_fullscreen_window.h",
+ "cocoa/separate_fullscreen_window.mm",
"cocoa/session_crashed_bubble.mm",
"cocoa/simple_message_box_bridge_views.mm",
"cocoa/simple_message_box_cocoa.h",
@@ -3060,6 +2987,9 @@ split_static_library("ui") {
"cocoa/tab_contents/favicon_util_mac.mm",
"cocoa/tab_contents/overlayable_contents_controller.h",
"cocoa/tab_contents/overlayable_contents_controller.mm",
+ "cocoa/tab_contents/sad_tab_mac.mm",
+ "cocoa/tab_contents/sad_tab_view_cocoa.h",
+ "cocoa/tab_contents/sad_tab_view_cocoa.mm",
"cocoa/tab_contents/tab_contents_controller.h",
"cocoa/tab_contents/tab_contents_controller.mm",
"cocoa/tab_dialogs_cocoa.h",
@@ -3068,6 +2998,8 @@ split_static_library("ui") {
"cocoa/tab_dialogs_views_mac.mm",
"cocoa/tab_modal_confirm_dialog_mac.h",
"cocoa/tab_modal_confirm_dialog_mac.mm",
+ "cocoa/tabbed_browser_window.h",
+ "cocoa/tabbed_browser_window.mm",
"cocoa/tabs/alert_indicator_button_cocoa.h",
"cocoa/tabs/alert_indicator_button_cocoa.mm",
"cocoa/tabs/tab_controller.h",
@@ -3548,13 +3480,6 @@ split_static_library("ui") {
"webui/extensions/extension_icon_source.h",
]
}
- if (enable_google_now && !is_android) {
- sources += [
- # These are non-Android because Android excludes all of options.
- "webui/options/geolocation_options_handler.cc",
- "webui/options/geolocation_options_handler.h",
- ]
- }
if (!is_android) {
sources += [
"toolbar/media_router_action.cc",
diff --git a/chromium/chrome/browser/ui/cocoa/notifications/BUILD.gn b/chromium/chrome/browser/ui/cocoa/notifications/BUILD.gn
index 4ea320fcae0..f55cf0c8b23 100644
--- a/chromium/chrome/browser/ui/cocoa/notifications/BUILD.gn
+++ b/chromium/chrome/browser/ui/cocoa/notifications/BUILD.gn
@@ -37,10 +37,11 @@ mac_app_bundle("alert_notification_xpc_service") {
if (is_component_build) {
ldflags += [
# The XPC service is in Chromium.app/Contents/Versions/X/Chromium \
- # Framework.framework/XPCServices/AlertNotificationService.xpc/\
- # Contents/MacOS/ so set rpath up to the base.
+ # Framework.framework/Versions/A/XPCServices/ \
+ # AlertNotificationService.xpc/Contents/MacOS/
+ # so set rpath up to the base.
"-rpath",
- "@loader_path/../../../../../../../../../",
+ "@loader_path/../../../../../../../../../../../",
]
}
}
diff --git a/chromium/chrome/browser/ui/libgtkui/BUILD.gn b/chromium/chrome/browser/ui/libgtkui/BUILD.gn
index e24526e1dc1..33b4f820bb4 100644
--- a/chromium/chrome/browser/ui/libgtkui/BUILD.gn
+++ b/chromium/chrome/browser/ui/libgtkui/BUILD.gn
@@ -47,6 +47,7 @@ template("libgtkui") {
"libgtkui_export.h",
"menu_util.cc",
"menu_util.h",
+ "nav_button_layout_manager.h",
"print_dialog_gtk.cc",
"print_dialog_gtk.h",
"printing_gtk_util.cc",
@@ -68,8 +69,8 @@ template("libgtkui") {
if (use_gconf) {
sources += [
- "gconf_listener.cc",
- "gconf_listener.h",
+ "nav_button_layout_manager_gconf.cc",
+ "nav_button_layout_manager_gconf.h",
]
configs += [ "//build/config/linux/gconf" ]
}
@@ -127,6 +128,10 @@ if (use_gtk3) {
sources = [
"native_theme_gtk3.cc",
"native_theme_gtk3.h",
+ "nav_button_layout_manager_gtk3.cc",
+ "nav_button_layout_manager_gtk3.h",
+ "nav_button_provider_gtk3.cc",
+ "nav_button_provider_gtk3.h",
]
deps = [
"//build/config/linux/gtk3",
diff --git a/chromium/chrome/browser/ui/webui/OWNERS b/chromium/chrome/browser/ui/webui/OWNERS
index 909e06d2304..b120d04327c 100644
--- a/chromium/chrome/browser/ui/webui/OWNERS
+++ b/chromium/chrome/browser/ui/webui/OWNERS
@@ -1,5 +1,8 @@
file://ui/webui/PLATFORM_OWNERS
+# Maintaining ownership from this file's original Chrome OS location.
+per-file device_log_ui*=stevenjb@chromium.org
+
per-file devtools_ui*=dgozman@chromium.org
per-file devtools_ui*=pfeldman@chromium.org
per-file inspect_ui*=dgozman@chromium.org
@@ -8,13 +11,14 @@ per-file inspect_ui*=pfeldman@chromium.org
per-file md_history_ui*=calamity@chromium.org
per-file md_history_ui*=tsergeant@chromium.org
+per-file net_export_ui.*=file://net/OWNERS
+
+per-file ntp_tiles_internals_ui.*=file://components/ntp_tiles/OWNERS
+
per-file signin_internals_ui*=achuith@chromium.org
per-file snippets_internals*=file://components/ntp_snippets/OWNERS
-per-file ntp_tiles_internals_ui.*=file://components/ntp_tiles/OWNERS
-per-file net_export_ui.*=file://net/OWNERS
-# Maintaining ownership from this file's original Chrome OS location.
-per-file device_log_ui*=stevenjb@chromium.org
+per-file sync_internals*=file://components/sync/OWNERS
# COMPONENT: UI>Browser>WebUI
diff --git a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc
index e003c093f57..b7ea9d79d7d 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc
+++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc
@@ -139,15 +139,11 @@ void AppLauncherLoginHandler::HandleShowSyncLoginUI(
RecordInHistogram(NTP_SIGN_IN_PROMO_CLICKED);
}
-void AppLauncherLoginHandler::RecordInHistogram(int type) {
- // Invalid type to record.
- if (type < NTP_SIGN_IN_PROMO_VIEWED ||
- type > NTP_SIGN_IN_PROMO_CLICKED) {
- NOTREACHED();
- } else {
- UMA_HISTOGRAM_ENUMERATION("SyncPromo.NTPPromo", type,
- NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY);
- }
+void AppLauncherLoginHandler::RecordInHistogram(NTPSignInPromoBuckets type) {
+ DCHECK(type >= NTP_SIGN_IN_PROMO_VIEWED &&
+ type < NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY);
+ UMA_HISTOGRAM_ENUMERATION("SyncPromo.NTPPromo", type,
+ NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY);
}
void AppLauncherLoginHandler::HandleLoginMessageSeen(
diff --git a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.h b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.h
index f678091feec..e99e4916175 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.h
+++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.h
@@ -54,7 +54,7 @@ class AppLauncherLoginHandler : public content::WebUIMessageHandler {
void HandleShowSyncLoginUI(const base::ListValue* args);
// Records actions in SyncPromo.NTPPromo histogram.
- void RecordInHistogram(int type);
+ void RecordInHistogram(NTPSignInPromoBuckets type);
// Called from JS when the sync promo NTP bubble has been displayed. |args| is
// the list of arguments passed from JS and should be an empty list.
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 62ac8ab3c5b..e5d3e53d535 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
+++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
@@ -12,6 +12,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/app_launcher_login_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
+#include "chrome/browser/ui/webui/ntp/app_icon_webui_handler.h"
#include "chrome/browser/ui/webui/ntp/app_launcher_handler.h"
#include "chrome/browser/ui/webui/ntp/app_resource_cache_factory.h"
#include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
@@ -46,6 +47,7 @@ AppLauncherPageUI::AppLauncherPageUI(content::WebUI* web_ui)
DCHECK(service);
web_ui->AddMessageHandler(base::MakeUnique<AppLauncherHandler>(service));
web_ui->AddMessageHandler(base::MakeUnique<CoreAppLauncherHandler>());
+ web_ui->AddMessageHandler(base::MakeUnique<AppIconWebUIHandler>());
web_ui->AddMessageHandler(base::MakeUnique<MetricsHandler>());
}
diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc
index 3aea7513220..c5cc78e59b3 100644
--- a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc
+++ b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc
@@ -13,13 +13,16 @@
#include "base/i18n/rtl.h"
#include "base/i18n/time_formatting.h"
#include "base/logging.h"
-#include "base/strings/string16.h"
+#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
+#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/favicon/large_icon_service_factory.h"
+#include "chrome/browser/history/history_service_factory.h"
+#include "chrome/browser/history/history_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/browser_finder.h"
@@ -27,11 +30,14 @@
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/features.h"
+#include "chrome/common/pref_names.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_utils.h"
#include "components/browser_sync/profile_sync_service.h"
#include "components/favicon/core/fallback_url_util.h"
#include "components/favicon/core/large_icon_service.h"
+#include "components/keyed_service/core/service_access_type.h"
+#include "components/prefs/pref_service.h"
#include "components/query_parser/snippet.h"
#include "components/strings/grit/components_strings.h"
#include "components/sync/device_info/device_info.h"
@@ -39,7 +45,6 @@
#include "components/url_formatter/url_formatter.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui.h"
-#include "extensions/features/features.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/time_format.h"
@@ -51,6 +56,10 @@
#endif
using bookmarks::BookmarkModel;
+using history::BrowsingHistoryService;
+using history::HistoryService;
+using history::WebHistoryService;
+using syncer::SyncService;
namespace {
@@ -59,23 +68,6 @@ static const char kDeviceTypeLaptop[] = "laptop";
static const char kDeviceTypePhone[] = "phone";
static const char kDeviceTypeTablet[] = "tablet";
-// Returns a localized version of |visit_time| including a relative
-// indicator (e.g. today, yesterday).
-base::string16 GetRelativeDateLocalized(base::Clock* clock,
- const base::Time& visit_time) {
- base::Time midnight = clock->Now().LocalMidnight();
- base::string16 date_str = ui::TimeFormat::RelativeDate(visit_time, &midnight);
- if (date_str.empty()) {
- date_str = base::TimeFormatFriendlyDate(visit_time);
- } else {
- date_str = l10n_util::GetStringFUTF16(
- IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
- date_str,
- base::TimeFormatFriendlyDate(visit_time));
- }
- return date_str;
-}
-
// Gets the name and type of a device for the given sync client ID.
// |name| and |type| are out parameters.
void GetDeviceNameAndType(const browser_sync::ProfileSyncService* sync_service,
@@ -110,15 +102,16 @@ void GetDeviceNameAndType(const browser_sync::ProfileSyncService* sync_service,
}
// Formats |entry|'s URL and title and adds them to |result|.
-void SetHistoryEntryUrlAndTitle(BrowsingHistoryService::HistoryEntry* entry,
- base::DictionaryValue* result) {
- result->SetString("url", entry->url.spec());
+void SetHistoryEntryUrlAndTitle(
+ const BrowsingHistoryService::HistoryEntry& entry,
+ base::DictionaryValue* result) {
+ result->SetString("url", entry.url.spec());
bool using_url_as_the_title = false;
- base::string16 title_to_set(entry->title);
- if (entry->title.empty()) {
+ base::string16 title_to_set(entry.title);
+ if (entry.title.empty()) {
using_url_as_the_title = true;
- title_to_set = base::UTF8ToUTF16(entry->url.spec());
+ title_to_set = base::UTF8ToUTF16(entry.url.spec());
}
// Since the title can contain BiDi text, we need to mark the text as either
@@ -142,18 +135,19 @@ void SetHistoryEntryUrlAndTitle(BrowsingHistoryService::HistoryEntry* entry,
// Converts |entry| to a DictionaryValue to be owned by the caller.
std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
- BrowsingHistoryService::HistoryEntry* entry,
+ const BrowsingHistoryService::HistoryEntry& entry,
BookmarkModel* bookmark_model,
SupervisedUserService* supervised_user_service,
- const browser_sync::ProfileSyncService* sync_service) {
+ const browser_sync::ProfileSyncService* sync_service,
+ base::Clock* clock) {
std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue());
SetHistoryEntryUrlAndTitle(entry, result.get());
- base::string16 domain = url_formatter::IDNToUnicode(entry->url.host());
+ base::string16 domain = url_formatter::IDNToUnicode(entry.url.host());
// When the domain is empty, use the scheme instead. This allows for a
// sensible treatment of e.g. file: URLs when group by domain is on.
if (domain.empty())
- domain = base::UTF8ToUTF16(entry->url.scheme() + ":");
+ domain = base::UTF8ToUTF16(entry.url.scheme() + ":");
// The items which are to be written into result are also described in
// chrome/browser/resources/history/history.js in @typedef for
@@ -163,21 +157,21 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
result->SetString(
"fallbackFaviconText",
- base::UTF16ToASCII(favicon::GetFallbackIconText(entry->url)));
+ base::UTF16ToASCII(favicon::GetFallbackIconText(entry.url)));
- result->SetDouble("time", entry->time.ToJsTime());
+ result->SetDouble("time", entry.time.ToJsTime());
// Pass the timestamps in a list.
std::unique_ptr<base::ListValue> timestamps(new base::ListValue);
- for (std::set<int64_t>::const_iterator it = entry->all_timestamps.begin();
- it != entry->all_timestamps.end(); ++it) {
- timestamps->AppendDouble(base::Time::FromInternalValue(*it).ToJsTime());
+ for (int64_t timestamp : entry.all_timestamps) {
+ timestamps->AppendDouble(
+ base::Time::FromInternalValue(timestamp).ToJsTime());
}
result->Set("allTimestamps", std::move(timestamps));
// Always pass the short date since it is needed both in the search and in
// the monthly view.
- result->SetString("dateShort", base::TimeFormatShortDate(entry->time));
+ result->SetString("dateShort", base::TimeFormatShortDate(entry.time));
base::string16 snippet_string;
base::string16 date_relative_day;
@@ -188,28 +182,27 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
// Only pass in the strings we need (search results need a shortdate
// and snippet, browse results need day and time information). Makes sure that
// values of result are never undefined
- if (entry->is_search_result) {
- snippet_string = entry->snippet;
+ if (entry.is_search_result) {
+ snippet_string = entry.snippet;
} else {
- base::Time midnight = entry->clock->Now().LocalMidnight();
- base::string16 date_str = ui::TimeFormat::RelativeDate(entry->time,
- &midnight);
+ base::Time midnight = clock->Now().LocalMidnight();
+ base::string16 date_str =
+ ui::TimeFormat::RelativeDate(entry.time, &midnight);
if (date_str.empty()) {
- date_str = base::TimeFormatFriendlyDate(entry->time);
+ date_str = base::TimeFormatFriendlyDate(entry.time);
} else {
date_str = l10n_util::GetStringFUTF16(
- IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
- date_str,
- base::TimeFormatFriendlyDate(entry->time));
+ IDS_HISTORY_DATE_WITH_RELATIVE_TIME, date_str,
+ base::TimeFormatFriendlyDate(entry.time));
}
date_relative_day = date_str;
- date_time_of_day = base::TimeFormatTimeOfDay(entry->time);
+ date_time_of_day = base::TimeFormatTimeOfDay(entry.time);
}
std::string device_name;
std::string device_type;
- if (!entry->client_id.empty())
- GetDeviceNameAndType(sync_service, entry->client_id, &device_name,
+ if (!entry.client_id.empty())
+ GetDeviceNameAndType(sync_service, entry.client_id, &device_name,
&device_type);
result->SetString("deviceName", device_name);
result->SetString("deviceType", device_type);
@@ -219,8 +212,8 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
const SupervisedUserURLFilter* url_filter =
supervised_user_service->GetURLFilter();
int filtering_behavior =
- url_filter->GetFilteringBehaviorForURL(entry->url.GetWithEmptyPath());
- is_blocked_visit = entry->blocked_visit;
+ url_filter->GetFilteringBehaviorForURL(entry.url.GetWithEmptyPath());
+ is_blocked_visit = entry.blocked_visit;
host_filtering_behavior = filtering_behavior;
}
#endif
@@ -228,7 +221,7 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
result->SetString("dateTimeOfDay", date_time_of_day);
result->SetString("dateRelativeDay", date_relative_day);
result->SetString("snippet", snippet_string);
- result->SetBoolean("starred", bookmark_model->IsBookmarked(entry->url));
+ result->SetBoolean("starred", bookmark_model->IsBookmarked(entry.url));
result->SetInteger("hostFilteringBehavior", host_filtering_behavior);
result->SetBoolean("blockedVisit", is_blocked_visit);
@@ -238,23 +231,29 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
} // namespace
BrowsingHistoryHandler::BrowsingHistoryHandler()
- : clock_(new base::DefaultClock()),
- browsing_history_service_(nullptr) {}
+ : clock_(new base::DefaultClock()), browsing_history_service_(nullptr) {}
-BrowsingHistoryHandler::~BrowsingHistoryHandler() {
-}
+BrowsingHistoryHandler::~BrowsingHistoryHandler() {}
void BrowsingHistoryHandler::RegisterMessages() {
+ Profile* profile = GetProfile();
+ HistoryService* local_history = HistoryServiceFactory::GetForProfile(
+ profile, ServiceAccessType::EXPLICIT_ACCESS);
+ SyncService* sync_service =
+ ProfileSyncServiceFactory::GetSyncServiceForBrowserContext(profile);
browsing_history_service_ = base::MakeUnique<BrowsingHistoryService>(
- Profile::FromWebUI(web_ui()), this);
+ this, local_history, sync_service);
// Create our favicon data source.
- Profile* profile = Profile::FromWebUI(web_ui());
content::URLDataSource::Add(profile, new FaviconSource(profile));
web_ui()->RegisterMessageCallback("queryHistory",
base::Bind(&BrowsingHistoryHandler::HandleQueryHistory,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "queryHistoryContinuation",
+ base::Bind(&BrowsingHistoryHandler::HandleQueryHistoryContinuation,
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback("removeVisits",
base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits,
base::Unretained(this)));
@@ -267,25 +266,16 @@ void BrowsingHistoryHandler::RegisterMessages() {
}
void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) {
- history::QueryOptions options;
+ query_history_continuation_.Reset();
- // Parse the arguments from JavaScript. There are five required arguments:
+ // Parse the arguments from JavaScript. There are two required arguments:
// - the text to search for (may be empty)
- // - the end time for the query. Only results older than this time will be
- // returned.
// - the maximum number of results to return (may be 0, meaning that there
// is no maximum).
base::string16 search_text = ExtractStringValue(args);
- double end_time;
- if (!args->GetDouble(1, &end_time)) {
- NOTREACHED() << "Failed to convert argument 1. ";
- return;
- }
- if (end_time)
- options.end_time = base::Time::FromJsTime(end_time);
-
- if (!args->GetInteger(2, &options.max_count)) {
+ history::QueryOptions options;
+ if (!args->GetInteger(1, &options.max_count)) {
NOTREACHED() << "Failed to convert argument 2.";
return;
}
@@ -294,9 +284,15 @@ void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) {
browsing_history_service_->QueryHistory(search_text, options);
}
+void BrowsingHistoryHandler::HandleQueryHistoryContinuation(
+ const base::ListValue* args) {
+ DCHECK(args->empty());
+ DCHECK(query_history_continuation_);
+ std::move(query_history_continuation_).Run();
+}
+
void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) {
- std::vector<std::unique_ptr<BrowsingHistoryService::HistoryEntry>>
- items_to_remove;
+ std::vector<BrowsingHistoryService::HistoryEntry> items_to_remove;
items_to_remove.reserve(args->GetSize());
for (base::ListValue::const_iterator it = args->begin();
it != args->end(); ++it) {
@@ -311,10 +307,8 @@ void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) {
return;
}
DCHECK_GT(timestamps->GetSize(), 0U);
- std::unique_ptr<BrowsingHistoryService::HistoryEntry> entry(
- new BrowsingHistoryService::HistoryEntry());
-
- entry->url = GURL(url);
+ BrowsingHistoryService::HistoryEntry entry;
+ entry.url = GURL(url);
double timestamp;
for (base::ListValue::const_iterator ts_iterator = timestamps->begin();
@@ -325,14 +319,13 @@ void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) {
}
base::Time visit_time = base::Time::FromJsTime(timestamp);
- entry->all_timestamps.insert(visit_time.ToInternalValue());
+ entry.all_timestamps.insert(visit_time.ToInternalValue());
}
- items_to_remove.push_back(std::move(entry));
+ items_to_remove.push_back(entry);
}
- browsing_history_service_->RemoveVisits(&items_to_remove);
- items_to_remove.clear();
+ browsing_history_service_->RemoveVisits(items_to_remove);
}
void BrowsingHistoryHandler::HandleClearBrowsingData(
@@ -346,14 +339,16 @@ void BrowsingHistoryHandler::HandleClearBrowsingData(
void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue* args) {
base::string16 url = ExtractStringValue(args);
- Profile* profile = Profile::FromWebUI(web_ui());
+ Profile* profile = GetProfile();
BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(profile);
bookmarks::RemoveAllBookmarks(model, GURL(url));
}
void BrowsingHistoryHandler::OnQueryComplete(
- std::vector<BrowsingHistoryService::HistoryEntry>* results,
- BrowsingHistoryService::QueryResultsInfo* query_results_info) {
+ const std::vector<BrowsingHistoryService::HistoryEntry>& results,
+ const BrowsingHistoryService::QueryResultsInfo& query_results_info,
+ base::OnceClosure continuation_closure) {
+ query_history_continuation_ = std::move(continuation_closure);
Profile* profile = Profile::FromWebUI(web_ui());
BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile);
@@ -368,10 +363,10 @@ void BrowsingHistoryHandler::OnQueryComplete(
// Convert the result vector into a ListValue.
base::ListValue results_value;
- for (std::vector<BrowsingHistoryService::HistoryEntry>::iterator it =
- results->begin(); it != results->end(); ++it) {
- std::unique_ptr<base::Value> value(HistoryEntryToValue(
- &(*it), bookmark_model, supervised_user_service, sync_service));
+ for (const BrowsingHistoryService::HistoryEntry& entry : results) {
+ std::unique_ptr<base::Value> value(
+ HistoryEntryToValue(entry, bookmark_model, supervised_user_service,
+ sync_service, clock_.get()));
results_value.Append(std::move(value));
}
@@ -380,19 +375,10 @@ void BrowsingHistoryHandler::OnQueryComplete(
// described in chrome/browser/resources/history/history.js in @typedef for
// HistoryQuery. Please update it whenever you add or remove any keys in
// results_info_value_.
- results_info.SetString("term", query_results_info->search_text);
- results_info.SetBoolean("finished", query_results_info->reached_beginning);
+ results_info.SetString("term", query_results_info.search_text);
+ results_info.SetBoolean("finished", query_results_info.reached_beginning);
results_info.SetBoolean("hasSyncedResults",
- query_results_info->has_synced_results);
-
- // Add the specific dates that were searched to display them.
- // TODO(sergiu): Put today if the start is in the future.
- results_info.SetString(
- "queryStartTime",
- GetRelativeDateLocalized(clock_.get(), query_results_info->start_time));
- results_info.SetString(
- "queryEndTime",
- GetRelativeDateLocalized(clock_.get(), query_results_info->end_time));
+ query_results_info.has_synced_results);
web_ui()->CallJavascriptFunctionUnsafe("historyResult", results_info,
results_value);
@@ -417,3 +403,7 @@ void BrowsingHistoryHandler::HasOtherFormsOfBrowsingHistory(
base::Value(has_synced_results),
base::Value(has_other_forms));
}
+
+Profile* BrowsingHistoryHandler::GetProfile() {
+ return Profile::FromWebUI(web_ui());
+}
diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler.h b/chromium/chrome/browser/ui/webui/browsing_history_handler.h
index 0b486f251cf..0a300973273 100644
--- a/chromium/chrome/browser/ui/webui/browsing_history_handler.h
+++ b/chromium/chrome/browser/ui/webui/browsing_history_handler.h
@@ -12,16 +12,16 @@
#include <utility>
#include <vector>
+#include "base/callback.h"
#include "base/macros.h"
#include "base/time/clock.h"
#include "base/values.h"
-#include "chrome/browser/history/browsing_history_service_handler.h"
+#include "chrome/browser/history/profile_based_browsing_history_driver.h"
#include "content/public/browser/web_ui_message_handler.h"
// The handler for Javascript messages related to the "history" view.
-class BrowsingHistoryHandler :
- public content::WebUIMessageHandler,
- public BrowsingHistoryServiceHandler {
+class BrowsingHistoryHandler : public content::WebUIMessageHandler,
+ public ProfileBasedBrowsingHistoryDriver {
public:
BrowsingHistoryHandler();
~BrowsingHistoryHandler() override;
@@ -32,6 +32,9 @@ class BrowsingHistoryHandler :
// Handler for the "queryHistory" message.
void HandleQueryHistory(const base::ListValue* args);
+ // Handler for the "queryHistoryContinuation" message.
+ void HandleQueryHistoryContinuation(const base::ListValue* args);
+
// Handler for the "removeVisits" message.
void HandleRemoveVisits(const base::ListValue* args);
@@ -41,16 +44,21 @@ class BrowsingHistoryHandler :
// Handler for "removeBookmark" message.
void HandleRemoveBookmark(const base::ListValue* args);
- // BrowsingHistoryServiceHandler implementation.
+ // BrowsingHistoryDriver implementation.
void OnQueryComplete(
- std::vector<BrowsingHistoryService::HistoryEntry>* results,
- BrowsingHistoryService::QueryResultsInfo* query_results_info) override;
+ const std::vector<history::BrowsingHistoryService::HistoryEntry>& results,
+ const history::BrowsingHistoryService::QueryResultsInfo&
+ query_results_info,
+ base::OnceClosure continuation_closure) override;
void OnRemoveVisitsComplete() override;
void OnRemoveVisitsFailed() override;
void HistoryDeleted() override;
void HasOtherFormsOfBrowsingHistory(
bool has_other_forms, bool has_synced_results) override;
+ // ProfileBasedBrowsingHistoryDriver implementation.
+ Profile* GetProfile() override;
+
// For tests.
void set_clock(std::unique_ptr<base::Clock> clock) {
clock_ = std::move(clock);
@@ -64,7 +72,9 @@ class BrowsingHistoryHandler :
// The clock used to vend times.
std::unique_ptr<base::Clock> clock_;
- std::unique_ptr<BrowsingHistoryService> browsing_history_service_;
+ std::unique_ptr<history::BrowsingHistoryService> browsing_history_service_;
+
+ base::OnceClosure query_history_continuation_;
DISALLOW_COPY_AND_ASSIGN(BrowsingHistoryHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc
index cd16e202d44..200dcb043aa 100644
--- a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc
@@ -11,10 +11,10 @@
#include "base/macros.h"
#include "base/memory/ptr_util.h"
+#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/simple_test_clock.h"
#include "base/values.h"
-#include "chrome/browser/history/browsing_history_service.h"
#include "chrome/browser/history/web_history_service_factory.h"
#include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
#include "chrome/browser/signin/fake_signin_manager_builder.h"
@@ -24,6 +24,7 @@
#include "chrome/browser/sync/profile_sync_test_util.h"
#include "chrome/test/base/testing_profile.h"
#include "components/browser_sync/test_profile_sync_service.h"
+#include "components/history/core/browser/browsing_history_service.h"
#include "components/history/core/test/fake_web_history_service.h"
#include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
#include "components/signin/core/browser/fake_signin_manager.h"
@@ -214,7 +215,7 @@ TEST_F(BrowsingHistoryHandlerTest, ObservingWebHistoryDeletions) {
web_history_service()->ExpireHistoryBetween(
std::set<GURL>(), base::Time(), base::Time::Max(),
base::Bind(
- &BrowsingHistoryService::RemoveWebHistoryComplete,
+ &history::BrowsingHistoryService::RemoveWebHistoryComplete,
handler.browsing_history_service_->weak_factory_.GetWeakPtr()),
PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS);
@@ -241,27 +242,23 @@ TEST_F(BrowsingHistoryHandlerTest, ObservingWebHistoryDeletions) {
#if !defined(OS_ANDROID)
TEST_F(BrowsingHistoryHandlerTest, MdTruncatesTitles) {
- history::URLResult long_result(
- GURL("http://looooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
+ history::BrowsingHistoryService::HistoryEntry long_url_entry;
+ long_url_entry.url = GURL(
+ "http://loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
- "ngurlislong.com"), base::Time());
- ASSERT_GT(long_result.url().spec().size(), 300u);
-
- std::vector<history::URLResult> result_vector;
- result_vector.push_back(std::move(long_result));
- history::QueryResults results;
- results.SetURLResults(std::move(result_vector));
+ "ngurlislong.com");
+ ASSERT_GT(long_url_entry.url.spec().size(), 300U);
BrowsingHistoryHandlerWithWebUIForTesting handler(web_ui());
- handler.RegisterMessages(); // Needed to create BrowsingHistoryService.
- web_ui()->ClearTrackedCalls();
+ ASSERT_TRUE(web_ui()->call_data().empty());
- handler.browsing_history_service_->QueryComplete(
- base::string16(), history::QueryOptions(), &results);
+ handler.OnQueryComplete({long_url_entry},
+ history::BrowsingHistoryService::QueryResultsInfo(),
+ base::OnceClosure());
ASSERT_FALSE(web_ui()->call_data().empty());
const base::ListValue* arg2;
diff --git a/chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.cc
new file mode 100644
index 00000000000..88a3a34ecf0
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.cc
@@ -0,0 +1,90 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h"
+
+#include "build/build_config.h"
+#include "chrome/grit/generated_resources.h"
+#include "content/public/browser/web_ui_data_source.h"
+
+namespace certificate_manager {
+
+void AddLocalizedStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"certificateManagerExpandA11yLabel",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_EXPAND_ACCESSIBILITY_LABEL},
+ {"certificateManagerNoCertificates",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_NO_CERTIFICATES},
+ {"certificateManagerYourCertificates",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_YOUR_CERTIFICATES},
+ {"certificateManagerYourCertificatesDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_YOUR_CERTIFICATES_DESCRIPTION},
+ {"certificateManagerServers", IDS_SETTINGS_CERTIFICATE_MANAGER_SERVERS},
+ {"certificateManagerServersDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_SERVERS_DESCRIPTION},
+ {"certificateManagerAuthorities",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_AUTHORITIES},
+ {"certificateManagerAuthoritiesDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_AUTHORITIES_DESCRIPTION},
+ {"certificateManagerOthers", IDS_SETTINGS_CERTIFICATE_MANAGER_OTHERS},
+ {"certificateManagerOthersDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_OTHERS_DESCRIPTION},
+ {"certificateManagerView", IDS_SETTINGS_CERTIFICATE_MANAGER_VIEW},
+ {"certificateManagerImport", IDS_SETTINGS_CERTIFICATE_MANAGER_IMPORT},
+ {"certificateManagerImportAndBind",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_IMPORT_AND_BIND},
+ {"certificateManagerExport", IDS_SETTINGS_CERTIFICATE_MANAGER_EXPORT},
+ {"certificateManagerDelete", IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE},
+ {"certificateManagerDone", IDS_SETTINGS_CERTIFICATE_MANAGER_DONE},
+ {"certificateManagerUntrusted",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_UNTRUSTED},
+ // CA trust edit dialog.
+ {"certificateManagerCaTrustEditDialogTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_TITLE},
+ {"certificateManagerCaTrustEditDialogDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_DESCRIPTION},
+ {"certificateManagerCaTrustEditDialogExplanation",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_EXPLANATION},
+ {"certificateManagerCaTrustEditDialogSsl",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_SSL},
+ {"certificateManagerCaTrustEditDialogEmail",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_EMAIL},
+ {"certificateManagerCaTrustEditDialogObjSign",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_OBJ_SIGN},
+ // Certificate delete confirmation dialog.
+ {"certificateManagerDeleteUserTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_USER_TITLE},
+ {"certificateManagerDeleteUserDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_USER_DESCRIPTION},
+ {"certificateManagerDeleteServerTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_SERVER_TITLE},
+ {"certificateManagerDeleteServerDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_SERVER_DESCRIPTION},
+ {"certificateManagerDeleteCaTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_CA_TITLE},
+ {"certificateManagerDeleteCaDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_CA_DESCRIPTION},
+ {"certificateManagerDeleteOtherTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_OTHER_TITLE},
+ // Encrypt/decrypt password dialogs.
+ {"certificateManagerEncryptPasswordTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_ENCRYPT_PASSWORD_TITLE},
+ {"certificateManagerDecryptPasswordTitle",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_DECRYPT_PASSWORD_TITLE},
+ {"certificateManagerEncryptPasswordDescription",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_ENCRYPT_PASSWORD_DESCRIPTION},
+ {"certificateManagerPassword", IDS_SETTINGS_CERTIFICATE_MANAGER_PASSWORD},
+ {"certificateManagerConfirmPassword",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_CONFIRM_PASSWORD},
+ {"certificateImportErrorFormat",
+ IDS_SETTINGS_CERTIFICATE_MANAGER_IMPORT_ERROR_FORMAT},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+}
+
+} // namespace certificate_manager
diff --git a/chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h b/chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h
new file mode 100644
index 00000000000..9b3dbbd9a49
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h
@@ -0,0 +1,21 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CERTIFICATE_MANAGER_LOCALIZED_STRINGS_PROVIDER_H_
+#define CHROME_BROWSER_UI_WEBUI_CERTIFICATE_MANAGER_LOCALIZED_STRINGS_PROVIDER_H_
+
+namespace content {
+class WebUIDataSource;
+}
+
+namespace certificate_manager {
+
+// Adds the strings needed for the certificate_manager component to
+// |html_source|. String ids correspond to ids in
+// ui/webui/resources/cr_components/certificate_manager/.
+void AddLocalizedStrings(content::WebUIDataSource* html_source);
+
+} // namespace certificate_manager
+
+#endif // CHROME_BROWSER_UI_WEBUI_CERTIFICATE_MANAGER_LOCALIZED_STRINGS_PROVIDER_H_
diff --git a/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc b/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc
index eae1c60fa03..caf4dd19732 100644
--- a/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc
+++ b/chromium/chrome/browser/ui/webui/certificate_viewer_webui.cc
@@ -23,7 +23,7 @@
#include "chrome/browser/ui/certificate_dialogs.h"
#include "chrome/browser/ui/webui/certificate_viewer_ui.h"
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
-#include "chrome/common/net/x509_certificate_model.h"
+#include "chrome/common/net/x509_certificate_model_nss.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/web_contents.h"
diff --git a/chromium/chrome/browser/ui/webui/settings/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc
index 70a3a822373..01fa17cee95 100644
--- a/chromium/chrome/browser/ui/webui/settings/certificates_handler.cc
+++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/settings/certificates_handler.h"
+#include "chrome/browser/ui/webui/certificates_handler.h"
#include <errno.h>
#include <stddef.h>
@@ -14,14 +14,16 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
+#include "base/containers/id_map.h"
#include "base/files/file_util.h" // for FileAccessProvider
#include "base/i18n/string_compare.h"
-#include "base/id_map.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/posix/safe_strerror.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/task_scheduler/task_traits.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
@@ -32,7 +34,6 @@
#include "chrome/browser/ui/crypto_module_password_dialog_nss.h"
#include "chrome/browser/ui/webui/certificate_viewer_webui.h"
#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "net/base/net_errors.h"
#include "net/cert/x509_certificate.h"
@@ -46,7 +47,6 @@
#endif
using base::UTF8ToUTF16;
-using content::BrowserThread;
namespace {
@@ -138,15 +138,6 @@ bool IsPolicyInstalledWithWebTrust(const net::CertificateList& web_trust_certs,
CertEquals(cert)) != web_trust_certs.end();
}
-#if defined(OS_CHROMEOS)
-void ShowCertificateViewerModalDialog(content::WebContents* web_contents,
- gfx::NativeWindow parent,
- net::X509Certificate* cert) {
- CertificateViewerModalDialog* dialog = new CertificateViewerModalDialog(cert);
- dialog->Show(web_contents, parent);
-}
-#endif
-
// Determine if |data| could be a PFX Protocol Data Unit.
// This only does the minimum parsing necessary to distinguish a PFX file from a
// DER encoded Certificate.
@@ -187,7 +178,7 @@ bool CouldBePFX(const std::string& data) {
} // namespace
-namespace settings {
+namespace certificate_manager {
///////////////////////////////////////////////////////////////////////////////
// CertIdMap
@@ -205,7 +196,7 @@ class CertIdMap {
typedef std::map<net::X509Certificate*, int32_t> CertMap;
// Creates an ID for cert and looks up the cert for an ID.
- IDMap<net::X509Certificate*> id_map_;
+ base::IDMap<net::X509Certificate*> id_map_;
// Finds the ID for a cert.
CertMap cert_map_;
@@ -294,10 +285,11 @@ base::CancelableTaskTracker::TaskId FileAccessProvider::StartRead(
int* saved_errno = new int(0);
std::string* data = new std::string();
- // Post task to file thread to read file.
+ // Post task to a background sequence to read file.
+ auto task_runner = base::CreateTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::BACKGROUND});
return tracker->PostTaskAndReply(
- BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get(),
- FROM_HERE,
+ task_runner.get(), FROM_HERE,
base::BindOnce(&FileAccessProvider::DoRead, this, path, saved_errno,
data),
base::BindOnce(callback, base::Owned(saved_errno), base::Owned(data)));
@@ -312,10 +304,12 @@ base::CancelableTaskTracker::TaskId FileAccessProvider::StartWrite(
int* saved_errno = new int(0);
int* bytes_written = new int(0);
- // Post task to file thread to write file.
+ // This task blocks shutdown because it saves critical user data.
+ auto task_runner = base::CreateTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::BACKGROUND,
+ base::TaskShutdownBehavior::BLOCK_SHUTDOWN});
return tracker->PostTaskAndReply(
- BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get(),
- FROM_HERE,
+ task_runner.get(), FROM_HERE,
base::BindOnce(&FileAccessProvider::DoWrite, this, path, data,
saved_errno, bytes_written),
base::BindOnce(callback, base::Owned(saved_errno),
@@ -340,9 +334,8 @@ void FileAccessProvider::DoWrite(const base::FilePath& path,
///////////////////////////////////////////////////////////////////////////////
// CertificatesHandler
-CertificatesHandler::CertificatesHandler(bool show_certs_in_modal_dialog)
- : show_certs_in_modal_dialog_(show_certs_in_modal_dialog),
- requested_certificate_manager_model_(false),
+CertificatesHandler::CertificatesHandler()
+ : requested_certificate_manager_model_(false),
use_hardware_backed_(false),
file_access_provider_(new FileAccessProvider()),
cert_id_map_(new CertIdMap),
@@ -470,13 +463,6 @@ void CertificatesHandler::HandleViewCertificate(const base::ListValue* args) {
net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
if (!cert)
return;
-#if defined(OS_CHROMEOS)
- if (show_certs_in_modal_dialog_) {
- ShowCertificateViewerModalDialog(web_ui()->GetWebContents(),
- GetParentWindow(), cert);
- return;
- }
-#endif
ShowCertificateViewer(web_ui()->GetWebContents(), GetParentWindow(), cert);
}
@@ -563,7 +549,8 @@ void CertificatesHandler::HandleExportPersonal(const base::ListValue* args) {
l10n_util::GetStringUTF16(IDS_SETTINGS_CERTIFICATE_MANAGER_PKCS12_FILES));
file_type_info.include_all_files = true;
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
select_file_dialog_->SelectFile(
ui::SelectFileDialog::SELECT_SAVEAS_FILE, base::string16(),
base::FilePath(), &file_type_info, 1, FILE_PATH_LITERAL("p12"),
@@ -647,7 +634,8 @@ void CertificatesHandler::HandleImportPersonal(const base::ListValue* args) {
IDS_SETTINGS_CERTIFICATE_MANAGER_USAGE_SSL_CLIENT));
file_type_info.include_all_files = true;
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
select_file_dialog_->SelectFile(
ui::SelectFileDialog::SELECT_OPEN_FILE, base::string16(),
base::FilePath(), &file_type_info, 1, FILE_PATH_LITERAL("p12"),
@@ -658,8 +646,9 @@ void CertificatesHandler::HandleImportPersonal(const base::ListValue* args) {
void CertificatesHandler::ImportPersonalFileSelected(
const base::FilePath& path) {
file_access_provider_->StartRead(
- path, base::Bind(&CertificatesHandler::ImportPersonalFileRead,
- base::Unretained(this)),
+ path,
+ base::Bind(&CertificatesHandler::ImportPersonalFileRead,
+ base::Unretained(this)),
&tracker_);
}
@@ -796,7 +785,8 @@ void CertificatesHandler::HandleImportServer(const base::ListValue* args) {
AssignWebUICallbackId(args);
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
ShowCertSelectFileDialog(
select_file_dialog_.get(), ui::SelectFileDialog::SELECT_OPEN_FILE,
base::FilePath(), GetParentWindow(),
@@ -805,8 +795,9 @@ void CertificatesHandler::HandleImportServer(const base::ListValue* args) {
void CertificatesHandler::ImportServerFileSelected(const base::FilePath& path) {
file_access_provider_->StartRead(
- path, base::Bind(&CertificatesHandler::ImportServerFileRead,
- base::Unretained(this)),
+ path,
+ base::Bind(&CertificatesHandler::ImportServerFileRead,
+ base::Unretained(this)),
&tracker_);
}
@@ -861,7 +852,8 @@ void CertificatesHandler::HandleImportCA(const base::ListValue* args) {
AssignWebUICallbackId(args);
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
ShowCertSelectFileDialog(select_file_dialog_.get(),
ui::SelectFileDialog::SELECT_OPEN_FILE,
base::FilePath(), GetParentWindow(),
@@ -870,8 +862,9 @@ void CertificatesHandler::HandleImportCA(const base::ListValue* args) {
void CertificatesHandler::ImportCAFileSelected(const base::FilePath& path) {
file_access_provider_->StartRead(
- path, base::Bind(&CertificatesHandler::ImportCAFileRead,
- base::Unretained(this)),
+ path,
+ base::Bind(&CertificatesHandler::ImportCAFileRead,
+ base::Unretained(this)),
&tracker_);
}
@@ -1141,4 +1134,4 @@ gfx::NativeWindow CertificatesHandler::GetParentWindow() const {
return web_ui()->GetWebContents()->GetTopLevelNativeWindow();
}
-} // namespace settings
+} // namespace certificate_manager
diff --git a/chromium/chrome/browser/ui/webui/settings/certificates_handler.h b/chromium/chrome/browser/ui/webui/certificates_handler.h
index 839351ea3d3..04d605c0f3f 100644
--- a/chromium/chrome/browser/ui/webui/settings/certificates_handler.h
+++ b/chromium/chrome/browser/ui/webui/certificates_handler.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CERTIFICATES_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CERTIFICATES_HANDLER_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_CERTIFICATES_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CERTIFICATES_HANDLER_H_
#include <memory>
#include <string>
@@ -13,28 +13,25 @@
#include "base/memory/weak_ptr.h"
#include "base/task/cancelable_task_tracker.h"
#include "chrome/browser/certificate_manager_model.h"
-#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
+#include "content/public/browser/web_ui_message_handler.h"
#include "net/cert/nss_cert_database.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/shell_dialogs/select_file_dialog.h"
-namespace settings {
+namespace certificate_manager {
class CertIdMap;
class FileAccessProvider;
-class CertificatesHandler
- : public SettingsPageUIHandler,
- public CertificateManagerModel::Observer,
- public ui::SelectFileDialog::Listener {
+class CertificatesHandler : public content::WebUIMessageHandler,
+ public CertificateManagerModel::Observer,
+ public ui::SelectFileDialog::Listener {
public:
- explicit CertificatesHandler(bool show_certs_in_modal_dialog);
+ CertificatesHandler();
~CertificatesHandler() override;
- // SettingsPageUIHandler implementation.
+ // content::WebUIMessageHandler.
void RegisterMessages() override;
- void OnJavascriptAllowed() override {}
- void OnJavascriptDisallowed() override {}
// CertificateManagerModel::Observer implementation.
void CertificatesRefreshed() override;
@@ -152,8 +149,8 @@ class CertificatesHandler
void RejectCallback(const base::Value& response);
// Reject the pending JS callback with a generic error.
- void RejectCallbackWithError(
- const std::string& title, const std::string& error);
+ void RejectCallbackWithError(const std::string& title,
+ const std::string& error);
// Reject the pending JS callback with a certificate import error.
void RejectCallbackWithImportError(
@@ -166,9 +163,6 @@ class CertificatesHandler
gfx::NativeWindow GetParentWindow() const;
- // True if certificate viewer should be shown in modal instead of constrianed
- // dialog.
- bool show_certs_in_modal_dialog_;
// The Certificates Manager model
bool requested_certificate_manager_model_;
std::unique_ptr<CertificateManagerModel> certificate_manager_model_;
@@ -198,6 +192,6 @@ class CertificatesHandler
DISALLOW_COPY_AND_ASSIGN(CertificatesHandler);
};
-} // namespace settings
+} // namespace certificate_manager
-#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CERTIFICATES_HANDLER_H_
+#endif // CHROME_BROWSER_UI_WEBUI_CERTIFICATES_HANDLER_H_
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 d2c501111f6..ef0d467e71e 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
@@ -40,13 +40,13 @@
#include "chrome/browser/ui/webui/local_state/local_state_ui.h"
#include "chrome/browser/ui/webui/log_web_ui_url.h"
#include "chrome/browser/ui/webui/media/media_engagement_ui.h"
+#include "chrome/browser/ui/webui/memory_internals_ui.h"
#include "chrome/browser/ui/webui/net_export_ui.h"
#include "chrome/browser/ui/webui/net_internals/net_internals_ui.h"
#include "chrome/browser/ui/webui/ntp_tiles_internals_ui.h"
#include "chrome/browser/ui/webui/omnibox/omnibox_ui.h"
#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h"
#include "chrome/browser/ui/webui/physical_web/physical_web_ui.h"
-#include "chrome/browser/ui/webui/policy_material_design_ui.h"
#include "chrome/browser/ui/webui/policy_ui.h"
#include "chrome/browser/ui/webui/predictors/predictors_ui.h"
#include "chrome/browser/ui/webui/profiler_ui.h"
@@ -209,10 +209,6 @@
#include "extensions/common/manifest.h"
#endif
-#if BUILDFLAG(ENABLE_OOP_HEAP_PROFILING)
-#include "chrome/browser/ui/webui/memory_internals_ui.h"
-#endif
-
using content::WebUI;
using content::WebUIController;
using ui::WebDialogUI;
@@ -269,20 +265,12 @@ WebUIController* NewWebUI<dom_distiller::DomDistillerUi>(WebUI* web_ui,
web_ui, service, dom_distiller::kDomDistillerScheme);
}
-#if !defined(OS_ANDROID)
-template<>
-WebUIController* NewWebUI<settings::MdSettingsUI>(WebUI* web_ui,
- const GURL& url) {
- return new settings::MdSettingsUI(web_ui, url);
-}
-
-#if !defined(OS_CHROMEOS)
+#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
template <>
WebUIController* NewWebUI<WelcomeUI>(WebUI* web_ui, const GURL& url) {
return new WelcomeUI(web_ui, url);
}
-#endif // !defined(OS_CHROMEOS)
-#endif // !defined(OS_ANDROID)
+#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#if defined(OS_WIN)
template <>
@@ -428,13 +416,13 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
// Identity API is not available on Android.
if (url.host_piece() == chrome::kChromeUIIdentityInternalsHost)
return &NewWebUI<IdentityInternalsUI>;
+ if (url.host_piece() == chrome::kChromeUIMemoryInternalsHost)
+ return &NewWebUI<MemoryInternalsUI>;
if (url.host_piece() == chrome::kChromeUINewTabHost)
return &NewWebUI<NewTabUI>;
// Settings are implemented with native UI elements on Android.
- if (url.host_piece() == chrome::kChromeUISettingsHost ||
- url.host_piece() == chrome::kChromeUIMdSettingsHost) {
+ if (url.host_piece() == chrome::kChromeUISettingsHost)
return &NewWebUI<settings::MdSettingsUI>;
- }
if (url.host_piece() == chrome::kChromeUIExtensionsHost)
return &NewWebUI<extensions::ExtensionsUI>;
if (url.host_piece() == chrome::kChromeUIHistoryHost)
@@ -545,9 +533,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<NaClUI>;
#endif
#if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(USE_AURA)
- if (url.host_piece() == chrome::kChromeUITabModalConfirmDialogHost) {
+ if (url.host_piece() == chrome::kChromeUITabModalConfirmDialogHost)
return &NewWebUI<ConstrainedWebDialogUI>;
- }
#endif
#if defined(USE_NSS_CERTS) && defined(USE_AURA)
if (url.host_piece() == chrome::kChromeUICertificateViewerHost)
@@ -560,10 +547,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
if (url.host_piece() == chrome::kChromeUIPolicyHost)
return &NewWebUI<PolicyUI>;
- if (url.host_piece() == chrome::kChromeUIMdPolicyHost &&
- switches::MdPolicyPageEnabled()) {
- return &NewWebUI<PolicyMaterialDesignUI>;
- }
#if BUILDFLAG(ENABLE_APP_LIST)
if (url.host_piece() == chrome::kChromeUIAppListStartPageHost)
@@ -571,8 +554,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
#endif
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
if (url.host() == chrome::kChromeUISigninDiceInternalsHost &&
- !profile->IsOffTheRecord() &&
- switches::IsAccountConsistencyDiceEnabled()) {
+ !profile->IsOffTheRecord() && signin::IsAccountConsistencyDiceEnabled()) {
return &NewWebUI<SigninDiceInternalsUI>;
}
#endif
@@ -580,10 +562,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
if (url.host_piece() == chrome::kChromeUIExtensionsFrameHost)
return &NewWebUI<extensions::ExtensionsUI>;
#endif
-#if BUILDFLAG(ENABLE_OOP_HEAP_PROFILING)
- if (url.host_piece() == chrome::kChromeUIMemoryInternalsHost)
- return &NewWebUI<MemoryInternalsUI>;
-#endif
#if BUILDFLAG(ENABLE_PLUGINS)
if (url.host_piece() == chrome::kChromeUIFlashHost)
return &NewWebUI<FlashUI>;
@@ -811,14 +789,14 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes(
return MdDownloadsUI::GetFaviconResourceBytes(scale_factor);
// Android doesn't use the Options/Settings pages.
- if (page_url.host_piece() == chrome::kChromeUISettingsHost ||
- page_url.host_piece() == chrome::kChromeUIMdSettingsHost)
+ if (page_url.host_piece() == chrome::kChromeUISettingsHost)
return settings_utils::GetFaviconResourceBytes(scale_factor);
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (page_url.host_piece() == chrome::kChromeUIExtensionsHost ||
- page_url.host_piece() == chrome::kChromeUIExtensionsFrameHost)
+ page_url.host_piece() == chrome::kChromeUIExtensionsFrameHost) {
return extensions::ExtensionsUI::GetFaviconResourceBytes(scale_factor);
+ }
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
#endif // !defined(OS_ANDROID)
diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.cc
new file mode 100644
index 00000000000..ce64fd42c3a
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.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 "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h"
+
+#include "build/build_config.h"
+#include "chrome/grit/generated_resources.h"
+#include "content/public/browser/web_ui_data_source.h"
+
+namespace chromeos {
+namespace bluetooth_dialog {
+
+void AddLocalizedStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"bluetoothAccept", IDS_SETTINGS_BLUETOOTH_ACCEPT_PASSKEY},
+ {"bluetoothEnterKey", IDS_SETTINGS_BLUETOOTH_ENTER_KEY},
+ {"bluetoothPair", IDS_SETTINGS_BLUETOOTH_PAIR},
+ {"bluetoothReject", IDS_SETTINGS_BLUETOOTH_REJECT_PASSKEY},
+ {"bluetoothStartConnecting", IDS_SETTINGS_BLUETOOTH_START_CONNECTING},
+ // Device connecting and pairing.
+ // These ids are generated in JS using 'bluetooth_' + a value from
+ // bluetoothPrivate.PairingEventType (see bluetooth_private.idl).
+ // 'keysEntered', and 'requestAuthorization' have no associated message.
+ {"bluetooth_requestPincode", IDS_SETTINGS_BLUETOOTH_REQUEST_PINCODE},
+ {"bluetooth_displayPincode", IDS_SETTINGS_BLUETOOTH_DISPLAY_PINCODE},
+ {"bluetooth_requestPasskey", IDS_SETTINGS_BLUETOOTH_REQUEST_PASSKEY},
+ {"bluetooth_displayPasskey", IDS_SETTINGS_BLUETOOTH_DISPLAY_PASSKEY},
+ {"bluetooth_confirmPasskey", IDS_SETTINGS_BLUETOOTH_CONFIRM_PASSKEY},
+ // These ids are generated in JS using 'bluetooth_connect_' + a value from
+ // bluetoothPrivate.ConnectResultType (see bluetooth_private.idl).
+ {"bluetooth_connect_attributeLengthInvalid",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_ATTRIBUTE_LENGTH_INVALID},
+ {"bluetooth_connect_authCanceled",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_CANCELED},
+ {"bluetooth_connect_authFailed",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_FAILED},
+ {"bluetooth_connect_authRejected",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_REJECTED},
+ {"bluetooth_connect_authTimeout",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_TIMEOUT},
+ {"bluetooth_connect_connectionCongested",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_CONNECTION_CONGESTED},
+ {"bluetooth_connect_failed", IDS_SETTINGS_BLUETOOTH_CONNECT_FAILED},
+ {"bluetooth_connect_inProgress",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_IN_PROGRESS},
+ {"bluetooth_connect_insufficientEncryption",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_INSUFFICIENT_ENCRYPTION},
+ {"bluetooth_connect_offsetInvalid",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_OFFSET_INVALID},
+ {"bluetooth_connect_readNotPermitted",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_READ_NOT_PERMITTED},
+ {"bluetooth_connect_requestNotSupported",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_REQUEST_NOT_SUPPORTED},
+ {"bluetooth_connect_unsupportedDevice",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_UNSUPPORTED_DEVICE},
+ {"bluetooth_connect_writeNotPermitted",
+ IDS_SETTINGS_BLUETOOTH_CONNECT_WRITE_NOT_PERMITTED},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+}
+
+} // namespace bluetooth_dialog
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h
new file mode 100644
index 00000000000..c85140ca4c0
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h
@@ -0,0 +1,22 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_DIALOG_LOCALIZED_STRINGS_PROVIDER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_DIALOG_LOCALIZED_STRINGS_PROVIDER_H_
+
+namespace content {
+class WebUIDataSource;
+}
+
+namespace chromeos {
+namespace bluetooth_dialog {
+
+// Adds the strings needed for network elements to |html_source|. String ids
+// correspond to ids in ui/webui/resources/cr_elements/chromeos/network/.
+void AddLocalizedStrings(content::WebUIDataSource* html_source);
+
+} // namespace bluetooth_dialog
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_DIALOG_LOCALIZED_STRINGS_PROVIDER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.cc
index bbd209e0b09..70a41a4d45c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.cc
@@ -4,59 +4,55 @@
#include "chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.h"
-#include "base/memory/ptr_util.h"
-#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h"
+#include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
-using content::WebContents;
-using content::WebUIMessageHandler;
-
namespace chromeos {
-BluetoothPairingUI::BluetoothPairingUI(content::WebUI* web_ui)
- : WebDialogUI(web_ui) {
- base::DictionaryValue localized_strings;
-
- auto core_handler = base::MakeUnique<options::CoreChromeOSOptionsHandler>();
- core_handler_ = core_handler.get();
- web_ui->AddMessageHandler(std::move(core_handler));
- core_handler_->set_handlers_host(this);
- core_handler_->GetLocalizedValues(&localized_strings);
+namespace {
+
+void AddBluetoothStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"ok", IDS_OK},
+ {"bluetoothPairDevicePageTitle",
+ IDS_SETTINGS_BLUETOOTH_PAIR_DEVICE_TITLE},
+ {"cancel", IDS_CANCEL},
+ {"close", IDS_CLOSE},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+ chromeos::bluetooth_dialog::AddLocalizedStrings(html_source);
+}
- auto bluetooth_handler = base::MakeUnique<options::BluetoothOptionsHandler>();
- bluetooth_handler_ = bluetooth_handler.get();
- web_ui->AddMessageHandler(std::move(bluetooth_handler));
- bluetooth_handler_->GetLocalizedValues(&localized_strings);
+} // namespace
+BluetoothPairingUI::BluetoothPairingUI(content::WebUI* web_ui)
+ : WebDialogUI(web_ui) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIBluetoothPairingHost);
- source->AddLocalizedStrings(localized_strings);
+
+ AddBluetoothStrings(source);
source->SetJsonPath("strings.js");
source->SetDefaultResource(IDR_BLUETOOTH_PAIR_DEVICE_HTML);
source->DisableContentSecurityPolicy();
- Profile* profile = Profile::FromWebUI(web_ui);
- content::WebUIDataSource::Add(profile, source);
-}
+ source->AddResourcePath("bluetooth_dialog_host.html",
+ IDR_BLUETOOTH_DIALOG_HOST_HTML);
+ source->AddResourcePath("bluetooth_dialog_host.js",
+ IDR_BLUETOOTH_DIALOG_HOST_JS);
-BluetoothPairingUI::~BluetoothPairingUI() {
- // Uninitialize all registered handlers. The base class owns them and it will
- // eventually delete them.
- core_handler_->Uninitialize();
- bluetooth_handler_->Uninitialize();
+ content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
}
-void BluetoothPairingUI::InitializeHandlers() {
- core_handler_->InitializeHandler();
- bluetooth_handler_->InitializeHandler();
- core_handler_->InitializePage();
- bluetooth_handler_->InitializePage();
-}
+BluetoothPairingUI::~BluetoothPairingUI() {}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.h b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.h
index 3690918354d..d49cf571737 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_ui.h
@@ -6,30 +6,17 @@
#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_PAIRING_UI_H_
#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
#include "ui/web_dialogs/web_dialog_ui.h"
namespace chromeos {
-namespace options {
-class CoreChromeOSOptionsHandler;
-class BluetoothOptionsHandler;
-}
-
// A WebUI to host bluetooth device pairing web ui.
-class BluetoothPairingUI : public ui::WebDialogUI,
- public ::options::OptionsPageUIHandlerHost {
+class BluetoothPairingUI : public ui::WebDialogUI {
public:
explicit BluetoothPairingUI(content::WebUI* web_ui);
~BluetoothPairingUI() override;
private:
- // Overridden from OptionsPageUIHandlerHost:
- void InitializeHandlers() override;
-
- options::CoreChromeOSOptionsHandler* core_handler_ = nullptr;
- options::BluetoothOptionsHandler* bluetooth_handler_ = nullptr;
-
DISALLOW_COPY_AND_ASSIGN(BluetoothPairingUI);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc
index fda473bef00..1c29e0a79d2 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.cc
@@ -4,159 +4,61 @@
#include "chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h"
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted_memory.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/options/certificate_manager_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h"
-#include "chrome/common/chrome_constants.h"
+#include "chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h"
+#include "chrome/browser/ui/webui/certificates_handler.h"
+#include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
-#include "chromeos/chromeos_constants.h"
-#include "content/public/browser/url_data_source.h"
-#include "content/public/browser/web_contents.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/strings/grit/components_strings.h"
+#include "components/user_manager/user_manager.h"
#include "content/public/browser/web_ui.h"
-#include "content/public/browser/web_ui_message_handler.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/template_expressions.h"
-#include "ui/base/webui/jstemplate_builder.h"
-#include "ui/base/webui/web_ui_util.h"
+#include "content/public/browser/web_ui_data_source.h"
-using content::WebContents;
-using content::WebUIMessageHandler;
+namespace chromeos {
namespace {
-const char kLocalizedStringsFile[] = "strings.js";
-
-class CertificateManagerDialogHTMLSource : public content::URLDataSource {
- public:
- explicit CertificateManagerDialogHTMLSource(
- base::DictionaryValue* localized_strings);
-
- // content::URLDataSource implementation.
- std::string GetSource() const override;
- void StartDataRequest(
- const std::string& path,
- const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
- const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override {
- return "text/html";
- }
- bool ShouldAddContentSecurityPolicy() const override { return false; }
- bool AllowCaching() const override {
- // Should not be cached to reflect dynamically-generated contents that may
- // depend on current locale setting.
- return false;
- }
-
- protected:
- ~CertificateManagerDialogHTMLSource() override {}
-
- private:
- std::unique_ptr<base::DictionaryValue> localized_strings_;
-
- DISALLOW_COPY_AND_ASSIGN(CertificateManagerDialogHTMLSource);
-};
-
-CertificateManagerDialogHTMLSource::CertificateManagerDialogHTMLSource(
- base::DictionaryValue* localized_strings)
- : localized_strings_(localized_strings) {
-}
-
-std::string CertificateManagerDialogHTMLSource::GetSource() const {
- return chrome::kChromeUICertificateManagerHost;
-}
-
-void CertificateManagerDialogHTMLSource::StartDataRequest(
- const std::string& path,
- const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
- const content::URLDataSource::GotDataCallback& callback) {
- scoped_refptr<base::RefCountedMemory> response_bytes;
- const std::string& app_locale = g_browser_process->GetApplicationLocale();
- webui::SetLoadTimeDataDefaults(app_locale, localized_strings_.get());
-
- if (path == kLocalizedStringsFile) {
- // Return dynamically-generated strings from memory.
- std::string strings_js;
- webui::AppendJsonJS(localized_strings_.get(), &strings_js);
- response_bytes = base::RefCountedString::TakeString(&strings_js);
- } else {
- // Return (and cache) the main options html page as the default.
- response_bytes = ui::ResourceBundle::GetSharedInstance().
- LoadDataResourceBytes(IDR_CERT_MANAGER_DIALOG_HTML);
- // Pre-process i18n strings.
- ui::TemplateReplacements replacements;
- ui::TemplateReplacementsFromDictionaryValue(*localized_strings_,
- &replacements);
- std::string replaced = ui::ReplaceTemplateExpressions(
- base::StringPiece(response_bytes->front_as<char>(),
- response_bytes->size()),
- replacements);
- response_bytes = base::RefCountedString::TakeString(&replaced);
- }
-
- callback.Run(response_bytes.get());
+void AddCertificateManagerStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"cancel", IDS_CANCEL},
+ {"close", IDS_CLOSE},
+ {"edit", IDS_SETTINGS_EDIT},
+ {"moreActions", IDS_SETTINGS_MORE_ACTIONS},
+ {"ok", IDS_OK},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+ certificate_manager::AddLocalizedStrings(html_source);
}
} // namespace
-namespace chromeos {
-
CertificateManagerDialogUI::CertificateManagerDialogUI(content::WebUI* web_ui)
- : ui::WebDialogUI(web_ui), initialized_handlers_(false) {
- // |localized_strings| will be owned by CertificateManagerDialogHTMLSource.
- base::DictionaryValue* localized_strings = new base::DictionaryValue();
-
- auto core_handler = base::MakeUnique<options::CoreChromeOSOptionsHandler>();
- core_handler_ = core_handler.get();
- web_ui->AddMessageHandler(std::move(core_handler));
- core_handler_->set_handlers_host(this);
- core_handler_->GetLocalizedValues(localized_strings);
+ : WebDialogUI(web_ui) {
+ content::WebUIDataSource* source =
+ content::WebUIDataSource::Create(chrome::kChromeUICertificateManagerHost);
- auto cert_handler =
- base::MakeUnique<::options::CertificateManagerHandler>(true);
- cert_handler_ = cert_handler.get();
- web_ui->AddMessageHandler(std::move(cert_handler));
- cert_handler_->GetLocalizedValues(localized_strings);
+ AddCertificateManagerStrings(source);
+ source->AddBoolean(
+ "isGuest",
+ user_manager::UserManager::Get()->IsLoggedInAsGuest() ||
+ user_manager::UserManager::Get()->IsLoggedInAsPublicAccount());
- bool keyboard_driven_oobe =
- system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation();
- localized_strings->SetString("highlightStrength",
- keyboard_driven_oobe ? "strong" : "normal");
+ source->SetJsonPath("strings.js");
+ source->SetDefaultResource(IDR_CERT_MANAGER_DIALOG_HTML);
+ source->DisableContentSecurityPolicy();
- CertificateManagerDialogHTMLSource* source =
- new CertificateManagerDialogHTMLSource(localized_strings);
- Profile* profile = Profile::FromWebUI(web_ui);
- content::URLDataSource::Add(profile, source);
-}
+ web_ui->AddMessageHandler(
+ base::MakeUnique<certificate_manager::CertificatesHandler>());
-CertificateManagerDialogUI::~CertificateManagerDialogUI() {
- // Uninitialize all registered handlers. The base class owns them and it will
- // eventually delete them.
- core_handler_->Uninitialize();
- cert_handler_->Uninitialize();
+ content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
}
-void CertificateManagerDialogUI::InitializeHandlers() {
- // A new web page DOM has been brought up in an existing renderer, causing
- // this method to be called twice. In that case, don't initialize the handlers
- // again. Compare with options_ui.cc.
- if (!initialized_handlers_) {
- core_handler_->InitializeHandler();
- cert_handler_->InitializeHandler();
- initialized_handlers_ = true;
- }
- core_handler_->InitializePage();
- cert_handler_->InitializePage();
-}
+CertificateManagerDialogUI::~CertificateManagerDialogUI() {}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h b/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h
index 374ceb2a25e..01f4a44e78d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/certificate_manager_dialog_ui.h
@@ -6,34 +6,17 @@
#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_CERTIFICATE_MANAGER_DIALOG_UI_H_
#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
#include "ui/web_dialogs/web_dialog_ui.h"
-namespace options {
-class CertificateManagerHandler;
-}
-
namespace chromeos {
-namespace options {
-class CoreChromeOSOptionsHandler;
-}
-
-// A WebUI to host certificate manager split from the main settings page.
-class CertificateManagerDialogUI : public ui::WebDialogUI,
- public ::options::OptionsPageUIHandlerHost {
+// A WebUI to host certificate manager UI.
+class CertificateManagerDialogUI : public ui::WebDialogUI {
public:
explicit CertificateManagerDialogUI(content::WebUI* web_ui);
~CertificateManagerDialogUI() override;
private:
- // Overridden from OptionsPageUIHandlerHost:
- void InitializeHandlers() override;
-
- bool initialized_handlers_;
-
- ::options::CertificateManagerHandler* cert_handler_ = nullptr;
- options::CoreChromeOSOptionsHandler* core_handler_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(CertificateManagerDialogUI);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/choose_mobile_network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/choose_mobile_network_ui.cc
index 7196f2cb691..3eec99c25a1 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/choose_mobile_network_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/choose_mobile_network_ui.cc
@@ -70,7 +70,7 @@ content::WebUIDataSource* CreateChooseMobileNetworkUIHTMLSource() {
IDS_NETWORK_SCANNING_THIS_MAY_TAKE_A_MINUTE);
source->AddLocalizedString("noMobileNetworks",
IDS_NETWORK_NO_MOBILE_NETWORKS);
- source->AddLocalizedString("connect", IDS_OPTIONS_SETTINGS_CONNECT);
+ source->AddLocalizedString("connect", IDS_SETTINGS_INTERNET_BUTTON_CONNECT);
source->AddLocalizedString("cancel", IDS_CANCEL);
source->SetJsonPath("strings.js");
diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc
index 1f22919bc9d..9c2e91fe57a 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.cc
@@ -43,17 +43,16 @@ FirstRunActor::StepPosition& FirstRunActor::StepPosition::SetLeft(int left) {
return *this;
}
-std::unique_ptr<base::DictionaryValue> FirstRunActor::StepPosition::AsValue()
- const {
- auto result = base::MakeUnique<base::DictionaryValue>();
+base::DictionaryValue FirstRunActor::StepPosition::AsValue() const {
+ base::DictionaryValue result;
if (top_ != kNoneValue)
- result->SetInteger("top", top_);
+ result.SetInteger("top", top_);
if (right_ != kNoneValue)
- result->SetInteger("right", right_);
+ result.SetInteger("right", right_);
if (bottom_ != kNoneValue)
- result->SetInteger("bottom", bottom_);
+ result.SetInteger("bottom", bottom_);
if (left_ != kNoneValue)
- result->SetInteger("left", left_);
+ result.SetInteger("left", left_);
return result;
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.h b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.h
index 56dafbf1a21..1d879e0a94b 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_actor.h
@@ -55,7 +55,7 @@ class FirstRunActor {
StepPosition& SetLeft(int left);
// Returns DictionaryValue containing set properties.
- std::unique_ptr<base::DictionaryValue> AsValue() const;
+ base::DictionaryValue AsValue() const;
private:
int top_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc
index cbe4caf67fc..312a70506e7 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_handler.cc
@@ -45,12 +45,12 @@ void FirstRunHandler::RemoveBackgroundHoles() {
void FirstRunHandler::ShowStepPositioned(const std::string& name,
const StepPosition& position) {
base::DictionaryValue step_params;
- step_params.SetString("name", name);
- step_params.Set("position",
- base::MakeUnique<base::Value>(*position.AsValue()));
- step_params.SetList("pointWithOffset", base::MakeUnique<base::ListValue>());
- step_params.SetBoolean("voiceInteractionEnabled",
- chromeos::switches::IsVoiceInteractionEnabled());
+ step_params.SetKey("name", base::Value(name));
+ step_params.SetKey("position", position.AsValue());
+ step_params.SetKey("pointWithOffset", base::Value(base::Value::Type::LIST));
+ step_params.SetKey(
+ "voiceInteractionEnabled",
+ base::Value(chromeos::switches::IsVoiceInteractionEnabled()));
web_ui()->CallJavascriptFunctionUnsafe("cr.FirstRun.showStep", step_params);
}
@@ -60,16 +60,16 @@ void FirstRunHandler::ShowStepPointingTo(const std::string& name,
int y,
int offset) {
base::DictionaryValue step_params;
- step_params.SetString("name", name);
- step_params.Set("position", base::MakeUnique<base::Value>());
+ step_params.SetKey("name", base::Value(name));
+ step_params.SetKey("position", base::Value());
base::ListValue point_with_offset;
point_with_offset.AppendInteger(x);
point_with_offset.AppendInteger(y);
point_with_offset.AppendInteger(offset);
- step_params.SetList("pointWithOffset",
- base::MakeUnique<base::ListValue>(point_with_offset));
- step_params.SetBoolean("voiceInteractionEnabled",
- chromeos::switches::IsVoiceInteractionEnabled());
+ step_params.SetKey("pointWithOffset", std::move(point_with_offset));
+ step_params.SetKey(
+ "voiceInteractionEnabled",
+ base::Value(chromeos::switches::IsVoiceInteractionEnabled()));
web_ui()->CallJavascriptFunctionUnsafe("cr.FirstRun.showStep", step_params);
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc
index 743d22e8c67..514536325e9 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc
@@ -16,16 +16,14 @@
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/task_scheduler/post_task.h"
+#include "base/task_scheduler/task_scheduler.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/chromeos/login/users/avatar/user_image_loader.h"
#include "chrome/common/url_constants.h"
#include "components/user_manager/user_image/user_image.h"
-#include "content/public/browser/browser_thread.h"
#include "net/base/mime_util.h"
-using content::BrowserThread;
-
namespace chromeos {
namespace {
@@ -37,8 +35,6 @@ const char* kWhitelistedDirectories[] = {
void ImageLoaded(
const content::URLDataSource::GotDataCallback& got_data_callback,
std::unique_ptr<user_manager::UserImage> user_image) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
if (user_image->has_image_bytes())
got_data_callback.Run(user_image->image_bytes());
else
@@ -48,11 +44,9 @@ void ImageLoaded(
} // namespace
ImageSource::ImageSource() : weak_factory_(this) {
- base::SequencedWorkerPool* blocking_pool =
- BrowserThread::GetBlockingPool();
- task_runner_ = blocking_pool->GetSequencedTaskRunnerWithShutdownBehavior(
- blocking_pool->GetSequenceToken(),
- base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN);
+ task_runner_ = base::CreateSequencedTaskRunnerWithTraits(
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
}
ImageSource::~ImageSource() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS
new file mode 100644
index 00000000000..7554fa7fece
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS
@@ -0,0 +1,6 @@
+specific_include_rules = {
+ # TODO(mash): Remove. http://crbug.com/720917.
+ "oobe_display_chooser_unittest.cc": [
+ "+ui/events/devices/device_data_manager.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
new file mode 100644
index 00000000000..b4f3e276234
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc
@@ -0,0 +1,141 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h"
+
+#include "base/memory/ptr_util.h"
+#include "chrome/browser/chromeos/login/oobe_screen.h"
+#include "chrome/browser/chromeos/login/screens/core_oobe_view.h"
+#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
+#include "chrome/grit/generated_resources.h"
+#include "chromeos/login/auth/authpolicy_login_helper.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 {
+
+namespace {
+
+constexpr char kJsScreenPath[] = "login.ActiveDirectoryPasswordChangeScreen";
+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
+
+ActiveDirectoryPasswordChangeScreenHandler::
+ ActiveDirectoryPasswordChangeScreenHandler(CoreOobeView* core_oobe_view)
+ : BaseScreenHandler(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE),
+ authpolicy_login_helper_(base::MakeUnique<AuthPolicyLoginHelper>()),
+ core_oobe_view_(core_oobe_view),
+ weak_factory_(this) {
+ set_call_js_prefix(kJsScreenPath);
+}
+
+ActiveDirectoryPasswordChangeScreenHandler::
+ ~ActiveDirectoryPasswordChangeScreenHandler() {}
+
+void ActiveDirectoryPasswordChangeScreenHandler::DeclareLocalizedValues(
+ ::login::LocalizedValuesBuilder* builder) {
+ builder->Add("adPassChangeMessage", IDS_AD_PASSWORD_CHANGE_MESSAGE);
+}
+
+void ActiveDirectoryPasswordChangeScreenHandler::Initialize() {}
+
+void ActiveDirectoryPasswordChangeScreenHandler::RegisterMessages() {
+ AddCallback("completeActiveDirectoryPasswordChange",
+ &ActiveDirectoryPasswordChangeScreenHandler::HandleComplete);
+ AddCallback("cancelActiveDirectoryPasswordChange",
+ &ActiveDirectoryPasswordChangeScreenHandler::HandleCancel);
+}
+
+void ActiveDirectoryPasswordChangeScreenHandler::HandleComplete(
+ 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)));
+}
+
+void ActiveDirectoryPasswordChangeScreenHandler::HandleCancel() {
+ authpolicy_login_helper_->CancelRequestsAndRestart();
+}
+
+void ActiveDirectoryPasswordChangeScreenHandler::ShowScreen(
+ const std::string& username,
+ SigninScreenHandlerDelegate* delegate) {
+ delegate_ = delegate;
+ base::DictionaryValue data;
+ data.SetString(kUsernameKey, username);
+ ShowScreenWithData(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE,
+ &data);
+}
+
+void ActiveDirectoryPasswordChangeScreenHandler::ShowScreenWithError(
+ int error) {
+ base::DictionaryValue data;
+ data.SetInteger(kErrorKey, error);
+ ShowScreenWithData(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE,
+ &data);
+}
+
+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(delegate_);
+ delegate_->SetDisplayAndGivenName(account_info.display_name(),
+ account_info.given_name());
+ UserContext user_context(account_id);
+ user_context.SetKey(key);
+ user_context.SetAuthFlow(UserContext::AUTH_FLOW_ACTIVE_DIRECTORY);
+ user_context.SetIsUsingOAuth(false);
+ user_context.SetUserType(
+ user_manager::UserType::USER_TYPE_ACTIVE_DIRECTORY);
+ delegate_->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, delegate_);
+ core_oobe_view_->ShowSignInError(
+ 0, l10n_util::GetStringUTF8(IDS_AD_AUTH_UNKNOWN_ERROR), std::string(),
+ HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
+ }
+}
+
+} // 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
new file mode 100644
index 00000000000..83b651b80f6
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h
@@ -0,0 +1,80 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_ACTIVE_DIRECTORY_PASSWORD_CHANGE_SCREEN_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_ACTIVE_DIRECTORY_PASSWORD_CHANGE_SCREEN_HANDLER_H_
+
+#include <string>
+
+#include "base/macros.h"
+#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
+#include "chromeos/login/auth/authpolicy_login_helper.h"
+
+namespace authpolicy {
+class ActiveDirectoryAccountInfo;
+}
+
+namespace chromeos {
+
+class CoreOobeView;
+class Key;
+class SigninScreenHandlerDelegate;
+
+// A class that handles WebUI hooks in Active Directory password change screen.
+class ActiveDirectoryPasswordChangeScreenHandler : public BaseScreenHandler {
+ public:
+ explicit ActiveDirectoryPasswordChangeScreenHandler(
+ CoreOobeView* core_oobe_view);
+ ~ActiveDirectoryPasswordChangeScreenHandler() override;
+
+ // BaseScreenHandler implementation:
+ void DeclareLocalizedValues(
+ ::login::LocalizedValuesBuilder* builder) override;
+ void Initialize() override;
+
+ // 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|. Uses |delegate| to
+ // compelete authentication process.
+ void ShowScreen(const std::string& username,
+ SigninScreenHandlerDelegate* delegate);
+
+ private:
+ // Shows the screen with the error message corresponding to |error|.
+ void ShowScreenWithError(int error);
+
+ // Callback called by AuthPolicyLoginHelper::AuthenticateUser with results and
+ // error code. (see AuthPolicyLoginHelper::AuthenticateUser)
+ void OnAuthFinished(
+ const std::string& username,
+ const Key& key,
+ authpolicy::ErrorType error,
+ const authpolicy::ActiveDirectoryAccountInfo& account_info);
+
+ // Helper to call AuthPolicyClient and cancel calls if needed. Used to change
+ // password on the Active Directory server.
+ std::unique_ptr<AuthPolicyLoginHelper> authpolicy_login_helper_;
+
+ // Non-owned. Used to complete authentication process.
+ SigninScreenHandlerDelegate* delegate_ = nullptr;
+
+ // Non-owned. Used to display signin error.
+ CoreOobeView* core_oobe_view_ = nullptr;
+
+ base::WeakPtrFactory<ActiveDirectoryPasswordChangeScreenHandler>
+ weak_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryPasswordChangeScreenHandler);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_ACTIVE_DIRECTORY_PASSWORD_CHANGE_SCREEN_HANDLER_H_
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 aca69389faf..aabc6bf80dd 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
@@ -79,8 +79,7 @@ void BaseWebUIHandler::ShowScreenWithData(OobeScreen screen,
base::DictionaryValue screen_params;
screen_params.SetString("id", GetOobeScreenName(screen));
if (data) {
- screen_params.SetWithoutPathExpansion("data",
- base::MakeUnique<base::Value>(*data));
+ screen_params.SetKey("data", data->Clone());
}
web_ui()->CallJavascriptFunctionUnsafe("cr.ui.Oobe.showScreen",
screen_params);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc
index 643edd3bb30..ea484c63a2f 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc
@@ -8,7 +8,6 @@
#include <string>
#include <utility>
-#include "ash/system/devicetype_utils.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/metrics/histogram_macros.h"
@@ -43,6 +42,7 @@
#include "services/device/public/interfaces/wake_lock_provider.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/base/text/bytes_formatting.h"
+#include "ui/chromeos/devicetype_utils.h"
namespace {
@@ -324,19 +324,19 @@ void EncryptionMigrationScreenHandler::DeclareLocalizedValues(
::login::LocalizedValuesBuilder* builder) {
builder->Add("migrationReadyTitle", IDS_ENCRYPTION_MIGRATION_READY_TITLE);
builder->Add("migrationReadyDescription",
- ash::SubstituteChromeOSDeviceType(
+ ui::SubstituteChromeOSDeviceType(
IDS_ENCRYPTION_MIGRATION_READY_DESCRIPTION));
builder->Add("migrationMigratingTitle",
IDS_ENCRYPTION_MIGRATION_MIGRATING_TITLE);
builder->Add("migrationMigratingDescription",
- ash::SubstituteChromeOSDeviceType(
+ ui::SubstituteChromeOSDeviceType(
IDS_ENCRYPTION_MIGRATION_MIGRATING_DESCRIPTION));
builder->Add("migrationProgressLabel",
IDS_ENCRYPTION_MIGRATION_PROGRESS_LABEL);
builder->Add("migrationBatteryWarningLabel",
IDS_ENCRYPTION_MIGRATION_BATTERY_WARNING_LABEL);
builder->Add("migrationAskChargeMessage",
- ash::SubstituteChromeOSDeviceType(
+ ui::SubstituteChromeOSDeviceType(
IDS_ENCRYPTION_MIGRATION_ASK_CHARGE_MESSAGE));
builder->Add("migrationNecessaryBatteryLevelLabel",
IDS_ENCRYPTION_MIGRATION_NECESSARY_BATTERY_LEVEL_MESSAGE);
@@ -346,7 +346,7 @@ void EncryptionMigrationScreenHandler::DeclareLocalizedValues(
builder->Add("migrationFailedSubtitle",
IDS_ENCRYPTION_MIGRATION_FAILED_SUBTITLE);
builder->Add("migrationFailedMessage",
- ash::SubstituteChromeOSDeviceType(
+ ui::SubstituteChromeOSDeviceType(
IDS_ENCRYPTION_MIGRATION_FAILED_MESSAGE));
builder->Add("migrationNospaceWarningLabel",
IDS_ENCRYPTION_MIGRATION_NOSPACE_WARNING_LABEL);
@@ -782,7 +782,8 @@ void EncryptionMigrationScreenHandler::MaybeStopForcingMigration() {
// |mode_| will be START_MIGRATION if migration was forced by user policy.
// If an incomplete migration is being resumed, it would be RESUME_MIGRATION.
// We only want to disable auto-starting migration in the first case.
- if (mode_ == EncryptionMigrationMode::START_MIGRATION)
+ if (mode_ == EncryptionMigrationMode::START_MIGRATION ||
+ mode_ == EncryptionMigrationMode::START_MINIMAL_MIGRATION)
CallJS("setIsResuming", false);
}
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 0499e1d1c0b..6abc19d48f6 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
@@ -6,7 +6,6 @@
#include <algorithm>
-#include "ash/system/devicetype_utils.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_util.h"
@@ -35,6 +34,7 @@
#include "google_apis/gaia/gaia_urls.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "ui/base/l10n/l10n_util.h"
+#include "ui/chromeos/devicetype_utils.h"
namespace chromeos {
namespace {
@@ -204,7 +204,7 @@ void EnrollmentScreenHandler::ShowEnrollmentSpinnerScreen() {
void EnrollmentScreenHandler::ShowAttestationBasedEnrollmentSuccessScreen(
const std::string& enterprise_domain) {
- CallJS("showAttestationBasedEnrollmentSuccess", ash::GetChromeOSDeviceName(),
+ CallJS("showAttestationBasedEnrollmentSuccess", ui::GetChromeOSDeviceName(),
enterprise_domain);
}
@@ -393,7 +393,7 @@ void EnrollmentScreenHandler::DeclareLocalizedValues(
builder->Add("oauthEnrollNextBtn", IDS_OFFLINE_LOGIN_NEXT_BUTTON_TEXT);
builder->Add("oauthEnrollSkip", IDS_ENTERPRISE_ENROLLMENT_SKIP);
builder->AddF("oauthEnrollSuccess", IDS_ENTERPRISE_ENROLLMENT_SUCCESS,
- ash::GetChromeOSDeviceName());
+ ui::GetChromeOSDeviceName());
builder->Add("oauthEnrollDeviceInformation",
IDS_ENTERPRISE_ENROLLMENT_DEVICE_INFORMATION);
builder->Add("oauthEnrollExplainAttributeLink",
@@ -659,7 +659,7 @@ void EnrollmentScreenHandler::ShowError(int message_id, bool retry) {
void EnrollmentScreenHandler::ShowErrorForDevice(int message_id, bool retry) {
ShowErrorMessage(
- l10n_util::GetStringFUTF8(message_id, ash::GetChromeOSDeviceName()),
+ l10n_util::GetStringFUTF8(message_id, ui::GetChromeOSDeviceName()),
retry);
}
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 a13f4aea87f..28de6f39ea5 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
@@ -124,10 +124,6 @@ class EnrollmentScreenHandler
// enrollment sign-in page.
bool IsEnrollmentScreenHiddenByError() const;
- // Helper function to wait for AD password written to a pipe.
- void OnPasswordPipeReady(const std::string& machine_name,
- const std::string& user_name,
- base::ScopedFD password_fd);
// Handler callback from AuthPolicyClient.
void HandleAdDomainJoin(const std::string& machine_name,
const std::string& user_name,
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc
index af75d9e1805..b8d7f9d35a7 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/error_screen_handler.cc
@@ -4,13 +4,13 @@
#include "chrome/browser/ui/webui/chromeos/login/error_screen_handler.h"
-#include "ash/system/devicetype_utils.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "chrome/browser/chromeos/login/screens/error_screen.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"
#include "ui/strings/grit/ui_strings.h"
namespace {
@@ -70,11 +70,11 @@ void ErrorScreenHandler::RegisterMessages() {
void ErrorScreenHandler::DeclareLocalizedValues(
::login::LocalizedValuesBuilder* builder) {
- builder->Add("deviceType", ash::GetChromeOSDeviceName());
+ builder->Add("deviceType", ui::GetChromeOSDeviceName());
builder->Add("loginErrorTitle", IDS_LOGIN_ERROR_TITLE);
builder->Add("rollbackErrorTitle", IDS_RESET_SCREEN_REVERT_ERROR);
builder->Add("signinOfflineMessageBody",
- ash::SubstituteChromeOSDeviceType(IDS_LOGIN_OFFLINE_MESSAGE));
+ ui::SubstituteChromeOSDeviceType(IDS_LOGIN_OFFLINE_MESSAGE));
builder->Add("kioskOfflineMessageBody", IDS_KIOSK_OFFLINE_MESSAGE);
builder->Add("kioskOnlineTitle", IDS_LOGIN_NETWORK_RESTORED_TITLE);
builder->Add("kioskOnlineMessageBody", IDS_KIOSK_ONLINE_MESSAGE);
@@ -91,7 +91,7 @@ void ErrorScreenHandler::DeclareLocalizedValues(
IDS_LOGIN_MAYBE_CAPTIVE_PORTAL_NETWORK_SELECT);
builder->Add("signinProxyMessageText", IDS_LOGIN_PROXY_ERROR_MESSAGE);
builder->Add("updateOfflineMessageBody",
- ash::SubstituteChromeOSDeviceType(IDS_UPDATE_OFFLINE_MESSAGE));
+ ui::SubstituteChromeOSDeviceType(IDS_UPDATE_OFFLINE_MESSAGE));
builder->Add("updateProxyMessageText", IDS_UPDATE_PROXY_ERROR_MESSAGE);
builder->AddF("localStateErrorText0", IDS_LOCAL_STATE_ERROR_TEXT_0,
IDS_SHORT_PRODUCT_NAME);
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 e7b59027eb4..8c2c588b741 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
@@ -4,7 +4,6 @@
#include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
-#include "ash/system/devicetype_utils.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/feature_list.h"
@@ -28,6 +27,7 @@
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/io_thread.h"
+#include "chrome/browser/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/signin/signin_utils.h"
@@ -53,6 +53,8 @@
#include "google_apis/gaia/gaia_urls.h"
#include "ui/base/ime/chromeos/input_method_manager.h"
#include "ui/base/ime/chromeos/input_method_util.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/chromeos/devicetype_utils.h"
using content::BrowserThread;
namespace em = enterprise_management;
@@ -236,10 +238,14 @@ GaiaScreenHandler::GaiaContext::GaiaContext() {}
GaiaScreenHandler::GaiaScreenHandler(
CoreOobeView* core_oobe_view,
- const scoped_refptr<NetworkStateInformer>& network_state_informer)
+ const scoped_refptr<NetworkStateInformer>& network_state_informer,
+ ActiveDirectoryPasswordChangeScreenHandler*
+ active_directory_password_change_screen_handler)
: BaseScreenHandler(kScreenId),
network_state_informer_(network_state_informer),
core_oobe_view_(core_oobe_view),
+ active_directory_password_change_screen_handler_(
+ active_directory_password_change_screen_handler),
weak_factory_(this) {
DCHECK(network_state_informer_.get());
set_call_js_prefix(kJsScreenPath);
@@ -436,7 +442,7 @@ void GaiaScreenHandler::DeclareLocalizedValues(
IDS_LOGIN_FATAL_ERROR_TRY_AGAIN_BUTTON);
builder->AddF("loginWelcomeMessage", IDS_LOGIN_WELCOME_MESSAGE,
- ash::GetChromeOSDeviceTypeResourceId());
+ ui::GetChromeOSDeviceTypeResourceId());
builder->Add("offlineLoginEmail", IDS_OFFLINE_LOGIN_EMAIL);
builder->Add("offlineLoginPassword", IDS_OFFLINE_LOGIN_PASSWORD);
builder->Add("offlineLoginInvalidEmail", IDS_OFFLINE_LOGIN_INVALID_EMAIL);
@@ -459,6 +465,19 @@ void GaiaScreenHandler::DeclareLocalizedValues(
builder->Add("adAuthWelcomeMessage", IDS_AD_DOMAIN_AUTH_WELCOME_MESSAGE);
builder->Add("adAuthLoginUsername", IDS_AD_AUTH_LOGIN_USER);
builder->Add("adLoginPassword", IDS_AD_LOGIN_PASSWORD);
+
+ builder->Add("adPassChangeOldPasswordHint",
+ IDS_AD_PASSWORD_CHANGE_OLD_PASSWORD_HINT);
+ builder->Add("adPassChangeNewPasswordHint",
+ IDS_AD_PASSWORD_CHANGE_NEW_PASSWORD_HINT);
+ builder->Add("adPassChangeRepeatNewPasswordHint",
+ IDS_AD_PASSWORD_CHANGE_REPEAT_NEW_PASSWORD_HINT);
+ builder->Add("adPassChangeOldPasswordError",
+ IDS_AD_PASSWORD_CHANGE_INVALID_PASSWORD_ERROR);
+ builder->Add("adPassChangeNewPasswordRejected",
+ IDS_AD_PASSWORD_CHANGE_NEW_PASSWORD_REJECTED_SHORT_ERROR);
+ builder->Add("adPassChangePasswordsMismatch",
+ IDS_AD_PASSWORD_CHANGE_PASSWORDS_MISMATCH_ERROR);
}
void GaiaScreenHandler::Initialize() {
@@ -487,8 +506,6 @@ void GaiaScreenHandler::RegisterMessages() {
&GaiaScreenHandler::HandleAuthExtensionLoaded);
AddCallback("completeAdAuthentication",
&GaiaScreenHandler::HandleCompleteAdAuthentication);
- AddCallback("completeAdPasswordChange",
- &GaiaScreenHandler::HandleCompleteAdPasswordChange);
AddCallback("cancelAdAuthentication",
&GaiaScreenHandler::HandleCancelActiveDirectoryAuth);
}
@@ -579,6 +596,9 @@ void GaiaScreenHandler::DoAdAuth(
const Key& key,
authpolicy::ErrorType error,
const authpolicy::ActiveDirectoryAccountInfo& account_info) {
+ if (error != authpolicy::ERROR_NONE)
+ authpolicy_login_helper_->CancelRequestsAndRestart();
+
switch (error) {
case authpolicy::ERROR_NONE: {
DCHECK(account_info.has_account_id() &&
@@ -597,35 +617,25 @@ void GaiaScreenHandler::DoAdAuth(
break;
}
case authpolicy::ERROR_PASSWORD_EXPIRED:
- core_oobe_view_->ShowActiveDirectoryPasswordChangeScreen(username);
+ DCHECK(active_directory_password_change_screen_handler_);
+ active_directory_password_change_screen_handler_->ShowScreen(username,
+ Delegate());
break;
case authpolicy::ERROR_PARSE_UPN_FAILED:
case authpolicy::ERROR_BAD_USER_NAME:
CallJS("invalidateAd", username,
static_cast<int>(ActiveDirectoryErrorState::BAD_USERNAME));
- return;
+ break;
case authpolicy::ERROR_BAD_PASSWORD:
CallJS("invalidateAd", username,
static_cast<int>(ActiveDirectoryErrorState::BAD_PASSWORD));
- case authpolicy::ERROR_UNKNOWN:
- case authpolicy::ERROR_DBUS_FAILURE:
- case authpolicy::ERROR_CANNOT_RESOLVE_KDC:
- case authpolicy::ERROR_KINIT_FAILED:
- case authpolicy::ERROR_NET_FAILED:
- case authpolicy::ERROR_SMBCLIENT_FAILED:
- case authpolicy::ERROR_PARSE_FAILED:
- case authpolicy::ERROR_PARSE_PREG_FAILED:
- case authpolicy::ERROR_BAD_GPOS:
- case authpolicy::ERROR_LOCAL_IO:
- case authpolicy::ERROR_NOT_JOINED:
- case authpolicy::ERROR_NOT_LOGGED_IN:
- case authpolicy::ERROR_STORE_POLICY_FAILED:
- LoadAuthExtension(true, false /* offline */);
break;
default:
- // TODO(rsorokin): Proper error handling.
DLOG(WARNING) << "Unhandled error code: " << error;
LoadAuthExtension(true, false /* offline */);
+ core_oobe_view_->ShowSignInError(
+ 0, l10n_util::GetStringUTF8(IDS_AD_AUTH_UNKNOWN_ERROR), std::string(),
+ HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
}
}
@@ -641,21 +651,6 @@ void GaiaScreenHandler::HandleCompleteAdAuthentication(
username, Key(password)));
}
-void GaiaScreenHandler::HandleCompleteAdPasswordChange(
- const std::string& username,
- const std::string& old_password,
- const std::string& new_password) {
- Delegate()->SetDisplayEmail(username);
- set_populated_email(username);
-
- DCHECK(authpolicy_login_helper_);
- authpolicy_login_helper_->AuthenticateUser(
- username, std::string() /* object_guid */,
- old_password + "\n" + new_password + "\n" + new_password,
- base::BindOnce(&GaiaScreenHandler::DoAdAuth, weak_factory_.GetWeakPtr(),
- username, Key(new_password)));
-}
-
void GaiaScreenHandler::HandleCancelActiveDirectoryAuth() {
DCHECK(authpolicy_login_helper_);
authpolicy_login_helper_->CancelRequestsAndRestart();
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 79f9fba2e76..b4a5a226599 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
@@ -14,19 +14,15 @@
#include "chrome/browser/chromeos/login/screens/gaia_view.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h"
-#include "chromeos/dbus/auth_policy_client.h"
+#include "chromeos/login/auth/authpolicy_login_helper.h"
#include "chromeos/network/portal_detector/network_portal_detector.h"
#include "net/base/net_errors.h"
class AccountId;
-namespace authpolicy {
-class ActiveDirectoryAccountInfo;
-}
-
namespace chromeos {
-class AuthPolicyLoginHelper;
+class ActiveDirectoryPasswordChangeScreenHandler;
class Key;
class SigninScreenHandler;
class SigninScreenHandlerDelegate;
@@ -45,7 +41,9 @@ class GaiaScreenHandler : public BaseScreenHandler,
GaiaScreenHandler(
CoreOobeView* core_oobe_view,
- const scoped_refptr<NetworkStateInformer>& network_state_informer);
+ const scoped_refptr<NetworkStateInformer>& network_state_informer,
+ ActiveDirectoryPasswordChangeScreenHandler*
+ active_directory_password_change_screen_handler);
~GaiaScreenHandler() override;
// GaiaView:
@@ -106,10 +104,6 @@ class GaiaScreenHandler : public BaseScreenHandler,
void HandleCompleteAdAuthentication(const std::string& username,
const std::string& password);
- void HandleCompleteAdPasswordChange(const std::string& username,
- const std::string& old_password,
- const std::string& new_password);
-
void HandleCancelActiveDirectoryAuth();
void HandleUsingSAMLAPI();
@@ -149,11 +143,6 @@ class GaiaScreenHandler : public BaseScreenHandler,
authpolicy::ErrorType error,
const authpolicy::ActiveDirectoryAccountInfo& account_info);
- // Callback for writing password into pipe.
- void OnPasswordPipeReady(const std::string& username,
- const Key& key,
- base::ScopedFD password_fd);
-
// Show sign-in screen for the given credentials.
void ShowSigninScreenForTest(const std::string& username,
const std::string& password);
@@ -225,6 +214,9 @@ class GaiaScreenHandler : public BaseScreenHandler,
CoreOobeView* core_oobe_view_ = nullptr;
+ ActiveDirectoryPasswordChangeScreenHandler*
+ active_directory_password_change_screen_handler_ = nullptr;
+
// Email to pre-populate with.
std::string populated_email_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc
index deb66892b6e..daa26f82bf7 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_dropdown.cc
@@ -151,7 +151,7 @@ gfx::NativeWindow NetworkDropdown::GetNativeWindow() const {
}
void NetworkDropdown::OpenButtonOptions() {
- LoginDisplayHost::default_host()->OpenProxySettings();
+ LoginDisplayHost::default_host()->OpenProxySettings("");
}
bool NetworkDropdown::ShouldOpenButtonOptions() const {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc
index a4aa6db07d0..0cdd481417f 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_screen_handler.cc
@@ -169,6 +169,20 @@ void NetworkScreenHandler::DeclareLocalizedValues(
builder->Add("timezoneSectionTitle", IDS_TIMEZONE_SECTION_TITLE);
builder->Add("networkSectionTitle", IDS_NETWORK_SECTION_TITLE);
builder->Add("networkSectionHint", IDS_NETWORK_SECTION_HINT);
+ builder->Add("advancedOptionsSectionTitle",
+ IDS_OOBE_ADVANCED_OPTIONS_SCREEN_TITLE);
+ builder->Add("advancedOptionsEEBootstrappingTitle",
+ IDS_OOBE_ADVANCED_OPTIONS_EE_BOOTSTRAPPING_TITLE);
+ builder->Add("advancedOptionsEEBootstrappingSubtitle",
+ IDS_OOBE_ADVANCED_OPTIONS_EE_BOOTSTRAPPING_SUBTITLE);
+ builder->Add("advancedOptionsCFMSetupTitle",
+ IDS_OOBE_ADVANCED_OPTIONS_CFM_SETUP_TITLE);
+ builder->Add("advancedOptionsCFMSetupSubtitle",
+ IDS_OOBE_ADVANCED_OPTIONS_CFM_SETUP_SUBTITLE);
+ builder->Add("advancedOptionsDeviceRequisitionTitle",
+ IDS_OOBE_ADVANCED_OPTIONS_DEVICE_REQUISITION_TITLE);
+ builder->Add("advancedOptionsDeviceRequisitionSubtitle",
+ IDS_OOBE_ADVANCED_OPTIONS_DEVICE_REQUISITION_SUBTITLE);
builder->Add("languageDropdownTitle", IDS_LANGUAGE_DROPDOWN_TITLE);
builder->Add("languageDropdownLabel", IDS_LANGUAGE_DROPDOWN_LABEL);
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 7118b9f5ec4..93b5b1f5a49 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
@@ -13,7 +13,7 @@
#include "ui/display/display.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/screen.h"
-#include "ui/events/devices/device_data_manager.h"
+#include "ui/events/devices/input_device_manager.h"
#include "ui/events/devices/touchscreen_device.h"
using content::BrowserThread;
@@ -30,9 +30,16 @@ bool TouchSupportAvailable(const display::Display& display) {
// TODO(felixe): More context at crbug.com/738885
const uint16_t kDeviceIds[] = {0x0457, 0x266e};
+// Returns true if |vendor_id| is a valid vendor id that may be made the primary
+// display.
+bool IsWhiteListedVendorId(uint16_t vendor_id) {
+ return base::ContainsValue(kDeviceIds, vendor_id);
+}
+
} // namespace
-OobeDisplayChooser::OobeDisplayChooser() : weak_ptr_factory_(this) {}
+OobeDisplayChooser::OobeDisplayChooser()
+ : scoped_observer_(this), weak_ptr_factory_(this) {}
OobeDisplayChooser::~OobeDisplayChooser() {}
@@ -50,30 +57,50 @@ void OobeDisplayChooser::TryToPlaceUiOnTouchDisplay() {
if (primary_display.is_valid() && !TouchSupportAvailable(primary_display)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
- base::BindOnce(&OobeDisplayChooser::MoveToTouchDisplay,
+ base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay,
weak_ptr_factory_.GetWeakPtr()));
}
}
+void OobeDisplayChooser::MaybeMoveToTouchDisplay() {
+ ui::InputDeviceManager* input_device_manager =
+ ui::InputDeviceManager::GetInstance();
+ if (input_device_manager->AreDeviceListsComplete() &&
+ input_device_manager->AreTouchscreenTargetDisplaysValid()) {
+ MoveToTouchDisplay();
+ } else if (!scoped_observer_.IsObserving(input_device_manager)) {
+ scoped_observer_.Add(input_device_manager);
+ }
+}
+
void OobeDisplayChooser::MoveToTouchDisplay() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- const ui::DeviceDataManager* device_manager =
- ui::DeviceDataManager::GetInstance();
+ scoped_observer_.RemoveAll();
+
+ const ui::InputDeviceManager* input_device_manager =
+ ui::InputDeviceManager::GetInstance();
for (const ui::TouchscreenDevice& device :
- device_manager->GetTouchscreenDevices()) {
- if (!base::ContainsValue(kDeviceIds, device.vendor_id))
- continue;
-
- int64_t display_id =
- device_manager->GetTargetDisplayForTouchDevice(device.id);
- if (display_id == display::kInvalidDisplayId)
- continue;
-
- ash::Shell::Get()->window_tree_host_manager()->SetPrimaryDisplayId(
- display_id);
- break;
+ input_device_manager->GetTouchscreenDevices()) {
+ if (IsWhiteListedVendorId(device.vendor_id) &&
+ device.target_display_id != display::kInvalidDisplayId) {
+ ash::Shell::Get()->window_tree_host_manager()->SetPrimaryDisplayId(
+ device.target_display_id);
+ break;
+ }
}
}
+void OobeDisplayChooser::OnTouchDeviceAssociationChanged() {
+ MaybeMoveToTouchDisplay();
+}
+
+void OobeDisplayChooser::OnTouchscreenDeviceConfigurationChanged() {
+ MaybeMoveToTouchDisplay();
+}
+
+void OobeDisplayChooser::OnDeviceListsComplete() {
+ MaybeMoveToTouchDisplay();
+}
+
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h
index f7e2def693e..c606294f5d2 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h
@@ -7,21 +7,39 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "base/scoped_observer.h"
+#include "ui/events/devices/input_device_event_observer.h"
+
+namespace ui {
+class InputDeviceManager;
+}
namespace chromeos {
-class OobeDisplayChooser {
+class OobeDisplayChooser : public ui::InputDeviceEventObserver {
public:
OobeDisplayChooser();
- ~OobeDisplayChooser();
+ ~OobeDisplayChooser() override;
// Tries to put the OOBE UI on a connected touch display (if available).
// Must be called on the BrowserThread::UI thread.
void TryToPlaceUiOnTouchDisplay();
private:
+ // Calls MoveToTouchDisplay() if touch device list is ready, otherwise adds an
+ // observer that calls MoveToTouchDisplay() once ready.
+ void MaybeMoveToTouchDisplay();
+
void MoveToTouchDisplay();
+ // ui::InputDeviceEventObserver:
+ void OnTouchDeviceAssociationChanged() override;
+ void OnTouchscreenDeviceConfigurationChanged() override;
+ void OnDeviceListsComplete() override;
+
+ ScopedObserver<ui::InputDeviceManager, ui::InputDeviceEventObserver>
+ scoped_observer_;
+
base::WeakPtrFactory<OobeDisplayChooser> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(OobeDisplayChooser);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc
index 4291ab0269f..a0622268bf7 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc
@@ -41,6 +41,14 @@ class OobeDisplayChooserTest : public ash::AshTestBase {
manager->OnTouchscreenDevicesUpdated(devices);
}
+ // ash::AshTestBase:
+ void SetUp() override {
+ ash::AshTestBase::SetUp();
+ static_cast<ui::DeviceHotplugEventObserver*>(
+ ui::DeviceDataManager::GetInstance())
+ ->OnDeviceListsComplete();
+ }
+
private:
DISALLOW_COPY_AND_ASSIGN(OobeDisplayChooserTest);
};
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 6075be4c1f6..2884d5dc81d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
@@ -29,6 +29,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/ash_util.h"
#include "chrome/browser/ui/webui/about_ui.h"
+#include "chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/arc_kiosk_splash_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.h"
@@ -297,8 +298,24 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url)
AddScreenHandler(base::MakeUnique<UserBoardScreenHandler>());
+ policy::BrowserPolicyConnectorChromeOS* connector =
+ g_browser_process->platform_part()->browser_policy_connector_chromeos();
+ ActiveDirectoryPasswordChangeScreenHandler*
+ active_directory_password_change_screen_handler = nullptr;
+ // Create Active Directory password change screen for corresponding devices
+ // only.
+ if (connector->IsActiveDirectoryManaged()) {
+ auto password_change_handler =
+ base::MakeUnique<ActiveDirectoryPasswordChangeScreenHandler>(
+ core_handler_);
+ active_directory_password_change_screen_handler =
+ password_change_handler.get();
+ AddScreenHandler(std::move(password_change_handler));
+ }
+
AddScreenHandler(base::MakeUnique<GaiaScreenHandler>(
- core_handler_, network_state_informer_));
+ core_handler_, network_state_informer_,
+ active_directory_password_change_screen_handler));
auto signin_screen_handler = base::MakeUnique<SigninScreenHandler>(
network_state_informer_, error_screen, core_handler_,
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 cb9873a4b9f..935e46c504f 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
@@ -11,12 +11,10 @@
#include "ash/login/ui/login_constants.h"
#include "ash/public/interfaces/constants.mojom.h"
+#include "ash/public/interfaces/shutdown.mojom.h"
#include "ash/public/interfaces/tray_action.mojom.h"
#include "ash/shell.h"
-#include "ash/shutdown_reason.h"
-#include "ash/system/devicetype_utils.h"
#include "ash/wallpaper/wallpaper_controller.h"
-#include "ash/wm/lock_state_controller.h"
#include "base/bind.h"
#include "base/i18n/number_formatting.h"
#include "base/location.h"
@@ -37,6 +35,7 @@
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
+#include "chrome/browser/chromeos/ash_config.h"
#include "chrome/browser/chromeos/language_preferences.h"
#include "chrome/browser/chromeos/lock_screen_apps/state_controller.h"
#include "chrome/browser/chromeos/login/error_screens_histogram_helper.h"
@@ -105,6 +104,7 @@
#include "ui/base/ime/chromeos/input_method_manager.h"
#include "ui/base/ime/chromeos/input_method_util.h"
#include "ui/base/webui/web_ui_util.h"
+#include "ui/chromeos/devicetype_utils.h"
#include "ui/gfx/color_analysis.h"
#include "ui/gfx/color_utils.h"
@@ -145,12 +145,6 @@ const char kRequestShutdownFromLockScreenAppUnlockUi[] =
const char kRequestSignoutFromLockScreenAppUnlockUi[] =
"LOCK_SCREEN_APPS_UNLOCK_ACTION.SIGN_OUT";
-ash::WallpaperController* GetWallpaperController() {
- if (!ash::Shell::HasInstance())
- return nullptr;
- return ash::Shell::Get()->wallpaper_controller();
-}
-
class CallOnReturn {
public:
explicit CallOnReturn(const base::Closure& callback)
@@ -261,7 +255,7 @@ SigninScreenHandler::SigninScreenHandler(
->CapsLockIsEnabled()),
proxy_auth_dialog_reload_times_(kMaxGaiaReloadForProxyAuthDialog),
gaia_screen_handler_(gaia_screen_handler),
- touch_view_binding_(this),
+ tablet_mode_binding_(this),
histogram_helper_(new ErrorScreensHistogramHelper("Signin")),
lock_screen_apps_observer_(this),
weak_factory_(this) {
@@ -297,15 +291,15 @@ SigninScreenHandler::SigninScreenHandler(
content::ServiceManagerConnection::GetForProcess()
->GetConnector()
- ->BindInterface(ash::mojom::kServiceName, &touch_view_manager_ptr_);
- ash::mojom::TouchViewObserverPtr observer;
- touch_view_binding_.Bind(mojo::MakeRequest(&observer));
- touch_view_manager_ptr_->AddObserver(std::move(observer));
+ ->BindInterface(ash::mojom::kServiceName, &tablet_mode_manager_ptr_);
+ ash::mojom::TabletModeObserverPtr observer;
+ tablet_mode_binding_.Bind(mojo::MakeRequest(&observer));
+ tablet_mode_manager_ptr_->AddObserver(std::move(observer));
if (lock_screen_apps::StateController::IsEnabled())
lock_screen_apps_observer_.Add(lock_screen_apps::StateController::Get());
- ash::WallpaperController* wallpaper_controller = GetWallpaperController();
- DCHECK(wallpaper_controller);
- wallpaper_controller->AddObserver(this);
+ // TODO(wzang): Make this work under mash.
+ if (GetAshConfig() != ash::Config::MASH)
+ ash::Shell::Get()->wallpaper_controller()->AddObserver(this);
}
SigninScreenHandler::~SigninScreenHandler() {
@@ -325,9 +319,10 @@ SigninScreenHandler::~SigninScreenHandler() {
network_state_informer_->RemoveObserver(this);
proximity_auth::ScreenlockBridge::Get()->SetLockHandler(nullptr);
proximity_auth::ScreenlockBridge::Get()->SetFocusedUser(EmptyAccountId());
- ash::WallpaperController* wallpaper_controller = GetWallpaperController();
- if (wallpaper_controller)
- wallpaper_controller->RemoveObserver(this);
+
+ // TODO(wzang): Make this work under mash.
+ if (GetAshConfig() != ash::Config::MASH)
+ ash::Shell::Get()->wallpaper_controller()->RemoveObserver(this);
}
void SigninScreenHandler::DeclareLocalizedValues(
@@ -409,7 +404,7 @@ void SigninScreenHandler::DeclareLocalizedValues(
builder->Add("forgotOldPasswordButtonText",
IDS_LOGIN_PASSWORD_CHANGED_FORGOT_PASSWORD);
builder->AddF("passwordChangedTitle", IDS_LOGIN_PASSWORD_CHANGED_TITLE,
- ash::GetChromeOSDeviceName());
+ ui::GetChromeOSDeviceName());
builder->Add("passwordChangedProceedAnywayTitle",
IDS_LOGIN_PASSWORD_CHANGED_PROCEED_ANYWAY);
builder->Add("passwordChangedTryAgain", IDS_LOGIN_PASSWORD_CHANGED_TRY_AGAIN);
@@ -456,7 +451,7 @@ void SigninScreenHandler::DeclareLocalizedValues(
builder->Add("samlNotice", IDS_LOGIN_SAML_NOTICE);
builder->Add("samlNoticeWithVideo", IDS_LOGIN_SAML_NOTICE_WITH_VIDEO);
builder->AddF("confirmPasswordTitle", IDS_LOGIN_CONFIRM_PASSWORD_TITLE,
- ash::GetChromeOSDeviceName());
+ ui::GetChromeOSDeviceName());
builder->Add("manualPasswordTitle", IDS_LOGIN_MANUAL_PASSWORD_TITLE);
builder->Add("manualPasswordInputLabel",
IDS_LOGIN_MANUAL_PASSWORD_INPUT_LABEL);
@@ -486,14 +481,6 @@ void SigninScreenHandler::DeclareLocalizedValues(
builder->Add("unrecoverableCryptohomeErrorRecreatingProfile",
IDS_LOGIN_UNRECOVERABLE_CRYPTOHOME_ERROR_WAIT_MESSAGE);
- builder->Add("adEnterOldPasswordHint", IDS_AD_PASSWORD_CHANGE_OLD_PASSWORD);
- builder->Add("adEnterNewPasswordHint", IDS_AD_PASSWORD_CHANGE_NEW_PASSWORD);
- builder->Add("adRepeatNewPasswordHint",
- IDS_AD_PASSWORD_CHANGE_REPEAT_NEW_PASSWORD);
- builder->Add("adPasswordChangeMessage", IDS_AD_PASSWORD_CHANGE_MESSAGE);
- builder->Add("adOldPasswordError", IDS_AD_PASSWORD_CHANGE_INVALID_PASSWORD);
- builder->Add("adNewPasswordError", IDS_AD_PASSWORD_CHANGE_PASSWORDS_MISMATCH);
-
builder->Add("newLockScreenNoteButton",
IDS_LOGIN_NEW_LOCK_SCREEN_NOTE_BUTTON_TITLE);
}
@@ -538,8 +525,8 @@ void SigninScreenHandler::RegisterMessages() {
AddCallback("noPodFocused", &SigninScreenHandler::HandleNoPodFocused);
AddCallback("getPublicSessionKeyboardLayouts",
&SigninScreenHandler::HandleGetPublicSessionKeyboardLayouts);
- AddCallback("getTouchViewState",
- &SigninScreenHandler::HandleGetTouchViewState);
+ AddCallback("getTabletModeState",
+ &SigninScreenHandler::HandleGetTabletModeState);
AddCallback("logRemoveUserWarningShown",
&SigninScreenHandler::HandleLogRemoveUserWarningShown);
AddCallback("firstIncorrectPasswordAttempt",
@@ -893,11 +880,13 @@ void SigninScreenHandler::ReloadGaia(bool force_reload) {
void SigninScreenHandler::UpdateAccountPickerColors() {
color_utils::ColorProfile color_profile(color_utils::LumaRange::DARK,
color_utils::SaturationRange::MUTED);
- ash::WallpaperController* wallpaper_controller = GetWallpaperController();
- SkColor dark_muted_color =
- wallpaper_controller
- ? wallpaper_controller->GetProminentColor(color_profile)
- : ash::login_constants::kDefaultBaseColor;
+ SkColor dark_muted_color = ash::login_constants::kDefaultBaseColor;
+ // TODO(wzang): Make this work under mash.
+ if (GetAshConfig() != ash::Config::MASH) {
+ dark_muted_color =
+ ash::Shell::Get()->wallpaper_controller()->GetProminentColor(
+ color_profile);
+ }
if (dark_muted_color == ash::WallpaperController::kInvalidColor)
dark_muted_color = ash::login_constants::kDefaultBaseColor;
@@ -1109,9 +1098,9 @@ void SigninScreenHandler::SuspendDone(const base::TimeDelta& sleep_duration) {
}
}
-void SigninScreenHandler::OnTouchViewToggled(bool enabled) {
- touch_view_enabled_ = enabled;
- CallJSOrDefer("login.AccountPickerScreen.setTouchViewState", enabled);
+void SigninScreenHandler::OnTabletModeToggled(bool enabled) {
+ tablet_mode_enabled_ = enabled;
+ CallJSOrDefer("login.AccountPickerScreen.setTabletModeState", enabled);
}
void SigninScreenHandler::OnLockScreenNoteStateChanged(
@@ -1218,8 +1207,12 @@ void SigninScreenHandler::HandleOfflineLogin(const base::ListValue* args) {
}
void SigninScreenHandler::HandleShutdownSystem() {
- ash::Shell::Get()->lock_state_controller()->RequestShutdown(
- ash::ShutdownReason::LOGIN_SHUT_DOWN_BUTTON);
+ ash::mojom::ShutdownControllerPtr shutdown_controller;
+ content::ServiceManagerConnection::GetForProcess()
+ ->GetConnector()
+ ->BindInterface(ash::mojom::kServiceName, &shutdown_controller);
+
+ shutdown_controller->RequestShutdownFromLoginScreen();
}
void SigninScreenHandler::HandleRebootSystem() {
@@ -1339,7 +1332,7 @@ void SigninScreenHandler::HandleSignOutUser() {
}
void SigninScreenHandler::HandleOpenProxySettings() {
- LoginDisplayHost::default_host()->OpenProxySettings();
+ LoginDisplayHost::default_host()->OpenProxySettings("");
}
void SigninScreenHandler::HandleLoginVisible(const std::string& source) {
@@ -1494,8 +1487,8 @@ void SigninScreenHandler::HandleLaunchArcKioskApp(
delegate_->Login(context, SigninSpecifics());
}
-void SigninScreenHandler::HandleGetTouchViewState() {
- CallJS("login.AccountPickerScreen.setTouchViewState", touch_view_enabled_);
+void SigninScreenHandler::HandleGetTabletModeState() {
+ CallJS("login.AccountPickerScreen.setTabletModeState", tablet_mode_enabled_);
}
void SigninScreenHandler::HandleLogRemoveUserWarningShown() {
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 1a1a3498595..afca3d868cb 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h
@@ -10,7 +10,7 @@
#include <set>
#include <string>
-#include "ash/public/interfaces/touch_view.mojom.h"
+#include "ash/public/interfaces/tablet_mode.mojom.h"
#include "ash/wallpaper/wallpaper_controller_observer.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
@@ -238,7 +238,7 @@ class SigninScreenHandler
public NetworkStateInformer::NetworkStateInformerObserver,
public PowerManagerClient::Observer,
public input_method::ImeKeyboard::Observer,
- public ash::mojom::TouchViewObserver,
+ public ash::mojom::TabletModeObserver,
public lock_screen_apps::StateObserver,
public OobeUI::Observer,
public ash::WallpaperControllerObserver {
@@ -364,8 +364,8 @@ class SigninScreenHandler
// PowerManagerClient::Observer implementation:
void SuspendDone(const base::TimeDelta& sleep_duration) override;
- // ash::mojom::TouchView:
- void OnTouchViewToggled(bool enabled) override;
+ // ash::mojom::TabletMode:
+ void OnTabletModeToggled(bool enabled) override;
// lock_screen_apps::StateObserver:
void OnLockScreenNoteStateChanged(ash::mojom::TrayActionState state) override;
@@ -421,7 +421,7 @@ class SigninScreenHandler
void HandleLaunchArcKioskApp(const AccountId& app_account_id);
void HandleGetPublicSessionKeyboardLayouts(const AccountId& account_id,
const std::string& locale);
- void HandleGetTouchViewState();
+ void HandleGetTabletModeState();
void HandleLogRemoveUserWarningShown();
void HandleFirstIncorrectPasswordAttempt(const AccountId& account_id);
void HandleMaxIncorrectPasswordAttempts(const AccountId& account_id);
@@ -541,9 +541,9 @@ class SigninScreenHandler
// TODO(antrim@): remove this dependency.
GaiaScreenHandler* gaia_screen_handler_ = nullptr;
- mojo::Binding<ash::mojom::TouchViewObserver> touch_view_binding_;
- ash::mojom::TouchViewManagerPtr touch_view_manager_ptr_;
- bool touch_view_enabled_ = false;
+ mojo::Binding<ash::mojom::TabletModeObserver> tablet_mode_binding_;
+ ash::mojom::TabletModeManagerPtr tablet_mode_manager_ptr_;
+ bool tablet_mode_enabled_ = false;
// Input Method Engine state used at signin screen.
scoped_refptr<input_method::InputMethodManager::State> ime_state_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.cc
index 9e73b08bd18..f8715f2eee2 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.cc
@@ -32,6 +32,7 @@ WaitForContainerReadyScreenHandler::~WaitForContainerReadyScreenHandler() {
}
timer_.Stop();
+ arc::ArcSessionManager::Get()->RemoveObserver(this);
if (!profile_)
return;
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
@@ -97,6 +98,13 @@ void WaitForContainerReadyScreenHandler::OnPackageListInitialRefreshed() {
weak_ptr_factory_.GetWeakPtr()));
}
+void WaitForContainerReadyScreenHandler::OnArcErrorShowRequested(
+ ArcSupportHost::Error error) {
+ // Error occurs during Arc provisioning, close the screen.
+ if (screen_)
+ screen_->OnContainerError();
+}
+
void WaitForContainerReadyScreenHandler::Initialize() {
profile_ = ProfileManager::GetPrimaryUserProfile();
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
@@ -105,6 +113,7 @@ void WaitForContainerReadyScreenHandler::Initialize() {
if (!is_app_list_ready_)
prefs->AddObserver(this);
}
+ arc::ArcSessionManager::Get()->AddObserver(this);
if (!screen_ || !show_on_init_)
return;
@@ -116,7 +125,7 @@ void WaitForContainerReadyScreenHandler::Initialize() {
void WaitForContainerReadyScreenHandler::OnMaxContainerWaitTimeout() {
// TODO(updowndota): Add histogram to Voice Interaction OptIn flow.
if (screen_)
- screen_->OnContainerReady();
+ screen_->OnContainerError();
}
void WaitForContainerReadyScreenHandler::NotifyContainerReady() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.h
index d5b3c3cf491..7baa747d494 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/wait_for_container_ready_screen_handler.h
@@ -9,6 +9,7 @@
#include <string>
#include "base/macros.h"
+#include "chrome/browser/chromeos/arc/arc_session_manager.h"
#include "chrome/browser/chromeos/login/screens/wait_for_container_ready_screen_view.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
@@ -18,7 +19,8 @@ namespace chromeos {
class WaitForContainerReadyScreenHandler
: public BaseScreenHandler,
public WaitForContainerReadyScreenView,
- public ArcAppListPrefs::Observer {
+ public ArcAppListPrefs::Observer,
+ public arc::ArcSessionManager::Observer {
public:
WaitForContainerReadyScreenHandler();
~WaitForContainerReadyScreenHandler() override;
@@ -36,6 +38,9 @@ class WaitForContainerReadyScreenHandler
// ArcAppListPrefs::Observer overrides.
void OnPackageListInitialRefreshed() override;
+ // ArcSessionManager::Observer overrides.
+ void OnArcErrorShowRequested(ArcSupportHost::Error error) override;
+
private:
// BaseScreenHandler:
void Initialize() override;
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 ef5eb8131a1..39e49396aa8 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
@@ -27,6 +27,7 @@ struct {
{"networkListItemConnected", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTED},
{"networkListItemConnecting", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTING},
{"networkListItemConnectingTo", IDS_NETWORK_LIST_CONNECTING_TO},
+ {"networkListItemInitializing", IDS_NETWORK_LIST_INITIALIZING},
{"networkListItemNotConnected", IDS_NETWORK_LIST_NOT_CONNECTED},
{"vpnNameTemplate", IDS_NETWORK_LIST_THIRD_PARTY_VPN_NAME_TEMPLATE},
};
@@ -42,6 +43,173 @@ void AddLocalizedValuesToBuilder(::login::LocalizedValuesBuilder* builder) {
builder->Add(entry.name, entry.id);
}
+void AddDetailsLocalizedStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"OncTypeCellular", IDS_NETWORK_TYPE_MOBILE_DATA},
+ {"OncTypeEthernet", IDS_NETWORK_TYPE_ETHERNET},
+ {"OncTypeTether", IDS_NETWORK_TYPE_MOBILE_DATA},
+ {"OncTypeVPN", IDS_NETWORK_TYPE_VPN},
+ {"OncTypeWiFi", IDS_NETWORK_TYPE_WIFI},
+ {"OncTypeWiMAX", IDS_NETWORK_TYPE_WIMAX},
+ {"networkListItemConnected", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTED},
+ {"networkListItemConnecting", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTING},
+ {"networkListItemConnectingTo", IDS_NETWORK_LIST_CONNECTING_TO},
+ {"networkListItemNotConnected", IDS_NETWORK_LIST_NOT_CONNECTED},
+ {"vpnNameTemplate", IDS_NETWORK_LIST_THIRD_PARTY_VPN_NAME_TEMPLATE},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+}
+
+void AddOncLocalizedStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ // Thes strings are generated by prepending 'Onc' to the ONC property
+ // name. Any '.' in the property name is replaced with '-'. Properties
+ // with translatable enumerated values have the value appended after '_'.
+ {"OncCellular-APN-AccessPointName",
+ IDS_ONC_CELLULAR_APN_ACCESS_POINT_NAME},
+ {"OncCellular-APN-AccessPointName_none",
+ IDS_ONC_CELLULAR_APN_ACCESS_POINT_NAME_NONE},
+ {"OncCellular-APN-Password", IDS_ONC_CELLULAR_APN_PASSWORD},
+ {"OncCellular-APN-Username", IDS_ONC_CELLULAR_APN_USERNAME},
+ {"OncCellular-ActivationState", IDS_ONC_CELLULAR_ACTIVATION_STATE},
+ {"OncCellular-ActivationState_Activated",
+ IDS_ONC_CELLULAR_ACTIVATION_STATE_ACTIVATED},
+ {"OncCellular-ActivationState_Activating",
+ IDS_ONC_CELLULAR_ACTIVATION_STATE_ACTIVATING},
+ {"OncCellular-ActivationState_NotActivated",
+ IDS_ONC_CELLULAR_ACTIVATION_STATE_NOT_ACTIVATED},
+ {"OncCellular-ActivationState_PartiallyActivated",
+ IDS_ONC_CELLULAR_ACTIVATION_STATE_PARTIALLY_ACTIVATED},
+ {"OncCellular-Carrier", IDS_ONC_CELLULAR_CARRIER},
+ {"OncCellular-Family", IDS_ONC_CELLULAR_FAMILY},
+ {"OncCellular-FirmwareRevision", IDS_ONC_CELLULAR_FIRMWARE_REVISION},
+ {"OncCellular-HardwareRevision", IDS_ONC_CELLULAR_HARDWARE_REVISION},
+ {"OncCellular-HomeProvider-Code", IDS_ONC_CELLULAR_HOME_PROVIDER_CODE},
+ {"OncCellular-HomeProvider-Country",
+ IDS_ONC_CELLULAR_HOME_PROVIDER_COUNTRY},
+ {"OncCellular-HomeProvider-Name", IDS_ONC_CELLULAR_HOME_PROVIDER_NAME},
+ {"OncCellular-Manufacturer", IDS_ONC_CELLULAR_MANUFACTURER},
+ {"OncCellular-ModelID", IDS_ONC_CELLULAR_MODEL_ID},
+ {"OncCellular-NetworkTechnology", IDS_ONC_CELLULAR_NETWORK_TECHNOLOGY},
+ {"OncCellular-PRLVersion", IDS_ONC_CELLULAR_PRL_VERSION},
+ {"OncCellular-RoamingState", IDS_ONC_CELLULAR_ROAMING_STATE},
+ {"OncCellular-RoamingState_Home", IDS_ONC_CELLULAR_ROAMING_STATE_HOME},
+ {"OncCellular-RoamingState_Roaming",
+ IDS_ONC_CELLULAR_ROAMING_STATE_ROAMING},
+ {"OncCellular-ServingOperator-Code",
+ IDS_ONC_CELLULAR_SERVING_OPERATOR_CODE},
+ {"OncCellular-ServingOperator-Name",
+ IDS_ONC_CELLULAR_SERVING_OPERATOR_NAME},
+ {"OncConnected", IDS_ONC_CONNECTED},
+ {"OncConnecting", IDS_ONC_CONNECTING},
+ {"OncEAP-AnonymousIdentity", IDS_ONC_EAP_ANONYMOUS_IDENTITY},
+ {"OncEAP-Identity", IDS_ONC_EAP_IDENTITY},
+ {"OncEAP-Inner", IDS_ONC_EAP_INNER},
+ {"OncEAP-Inner_Automatic", IDS_ONC_EAP_INNER_AUTOMATIC},
+ {"OncEAP-Inner_CHAP", IDS_ONC_EAP_INNER_CHAP},
+ {"OncEAP-Inner_GTC", IDS_ONC_EAP_INNER_GTC},
+ {"OncEAP-Inner_MD5", IDS_ONC_EAP_INNER_MD5},
+ {"OncEAP-Inner_MSCHAP", IDS_ONC_EAP_INNER_MSCHAP},
+ {"OncEAP-Inner_MSCHAPv2", IDS_ONC_EAP_INNER_MSCHAPV2},
+ {"OncEAP-Inner_PAP", IDS_ONC_EAP_INNER_PAP},
+ {"OncEAP-Outer", IDS_ONC_EAP_OUTER},
+ {"OncEAP-Outer_LEAP", IDS_ONC_EAP_OUTER_LEAP},
+ {"OncEAP-Outer_PEAP", IDS_ONC_EAP_OUTER_PEAP},
+ {"OncEAP-Outer_EAP-TLS", IDS_ONC_EAP_OUTER_TLS},
+ {"OncEAP-Outer_EAP-TTLS", IDS_ONC_EAP_OUTER_TTLS},
+ {"OncEAP-Password", IDS_ONC_WIFI_PASSWORD},
+ {"OncEAP-SubjectMatch", IDS_ONC_EAP_SUBJECT_MATCH},
+ {"OncMacAddress", IDS_ONC_MAC_ADDRESS},
+ {"OncNotConnected", IDS_ONC_NOT_CONNECTED},
+ {"OncRestrictedConnectivity", IDS_ONC_RESTRICTED_CONNECTIVITY},
+ {"OncTether-BatteryPercentage", IDS_ONC_TETHER_BATTERY_PERCENTAGE},
+ {"OncTether-BatteryPercentage_Value",
+ IDS_ONC_TETHER_BATTERY_PERCENTAGE_VALUE},
+ {"OncTether-SignalStrength", IDS_ONC_TETHER_SIGNAL_STRENGTH},
+ {"OncTether-SignalStrength_Weak", IDS_ONC_TETHER_SIGNAL_STRENGTH_WEAK},
+ {"OncTether-SignalStrength_Okay", IDS_ONC_TETHER_SIGNAL_STRENGTH_OKAY},
+ {"OncTether-SignalStrength_Good", IDS_ONC_TETHER_SIGNAL_STRENGTH_GOOD},
+ {"OncTether-SignalStrength_Strong",
+ IDS_ONC_TETHER_SIGNAL_STRENGTH_STRONG},
+ {"OncTether-SignalStrength_VeryStrong",
+ IDS_ONC_TETHER_SIGNAL_STRENGTH_VERY_STRONG},
+ {"OncTether-Carrier", IDS_ONC_TETHER_CARRIER},
+ {"OncTether-Carrier_Unknown", IDS_ONC_TETHER_CARRIER_UNKNOWN},
+ {"OncVPN-Host", IDS_ONC_VPN_HOST},
+ {"OncVPN-L2TP-Username", IDS_ONC_VPN_L2TP_USERNAME},
+ {"OncVPN-OpenVPN-Username", IDS_ONC_VPN_OPEN_VPN_USERNAME},
+ {"OncVPN-ThirdPartyVPN-ProviderName",
+ IDS_ONC_VPN_THIRD_PARTY_VPN_PROVIDER_NAME},
+ {"OncVPN-Type", IDS_ONC_VPN_TYPE},
+ {"OncWiFi-Frequency", IDS_ONC_WIFI_FREQUENCY},
+ {"OncWiFi-Passphrase", IDS_ONC_WIFI_PASSWORD},
+ {"OncWiFi-SSID", IDS_ONC_WIFI_SSID},
+ {"OncWiFi-Security", IDS_ONC_WIFI_SECURITY},
+ {"OncWiFi-Security_None", IDS_ONC_WIFI_SECURITY_NONE},
+ {"OncWiFi-Security_WEP-PSK", IDS_ONC_WIFI_SECURITY_WEP},
+ {"OncWiFi-Security_WPA-EAP", IDS_ONC_WIFI_SECURITY_EAP},
+ {"OncWiFi-Security_WPA-PSK", IDS_ONC_WIFI_SECURITY_PSK},
+ {"OncWiFi-Security_WEP-8021X", IDS_ONC_WIFI_SECURITY_EAP},
+ {"OncWiFi-SignalStrength", IDS_ONC_WIFI_SIGNAL_STRENGTH},
+ {"OncWiMAX-EAP-Identity", IDS_ONC_WIMAX_EAP_IDENTITY},
+ {"Oncipv4-Gateway", IDS_ONC_IPV4_GATEWAY},
+ {"Oncipv4-IPAddress", IDS_ONC_IPV4_ADDRESS},
+ {"Oncipv4-RoutingPrefix", IDS_ONC_IPV4_ROUTING_PREFIX},
+ {"Oncipv6-IPAddress", IDS_ONC_IPV6_ADDRESS},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+}
+
+void AddConfigLocalizedStrings(content::WebUIDataSource* html_source) {
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"networkProxy", IDS_SETTINGS_INTERNET_NETWORK_PROXY_PROXY},
+ {"networkProxyAddException",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_ADD_EXCEPTION},
+ {"networkProxyAllowShared",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_ALLOW_SHARED},
+ {"networkProxyAllowSharedWarningTitle",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_ALLOW_SHARED_WARNING_TITLE},
+ {"networkProxyAllowSharedWarningMessage",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_ALLOW_SHARED_WARNING_MESSAGE},
+ {"networkProxyAutoConfig",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_AUTO_CONFIG},
+ {"networkProxyConnectionType",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_CONNECTION_TYPE},
+ {"networkProxyEnforcedPolicy",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_ENFORCED_POLICY},
+ {"networkProxyExceptionList",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_EXCEPTION_LIST},
+ {"networkProxyFtp", IDS_SETTINGS_INTERNET_NETWORK_PROXY_FTP_PROXY},
+ {"networkProxyHttp", IDS_SETTINGS_INTERNET_NETWORK_PROXY_HTTP_PROXY},
+ {"networkProxyPort", IDS_SETTINGS_INTERNET_NETWORK_PROXY_PORT},
+ {"networkProxyShttp", IDS_SETTINGS_INTERNET_NETWORK_PROXY_SHTTP_PROXY},
+ {"networkProxySocks", IDS_SETTINGS_INTERNET_NETWORK_PROXY_SOCKS_HOST},
+ {"networkProxyTypeDirect",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_DIRECT},
+ {"networkProxyTypeManual",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_MANUAL},
+ {"networkProxyTypePac", IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_PAC},
+ {"networkProxyTypeWpad", IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_WPAD},
+ {"networkProxyUseSame", IDS_SETTINGS_INTERNET_NETWORK_PROXY_USE_SAME},
+ {"networkAccessPoint", IDS_SETTINGS_INTERNET_NETWORK_ACCESS_POINT},
+ {"networkNameservers", IDS_SETTINGS_INTERNET_NETWORK_NAMESERVERS},
+ {"networkProxyWpad", IDS_SETTINGS_INTERNET_NETWORK_PROXY_WPAD},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
+}
+
} // namespace network_element
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h b/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h
index a16ead5b983..2c1154e57d8 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h
@@ -23,6 +23,13 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source);
// Same as AddLocalizedStrings but for a LocalizedValuesBuilder.
void AddLocalizedValuesToBuilder(::login::LocalizedValuesBuilder* builder);
+// Adds ONC strings used by the details dialog used in Settings and WebUI.
+void AddOncLocalizedStrings(content::WebUIDataSource* html_source);
+
+// Adds configuration strings used by the details dialog used in Settings and
+// WebUI.
+void AddConfigLocalizedStrings(content::WebUIDataSource* html_source);
+
} // namespace network_element
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
index dbf5a400ecd..a9202a4fc5c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
@@ -114,7 +114,7 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
dictionary.DeepCopy());
// Set the 'ServicePath' property for debugging.
- dictionary_copy->SetStringWithoutPathExpansion("ServicePath", service_path);
+ dictionary_copy->SetKey("ServicePath", base::Value(service_path));
// Set the device properties for debugging.
SetDeviceProperties(dictionary_copy.get());
@@ -131,8 +131,8 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
NET_LOG(ERROR) << "Shill Error: " << error_name << " guid=" << guid;
base::ListValue return_arg_list;
std::unique_ptr<base::DictionaryValue> dictionary;
- dictionary->SetStringWithoutPathExpansion(shill::kGuidProperty, guid);
- dictionary->SetStringWithoutPathExpansion("ShillError", error_name);
+ dictionary->SetKey(shill::kGuidProperty, base::Value(guid));
+ dictionary->SetKey("ShillError", base::Value(error_name));
return_arg_list.Append(std::move(dictionary));
web_ui()->CallJavascriptFunctionUnsafe("NetworkUI.getShillPropertiesResult",
return_arg_list);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.cc
index 33114a58fb5..53455aa271a 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.cc
@@ -4,140 +4,65 @@
#include "chrome/browser/ui/webui/chromeos/proxy_settings_ui.h"
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted_memory.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h"
-#include "chrome/browser/ui/webui/options/chromeos/proxy_handler.h"
-#include "chrome/common/chrome_constants.h"
+#include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
-#include "chromeos/chromeos_constants.h"
-#include "content/public/browser/url_data_source.h"
-#include "content/public/browser/web_contents.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
-#include "content/public/browser/web_ui_message_handler.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/webui/jstemplate_builder.h"
-#include "ui/base/webui/web_ui_util.h"
+#include "content/public/browser/web_ui_data_source.h"
-using content::WebContents;
-using content::WebUIMessageHandler;
+namespace chromeos {
namespace {
-class ProxySettingsHTMLSource : public content::URLDataSource {
- public:
- explicit ProxySettingsHTMLSource(base::DictionaryValue* localized_strings);
-
- // content::URLDataSource implementation.
- std::string GetSource() const override;
- void StartDataRequest(
- const std::string& path,
- const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
- const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override {
- return "text/html";
- }
- bool ShouldAddContentSecurityPolicy() const override { return false; }
- bool AllowCaching() const override {
- // Should not be cached to reflect dynamically-generated contents that
- // may depend on current settings.
- return false;
- }
-
- protected:
- ~ProxySettingsHTMLSource() override {}
-
- private:
- std::unique_ptr<base::DictionaryValue> localized_strings_;
-
- DISALLOW_COPY_AND_ASSIGN(ProxySettingsHTMLSource);
-};
-
-ProxySettingsHTMLSource::ProxySettingsHTMLSource(
- base::DictionaryValue* localized_strings)
- : localized_strings_(localized_strings) {
-}
-
-std::string ProxySettingsHTMLSource::GetSource() const {
- return chrome::kChromeUIProxySettingsHost;
-}
-
-void ProxySettingsHTMLSource::StartDataRequest(
- const std::string& path,
- const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
- const content::URLDataSource::GotDataCallback& callback) {
- const std::string& app_locale = g_browser_process->GetApplicationLocale();
- webui::SetLoadTimeDataDefaults(app_locale, localized_strings_.get());
- static const base::StringPiece html(
- ResourceBundle::GetSharedInstance().GetRawDataResource(
- IDR_PROXY_SETTINGS_HTML));
- std::string full_html = webui::GetI18nTemplateHtml(
- html, localized_strings_.get());
-
- callback.Run(base::RefCountedString::TakeString(&full_html));
+void AddInternetStrings(content::WebUIDataSource* html_source) {
+ // Add default strings first.
+ chromeos::network_element::AddLocalizedStrings(html_source);
+ chromeos::network_element::AddOncLocalizedStrings(html_source);
+ chromeos::network_element::AddConfigLocalizedStrings(html_source);
+ // Add additional strings and overrides needed by the dialog.
+ struct {
+ const char* name;
+ int id;
+ } localized_strings[] = {
+ {"networkButtonConnect", IDS_SETTINGS_INTERNET_BUTTON_CONNECT},
+ {"networkButtonDisconnect", IDS_SETTINGS_INTERNET_BUTTON_DISCONNECT},
+ {"networkIPAddress", IDS_SETTINGS_INTERNET_NETWORK_IP_ADDRESS},
+ {"networkSectionNetwork", IDS_SETTINGS_INTERNET_NETWORK_SECTION_NETWORK},
+ {"networkSectionProxy", IDS_SETTINGS_INTERNET_NETWORK_SECTION_PROXY},
+ {"networkIPConfigAuto", IDS_SETTINGS_INTERNET_NETWORK_IP_CONFIG_AUTO},
+ {"save", IDS_SAVE},
+ // Override for network_element::AddConfigLocalizedStrings
+ {"networkProxyConnectionType",
+ IDS_SETTINGS_INTERNET_NETWORK_PROXY_CONNECTION_TYPE_DIALOG},
+ };
+ for (const auto& entry : localized_strings)
+ html_source->AddLocalizedString(entry.name, entry.id);
}
} // namespace
-namespace chromeos {
-
ProxySettingsUI::ProxySettingsUI(content::WebUI* web_ui)
- : ui::WebDialogUI(web_ui), initialized_handlers_(false) {
- // |localized_strings| will be owned by ProxySettingsHTMLSource.
- base::DictionaryValue* localized_strings = new base::DictionaryValue();
-
- auto core_handler = base::MakeUnique<options::CoreChromeOSOptionsHandler>();
- core_handler_ = core_handler.get();
- web_ui->AddMessageHandler(std::move(core_handler));
- core_handler_->set_handlers_host(this);
- core_handler_->GetLocalizedValues(localized_strings);
+ : ui::WebDialogUI(web_ui) {
+ content::WebUIDataSource* source =
+ content::WebUIDataSource::Create(chrome::kChromeUIProxySettingsHost);
- auto proxy_handler = base::MakeUnique<options::ProxyHandler>();
- proxy_handler_ = proxy_handler.get();
- web_ui->AddMessageHandler(std::move(proxy_handler));
- proxy_handler_->GetLocalizedValues(localized_strings);
+ AddInternetStrings(source);
- internet_options_strings::RegisterLocalizedStrings(localized_strings);
- bool keyboard_driven_oobe =
- system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation();
- localized_strings->SetString("highlightStrength",
- keyboard_driven_oobe ? "strong" : "normal");
+ source->SetJsonPath("strings.js");
+ source->SetDefaultResource(IDR_PROXY_SETTINGS_HTML);
+ source->DisableContentSecurityPolicy();
- ProxySettingsHTMLSource* source =
- new ProxySettingsHTMLSource(localized_strings);
- Profile* profile = Profile::FromWebUI(web_ui);
- content::URLDataSource::Add(profile, source);
-}
+ source->AddResourcePath("internet_detail_dialog.html",
+ IDR_INTERNET_DETAIL_DIALOG_HTML);
+ source->AddResourcePath("internet_detail_dialog.js",
+ IDR_INTERNET_DETAIL_DIALOG_JS);
-ProxySettingsUI::~ProxySettingsUI() {
- // Uninitialize all registered handlers. The base class owns them and it will
- // eventually delete them.
- core_handler_->Uninitialize();
- proxy_handler_->Uninitialize();
+ content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
}
-void ProxySettingsUI::InitializeHandlers() {
- // A new web page DOM has been brought up in an existing renderer, causing
- // this method to be called twice. In that case, don't initialize the handlers
- // again. Compare with options_ui.cc.
- if (!initialized_handlers_) {
- core_handler_->InitializeHandler();
- proxy_handler_->InitializeHandler();
- initialized_handlers_ = true;
- }
- core_handler_->InitializePage();
- proxy_handler_->InitializePage();
-}
+ProxySettingsUI::~ProxySettingsUI() {}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.h b/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.h
index d0162c830cb..f0f23a82fe6 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/proxy_settings_ui.h
@@ -6,33 +6,19 @@
#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_PROXY_SETTINGS_UI_H_
#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
#include "ui/web_dialogs/web_dialog_ui.h"
namespace chromeos {
-namespace options {
-class CoreChromeOSOptionsHandler;
-class ProxyHandler;
-}
-
-// A WebUI to host proxy settings splitted from settings page for better
-// performance.
-class ProxySettingsUI : public ui::WebDialogUI,
- public ::options::OptionsPageUIHandlerHost {
+// A WebUI to host a subset of the network details page to allow setting of
+// proxy, IP address, and nameservers in the login screen. (Historically the
+// dialog only contained proxy settings).
+class ProxySettingsUI : public ui::WebDialogUI {
public:
explicit ProxySettingsUI(content::WebUI* web_ui);
~ProxySettingsUI() override;
private:
- // Overridden from OptionsPageUIHandlerHost:
- void InitializeHandlers() override;
-
- bool initialized_handlers_;
-
- options::ProxyHandler* proxy_handler_ = nullptr;
- options::CoreChromeOSOptionsHandler* core_handler_ = nullptr;
-
DISALLOW_COPY_AND_ASSIGN(ProxySettingsUI);
};
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 98871678f7e..bc44b7e8b4b 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
@@ -22,6 +22,7 @@
#include "chromeos/dbus/system_clock_client.h"
#include "chromeos/login/login_state.h"
#include "chromeos/settings/timezone_settings.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"
@@ -63,6 +64,10 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler,
web_ui()->CallJavascriptFunctionUnsafe("settime.TimeSetter.updateTime");
}
+ // UI actually shows real device timezone, but only allows changing the user
+ // timezone. If user timezone settings are different from system, this means
+ // that user settings are overriden and must be disabled. (And we will still
+ // show the actual device timezone.)
// system::TimezoneSettings::Observer:
void TimezoneChanged(const icu::TimeZone& timezone) override {
base::Value timezone_id(system::TimezoneSettings::GetTimezoneID(timezone));
@@ -94,7 +99,10 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler,
return;
}
- CrosSettings::Get()->SetString(kSystemTimezone, timezone_id);
+ Profile* profile = Profile::FromBrowserContext(
+ web_ui()->GetWebContents()->GetBrowserContext());
+ DCHECK(profile);
+ system::SetTimezoneFromUI(profile, timezone_id);
}
DISALLOW_COPY_AND_ASSIGN(SetTimeMessageHandler);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/sim_unlock_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/sim_unlock_ui.cc
index 766a7dab2cc..896d5cad6db 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/sim_unlock_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/sim_unlock_ui.cc
@@ -312,12 +312,13 @@ void SimUnlockUIHTMLSource::StartDataRequest(
l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_CHOOSE_PIN_TITLE));
strings.SetString("choosePinMessage",
l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_CHOOSE_PIN_MESSAGE));
- strings.SetString("newPin", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_NEW_PIN));
+ strings.SetString(
+ "newPin", l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_CHANGE_PIN_NEW_PIN));
strings.SetString("retypeNewPin", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_RETYPE_PIN));
- strings.SetString("pinsDontMatchMessage", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_PINS_DONT_MATCH_ERROR));
+ IDS_SIM_UNLOCK_CHANGE_PIN_RETYPE_PIN));
+ strings.SetString(
+ "pinsDontMatchMessage",
+ l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_PINS_DONT_MATCH_ERROR));
strings.SetString("noPukTriesLeft",
l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_NO_PUK_TRIES_LEFT_MESSAGE));
strings.SetString("simDisabledTitle",
@@ -325,12 +326,12 @@ void SimUnlockUIHTMLSource::StartDataRequest(
strings.SetString("simDisabledMessage",
l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_SIM_DISABLED_MESSAGE));
- strings.SetString("changePinTitle", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_TITLE));
+ strings.SetString("changePinTitle",
+ l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_CHANGE_PIN_TITLE));
strings.SetString("changePinMessage", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_MESSAGE));
- strings.SetString("oldPin", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_OLD_PIN));
+ IDS_SIM_UNLOCK_CHANGE_PIN_MESSAGE));
+ strings.SetString(
+ "oldPin", l10n_util::GetStringUTF16(IDS_SIM_UNLOCK_CHANGE_PIN_OLD_PIN));
const std::string& app_locale = g_browser_process->GetApplicationLocale();
webui::SetLoadTimeDataDefaults(app_locale, &strings);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc b/chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc
deleted file mode 100644
index 85a7c7cf159..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h"
-
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chromeos/settings/cros_settings_names.h"
-#include "components/user_manager/user_manager.h"
-#include "content/public/browser/web_ui_data_source.h"
-
-namespace chromeos {
-
-void AddAccountUITweaksLocalizedValues(
- base::DictionaryValue* localized_strings,
- Profile* profile) {
- DCHECK(localized_strings);
-
- std::string owner_email;
- CrosSettings::Get()->GetString(kDeviceOwner, &owner_email);
- // Translate owner's email to the display email.
- std::string display_email =
- user_manager::UserManager::Get()->GetUserDisplayEmail(
- AccountId::FromUserEmail(owner_email));
- localized_strings->SetString("ownerUserId", display_email);
-
- localized_strings->SetBoolean("currentUserIsOwner",
- ProfileHelper::IsOwnerProfile(profile));
-
- localized_strings->SetBoolean(
- "loggedInAsGuest", user_manager::UserManager::Get()->IsLoggedInAsGuest());
-
- localized_strings->SetBoolean(
- "loggedInAsSupervisedUser",
- user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser());
-
- localized_strings->SetBoolean(
- "loggedInAsPublicAccount",
- user_manager::UserManager::Get()->IsLoggedInAsPublicAccount());
-}
-
-void AddAccountUITweaksLocalizedValues(
- content::WebUIDataSource* source,
- Profile* profile) {
- DCHECK(source);
- base::DictionaryValue dict;
- AddAccountUITweaksLocalizedValues(&dict, profile);
- source->AddLocalizedStrings(dict);
-}
-
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.h b/chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.h
deleted file mode 100644
index 271085ac74c..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/ui_account_tweaks.h
+++ /dev/null
@@ -1,38 +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_UI_ACCOUNT_TWEAKS_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_UI_ACCOUNT_TWEAKS_H_
-
-#include "base/values.h"
-#include "base/compiler_specific.h"
-
-class Profile;
-
-namespace content {
-class WebUIDataSource;
-}
-
-namespace chromeos {
-
-/**
- * Fills given dictionary with account status data (whether current user is
- * owner/guest, id of the owner).
- * @param localized_strings non-null dictionary that will be filled.
- */
-void AddAccountUITweaksLocalizedValues(
- base::DictionaryValue* localized_strings, Profile* profile);
-
-/**
- * Fills given data source with account status data (whether current user is
- * owner/guest, id of the owner).
- * @param source non-null ui data source which localized values dictionary will
- * be filled.
- */
-void AddAccountUITweaksLocalizedValues(content::WebUIDataSource* source,
- Profile* profile);
-
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_UI_ACCOUNT_TWEAKS_H_
diff --git a/chromium/chrome/browser/ui/webui/components_ui.cc b/chromium/chrome/browser/ui/webui/components_ui.cc
index 2fd60e32d82..e7ec3d61196 100644
--- a/chromium/chrome/browser/ui/webui/components_ui.cc
+++ b/chromium/chrome/browser/ui/webui/components_ui.cc
@@ -31,7 +31,7 @@
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_CHROMEOS)
-#include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h"
+#include "components/user_manager/user_manager.h"
#endif
using content::WebUIMessageHandler;
@@ -51,12 +51,18 @@ content::WebUIDataSource* CreateComponentsUIHTMLSource(Profile* profile) {
source->AddLocalizedString("statusLabel", IDS_COMPONENTS_STATUS_LABEL);
source->AddLocalizedString("checkingLabel", IDS_COMPONENTS_CHECKING_LABEL);
+ source->AddBoolean(
+ "isGuest",
+#if defined(OS_CHROMEOS)
+ user_manager::UserManager::Get()->IsLoggedInAsGuest() ||
+ user_manager::UserManager::Get()->IsLoggedInAsPublicAccount()
+#else
+ profile->IsOffTheRecord()
+#endif
+ );
source->SetJsonPath("strings.js");
source->AddResourcePath("components.js", IDR_COMPONENTS_JS);
source->SetDefaultResource(IDR_COMPONENTS_HTML);
-#if defined(OS_CHROMEOS)
- chromeos::AddAccountUITweaksLocalizedValues(source, profile);
-#endif
return source;
}
diff --git a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h
index 7cc6b3bc96a..02c30f4882d 100644
--- a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h
+++ b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h
@@ -10,7 +10,7 @@
#include <map>
#include <string>
-#include "base/id_map.h"
+#include "base/containers/id_map.h"
#include "base/macros.h"
#include "base/strings/string16.h"
@@ -55,7 +55,7 @@ class CookiesTreeModelUtil {
const base::string16& title);
private:
- using CookiesTreeNodeIdMap = IDMap<const CookieTreeNode*>;
+ using CookiesTreeNodeIdMap = base::IDMap<const CookieTreeNode*>;
using CookieTreeNodeMap = std::map<const CookieTreeNode*, int32_t>;
// Populate given |dict| with cookie tree node properties. |id_map| maps
diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc
index fb821773188..5ae56ba5828 100644
--- a/chromium/chrome/browser/ui/webui/devtools_ui.cc
+++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc
@@ -239,7 +239,7 @@ void DevToolsDataSource::StartRemoteDataRequest(
destination: GOOGLE_OWNED_SERVICE
}
policy {
- cookies_allowed: true
+ cookies_allowed: YES
cookies_store: "user"
setting: "This feature cannot be disabled by settings."
chrome_policy {
@@ -283,7 +283,7 @@ void DevToolsDataSource::StartCustomDataRequest(
destination: WEBSITE
}
policy {
- cookies_allowed: true
+ cookies_allowed: YES
cookies_store: "user"
setting: "This feature cannot be disabled by settings."
chrome_policy {
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 7a2aebd49be..4415eb9762f 100644
--- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc
@@ -4,6 +4,9 @@
#include "chrome/browser/ui/webui/domain_reliability_internals_ui.h"
+#include <string>
+#include <unordered_set>
+
#include "chrome/browser/domain_reliability/service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
@@ -20,7 +23,6 @@ DomainReliabilityInternalsUI::DomainReliabilityInternalsUI(
: content::WebUIController(web_ui) {
content::WebUIDataSource* html_source = content::WebUIDataSource::Create(
chrome::kChromeUIDomainReliabilityInternalsHost);
- html_source->SetJsonPath("strings.js");
html_source->AddResourcePath("domain_reliability_internals.css",
IDR_DOMAIN_RELIABILITY_INTERNALS_CSS);
html_source->AddResourcePath("domain_reliability_internals.js",
diff --git a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc
index 89cf68b124e..e45841f19d1 100644
--- a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc
+++ b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc
@@ -82,9 +82,9 @@ SiteEngagementUI::SiteEngagementUI(content::WebUI* web_ui)
content::WebUIDataSource::Create(chrome::kChromeUISiteEngagementHost));
source->AddResourcePath("site_engagement.js", IDR_SITE_ENGAGEMENT_JS);
source->AddResourcePath(
- "chrome/browser/engagement/site_engagement_details.mojom",
+ "chrome/browser/engagement/site_engagement_details.mojom.js",
IDR_SITE_ENGAGEMENT_MOJO_JS);
- source->AddResourcePath("url/mojo/url.mojom", IDR_URL_MOJO_JS);
+ source->AddResourcePath("url/mojo/url.mojom.js", IDR_URL_MOJO_JS);
source->SetDefaultResource(IDR_SITE_ENGAGEMENT_HTML);
source->UseGzip(std::unordered_set<std::string>());
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source.release());
diff --git a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc
index 7651f052ee2..604f60eaa0f 100644
--- a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.cc
@@ -149,39 +149,35 @@ void KioskAppsHandler::GetLocalizedValues(content::WebUIDataSource* source) {
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ADD_KIOSK_APP_BUTTON));
source->AddString(
"kioskOverlayTitle",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_OVERLAY_TITLE));
- source->AddString(
- "addKioskApp",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_ADD_APP));
+ l10n_util::GetStringUTF16(IDS_EXTENSIONS_KIOSK_OVERLAY_TITLE));
+ source->AddString("addKioskApp",
+ l10n_util::GetStringUTF16(IDS_EXTENSIONS_KIOSK_ADD_APP));
source->AddString(
"kioskAppIdEditHint",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_ADD_APP_HINT));
+ l10n_util::GetStringUTF16(IDS_EXTENSIONS_KIOSK_ADD_APP_HINT));
source->AddString(
"enableAutoLaunchButton",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_ENABLE_AUTO_LAUNCH));
+ l10n_util::GetStringUTF16(IDS_EXTENSIONS_KIOSK_ENABLE_AUTO_LAUNCH));
source->AddString(
"disableAutoLaunchButton",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_DISABLE_AUTO_LAUNCH));
- source->AddString(
- "autoLaunch",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_AUTO_LAUNCH));
- source->AddString(
- "invalidApp",
- l10n_util::GetStringUTF16(IDS_OPTIONS_KIOSK_INVALID_APP));
- source->AddString(
- "kioskDiableBailoutShortcutLabel",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_KIOSK_DISABLE_BAILOUT_SHORTCUT_LABEL));
+ l10n_util::GetStringUTF16(IDS_EXTENSIONS_KIOSK_DISABLE_AUTO_LAUNCH));
+ source->AddString("autoLaunch", l10n_util::GetStringUTF16(
+ IDS_EXTENSIONS_KIOSK_AUTO_LAUNCH));
+ source->AddString("invalidApp", l10n_util::GetStringUTF16(
+ IDS_EXTENSIONS_KIOSK_INVALID_APP));
+ source->AddString("kioskDiableBailoutShortcutLabel",
+ l10n_util::GetStringUTF16(
+ IDS_EXTENSIONS_KIOSK_DISABLE_BAILOUT_SHORTCUT_LABEL));
source->AddString(
"kioskDisableBailoutShortcutWarningBold",
l10n_util::GetStringUTF16(
- IDS_OPTIONS_KIOSK_DISABLE_BAILOUT_SHORTCUT_WARNING_BOLD));
+ IDS_EXTENSIONS_KIOSK_DISABLE_BAILOUT_SHORTCUT_WARNING_BOLD));
const base::string16 product_os_name =
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_OS_NAME);
source->AddString(
"kioskDisableBailoutShortcutWarning",
l10n_util::GetStringFUTF16(
- IDS_OPTIONS_KIOSK_DISABLE_BAILOUT_SHORTCUT_WARNING_FORMAT,
+ IDS_EXTENSIONS_KIOSK_DISABLE_BAILOUT_SHORTCUT_WARNING_FORMAT,
product_os_name));
source->AddString(
"kioskDisableBailoutShortcutConfirm",
diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_settings_handler.cc b/chromium/chrome/browser/ui/webui/extensions/extension_settings_handler.cc
index a62c8587add..b3c34254a83 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extension_settings_handler.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extension_settings_handler.cc
@@ -275,9 +275,8 @@ void ExtensionSettingsHandler::GetLocalizedValues(
source->AddString("ok", l10n_util::GetStringUTF16(IDS_OK));
// 'Bubble' text for the controlled-setting-indicator
- source->AddString(
- "extensionControlledSettingPolicy",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CONTROLLED_SETTING_POLICY));
+ source->AddString("extensionControlledSettingPolicy",
+ l10n_util::GetStringUTF16(IDS_CONTROLLED_SETTING_POLICY));
}
void ExtensionSettingsHandler::DidStartNavigation(
diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
index f6b72930024..009d70abbe5 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
@@ -109,6 +109,8 @@ content::WebUIDataSource* CreateMdExtensionsSource() {
// Add common strings.
source->AddLocalizedString("close", IDS_CLOSE);
+ source->AddLocalizedString("ok", IDS_OK);
+ source->AddLocalizedString("cancel", IDS_CANCEL);
// Add extension-specific strings.
source->AddLocalizedString("title",
@@ -207,6 +209,12 @@ content::WebUIDataSource* CreateMdExtensionsSource() {
IDS_EXTENSIONS_ERROR_NO_ERRORS_CODE_MESSAGE);
source->AddLocalizedString("packDialogTitle",
IDS_MD_EXTENSIONS_PACK_DIALOG_TITLE);
+ source->AddLocalizedString("packDialogWarningTitle",
+ IDS_MD_EXTENSIONS_PACK_DIALOG_WARNING_TITLE);
+ source->AddLocalizedString("packDialogErrorTitle",
+ IDS_MD_EXTENSIONS_PACK_DIALOG_ERROR_TITLE);
+ source->AddLocalizedString("packDialogProceedAnyway",
+ IDS_MD_EXTENSIONS_PACK_DIALOG_PROCEED_ANYWAY);
source->AddLocalizedString("packDialogBrowse",
IDS_MD_EXTENSIONS_PACK_DIALOG_BROWSE_BUTTON);
source->AddLocalizedString(
@@ -252,10 +260,6 @@ content::WebUIDataSource* CreateMdExtensionsSource() {
GURL(extension_urls::GetWebstoreExtensionsCategoryURL()),
g_browser_process->GetApplicationLocale()).spec()));
- source->AddResourcePath("animation_helper.html",
- IDR_MD_EXTENSIONS_ANIMATION_HELPER_HTML);
- source->AddResourcePath("animation_helper.js",
- IDR_MD_EXTENSIONS_ANIMATION_HELPER_JS);
source->AddResourcePath("code_section.html",
IDR_MD_EXTENSIONS_CODE_SECTION_HTML);
source->AddResourcePath("code_section.js", IDR_MD_EXTENSIONS_CODE_SECTION_JS);
@@ -298,6 +302,10 @@ content::WebUIDataSource* CreateMdExtensionsSource() {
source->AddResourcePath("pack_dialog.html",
IDR_MD_EXTENSIONS_PACK_DIALOG_HTML);
source->AddResourcePath("pack_dialog.js", IDR_MD_EXTENSIONS_PACK_DIALOG_JS);
+ source->AddResourcePath("pack_dialog_alert.html",
+ IDR_MD_EXTENSIONS_PACK_DIALOG_ALERT_HTML);
+ source->AddResourcePath("pack_dialog_alert.js",
+ IDR_MD_EXTENSIONS_PACK_DIALOG_ALERT_JS);
source->AddResourcePath("service.html", IDR_MD_EXTENSIONS_SERVICE_HTML);
source->AddResourcePath("service.js", IDR_MD_EXTENSIONS_SERVICE_JS);
source->AddResourcePath("shortcut_input.html",
@@ -312,6 +320,9 @@ content::WebUIDataSource* CreateMdExtensionsSource() {
source->AddResourcePath("strings.html", IDR_MD_EXTENSIONS_STRINGS_HTML);
source->AddResourcePath("toolbar.html", IDR_MD_EXTENSIONS_TOOLBAR_HTML);
source->AddResourcePath("toolbar.js", IDR_MD_EXTENSIONS_TOOLBAR_JS);
+ source->AddResourcePath("view_manager.html",
+ IDR_MD_EXTENSIONS_VIEW_MANAGER_HTML);
+ source->AddResourcePath("view_manager.js", IDR_MD_EXTENSIONS_VIEW_MANAGER_JS);
source->SetDefaultResource(IDR_MD_EXTENSIONS_EXTENSIONS_HTML);
return source;
diff --git a/chromium/chrome/browser/ui/webui/help/help_handler.cc b/chromium/chrome/browser/ui/webui/help/help_handler.cc
deleted file mode 100644
index 2a26fa57a75..00000000000
--- a/chromium/chrome/browser/ui/webui/help/help_handler.cc
+++ /dev/null
@@ -1,766 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/help/help_handler.h"
-
-#include <stddef.h>
-
-#include <string>
-
-#include "ash/system/devicetype_utils.h"
-#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/i18n/message_formatter.h"
-#include "base/location.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/task_scheduler/post_task.h"
-#include "base/time/time.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/lifetime/application_lifetime.h"
-#include "chrome/browser/obsolete_system/obsolete_system.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_commands.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/chrome_pages.h"
-#include "chrome/browser/upgrade_detector.h"
-#include "chrome/common/channel_info.h"
-#include "chrome/common/chrome_content_client.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 "components/google/core/browser/google_util.h"
-#include "components/policy/core/common/policy_namespace.h"
-#include "components/policy/policy_constants.h"
-#include "components/strings/grit/components_chromium_strings.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/version_info/version_info.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "v8/include/v8-version-string.h"
-
-#if defined(OS_CHROMEOS)
-#include "base/files/file_util_proxy.h"
-#include "base/i18n/time_formatting.h"
-#include "base/sys_info.h"
-#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h"
-#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/chromeos/image_source.h"
-#include "chrome/browser/ui/webui/help/help_utils_chromeos.h"
-#include "chrome/browser/ui/webui/help/version_updater_chromeos.h"
-#include "chromeos/chromeos_switches.h"
-#include "chromeos/dbus/dbus_thread_manager.h"
-#include "chromeos/dbus/power_manager_client.h"
-#include "chromeos/system/statistics_provider.h"
-#include "components/prefs/pref_service.h"
-#include "components/user_manager/user_manager.h"
-#endif
-
-using base::ListValue;
-using content::BrowserThread;
-
-namespace {
-
-#if defined(OS_CHROMEOS)
-
-// Directory containing the regulatory labels for supported regions.
-const char kRegulatoryLabelsDirectory[] = "regulatory_labels";
-
-// File names of the image file and the file containing alt text for the label.
-const char kRegulatoryLabelImageFilename[] = "label.png";
-const char kRegulatoryLabelTextFilename[] = "label.txt";
-
-// Default region code to use if there's no label for the VPD region code.
-const char kDefaultRegionCode[] = "us";
-
-struct RegulatoryLabel {
- const std::string label_text;
- const std::string image_url;
-};
-
-// 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() {
- // Old help page does not support interactive-updates over cellular, so just
- // sets |interactive| to false to make its behavior the same as before.
- if (help_utils_chromeos::IsUpdateOverCellularAllowed(
- false /* interactive */)) {
- return l10n_util::GetStringUTF16(IDS_UPGRADE_NETWORK_LIST_CELLULAR_ALLOWED);
- } else {
- return l10n_util::GetStringUTF16(
- IDS_UPGRADE_NETWORK_LIST_CELLULAR_DISALLOWED);
- }
-}
-
-// Returns true if the device is enterprise managed, false otherwise.
-bool IsEnterpriseManaged() {
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- return connector->IsEnterpriseManaged();
-}
-
-// Returns true if current user can change channel, false otherwise.
-bool CanChangeChannel(Profile* profile) {
- bool value = false;
- chromeos::CrosSettings::Get()->GetBoolean(chromeos::kReleaseChannelDelegated,
- &value);
-
- // On a managed machine we delegate this setting to the users of the same
- // domain only if the policy value is "domain".
- if (IsEnterpriseManaged()) {
- if (!value)
- return false;
- // Get the currently logged in user and strip the domain part only.
- std::string domain = "";
- const user_manager::User* user =
- profile ? chromeos::ProfileHelper::Get()->GetUserByProfile(profile)
- : nullptr;
- std::string email =
- user ? user->GetAccountId().GetUserEmail() : std::string();
- size_t at_pos = email.find('@');
- if (at_pos != std::string::npos && at_pos + 1 < email.length())
- domain = email.substr(email.find('@') + 1);
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- return domain == connector->GetEnterpriseEnrollmentDomain();
- } else {
- chromeos::OwnerSettingsServiceChromeOS* service =
- chromeos::OwnerSettingsServiceChromeOSFactory::GetInstance()
- ->GetForBrowserContext(profile);
- // On non managed machines we have local owner who is the only one to change
- // anything. Ensure that ReleaseChannelDelegated is false.
- if (service && service->IsOwner())
- return !value;
- }
- return false;
-}
-
-// Returns the path of the regulatory labels directory for a given region, if
-// found. Must be called from the blocking pool.
-base::FilePath GetRegulatoryLabelDirForRegion(const std::string& region) {
- // Generate the path under the asset dir or URL host to the regulatory files
- // for the region, e.g., "regulatory_labels/us/".
- const base::FilePath region_path =
- base::FilePath(kRegulatoryLabelsDirectory).AppendASCII(region);
-
- // Check for file existence starting in /usr/share/chromeos-assets/, e.g.,
- // "/usr/share/chromeos-assets/regulatory_labels/us/label.png".
- const base::FilePath asset_dir(chrome::kChromeOSAssetPath);
- if (base::PathExists(asset_dir.Append(region_path)
- .AppendASCII(kRegulatoryLabelImageFilename))) {
- return region_path;
- }
-
- return base::FilePath();
-}
-
-// Finds the directory for the regulatory label, using the VPD region code.
-// Also tries "us" as a fallback region. Must be called from the blocking pool.
-base::FilePath FindRegulatoryLabelDir() {
- std::string region;
- base::FilePath region_path;
- // Use the VPD region code to find the label dir.
- if (chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
- "region", &region) && !region.empty()) {
- region_path = GetRegulatoryLabelDirForRegion(region);
- }
-
- // Try the fallback region code if no directory was found.
- if (region_path.empty() && region != kDefaultRegionCode)
- region_path = GetRegulatoryLabelDirForRegion(kDefaultRegionCode);
-
- return region_path;
-}
-
-// Reads the file containing the regulatory label text, if found, relative to
-// the asset directory. Must be called from the blocking pool.
-std::string ReadRegulatoryLabelText(const base::FilePath& path) {
- base::FilePath text_path(chrome::kChromeOSAssetPath);
- text_path = text_path.Append(path);
- text_path = text_path.AppendASCII(kRegulatoryLabelTextFilename);
-
- std::string contents;
- if (base::ReadFileToString(text_path, &contents))
- return contents;
- return std::string();
-}
-#endif // defined(OS_CHROMEOS)
-
-} // namespace
-
-HelpHandler::HelpHandler()
- : policy_registrar_(
- g_browser_process->policy_service(),
- policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())),
- apply_changes_from_upgrade_observer_(false),
- weak_factory_(this) {
- UpgradeDetector::GetInstance()->AddObserver(this);
-}
-
-HelpHandler::~HelpHandler() {
- UpgradeDetector::GetInstance()->RemoveObserver(this);
-}
-
-void HelpHandler::GetLocalizedValues(base::DictionaryValue* localized_strings) {
- struct L10nResources {
- const char* name;
- int ids;
- };
-
- static L10nResources resources[] = {
- {"aboutTitle", IDS_ABOUT_TITLE},
-#if defined(OS_CHROMEOS)
- {"aboutProductTitle", IDS_PRODUCT_OS_NAME},
-#else
- {"aboutProductTitle", IDS_PRODUCT_NAME},
-#endif
- {"aboutProductDescription", IDS_ABOUT_PRODUCT_DESCRIPTION},
- {"relaunch", IDS_RELAUNCH_BUTTON},
-#if defined(OS_CHROMEOS)
- {"relaunchAndPowerwash", IDS_RELAUNCH_AND_POWERWASH_BUTTON},
-#endif
- {"productName", IDS_PRODUCT_NAME},
- {"updateCheckStarted", IDS_UPGRADE_CHECK_STARTED},
- {"updating", IDS_UPGRADE_UPDATING},
-#if defined(OS_CHROMEOS) || defined(OS_WIN)
- {"updateDisabledByPolicy", IDS_UPGRADE_DISABLED_BY_POLICY},
-#endif // defined(OS_CHROMEOS) || defined(OS_WIN)
-#if defined(OS_CHROMEOS)
- {"updateButton", IDS_UPGRADE_BUTTON},
- {"updatingChannelSwitch", IDS_UPGRADE_UPDATING_CHANNEL_SWITCH},
-#endif
- {"updateAlmostDone", IDS_UPGRADE_SUCCESSFUL_RELAUNCH},
-#if defined(OS_CHROMEOS)
- {"successfulChannelSwitch", IDS_UPGRADE_SUCCESSFUL_CHANNEL_SWITCH},
-#endif
- {"getHelpWithChrome", IDS_GET_HELP_USING_CHROME},
- {"reportAnIssue", IDS_REPORT_AN_ISSUE},
-#if defined(OS_CHROMEOS)
- {"platform", IDS_PLATFORM_LABEL},
- {"arcVersion", IDS_ARC_VERSION_LABEL},
- {"firmware", IDS_ABOUT_PAGE_FIRMWARE},
- {"showMoreInfo", IDS_SHOW_MORE_INFO},
- {"hideMoreInfo", IDS_HIDE_MORE_INFO},
- {"channel", IDS_ABOUT_PAGE_CHANNEL},
- {"stable", IDS_ABOUT_PAGE_CHANNEL_STABLE},
- {"beta", IDS_ABOUT_PAGE_CHANNEL_BETA},
- {"dev", IDS_ABOUT_PAGE_CHANNEL_DEVELOPMENT},
- {"devChannelDisclaimer", IDS_ABOUT_PAGE_CHANNEL_DEVELOPMENT_DISCLAIMER},
- {"channel-changed", IDS_ABOUT_PAGE_CHANNEL_CHANGED},
- {"currentChannelStable", IDS_ABOUT_PAGE_CURRENT_CHANNEL_STABLE},
- {"currentChannelBeta", IDS_ABOUT_PAGE_CURRENT_CHANNEL_BETA},
- {"currentChannelDev", IDS_ABOUT_PAGE_CURRENT_CHANNEL_DEV},
- {"currentChannel", IDS_ABOUT_PAGE_CURRENT_CHANNEL},
- {"channelChangeButton", IDS_ABOUT_PAGE_CHANNEL_CHANGE_BUTTON},
- {"channelChangeDisallowedMessage",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_DISALLOWED_MESSAGE},
- {"channelChangePageTitle", IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_TITLE},
- {"channelChangePagePowerwashTitle",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_POWERWASH_TITLE},
- {"channelChangePagePowerwashMessage",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_POWERWASH_MESSAGE},
- {"channelChangePageDelayedChangeTitle",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_DELAYED_CHANGE_TITLE},
- {"channelChangePageUnstableTitle",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_UNSTABLE_TITLE},
- {"channelChangePagePowerwashButton",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_POWERWASH_BUTTON},
- {"channelChangePageChangeButton",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_CHANGE_BUTTON},
- {"channelChangePageCancelButton",
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_CANCEL_BUTTON},
- {"userAgent", IDS_VERSION_UI_USER_AGENT},
- {"commandLine", IDS_VERSION_UI_COMMAND_LINE},
- {"buildDate", IDS_VERSION_UI_BUILD_DATE},
-#endif
-#if defined(OS_MACOSX) || defined(OS_WIN)
- {"learnMore", IDS_LEARN_MORE},
-#endif
-#if defined(OS_MACOSX)
- {"promote", IDS_ABOUT_CHROME_PROMOTE_UPDATER},
-#endif
- };
-
- for (size_t i = 0; i < arraysize(resources); ++i) {
- localized_strings->SetString(resources[i].name,
- l10n_util::GetStringUTF16(resources[i].ids));
- }
-
-#if defined(OS_CHROMEOS)
- localized_strings->SetString("upToDate", ash::SubstituteChromeOSDeviceType(
- IDS_UPGRADE_UP_TO_DATE));
-#else
- localized_strings->SetString("upToDate", l10n_util::GetStringUTF16(
- IDS_UPGRADE_UP_TO_DATE));
-#endif
-
- localized_strings->SetString("updateObsoleteSystem",
- ObsoleteSystem::LocalizedObsoleteString());
- localized_strings->SetString("updateObsoleteSystemURL",
- ObsoleteSystem::GetLinkURL());
-
- localized_strings->SetString(
- "browserVersion",
- l10n_util::GetStringFUTF16(IDS_ABOUT_PRODUCT_VERSION,
- BuildBrowserVersionString()));
-
- localized_strings->SetString(
- "productCopyright",
- base::i18n::MessageFormatter::FormatWithNumberedArgs(
- l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COPYRIGHT),
- base::Time::Now()));
-
- base::string16 license = l10n_util::GetStringFUTF16(
- IDS_VERSION_UI_LICENSE, base::ASCIIToUTF16(chrome::kChromiumProjectURL),
- base::ASCIIToUTF16(chrome::kChromeUICreditsURL));
- localized_strings->SetString("productLicense", license);
-
-#if defined(OS_CHROMEOS)
- base::string16 os_license = l10n_util::GetStringFUTF16(
- IDS_ABOUT_CROS_VERSION_LICENSE,
- base::ASCIIToUTF16(chrome::kChromeUIOSCreditsURL));
- localized_strings->SetString("productOsLicense", os_license);
-
- base::string16 product_name = l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME);
- localized_strings->SetString(
- "channelChangePageDelayedChangeMessage",
- l10n_util::GetStringFUTF16(
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_DELAYED_CHANGE_MESSAGE,
- product_name));
- localized_strings->SetString(
- "channelChangePageUnstableMessage",
- l10n_util::GetStringFUTF16(
- IDS_ABOUT_PAGE_CHANNEL_CHANGE_PAGE_UNSTABLE_MESSAGE,
- product_name));
-
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(
- chromeos::switches::kDisableNewChannelSwitcherUI)) {
- localized_strings->SetBoolean("disableNewChannelSwitcherUI", true);
- }
-
- localized_strings->SetString(
- "eolLearnMore", l10n_util::GetStringFUTF16(
- IDS_ABOUT_PAGE_EOL_LEARN_MORE,
- base::ASCIIToUTF16(chrome::kEolNotificationURL)));
-#endif
-
- base::string16 tos = l10n_util::GetStringFUTF16(
- IDS_ABOUT_TERMS_OF_SERVICE, base::UTF8ToUTF16(chrome::kChromeUITermsURL));
- localized_strings->SetString("productTOS", tos);
-
- localized_strings->SetString("jsEngine", "V8");
- localized_strings->SetString("jsEngineVersion", V8_VERSION_STRING);
-
- localized_strings->SetString("userAgentInfo", GetUserAgent());
-
- base::CommandLine::StringType command_line =
- base::CommandLine::ForCurrentProcess()->GetCommandLineString();
- localized_strings->SetString("commandLineInfo", command_line);
-}
-
-void HelpHandler::RegisterMessages() {
- version_updater_.reset(VersionUpdater::Create(web_ui()->GetWebContents()));
- apply_changes_from_upgrade_observer_ = true;
- policy_registrar_.Observe(
- policy::key::kDeviceAutoUpdateDisabled,
- base::Bind(&HelpHandler::OnDeviceAutoUpdatePolicyChanged,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback("onPageLoaded",
- base::Bind(&HelpHandler::OnPageLoaded, base::Unretained(this)));
- web_ui()->RegisterMessageCallback("relaunchNow",
- base::Bind(&HelpHandler::RelaunchNow, base::Unretained(this)));
- web_ui()->RegisterMessageCallback("openFeedbackDialog",
- base::Bind(&HelpHandler::OpenFeedbackDialog, base::Unretained(this)));
- web_ui()->RegisterMessageCallback("openHelpPage",
- base::Bind(&HelpHandler::OpenHelpPage, base::Unretained(this)));
-#if defined(OS_CHROMEOS)
- web_ui()->RegisterMessageCallback("setChannel",
- base::Bind(&HelpHandler::SetChannel, base::Unretained(this)));
- web_ui()->RegisterMessageCallback("relaunchAndPowerwash",
- base::Bind(&HelpHandler::RelaunchAndPowerwash, base::Unretained(this)));
- web_ui()->RegisterMessageCallback("requestUpdate",
- base::Bind(&HelpHandler::RequestUpdate, base::Unretained(this)));
-#endif
-#if defined(OS_MACOSX)
- web_ui()->RegisterMessageCallback("promoteUpdater",
- base::Bind(&HelpHandler::PromoteUpdater, base::Unretained(this)));
-#endif
-
-#if defined(OS_CHROMEOS)
- // Handler for the product label image, which will be shown if available.
- content::URLDataSource::Add(Profile::FromWebUI(web_ui()),
- new chromeos::ImageSource());
-#endif
-}
-
-void HelpHandler::OnUpgradeRecommended() {
- if (apply_changes_from_upgrade_observer_) {
- // A version update is installed and ready to go. Refresh the UI so the
- // correct state will be shown.
- RequestUpdate(nullptr);
- }
-}
-
-// static
-base::string16 HelpHandler::BuildBrowserVersionString() {
- std::string version = version_info::GetVersionNumber();
-
- std::string modifier = chrome::GetChannelString();
- if (!modifier.empty())
- version += " " + modifier;
-
-#if defined(ARCH_CPU_64_BITS)
- version += " (64-bit)";
-#endif
-
- return base::UTF8ToUTF16(version);
-}
-
-void HelpHandler::OnDeviceAutoUpdatePolicyChanged(
- const base::Value* previous_policy,
- const base::Value* current_policy) {
- bool previous_auto_update_disabled = false;
- if (previous_policy)
- CHECK(previous_policy->GetAsBoolean(&previous_auto_update_disabled));
-
- bool current_auto_update_disabled = false;
- if (current_policy)
- CHECK(current_policy->GetAsBoolean(&current_auto_update_disabled));
-
- if (current_auto_update_disabled != previous_auto_update_disabled) {
- // Refresh the update status to refresh the status of the UI.
- RefreshUpdateStatus();
- }
-}
-
-void HelpHandler::RefreshUpdateStatus() {
- // On Chrome OS, do not check for an update automatically.
-#if defined(OS_CHROMEOS)
- static_cast<VersionUpdaterCros*>(version_updater_.get())->GetUpdateStatus(
- base::Bind(&HelpHandler::SetUpdateStatus, base::Unretained(this)));
-#else
- RequestUpdate(NULL);
-#endif
-}
-
-void HelpHandler::OnPageLoaded(const base::ListValue* args) {
-#if defined(OS_CHROMEOS)
- base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&chromeos::version_loader::GetVersion,
- chromeos::version_loader::VERSION_FULL),
- base::Bind(&HelpHandler::OnOSVersion, weak_factory_.GetWeakPtr()));
- base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&chromeos::version_loader::GetARCVersion),
- base::Bind(&HelpHandler::OnARCVersion, weak_factory_.GetWeakPtr()));
- base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&chromeos::version_loader::GetFirmware),
- base::Bind(&HelpHandler::OnOSFirmware, weak_factory_.GetWeakPtr()));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.updateEnableReleaseChannel",
- base::Value(CanChangeChannel(Profile::FromWebUI(web_ui()))));
-
- base::Time build_time = base::SysInfo::GetLsbReleaseTime();
- base::string16 build_date = base::TimeFormatFriendlyDate(build_time);
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setBuildDate",
- base::Value(build_date));
-#endif // defined(OS_CHROMEOS)
-
- RefreshUpdateStatus();
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.setObsoleteSystem",
- base::Value(ObsoleteSystem::IsObsoleteNowOrSoon()));
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.setObsoleteSystemEndOfTheLine",
- base::Value(ObsoleteSystem::IsObsoleteNowOrSoon() &&
- ObsoleteSystem::IsEndOfTheLine()));
-
-#if defined(OS_CHROMEOS)
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.updateIsEnterpriseManaged",
- base::Value(IsEnterpriseManaged()));
- // First argument to GetChannel() is a flag that indicates whether
- // current channel should be returned (if true) or target channel
- // (otherwise).
- version_updater_->GetChannel(true,
- base::Bind(&HelpHandler::OnCurrentChannel, weak_factory_.GetWeakPtr()));
- version_updater_->GetChannel(false,
- base::Bind(&HelpHandler::OnTargetChannel, weak_factory_.GetWeakPtr()));
-
- if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
- chromeos::switches::kDisableEolNotification)) {
- version_updater_->GetEolStatus(
- base::Bind(&HelpHandler::OnEolStatus, weak_factory_.GetWeakPtr()));
- }
-
- base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&FindRegulatoryLabelDir),
- base::Bind(&HelpHandler::OnRegulatoryLabelDirFound,
- weak_factory_.GetWeakPtr()));
-#endif
-}
-
-#if defined(OS_MACOSX)
-void HelpHandler::PromoteUpdater(const base::ListValue* args) {
- version_updater_->PromoteUpdater();
-}
-#endif
-
-void HelpHandler::RelaunchNow(const base::ListValue* args) {
- DCHECK(args->empty());
- chrome::AttemptRelaunch();
-}
-
-void HelpHandler::OpenFeedbackDialog(const base::ListValue* args) {
- DCHECK(args->empty());
- Browser* browser = chrome::FindBrowserWithWebContents(
- web_ui()->GetWebContents());
- chrome::OpenFeedbackDialog(browser,
- chrome::kFeedbackSourceOldSettingsAboutPage);
-}
-
-void HelpHandler::OpenHelpPage(const base::ListValue* args) {
- DCHECK(args->empty());
- Browser* browser = chrome::FindBrowserWithWebContents(
- web_ui()->GetWebContents());
- chrome::ShowHelp(browser, chrome::HELP_SOURCE_WEBUI);
-}
-
-#if defined(OS_CHROMEOS)
-
-void HelpHandler::SetChannel(const base::ListValue* args) {
- DCHECK(args->GetSize() == 2);
-
- if (!CanChangeChannel(Profile::FromWebUI(web_ui()))) {
- LOG(WARNING) << "Non-owner tried to change release track.";
- return;
- }
-
- base::string16 channel;
- bool is_powerwash_allowed;
- if (!args->GetString(0, &channel) ||
- !args->GetBoolean(1, &is_powerwash_allowed)) {
- LOG(ERROR) << "Can't parse SetChannel() args";
- return;
- }
-
- version_updater_->SetChannel(base::UTF16ToUTF8(channel),
- is_powerwash_allowed);
- if (user_manager::UserManager::Get()->IsCurrentUserOwner()) {
- // Check for update after switching release channel.
- version_updater_->CheckForUpdate(base::Bind(&HelpHandler::SetUpdateStatus,
- base::Unretained(this)),
- VersionUpdater::PromoteCallback());
- }
-}
-
-void HelpHandler::RelaunchAndPowerwash(const base::ListValue* args) {
- DCHECK(args->empty());
-
- if (IsEnterpriseManaged())
- return;
-
- PrefService* prefs = g_browser_process->local_state();
- prefs->SetBoolean(prefs::kFactoryResetRequested, true);
- prefs->CommitPendingWrite();
-
- // Perform sign out. Current chrome process will then terminate, new one will
- // be launched (as if it was a restart).
- chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
-}
-
-#endif // defined(OS_CHROMEOS)
-
-void HelpHandler::RequestUpdate(const base::ListValue* args) {
- VersionUpdater::PromoteCallback promote_callback;
- version_updater_->CheckForUpdate(
- base::Bind(&HelpHandler::SetUpdateStatus, base::Unretained(this)),
-#if defined(OS_MACOSX)
- base::Bind(&HelpHandler::SetPromotionState, base::Unretained(this)));
-#else
- VersionUpdater::PromoteCallback());
-#endif // OS_MACOSX
-}
-
-void HelpHandler::SetUpdateStatus(VersionUpdater::Status status,
- int progress,
- const std::string& /* version */,
- int64_t /* size */,
- const base::string16& message) {
- // Only UPDATING state should have progress set.
- DCHECK(status == VersionUpdater::UPDATING || progress == 0);
-
- std::string status_str;
- switch (status) {
- case VersionUpdater::CHECKING:
- status_str = "checking";
- break;
- case VersionUpdater::UPDATING:
- status_str = "updating";
- break;
- case VersionUpdater::NEARLY_UPDATED:
- status_str = "nearly_updated";
- break;
- case VersionUpdater::UPDATED:
- status_str = "updated";
- break;
- case VersionUpdater::FAILED:
- case VersionUpdater::FAILED_OFFLINE:
- case VersionUpdater::FAILED_CONNECTION_TYPE_DISALLOWED:
- // Old help page does not support update over cellular connection. Treat this
- // signal as FAILED.
- case VersionUpdater::NEED_PERMISSION_TO_UPDATE:
- status_str = "failed";
- break;
- case VersionUpdater::DISABLED:
- status_str = "disabled";
- break;
- case VersionUpdater::DISABLED_BY_ADMIN:
- status_str = "disabled_by_admin";
- break;
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setUpdateStatus",
- base::Value(status_str),
- base::Value(message));
-
- if (status == VersionUpdater::UPDATING) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setProgress",
- base::Value(progress));
- }
-
-#if defined(OS_CHROMEOS)
- if (status == VersionUpdater::FAILED_OFFLINE ||
- status == VersionUpdater::FAILED_CONNECTION_TYPE_DISALLOWED) {
- base::string16 types_msg = GetAllowedConnectionTypesMessage();
- if (!types_msg.empty()) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.setAndShowAllowedConnectionTypesMsg",
- base::Value(types_msg));
- } else {
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.showAllowedConnectionTypesMsg", base::Value(false));
- }
- } else {
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.showAllowedConnectionTypesMsg", base::Value(false));
- }
-#endif // defined(OS_CHROMEOS)
-}
-
-#if defined(OS_MACOSX)
-void HelpHandler::SetPromotionState(VersionUpdater::PromotionState state) {
- std::string state_str;
- switch (state) {
- case VersionUpdater::PROMOTE_HIDDEN:
- case VersionUpdater::PROMOTED:
- state_str = "hidden";
- break;
- case VersionUpdater::PROMOTE_ENABLED:
- state_str = "enabled";
- break;
- case VersionUpdater::PROMOTE_DISABLED:
- state_str = "disabled";
- break;
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setPromotionState",
- base::Value(state_str));
-}
-#endif // defined(OS_MACOSX)
-
-#if defined(OS_CHROMEOS)
-void HelpHandler::OnOSVersion(const std::string& version) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setOSVersion",
- base::Value(version));
-}
-
-void HelpHandler::OnARCVersion(const std::string& firmware) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setARCVersion",
- base::Value(firmware));
-}
-
-void HelpHandler::OnOSFirmware(const std::string& firmware) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setOSFirmware",
- base::Value(firmware));
-}
-
-void HelpHandler::OnCurrentChannel(const std::string& channel) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.updateCurrentChannel",
- base::Value(channel));
-}
-
-void HelpHandler::OnTargetChannel(const std::string& channel) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.updateTargetChannel",
- base::Value(channel));
-}
-
-void HelpHandler::OnRegulatoryLabelDirFound(const base::FilePath& path) {
- if (path.empty())
- return;
-
- base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&ReadRegulatoryLabelText, path),
- base::Bind(&HelpHandler::OnRegulatoryLabelTextRead,
- weak_factory_.GetWeakPtr()));
-
- // Send the image path to the WebUI.
- OnRegulatoryLabelImageFound(path.AppendASCII(kRegulatoryLabelImageFilename));
-}
-
-void HelpHandler::OnRegulatoryLabelImageFound(const base::FilePath& path) {
- std::string url = std::string("chrome://") + chrome::kChromeOSAssetHost +
- "/" + path.MaybeAsASCII();
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.setRegulatoryLabelPath",
- base::Value(url));
-}
-
-void HelpHandler::OnRegulatoryLabelTextRead(const std::string& text) {
- // Remove unnecessary whitespace.
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.setRegulatoryLabelText",
- base::Value(base::CollapseWhitespaceASCII(text, true)));
-}
-
-void HelpHandler::OnEolStatus(update_engine::EndOfLifeStatus status) {
- // Security only state is no longer supported.
- if (status == update_engine::EndOfLifeStatus::kSecurityOnly ||
- IsEnterpriseManaged()) {
- return;
- }
-
- if (status == update_engine::EndOfLifeStatus::kSupported) {
- web_ui()->CallJavascriptFunctionUnsafe("help.HelpPage.updateEolMessage",
- base::Value("device_supported"),
- base::Value(""));
- } else {
- web_ui()->CallJavascriptFunctionUnsafe(
- "help.HelpPage.updateEolMessage", base::Value("device_endoflife"),
- base::Value(l10n_util::GetStringUTF16(IDS_ABOUT_PAGE_EOL_EOL)));
- }
-}
-
-#endif // defined(OS_CHROMEOS)
diff --git a/chromium/chrome/browser/ui/webui/help/help_handler.h b/chromium/chrome/browser/ui/webui/help/help_handler.h
deleted file mode 100644
index 5aea40c2f0c..00000000000
--- a/chromium/chrome/browser/ui/webui/help/help_handler.h
+++ /dev/null
@@ -1,136 +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_HELP_HELP_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_HELP_HELP_HANDLER_H_
-
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/strings/string16.h"
-#include "build/build_config.h"
-#include "chrome/browser/ui/webui/help/version_updater.h"
-#include "chrome/browser/upgrade_observer.h"
-#include "components/policy/core/common/policy_service.h"
-#include "content/public/browser/web_ui_message_handler.h"
-
-#if defined(OS_CHROMEOS)
-#include "base/task/cancelable_task_tracker.h"
-#include "chromeos/system/version_loader.h"
-#include "third_party/cros_system_api/dbus/update_engine/dbus-constants.h"
-#endif // defined(OS_CHROMEOS)
-
-namespace base {
-class DictionaryValue;
-class FilePath;
-class ListValue;
-}
-
-// WebUI message handler for the help page.
-class HelpHandler : public content::WebUIMessageHandler,
- public UpgradeObserver {
- public:
- HelpHandler();
- ~HelpHandler() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // Adds string values for the UI to |localized_strings|.
- static void GetLocalizedValues(base::DictionaryValue* localized_strings);
-
- // UpgradeObserver implementation.
- void OnUpgradeRecommended() override;
-
- // Returns the browser version as a string.
- static base::string16 BuildBrowserVersionString();
-
- private:
- void OnDeviceAutoUpdatePolicyChanged(const base::Value* previous_policy,
- const base::Value* current_policy);
-
- // On ChromeOS, this gets the current update status. On other platforms, it
- // will request and perform an update (if one is available).
- void RefreshUpdateStatus();
-
- // Initializes querying values for the page.
- void OnPageLoaded(const base::ListValue* args);
-
-#if defined(OS_MACOSX)
- // Promotes the updater for all users.
- void PromoteUpdater(const base::ListValue* args);
-#endif
-
- // Relaunches the browser. |args| must be empty.
- void RelaunchNow(const base::ListValue* args);
-
- // Opens the feedback dialog. |args| must be empty.
- void OpenFeedbackDialog(const base::ListValue* args);
-
- // Opens the help page. |args| must be empty.
- void OpenHelpPage(const base::ListValue* args);
-
-#if defined(OS_CHROMEOS)
- // Sets the release track version.
- void SetChannel(const base::ListValue* args);
-
- // Performs relaunch and powerwash.
- void RelaunchAndPowerwash(const base::ListValue* args);
-#endif
-
- // Checks for and applies update.
- void RequestUpdate(const base::ListValue* args);
-
- // Callback method which forwards status updates to the page.
- void SetUpdateStatus(VersionUpdater::Status status,
- int progress,
- const std::string& version,
- int64_t size,
- const base::string16& fail_message);
-
-#if defined(OS_MACOSX)
- // Callback method which forwards promotion state to the page.
- void SetPromotionState(VersionUpdater::PromotionState state);
-#endif
-
-#if defined(OS_CHROMEOS)
- // Callbacks from VersionLoader.
- void OnOSVersion(const std::string& version);
- void OnARCVersion(const std::string& firmware);
- void OnOSFirmware(const std::string& firmware);
- void OnCurrentChannel(const std::string& channel);
- void OnTargetChannel(const std::string& channel);
-
- // Callback for when the directory with the regulatory label image and alt
- // text has been found.
- void OnRegulatoryLabelDirFound(const base::FilePath& path);
-
- // Callback for setting the regulatory label source.
- void OnRegulatoryLabelImageFound(const base::FilePath& path);
-
- // Callback for setting the regulatory label alt text.
- void OnRegulatoryLabelTextRead(const std::string& text);
-
- // Callback for setting the eol string text.
- void OnEolStatus(update_engine::EndOfLifeStatus status);
-#endif
-
- // Specialized instance of the VersionUpdater used to update the browser.
- std::unique_ptr<VersionUpdater> version_updater_;
-
- // Used to observe changes in the |kDeviceAutoUpdateDisabled| policy.
- policy::PolicyChangeRegistrar policy_registrar_;
-
- // If true changes to UpgradeObserver are applied, if false they are ignored.
- bool apply_changes_from_upgrade_observer_;
-
- // Used for callbacks.
- base::WeakPtrFactory<HelpHandler> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(HelpHandler);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_HELP_HELP_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.cc b/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.cc
index 068f3586a9a..46b3ad2c0e1 100644
--- a/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.cc
@@ -11,13 +11,8 @@
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/grit/generated_resources.h"
#include "chromeos/chromeos_switches.h"
-#include "chromeos/network/network_state.h"
-#include "chromeos/network/network_type_pattern.h"
#include "chromeos/settings/cros_settings_names.h"
-#include "third_party/cros_system_api/dbus/service_constants.h"
-#include "ui/base/l10n/l10n_util.h"
namespace help_utils_chromeos {
@@ -52,25 +47,4 @@ bool IsUpdateOverCellularAllowed(bool interactive) {
return false;
}
-base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) {
- const std::string type =
- network->IsUsingMobileData() ? shill::kTypeCellular : network->type();
- if (chromeos::NetworkTypePattern::Ethernet().MatchesType(type))
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_ETHERNET);
- if (type == shill::kTypeWifi)
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIFI);
- if (type == shill::kTypeWimax)
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIMAX);
- if (type == shill::kTypeBluetooth)
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_BLUETOOTH);
- if (type == shill::kTypeCellular ||
- chromeos::NetworkTypePattern::Tether().MatchesType(type)) {
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_MOBILE_DATA);
- }
- if (type == shill::kTypeVPN)
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_VPN);
- NOTREACHED();
- return base::string16();
-}
-
} // namespace help_utils_chromeos
diff --git a/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.h b/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.h
index ec388efd4bf..c022989ae2d 100644
--- a/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.h
+++ b/chromium/chrome/browser/ui/webui/help/help_utils_chromeos.h
@@ -5,12 +5,6 @@
#ifndef CHROME_BROWSER_UI_WEBUI_HELP_HELP_UTILS_CHROMEOS_H_
#define CHROME_BROWSER_UI_WEBUI_HELP_HELP_UTILS_CHROMEOS_H_
-#include "base/strings/string16.h"
-
-namespace chromeos {
-class NetworkState;
-}
-
namespace help_utils_chromeos {
// Returns true if updates over cellular networks are allowed. If |interactive|
@@ -20,9 +14,6 @@ namespace help_utils_chromeos {
// policy.
bool IsUpdateOverCellularAllowed(bool interactive);
-// Returns localized name for the connection |type|.
-base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network);
-
} // namespace help_utils_chromeos
#endif // CHROME_BROWSER_UI_WEBUI_HELP_HELP_UTILS_CHROMEOS_H_
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater.h b/chromium/chrome/browser/ui/webui/help/version_updater.h
index d36b26fb472..bbf32c32a9f 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater.h
+++ b/chromium/chrome/browser/ui/webui/help/version_updater.h
@@ -93,13 +93,19 @@ class VersionUpdater {
const ChannelCallback& callback) = 0;
virtual void GetEolStatus(const EolStatusCallback& callback) = 0;
- // Set the update over cellular target in |target_version| and |target_size|
- // arguments maintained by update engine. The arguments are later used by
- // update engine to match the given target with the server head and to allow
- // update over cellular to this given target.
- virtual void SetUpdateOverCellularTarget(const StatusCallback& callback,
- const std::string& target_version,
- int64_t target_size) = 0;
+ // Sets a one time permission on a certain update in Update Engine.
+ // - update_version: the Chrome OS version we want to update to.
+ // - update_size: the size of that Chrome OS version in bytes.
+ // These two parameters are a failsafe to prevent downloading an update that
+ // the user didn't agree to. They should be set using the version and size we
+ // received from update engine when it broadcasts NEED_PERMISSION_TO_UPDATE.
+ // They are used by update engine to double-check with update server in case
+ // there's a new update available or a delta update becomes a full update with
+ // a larger size.
+ virtual void SetUpdateOverCellularOneTimePermission(
+ const StatusCallback& callback,
+ const std::string& update_version,
+ int64_t update_size) = 0;
#endif
};
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 f5a75e9a87a..6f1d85c8592 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
@@ -8,6 +8,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
+#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
@@ -22,8 +23,10 @@
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
+#include "chromeos/network/network_type_pattern.h"
#include "chromeos/settings/cros_settings_names.h"
#include "content/public/browser/web_contents.h"
+#include "third_party/cros_system_api/dbus/service_constants.h"
#include "ui/base/l10n/l10n_util.h"
using chromeos::CrosSettings;
@@ -76,6 +79,27 @@ bool IsAutoUpdateDisabled() {
return update_disabled;
}
+base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) {
+ const std::string type =
+ network->IsUsingMobileData() ? shill::kTypeCellular : network->type();
+ if (chromeos::NetworkTypePattern::Ethernet().MatchesType(type))
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_ETHERNET);
+ if (type == shill::kTypeWifi)
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIFI);
+ if (type == shill::kTypeWimax)
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIMAX);
+ if (type == shill::kTypeBluetooth)
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_BLUETOOTH);
+ if (type == shill::kTypeCellular ||
+ chromeos::NetworkTypePattern::Tether().MatchesType(type)) {
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_MOBILE_DATA);
+ }
+ if (type == shill::kTypeVPN)
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_VPN);
+ NOTREACHED();
+ return base::string16();
+}
+
// Returns whether an update is allowed. If not, it calls the callback with
// the appropriate status. |interactive| indicates whether the user is actively
// checking for updates.
@@ -101,8 +125,7 @@ bool EnsureCanUpdate(bool interactive,
return false;
} else if (status == NETWORK_STATUS_DISALLOWED) {
base::string16 message = l10n_util::GetStringFUTF16(
- IDS_UPGRADE_DISALLOWED,
- help_utils_chromeos::GetConnectionTypeAsUTF16(network));
+ IDS_UPGRADE_DISALLOWED, GetConnectionTypeAsUTF16(network));
callback.Run(VersionUpdater::FAILED_CONNECTION_TYPE_DISALLOWED, 0,
std::string(), 0, message);
return false;
@@ -175,27 +198,29 @@ void VersionUpdaterCros::SetChannel(const std::string& channel,
SetChannel(channel, is_powerwash_allowed);
}
-void VersionUpdaterCros::SetUpdateOverCellularTarget(
+void VersionUpdaterCros::SetUpdateOverCellularOneTimePermission(
const StatusCallback& callback,
- const std::string& target_version,
- int64_t target_size) {
+ const std::string& update_version,
+ int64_t update_size) {
callback_ = callback;
DBusThreadManager::Get()
->GetUpdateEngineClient()
- ->SetUpdateOverCellularTarget(
- target_version, target_size,
- base::Bind(&VersionUpdaterCros::OnSetUpdateOverCellularTarget,
- weak_ptr_factory_.GetWeakPtr()));
+ ->SetUpdateOverCellularOneTimePermission(
+ update_version, update_size,
+ base::Bind(
+ &VersionUpdaterCros::OnSetUpdateOverCellularOneTimePermission,
+ weak_ptr_factory_.GetWeakPtr()));
}
-void VersionUpdaterCros::OnSetUpdateOverCellularTarget(bool success) {
+void VersionUpdaterCros::OnSetUpdateOverCellularOneTimePermission(
+ bool success) {
if (success) {
- // Target is set successfully, so we can proceed to update.
+ // One time permission is set successfully, so we can proceed to update.
CheckForUpdate(callback_, VersionUpdater::PromoteCallback());
} else {
// TODO(weidongg/691108): invoke callback to signal about page to show
// appropriate error message.
- LOG(ERROR) << "Error setting update over cellular target.";
+ LOG(ERROR) << "Error setting update over cellular one time permission.";
callback_.Run(VersionUpdater::FAILED, 0, std::string(), 0,
base::string16());
}
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h
index b6de0cb2f63..7defbfa5492 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h
@@ -26,9 +26,9 @@ class VersionUpdaterCros : public VersionUpdater,
bool is_powerwash_allowed) override;
void GetChannel(bool get_current_channel,
const ChannelCallback& callback) override;
- void SetUpdateOverCellularTarget(const StatusCallback& callback,
- const std::string& target_version,
- int64_t target_size) override;
+ void SetUpdateOverCellularOneTimePermission(const StatusCallback& callback,
+ const std::string& update_version,
+ int64_t update_size) override;
// Gets the last update status, without triggering a new check or download.
void GetUpdateStatus(const StatusCallback& callback);
@@ -50,8 +50,8 @@ class VersionUpdaterCros : public VersionUpdater,
// Callback from UpdateEngineClient::RequestUpdateCheck().
void OnUpdateCheck(chromeos::UpdateEngineClient::UpdateCheckResult result);
- // Callback from UpdateEngineClient::SetUpdateOverCellularTarget().
- void OnSetUpdateOverCellularTarget(bool success);
+ // Callback from UpdateEngineClient::SetUpdateOverCellularOneTimePermission().
+ void OnSetUpdateOverCellularOneTimePermission(bool success);
// Callback from UpdateEngineClient::GetChannel().
void OnGetChannel(const ChannelCallback& cb,
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 3db6e62b139..a327c5873be 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
@@ -63,8 +63,13 @@ class VersionUpdaterCrosTest : public ::testing::Test {
CrosSettings::Initialize();
NetworkHandler::Initialize();
+ base::RunLoop().RunUntilIdle();
+ }
+
+ void SetEthernetService() {
ShillServiceClient::TestInterface* service_test =
DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface();
+ service_test->ClearServices();
service_test->AddService("/service/eth",
"eth" /* guid */,
"eth",
@@ -73,6 +78,16 @@ class VersionUpdaterCrosTest : public ::testing::Test {
base::RunLoop().RunUntilIdle();
}
+ void SetCellularService() {
+ ShillServiceClient::TestInterface* service_test =
+ DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface();
+ service_test->ClearServices();
+ service_test->AddService("/service/cell", "cell" /* guid */, "cell",
+ shill::kTypeCellular, shill::kStateOnline,
+ true /* visible */);
+ base::RunLoop().RunUntilIdle();
+ }
+
void TearDown() override {
NetworkHandler::Shutdown();
@@ -101,6 +116,7 @@ class VersionUpdaterCrosTest : public ::testing::Test {
// 4. When update engine becomes idle downloading of the stable channel is
// initiated.
TEST_F(VersionUpdaterCrosTest, TwoOverlappingSetChannelRequests) {
+ SetEthernetService();
version_updater_->SetChannel("beta-channel", true);
{
@@ -152,4 +168,27 @@ TEST_F(VersionUpdaterCrosTest, TwoOverlappingSetChannelRequests) {
EXPECT_EQ(2, fake_update_engine_client_->request_update_check_call_count());
}
+// Test that when interactively checking for update, cellular connection is
+// allowed in Chrome by default, so that the request will be sent to Update
+// Engine.
+TEST_F(VersionUpdaterCrosTest, InteractiveCellularUpdateAllowed) {
+ SetCellularService();
+ EXPECT_EQ(0, fake_update_engine_client_->request_update_check_call_count());
+ version_updater_->CheckForUpdate(base::Bind(&CheckNotification),
+ VersionUpdater::PromoteCallback());
+ EXPECT_EQ(1, fake_update_engine_client_->request_update_check_call_count());
+}
+
+// Test that after update over cellular one time permission is set successfully,
+// an update check will be triggered.
+TEST_F(VersionUpdaterCrosTest, CellularUpdateOneTimePermission) {
+ SetCellularService();
+ EXPECT_EQ(0, fake_update_engine_client_->request_update_check_call_count());
+ const std::string& update_version = "9999.0.0";
+ const int64_t update_size = 99999;
+ version_updater_->SetUpdateOverCellularOneTimePermission(
+ base::Bind(&CheckNotification), update_version, update_size);
+ EXPECT_EQ(1, fake_update_engine_client_->request_update_check_call_count());
+}
+
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
index 5ff5332f195..42e285e3191 100644
--- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
+++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
@@ -15,6 +15,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/bad_clock_blocking_page.h"
+#include "chrome/browser/ssl/mitm_software_blocking_page.h"
#include "chrome/browser/ssl/ssl_blocking_page.h"
#include "chrome/browser/supervised_user/supervised_user_interstitial.h"
#include "chrome/common/features.h"
@@ -174,6 +175,27 @@ SSLBlockingPage* CreateSSLBlockingPage(content::WebContents* web_contents,
base::Callback<void(content::CertificateRequestResultType)>());
}
+MITMSoftwareBlockingPage* CreateMITMSoftwareBlockingPage(
+ content::WebContents* web_contents) {
+ const int cert_error = net::ERR_CERT_AUTHORITY_INVALID;
+ const GURL request_url("https://example.com");
+ const std::string mitm_software_name = "Misconfigured Antivirus";
+ bool is_enterprise_managed = false;
+
+ std::string is_enterprise_managed_param;
+ if (net::GetValueForKeyInQuery(web_contents->GetURL(), "enterprise",
+ &is_enterprise_managed_param)) {
+ is_enterprise_managed = is_enterprise_managed_param == "1";
+ }
+
+ net::SSLInfo ssl_info;
+ ssl_info.cert = ssl_info.unverified_cert = CreateFakeCert();
+ return new MITMSoftwareBlockingPage(
+ web_contents, cert_error, request_url, nullptr, ssl_info,
+ mitm_software_name, is_enterprise_managed,
+ base::Callback<void(content::CertificateRequestResultType)>());
+}
+
BadClockBlockingPage* CreateBadClockBlockingPage(
content::WebContents* web_contents) {
// Set up a fake clock error.
@@ -420,6 +442,9 @@ void InterstitialHTMLSource::StartDataRequest(
base::CompareCase::SENSITIVE)) {
interstitial_delegate.reset(
CreateSSLBlockingPage(web_contents, true /* is superfish */));
+ } else if (base::StartsWith(path, "mitm-software-ssl",
+ base::CompareCase::SENSITIVE)) {
+ interstitial_delegate.reset(CreateMITMSoftwareBlockingPage(web_contents));
} else if (base::StartsWith(path, "safebrowsing",
base::CompareCase::SENSITIVE)) {
interstitial_delegate.reset(CreateSafeBrowsingBlockingPage(web_contents));
diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc
index bc4f800ae1f..b6f0b6083d5 100644
--- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc
@@ -57,6 +57,11 @@ IN_PROC_BROWSER_TEST_F(InterstitialUITest, SuperfishInterstitial) {
"Privacy error");
}
+IN_PROC_BROWSER_TEST_F(InterstitialUITest, MITMSoftwareInterstitial) {
+ TestInterstitial(GURL("chrome://interstitials/mitm-software-ssl"),
+ "Privacy error");
+}
+
IN_PROC_BROWSER_TEST_F(InterstitialUITest, PinnedCertInterstitial) {
TestInterstitial(GURL("chrome://interstitials/ssl?type=hpkp_failure"),
"Privacy error");
diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc
index 6cedb644387..8d043bdcef5 100644
--- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc
+++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui.cc
@@ -101,11 +101,11 @@ content::WebUIDataSource* CreateLocalDiscoveryHTMLSource() {
// Cloud print connector-related strings.
#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
source->AddLocalizedString("cloudPrintConnectorEnablingButton",
- IDS_OPTIONS_CLOUD_PRINT_CONNECTOR_ENABLING_BUTTON);
+ IDS_CLOUD_PRINT_CONNECTOR_ENABLING_BUTTON);
source->AddLocalizedString("cloudPrintConnectorDisabledButton",
- IDS_OPTIONS_CLOUD_PRINT_CONNECTOR_DISABLED_BUTTON);
+ IDS_CLOUD_PRINT_CONNECTOR_DISABLED_BUTTON);
source->AddLocalizedString("cloudPrintConnectorEnabledButton",
- IDS_OPTIONS_CLOUD_PRINT_CONNECTOR_ENABLED_BUTTON);
+ IDS_CLOUD_PRINT_CONNECTOR_ENABLED_BUTTON);
source->AddLocalizedString("cloudPrintName",
IDS_GOOGLE_CLOUD_PRINT);
source->AddLocalizedString("titleConnector",
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 9971504107a..fc499de4454 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
@@ -298,7 +298,7 @@ class TestMessageLoopCondition {
void Signal() {
signaled_ = true;
if (waiting_)
- base::MessageLoop::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
// Pause execution and recursively run the message loop until |Signal()| is
@@ -453,8 +453,7 @@ class LocalDiscoveryUITest : public WebUIBrowserTest {
void RunFor(base::TimeDelta time_period) {
base::CancelableCallback<void()> callback(
- base::Bind(&base::MessageLoop::QuitWhenIdle,
- base::Unretained(base::MessageLoop::current())));
+ base::Bind(&base::RunLoop::QuitCurrentWhenIdleDeprecated));
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, callback.callback(), time_period);
diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
index 1b25fe1c8b1..bda2aa8bed1 100644
--- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
@@ -593,7 +593,7 @@ void LocalDiscoveryUIHandler::SetupCloudPrintConnectorSection() {
l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT));
} else {
label_str = l10n_util::GetStringFUTF16(
- IDS_OPTIONS_CLOUD_PRINT_CONNECTOR_ENABLED_LABEL,
+ IDS_CLOUD_PRINT_CONNECTOR_ENABLED_LABEL,
l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT),
base::UTF8ToUTF16(email));
}
diff --git a/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc b/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc
index d688f7a7072..848cd752dfc 100644
--- a/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc
+++ b/chromium/chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.cc
@@ -12,6 +12,7 @@
#include "base/strings/string16.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/md_bookmarks/bookmarks_message_handler.h"
+#include "chrome/browser/ui/webui/metrics_handler.h"
#include "chrome/browser/ui/webui/plural_string_handler.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/url_constants.h"
@@ -54,6 +55,8 @@ content::WebUIDataSource* CreateMdBookmarksUIHTMLSource(Profile* profile) {
IDS_BOOKMARK_MANAGER_URL_INPUT_PLACE_HOLDER);
AddLocalizedString(source, "emptyList",
IDS_MD_BOOKMARK_MANAGER_EMPTY_LIST);
+ AddLocalizedString(source, "folderLabel",
+ IDS_MD_BOOKMARK_MANAGER_FOLDER_LABEL);
AddLocalizedString(source, "itemsSelected",
IDS_MD_BOOKMARK_MANAGER_ITEMS_SELECTED);
AddLocalizedString(source, "menuAddBookmark",
@@ -66,22 +69,20 @@ content::WebUIDataSource* CreateMdBookmarksUIHTMLSource(Profile* profile) {
AddLocalizedString(source, "menuEdit", IDS_EDIT);
AddLocalizedString(source, "menuExport", IDS_MD_BOOKMARK_MANAGER_MENU_EXPORT);
AddLocalizedString(source, "menuImport", IDS_MD_BOOKMARK_MANAGER_MENU_IMPORT);
- // TODO(tsergeant): These are not the exact strings specified by UI. Reconcile
- // the differences between these strings and the work in crbug.com/708815.
AddLocalizedString(source, "menuOpenAllNewTab", IDS_BOOKMARK_BAR_OPEN_ALL);
AddLocalizedString(source, "menuOpenAllNewWindow",
- IDS_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW);
+ IDS_MD_BOOKMARK_MANAGER_MENU_OPEN_ALL_NEW_WINDOW);
AddLocalizedString(source, "menuOpenAllIncognito",
- IDS_BOOKMARK_BAR_OPEN_ALL_INCOGNITO);
+ IDS_MD_BOOKMARK_MANAGER_MENU_OPEN_ALL_INCOGNITO);
AddLocalizedString(source, "menuOpenNewTab",
- IDS_BOOKMARK_BAR_OPEN_IN_NEW_TAB);
+ IDS_MD_BOOKMARK_MANAGER_MENU_OPEN_IN_NEW_TAB);
AddLocalizedString(source, "menuOpenNewWindow",
- IDS_BOOKMARK_BAR_OPEN_IN_NEW_WINDOW);
+ IDS_MD_BOOKMARK_MANAGER_MENU_OPEN_IN_NEW_WINDOW);
AddLocalizedString(source, "menuOpenIncognito",
- IDS_BOOKMARK_BAR_OPEN_INCOGNITO);
+ IDS_MD_BOOKMARK_MANAGER_MENU_OPEN_INCOGNITO);
AddLocalizedString(source, "menuRename", IDS_MD_BOOKMARK_MANAGER_MENU_RENAME);
AddLocalizedString(source, "menuShowInFolder",
- IDS_BOOKMARK_MANAGER_SHOW_IN_FOLDER);
+ IDS_MD_BOOKMARK_MANAGER_MENU_SHOW_IN_FOLDER);
AddLocalizedString(source, "menuSort", IDS_MD_BOOKMARK_MANAGER_MENU_SORT);
AddLocalizedString(source, "moreActionsButtonTitle",
IDS_MD_BOOKMARK_MANAGER_MORE_ACTIONS);
@@ -212,6 +213,7 @@ MdBookmarksUI::MdBookmarksUI(content::WebUI* web_ui) : WebUIController(web_ui) {
web_ui->AddMessageHandler(std::move(plural_string_handler));
web_ui->AddMessageHandler(base::MakeUnique<BookmarksMessageHandler>());
+ web_ui->AddMessageHandler(base::MakeUnique<MetricsHandler>());
}
// static
diff --git a/chromium/chrome/browser/ui/webui/md_downloads/OWNERS b/chromium/chrome/browser/ui/webui/md_downloads/OWNERS
index 8eefb55c2d8..53ef569f103 100644
--- a/chromium/chrome/browser/ui/webui/md_downloads/OWNERS
+++ b/chromium/chrome/browser/ui/webui/md_downloads/OWNERS
@@ -1,4 +1,3 @@
asanka@chromium.org
-dbeam@chromium.org
# COMPONENT: UI>Browser>Downloads
diff --git a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc
index f2da6b7eb21..702887c7946 100644
--- a/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc
+++ b/chromium/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc
@@ -118,6 +118,10 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) {
IDR_MD_DOWNLOADS_ACTION_SERVICE_HTML);
source->AddResourcePath("action_service.js",
IDR_MD_DOWNLOADS_ACTION_SERVICE_JS);
+ source->AddResourcePath("browser_proxy.html",
+ IDR_MD_DOWNLOADS_BROWSER_PROXY_HTML);
+ source->AddResourcePath("browser_proxy.js",
+ IDR_MD_DOWNLOADS_BROWSER_PROXY_JS);
source->AddResourcePath("constants.html", IDR_MD_DOWNLOADS_CONSTANTS_HTML);
source->AddResourcePath("constants.js", IDR_MD_DOWNLOADS_CONSTANTS_JS);
source->AddResourcePath("downloads.js", IDR_MD_DOWNLOADS_DOWNLOADS_JS);
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc
index 83da136340b..d20560b4329 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.cc
@@ -327,15 +327,14 @@ void MediaRouterDialogControllerImpl::PopulateDialog(
media_router_dialog->GetWebUI()->GetController());
DCHECK(media_router_ui);
- std::unique_ptr<CreatePresentationConnectionRequest>
- create_connection_request(TakeCreateConnectionRequest());
+ auto start_presentation_context = std::move(start_presentation_context_);
PresentationServiceDelegateImpl* delegate =
PresentationServiceDelegateImpl::FromWebContents(initiator());
- if (!create_connection_request.get()) {
+ if (!start_presentation_context) {
media_router_ui->InitWithDefaultMediaSource(initiator(), delegate);
} else {
- media_router_ui->InitWithPresentationSessionRequest(
- initiator(), delegate, std::move(create_connection_request));
+ media_router_ui->InitWithStartPresentationContext(
+ initiator(), delegate, std::move(start_presentation_context));
}
}
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc
index 5be13b0bf19..9197befe227 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl_unittest.cc
@@ -252,18 +252,16 @@ TEST_F(MediaRouterDialogControllerImplTest, NotifyActionController) {
dialog_controller_->HideMediaRouterDialog();
EXPECT_CALL(*action_controller, OnDialogShown());
- dialog_controller_->ShowMediaRouterDialogForPresentation(
- std::unique_ptr<CreatePresentationConnectionRequest>(
- new CreatePresentationConnectionRequest(
- RenderFrameHostId(1, 2),
- {GURL("http://test.com"), GURL("http://test2.com")},
- url::Origin(GURL("http://example.com")),
- base::Bind(&MediaRouterDialogControllerImplTest::
- PresentationSuccessCallback,
- base::Unretained(this)),
- base::Bind(&MediaRouterDialogControllerImplTest::
- PresentationErrorCallback,
- base::Unretained(this)))));
+ EXPECT_TRUE(dialog_controller_->ShowMediaRouterDialogForPresentation(
+ content::PresentationRequest(
+ {1, 2}, {GURL("http://test.com"), GURL("http://test2.com")},
+ url::Origin(GURL("http://example.com"))),
+ base::Bind(
+ &MediaRouterDialogControllerImplTest::PresentationSuccessCallback,
+ base::Unretained(this)),
+ base::Bind(
+ &MediaRouterDialogControllerImplTest::PresentationErrorCallback,
+ base::Unretained(this))));
// When |dialog_controller_| is destroyed with its dialog open,
// |action_controller| should be notified.
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc
index 517e61fbadb..f357dba3a5e 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_file_dialog.cc
@@ -108,7 +108,7 @@ void MediaRouterFileDialog::FileSystemDelegate::OpenFileDialog(
const base::FilePath& default_directory,
const ui::SelectFileDialog::FileTypeInfo* file_type_info) {
select_file_dialog_ = ui::SelectFileDialog::Create(
- listener, new ChromeSelectFilePolicy(
+ listener, std::make_unique<ChromeSelectFilePolicy>(
browser->tab_strip_model()->GetActiveWebContents()));
gfx::NativeWindow parent_window = browser->window()->GetNativeWindow();
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc
index 17af03a9c93..416111ad044 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc
@@ -49,6 +49,10 @@ void AddRouteDetailsStrings(content::WebUIDataSource* html_source) {
IDS_MEDIA_ROUTER_ROUTE_DETAILS_SEEK_TITLE);
html_source->AddLocalizedString("volumeTitle",
IDS_MEDIA_ROUTER_ROUTE_DETAILS_VOLUME_TITLE);
+ html_source->AddLocalizedString(
+ "currentTimeLabel", IDS_MEDIA_ROUTER_ROUTE_DETAILS_CURRENT_TIME_LABEL);
+ html_source->AddLocalizedString(
+ "durationLabel", IDS_MEDIA_ROUTER_ROUTE_DETAILS_DURATION_LABEL);
}
void AddIssuesStrings(content::WebUIDataSource* html_source) {
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc
index 679cf901b03..5de68ca212a 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc
@@ -17,7 +17,6 @@
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/media/router/create_presentation_connection_request.h"
#include "chrome/browser/media/router/event_page_request_manager.h"
#include "chrome/browser/media/router/event_page_request_manager_factory.h"
#include "chrome/browser/media/router/issues_observer.h"
@@ -134,16 +133,17 @@ Browser* MediaRouterUI::GetBrowser() {
return chrome::FindBrowserWithWebContents(initiator());
}
-void MediaRouterUI::OpenTabWithUrl(const GURL url) {
+content::WebContents* MediaRouterUI::OpenTabWithUrl(const GURL url) {
// Check if the current page is a new tab. If so open file in current page.
// If not then open a new page.
if (initiator_->GetVisibleURL() == chrome::kChromeUINewTabURL) {
content::NavigationController::LoadURLParams load_params(url);
load_params.transition_type = ui::PAGE_TRANSITION_GENERATED;
initiator_->GetController().LoadURLWithParams(load_params);
+ return initiator_;
} else {
- initiator_ = chrome::AddSelectedTabWithURL(GetBrowser(), url,
- ui::PAGE_TRANSITION_LINK);
+ return chrome::AddSelectedTabWithURL(GetBrowser(), url,
+ ui::PAGE_TRANSITION_LINK);
}
}
@@ -258,22 +258,24 @@ MediaRouterUI::~MediaRouterUI() {
if (presentation_service_delegate_.get())
presentation_service_delegate_->RemoveDefaultPresentationRequestObserver(
this);
- // If |create_session_request_| still exists, then it means presentation route
- // request was never attempted.
- if (create_session_request_) {
+ // If |start_presentation_context_| still exists, then it means presentation
+ // route request was never attempted.
+ if (start_presentation_context_) {
bool presentation_sinks_available = std::any_of(
sinks_.begin(), sinks_.end(), [](const MediaSinkWithCastModes& sink) {
return base::ContainsKey(sink.cast_modes,
MediaCastMode::PRESENTATION);
});
if (presentation_sinks_available) {
- create_session_request_->InvokeErrorCallback(content::PresentationError(
- content::PRESENTATION_ERROR_PRESENTATION_REQUEST_CANCELLED,
- "Dialog closed."));
+ start_presentation_context_->InvokeErrorCallback(
+ content::PresentationError(
+ content::PRESENTATION_ERROR_PRESENTATION_REQUEST_CANCELLED,
+ "Dialog closed."));
} else {
- create_session_request_->InvokeErrorCallback(content::PresentationError(
- content::PRESENTATION_ERROR_NO_AVAILABLE_SCREENS,
- "No screens found."));
+ start_presentation_context_->InvokeErrorCallback(
+ content::PresentationError(
+ content::PRESENTATION_ERROR_NO_AVAILABLE_SCREENS,
+ "No screens found."));
}
}
}
@@ -301,22 +303,22 @@ void MediaRouterUI::InitWithDefaultMediaSource(
}
}
-void MediaRouterUI::InitWithPresentationSessionRequest(
+void MediaRouterUI::InitWithStartPresentationContext(
content::WebContents* initiator,
PresentationServiceDelegateImpl* delegate,
- std::unique_ptr<CreatePresentationConnectionRequest>
- create_session_request) {
+ std::unique_ptr<StartPresentationContext> context) {
DCHECK(initiator);
DCHECK(delegate);
- DCHECK(create_session_request);
- DCHECK(!create_session_request_);
+ DCHECK(context);
+ DCHECK(!start_presentation_context_);
DCHECK(!query_result_manager_);
- create_session_request_ = std::move(create_session_request);
+ start_presentation_context_ = std::move(context);
presentation_service_delegate_ = delegate->GetWeakPtr();
InitCommon(initiator);
- OnDefaultPresentationChanged(create_session_request_->presentation_request());
+ OnDefaultPresentationChanged(
+ start_presentation_context_->presentation_request());
}
void MediaRouterUI::InitCommon(content::WebContents* initiator) {
@@ -328,7 +330,7 @@ void MediaRouterUI::InitCommon(content::WebContents* initiator) {
// Presentation requests from content must show the origin requesting
// presentation: crbug.com/704964
- if (create_session_request_)
+ if (start_presentation_context_)
forced_cast_mode_ = MediaCastMode::PRESENTATION;
router_->OnUserGesture();
@@ -379,26 +381,32 @@ void MediaRouterUI::InitForTest(
MediaRouter* router,
content::WebContents* initiator,
MediaRouterWebUIMessageHandler* handler,
- std::unique_ptr<CreatePresentationConnectionRequest> create_session_request,
+ std::unique_ptr<StartPresentationContext> context,
std::unique_ptr<MediaRouterFileDialog> file_dialog) {
router_ = router;
handler_ = handler;
- create_session_request_ = std::move(create_session_request);
- media_router_file_dialog_ = std::move(file_dialog);
+ start_presentation_context_ = std::move(context);
+ InitForTest(std::move(file_dialog));
InitCommon(initiator);
- if (create_session_request_) {
+ if (start_presentation_context_) {
OnDefaultPresentationChanged(
- create_session_request_->presentation_request());
+ start_presentation_context_->presentation_request());
}
}
+void MediaRouterUI::InitForTest(
+ std::unique_ptr<MediaRouterFileDialog> file_dialog) {
+ media_router_file_dialog_ = std::move(file_dialog);
+}
+
void MediaRouterUI::OnDefaultPresentationChanged(
- const PresentationRequest& presentation_request) {
- std::vector<MediaSource> sources = presentation_request.GetMediaSources();
- presentation_request_.reset(new PresentationRequest(presentation_request));
+ const content::PresentationRequest& presentation_request) {
+ std::vector<MediaSource> sources =
+ MediaSourcesForPresentationUrls(presentation_request.presentation_urls);
+ presentation_request_ = presentation_request;
query_result_manager_->SetSourcesForCastMode(
MediaCastMode::PRESENTATION, sources,
- presentation_request_->frame_origin());
+ presentation_request_->frame_origin);
// Register for MediaRoute updates. NOTE(mfoltz): If there are multiple
// sources that can be connected to via the dialog, this will break. We will
// need to observe multiple sources (keyed by sinks) in that case. As this is
@@ -482,18 +490,27 @@ bool MediaRouterUI::CreateRoute(const MediaSink::Id& sink_id,
base::TimeDelta timeout;
bool incognito;
+ // Default the tab casting the content to the initiator, and change if
+ // necessary.
+ content::WebContents* tab_contents = initiator_;
+
if (cast_mode == MediaCastMode::LOCAL_FILE) {
GURL url = media_router_file_dialog_->GetLastSelectedFileUrl();
- OpenTabWithUrl(url);
- }
+ tab_contents = OpenTabWithUrl(url);
- if (!SetRouteParameters(sink_id, cast_mode, &source_id, &origin,
- &route_response_callbacks, &timeout, &incognito)) {
+ SessionID::id_type tab_id = SessionTabHelper::IdForTab(tab_contents);
+ source_id = MediaSourceForTab(tab_id).id();
+
+ SetLocalFileRouteParameters(sink_id, &origin, &route_response_callbacks,
+ &timeout, &incognito);
+ } else if (!SetRouteParameters(sink_id, cast_mode, &source_id, &origin,
+ &route_response_callbacks, &timeout,
+ &incognito)) {
SendIssueForUnableToCast(cast_mode);
return false;
}
- router_->CreateRoute(source_id, sink_id, origin, initiator_,
+ router_->CreateRoute(source_id, sink_id, origin, tab_contents,
std::move(route_response_callbacks), timeout, incognito);
return true;
}
@@ -535,7 +552,7 @@ bool MediaRouterUI::SetRouteParameters(
current_route_request_id_ = ++route_request_counter_;
*origin = for_presentation_source
- ? presentation_request_->frame_origin()
+ ? presentation_request_->frame_origin
: url::Origin(GURL(chrome::kChromeUIMediaRouterURL));
DVLOG(1) << "DoCreateRoute: origin: " << *origin;
@@ -543,26 +560,25 @@ bool MediaRouterUI::SetRouteParameters(
// notified. In case (2) the dialog will be closed.
// (1) Non-presentation route request (e.g., mirroring). No additional
// notification necessary.
- // (2) Presentation route request for a Presentation API startSession call.
- // The startSession (CreatePresentationConnectionRequest) will need to be
- // answered with the route response.
- // (3) Browser-initiated presentation route request. If successful,
+ // (2) Presentation route request for a PresentationRequest.start() call.
+ // The StartPresentationContext will need to be answered with the route
+ // response. (3) Browser-initiated presentation route request. If successful,
// PresentationServiceDelegateImpl will have to be notified. Note that we
// treat subsequent route requests from a Presentation API-initiated dialogs
// as browser-initiated.
- if (!for_presentation_source || !create_session_request_) {
+ if (!for_presentation_source || !start_presentation_context_) {
route_response_callbacks->push_back(base::BindOnce(
&MediaRouterUI::OnRouteResponseReceived, weak_factory_.GetWeakPtr(),
current_route_request_id_, sink_id, cast_mode,
base::UTF8ToUTF16(GetTruncatedPresentationRequestSourceName())));
}
if (for_presentation_source) {
- if (create_session_request_) {
- // |create_session_request_| will be nullptr after this call, as the
+ if (start_presentation_context_) {
+ // |start_presentation_context_| will be nullptr after this call, as the
// object will be transferred to the callback.
- route_response_callbacks->push_back(base::BindOnce(
- &CreatePresentationConnectionRequest::HandleRouteResponse,
- base::Passed(&create_session_request_)));
+ route_response_callbacks->push_back(
+ base::BindOnce(&StartPresentationContext::HandleRouteResponse,
+ std::move(start_presentation_context_)));
route_response_callbacks->push_back(base::BindOnce(
&MediaRouterUI::HandleCreateSessionRequestRouteResponse,
weak_factory_.GetWeakPtr()));
@@ -577,18 +593,43 @@ bool MediaRouterUI::SetRouteParameters(
base::BindOnce(&MediaRouterUI::MaybeReportCastingSource,
weak_factory_.GetWeakPtr(), cast_mode));
- if (cast_mode == MediaCastMode::LOCAL_FILE) {
- route_response_callbacks->push_back(
- base::BindOnce(&MediaRouterUI::MaybeReportFileInformation,
- weak_factory_.GetWeakPtr()));
- }
-
*timeout = GetRouteRequestTimeout(cast_mode);
*incognito = Profile::FromWebUI(web_ui())->IsOffTheRecord();
return true;
}
+// TODO(Issue 751317) This function and the above function are messy, this code
+// would be much neater if the route params were combined in a single struct,
+// which will require mojo changes as well.
+bool MediaRouterUI::SetLocalFileRouteParameters(
+ const MediaSink::Id& sink_id,
+ url::Origin* origin,
+ std::vector<MediaRouteResponseCallback>* route_response_callbacks,
+ base::TimeDelta* timeout,
+ bool* incognito) {
+ // Use a placeholder URL as origin for local file casting, which is
+ // essentially mirroring.
+ *origin = url::Origin(GURL(chrome::kChromeUIMediaRouterURL));
+
+ route_response_callbacks->push_back(base::BindOnce(
+ &MediaRouterUI::OnRouteResponseReceived, weak_factory_.GetWeakPtr(),
+ current_route_request_id_, sink_id, MediaCastMode::LOCAL_FILE,
+ base::UTF8ToUTF16(GetTruncatedPresentationRequestSourceName())));
+
+ route_response_callbacks->push_back(
+ base::BindOnce(&MediaRouterUI::MaybeReportCastingSource,
+ weak_factory_.GetWeakPtr(), MediaCastMode::LOCAL_FILE));
+
+ route_response_callbacks->push_back(base::BindOnce(
+ &MediaRouterUI::MaybeReportFileInformation, weak_factory_.GetWeakPtr()));
+
+ *timeout = GetRouteRequestTimeout(MediaCastMode::LOCAL_FILE);
+ *incognito = Profile::FromWebUI(web_ui())->IsOffTheRecord();
+
+ return true;
+}
+
bool MediaRouterUI::ConnectRoute(const MediaSink::Id& sink_id,
const MediaRoute::Id& route_id) {
MediaSource::Id source_id;
@@ -837,7 +878,7 @@ void MediaRouterUI::SendIssueForUnableToCast(MediaCastMode cast_mode) {
}
GURL MediaRouterUI::GetFrameURL() const {
- return presentation_request_ ? presentation_request_->frame_origin().GetURL()
+ return presentation_request_ ? presentation_request_->frame_origin.GetURL()
: GURL();
}
@@ -889,7 +930,7 @@ void MediaRouterUI::UpdateMaxDialogHeight(int height) {
handler_->UpdateMaxDialogHeight(height);
}
-const MediaRouteController* MediaRouterUI::GetMediaRouteController() const {
+MediaRouteController* MediaRouterUI::GetMediaRouteController() const {
return route_controller_observer_
? route_controller_observer_->controller().get()
: nullptr;
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h
index bb70fa41482..808a967e246 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h
@@ -14,6 +14,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
+#include "chrome/browser/media/router/media_router_dialog_controller.h"
#include "chrome/browser/media/router/mojo/media_route_controller.h"
#include "chrome/browser/media/router/presentation_service_delegate_impl.h"
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
@@ -28,6 +29,7 @@
#include "url/gurl.h"
namespace content {
+struct PresentationRequest;
class WebContents;
}
@@ -43,7 +45,6 @@ class Browser;
namespace media_router {
-class CreatePresentationConnectionRequest;
class EventPageRequestManager;
class IssuesObserver;
class MediaRoute;
@@ -82,7 +83,7 @@ class MediaRouterUI
PresentationServiceDelegateImpl* delegate);
// Initializes internal state targeting the presentation specified in
- // |request|. Also sets up mirroring sources based on |initiator|.
+ // |context|. Also sets up mirroring sources based on |initiator|.
// This is different from |InitWithDefaultMediaSource| in that it does not
// listen for default media source changes, as the UI is fixed to the source
// in |request|.
@@ -91,13 +92,13 @@ class MediaRouterUI
// Must not be null.
// |delegate|: PresentationServiceDelegateImpl of the initiator tab.
// Must not be null.
- // |presentation_request|: The presentation request. This instance will take
+ // |context|: Context object for the PresentationRequest. This instance will
+ // take
// ownership of it. Must not be null.
- void InitWithPresentationSessionRequest(
+ void InitWithStartPresentationContext(
content::WebContents* initiator,
PresentationServiceDelegateImpl* delegate,
- std::unique_ptr<CreatePresentationConnectionRequest>
- presentation_request);
+ std::unique_ptr<StartPresentationContext> context);
// Closes the media router UI.
void Close();
@@ -176,7 +177,7 @@ class MediaRouterUI
// Gets the route controller currently in use by the UI. Returns a nullptr if
// none is in use.
- virtual const MediaRouteController* GetMediaRouteController() const;
+ virtual MediaRouteController* GetMediaRouteController() const;
// Called when a media controller UI surface is created. Creates an observer
// for the MediaRouteController for |route_id| to listen for media status
@@ -189,10 +190,11 @@ class MediaRouterUI
void InitForTest(MediaRouter* router,
content::WebContents* initiator,
MediaRouterWebUIMessageHandler* handler,
- std::unique_ptr<CreatePresentationConnectionRequest>
- create_session_request,
+ std::unique_ptr<StartPresentationContext> context,
std::unique_ptr<MediaRouterFileDialog> file_dialog);
+ void InitForTest(std::unique_ptr<MediaRouterFileDialog> file_dialog);
+
private:
friend class MediaRouterUITest;
@@ -264,8 +266,8 @@ class MediaRouterUI
// Retrieves the browser associated with this UI.
Browser* GetBrowser();
- // Opens the URL in a tab which is then |initator_|.
- void OpenTabWithUrl(const GURL url);
+ // Opens the URL in a tab, returns the tab it was opened in.
+ content::WebContents* OpenTabWithUrl(const GURL url);
// Methods for MediaRouterFileDialogDelegate
void FileDialogFileSelected(const ui::SelectedFileInfo& file_info) override;
@@ -302,8 +304,8 @@ class MediaRouterUI
void MaybeReportFileInformation(const RouteRequestResult& result);
// Closes the dialog after receiving a route response when using
- // |create_session_request_|. This prevents the dialog from trying to use the
- // same presentation request again.
+ // |start_presentation_context_|. This prevents the dialog from trying to use
+ // the same presentation request again.
void HandleCreateSessionRequestRouteResponse(const RouteRequestResult&);
// Callback passed to MediaRouter to receive the sink ID of the sink found by
@@ -324,7 +326,7 @@ class MediaRouterUI
// PresentationServiceDelegateImpl::DefaultPresentationObserver
void OnDefaultPresentationChanged(
- const PresentationRequest& presentation_request) override;
+ const content::PresentationRequest& presentation_request) override;
void OnDefaultPresentationRemoved() override;
// Populates common route-related parameters for CreateRoute(),
@@ -338,6 +340,15 @@ class MediaRouterUI
base::TimeDelta* timeout,
bool* incognito);
+ // Populates route-related parameters for CreateRoute() when doing file
+ // casting.
+ bool SetLocalFileRouteParameters(
+ const MediaSink::Id& sink_id,
+ url::Origin* origin,
+ std::vector<MediaRouteResponseCallback>* route_response_callbacks,
+ base::TimeDelta* timeout,
+ bool* incognito);
+
// Updates the set of supported cast modes and sends the updated set to
// |handler_|.
void UpdateCastModes();
@@ -395,11 +406,11 @@ class MediaRouterUI
// If set, then the result of the next presentation route request will
// be handled by this object.
- std::unique_ptr<CreatePresentationConnectionRequest> create_session_request_;
+ std::unique_ptr<StartPresentationContext> start_presentation_context_;
// Set to the presentation request corresponding to the presentation cast
// mode, if supported. Otherwise set to nullptr.
- std::unique_ptr<PresentationRequest> presentation_request_;
+ base::Optional<content::PresentationRequest> presentation_request_;
// It's possible for PresentationServiceDelegateImpl to be destroyed before
// this class.
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc
index a3b440ef8c9..920c64e8ce2 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc
@@ -10,7 +10,8 @@
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
-#include "chrome/browser/media/router/create_presentation_connection_request.h"
+#include "chrome/browser/media/router/event_page_request_manager_factory.h"
+#include "chrome/browser/media/router/media_router_factory.h"
#include "chrome/browser/media/router/mock_media_router.h"
#include "chrome/browser/media/router/mojo/media_router_mojo_test.h"
#include "chrome/browser/media/router/test_helper.h"
@@ -27,7 +28,6 @@
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
-#include "extensions/common/test_util.h"
#include "extensions/common/value_builder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -93,23 +93,34 @@ class PresentationRequestCallbacks {
class MediaRouterUITest : public ChromeRenderViewHostTestHarness {
public:
- MediaRouterUITest() {
- ON_CALL(mock_router_, GetCurrentRoutes())
- .WillByDefault(Return(std::vector<MediaRoute>()));
-
+ MediaRouterUITest()
+ : presentation_request_({0, 0},
+ {GURL("https://google.com/presentation")},
+ url::Origin(GURL("http://google.com"))) {
// enable and disable features
scoped_feature_list_.InitFromCommandLine(
"EnableCastLocalMedia" /* enabled features */,
std::string() /* disabled features */);
}
+ void SetUp() override {
+ ChromeRenderViewHostTestHarness::SetUp();
+ EventPageRequestManagerFactory::GetInstance()->SetTestingFactory(
+ profile(), &MockEventPageRequestManager::Create);
+ mock_router_ = static_cast<MockMediaRouter*>(
+ MediaRouterFactory::GetInstance()->SetTestingFactoryAndUse(
+ profile(), &MockMediaRouter::Create));
+ ON_CALL(*mock_router_, GetCurrentRoutes())
+ .WillByDefault(Return(std::vector<MediaRoute>()));
+ }
+
void TearDown() override {
- EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_))
+ EXPECT_CALL(*mock_router_, UnregisterMediaSinksObserver(_))
.Times(AnyNumber());
- EXPECT_CALL(mock_router_, UnregisterMediaRoutesObserver(_))
+ EXPECT_CALL(*mock_router_, UnregisterMediaRoutesObserver(_))
.Times(AnyNumber());
web_ui_contents_.reset();
- create_session_request_.reset();
+ start_presentation_context_.reset();
media_router_ui_.reset();
message_handler_.reset();
ChromeRenderViewHostTestHarness::TearDown();
@@ -135,16 +146,16 @@ class MediaRouterUITest : public ChromeRenderViewHostTestHarness {
auto file_dialog = base::MakeUnique<MockMediaRouterFileDialog>();
mock_file_dialog_ = file_dialog.get();
- EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_))
+ EXPECT_CALL(*mock_router_, RegisterMediaSinksObserver(_))
.WillRepeatedly(Invoke([this](MediaSinksObserver* observer) {
this->media_sinks_observers_.push_back(observer);
return true;
}));
- EXPECT_CALL(mock_router_, RegisterMediaRoutesObserver(_))
+ EXPECT_CALL(*mock_router_, RegisterMediaRoutesObserver(_))
.Times(AnyNumber());
media_router_ui_->InitForTest(
- &mock_router_, web_contents(), message_handler_.get(),
- std::move(create_session_request_), std::move(file_dialog));
+ mock_router_, web_contents(), message_handler_.get(),
+ std::move(start_presentation_context_), std::move(file_dialog));
message_handler_->SetWebUIForTest(&web_ui_);
}
@@ -155,25 +166,18 @@ class MediaRouterUITest : public ChromeRenderViewHostTestHarness {
return sink;
}
- scoped_refptr<MockMediaRouteController> CreateMediaRouteController(
- const MediaRoute::Id& route_id) {
- mojom::MediaControllerPtr mojo_media_controller;
- mojo::MakeRequest(&mojo_media_controller);
- return scoped_refptr<MockMediaRouteController>(new MockMediaRouteController(
- route_id, std::move(mojo_media_controller), &mock_router_));
- }
-
// Notifies MediaRouterUI that a route details view has been opened. Expects
// MediaRouterUI to request a MediaRouteController, and gives it a mock
// controller. Returns a reference to the mock controller.
scoped_refptr<MockMediaRouteController> OpenUIDetailsView(
const MediaRoute::Id& route_id) {
- auto controller = CreateMediaRouteController(route_id);
+ auto controller =
+ base::MakeRefCounted<MockMediaRouteController>(route_id, profile());
MediaSource media_source("mediaSource");
MediaRoute route(route_id, media_source, "sinkId", "", true, "", true);
media_router_ui_->OnRoutesUpdated({route}, std::vector<MediaRoute::Id>());
- EXPECT_CALL(mock_router_, GetRouteController(route_id))
+ EXPECT_CALL(*mock_router_, GetRouteController(route_id))
.WillOnce(Return(controller));
media_router_ui_->OnMediaControllerUIAvailable(route_id);
@@ -181,10 +185,11 @@ class MediaRouterUITest : public ChromeRenderViewHostTestHarness {
}
protected:
- MockMediaRouter mock_router_;
+ content::PresentationRequest presentation_request_;
+ MockMediaRouter* mock_router_ = nullptr;
content::TestWebUI web_ui_;
std::unique_ptr<WebContents> web_ui_contents_;
- std::unique_ptr<CreatePresentationConnectionRequest> create_session_request_;
+ std::unique_ptr<StartPresentationContext> start_presentation_context_;
std::unique_ptr<MediaRouterUI> media_router_ui_;
std::unique_ptr<MockMediaRouterWebUIMessageHandler> message_handler_;
MockMediaRouterFileDialog* mock_file_dialog_ = nullptr;
@@ -195,7 +200,7 @@ class MediaRouterUITest : public ChromeRenderViewHostTestHarness {
TEST_F(MediaRouterUITest, RouteCreationTimeoutForTab) {
CreateMediaRouterUI(profile());
std::vector<MediaRouteResponseCallback> callbacks;
- EXPECT_CALL(mock_router_,
+ EXPECT_CALL(*mock_router_,
CreateRouteInternal(_, _, _, _, _,
base::TimeDelta::FromSeconds(60), false))
.WillOnce(SaveArgWithMove<4>(&callbacks));
@@ -204,7 +209,7 @@ TEST_F(MediaRouterUITest, RouteCreationTimeoutForTab) {
std::string expected_title = l10n_util::GetStringUTF8(
IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_TAB);
- EXPECT_CALL(mock_router_, AddIssue(IssueTitleEquals(expected_title)));
+ EXPECT_CALL(*mock_router_, AddIssue(IssueTitleEquals(expected_title)));
std::unique_ptr<RouteRequestResult> result =
RouteRequestResult::FromError("Timed out", RouteRequestResult::TIMED_OUT);
for (auto& callback : callbacks)
@@ -214,7 +219,7 @@ TEST_F(MediaRouterUITest, RouteCreationTimeoutForTab) {
TEST_F(MediaRouterUITest, RouteCreationTimeoutForDesktop) {
CreateMediaRouterUI(profile());
std::vector<MediaRouteResponseCallback> callbacks;
- EXPECT_CALL(mock_router_,
+ EXPECT_CALL(*mock_router_,
CreateRouteInternal(_, _, _, _, _,
base::TimeDelta::FromSeconds(120), false))
.WillOnce(SaveArgWithMove<4>(&callbacks));
@@ -223,7 +228,7 @@ TEST_F(MediaRouterUITest, RouteCreationTimeoutForDesktop) {
std::string expected_title = l10n_util::GetStringUTF8(
IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_DESKTOP);
- EXPECT_CALL(mock_router_, AddIssue(IssueTitleEquals(expected_title)));
+ EXPECT_CALL(*mock_router_, AddIssue(IssueTitleEquals(expected_title)));
std::unique_ptr<RouteRequestResult> result =
RouteRequestResult::FromError("Timed out", RouteRequestResult::TIMED_OUT);
for (auto& callback : callbacks)
@@ -232,12 +237,12 @@ TEST_F(MediaRouterUITest, RouteCreationTimeoutForDesktop) {
TEST_F(MediaRouterUITest, RouteCreationTimeoutForPresentation) {
CreateMediaRouterUI(profile());
- PresentationRequest presentation_request(
- RenderFrameHostId(0, 0), {GURL("https://presentationurl.com")},
+ content::PresentationRequest presentation_request(
+ {0, 0}, {GURL("https://presentationurl.com")},
url::Origin(GURL("https://frameurl.fakeurl")));
media_router_ui_->OnDefaultPresentationChanged(presentation_request);
std::vector<MediaRouteResponseCallback> callbacks;
- EXPECT_CALL(mock_router_,
+ EXPECT_CALL(*mock_router_,
CreateRouteInternal(_, _, _, _, _,
base::TimeDelta::FromSeconds(20), false))
.WillOnce(SaveArgWithMove<4>(&callbacks));
@@ -247,7 +252,7 @@ TEST_F(MediaRouterUITest, RouteCreationTimeoutForPresentation) {
std::string expected_title =
l10n_util::GetStringFUTF8(IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT,
base::UTF8ToUTF16("frameurl.fakeurl"));
- EXPECT_CALL(mock_router_, AddIssue(IssueTitleEquals(expected_title)));
+ EXPECT_CALL(*mock_router_, AddIssue(IssueTitleEquals(expected_title)));
std::unique_ptr<RouteRequestResult> result =
RouteRequestResult::FromError("Timed out", RouteRequestResult::TIMED_OUT);
for (auto& callback : callbacks)
@@ -270,7 +275,7 @@ TEST_F(MediaRouterUITest, RouteCreationLocalFileModeInTab) {
// Expect that the media_router_ will make a call to the mock_router
// then we will want to check that it made the call with.
- EXPECT_CALL(mock_router_, CreateRouteInternal(_, _, _, _, _, _, _))
+ EXPECT_CALL(*mock_router_, CreateRouteInternal(_, _, _, _, _, _, _))
.WillOnce(SaveArgWithMove<3>(&location_file_opened));
media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
@@ -283,7 +288,7 @@ TEST_F(MediaRouterUITest, RouteCreationLocalFileModeInTab) {
TEST_F(MediaRouterUITest, RouteCreationParametersCantBeCreated) {
CreateMediaRouterUI(profile());
MediaSinkSearchResponseCallback sink_callback;
- EXPECT_CALL(mock_router_, SearchSinksInternal(_, _, _, _, _))
+ EXPECT_CALL(*mock_router_, SearchSinksInternal(_, _, _, _, _))
.WillOnce(SaveArgWithMove<4>(&sink_callback));
// Use PRESENTATION mode without setting a PresentationRequest.
@@ -291,19 +296,15 @@ TEST_F(MediaRouterUITest, RouteCreationParametersCantBeCreated) {
"sinkId", "search input", "domain", MediaCastMode::PRESENTATION);
std::string expected_title = l10n_util::GetStringUTF8(
IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_TAB);
- EXPECT_CALL(mock_router_, AddIssue(IssueTitleEquals(expected_title)));
+ EXPECT_CALL(*mock_router_, AddIssue(IssueTitleEquals(expected_title)));
std::move(sink_callback).Run("foundSinkId");
}
TEST_F(MediaRouterUITest, RouteRequestFromIncognito) {
CreateMediaRouterUI(profile()->GetOffTheRecordProfile());
+ media_router_ui_->OnDefaultPresentationChanged(presentation_request_);
- PresentationRequest presentation_request(
- RenderFrameHostId(0, 0), {GURL("https://foo.url.com/")},
- url::Origin(GURL("https://frameUrl")));
- media_router_ui_->OnDefaultPresentationChanged(presentation_request);
-
- EXPECT_CALL(mock_router_,
+ EXPECT_CALL(*mock_router_,
CreateRouteInternal(_, _, _, _, _,
base::TimeDelta::FromSeconds(20), true));
media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
@@ -430,7 +431,7 @@ TEST_F(MediaRouterUITest, UIMediaRoutesObserverAssignsCurrentCastModes) {
MediaSource media_source_3(MediaSourceForDesktop());
std::unique_ptr<MediaRouterUI::UIMediaRoutesObserver> observer(
new MediaRouterUI::UIMediaRoutesObserver(
- &mock_router_, MediaSource::Id(),
+ mock_router_, MediaSource::Id(),
base::Bind(&MediaRouterUI::OnRoutesUpdated,
base::Unretained(media_router_ui_.get()))));
@@ -467,7 +468,7 @@ TEST_F(MediaRouterUITest, UIMediaRoutesObserverAssignsCurrentCastModes) {
EXPECT_NE(end(current_cast_modes), cast_mode_entry);
EXPECT_EQ(MediaCastMode::DESKTOP_MIRROR, cast_mode_entry->second);
- EXPECT_CALL(mock_router_, UnregisterMediaRoutesObserver(_)).Times(1);
+ EXPECT_CALL(*mock_router_, UnregisterMediaRoutesObserver(_)).Times(1);
observer.reset();
}
@@ -478,7 +479,7 @@ TEST_F(MediaRouterUITest, UIMediaRoutesObserverSkipsUnavailableCastModes) {
MediaSource media_source_3(MediaSourceForDesktop());
std::unique_ptr<MediaRouterUI::UIMediaRoutesObserver> observer(
new MediaRouterUI::UIMediaRoutesObserver(
- &mock_router_, MediaSource::Id(),
+ mock_router_, MediaSource::Id(),
base::Bind(&MediaRouterUI::OnRoutesUpdated,
base::Unretained(media_router_ui_.get()))));
@@ -515,7 +516,7 @@ TEST_F(MediaRouterUITest, UIMediaRoutesObserverSkipsUnavailableCastModes) {
EXPECT_NE(end(current_cast_modes), cast_mode_entry);
EXPECT_EQ(MediaCastMode::DESKTOP_MIRROR, cast_mode_entry->second);
- EXPECT_CALL(mock_router_, UnregisterMediaRoutesObserver(_)).Times(1);
+ EXPECT_CALL(*mock_router_, UnregisterMediaRoutesObserver(_)).Times(1);
observer.reset();
}
@@ -525,10 +526,8 @@ TEST_F(MediaRouterUITest, GetExtensionNameExtensionPresent) {
std::unique_ptr<extensions::ExtensionRegistry> registry =
base::MakeUnique<extensions::ExtensionRegistry>(nullptr);
scoped_refptr<extensions::Extension> app =
- extensions::test_util::BuildApp(extensions::ExtensionBuilder())
- .MergeManifest(extensions::DictionaryBuilder()
- .Set("name", "test app name")
- .Build())
+ extensions::ExtensionBuilder(
+ "test app name", extensions::ExtensionBuilder::Type::PLATFORM_APP)
.SetID(id)
.Build();
@@ -559,15 +558,12 @@ TEST_F(MediaRouterUITest, NotFoundErrorOnCloseWithNoSinks) {
content::PresentationErrorType::PRESENTATION_ERROR_NO_AVAILABLE_SCREENS,
"No screens found.");
PresentationRequestCallbacks request_callbacks(expected_error);
- create_session_request_.reset(new CreatePresentationConnectionRequest(
- RenderFrameHostId(0, 0),
- {GURL("http://google.com/presentation"),
- GURL("http://google.com/presentation2")},
- url::Origin(GURL("http://google.com")),
+ start_presentation_context_ = base::MakeUnique<StartPresentationContext>(
+ presentation_request_,
base::Bind(&PresentationRequestCallbacks::Success,
base::Unretained(&request_callbacks)),
base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks))));
+ base::Unretained(&request_callbacks)));
CreateMediaRouterUI(profile());
// Destroying the UI should return the expected error from above to the error
// callback.
@@ -579,14 +575,12 @@ TEST_F(MediaRouterUITest, NotFoundErrorOnCloseWithNoCompatibleSinks) {
content::PresentationErrorType::PRESENTATION_ERROR_NO_AVAILABLE_SCREENS,
"No screens found.");
PresentationRequestCallbacks request_callbacks(expected_error);
- GURL presentation_url("http://google.com/presentation");
- create_session_request_.reset(new CreatePresentationConnectionRequest(
- RenderFrameHostId(0, 0), {presentation_url},
- url::Origin(GURL("http://google.com")),
+ start_presentation_context_ = base::MakeUnique<StartPresentationContext>(
+ presentation_request_,
base::Bind(&PresentationRequestCallbacks::Success,
base::Unretained(&request_callbacks)),
base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks))));
+ base::Unretained(&request_callbacks)));
CreateMediaRouterUI(profile());
// Send a sink to the UI that is compatible with sources other than the
@@ -594,8 +588,10 @@ TEST_F(MediaRouterUITest, NotFoundErrorOnCloseWithNoCompatibleSinks) {
std::vector<MediaSink> sinks;
sinks.emplace_back("sink id", "sink name", SinkIconType::GENERIC);
std::vector<url::Origin> origins;
+ auto presentation_source =
+ MediaSourceForPresentationUrl(presentation_request_.presentation_urls[0]);
for (auto* observer : media_sinks_observers_) {
- if (observer->source().id() != presentation_url.spec()) {
+ if (!(observer->source() == presentation_source)) {
observer->OnSinksUpdated(sinks, origins);
}
}
@@ -610,14 +606,12 @@ TEST_F(MediaRouterUITest, AbortErrorOnClose) {
PRESENTATION_ERROR_PRESENTATION_REQUEST_CANCELLED,
"Dialog closed.");
PresentationRequestCallbacks request_callbacks(expected_error);
- GURL presentation_url("http://google.com/presentation");
- create_session_request_.reset(new CreatePresentationConnectionRequest(
- RenderFrameHostId(0, 0), {presentation_url},
- url::Origin(GURL("http://google.com")),
+ start_presentation_context_ = base::MakeUnique<StartPresentationContext>(
+ presentation_request_,
base::Bind(&PresentationRequestCallbacks::Success,
base::Unretained(&request_callbacks)),
base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks))));
+ base::Unretained(&request_callbacks)));
CreateMediaRouterUI(profile());
// Send a sink to the UI that is compatible with the presentation url to avoid
@@ -625,10 +619,10 @@ TEST_F(MediaRouterUITest, AbortErrorOnClose) {
std::vector<MediaSink> sinks;
sinks.emplace_back("sink id", "sink name", SinkIconType::GENERIC);
std::vector<url::Origin> origins;
- MediaSource::Id presentation_source_id =
- MediaSourceForPresentationUrl(presentation_url).id();
+ auto presentation_source =
+ MediaSourceForPresentationUrl(presentation_request_.presentation_urls[0]);
for (auto* observer : media_sinks_observers_) {
- if (observer->source().id() == presentation_source_id) {
+ if (observer->source() == presentation_source) {
observer->OnSinksUpdated(sinks, origins);
}
}
@@ -702,10 +696,10 @@ TEST_F(MediaRouterUITest, OpenAndCloseUIDetailsView) {
// When the route details view is closed, the route controller observer should
// be destroyed, also triggering the destruction of the controller.
- EXPECT_CALL(mock_router_, DetachRouteController(route_id, _));
+ EXPECT_CALL(*mock_router_, DetachRouteController(route_id, _));
media_router_ui_->OnMediaControllerUIClosed();
- EXPECT_TRUE(Mock::VerifyAndClearExpectations(&mock_router_));
+ EXPECT_TRUE(Mock::VerifyAndClearExpectations(mock_router_));
}
TEST_F(MediaRouterUITest, SendMediaStatusUpdate) {
@@ -719,13 +713,19 @@ TEST_F(MediaRouterUITest, SendMediaStatusUpdate) {
// update to the message handler.
EXPECT_CALL(*message_handler_, UpdateMediaRouteStatus(status));
controller->OnMediaStatusUpdated(status);
+
+ // |controller| will outlive |mock_router_| because we passed it into
+ // testing::Return(). Invalidate it so that it doesn't reference
+ // |mock_router_| in its dtor.
+ controller->Invalidate();
}
TEST_F(MediaRouterUITest, SendInitialMediaStatusUpdate) {
MediaStatus status;
status.title = "test title";
std::string route_id = "routeId";
- auto controller = CreateMediaRouteController(route_id);
+ auto controller =
+ base::MakeRefCounted<MockMediaRouteController>(route_id, profile());
controller->OnMediaStatusUpdated(status);
CreateMediaRouterUI(profile());
@@ -735,26 +735,30 @@ TEST_F(MediaRouterUITest, SendInitialMediaStatusUpdate) {
// If the controller has already received a media status update, MediaRouterUI
// should be notified with it when it starts observing the controller.
- EXPECT_CALL(mock_router_, GetRouteController(route_id))
+ EXPECT_CALL(*mock_router_, GetRouteController(route_id))
.WillOnce(Return(controller));
EXPECT_CALL(*message_handler_, UpdateMediaRouteStatus(status));
media_router_ui_->OnMediaControllerUIAvailable(route_id);
+
+ // |controller| will outlive |mock_router_| because we passed it into
+ // testing::Return(). Invalidate it so that it doesn't reference
+ // |mock_router_| in its dtor.
+ controller->Invalidate();
}
TEST_F(MediaRouterUITest, SetsForcedCastModeWithPresentationURLs) {
+ presentation_request_.presentation_urls.push_back(
+ GURL("https://google.com/presentation2"));
content::PresentationError expected_error(
content::PresentationErrorType::PRESENTATION_ERROR_NO_AVAILABLE_SCREENS,
"No screens found.");
PresentationRequestCallbacks request_callbacks(expected_error);
- create_session_request_.reset(new CreatePresentationConnectionRequest(
- RenderFrameHostId(0, 0),
- {GURL("http://google.com/presentation"),
- GURL("http://google.com/presentation2")},
- url::Origin(GURL("http://google.com")),
+ start_presentation_context_ = base::MakeUnique<StartPresentationContext>(
+ presentation_request_,
base::Bind(&PresentationRequestCallbacks::Success,
base::Unretained(&request_callbacks)),
base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks))));
+ base::Unretained(&request_callbacks)));
SessionTabHelper::CreateForWebContents(web_contents());
web_ui_contents_.reset(
@@ -764,12 +768,12 @@ TEST_F(MediaRouterUITest, SetsForcedCastModeWithPresentationURLs) {
message_handler_ = base::MakeUnique<MockMediaRouterWebUIMessageHandler>(
media_router_ui_.get());
message_handler_->SetWebUIForTest(&web_ui_);
- EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_))
+ EXPECT_CALL(*mock_router_, RegisterMediaSinksObserver(_))
.WillRepeatedly(Invoke([this](MediaSinksObserver* observer) {
this->media_sinks_observers_.push_back(observer);
return true;
}));
- EXPECT_CALL(mock_router_, RegisterMediaRoutesObserver(_)).Times(AnyNumber());
+ EXPECT_CALL(*mock_router_, RegisterMediaRoutesObserver(_)).Times(AnyNumber());
// For some reason we push two sets of cast modes to the dialog, even when
// initializing the dialog with a presentation request. The WebUI can handle
// the forced mode that is not in the initial cast mode set, but is this a
@@ -787,9 +791,9 @@ TEST_F(MediaRouterUITest, SetsForcedCastModeWithPresentationURLs) {
expected_modes, "google.com",
base::Optional<MediaCastMode>(MediaCastMode::PRESENTATION)));
media_router_ui_->UIInitialized();
- media_router_ui_->InitForTest(&mock_router_, web_contents(),
- message_handler_.get(),
- std::move(create_session_request_), nullptr);
+ media_router_ui_->InitForTest(
+ mock_router_, web_contents(), message_handler_.get(),
+ std::move(start_presentation_context_), nullptr);
// |media_router_ui_| takes ownership of |request_callbacks|.
media_router_ui_.reset();
}
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc
index 31cb121e64d..aa311c86fff 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc
@@ -907,7 +907,7 @@ void MediaRouterWebUIMessageHandler::OnMediaControllerClosed(
void MediaRouterWebUIMessageHandler::OnPauseCurrentMedia(
const base::ListValue* args) {
- const MediaRouteController* route_controller =
+ MediaRouteController* route_controller =
media_router_ui_->GetMediaRouteController();
if (route_controller)
route_controller->Pause();
@@ -915,7 +915,7 @@ void MediaRouterWebUIMessageHandler::OnPauseCurrentMedia(
void MediaRouterWebUIMessageHandler::OnPlayCurrentMedia(
const base::ListValue* args) {
- const MediaRouteController* route_controller =
+ MediaRouteController* route_controller =
media_router_ui_->GetMediaRouteController();
if (route_controller)
route_controller->Play();
@@ -931,7 +931,7 @@ void MediaRouterWebUIMessageHandler::OnSeekCurrentMedia(
return;
}
base::TimeDelta time_delta = base::TimeDelta::FromSeconds(time);
- const MediaRouteController* route_controller =
+ MediaRouteController* route_controller =
media_router_ui_->GetMediaRouteController();
if (route_controller && current_media_status_ &&
time_delta >= base::TimeDelta() &&
@@ -949,7 +949,7 @@ void MediaRouterWebUIMessageHandler::OnSetCurrentMediaMute(
DVLOG(1) << "Unable to extract mute";
return;
}
- const MediaRouteController* route_controller =
+ MediaRouteController* route_controller =
media_router_ui_->GetMediaRouteController();
if (route_controller)
route_controller->SetMute(mute);
@@ -964,7 +964,7 @@ void MediaRouterWebUIMessageHandler::OnSetCurrentMediaVolume(
DVLOG(1) << "Unable to extract volume";
return;
}
- const MediaRouteController* route_controller =
+ MediaRouteController* route_controller =
media_router_ui_->GetMediaRouteController();
if (route_controller && volume >= 0 && volume <= 1)
route_controller->SetVolume(volume);
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc
index 9cb1e48f54e..e945cf62f82 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc
@@ -103,7 +103,7 @@ class MockMediaRouterUI : public MediaRouterUI {
MOCK_METHOD1(SeekRoute, void(base::TimeDelta time));
MOCK_METHOD1(SetRouteMute, void(bool mute));
MOCK_METHOD1(SetRouteVolume, void(float volume));
- MOCK_CONST_METHOD0(GetMediaRouteController, const MediaRouteController*());
+ MOCK_CONST_METHOD0(GetMediaRouteController, MediaRouteController*());
};
class TestMediaRouterWebUIMessageHandler
@@ -600,12 +600,8 @@ TEST_F(MediaRouterWebUIMessageHandlerTest, OnRouteDetailsOpenedAndClosed) {
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnMediaCommandsReceived) {
- mojom::MediaControllerPtr mojo_media_controller;
- mojo::MakeRequest(&mojo_media_controller);
- MockMediaRouter media_router;
- scoped_refptr<MockMediaRouteController> controller =
- new MockMediaRouteController("routeId", std::move(mojo_media_controller),
- &media_router);
+ auto controller =
+ base::MakeRefCounted<MockMediaRouteController>("routeId", profile());
EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
.WillRepeatedly(Return(controller.get()));
MediaStatus status;
@@ -642,12 +638,8 @@ TEST_F(MediaRouterWebUIMessageHandlerTest, OnMediaCommandsReceived) {
}
TEST_F(MediaRouterWebUIMessageHandlerTest, OnInvalidMediaCommandsReceived) {
- mojom::MediaControllerPtr mojo_media_controller;
- mojo::MakeRequest(&mojo_media_controller);
- MockMediaRouter media_router;
- scoped_refptr<MockMediaRouteController> controller =
- new MockMediaRouteController("routeId", std::move(mojo_media_controller),
- &media_router);
+ auto controller =
+ base::MakeRefCounted<MockMediaRouteController>("routeId", profile());
EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
.WillRepeatedly(Return(controller.get()));
diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
index e6d64f90ff5..8cd1001ad84 100644
--- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
@@ -4,25 +4,83 @@
#include "chrome/browser/ui/webui/memory_internals_ui.h"
+#include <iterator>
+
+#include "base/allocator/features.h"
#include "base/bind.h"
#include "base/memory/ptr_util.h"
+#include "base/memory/weak_ptr.h"
+#include "base/path_service.h"
+#include "base/process/process_handle.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/profiling_host/profiling_process_host.h"
+#include "chrome/browser/ui/chrome_select_file_policy.h"
+#include "chrome/common/chrome_paths.h"
+#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "content/public/browser/browser_child_process_host_iterator.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/child_process_data.h"
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
+#include "content/public/common/process_type.h"
+#include "content/public/common/service_manager_connection.h"
+#include "mojo/public/cpp/system/platform_handle.h"
+#include "services/service_manager/public/cpp/connector.h"
+#include "ui/shell_dialogs/select_file_dialog.h"
+#include "ui/shell_dialogs/select_file_policy.h"
namespace {
+// Returns the string to display at the top of the page for help.
+std::string GetMessageString() {
+#if BUILDFLAG(USE_ALLOCATOR_SHIM)
+ switch (profiling::ProfilingProcessHost::GetCurrentMode()) {
+ case profiling::ProfilingProcessHost::Mode::kBrowser:
+ return std::string("Memory logging is enabled for the browser only.");
+
+ case profiling::ProfilingProcessHost::Mode::kAll:
+ return std::string("Memory logging is enabled for all processes.");
+
+ case profiling::ProfilingProcessHost::Mode::kNone:
+ default:
+ return std::string("Memory logging is not enabled. Start with --") +
+ switches::kMemlog + "=" + switches::kMemlogModeAll +
+ " to log all processes, or --" + switches::kMemlog + "=" +
+ switches::kMemlogModeBrowser +
+ " to log only the browser process. "
+ "This is also configurable in chrome://flags";
+ }
+#else
+ return "Memory logging is not available in this build because "
+ "USE_ALLOCATOR_SHIM is not set. It can not have sanitizers enabled "
+ "and on Windows it must be a release non-component build.";
+#endif
+}
+
// Generates one row of the returned process info.
-base::Value MakeProcessInfo(int pid, const std::string& description) {
+base::Value MakeProcessInfo(int pid, std::string description) {
base::Value result(base::Value::Type::LIST);
result.GetList().push_back(base::Value(pid));
- result.GetList().push_back(base::Value(description));
+ result.GetList().push_back(base::Value(std::move(description)));
return result;
}
+// Some child processes have good descriptions and some don't, this function
+// returns the best it can given the data.
+std::string GetChildDescription(const content::ChildProcessData& data) {
+ if (!data.name.empty())
+ return base::UTF16ToUTF8(data.name);
+ return content::GetProcessTypeNameInEnglish(data.process_type);
+}
+
content::WebUIDataSource* CreateMemoryInternalsUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIMemoryInternalsHost);
@@ -31,9 +89,10 @@ content::WebUIDataSource* CreateMemoryInternalsUIHTMLSource() {
return source;
}
-class MemoryInternalsDOMHandler : public content::WebUIMessageHandler {
+class MemoryInternalsDOMHandler : public content::WebUIMessageHandler,
+ ui::SelectFileDialog::Listener {
public:
- MemoryInternalsDOMHandler();
+ explicit MemoryInternalsDOMHandler(content::WebUI* web_ui);
~MemoryInternalsDOMHandler() override;
// WebUIMessageHandler implementation.
@@ -45,13 +104,37 @@ class MemoryInternalsDOMHandler : public content::WebUIMessageHandler {
// Callback for the "dumpProcess" message.
void HandleDumpProcess(const base::ListValue* args);
+ // Callback for the "reportProcess" message.
+ void HandleReportProcess(const base::ListValue* args);
+
private:
+ // Hops to the IO thread to enumerate child processes, and back to the UI
+ // thread to fill in the renderer processes.
+ static void GetChildProcessesOnIOThread(
+ base::WeakPtr<MemoryInternalsDOMHandler> dom_handler);
+ void ReturnProcessListOnUIThread(std::vector<base::Value> children);
+
+ // SelectFileDialog::Listener implementation:
+ void FileSelected(const base::FilePath& path,
+ int index,
+ void* params) override;
+ void FileSelectionCanceled(void* params) override;
+
+ scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
+ content::WebUI* web_ui_; // The WebUI that owns us.
+
+ base::WeakPtrFactory<MemoryInternalsDOMHandler> weak_factory_;
+
DISALLOW_COPY_AND_ASSIGN(MemoryInternalsDOMHandler);
};
-MemoryInternalsDOMHandler::MemoryInternalsDOMHandler() {}
+MemoryInternalsDOMHandler::MemoryInternalsDOMHandler(content::WebUI* web_ui)
+ : web_ui_(web_ui), weak_factory_(this) {}
-MemoryInternalsDOMHandler::~MemoryInternalsDOMHandler() {}
+MemoryInternalsDOMHandler::~MemoryInternalsDOMHandler() {
+ if (select_file_dialog_)
+ select_file_dialog_->ListenerDestroyed();
+}
void MemoryInternalsDOMHandler::RegisterMessages() {
// Unretained should be OK here since this class is bound to the lifetime of
@@ -61,33 +144,161 @@ void MemoryInternalsDOMHandler::RegisterMessages() {
base::Bind(&MemoryInternalsDOMHandler::HandleRequestProcessList,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "dumpProcess", base::Bind(&MemoryInternalsDOMHandler::HandleDumpProcess,
- base::Unretained(this)));
+ "dumpProcess",
+ base::BindRepeating(&MemoryInternalsDOMHandler::HandleDumpProcess,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "reportProcess",
+ base::BindRepeating(&MemoryInternalsDOMHandler::HandleReportProcess,
+ base::Unretained(this)));
}
void MemoryInternalsDOMHandler::HandleRequestProcessList(
const base::ListValue* args) {
- base::Value result(base::Value::Type::LIST);
- // Return some canned data for now.
- // TODO(brettW) hook this up.
- result.GetList().push_back(MakeProcessInfo(11234, "Process 11234 [Browser]"));
- result.GetList().push_back(MakeProcessInfo(11235, "Process 11235 [GPU]"));
- result.GetList().push_back(MakeProcessInfo(11236, "Process 11236 [Rend]"));
+ // 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.
+ content::BrowserThread::PostTask(
+ content::BrowserThread::IO, FROM_HERE,
+ base::Bind(&MemoryInternalsDOMHandler::GetChildProcessesOnIOThread,
+ weak_factory_.GetWeakPtr()));
+}
+
+void MemoryInternalsDOMHandler::HandleDumpProcess(const base::ListValue* args) {
+ if (!args->is_list() || args->GetList().size() != 1)
+ return;
+ const base::Value& pid_value = args->GetList()[0];
+ if (!pid_value.is_int())
+ return;
+
+ int pid = pid_value.GetInt();
+ base::FilePath default_file = base::FilePath().AppendASCII(
+ base::StringPrintf("memlog_%lld.json.gz", static_cast<long long>(pid)));
+
+#if defined(OS_ANDROID)
+ // On Android write to the user data dir.
+ // TODO(bug 757115) Does it make sense to show the Android file picker here
+ // instead? Need to test what that looks like.
+ base::FilePath user_data_dir;
+ PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
+ base::FilePath output_path = user_data_dir.Append(default_file);
+ profiling::ProfilingProcessHost::GetInstance()->RequestProcessDump(
+ pid, output_path);
+ (void)web_ui_; // Avoid warning about not using private web_ui_ member.
+#else
+ if (select_file_dialog_)
+ return; // Currently running, wait for existing save to complete.
+ select_file_dialog_ = ui::SelectFileDialog::Create(
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui_->GetWebContents()));
+
+ // Pass the PID to dump via the "params" for the callback to use.
+ select_file_dialog_->SelectFile(
+ ui::SelectFileDialog::SELECT_SAVEAS_FILE, base::string16(), default_file,
+ nullptr, 0, FILE_PATH_LITERAL(".json.gz"),
+ web_ui_->GetWebContents()->GetTopLevelNativeWindow(),
+ reinterpret_cast<void*>(pid));
+#endif
+}
+
+void MemoryInternalsDOMHandler::HandleReportProcess(
+ const base::ListValue* args) {
+ if (!args->is_list() || args->GetList().size() != 1)
+ return;
+ const base::Value& pid_value = args->GetList()[0];
+ if (!pid_value.is_int())
+ return;
+
+ int pid = pid_value.GetInt();
+ profiling::ProfilingProcessHost::GetInstance()->RequestProcessReport(pid);
+}
+
+void MemoryInternalsDOMHandler::GetChildProcessesOnIOThread(
+ base::WeakPtr<MemoryInternalsDOMHandler> dom_handler) {
+ std::vector<base::Value> result;
+
+ if (profiling::ProfilingProcessHost::GetCurrentMode() ==
+ profiling::ProfilingProcessHost::Mode::kAll) {
+ // Add child processes (this does not include renderers).
+ for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
+ // Note that ChildProcessData.id is a child ID and not an OS PID.
+ const content::ChildProcessData& data = iter.GetData();
+ result.push_back(MakeProcessInfo(base::GetProcId(data.handle),
+ GetChildDescription(data)));
+ }
+ }
+
+ content::BrowserThread::PostTask(
+ content::BrowserThread::UI, FROM_HERE,
+ base::BindOnce(&MemoryInternalsDOMHandler::ReturnProcessListOnUIThread,
+ dom_handler, std::move(result)));
+}
+
+void MemoryInternalsDOMHandler::ReturnProcessListOnUIThread(
+ std::vector<base::Value> children) {
+ // This function will be called with the child processes that are not
+ // renderers. It will full in the browser and renderer processes on the UI
+ // thread (RenderProcessHost is UI-thread only) and return the full list.
+ base::Value process_list_value(base::Value::Type::LIST);
+ std::vector<base::Value>& process_list = process_list_value.GetList();
+
+ profiling::ProfilingProcessHost::Mode profiling_mode =
+ profiling::ProfilingProcessHost::GetCurrentMode();
+
+ // Add browser process.
+ if (profiling_mode != profiling::ProfilingProcessHost::Mode::kNone) {
+ process_list.push_back(
+ MakeProcessInfo(base::GetCurrentProcId(), "Browser"));
+ }
+
+ // Append renderer processes.
+ if (profiling_mode == profiling::ProfilingProcessHost::Mode::kAll) {
+ auto iter = content::RenderProcessHost::AllHostsIterator();
+ while (!iter.IsAtEnd()) {
+ base::ProcessHandle renderer_handle = iter.GetCurrentValue()->GetHandle();
+ base::ProcessId renderer_pid = base::GetProcId(renderer_handle);
+ if (renderer_pid != 0) {
+ // TODO(brettw) make a better description of the process, maybe see
+ // what TaskManager does to get the page title.
+ process_list.push_back(MakeProcessInfo(renderer_pid, "Renderer"));
+ }
+ iter.Advance();
+ }
+ }
+
+ // Append all child processes collected on the IO thread.
+ process_list.insert(process_list.end(),
+ std::make_move_iterator(std::begin(children)),
+ std::make_move_iterator(std::end(children)));
+
+ // Pass the results in a dictionary.
+ base::Value result(base::Value::Type::DICTIONARY);
+ result.SetKey("message", base::Value(GetMessageString()));
+ result.SetKey("processes", std::move(process_list_value));
AllowJavascript();
CallJavascriptFunction("returnProcessList", result);
DisallowJavascript();
}
-void MemoryInternalsDOMHandler::HandleDumpProcess(const base::ListValue* args) {
- // TODO(brettW) hook this up.
+void MemoryInternalsDOMHandler::FileSelected(const base::FilePath& path,
+ int index,
+ void* params) {
+ // The PID to dump was stashed in the params.
+ int pid = reinterpret_cast<intptr_t>(params);
+ profiling::ProfilingProcessHost::GetInstance()->RequestProcessDump(pid, path);
+ select_file_dialog_ = nullptr;
+}
+
+void MemoryInternalsDOMHandler::FileSelectionCanceled(void* params) {
+ select_file_dialog_ = nullptr;
}
} // namespace
MemoryInternalsUI::MemoryInternalsUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
- web_ui->AddMessageHandler(base::MakeUnique<MemoryInternalsDOMHandler>());
+ web_ui->AddMessageHandler(
+ base::MakeUnique<MemoryInternalsDOMHandler>(web_ui));
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, CreateMemoryInternalsUIHTMLSource());
diff --git a/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h b/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h
index 501a9cc48bc..627e5799b1b 100644
--- a/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h
+++ b/chromium/chrome/browser/ui/webui/mojo_web_ui_controller.h
@@ -13,6 +13,8 @@
#include "chrome/browser/ui/webui/mojo_web_ui_handler.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui_controller.h"
#include "mojo/public/cpp/system/core.h"
#include "services/service_manager/public/cpp/binder_registry.h"
@@ -38,22 +40,26 @@ class MojoWebUIControllerBase : public content::WebUIController {
// . Override BindUIHandler() to create and bind the implementation of the
// bindings.
template <typename Interface>
-class MojoWebUIController : public MojoWebUIControllerBase {
+class MojoWebUIController : public MojoWebUIControllerBase,
+ public content::WebContentsObserver {
public:
explicit MojoWebUIController(content::WebUI* contents)
- : MojoWebUIControllerBase(contents), weak_factory_(this) {}
+ : MojoWebUIControllerBase(contents),
+ content::WebContentsObserver(contents->GetWebContents()),
+ weak_factory_(this) {
+ registry_.AddInterface<Interface>(base::Bind(
+ &MojoWebUIController::BindUIHandler, base::Unretained(this)));
+ }
~MojoWebUIController() override {}
- void RenderFrameCreated(
- content::RenderFrameHost* render_frame_host) override {
- MojoWebUIControllerBase::RenderFrameCreated(render_frame_host);
-
+ // content::WebContentsObserver implementation.
+ void OnInterfaceRequestFromFrame(
+ content::RenderFrameHost* render_frame_host,
+ const std::string& interface_name,
+ mojo::ScopedMessagePipeHandle* interface_pipe) override {
// Right now, this is expected to be called only for main frames.
DCHECK(!render_frame_host->GetParent());
- render_frame_host->GetInterfaceRegistry()->
- AddInterface<Interface>(
- base::Bind(&MojoWebUIController::BindUIHandler,
- weak_factory_.GetWeakPtr()));
+ registry_.TryBindInterface(interface_name, interface_pipe);
}
protected:
@@ -61,6 +67,8 @@ class MojoWebUIController : public MojoWebUIControllerBase {
virtual void BindUIHandler(mojo::InterfaceRequest<Interface> request) = 0;
private:
+ service_manager::BinderRegistry registry_;
+
base::WeakPtrFactory<MojoWebUIController> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MojoWebUIController);
diff --git a/chromium/chrome/browser/ui/webui/net_export_ui.cc b/chromium/chrome/browser/ui/webui/net_export_ui.cc
index d5b86613512..5e3561ca70b 100644
--- a/chromium/chrome/browser/ui/webui/net_export_ui.cc
+++ b/chromium/chrome/browser/ui/webui/net_export_ui.cc
@@ -168,7 +168,6 @@ NetExportMessageHandler::NetExportMessageHandler()
state_observer_manager_(this),
weak_ptr_factory_(this) {
file_writer_->Initialize(
- BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE_USER_BLOCKING),
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO));
}
@@ -375,7 +374,7 @@ void NetExportMessageHandler::ShowSelectFileDialog(
WebContents* webcontents = web_ui()->GetWebContents();
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(webcontents));
+ this, std::make_unique<ChromeSelectFilePolicy>(webcontents));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions = {{FILE_PATH_LITERAL("json")}};
gfx::NativeWindow owning_window = webcontents->GetTopLevelNativeWindow();
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 57f7ed64a22..1c3b918736f 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
@@ -276,9 +276,11 @@ class NetInternalsMessageHandler::IOThreadImpl
void OnReloadProxySettings(const base::ListValue* list);
void OnClearBadProxies(const base::ListValue* list);
void OnClearHostResolverCache(const base::ListValue* list);
+ void OnDomainSecurityPolicyDelete(const base::ListValue* list);
void OnHSTSQuery(const base::ListValue* list);
void OnHSTSAdd(const base::ListValue* list);
- void OnHSTSDelete(const base::ListValue* list);
+ void OnExpectCTQuery(const base::ListValue* list);
+ void OnExpectCTAdd(const base::ListValue* list);
void OnCloseIdleSockets(const base::ListValue* list);
void OnFlushSocketPools(const base::ListValue* list);
#if defined(OS_WIN)
@@ -407,6 +409,10 @@ void NetInternalsMessageHandler::RegisterMessages() {
base::Bind(&IOThreadImpl::CallbackHelper,
&IOThreadImpl::OnClearHostResolverCache, proxy_));
web_ui()->RegisterMessageCallback(
+ "domainSecurityPolicyDelete",
+ base::Bind(&IOThreadImpl::CallbackHelper,
+ &IOThreadImpl::OnDomainSecurityPolicyDelete, proxy_));
+ web_ui()->RegisterMessageCallback(
"hstsQuery",
base::Bind(&IOThreadImpl::CallbackHelper,
&IOThreadImpl::OnHSTSQuery, proxy_));
@@ -415,9 +421,11 @@ void NetInternalsMessageHandler::RegisterMessages() {
base::Bind(&IOThreadImpl::CallbackHelper,
&IOThreadImpl::OnHSTSAdd, proxy_));
web_ui()->RegisterMessageCallback(
- "hstsDelete",
- base::Bind(&IOThreadImpl::CallbackHelper,
- &IOThreadImpl::OnHSTSDelete, proxy_));
+ "expectCTQuery", base::Bind(&IOThreadImpl::CallbackHelper,
+ &IOThreadImpl::OnExpectCTQuery, proxy_));
+ web_ui()->RegisterMessageCallback(
+ "expectCTAdd", base::Bind(&IOThreadImpl::CallbackHelper,
+ &IOThreadImpl::OnExpectCTAdd, proxy_));
web_ui()->RegisterMessageCallback(
"closeIdleSockets",
base::Bind(&IOThreadImpl::CallbackHelper,
@@ -665,11 +673,30 @@ void NetInternalsMessageHandler::IOThreadImpl::OnClearHostResolverCache(
SendNetInfo(net::NET_INFO_HOST_RESOLVER);
}
+void NetInternalsMessageHandler::IOThreadImpl::OnDomainSecurityPolicyDelete(
+ const base::ListValue* list) {
+ // |list| should be: [<domain to query>].
+ std::string domain;
+ bool result = list->GetString(0, &domain);
+ DCHECK(result);
+ if (!base::IsStringASCII(domain)) {
+ // There cannot be a unicode entry in the HSTS set.
+ return;
+ }
+ net::TransportSecurityState* transport_security_state =
+ GetMainContext()->transport_security_state();
+ if (!transport_security_state)
+ return;
+
+ transport_security_state->DeleteDynamicDataForHost(domain);
+}
+
void NetInternalsMessageHandler::IOThreadImpl::OnHSTSQuery(
const base::ListValue* list) {
// |list| should be: [<domain to query>].
std::string domain;
- CHECK(list->GetString(0, &domain));
+ bool get_domain_result = list->GetString(0, &domain);
+ DCHECK(get_domain_result);
auto result = base::MakeUnique<base::DictionaryValue>();
if (base::IsStringASCII(domain)) {
@@ -678,7 +705,7 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSQuery(
if (transport_security_state) {
net::TransportSecurityState::STSState static_sts_state;
net::TransportSecurityState::PKPState static_pkp_state;
- const bool found_static = transport_security_state->GetStaticDomainState(
+ bool found_static = transport_security_state->GetStaticDomainState(
domain, &static_sts_state, &static_pkp_state);
if (found_static) {
result->SetInteger("static_upgrade_mode",
@@ -703,13 +730,11 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSQuery(
net::TransportSecurityState::STSState dynamic_sts_state;
net::TransportSecurityState::PKPState dynamic_pkp_state;
- const bool found_sts_dynamic =
- transport_security_state->GetDynamicSTSState(domain,
- &dynamic_sts_state);
+ bool found_sts_dynamic = transport_security_state->GetDynamicSTSState(
+ domain, &dynamic_sts_state);
- const bool found_pkp_dynamic =
- transport_security_state->GetDynamicPKPState(domain,
- &dynamic_pkp_state);
+ bool found_pkp_dynamic = transport_security_state->GetDynamicPKPState(
+ domain, &dynamic_pkp_state);
if (found_sts_dynamic) {
result->SetInteger("dynamic_upgrade_mode",
static_cast<int>(dynamic_sts_state.upgrade_mode));
@@ -751,18 +776,22 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd(
// |list| should be: [<domain to query>, <STS include subdomains>, <PKP
// include subdomains>, <key pins>].
std::string domain;
- CHECK(list->GetString(0, &domain));
+ bool result = list->GetString(0, &domain);
+ DCHECK(result);
if (!base::IsStringASCII(domain)) {
// Silently fail. The user will get a helpful error if they query for the
// name.
return;
}
bool sts_include_subdomains;
- CHECK(list->GetBoolean(1, &sts_include_subdomains));
+ result = list->GetBoolean(1, &sts_include_subdomains);
+ DCHECK(result);
bool pkp_include_subdomains;
- CHECK(list->GetBoolean(2, &pkp_include_subdomains));
+ result = list->GetBoolean(2, &pkp_include_subdomains);
+ DCHECK(result);
std::string hashes_str;
- CHECK(list->GetString(3, &hashes_str));
+ result = list->GetString(3, &hashes_str);
+ DCHECK(result);
net::TransportSecurityState* transport_security_state =
GetMainContext()->transport_security_state();
@@ -781,21 +810,72 @@ void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd(
hashes, GURL());
}
-void NetInternalsMessageHandler::IOThreadImpl::OnHSTSDelete(
+void NetInternalsMessageHandler::IOThreadImpl::OnExpectCTQuery(
const base::ListValue* list) {
// |list| should be: [<domain to query>].
std::string domain;
- CHECK(list->GetString(0, &domain));
+ bool domain_result = list->GetString(0, &domain);
+ DCHECK(domain_result);
+ auto result = base::MakeUnique<base::DictionaryValue>();
+
+ if (base::IsStringASCII(domain)) {
+ net::TransportSecurityState* transport_security_state =
+ GetMainContext()->transport_security_state();
+ if (transport_security_state) {
+ net::TransportSecurityState::ExpectCTState dynamic_expect_ct_state;
+ bool found = transport_security_state->GetDynamicExpectCTState(
+ domain, &dynamic_expect_ct_state);
+
+ // TODO(estark): query static Expect-CT state as well.
+ if (found) {
+ result->SetString("dynamic_expect_ct_domain", domain);
+ result->SetDouble("dynamic_expect_ct_observed",
+ dynamic_expect_ct_state.last_observed.ToDoubleT());
+ result->SetDouble("dynamic_expect_ct_expiry",
+ dynamic_expect_ct_state.expiry.ToDoubleT());
+ result->SetBoolean("dynamic_expect_ct_enforce",
+ dynamic_expect_ct_state.enforce);
+ result->SetString("dynamic_expect_ct_report_uri",
+ dynamic_expect_ct_state.report_uri.spec());
+ }
+
+ result->SetBoolean("result", found);
+ } else {
+ result->SetString("error", "no Expect-CT state active");
+ }
+ } else {
+ result->SetString("error", "non-ASCII domain name");
+ }
+
+ SendJavascriptCommand("receivedExpectCTResult", std::move(result));
+}
+
+void NetInternalsMessageHandler::IOThreadImpl::OnExpectCTAdd(
+ const base::ListValue* list) {
+ // |list| should be: [<domain to add>, <report URI>, <enforce>].
+ std::string domain;
+ bool result = list->GetString(0, &domain);
+ DCHECK(result);
if (!base::IsStringASCII(domain)) {
- // There cannot be a unicode entry in the HSTS set.
+ // Silently fail. The user will get a helpful error if they query for the
+ // name.
return;
}
+ std::string report_uri_str;
+ result = list->GetString(1, &report_uri_str);
+ DCHECK(result);
+ bool enforce;
+ result = list->GetBoolean(2, &enforce);
+ DCHECK(result);
+
net::TransportSecurityState* transport_security_state =
GetMainContext()->transport_security_state();
if (!transport_security_state)
return;
- transport_security_state->DeleteDynamicDataForHost(domain);
+ base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
+ transport_security_state->AddExpectCT(domain, expiry, enforce,
+ GURL(report_uri_str));
}
void NetInternalsMessageHandler::IOThreadImpl::OnFlushSocketPools(
diff --git a/chromium/chrome/browser/ui/webui/ntp/OWNERS b/chromium/chrome/browser/ui/webui/ntp/OWNERS
index df619791e08..32b85cb193d 100644
--- a/chromium/chrome/browser/ui/webui/ntp/OWNERS
+++ b/chromium/chrome/browser/ui/webui/ntp/OWNERS
@@ -1,5 +1,4 @@
estade@chromium.org
-dbeam@chromium.org
# TEAM: ntp-dev@chromium.org
# COMPONENT: UI>Browser>NewTabPage
diff --git a/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc b/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc
new file mode 100644
index 00000000000..5112ef8092d
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.cc
@@ -0,0 +1,74 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/ntp/app_icon_webui_handler.h"
+
+#include <stddef.h>
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/strings/stringprintf.h"
+#include "base/values.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/url_constants.h"
+#include "extensions/browser/extension_registry.h"
+#include "third_party/skia/include/core/SkBitmap.h"
+#include "ui/gfx/codec/png_codec.h"
+#include "ui/gfx/color_analysis.h"
+
+namespace {
+
+std::unique_ptr<base::Value> GetDominantColorCssString(
+ scoped_refptr<base::RefCountedMemory> png) {
+ color_utils::GridSampler sampler;
+ SkColor color = color_utils::CalculateKMeanColorOfPNG(png);
+ return base::MakeUnique<base::Value>(
+ base::StringPrintf("rgb(%d, %d, %d)", SkColorGetR(color),
+ SkColorGetG(color), SkColorGetB(color)));
+}
+
+} // namespace
+
+AppIconWebUIHandler::AppIconWebUIHandler() {
+ extension_icon_manager_.set_observer(this);
+}
+
+AppIconWebUIHandler::~AppIconWebUIHandler() {}
+
+void AppIconWebUIHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "getAppIconDominantColor",
+ base::Bind(&AppIconWebUIHandler::HandleGetAppIconDominantColor,
+ base::Unretained(this)));
+}
+
+void AppIconWebUIHandler::HandleGetAppIconDominantColor(
+ const base::ListValue* args) {
+ std::string extension_id;
+ CHECK(args->GetString(0, &extension_id));
+
+ Profile* profile = Profile::FromWebUI(web_ui());
+ extensions::ExtensionRegistry* extension_registry =
+ extensions::ExtensionRegistry::Get(profile);
+ const extensions::Extension* extension =
+ extension_registry->enabled_extensions().GetByID(extension_id);
+ if (!extension)
+ return;
+ extension_icon_manager_.LoadIcon(profile, extension);
+}
+
+void AppIconWebUIHandler::OnImageLoaded(const std::string& extension_id) {
+ gfx::Image icon = extension_icon_manager_.GetIcon(extension_id);
+ // TODO(estade): would be nice to avoid a round trip through png encoding.
+ std::vector<unsigned char> bits;
+ if (!gfx::PNGCodec::EncodeBGRASkBitmap(*icon.ToSkBitmap(), true, &bits))
+ return;
+ scoped_refptr<base::RefCountedStaticMemory> bits_mem(
+ new base::RefCountedStaticMemory(&bits.front(), bits.size()));
+ std::unique_ptr<base::Value> color_value =
+ GetDominantColorCssString(bits_mem);
+ base::Value id(extension_id);
+ web_ui()->CallJavascriptFunctionUnsafe("ntp.setFaviconDominantColor", id,
+ *color_value);
+}
diff --git a/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.h b/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.h
new file mode 100644
index 00000000000..18b05194c10
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/ntp/app_icon_webui_handler.h
@@ -0,0 +1,46 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_NTP_APP_ICON_WEBUI_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_NTP_APP_ICON_WEBUI_HANDLER_H_
+
+#include <memory>
+#include <string>
+
+#include "base/macros.h"
+#include "base/task/cancelable_task_tracker.h"
+#include "chrome/browser/extensions/extension_icon_manager.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace base {
+class ListValue;
+}
+
+// Handles requests for app icon "dominant" color, i.e. the stripe that appears
+// at the bottom of an app tile that has been generated from a link.
+class AppIconWebUIHandler : public content::WebUIMessageHandler,
+ public ExtensionIconManager::Observer {
+ public:
+ AppIconWebUIHandler();
+ ~AppIconWebUIHandler() override;
+
+ // WebUIMessageHandler
+ void RegisterMessages() override;
+
+ // The sole argument is the extension ID.
+ void HandleGetAppIconDominantColor(const base::ListValue* args);
+
+ // ExtensionIconManager::Observer:
+ void OnImageLoaded(const std::string& extension_id) override;
+
+ private:
+ base::CancelableTaskTracker cancelable_task_tracker_;
+
+ // Manage retrieval of icons from apps.
+ ExtensionIconManager extension_icon_manager_;
+
+ DISALLOW_COPY_AND_ASSIGN(AppIconWebUIHandler);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_NTP_APP_ICON_WEBUI_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
index ad2603e6cd0..80f8da213b9 100644
--- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
@@ -70,6 +70,7 @@
#include "extensions/common/extension.h"
#include "extensions/common/extension_icon_set.h"
#include "extensions/common/extension_set.h"
+#include "extensions/common/manifest_handlers/icons_handler.h"
#include "net/base/url_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -163,12 +164,25 @@ void AppLauncherHandler::CreateAppInfo(
service->profile())->management_policy()->UserMayModifySettings(
extension, NULL));
- // Instead of setting grayscale here, we do it in apps_page.js.
- GURL icon = extensions::ExtensionIconSource::GetIconURL(
- extension, extension_misc::EXTENSION_ICON_LARGE,
- ExtensionIconSet::MATCH_BIGGER, false);
- DCHECK_NE(GURL(), icon);
- value->SetString("icon", icon.spec());
+ auto icon_size = extension_misc::EXTENSION_ICON_LARGE;
+ auto match_type = ExtensionIconSet::MATCH_BIGGER;
+ bool has_non_default_large_icon =
+ !extensions::IconsInfo::GetIconURL(extension, icon_size, match_type)
+ .is_empty();
+ GURL large_icon = extensions::ExtensionIconSource::GetIconURL(
+ extension, icon_size, match_type, false);
+ value->SetString("icon_big", large_icon.spec());
+ value->SetBoolean("icon_big_exists", has_non_default_large_icon);
+
+ icon_size = extension_misc::EXTENSION_ICON_BITTY;
+ bool has_non_default_small_icon =
+ !extensions::IconsInfo::GetIconURL(extension, icon_size, match_type)
+ .is_empty();
+ GURL small_icon = extensions::ExtensionIconSource::GetIconURL(
+ extension, icon_size, match_type, false);
+ value->SetString("icon_small", small_icon.spec());
+ value->SetBoolean("icon_small_exists", has_non_default_small_icon);
+
value->SetInteger("launch_container",
extensions::AppLaunchInfo::GetLaunchContainer(extension));
ExtensionPrefs* prefs = ExtensionPrefs::Get(service->profile());
@@ -384,10 +398,9 @@ void AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) {
base::ListValue* list = update.Get();
list->Set(0, base::MakeUnique<base::Value>(
l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)));
- dictionary->Set("appPageNames", base::MakeUnique<base::Value>(*list));
+ dictionary->SetKey("appPageNames", list->Clone());
} else {
- dictionary->Set("appPageNames",
- base::MakeUnique<base::Value>(*app_page_names));
+ dictionary->SetKey("appPageNames", app_page_names->Clone());
}
}
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 c9e54c0d2c5..2441a60cc94 100644
--- a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
@@ -77,6 +77,7 @@ bool ChromeNTPTilesInternalsMessageHandlerClient::DoesSourceExist(
case ntp_tiles::TileSource::WHITELIST:
case ntp_tiles::TileSource::HOMEPAGE:
return true;
+ case ntp_tiles::TileSource::POPULAR_BAKED_IN:
case ntp_tiles::TileSource::POPULAR:
#if defined(OS_ANDROID)
return true;
diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc
index 3e370fc2487..09b0068c7fc 100644
--- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc
@@ -18,7 +18,7 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
-#include "chrome/browser/android/offline_pages/prefetch/prefetch_background_task.h"
+#include "chrome/browser/offline_pages/android/prefetch_background_task_android.h"
#include "chrome/browser/offline_pages/offline_page_model_factory.h"
#include "chrome/browser/offline_pages/prefetch/prefetch_service_factory.h"
#include "chrome/browser/offline_pages/request_coordinator_factory.h"
@@ -206,6 +206,7 @@ void OfflineInternalsUIMessageHandler::HandleStoredPagesCallback(
offline_page->SetDouble("lastAccessTime", page.last_access_time.ToJsTime());
offline_page->SetInteger("accessCount", page.access_count);
offline_page->SetString("originalUrl", page.original_url.spec());
+ offline_page->SetString("requestOrigin", page.request_origin);
results.Append(std::move(offline_page));
}
ResolveJavascriptCallback(base::Value(callback_id), results);
@@ -230,6 +231,7 @@ void OfflineInternalsUIMessageHandler::HandleRequestQueueCallback(
save_page_request->SetString("id", std::to_string(request->request_id()));
save_page_request->SetString("originalUrl",
request->original_url().spec());
+ save_page_request->SetString("requestOrigin", request->request_origin());
save_page_requests.Append(std::move(save_page_request));
}
}
@@ -295,8 +297,10 @@ void OfflineInternalsUIMessageHandler::HandleScheduleNwake(
const base::Value* callback_id;
CHECK(args->Get(0, &callback_id));
- offline_pages::PrefetchBackgroundTask::Schedule(0);
-
+ if (prefetch_service_) {
+ prefetch_service_->GetPrefetchBackgroundTaskHandler()
+ ->EnsureTaskScheduled();
+ }
ResolveJavascriptCallback(*callback_id, base::Value("Scheduled."));
}
@@ -306,7 +310,10 @@ void OfflineInternalsUIMessageHandler::HandleCancelNwake(
const base::Value* callback_id;
CHECK(args->Get(0, &callback_id));
- offline_pages::PrefetchBackgroundTask::Cancel();
+ if (prefetch_service_) {
+ prefetch_service_->GetPrefetchBackgroundTaskHandler()
+ ->CancelBackgroundTask();
+ }
ResolveJavascriptCallback(*callback_id, base::Value("Cancelled."));
}
diff --git a/chromium/chrome/browser/ui/webui/options/DEPS b/chromium/chrome/browser/ui/webui/options/DEPS
deleted file mode 100644
index 0cb6537cd9d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/DEPS
+++ /dev/null
@@ -1,4 +0,0 @@
-include_rules = [
- "+components/user_manager",
- "+third_party/libaddressinput", # for third_party/libaddressinput/messages.h
-]
diff --git a/chromium/chrome/browser/ui/webui/options/OWNERS b/chromium/chrome/browser/ui/webui/options/OWNERS
deleted file mode 100644
index 12eda5ad501..00000000000
--- a/chromium/chrome/browser/ui/webui/options/OWNERS
+++ /dev/null
@@ -1,8 +0,0 @@
-# This UI is deprecated. See chrome/browser/ui/webui/settings/ instead.
-set noparent
-
-dbeam@chromium.org
-stevenjb@chromium.org
-
-per-file sync_setup_handler*=atwilson@chromium.org
-per-file sync_setup_handler*=rogerta@chromium.org
diff --git a/chromium/chrome/browser/ui/webui/options/autofill_options_handler.cc b/chromium/chrome/browser/ui/webui/options/autofill_options_handler.cc
deleted file mode 100644
index f4480a23c69..00000000000
--- a/chromium/chrome/browser/ui/webui/options/autofill_options_handler.cc
+++ /dev/null
@@ -1,507 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/autofill_options_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/guid.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_split.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/autofill/personal_data_manager_factory.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/chromium_strings.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/autofill/core/browser/autofill_address_util.h"
-#include "components/autofill/core/browser/autofill_data_util.h"
-#include "components/autofill/core/browser/autofill_profile.h"
-#include "components/autofill/core/browser/country_combobox_model.h"
-#include "components/autofill/core/browser/credit_card.h"
-#include "components/autofill/core/browser/payments/payments_service_url.h"
-#include "components/autofill/core/browser/personal_data_manager.h"
-#include "components/autofill/core/browser/phone_number_i18n.h"
-#include "components/autofill/core/common/autofill_constants.h"
-#include "components/autofill/core/common/autofill_switches.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/web_ui.h"
-#include "third_party/libaddressinput/messages.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/webui/web_ui_util.h"
-
-using autofill::AutofillType;
-using autofill::AutofillProfile;
-using autofill::CreditCard;
-using autofill::PersonalDataManager;
-
-namespace {
-
-static const char kComponents[] = "components";
-static const char kLanguageCode[] = "languageCode";
-
-std::unique_ptr<base::DictionaryValue> CreditCardToDictionary(
- const CreditCard& card) {
- std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
- value->SetString("guid", card.guid());
- std::pair<base::string16, base::string16> label_pieces = card.LabelPieces();
- value->SetString("label", label_pieces.first);
- value->SetString("sublabel", label_pieces.second);
- value->SetBoolean("isLocal", card.record_type() == CreditCard::LOCAL_CARD);
- value->SetBoolean("isCached",
- card.record_type() == CreditCard::FULL_SERVER_CARD);
- return value;
-}
-
-} // namespace
-
-namespace options {
-
-AutofillOptionsHandler::AutofillOptionsHandler() : personal_data_(nullptr) {}
-
-AutofillOptionsHandler::~AutofillOptionsHandler() {
- if (personal_data_)
- personal_data_->RemoveObserver(this);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// OptionsPageUIHandler implementation:
-void AutofillOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "autofillAddresses", IDS_AUTOFILL_ADDRESSES_GROUP_NAME },
- { "autofillCreditCards", IDS_AUTOFILL_CREDITCARDS_GROUP_NAME },
- { "autofillAddAddress", IDS_AUTOFILL_ADD_ADDRESS_BUTTON },
- { "autofillAddCreditCard", IDS_AUTOFILL_ADD_CREDITCARD_BUTTON },
- { "autofillEditProfileButton", IDS_AUTOFILL_EDIT_PROFILE_BUTTON },
- { "autofillFromGoogleAccount", IDS_AUTOFILL_FROM_GOOGLE_ACCOUNT },
- { "autofillDescribeLocalCopy", IDS_AUTOFILL_DESCRIBE_LOCAL_COPY },
- { "autofillClearLocalCopyButton", IDS_AUTOFILL_CLEAR_LOCAL_COPY_BUTTON },
- { "helpButton", IDS_AUTOFILL_HELP_LABEL },
- { "addAddressTitle", IDS_AUTOFILL_ADD_ADDRESS_CAPTION },
- { "editAddressTitle", IDS_AUTOFILL_EDIT_ADDRESS_CAPTION },
- { "addCreditCardTitle", IDS_AUTOFILL_ADD_CREDITCARD_CAPTION },
- { "editCreditCardTitle", IDS_AUTOFILL_EDIT_CREDITCARD_CAPTION },
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "autofillOptionsPage",
- IDS_AUTOFILL_OPTIONS_TITLE);
-
- localized_strings->SetString("helpUrl", autofill::kHelpURL);
-
- personal_data_ = autofill::PersonalDataManagerFactory::GetForProfile(
- Profile::FromWebUI(web_ui()));
-
- SetAddressOverlayStrings(localized_strings);
- SetCreditCardOverlayStrings(localized_strings);
-
- localized_strings->SetString(
- "paymentsManageAddressesUrl",
- autofill::payments::GetManageAddressesUrl(0).spec());
- localized_strings->SetString(
- "paymentsManageInstrumentsUrl",
- autofill::payments::GetManageInstrumentsUrl(0).spec());
-}
-
-void AutofillOptionsHandler::InitializeHandler() {
- // personal_data_ is NULL in guest mode on Chrome OS.
- if (personal_data_)
- personal_data_->AddObserver(this);
-}
-
-void AutofillOptionsHandler::InitializePage() {
- if (personal_data_)
- LoadAutofillData();
-}
-
-void AutofillOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "removeData",
- base::Bind(&AutofillOptionsHandler::RemoveData,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "loadAddressEditor",
- base::Bind(&AutofillOptionsHandler::LoadAddressEditor,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "loadAddressEditorComponents",
- base::Bind(&AutofillOptionsHandler::LoadAddressEditorComponents,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "loadCreditCardEditor",
- base::Bind(&AutofillOptionsHandler::LoadCreditCardEditor,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setAddress",
- base::Bind(&AutofillOptionsHandler::SetAddress, base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setCreditCard",
- base::Bind(&AutofillOptionsHandler::SetCreditCard,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "clearLocalCardCopy",
- base::Bind(&AutofillOptionsHandler::RemaskServerCard,
- base::Unretained(this)));
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// PersonalDataManagerObserver implementation:
-void AutofillOptionsHandler::OnPersonalDataChanged() {
- LoadAutofillData();
-}
-
-void AutofillOptionsHandler::SetAddressOverlayStrings(
- base::DictionaryValue* localized_strings) {
- localized_strings->SetString("autofillEditAddressTitle",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_ADDRESS_CAPTION));
- localized_strings->SetString("autofillCountryLabel",
- l10n_util::GetStringUTF16(IDS_LIBADDRESSINPUT_COUNTRY_OR_REGION_LABEL));
- localized_strings->SetString("autofillPhoneLabel",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_FIELD_LABEL_PHONE));
- localized_strings->SetString("autofillEmailLabel",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_FIELD_LABEL_EMAIL));
- SetCountryData(*personal_data_, localized_strings,
- g_browser_process->GetApplicationLocale());
-}
-
-void AutofillOptionsHandler::SetCreditCardOverlayStrings(
- base::DictionaryValue* localized_strings) {
- localized_strings->SetString("autofillEditCreditCardTitle",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_CREDITCARD_CAPTION));
- localized_strings->SetString("nameOnCardLabel",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_FIELD_LABEL_NAME_ON_CARD));
- localized_strings->SetString("creditCardNumberLabel",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_FIELD_LABEL_CREDIT_CARD_NUMBER));
- localized_strings->SetString("creditCardExpirationDateLabel",
- l10n_util::GetStringUTF16(IDS_AUTOFILL_FIELD_LABEL_EXPIRATION_DATE));
-}
-
-void AutofillOptionsHandler::LoadAutofillData() {
- if (!IsPersonalDataLoaded())
- return;
-
- const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles();
- std::vector<base::string16> labels;
- AutofillProfile::CreateDifferentiatingLabels(
- profiles,
- g_browser_process->GetApplicationLocale(),
- &labels);
- DCHECK_EQ(labels.size(), profiles.size());
-
- base::ListValue addresses;
- for (size_t i = 0; i < profiles.size(); ++i) {
- // Skip showing auxiliary profiles (e.g. Mac Contacts) for now.
- if (profiles[i]->record_type() == AutofillProfile::AUXILIARY_PROFILE)
- continue;
-
- base::string16 separator =
- l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_SUMMARY_SEPARATOR);
- std::vector<base::string16> label_parts = base::SplitStringUsingSubstr(
- labels[i], separator, base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-
- std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
- value->SetString("guid", profiles[i]->guid());
- value->SetString("label", label_parts[0]);
- value->SetString("sublabel", labels[i].substr(label_parts[0].size()));
- value->SetBoolean("isLocal", profiles[i]->record_type() ==
- AutofillProfile::LOCAL_PROFILE);
- addresses.Append(std::move(value));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("AutofillOptions.setAddressList",
- addresses);
-
- base::ListValue credit_cards;
- const std::vector<CreditCard*>& cards = personal_data_->GetCreditCards();
- for (const CreditCard* card : cards) {
- credit_cards.Append(CreditCardToDictionary(*card));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("AutofillOptions.setCreditCardList",
- credit_cards);
-}
-
-void AutofillOptionsHandler::RemoveData(const base::ListValue* args) {
- DCHECK(IsPersonalDataLoaded());
-
- std::string guid;
- if (!args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
-
- personal_data_->RemoveByGUID(guid);
-}
-
-void AutofillOptionsHandler::LoadAddressEditor(const base::ListValue* args) {
- DCHECK(IsPersonalDataLoaded());
-
- std::string guid;
- if (!args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
-
- const AutofillProfile* prior_profile = personal_data_->GetProfileByGUID(guid);
- if (!prior_profile) {
- // There is a race where a user can click once on the close button and
- // quickly click again on the list item before the item is removed (since
- // the list is not updated until the model tells the list an item has been
- // removed). This will activate the editor for a profile that has been
- // removed. Do nothing in that case.
- return;
- }
-
- base::DictionaryValue address;
- AutofillProfileToDictionary(*prior_profile, &address);
-
- web_ui()->CallJavascriptFunctionUnsafe("AutofillOptions.editAddress",
- address);
-}
-
-void AutofillOptionsHandler::LoadAddressEditorComponents(
- const base::ListValue* args) {
- std::string country_code;
- if (!args->GetString(0, &country_code)) {
- NOTREACHED();
- return;
- }
-
- base::DictionaryValue input;
- std::unique_ptr<base::ListValue> components(new base::ListValue);
- std::string language_code;
- autofill::GetAddressComponents(country_code,
- g_browser_process->GetApplicationLocale(),
- components.get(), &language_code);
- input.Set(kComponents, std::move(components));
- input.SetString(kLanguageCode, language_code);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "AutofillEditAddressOverlay.loadAddressComponents", input);
-}
-
-void AutofillOptionsHandler::LoadCreditCardEditor(const base::ListValue* args) {
- DCHECK(IsPersonalDataLoaded());
-
- std::string guid;
- if (!args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
-
- CreditCard* credit_card = personal_data_->GetCreditCardByGUID(guid);
- if (!credit_card) {
- // There is a race where a user can click once on the close button and
- // quickly click again on the list item before the item is removed (since
- // the list is not updated until the model tells the list an item has been
- // removed). This will activate the editor for a profile that has been
- // removed. Do nothing in that case.
- return;
- }
-
- base::DictionaryValue credit_card_data;
- credit_card_data.SetString("guid", credit_card->guid());
- credit_card_data.SetString(
- "nameOnCard", credit_card->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL));
- credit_card_data.SetString(
- "creditCardNumber",
- credit_card->GetRawInfo(autofill::CREDIT_CARD_NUMBER));
- credit_card_data.SetString(
- "expirationMonth",
- credit_card->GetRawInfo(autofill::CREDIT_CARD_EXP_MONTH));
- credit_card_data.SetString(
- "expirationYear",
- credit_card->GetRawInfo(autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR));
-
- web_ui()->CallJavascriptFunctionUnsafe("AutofillOptions.editCreditCard",
- credit_card_data);
-}
-
-void AutofillOptionsHandler::SetAddress(const base::ListValue* args) {
- if (!IsPersonalDataLoaded())
- return;
-
- int arg_counter = 0;
- std::string guid;
- if (!args->GetString(arg_counter++, &guid)) {
- NOTREACHED();
- return;
- }
-
- AutofillProfile profile(guid, autofill::kSettingsOrigin);
-
- base::string16 full_name;
- if (args->GetString(arg_counter++, &full_name)) {
- // Although First/Middle/Last are not displayed on the form, we transfer
- // this information when they match the full name in the old version of the
- // profile, if one exists. This is because it may not be possible later to
- // correctly tokenize the concatenated full name; e.g., when the last name
- // contains a space, the first word would be treated as a middle name.
- const AutofillProfile* prior_profile =
- base::IsValidGUID(profile.guid())
- ? personal_data_->GetProfileByGUID(guid)
- : nullptr;
-
- if (prior_profile && autofill::data_util::ProfileMatchesFullName(
- full_name, *prior_profile)) {
- profile.SetRawInfo(autofill::NAME_FULL, full_name);
-
- profile.SetRawInfo(autofill::NAME_FIRST,
- prior_profile->GetRawInfo(autofill::NAME_FIRST));
- profile.SetRawInfo(autofill::NAME_MIDDLE,
- prior_profile->GetRawInfo(autofill::NAME_MIDDLE));
- profile.SetRawInfo(autofill::NAME_LAST,
- prior_profile->GetRawInfo(autofill::NAME_LAST));
- } else {
- // In contrast to SetRawInfo, SetInfo will naively attempt to populate the
- // First/Middle/Last fields by tokenization.
- profile.SetInfo(AutofillType(autofill::NAME_FULL), full_name,
- g_browser_process->GetApplicationLocale());
- }
- }
-
- base::string16 value;
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::COMPANY_NAME, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_STREET_ADDRESS, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_DEPENDENT_LOCALITY, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_CITY, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_STATE, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_ZIP, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_SORTING_CODE, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::ADDRESS_HOME_COUNTRY, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.SetRawInfo(autofill::EMAIL_ADDRESS, value);
-
- if (args->GetString(arg_counter++, &value))
- profile.set_language_code(base::UTF16ToUTF8(value));
-
- if (!base::IsValidGUID(profile.guid())) {
- profile.set_guid(base::GenerateGUID());
- personal_data_->AddProfile(profile);
- } else {
- personal_data_->UpdateProfile(profile);
- }
-}
-
-void AutofillOptionsHandler::SetCreditCard(const base::ListValue* args) {
- if (!IsPersonalDataLoaded())
- return;
-
- std::string guid;
- if (!args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
-
- CreditCard credit_card(guid, autofill::kSettingsOrigin);
-
- base::string16 value;
- if (args->GetString(1, &value))
- credit_card.SetRawInfo(autofill::CREDIT_CARD_NAME_FULL, value);
-
- if (args->GetString(2, &value))
- credit_card.SetRawInfo(autofill::CREDIT_CARD_NUMBER, value);
-
- if (args->GetString(3, &value))
- credit_card.SetRawInfo(autofill::CREDIT_CARD_EXP_MONTH, value);
-
- if (args->GetString(4, &value))
- credit_card.SetRawInfo(autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR, value);
-
- if (!base::IsValidGUID(credit_card.guid())) {
- credit_card.set_guid(base::GenerateGUID());
- personal_data_->AddCreditCard(credit_card);
- } else {
- personal_data_->UpdateCreditCard(credit_card);
- }
-}
-
-void AutofillOptionsHandler::RemaskServerCard(const base::ListValue* args) {
- std::string guid;
- if (!args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
-
- personal_data_->ResetFullServerCard(guid);
-}
-
-bool AutofillOptionsHandler::IsPersonalDataLoaded() const {
- return personal_data_ && personal_data_->IsDataLoaded();
-}
-
-// static
-void AutofillOptionsHandler::AutofillProfileToDictionary(
- const autofill::AutofillProfile& profile,
- base::DictionaryValue* address) {
- address->SetString("guid", profile.guid());
- address->SetString(
- autofill::kFullNameField,
- profile.GetInfo(AutofillType(autofill::NAME_FULL),
- g_browser_process->GetApplicationLocale()));
- address->SetString(autofill::kCompanyNameField,
- profile.GetRawInfo(autofill::COMPANY_NAME));
- address->SetString(autofill::kAddressLineField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_STREET_ADDRESS));
- address->SetString(autofill::kCityField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_CITY));
- address->SetString(autofill::kStateField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_STATE));
- address->SetString(
- autofill::kDependentLocalityField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_DEPENDENT_LOCALITY));
- address->SetString(autofill::kSortingCodeField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_SORTING_CODE));
- address->SetString(autofill::kPostalCodeField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_ZIP));
- address->SetString(autofill::kCountryField,
- profile.GetRawInfo(autofill::ADDRESS_HOME_COUNTRY));
- address->SetString("phone",
- profile.GetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER));
- address->SetString("email", profile.GetRawInfo(autofill::EMAIL_ADDRESS));
- address->SetString(kLanguageCode, profile.language_code());
-
- std::unique_ptr<base::ListValue> components(new base::ListValue);
- autofill::GetAddressComponents(
- base::UTF16ToUTF8(profile.GetRawInfo(autofill::ADDRESS_HOME_COUNTRY)),
- profile.language_code(), components.get(), nullptr);
- address->Set(kComponents, std::move(components));
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/autofill_options_handler.h b/chromium/chrome/browser/ui/webui/options/autofill_options_handler.h
deleted file mode 100644
index ef00b3ec45b..00000000000
--- a/chromium/chrome/browser/ui/webui/options/autofill_options_handler.h
+++ /dev/null
@@ -1,114 +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_OPTIONS_AUTOFILL_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_AUTOFILL_OPTIONS_HANDLER_H_
-
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/scoped_observer.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/autofill/core/browser/personal_data_manager_observer.h"
-
-namespace autofill {
-class AutofillProfile;
-class PersonalDataManager;
-} // namespace autofill
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace options {
-
-class AutofillOptionsHandler : public OptionsPageUIHandler,
- public autofill::PersonalDataManagerObserver {
- public:
- AutofillOptionsHandler();
- ~AutofillOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // PersonalDataManagerObserver implementation.
- void OnPersonalDataChanged() override;
-
- private:
- FRIEND_TEST_ALL_PREFIXES(AutofillOptionsHandlerTest, AddressToDictionary);
-
- // Loads the strings for the address and credit card overlays.
- void SetAddressOverlayStrings(base::DictionaryValue* localized_strings);
- void SetCreditCardOverlayStrings(base::DictionaryValue* localized_strings);
-
- // Loads Autofill addresses and credit cards using the PersonalDataManager.
- void LoadAutofillData();
-
- // Removes data from the PersonalDataManager.
- // |args| - A string, the GUID of the address or credit card to remove.
- void RemoveData(const base::ListValue* args);
-
- // Requests profile data for a specific address. Calls into WebUI with the
- // loaded profile data to open the address editor.
- // |args| - A string, the GUID of the address to load.
- void LoadAddressEditor(const base::ListValue* args);
-
- // Requests input form layout information for a specific country code. Calls
- // into WebUI with the layout information.
- // |args| - A string, the country code to load.
- void LoadAddressEditorComponents(const base::ListValue* args);
-
- // Requests profile data for a specific credit card. Calls into WebUI with the
- // loaded profile data to open the credit card editor.
- // |args| - A string, the GUID of the credit card to load.
- void LoadCreditCardEditor(const base::ListValue* args);
-
- // Adds or updates an address, depending on the GUID of the profile. If the
- // GUID is empty, a new address is added to the WebDatabase; otherwise, the
- // address with the matching GUID is updated. Called from WebUI.
- // |args| - an array containing the GUID of the address followed by the
- // address data.
- void SetAddress(const base::ListValue* args);
-
- // Adds or updates a credit card, depending on the GUID of the profile. If the
- // GUID is empty, a new credit card is added to the WebDatabase; otherwise,
- // the credit card with the matching GUID is updated. Called from WebUI.
- // |args| - an array containing the GUID of the credit card followed by the
- // credit card data.
- void SetCreditCard(const base::ListValue* args);
-
- // Validates a list of phone numbers. The resulting validated list of
- // numbers is then sent back to the WebUI.
- // |args| - an array containing the index of the modified or added number, the
- // array of numbers, and the country code string set on the profile.
- void ValidatePhoneNumbers(const base::ListValue* args);
-
- // Resets the masked state on the unmasked Wallet card described by the GUID
- // in args[0].
- void RemaskServerCard(const base::ListValue* args);
-
- // Returns true if |personal_data_| is non-null and loaded.
- bool IsPersonalDataLoaded() const;
-
- // Fills in |address| with the data format that the options js expects.
- static void AutofillProfileToDictionary(
- const autofill::AutofillProfile& profile,
- base::DictionaryValue* address);
-
- // The personal data manager, used to load Autofill profiles and credit cards.
- // Unowned pointer, may not be NULL.
- autofill::PersonalDataManager* personal_data_;
-
- DISALLOW_COPY_AND_ASSIGN(AutofillOptionsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_AUTOFILL_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.cc b/chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.cc
deleted file mode 100644
index f6bf319a8e8..00000000000
--- a/chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.cc
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/automatic_settings_reset_handler.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#include "base/time/time.h"
-#include "chrome/browser/prefs/chrome_pref_service_factory.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/web_ui.h"
-
-namespace {
-
-void OnDismissedAutomaticSettingsResetBanner(Profile* profile,
- const base::ListValue* value) {
- chrome_prefs::ClearResetTime(profile);
-}
-
-} // namespace
-
-namespace options {
-
-AutomaticSettingsResetHandler::AutomaticSettingsResetHandler() {}
-AutomaticSettingsResetHandler::~AutomaticSettingsResetHandler() {}
-
-void AutomaticSettingsResetHandler::InitializePage() {
- static const int kBannerShowTimeInDays = 5;
-
- const base::Time then =
- chrome_prefs::GetResetTime(Profile::FromWebUI(web_ui()));
- if (!then.is_null()) {
- const base::Time now = base::Time::Now();
- if ((now - then).InDays() < kBannerShowTimeInDays)
- web_ui()->CallJavascriptFunctionUnsafe(
- "AutomaticSettingsResetBanner.show");
- }
-}
-
-void AutomaticSettingsResetHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static const OptionsStringResource resources[] = {
- { "automaticSettingsResetBannerResetButtonText",
- IDS_AUTOMATIC_SETTINGS_RESET_BANNER_RESET_BUTTON_TEXT },
- { "automaticSettingsResetBannerText",
- IDS_AUTOMATIC_SETTINGS_RESET_BANNER_TEXT },
- { "automaticSettingsResetLearnMoreUrl",
- IDS_LEARN_MORE },
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- localized_strings->SetString(
- "automaticSettingsResetLearnMoreUrl",
- chrome::kAutomaticSettingsResetLearnMoreURL);
-}
-
-void AutomaticSettingsResetHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "onDismissedAutomaticSettingsResetBanner",
- base::Bind(&OnDismissedAutomaticSettingsResetBanner,
- Profile::FromWebUI(web_ui())));
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.h b/chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.h
deleted file mode 100644
index 1b4baed4b69..00000000000
--- a/chromium/chrome/browser/ui/webui/options/automatic_settings_reset_handler.h
+++ /dev/null
@@ -1,34 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_AUTOMATIC_SETTINGS_RESET_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_AUTOMATIC_SETTINGS_RESET_HANDLER_H_
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace options {
-
-// Handler for the banner that displays a settings reset event at the top of the
-// settings page.
-class AutomaticSettingsResetHandler : public OptionsPageUIHandler {
- public:
- AutomaticSettingsResetHandler();
- ~AutomaticSettingsResetHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(AutomaticSettingsResetHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_AUTOMATIC_SETTINGS_RESET_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/browser_options_handler.cc b/chromium/chrome/browser/ui/webui/options/browser_options_handler.cc
deleted file mode 100644
index d775e136f69..00000000000
--- a/chromium/chrome/browser/ui/webui/options/browser_options_handler.cc
+++ /dev/null
@@ -1,2347 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/browser_options_handler.h"
-
-#include <stddef.h>
-
-#include <set>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/environment.h"
-#include "base/i18n/number_formatting.h"
-#include "base/macros.h"
-#include "base/memory/singleton.h"
-#include "base/metrics/field_trial.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/metrics/user_metrics.h"
-#include "base/stl_util.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/value_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/custom_home_pages_table_model.h"
-#include "chrome/browser/download/download_prefs.h"
-#include "chrome/browser/extensions/settings_api_helpers.h"
-#include "chrome/browser/gpu/gpu_mode_manager.h"
-#include "chrome/browser/lifetime/application_lifetime.h"
-#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
-#include "chrome/browser/metrics/metrics_reporting_state.h"
-#include "chrome/browser/net/prediction_options.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
-#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_attributes_entry.h"
-#include "chrome/browser/profiles/profile_avatar_icon_util.h"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/profiles/profile_metrics.h"
-#include "chrome/browser/profiles/profile_shortcut_manager.h"
-#include "chrome/browser/profiles/profile_window.h"
-#include "chrome/browser/profiles/profiles_state.h"
-#include "chrome/browser/search/hotword_audio_history_handler.h"
-#include "chrome/browser/search/hotword_service.h"
-#include "chrome/browser/search/hotword_service_factory.h"
-#include "chrome/browser/search/search.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-#include "chrome/browser/signin/easy_unlock_service.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
-#include "chrome/browser/signin/signin_ui_util.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/sync/sync_ui_util.h"
-#include "chrome/browser/themes/theme_service.h"
-#include "chrome/browser/themes/theme_service_factory.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/chrome_select_file_policy.h"
-#include "chrome/browser/ui/passwords/manage_passwords_view_utils_desktop.h"
-#include "chrome/browser/ui/webui/favicon_source.h"
-#include "chrome/browser/ui/webui/profile_helper.h"
-#include "chrome/common/chrome_constants.h"
-#include "chrome/common/chrome_features.h"
-#include "chrome/common/chrome_paths.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/common/extensions/extension_constants.h"
-#include "chrome/common/features.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 "chrome/grit/locale_settings.h"
-#include "components/browser_sync/profile_sync_service.h"
-#include "components/metrics/metrics_pref_names.h"
-#include "components/policy/core/common/policy_map.h"
-#include "components/policy/core/common/policy_namespace.h"
-#include "components/policy/core/common/policy_service.h"
-#include "components/policy/policy_constants.h"
-#include "components/prefs/pref_service.h"
-#include "components/prefs/scoped_user_pref_update.h"
-#include "components/proximity_auth/switches.h"
-#include "components/proxy_config/proxy_config_pref_names.h"
-#include "components/safe_browsing/common/safe_browsing_prefs.h"
-#include "components/search_engines/template_url.h"
-#include "components/search_engines/template_url_service.h"
-#include "components/signin/core/browser/signin_manager.h"
-#include "components/signin/core/common/profile_management_switches.h"
-#include "components/signin/core/common/signin_pref_names.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/user_manager/user_type.h"
-#include "components/zoom/page_zoom.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/browser_url_handler.h"
-#include "content/public/browser/download_manager.h"
-#include "content/public/browser/navigation_controller.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/notification_source.h"
-#include "content/public/browser/notification_types.h"
-#include "content/public/browser/url_data_source.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/page_zoom.h"
-#include "extensions/browser/extension_registry.h"
-#include "google_apis/gaia/gaia_auth_util.h"
-#include "google_apis/gaia/google_service_auth_error.h"
-#include "printing/features/features.h"
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/webui/web_ui_util.h"
-
-#if !defined(OS_CHROMEOS)
-#include "chrome/browser/ui/startup/default_browser_prompt.h"
-#include "chrome/browser/ui/webui/settings_utils.h"
-#endif
-
-#if defined(OS_CHROMEOS)
-#include "ash/accessibility_types.h" // nogncheck
-#include "ash/shell.h" // nogncheck
-#include "ash/system/devicetype_utils.h" // nogncheck
-#include "chrome/browser/browser_process_platform_part.h"
-#include "chrome/browser/chromeos/accessibility/accessibility_util.h"
-#include "chrome/browser/chromeos/arc/arc_util.h"
-#include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h"
-#include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
-#include "chrome/browser/chromeos/net/wake_on_wifi_manager.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/chromeos/reset/metrics.h"
-#include "chrome/browser/chromeos/system/timezone_util.h"
-#include "chrome/browser/policy/profile_policy_connector.h"
-#include "chrome/browser/policy/profile_policy_connector_factory.h"
-#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
-#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chromeos/chromeos_switches.h"
-#include "chromeos/dbus/dbus_thread_manager.h"
-#include "chromeos/dbus/power_manager_client.h"
-#include "components/arc/arc_util.h"
-#include "components/user_manager/user.h"
-#include "components/user_manager/user_manager.h"
-#include "ui/gfx/image/image_skia.h"
-#endif // defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
-#include "chrome/browser/printing/cloud_print/privet_notifications.h"
-#endif
-
-using base::UserMetricsAction;
-using content::BrowserContext;
-using content::BrowserThread;
-using content::DownloadManager;
-using content::OpenURLParams;
-using content::Referrer;
-using extensions::Extension;
-using extensions::ExtensionRegistry;
-
-namespace {
-
-void AppendExtensionData(const std::string& key,
- const Extension* extension,
- base::DictionaryValue* dict) {
- std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
- details->SetString("id", extension ? extension->id() : std::string());
- details->SetString("name", extension ? extension->name() : std::string());
- dict->Set(key, std::move(details));
-}
-
-#if !defined(OS_CHROMEOS)
-bool IsDisabledByPolicy(const BooleanPrefMember& pref) {
- return pref.IsManaged() && !pref.GetValue();
-}
-#endif // !defined(OS_CHROMEOS)
-
-std::string GetSyncErrorAction(sync_ui_util::ActionType action_type) {
- switch (action_type) {
- case sync_ui_util::REAUTHENTICATE:
- return "reauthenticate";
- case sync_ui_util::SIGNOUT_AND_SIGNIN:
- return "signOutAndSignIn";
- case sync_ui_util::UPGRADE_CLIENT:
- return "upgradeClient";
- case sync_ui_util::ENTER_PASSPHRASE:
- return "enterPassphrase";
- default:
- return "noAction";
- }
-}
-
-#if defined(OS_CHROMEOS)
-bool g_enable_polymer_preload = true;
-#endif // defined(OS_CHROMEOS)
-} // namespace
-
-namespace options {
-
-BrowserOptionsHandler::BrowserOptionsHandler()
- : page_initialized_(false),
- template_url_service_(NULL),
- cloud_print_mdns_ui_enabled_(false),
-#if defined(OS_CHROMEOS)
- enable_factory_reset_(false),
-#endif // defined(OS_CHROMEOS)
- signin_observer_(this),
- weak_ptr_factory_(this) {
-#if !defined(OS_CHROMEOS)
- // The worker pointer is reference counted. While it is running, the
- // message loops of the FILE and UI thread will hold references to it
- // and it will be automatically freed once all its tasks have finished.
- default_browser_worker_ = new shell_integration::DefaultBrowserWorker(
- base::Bind(&BrowserOptionsHandler::OnDefaultBrowserWorkerFinished,
- weak_ptr_factory_.GetWeakPtr()));
-#endif // !defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- cloud_print_mdns_ui_enabled_ = true;
-#endif
-}
-
-BrowserOptionsHandler::~BrowserOptionsHandler() {
- browser_sync::ProfileSyncService* sync_service(
- ProfileSyncServiceFactory::GetInstance()->GetForProfile(
- Profile::FromWebUI(web_ui())));
- if (sync_service)
- sync_service->RemoveObserver(this);
-
- if (template_url_service_)
- template_url_service_->RemoveObserver(this);
- // There may be pending file dialogs, we need to tell them that we've gone
- // away so they don't try and call back to us.
- if (select_folder_dialog_.get())
- select_folder_dialog_->ListenerDestroyed();
-
- g_browser_process->policy_service()->RemoveObserver(
- policy::POLICY_DOMAIN_CHROME, this);
-}
-
-void BrowserOptionsHandler::GetLocalizedValues(base::DictionaryValue* values) {
- DCHECK(values);
-
-#if defined(OS_CHROMEOS)
- const int device_type_resource_id = ash::GetChromeOSDeviceTypeResourceId();
- const int enable_logging_resource_id =
- IDS_OPTIONS_ENABLE_LOGGING_DIAGNOSTIC_AND_USAGE_DATA;
-#else
- const int device_type_resource_id = IDS_EASY_UNLOCK_GENERIC_DEVICE_TYPE;
- const int enable_logging_resource_id = IDS_OPTIONS_ENABLE_LOGGING;
-#endif // defined(OS_CHROMEOS)
-
- static OptionsStringResource resources[] = {
- // Please keep these in alphabetical order.
- {"accessibilityFeaturesLink", IDS_OPTIONS_ACCESSIBILITY_FEATURES_LINK},
- {"accessibilityTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_ACCESSIBILITY},
- {"advancedSectionTitleCertificates",
- IDS_OPTIONS_ADVANCED_SECTION_TITLE_CERTIFICATES},
- {"advancedSectionTitleCloudPrint", IDS_GOOGLE_CLOUD_PRINT},
- {"advancedSectionTitleContent", IDS_OPTIONS_ADVANCED_SECTION_TITLE_CONTENT},
- {"advancedSectionTitleLanguages",
- IDS_OPTIONS_ADVANCED_SECTION_TITLE_LANGUAGES},
- {"advancedSectionTitleNetwork", IDS_OPTIONS_ADVANCED_SECTION_TITLE_NETWORK},
- {"advancedSectionTitlePrivacy", IDS_OPTIONS_ADVANCED_SECTION_TITLE_PRIVACY},
- {"advancedSectionTitleSystem", IDS_OPTIONS_ADVANCED_SECTION_TITLE_SYSTEM},
- {"autoOpenFileTypesInfo", IDS_OPTIONS_OPEN_FILE_TYPES_AUTOMATICALLY},
- {"autoOpenFileTypesResetToDefault",
- IDS_OPTIONS_AUTOOPENFILETYPES_RESETTODEFAULT},
- {"autofillEnabled", IDS_OPTIONS_AUTOFILL_ENABLE},
- {"autologinEnabled", IDS_OPTIONS_PASSWORDS_AUTOLOGIN},
- {"certificatesManageButton", IDS_OPTIONS_CERTIFICATES_MANAGE_BUTTON},
- {"changeHomePage", IDS_OPTIONS_CHANGE_HOME_PAGE},
- {"childLabel", IDS_PROFILES_LIST_CHILD_LABEL},
- {"currentUserOnly", IDS_OPTIONS_CURRENT_USER_ONLY},
- {"customizeSync", IDS_OPTIONS_CUSTOMIZE_SYNC_BUTTON_LABEL},
- {"defaultBrowserUnknown", IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN,
- IDS_PRODUCT_NAME},
- {"defaultBrowserUseAsDefault", IDS_OPTIONS_DEFAULTBROWSER_USEASDEFAULT},
- {"defaultFontSizeLabel", IDS_OPTIONS_DEFAULT_FONT_SIZE_LABEL},
- {"defaultSearchManageEngines", IDS_OPTIONS_DEFAULTSEARCH_MANAGE_ENGINES},
- {"defaultZoomFactorLabel", IDS_OPTIONS_DEFAULT_ZOOM_LEVEL_LABEL},
- {"disableWebServices", IDS_OPTIONS_DISABLE_WEB_SERVICES},
- {"doNotTrack", IDS_OPTIONS_ENABLE_DO_NOT_TRACK},
- {"doNotTrackConfirmDisable",
- IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_DISABLE},
- {"doNotTrackConfirmEnable", IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_ENABLE},
- {"doNotTrackConfirmMessage", IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_TEXT},
- {"downloadLocationAskForSaveLocation",
- IDS_OPTIONS_DOWNLOADLOCATION_ASKFORSAVELOCATION},
- {"downloadLocationBrowseTitle", IDS_OPTIONS_DOWNLOADLOCATION_BROWSE_TITLE},
- {"downloadLocationChangeButton",
- IDS_OPTIONS_DOWNLOADLOCATION_CHANGE_BUTTON},
- {"downloadLocationGroupName", IDS_OPTIONS_DOWNLOADLOCATION_GROUP_NAME},
- {"easyUnlockDescription", IDS_OPTIONS_EASY_UNLOCK_DESCRIPTION,
- device_type_resource_id},
- {"easyUnlockSectionTitle", IDS_OPTIONS_EASY_UNLOCK_SECTION_TITLE},
- {"easyUnlockSetupButton", IDS_OPTIONS_EASY_UNLOCK_SETUP_BUTTON},
- {"easyUnlockSetupIntro", IDS_OPTIONS_EASY_UNLOCK_SETUP_INTRO,
- device_type_resource_id},
- {"enableLogging", enable_logging_resource_id},
- {"extensionControlled", IDS_OPTIONS_TAB_EXTENSION_CONTROLLED},
- {"extensionDisable", IDS_OPTIONS_TAB_EXTENSION_CONTROLLED_DISABLE},
- {"fontSettingsCustomizeFontsButton",
- IDS_OPTIONS_FONTSETTINGS_CUSTOMIZE_FONTS_BUTTON},
- {"fontSizeLabelCustom", IDS_OPTIONS_FONT_SIZE_LABEL_CUSTOM},
- {"fontSizeLabelLarge", IDS_OPTIONS_FONT_SIZE_LABEL_LARGE},
- {"fontSizeLabelMedium", IDS_OPTIONS_FONT_SIZE_LABEL_MEDIUM},
- {"fontSizeLabelSmall", IDS_OPTIONS_FONT_SIZE_LABEL_SMALL},
- {"fontSizeLabelVeryLarge", IDS_OPTIONS_FONT_SIZE_LABEL_VERY_LARGE},
- {"fontSizeLabelVerySmall", IDS_OPTIONS_FONT_SIZE_LABEL_VERY_SMALL},
- {"googleNowLauncherEnable", IDS_OPTIONS_ENABLE_GOOGLE_NOW},
- {"hideAdvancedSettings", IDS_SETTINGS_HIDE_ADVANCED_SETTINGS},
- {"homePageNtp", IDS_OPTIONS_HOMEPAGE_NTP},
- {"homePageShowHomeButton", IDS_OPTIONS_TOOLBAR_SHOW_HOME_BUTTON},
- {"homePageUseNewTab", IDS_OPTIONS_HOMEPAGE_USE_NEWTAB},
- {"homePageUseURL", IDS_OPTIONS_HOMEPAGE_USE_URL},
- {"hotwordAlwaysOnAudioHistoryDescription",
- IDS_HOTWORD_ALWAYS_ON_AUDIO_HISTORY_DESCRIPTION},
- {"hotwordAlwaysOnDesc", IDS_HOTWORD_SEARCH_ALWAYS_ON_DESCRIPTION},
- {"hotwordAudioHistoryManage", IDS_HOTWORD_AUDIO_HISTORY_MANAGE_LINK},
- {"hotwordAudioLoggingEnable", IDS_HOTWORD_AUDIO_LOGGING_ENABLE},
- {"hotwordConfirmDisable", IDS_HOTWORD_CONFIRM_BUBBLE_DISABLE},
- {"hotwordConfirmEnable", IDS_HOTWORD_CONFIRM_BUBBLE_ENABLE},
- {"hotwordConfirmMessage", IDS_HOTWORD_SEARCH_PREF_DESCRIPTION},
- {"hotwordNoDSPDesc", IDS_HOTWORD_SEARCH_NO_DSP_DESCRIPTION},
- {"hotwordRetrainLink", IDS_HOTWORD_RETRAIN_LINK},
- {"hotwordSearchEnable", IDS_HOTWORD_SEARCH_PREF_CHKBOX},
- {"importData", IDS_OPTIONS_IMPORT_DATA_BUTTON},
- {"improveBrowsingExperience", IDS_OPTIONS_IMPROVE_BROWSING_EXPERIENCE},
- {"languageAndSpellCheckSettingsButton",
- IDS_OPTIONS_SETTINGS_LANGUAGE_AND_INPUT_SETTINGS},
-#if defined(OS_CHROMEOS)
- {"languageSectionLabel", IDS_OPTIONS_ADVANCED_LANGUAGE_LABEL,
- IDS_SHORT_PRODUCT_OS_NAME},
-#else
- {"languageSectionLabel", IDS_OPTIONS_ADVANCED_LANGUAGE_LABEL,
- IDS_SHORT_PRODUCT_NAME},
-#endif
- {"linkDoctorPref", IDS_OPTIONS_LINKDOCTOR_PREF},
- {"manageAutofillSettings", IDS_OPTIONS_MANAGE_AUTOFILL_SETTINGS_LINK},
- {"manageLanguages", IDS_OPTIONS_TRANSLATE_MANAGE_LANGUAGES},
- {"managePasswords", IDS_OPTIONS_PASSWORDS_MANAGE_PASSWORDS_LINK},
- {"metricsReportingResetRestart", IDS_OPTIONS_ENABLE_LOGGING_RESTART},
- {"networkPredictionEnabledDescription",
- IDS_NETWORK_PREDICTION_ENABLED_DESCRIPTION},
- {"passwordManagerEnabled", GetPasswordManagerSettingsStringId(
- ProfileSyncServiceFactory::GetForProfile(
- Profile::FromWebUI(web_ui())))},
- {"passwordsAndAutofillGroupName",
- IDS_OPTIONS_PASSWORDS_AND_FORMS_GROUP_NAME},
- {"privacyClearDataButton", IDS_OPTIONS_PRIVACY_CLEAR_DATA_BUTTON},
- {"privacyContentSettingsButton",
- IDS_OPTIONS_PRIVACY_CONTENT_SETTINGS_BUTTON},
- {"profileAddPersonEnable", IDS_PROFILE_ADD_PERSON_ENABLE},
- {"profileBrowserGuestEnable", IDS_PROFILE_BROWSER_GUEST_ENABLE},
- {"profilesCreate", IDS_PROFILES_CREATE_BUTTON_LABEL},
- {"profilesDelete", IDS_PROFILES_DELETE_BUTTON_LABEL},
- {"profilesDeleteSingle", IDS_PROFILES_DELETE_SINGLE_BUTTON_LABEL},
- {"profilesListItemCurrent", IDS_PROFILES_LIST_ITEM_CURRENT},
- {"profilesManage", IDS_PROFILES_MANAGE_BUTTON_LABEL},
- {"profilesSingleUser", IDS_PROFILES_SINGLE_USER_MESSAGE, IDS_PRODUCT_NAME},
- {"proxiesLabelExtension", IDS_OPTIONS_EXTENSION_PROXIES_LABEL},
- {"proxiesLabelSystem", IDS_OPTIONS_SYSTEM_PROXIES_LABEL, IDS_PRODUCT_NAME},
- {"resetProfileSettings", IDS_RESET_PROFILE_SETTINGS_BUTTON},
- {"resetProfileSettingsDescription", IDS_RESET_PROFILE_SETTINGS_DESCRIPTION},
- {"resetProfileSettingsSectionTitle",
- IDS_RESET_PROFILE_SETTINGS_SECTION_TITLE},
- {"safeBrowsingEnableProtection", IDS_OPTIONS_SAFEBROWSING_ENABLEPROTECTION},
- {"sectionTitleAppearance", IDS_APPEARANCE_GROUP_NAME},
- {"sectionTitleDefaultBrowser", IDS_OPTIONS_DEFAULTBROWSER_GROUP_NAME},
- {"sectionTitleProxy", IDS_OPTIONS_PROXY_GROUP_NAME},
- {"sectionTitleSearch", IDS_OPTIONS_DEFAULTSEARCH_GROUP_NAME},
- {"sectionTitleStartup", IDS_OPTIONS_STARTUP_GROUP_NAME},
- {"sectionTitleSync", IDS_SYNC_OPTIONS_GROUP_NAME},
- {"sectionTitleUsers", IDS_PROFILES_OPTIONS_GROUP_NAME},
- {"settingsTitle", IDS_SETTINGS_TITLE},
- {"showAdvancedSettings", IDS_SETTINGS_SHOW_ADVANCED_SETTINGS},
- {"spellingConfirmDisable", IDS_CONTENT_CONTEXT_SPELLING_BUBBLE_DISABLE},
- {"spellingConfirmEnable", IDS_CONTENT_CONTEXT_SPELLING_BUBBLE_ENABLE},
- {"spellingConfirmMessage", IDS_CONTENT_CONTEXT_SPELLING_BUBBLE_TEXT},
- {"spellingPref", IDS_OPTIONS_SPELLING_PREF},
- {"startupRestoreLastSession", IDS_OPTIONS_STARTUP_RESTORE_LAST_SESSION},
- {"startupSetPages", IDS_OPTIONS_STARTUP_SET_PAGES},
- {"startupShowNewTab", IDS_OPTIONS_STARTUP_SHOW_NEWTAB},
- {"startupShowPages", IDS_OPTIONS_STARTUP_SHOW_PAGES},
- {"suggestPref", IDS_OPTIONS_SUGGEST_PREF},
- {"supervisedUserLabel", IDS_PROFILES_LIST_LEGACY_SUPERVISED_USER_LABEL},
- {"syncButtonTextInProgress", IDS_SYNC_NTP_SETUP_IN_PROGRESS},
- {"syncButtonTextSignIn", IDS_SYNC_START_SYNC_BUTTON_LABEL,
- IDS_SHORT_PRODUCT_NAME},
- {"syncButtonTextStop", IDS_SYNC_STOP_SYNCING_BUTTON_LABEL},
- {"syncOverview", IDS_SYNC_OVERVIEW},
- {"tabsToLinksPref", IDS_OPTIONS_TABS_TO_LINKS_PREF},
- {"themesGallery", IDS_THEMES_GALLERY_BUTTON},
- {"themesGalleryURL", IDS_THEMES_GALLERY_URL},
- {"themesReset", IDS_THEMES_RESET_BUTTON},
- {"toolbarShowBookmarksBar", IDS_OPTIONS_TOOLBAR_SHOW_BOOKMARKS_BAR},
- {"toolbarShowHomeButton", IDS_OPTIONS_TOOLBAR_SHOW_HOME_BUTTON},
- {"translateEnableTranslate", IDS_OPTIONS_TRANSLATE_ENABLE_TRANSLATE},
-#if defined(OS_CHROMEOS)
- {"accessibilityAlwaysShowMenu",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SHOULD_ALWAYS_SHOW_MENU},
- {"accessibilityAutoclick",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DESCRIPTION},
- {"accessibilityAutoclickDropdown",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DROPDOWN_DESCRIPTION},
- {"accessibilityCaretHighlight",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_CARET_HIGHLIGHT_DESCRIPTION},
- {"accessibilityCursorHighlight",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_CURSOR_HIGHLIGHT_DESCRIPTION},
- {"accessibilityExplanation",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_EXPLANATION},
- {"accessibilityFocusHighlight",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_FOCUS_HIGHLIGHT_DESCRIPTION},
- {"accessibilityHighContrast",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_HIGH_CONTRAST_DESCRIPTION},
- {"accessibilityLargeCursor",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_LARGE_CURSOR_DESCRIPTION},
- {"accessibilityScreenMagnifier",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_DESCRIPTION},
- {"accessibilityScreenMagnifierCenterFocus",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_CENTER_FOCUS},
- {"accessibilityScreenMagnifierFull",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_FULL},
- {"accessibilityScreenMagnifierOff",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_OFF},
- {"accessibilityScreenMagnifierPartial",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_PARTIAL},
- {"accessibilitySelectToSpeak",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_DESCRIPTION},
- {"accessibilitySettings", IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SETTINGS},
- {"accessibilitySpokenFeedback",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SPOKEN_FEEDBACK_DESCRIPTION},
- {"accessibilityStickyKeys",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_STICKY_KEYS_DESCRIPTION},
- {"accessibilitySwitchAccess",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_DESCRIPTION},
- {"accessibilityTalkBackSettings",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_TALKBACK_SETTINGS},
- {"accessibilityTapDragging",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_TOUCHPAD_TAP_DRAGGING_DESCRIPTION},
- {"accessibilityVirtualKeyboard",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_VIRTUAL_KEYBOARD_DESCRIPTION},
- {"accessibilityMonoAudio",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_MONO_AUDIO_DESCRIPTION},
- {"advancedSectionTitleCupsPrint",
- IDS_OPTIONS_ADVANCED_SECTION_TITLE_CUPS_PRINT},
- {"androidAppsTitle", IDS_OPTIONS_ARC_TITLE},
- {"androidAppsEnabled", IDS_OPTIONS_ARC_ENABLE},
- {"androidAppsSettingsLabel", IDS_OPTIONS_ARC_MANAGE_APPS},
- {"arcOptOutConfirmOverlayTabTitle", IDS_ARC_OPT_OUT_TAB_TITLE},
- {"arcOptOutDialogHeader", IDS_ARC_OPT_OUT_DIALOG_HEADER},
- {"arcOptOutDialogDescription", IDS_ARC_OPT_OUT_DIALOG_DESCRIPTION},
- {"arcOptOutDialogButtonConfirmDisable",
- IDS_ARC_OPT_OUT_DIALOG_BUTTON_CONFIRM_DISABLE},
- {"arcOptOutDialogButtonCancel", IDS_ARC_OPT_OUT_DIALOG_BUTTON_CANCEL},
- {"autoclickDelayExtremelyShort",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_EXTREMELY_SHORT},
- {"autoclickDelayLong",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_LONG},
- {"autoclickDelayShort",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_SHORT},
- {"autoclickDelayVeryLong",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_VERY_LONG},
- {"autoclickDelayVeryShort",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_VERY_SHORT},
- {"changePicture", IDS_OPTIONS_CHANGE_PICTURE},
- {"changePictureCaption", IDS_OPTIONS_CHANGE_PICTURE_CAPTION},
- {"cupsPrintOptionLabel", IDS_OPTIONS_ADVANCED_SECTION_CUPS_PRINT_LABEL},
- {"cupsPrintersManageButton",
- IDS_OPTIONS_ADVANCED_SECTION_CUPS_PRINT_MANAGE_BUTTON},
- {"datetimeTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_DATETIME},
- {"deviceGroupDescription", IDS_OPTIONS_DEVICE_GROUP_DESCRIPTION},
- {"deviceGroupPointer", IDS_OPTIONS_DEVICE_GROUP_POINTER_SECTION},
- {"disableGData", IDS_OPTIONS_DISABLE_GDATA},
- {"displayOptions", IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_BUTTON_LABEL},
- {"enableContentProtectionAttestation",
- IDS_OPTIONS_ENABLE_CONTENT_PROTECTION_ATTESTATION},
- {"manageScreenlock", IDS_OPTIONS_MANAGE_SCREENLOCKER},
- {"factoryResetDataRestart", IDS_RELAUNCH_BUTTON},
- {"factoryResetDescription", IDS_OPTIONS_FACTORY_RESET_DESCRIPTION,
- IDS_SHORT_PRODUCT_NAME},
- {"factoryResetHeading", IDS_OPTIONS_FACTORY_RESET_HEADING},
- {"factoryResetHelpUrl", IDS_FACTORY_RESET_HELP_URL},
- {"factoryResetRestart", IDS_OPTIONS_FACTORY_RESET_BUTTON},
- {"factoryResetTitle", IDS_OPTIONS_FACTORY_RESET},
- {"factoryResetWarning", IDS_OPTIONS_FACTORY_RESET_WARNING},
- {"internetOptionsButtonTitle", IDS_OPTIONS_INTERNET_OPTIONS_BUTTON_TITLE},
- {"keyboardSettingsButtonTitle",
- IDS_OPTIONS_DEVICE_GROUP_KEYBOARD_SETTINGS_BUTTON_TITLE},
- {"manageAccountsButtonTitle", IDS_OPTIONS_ACCOUNTS_BUTTON_TITLE},
- {"mouseSpeed", IDS_OPTIONS_SETTINGS_MOUSE_SPEED_DESCRIPTION},
- {"noPointingDevices", IDS_OPTIONS_NO_POINTING_DEVICES},
- {"confirm", IDS_CONFIRM},
- {"configureFingerprintTitle", IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_TITLE},
- {"configureFingerprintInstructionLocateScannerStep",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER},
- {"configureFingerprintInstructionMoveFingerStep",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_MOVE_FINGER},
- {"configureFingerprintInstructionReadyStep",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_READY},
- {"configureFingerprintLiftFinger",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_LIFT_FINGER},
- {"configureFingerprintPartialData",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_PARTIAL_DATA},
- {"configureFingerprintInsufficientData",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSUFFICIENT_DATA},
- {"configureFingerprintSensorDirty",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_SENSOR_DIRTY},
- {"configureFingerprintTooSlow",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_FINGER_TOO_SLOW},
- {"configureFingerprintTooFast",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_FINGER_TOO_FAST},
- {"configureFingerprintImmobile",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_FINGER_IMMOBILE},
- {"configureFingerprintCancelButton",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_CANCEL_BUTTON},
- {"configureFingerprintDoneButton",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_DONE_BUTTON},
- {"configureFingerprintAddAnotherButton",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_ADD_ANOTHER_BUTTON},
- {"configurePinChoosePinTitle",
- IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_CHOOSE_PIN_TITLE},
- {"configurePinConfirmPinTitle",
- IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_CONFIRM_PIN_TITLE},
- {"configurePinContinueButton",
- IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_CONTINUE_BUTTON},
- {"configurePinMismatched", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_MISMATCHED},
- {"configurePinTooShort", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_TOO_SHORT},
- {"configurePinTooLong", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_TOO_LONG},
- {"configurePinWeakPin", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_WEAK_PIN},
- {"lockScreenAddFingerprint",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_ADD_FINGERPRINT_BUTTON},
- {"lockScreenChangePinButton",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_CHANGE_PIN_BUTTON},
- {"lockScreenEditFingerprints",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_EDIT_FINGERPRINTS},
- {"lockScreenEditFingerprintsDescription",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_EDIT_FINGERPRINTS_DESCRIPTION},
- {"lockScreenSetupFingerprintButton",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_SETUP_BUTTON},
- {"lockScreenNumberFingerprints",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_NUM_FINGERPRINTS},
- {"lockScreenFingerprintEnable",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_ENABLE_FINGERPRINT_CHECKBOX_LABEL},
- {"lockScreenFingerprintNewName",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_NEW_FINGERPRINT_DEFAULT_NAME},
- {"lockScreenFingerprintTitle",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_SUBPAGE_TITLE},
- {"lockScreenFingerprintWarning",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_LESS_SECURE},
- {"lockScreenNone", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_NONE},
- {"lockScreenOptions", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_OPTIONS},
- {"lockScreenPasswordOnly", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_PASSWORD_ONLY},
- {"lockScreenPinOrPassword",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_PIN_OR_PASSWORD},
- {"lockScreenRegisteredFingerprints",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_REGISTERED_FINGERPRINTS_LABEL},
- {"lockScreenSetupPinButton",
- IDS_SETTINGS_PEOPLE_LOCK_SCREEN_SETUP_PIN_BUTTON},
- {"lockScreenTitle", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_TITLE},
- {"passwordPromptEnterPassword",
- IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_ENTER_PASSWORD},
- {"passwordPromptInvalidPassword",
- IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_INVALID_PASSWORD},
- {"passwordPromptPasswordLabel",
- IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_PASSWORD_LABEL},
- {"passwordPromptTitle", IDS_SETTINGS_PEOPLE_PASSWORD_PROMPT_TITLE},
- {"pinKeyboardPlaceholderPin", IDS_PIN_KEYBOARD_HINT_TEXT_PIN},
- {"pinKeyboardPlaceholderPinPassword",
- IDS_PIN_KEYBOARD_HINT_TEXT_PIN_PASSWORD},
- {"pinKeyboardDeleteAccessibleName",
- IDS_LOGIN_POD_PASSWORD_FIELD_ACCESSIBLE_NAME},
- {"powerSettingsButton", IDS_OPTIONS_DEVICE_GROUP_POWER_SETTINGS_BUTTON},
- {"resolveTimezoneByGeoLocation",
- IDS_OPTIONS_RESOLVE_TIMEZONE_BY_GEOLOCATION_DESCRIPTION},
- {"sectionTitleDevice", IDS_OPTIONS_DEVICE_GROUP_NAME},
- {"sectionTitleInternet", IDS_OPTIONS_INTERNET_OPTIONS_GROUP_LABEL},
- {"storageManagerButtonTitle",
- IDS_OPTIONS_DEVICE_GROUP_STORAGE_MANAGER_BUTTON_TITLE},
- {"syncButtonTextStart", IDS_SYNC_SETUP_BUTTON_LABEL},
- {"thirdPartyImeConfirmDisable", IDS_CANCEL},
- {"thirdPartyImeConfirmEnable", IDS_OK},
- {"thirdPartyImeConfirmMessage",
- IDS_OPTIONS_SETTINGS_LANGUAGES_THIRD_PARTY_WARNING_MESSAGE},
- {"timezone", IDS_OPTIONS_SETTINGS_TIMEZONE_DESCRIPTION},
- {"touchpadSpeed", IDS_OPTIONS_SETTINGS_TOUCHPAD_SPEED_DESCRIPTION},
- {"use24HourClock", IDS_OPTIONS_SETTINGS_USE_24HOUR_CLOCK_DESCRIPTION},
- {"wakeOnWifiLabel", IDS_OPTIONS_SETTINGS_WAKE_ON_WIFI_DESCRIPTION},
-#else
- {"gpuModeCheckbox", IDS_OPTIONS_SYSTEM_ENABLE_HARDWARE_ACCELERATION_MODE},
- {"gpuModeResetRestart",
- IDS_OPTIONS_SYSTEM_ENABLE_HARDWARE_ACCELERATION_MODE_RESTART},
- {"proxiesConfigureButton", IDS_OPTIONS_PROXIES_CONFIGURE_BUTTON},
- {"syncButtonTextStart", IDS_SYNC_SETUP_BUTTON_LABEL},
-#endif // defined(OS_CHROMEOS)
-
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
- {"showWindowDecorations", IDS_SHOW_WINDOW_DECORATIONS},
- {"themesNativeButton", IDS_THEMES_GTK_BUTTON},
- {"themesSetClassic", IDS_THEMES_SET_CLASSIC},
-#else
- {"themes", IDS_THEMES_GROUP_NAME},
-#endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
-
-#if defined(OS_CHROMEOS)
- {"setWallpaper", IDS_SET_WALLPAPER_BUTTON},
-#endif // defined(OS_CHROMEOS)
-
-#if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
- {"backgroundModeCheckbox", IDS_OPTIONS_SYSTEM_ENABLE_BACKGROUND_MODE},
-#endif // defined(OS_MACOSX) && !defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- {"cloudPrintDevicesPageButton", IDS_LOCAL_DISCOVERY_DEVICES_PAGE_BUTTON},
- {"cloudPrintEnableNotificationsLabel",
- IDS_LOCAL_DISCOVERY_NOTIFICATIONS_ENABLE_CHECKBOX_LABEL},
-#endif
- };
-
- RegisterStrings(values, resources, arraysize(resources));
- RegisterTitle(values, "doNotTrackConfirmOverlay",
- IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_TITLE);
- RegisterTitle(values, "spellingConfirmOverlay",
- IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE);
-#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
- RegisterCloudPrintValues(values);
-#endif
-
- Profile* profile = Profile::FromWebUI(web_ui());
- values->SetString(
- "safeBrowsingEnableExtendedReporting",
- l10n_util::GetStringUTF16(safe_browsing::ChooseOptInTextResource(
- *profile->GetPrefs(),
- IDS_OPTIONS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING,
- IDS_OPTIONS_SAFEBROWSING_ENABLE_SCOUT_REPORTING)));
- values->SetString("syncLearnMoreURL", chrome::kSyncLearnMoreURL);
- base::string16 omnibox_url = base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL);
- values->SetString(
- "defaultSearchGroupLabel",
- l10n_util::GetStringFUTF16(IDS_SEARCH_PREF_EXPLANATION, omnibox_url));
- values->SetString("hotwordLearnMoreURL", chrome::kHotwordLearnMoreURL);
- RegisterTitle(values, "hotwordConfirmOverlay",
- IDS_HOTWORD_CONFIRM_BUBBLE_TITLE);
- values->SetString("hotwordManageAudioHistoryURL",
- chrome::kManageAudioHistoryURL);
- base::string16 supervised_user_dashboard =
- base::ASCIIToUTF16(chrome::kLegacySupervisedUserManagementURL);
- values->SetString("profilesSupervisedDashboardTip",
- l10n_util::GetStringFUTF16(
- IDS_PROFILES_LEGACY_SUPERVISED_USER_DASHBOARD_TIP,
- supervised_user_dashboard));
-
-#if defined(OS_CHROMEOS)
- std::string username = profile->GetProfileUserName();
- if (username.empty()) {
- const user_manager::User* user =
- chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
- if (user && (user->GetType() != user_manager::USER_TYPE_GUEST))
- username = user->GetAccountId().GetUserEmail();
- }
- if (!username.empty())
- username = gaia::SanitizeEmail(gaia::CanonicalizeEmail(username));
-
- values->SetString("username", username);
-#endif
- // Pass along sync status early so it will be available during page init.
- values->Set("syncData", GetSyncStateDictionary());
-
- values->SetString("privacyLearnMoreURL", chrome::kPrivacyLearnMoreURL);
-
- values->SetString("doNotTrackLearnMoreURL", chrome::kDoNotTrackLearnMoreURL);
-
- values->SetBoolean(
- "metricsReportingEnabledAtStart",
- ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
-
-#if defined(OS_CHROMEOS)
- // TODO(pastarmovj): replace this with a call to the CrosSettings list
- // handling functionality to come.
- values->Set("timezoneList", chromeos::system::GetTimezoneList());
-
- values->SetString("accessibilityLearnMoreURL",
- chrome::kChromeAccessibilityHelpURL);
-
- std::string settings_url = std::string("chrome-extension://") +
- extension_misc::kChromeVoxExtensionId +
- chrome::kChromeAccessibilitySettingsURL;
-
- values->SetString("accessibilitySettingsURL",
- settings_url);
-
- values->SetString("contentProtectionAttestationLearnMoreURL",
- chrome::kAttestationForContentProtectionLearnMoreURL);
-
- // Creates magnifierList.
- std::unique_ptr<base::ListValue> magnifier_list(new base::ListValue);
-
- std::unique_ptr<base::ListValue> option_full(new base::ListValue);
- option_full->AppendInteger(ash::MAGNIFIER_FULL);
- option_full->AppendString(l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_FULL));
- magnifier_list->Append(std::move(option_full));
-
- std::unique_ptr<base::ListValue> option_partial(new base::ListValue);
- option_partial->AppendInteger(ash::MAGNIFIER_PARTIAL);
- option_partial->AppendString(l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_PARTIAL));
- magnifier_list->Append(std::move(option_partial));
-
- values->Set("magnifierList", std::move(magnifier_list));
- values->SetBoolean("enablePolymerPreload", g_enable_polymer_preload);
-#endif // defined(OS_CHROMEOS)
-
-#if defined(OS_MACOSX)
- values->SetString("macPasswordsWarning",
- l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_MAC_WARNING));
- values->SetBoolean("multiple_profiles",
- g_browser_process->profile_manager()->GetNumberOfProfiles() > 1);
-#endif
-
- if (ShouldShowMultiProfilesUserList())
- values->Set("profilesInfo", GetProfilesInfoList());
-
- // Profile deletion is not allowed for any users in ChromeOS.
- bool allow_deletion = true;
-#if defined(OS_CHROMEOS)
- allow_deletion = allow_deletion && !ash::Shell::HasInstance();
-#endif
- values->SetBoolean("allowProfileDeletion", allow_deletion);
- values->SetBoolean("profileIsGuest", profile->IsOffTheRecord());
- values->SetBoolean("profileIsSupervised", profile->IsSupervised());
-
-#if !defined(OS_CHROMEOS)
- values->SetBoolean(
- "gpuEnabledAtStart",
- g_browser_process->gpu_mode_manager()->initial_gpu_mode_pref());
-#endif
-
-#if defined(OS_CHROMEOS)
- values->SetString("cupsPrintLearnMoreURL", chrome::kCrosPrintingLearnMoreURL);
-#endif // defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- values->SetBoolean("cloudPrintHideNotificationsCheckbox",
- !cloud_print::PrivetNotificationService::IsEnabled());
-#endif
-
- values->SetBoolean("cloudPrintShowMDnsOptions",
- cloud_print_mdns_ui_enabled_);
-
- values->SetString("cloudPrintLearnMoreURL", chrome::kCloudPrintLearnMoreURL);
-
- values->SetString("languagesLearnMoreURL",
- chrome::kLanguageSettingsLearnMoreUrl);
-
- values->SetBoolean(
- "easyUnlockAllowed", EasyUnlockService::Get(profile)->IsAllowed());
- values->SetString("easyUnlockLearnMoreURL", chrome::kEasyUnlockLearnMoreUrl);
-
-#if defined(OS_CHROMEOS)
- RegisterTitle(values, "thirdPartyImeConfirmOverlay",
- IDS_OPTIONS_SETTINGS_LANGUAGES_THIRD_PARTY_WARNING_TITLE);
- values->SetBoolean("usingNewProfilesUI", false);
-#else
- values->SetBoolean("usingNewProfilesUI", true);
-#endif
-
- values->SetBoolean("showSetDefault", ShouldShowSetDefaultBrowser());
-
- values->SetBoolean("allowAdvancedSettings", ShouldAllowAdvancedSettings());
-
-#if defined(OS_CHROMEOS)
- values->SetBoolean(
- "showWakeOnWifi",
- chromeos::WakeOnWifiManager::Get()->WakeOnWifiSupported() &&
- chromeos::switches::WakeOnWifiEnabled());
- values->SetBoolean("enableTimeZoneTrackingOption",
- !chromeos::system::HasSystemTimezonePolicy());
- values->SetBoolean("resolveTimezoneByGeolocationInitialValue",
- profile->GetPrefs()->GetBoolean(prefs::kResolveTimezoneByGeolocation));
- values->SetBoolean("enableLanguageOptionsImeMenu",
- base::FeatureList::IsEnabled(features::kOptInImeMenu));
- values->SetBoolean(
- "enableExperimentalAccessibilityFeatures",
- base::CommandLine::ForCurrentProcess()->HasSwitch(
- chromeos::switches::kEnableExperimentalAccessibilityFeatures));
-
- chromeos::CrosSettings* cros_settings = chromeos::CrosSettings::Get();
- bool allow_bluetooth = true;
- cros_settings->GetBoolean(chromeos::kAllowBluetooth, &allow_bluetooth);
- values->SetBoolean("allowBluetooth", allow_bluetooth);
-
- values->SetBoolean("showQuickUnlockSettings",
- chromeos::quick_unlock::IsPinEnabled(profile->GetPrefs()));
- values->SetBoolean("fingerprintUnlockEnabled",
- chromeos::quick_unlock::IsFingerprintEnabled());
- values->SetBoolean("quickUnlockEnabled",
- chromeos::quick_unlock::IsPinEnabled(profile->GetPrefs()));
- if (chromeos::quick_unlock::IsPinEnabled(profile->GetPrefs())) {
- values->SetString(
- "enableScreenlock",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_ENABLE_SCREENLOCKER_CHECKBOX_WITH_QUICK_UNLOCK));
- } else {
- values->SetString(
- "enableScreenlock",
- l10n_util::GetStringUTF16(IDS_OPTIONS_ENABLE_SCREENLOCKER_CHECKBOX));
- }
- // Format numbers to be used on the pin keyboard.
- for (int j = 0; j <= 9; ++j) {
- values->SetString("pinKeyboard" + base::IntToString(j),
- base::FormatNumber(int64_t{j}));
- }
-#endif
-}
-
-#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
-void BrowserOptionsHandler::RegisterCloudPrintValues(
- base::DictionaryValue* values) {
- values->SetString("cloudPrintOptionLabel",
- l10n_util::GetStringFUTF16(
- IDS_CLOUD_PRINT_CHROMEOS_OPTION_LABEL,
- l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
-}
-#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
-
-void BrowserOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "setDefaultSearchEngine",
- base::Bind(&BrowserOptionsHandler::SetDefaultSearchEngine,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "deleteProfile",
- base::Bind(&BrowserOptionsHandler::DeleteProfile,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "themesReset",
- base::Bind(&BrowserOptionsHandler::ThemesReset,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "requestProfilesInfo",
- base::Bind(&BrowserOptionsHandler::HandleRequestProfilesInfo,
- base::Unretained(this)));
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
- web_ui()->RegisterMessageCallback(
- "themesSetNative",
- base::Bind(&BrowserOptionsHandler::ThemesSetNative,
- base::Unretained(this)));
-#endif
- web_ui()->RegisterMessageCallback(
- "selectDownloadLocation",
- base::Bind(&BrowserOptionsHandler::HandleSelectDownloadLocation,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "autoOpenFileTypesAction",
- base::Bind(&BrowserOptionsHandler::HandleAutoOpenButton,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "defaultFontSizeAction",
- base::Bind(&BrowserOptionsHandler::HandleDefaultFontSize,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "defaultZoomFactorAction",
- base::Bind(&BrowserOptionsHandler::HandleDefaultZoomFactor,
- base::Unretained(this)));
-#if defined(OS_WIN) || defined(OS_MACOSX)
- web_ui()->RegisterMessageCallback(
- "showManageSSLCertificates",
- base::Bind(&BrowserOptionsHandler::ShowManageSSLCertificates,
- base::Unretained(this)));
-#endif
-#if defined(OS_CHROMEOS)
- web_ui()->RegisterMessageCallback(
- "openWallpaperManager",
- base::Bind(&BrowserOptionsHandler::HandleOpenWallpaperManager,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "virtualKeyboardChange",
- base::Bind(&BrowserOptionsHandler::VirtualKeyboardChangeCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "onPowerwashDialogShow",
- base::Bind(&BrowserOptionsHandler::OnPowerwashDialogShow,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "performFactoryResetRestart",
- base::Bind(&BrowserOptionsHandler::PerformFactoryResetRestart,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "showAndroidAppsSettings",
- base::Bind(&BrowserOptionsHandler::ShowAndroidAppsSettings,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "showPlayStoreApps",
- base::Bind(&BrowserOptionsHandler::ShowPlayStoreApps,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "showAccessibilityTalkBackSettings",
- base::Bind(&BrowserOptionsHandler::ShowAccessibilityTalkBackSettings,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "showCupsPrintDevicesPage",
- base::Bind(&BrowserOptionsHandler::ShowCupsPrintDevicesPage,
- base::Unretained(this)));
-#else
- web_ui()->RegisterMessageCallback(
- "becomeDefaultBrowser",
- base::Bind(&BrowserOptionsHandler::BecomeDefaultBrowser,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "restartBrowser",
- base::Bind(&BrowserOptionsHandler::HandleRestartBrowser,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "showNetworkProxySettings",
- base::Bind(&BrowserOptionsHandler::ShowNetworkProxySettings,
- base::Unretained(this)));
-#endif // defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- if (cloud_print_mdns_ui_enabled_) {
- web_ui()->RegisterMessageCallback(
- "showCloudPrintDevicesPage",
- base::Bind(&BrowserOptionsHandler::ShowCloudPrintDevicesPage,
- base::Unretained(this)));
- }
-#endif
- web_ui()->RegisterMessageCallback(
- "requestGoogleNowAvailable",
- base::Bind(&BrowserOptionsHandler::HandleRequestGoogleNowAvailable,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "requestHotwordAvailable",
- base::Bind(&BrowserOptionsHandler::HandleRequestHotwordAvailable,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "launchHotwordAudioVerificationApp",
- base::Bind(
- &BrowserOptionsHandler::HandleLaunchHotwordAudioVerificationApp,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "launchEasyUnlockSetup",
- base::Bind(&BrowserOptionsHandler::HandleLaunchEasyUnlockSetup,
- base::Unretained(this)));
-#if defined(OS_WIN)
- web_ui()->RegisterMessageCallback(
- "refreshExtensionControlIndicators",
- base::Bind(
- &BrowserOptionsHandler::HandleRefreshExtensionControlIndicators,
- base::Unretained(this)));
-#endif // defined(OS_WIN)
- web_ui()->RegisterMessageCallback("metricsReportingCheckboxChanged",
- base::Bind(&BrowserOptionsHandler::HandleMetricsReportingChange,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "safeBrowsingExtendedReportingAction",
- base::Bind(&BrowserOptionsHandler::HandleSafeBrowsingExtendedReporting,
- base::Unretained(this)));
-}
-
-void BrowserOptionsHandler::Uninitialize() {
- registrar_.RemoveAll();
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().RemoveObserver(this);
-#if defined(OS_WIN)
- ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))->RemoveObserver(this);
-#endif
-#if defined(OS_CHROMEOS)
- ArcAppListPrefs* arc_prefs = ArcAppListPrefs::Get(
- Profile::FromWebUI(web_ui()));
- if (arc_prefs)
- arc_prefs->RemoveObserver(this);
- user_manager::UserManager::Get()->RemoveObserver(this);
-#endif
-}
-
-void BrowserOptionsHandler::OnStateChanged(syncer::SyncService* sync) {
- UpdateSyncState();
-}
-
-void BrowserOptionsHandler::GoogleSigninSucceeded(const std::string& account_id,
- const std::string& username) {
- UpdateSyncState();
-}
-
-void BrowserOptionsHandler::GoogleSignedOut(const std::string& account_id,
- const std::string& username) {
- UpdateSyncState();
-}
-
-void BrowserOptionsHandler::PageLoadStarted() {
- page_initialized_ = false;
-}
-
-void BrowserOptionsHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
- PrefService* prefs = profile->GetPrefs();
- ChromeZoomLevelPrefs* zoom_level_prefs = profile->GetZoomLevelPrefs();
- // Only regular profiles are able to edit default zoom level, or delete per-
- // host zoom levels, via the settings menu. We only require a zoom_level_prefs
- // if the profile is able to change these preference types.
- DCHECK(zoom_level_prefs ||
- profile->GetProfileType() != Profile::REGULAR_PROFILE);
- if (zoom_level_prefs) {
- default_zoom_level_subscription_ =
- zoom_level_prefs->RegisterDefaultZoomLevelCallback(
- base::Bind(&BrowserOptionsHandler::SetupPageZoomSelector,
- base::Unretained(this)));
- }
-
- g_browser_process->policy_service()->AddObserver(
- policy::POLICY_DOMAIN_CHROME, this);
-
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().AddObserver(this);
-
- browser_sync::ProfileSyncService* sync_service(
- ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile));
- // TODO(blundell): Use a ScopedObserver to observe the PSS so that cleanup on
- // destruction is automatic.
- if (sync_service)
- sync_service->AddObserver(this);
-
- SigninManagerBase* signin_manager(
- SigninManagerFactory::GetInstance()->GetForProfile(profile));
- if (signin_manager)
- signin_observer_.Add(signin_manager);
-
- // Create our favicon data source.
- content::URLDataSource::Add(profile, new FaviconSource(profile));
-
-#if !defined(OS_CHROMEOS)
- default_browser_policy_.Init(
- prefs::kDefaultBrowserSettingEnabled,
- g_browser_process->local_state(),
- base::Bind(&BrowserOptionsHandler::UpdateDefaultBrowserState,
- base::Unretained(this)));
-#endif
-
-#if defined(OS_CHROMEOS)
- user_manager::UserManager::Get()->AddObserver(this);
-#endif
- registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
- content::Source<ThemeService>(
- ThemeServiceFactory::GetForProfile(profile)));
- registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
- content::Source<Profile>(profile));
- AddTemplateUrlServiceObserver();
-
-#if defined(OS_WIN)
- ExtensionRegistry::Get(profile)->AddObserver(this);
-#endif
-
- // No preferences below this point may be modified by guest profiles.
- if (profile->IsGuestSession())
- return;
-
- auto_open_files_.Init(
- prefs::kDownloadExtensionsToOpen, prefs,
- base::Bind(&BrowserOptionsHandler::SetupAutoOpenFileTypes,
- base::Unretained(this)));
- profile_pref_registrar_.Init(prefs);
- profile_pref_registrar_.Add(
- prefs::kNetworkPredictionOptions,
- base::Bind(&BrowserOptionsHandler::SetupNetworkPredictionControl,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kWebKitDefaultFontSize,
- base::Bind(&BrowserOptionsHandler::SetupFontSizeSelector,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kWebKitDefaultFixedFontSize,
- base::Bind(&BrowserOptionsHandler::SetupFontSizeSelector,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kSupervisedUsers,
- base::Bind(&BrowserOptionsHandler::SetupManagingSupervisedUsers,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kSigninAllowed,
- base::Bind(&BrowserOptionsHandler::OnSigninAllowedPrefChange,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kEasyUnlockPairing,
- base::Bind(&BrowserOptionsHandler::SetupEasyUnlock,
- base::Unretained(this)));
-
-#if defined(OS_WIN)
- profile_pref_registrar_.Add(
- prefs::kURLsToRestoreOnStartup,
- base::Bind(&BrowserOptionsHandler::SetupExtensionControlledIndicators,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kHomePage,
- base::Bind(&BrowserOptionsHandler::SetupExtensionControlledIndicators,
- base::Unretained(this)));
-#endif // defined(OS_WIN)
-
-#if defined(OS_CHROMEOS)
- if (!policy_registrar_) {
- policy_registrar_.reset(new policy::PolicyChangeRegistrar(
- policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile)
- ->policy_service(),
- policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())));
- policy_registrar_->Observe(
- policy::key::kUserAvatarImage,
- base::Bind(&BrowserOptionsHandler::OnUserImagePolicyChanged,
- base::Unretained(this)));
- policy_registrar_->Observe(
- policy::key::kWallpaperImage,
- base::Bind(&BrowserOptionsHandler::OnWallpaperPolicyChanged,
- base::Unretained(this)));
- }
- system_timezone_policy_observer_ =
- chromeos::CrosSettings::Get()->AddSettingsObserver(
- chromeos::kSystemTimezonePolicy,
- base::Bind(&BrowserOptionsHandler::OnSystemTimezonePolicyChanged,
- weak_ptr_factory_.GetWeakPtr()));
- local_state_pref_change_registrar_.Init(g_browser_process->local_state());
- local_state_pref_change_registrar_.Add(
- prefs::kSystemTimezoneAutomaticDetectionPolicy,
- base::Bind(&BrowserOptionsHandler::
- OnSystemTimezoneAutomaticDetectionPolicyChanged,
- base::Unretained(this)));
- ArcAppListPrefs* arc_prefs = ArcAppListPrefs::Get(profile);
- if (arc_prefs)
- arc_prefs->AddObserver(this);
-#else // !defined(OS_CHROMEOS)
- profile_pref_registrar_.Add(
- proxy_config::prefs::kProxy,
- base::Bind(&BrowserOptionsHandler::SetupProxySettingsSection,
- base::Unretained(this)));
-#endif // !defined(OS_CHROMEOS)
-
- profile_pref_registrar_.Add(
- prefs::kSafeBrowsingExtendedReportingEnabled,
- base::Bind(&BrowserOptionsHandler::SetupSafeBrowsingExtendedReporting,
- base::Unretained(this)));
- profile_pref_registrar_.Add(
- prefs::kSafeBrowsingScoutReportingEnabled,
- base::Bind(&BrowserOptionsHandler::SetupSafeBrowsingExtendedReporting,
- base::Unretained(this)));
-}
-
-void BrowserOptionsHandler::InitializePage() {
- page_initialized_ = true;
-
- OnTemplateURLServiceChanged();
-
- ObserveThemeChanged();
- UpdateSyncState();
-#if !defined(OS_CHROMEOS)
- UpdateDefaultBrowserState();
-#endif
-
- SetupMetricsReportingSettingVisibility();
- SetupMetricsReportingCheckbox();
- SetupNetworkPredictionControl();
- SetupFontSizeSelector();
- SetupPageZoomSelector();
- SetupAutoOpenFileTypes();
- SetupProxySettingsSection();
- SetupManagingSupervisedUsers();
- SetupEasyUnlock();
- SetupExtensionControlledIndicators();
- SetupSafeBrowsingExtendedReporting();
-
-#if defined(OS_CHROMEOS)
- SetupAccessibilityFeatures();
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- enable_factory_reset_ = !connector->IsEnterpriseManaged() &&
- !user_manager::UserManager::Get()->IsLoggedInAsGuest() &&
- !user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser();
- if (enable_factory_reset_) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.enableFactoryResetSection");
- }
-
- Profile* const profile = Profile::FromWebUI(web_ui());
- user_manager::User const* const user =
- chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
-
- OnAccountPictureManagedChanged(
- policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile)
- ->policy_service()
- ->GetPolicies(policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
- std::string()))
- .Get(policy::key::kUserAvatarImage));
-
- OnWallpaperManagedChanged(
- chromeos::WallpaperManager::Get()->IsPolicyControlled(
- user->GetAccountId()));
-
- if (arc::IsArcAllowedForProfile(profile) &&
- !arc::IsArcOptInVerificationDisabled()) {
- base::Value is_play_store_enabled(
- arc::IsArcPlayStoreEnabledForProfile(profile));
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.showAndroidAppsSection", is_play_store_enabled);
- // Get the initial state of Android Settings app readiness.
- std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
- ArcAppListPrefs::Get(profile)->GetApp(arc::kSettingsAppId);
- if (app_info && app_info->ready)
- UpdateAndroidSettingsAppState(app_info->ready);
- }
-
- OnSystemTimezoneAutomaticDetectionPolicyChanged();
-#endif
-}
-
-bool BrowserOptionsHandler::ShouldShowSetDefaultBrowser() {
-#if defined(OS_CHROMEOS)
- // We're always the default browser on ChromeOS.
- return false;
-#else
- return !Profile::FromWebUI(web_ui())->IsGuestSession();
-#endif
-}
-
-bool BrowserOptionsHandler::ShouldShowMultiProfilesUserList() {
-#if defined(OS_CHROMEOS)
- // On Chrome OS we use different UI for multi-profiles.
- return false;
-#else
- if (Profile::FromWebUI(web_ui())->IsGuestSession())
- return false;
- return profiles::IsMultipleProfilesEnabled();
-#endif
-}
-
-bool BrowserOptionsHandler::ShouldAllowAdvancedSettings() {
-#if defined(OS_CHROMEOS)
- // ChromeOS handles guest-mode restrictions in a different manner.
- return true;
-#else
- return !Profile::FromWebUI(web_ui())->IsGuestSession();
-#endif
-}
-
-#if !defined(OS_CHROMEOS)
-
-void BrowserOptionsHandler::UpdateDefaultBrowserState() {
- default_browser_worker_->StartCheckIsDefault();
-}
-
-void BrowserOptionsHandler::BecomeDefaultBrowser(const base::ListValue* args) {
- // If the default browser setting is managed then we should not be able to
- // call this function.
- if (IsDisabledByPolicy(default_browser_policy_))
- return;
-
- base::RecordAction(UserMetricsAction("Options_SetAsDefaultBrowser"));
- UMA_HISTOGRAM_COUNTS("Settings.StartSetAsDefault", true);
-
- // Callback takes care of updating UI.
- default_browser_worker_->StartSetAsDefault();
-
- // If the user attempted to make Chrome the default browser, notify
- // them when this changes.
- chrome::ResetDefaultBrowserPrompt(Profile::FromWebUI(web_ui()));
-}
-
-void BrowserOptionsHandler::OnDefaultBrowserWorkerFinished(
- shell_integration::DefaultWebClientState state) {
- int status_string_id;
-
- if (state == shell_integration::IS_DEFAULT) {
- status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;
- // Notify the user in the future if Chrome ceases to be the user's chosen
- // default browser.
- chrome::ResetDefaultBrowserPrompt(Profile::FromWebUI(web_ui()));
- } else if (state == shell_integration::NOT_DEFAULT) {
- if (shell_integration::CanSetAsDefaultBrowser()) {
- status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;
- } else {
- status_string_id = IDS_OPTIONS_DEFAULTBROWSER_SXS;
- }
- } else if (state == shell_integration::UNKNOWN_DEFAULT) {
- status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;
- } else {
- NOTREACHED();
- return;
- }
-
- SetDefaultBrowserUIString(status_string_id);
-}
-
-void BrowserOptionsHandler::SetDefaultBrowserUIString(int status_string_id) {
- base::Value status_string(l10n_util::GetStringFUTF16(
- status_string_id, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
-
- base::Value is_default(status_string_id ==
- IDS_OPTIONS_DEFAULTBROWSER_DEFAULT);
-
- base::Value can_be_default(
- !IsDisabledByPolicy(default_browser_policy_) &&
- (status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT ||
- status_string_id == IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.updateDefaultBrowserState", status_string, is_default,
- can_be_default);
-}
-#endif // !defined(OS_CHROMEOS)
-
-void BrowserOptionsHandler::OnTemplateURLServiceChanged() {
- if (!template_url_service_ || !template_url_service_->loaded())
- return;
-
- const TemplateURL* default_url =
- template_url_service_->GetDefaultSearchProvider();
-
- int default_index = -1;
- base::ListValue search_engines;
- TemplateURLService::TemplateURLVector model_urls(
- template_url_service_->GetTemplateURLs());
- for (size_t i = 0; i < model_urls.size(); ++i) {
- TemplateURL* t_url = model_urls[i];
- if (!template_url_service_->ShowInDefaultList(t_url))
- continue;
-
- std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
- entry->SetString("name", t_url->short_name());
- entry->SetInteger("index", i);
- search_engines.Append(std::move(entry));
- if (t_url == default_url)
- default_index = i;
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.updateSearchEngines", search_engines,
- base::Value(default_index),
- base::Value(template_url_service_->is_default_search_managed() ||
- template_url_service_->IsExtensionControlledDefaultSearch()));
-
- SetupExtensionControlledIndicators();
-
- HandleRequestHotwordAvailable(nullptr);
- HandleRequestGoogleNowAvailable(nullptr);
-}
-
-void BrowserOptionsHandler::SetDefaultSearchEngine(
- const base::ListValue* args) {
- int selected_index = -1;
- if (!ExtractIntegerValue(args, &selected_index)) {
- NOTREACHED();
- return;
- }
-
- TemplateURLService::TemplateURLVector model_urls(
- template_url_service_->GetTemplateURLs());
- if (selected_index >= 0 &&
- selected_index < static_cast<int>(model_urls.size()))
- template_url_service_->SetUserSelectedDefaultSearchProvider(
- model_urls[selected_index]);
-
- base::RecordAction(UserMetricsAction("Options_SearchEngineChanged"));
-}
-
-void BrowserOptionsHandler::AddTemplateUrlServiceObserver() {
- template_url_service_ =
- TemplateURLServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()));
- if (template_url_service_) {
- template_url_service_->Load();
- template_url_service_->AddObserver(this);
- }
-}
-
-void BrowserOptionsHandler::OnExtensionLoaded(
- content::BrowserContext* browser_context,
- const Extension* extension) {
- SetupExtensionControlledIndicators();
-}
-
-void BrowserOptionsHandler::OnExtensionUnloaded(
- content::BrowserContext* browser_context,
- const Extension* extension,
- extensions::UnloadedExtensionReason reason) {
- SetupExtensionControlledIndicators();
-}
-
-void BrowserOptionsHandler::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- // Notifications are used to update the UI dynamically when settings change in
- // the background. If the UI is currently being loaded, no dynamic updates are
- // possible (as the DOM and JS are not fully loaded) or necessary (as
- // InitializePage() will update the UI at the end of the load).
- if (!page_initialized_)
- return;
-
- switch (type) {
- case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
- ObserveThemeChanged();
- break;
- case chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED:
- // Update our sync/signin status display.
- UpdateSyncState();
- break;
- default:
- NOTREACHED();
- }
-}
-
-void BrowserOptionsHandler::OnProfileAdded(const base::FilePath& profile_path) {
- SendProfilesInfo();
-}
-
-void BrowserOptionsHandler::OnProfileWasRemoved(
- const base::FilePath& profile_path,
- const base::string16& profile_name) {
- SendProfilesInfo();
-}
-
-void BrowserOptionsHandler::OnProfileNameChanged(
- const base::FilePath& profile_path,
- const base::string16& old_profile_name) {
- SendProfilesInfo();
-}
-
-void BrowserOptionsHandler::OnProfileAvatarChanged(
- const base::FilePath& profile_path) {
- SendProfilesInfo();
-}
-
-std::unique_ptr<base::ListValue> BrowserOptionsHandler::GetProfilesInfoList() {
- std::vector<ProfileAttributesEntry*> entries =
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().GetAllProfilesAttributesSortedByName();
- std::unique_ptr<base::ListValue> profile_info_list(new base::ListValue);
- base::FilePath current_profile_path =
- web_ui()->GetWebContents()->GetBrowserContext()->GetPath();
-
- for (const ProfileAttributesEntry* entry : entries) {
- // The items in |profile_value| are also described in
- // chrome/browser/resources/options/browser_options.js in a @typedef for
- // Profile. Please update it whenever you add or remove any keys here.
- std::unique_ptr<base::DictionaryValue> profile_value(
- new base::DictionaryValue());
- profile_value->SetString("name", entry->GetName());
- base::FilePath profile_path = entry->GetPath();
- profile_value->Set("filePath", base::CreateFilePathValue(profile_path));
- profile_value->SetBoolean("isCurrentProfile",
- profile_path == current_profile_path);
- profile_value->SetBoolean("isSupervised", entry->IsSupervised());
- profile_value->SetBoolean("isChild", entry->IsChild());
-
- if (entry->IsUsingGAIAPicture() && entry->GetGAIAPicture()) {
- gfx::Image icon = profiles::GetAvatarIconForWebUI(entry->GetAvatarIcon(),
- true);
- profile_value->SetString("iconURL",
- webui::GetBitmapDataUrl(icon.AsBitmap()));
- } else {
- size_t icon_index = entry->GetAvatarIconIndex();
- profile_value->SetString("iconURL",
- profiles::GetDefaultAvatarIconUrl(icon_index));
- }
-
- profile_info_list->Append(std::move(profile_value));
- }
-
- return profile_info_list;
-}
-
-void BrowserOptionsHandler::SendProfilesInfo() {
- if (!ShouldShowMultiProfilesUserList())
- return;
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.setProfilesInfo",
- *GetProfilesInfoList());
-}
-
-void BrowserOptionsHandler::DeleteProfile(const base::ListValue* args) {
- DCHECK(args);
- const base::Value* file_path_value;
- if (!args->Get(0, &file_path_value)) {
- NOTREACHED();
- return;
- }
-
- base::FilePath file_path;
- if (!base::GetValueAsFilePath(*file_path_value, &file_path)) {
- NOTREACHED();
- return;
- }
-
- webui::DeleteProfileAtPath(file_path,
- web_ui(),
- ProfileMetrics::DELETE_PROFILE_SETTINGS);
-}
-
-void BrowserOptionsHandler::ObserveThemeChanged() {
- Profile* profile = Profile::FromWebUI(web_ui());
- ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile);
- bool is_system_theme = false;
-
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
- bool profile_is_supervised = profile->IsSupervised();
- is_system_theme = theme_service->UsingSystemTheme();
- base::Value native_theme_enabled(!is_system_theme && !profile_is_supervised);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setNativeThemeButtonEnabled", native_theme_enabled);
-#endif
-
- bool is_classic_theme = !is_system_theme &&
- theme_service->UsingDefaultTheme();
- base::Value enabled(!is_classic_theme);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setThemesResetButtonEnabled", enabled);
-}
-
-void BrowserOptionsHandler::ThemesReset(const base::ListValue* args) {
- Profile* profile = Profile::FromWebUI(web_ui());
- base::RecordAction(UserMetricsAction("Options_ThemesReset"));
- ThemeServiceFactory::GetForProfile(profile)->UseDefaultTheme();
-}
-
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
-void BrowserOptionsHandler::ThemesSetNative(const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("Options_GtkThemeSet"));
- Profile* profile = Profile::FromWebUI(web_ui());
- ThemeServiceFactory::GetForProfile(profile)->UseSystemTheme();
-}
-#endif
-
-#if defined(OS_CHROMEOS)
-void BrowserOptionsHandler::UpdateAccountPicture() {
- std::string email = user_manager::UserManager::Get()
- ->GetActiveUser()
- ->GetAccountId()
- .GetUserEmail();
- if (!email.empty()) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.updateAccountPicture");
- base::Value email_value(email);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.updateAccountPicture", email_value);
- web_ui()->CallJavascriptFunctionUnsafe(
- "AccountsOptions.getInstance().updateAccountPicture", email_value);
- }
-}
-
-void BrowserOptionsHandler::OnAccountPictureManagedChanged(bool managed) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setAccountPictureManaged", base::Value(managed));
-}
-
-void BrowserOptionsHandler::OnWallpaperManagedChanged(bool managed) {
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.setWallpaperManaged",
- base::Value(managed));
-}
-
-void BrowserOptionsHandler::OnSystemTimezonePolicyChanged() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setSystemTimezoneManaged",
- base::Value(chromeos::system::HasSystemTimezonePolicy()));
-}
-
-void BrowserOptionsHandler::OnSystemTimezoneAutomaticDetectionPolicyChanged() {
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(
- chromeos::switches::kDisableSystemTimezoneAutomaticDetectionPolicy)) {
- return;
- }
-
- PrefService* prefs = g_browser_process->local_state();
- const bool is_managed = prefs->IsManagedPreference(
- prefs::kSystemTimezoneAutomaticDetectionPolicy);
- const int value =
- prefs->GetInteger(prefs::kSystemTimezoneAutomaticDetectionPolicy);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setSystemTimezoneAutomaticDetectionManaged",
- base::Value(is_managed), base::Value(value));
-}
-#endif
-
-std::unique_ptr<base::DictionaryValue>
-BrowserOptionsHandler::GetSyncStateDictionary() {
- // The items which are to be written into |sync_status| are also described in
- // chrome/browser/resources/options/browser_options.js in @typedef
- // for SyncStatus. Please update it whenever you add or remove any keys here.
- std::unique_ptr<base::DictionaryValue> sync_status(new base::DictionaryValue);
- Profile* profile = Profile::FromWebUI(web_ui());
- if (profile->IsGuestSession()) {
- // Cannot display signin status when running in guest mode on chromeos
- // because there is no SigninManager.
- sync_status->SetBoolean("signinAllowed", false);
- return sync_status;
- }
-
- sync_status->SetBoolean("supervisedUser", profile->IsSupervised());
- sync_status->SetBoolean("childUser", profile->IsChild());
-
- bool signout_prohibited = false;
-#if !defined(OS_CHROMEOS)
- // Signout is not allowed if the user has policy (crbug.com/172204).
- signout_prohibited =
- SigninManagerFactory::GetForProfile(profile)->IsSignoutProhibited();
-#endif
-
- browser_sync::ProfileSyncService* service =
- ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
- SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile);
- DCHECK(signin);
- sync_status->SetBoolean("signoutAllowed", !signout_prohibited);
- sync_status->SetBoolean("signinAllowed", signin->IsSigninAllowed());
- sync_status->SetBoolean("syncSystemEnabled", (service != NULL));
- sync_status->SetBoolean("setupCompleted",
- service && service->IsFirstSetupComplete());
- sync_status->SetBoolean("setupInProgress",
- service && !service->IsManaged() && service->IsFirstSetupInProgress());
-
- base::string16 status_label;
- base::string16 link_label;
- sync_ui_util::ActionType action_type = sync_ui_util::NO_ACTION;
- bool status_has_error =
- sync_ui_util::GetStatusLabels(profile, service, *signin,
- sync_ui_util::WITH_HTML, &status_label,
- &link_label, &action_type) ==
- sync_ui_util::SYNC_ERROR;
- sync_status->SetString("statusText", status_label);
- sync_status->SetString("actionLinkText", link_label);
- sync_status->SetBoolean("hasError", status_has_error);
- sync_status->SetString("statusAction", GetSyncErrorAction(action_type));
- sync_status->SetBoolean("managed", service && service->IsManaged());
- sync_status->SetBoolean("signedIn", signin->IsAuthenticated());
- sync_status->SetString("accountInfo",
- l10n_util::GetStringFUTF16(
- IDS_SYNC_ACCOUNT_INFO,
- signin_ui_util::GetAuthenticatedUsername(signin)));
- sync_status->SetBoolean("hasUnrecoverableError",
- service && service->HasUnrecoverableError());
-
- return sync_status;
-}
-
-void BrowserOptionsHandler::HandleSelectDownloadLocation(
- const base::ListValue* args) {
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
- select_folder_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- ui::SelectFileDialog::FileTypeInfo info;
- info.allowed_paths = ui::SelectFileDialog::FileTypeInfo::NATIVE_OR_DRIVE_PATH;
- select_folder_dialog_->SelectFile(
- ui::SelectFileDialog::SELECT_FOLDER,
- l10n_util::GetStringUTF16(IDS_OPTIONS_DOWNLOADLOCATION_BROWSE_TITLE),
- pref_service->GetFilePath(prefs::kDownloadDefaultDirectory),
- &info,
- 0,
- base::FilePath::StringType(),
- web_ui()->GetWebContents()->GetTopLevelNativeWindow(),
- NULL);
-}
-
-void BrowserOptionsHandler::FileSelected(const base::FilePath& path, int index,
- void* params) {
- base::RecordAction(UserMetricsAction("Options_SetDownloadDirectory"));
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
- pref_service->SetFilePath(prefs::kDownloadDefaultDirectory, path);
- pref_service->SetFilePath(prefs::kSaveFileDefaultDirectory, path);
-}
-
-#if defined(OS_CHROMEOS)
-void BrowserOptionsHandler::TouchpadExists(bool exists) {
- base::Value val(exists);
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.showTouchpadControls",
- val);
-}
-
-void BrowserOptionsHandler::MouseExists(bool exists) {
- base::Value val(exists);
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.showMouseControls",
- val);
-}
-
-void BrowserOptionsHandler::OnUserImagePolicyChanged(
- const base::Value* previous_policy,
- const base::Value* current_policy) {
- const bool had_policy = previous_policy;
- const bool has_policy = current_policy;
- if (had_policy != has_policy)
- OnAccountPictureManagedChanged(has_policy);
-}
-
-void BrowserOptionsHandler::OnWallpaperPolicyChanged(
- const base::Value* previous_policy,
- const base::Value* current_policy) {
- const bool had_policy = previous_policy;
- const bool has_policy = current_policy;
- if (had_policy != has_policy)
- OnWallpaperManagedChanged(has_policy);
-}
-
-void BrowserOptionsHandler::OnPowerwashDialogShow(
- const base::ListValue* args) {
- UMA_HISTOGRAM_ENUMERATION(
- "Reset.ChromeOS.PowerwashDialogShown",
- chromeos::reset::DIALOG_FROM_OPTIONS,
- chromeos::reset::DIALOG_VIEW_TYPE_SIZE);
-}
-
-#endif // defined(OS_CHROMEOS)
-
-void BrowserOptionsHandler::UpdateSyncState() {
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.updateSyncState",
- *GetSyncStateDictionary());
-
- // A change in sign-in state also affects how hotwording and audio history are
- // displayed. Hide all hotwording and re-display properly.
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setAllHotwordSectionsVisible", base::Value(false));
- HandleRequestHotwordAvailable(nullptr);
-}
-
-void BrowserOptionsHandler::OnSigninAllowedPrefChange() {
- UpdateSyncState();
-}
-
-void BrowserOptionsHandler::HandleAutoOpenButton(const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("Options_ResetAutoOpenFiles"));
- DownloadManager* manager = BrowserContext::GetDownloadManager(
- web_ui()->GetWebContents()->GetBrowserContext());
- DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
-}
-
-void BrowserOptionsHandler::HandleDefaultFontSize(const base::ListValue* args) {
- int font_size;
- if (ExtractIntegerValue(args, &font_size)) {
- if (font_size > 0) {
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
- pref_service->SetInteger(prefs::kWebKitDefaultFontSize, font_size);
- SetupFontSizeSelector();
- }
- }
-}
-
-void BrowserOptionsHandler::HandleDefaultZoomFactor(
- const base::ListValue* args) {
- double zoom_factor;
- if (ExtractDoubleValue(args, &zoom_factor)) {
- ChromeZoomLevelPrefs* zoom_level_prefs =
- Profile::FromWebUI(web_ui())->GetZoomLevelPrefs();
- DCHECK(zoom_level_prefs);
- zoom_level_prefs->SetDefaultZoomLevelPref(
- content::ZoomFactorToZoomLevel(zoom_factor));
- }
-}
-
-void BrowserOptionsHandler::HandleRestartBrowser(const base::ListValue* args) {
- chrome::AttemptRestart();
-}
-
-void BrowserOptionsHandler::HandleRequestProfilesInfo(
- const base::ListValue* args) {
- SendProfilesInfo();
-}
-
-#if !defined(OS_CHROMEOS)
-void BrowserOptionsHandler::ShowNetworkProxySettings(
- const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("Options_ShowProxySettings"));
- settings_utils::ShowNetworkProxySettings(web_ui()->GetWebContents());
-}
-#endif
-
-#if defined(OS_WIN) || defined(OS_MACOSX)
-void BrowserOptionsHandler::ShowManageSSLCertificates(
- const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("Options_ManageSSLCertificates"));
- settings_utils::ShowManageSSLCertificates(web_ui()->GetWebContents());
-}
-#endif
-
-#if defined(OS_CHROMEOS)
-void BrowserOptionsHandler::ShowCupsPrintDevicesPage(
- const base::ListValue* args) {
- // Navigate in current tab to CUPS printers management page.
- OpenURLParams params(GURL(chrome::kChromeUIMdCupsSettingsURL), Referrer(),
- WindowOpenDisposition::NEW_FOREGROUND_TAB,
- ui::PAGE_TRANSITION_LINK, false);
- web_ui()->GetWebContents()->OpenURL(params);
-}
-#endif // defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
-void BrowserOptionsHandler::ShowCloudPrintDevicesPage(
- const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("Options_CloudPrintDevicesPage"));
- // Navigate in current tab to devices page.
- OpenURLParams params(GURL(chrome::kChromeUIDevicesURL), Referrer(),
- WindowOpenDisposition::CURRENT_TAB,
- ui::PAGE_TRANSITION_LINK, false);
- web_ui()->GetWebContents()->OpenURL(params);
-}
-#endif
-
-void BrowserOptionsHandler::SetHotwordAudioHistorySectionVisible(
- const base::string16& audio_history_state,
- bool success, bool logging_enabled) {
- bool visible = logging_enabled && success;
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setAudioHistorySectionVisible", base::Value(visible),
- base::Value(audio_history_state));
-}
-
-void BrowserOptionsHandler::HandleRequestGoogleNowAvailable(
- const base::ListValue* args) {
- bool is_search_provider_google = false;
- if (template_url_service_ && template_url_service_->loaded()) {
- const TemplateURL* default_url =
- template_url_service_->GetDefaultSearchProvider();
- if (default_url && default_url->HasGoogleBaseURLs(
- template_url_service_->search_terms_data())) {
- is_search_provider_google = true;
- }
- }
-
- std::string group = base::FieldTrialList::FindFullName("GoogleNowExtension");
- bool has_field_trial = !group.empty() && group != "Disabled";
-
- bool should_show = is_search_provider_google && has_field_trial;
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.setNowSectionVisible",
- base::Value(should_show));
-}
-
-void BrowserOptionsHandler::HandleRequestHotwordAvailable(
- const base::ListValue* args) {
- Profile* profile = Profile::FromWebUI(web_ui());
-
- bool is_search_provider_google = false;
- // The check for default search provider is only valid if the
- // |template_url_service_| has loaded already.
- if (template_url_service_ && template_url_service_->loaded()) {
- const TemplateURL* default_url =
- template_url_service_->GetDefaultSearchProvider();
- if (default_url && default_url->HasGoogleBaseURLs(
- template_url_service_->search_terms_data())) {
- is_search_provider_google = true;
- } else {
- // If the user has chosen a default search provide other than Google, turn
- // off hotwording since other providers don't provide that functionality.
- HotwordService* hotword_service =
- HotwordServiceFactory::GetForProfile(profile);
- if (hotword_service)
- hotword_service->DisableHotwordPreferences();
- }
- }
-
- // |is_search_provider_google| may be false because |template_url_service_|
- // does not exist yet or because the user selected a different search
- // provider. In either case it does not make sense to show the hotwording
- // options.
- if (!is_search_provider_google) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setAllHotwordSectionsVisible", base::Value(false));
- return;
- }
-
- // Don't need to check the field trial here since |IsHotwordAllowed| also
- // checks it.
- if (HotwordServiceFactory::IsHotwordAllowed(profile)) {
- // Update the current error value.
- HotwordServiceFactory::IsServiceAvailable(profile);
- int error = HotwordServiceFactory::GetCurrentError(profile);
-
- std::string function_name;
- bool always_on = false;
- SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile);
- bool authenticated = signin && signin->IsAuthenticated();
- if (HotwordServiceFactory::IsAlwaysOnAvailable() && authenticated) {
- function_name = "BrowserOptions.showHotwordAlwaysOnSection";
- always_on = true;
- // Show the retrain link if always-on is enabled.
- if (profile->GetPrefs()->GetBoolean(
- prefs::kHotwordAlwaysOnSearchEnabled)) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setHotwordRetrainLinkVisible", base::Value(true));
- }
- } else {
- function_name = "BrowserOptions.showHotwordNoDspSection";
- }
-
- // Audio history should be displayed if it's enabled regardless of the
- // hotword error state if the user is signed in. If the user is not signed
- // in, audio history is meaningless. This is only displayed if always-on
- // hotwording is available.
- if (authenticated && always_on) {
- std::string user_display_name =
- signin->GetAuthenticatedAccountInfo().email;
- DCHECK(!user_display_name.empty());
- base::string16 audio_history_state =
- l10n_util::GetStringFUTF16(IDS_HOTWORD_AUDIO_HISTORY_ENABLED,
- base::ASCIIToUTF16(user_display_name));
- HotwordService* hotword_service =
- HotwordServiceFactory::GetForProfile(profile);
- if (hotword_service) {
- hotword_service->GetAudioHistoryHandler()->GetAudioHistoryEnabled(
- base::Bind(
- &BrowserOptionsHandler::SetHotwordAudioHistorySectionVisible,
- weak_ptr_factory_.GetWeakPtr(),
- audio_history_state));
- }
- }
-
- if (!error) {
- web_ui()->CallJavascriptFunctionUnsafe(function_name);
- } else {
- base::string16 hotword_help_url =
- base::ASCIIToUTF16(chrome::kHotwordLearnMoreURL);
- base::Value error_message(l10n_util::GetStringUTF16(error));
- if (error == IDS_HOTWORD_GENERIC_ERROR_MESSAGE) {
- error_message =
- base::Value(l10n_util::GetStringFUTF16(error, hotword_help_url));
- }
- web_ui()->CallJavascriptFunctionUnsafe(function_name, error_message);
- }
- }
-}
-
-void BrowserOptionsHandler::HandleLaunchHotwordAudioVerificationApp(
- const base::ListValue* args) {
- Profile* profile = Profile::FromWebUI(web_ui());
-
- bool retrain = false;
- bool success = args->GetBoolean(0, &retrain);
- DCHECK(success);
- HotwordService::LaunchMode launch_mode =
- HotwordService::HOTWORD_AND_AUDIO_HISTORY;
-
- if (retrain) {
- DCHECK(profile->GetPrefs()->GetBoolean(
- prefs::kHotwordAlwaysOnSearchEnabled));
- DCHECK(profile->GetPrefs()->GetBoolean(
- prefs::kHotwordAudioLoggingEnabled));
-
- launch_mode = HotwordService::RETRAIN;
- } else if (profile->GetPrefs()->GetBoolean(
- prefs::kHotwordAudioLoggingEnabled)) {
- DCHECK(!profile->GetPrefs()->GetBoolean(
- prefs::kHotwordAlwaysOnSearchEnabled));
- launch_mode = HotwordService::HOTWORD_ONLY;
- } else {
- DCHECK(!profile->GetPrefs()->GetBoolean(
- prefs::kHotwordAlwaysOnSearchEnabled));
- }
-
- HotwordService* hotword_service =
- HotwordServiceFactory::GetForProfile(profile);
- if (!hotword_service)
- return;
-
- hotword_service->OptIntoHotwording(launch_mode);
-}
-
-void BrowserOptionsHandler::HandleLaunchEasyUnlockSetup(
- const base::ListValue* args) {
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->LaunchSetup();
-}
-
-void BrowserOptionsHandler::HandleRefreshExtensionControlIndicators(
- const base::ListValue* args) {
- SetupExtensionControlledIndicators();
-}
-
-#if defined(OS_CHROMEOS)
-void BrowserOptionsHandler::HandleOpenWallpaperManager(
- const base::ListValue* args) {
- chromeos::WallpaperManager::Get()->Open();
-}
-
-void BrowserOptionsHandler::VirtualKeyboardChangeCallback(
- const base::ListValue* args) {
- bool enabled = false;
- args->GetBoolean(0, &enabled);
-
- chromeos::accessibility::EnableVirtualKeyboard(enabled);
-}
-
-void BrowserOptionsHandler::PerformFactoryResetRestart(
- const base::ListValue* args) {
- if (!enable_factory_reset_)
- return;
-
- PrefService* prefs = g_browser_process->local_state();
- prefs->SetBoolean(prefs::kFactoryResetRequested, true);
- prefs->CommitPendingWrite();
-
- // Perform sign out. Current chrome process will then terminate, new one will
- // be launched (as if it was a restart).
- chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
-}
-
-void BrowserOptionsHandler::OnAppRegistered(
- const std::string& app_id,
- const ArcAppListPrefs::AppInfo& app_info) {
- OnAppReadyChanged(app_id, app_info.ready);
-}
-
-void BrowserOptionsHandler::OnAppRemoved(const std::string& app_id) {
- OnAppReadyChanged(app_id, false);
-}
-
-void BrowserOptionsHandler::OnAppReadyChanged(
- const std::string& app_id,
- bool ready) {
- if (app_id == arc::kSettingsAppId) {
- UpdateAndroidSettingsAppState(ready);
- }
-}
-
-void BrowserOptionsHandler::OnUserImageChanged(const user_manager::User& user) {
- UpdateAccountPicture();
-}
-
-void BrowserOptionsHandler::UpdateAndroidSettingsAppState(bool visible) {
- base::Value is_visible(visible);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setAndroidAppsSettingsVisibility", is_visible);
-}
-
-void BrowserOptionsHandler::ShowAndroidAppsSettings(
- const base::ListValue* args) {
- Profile* profile = Profile::FromWebUI(web_ui());
- // Settings in secondary profile cannot access ARC.
- if (!arc::IsArcAllowedForProfile(profile)) {
- LOG(ERROR) << "Settings can't be invoked for non-primary profile";
- return;
- }
-
- // We only care whether the event came from a keyboard or non-keyboard
- // (mouse/touch). Set the default flags in such a way that it would appear
- // that it came from a mouse by default.
- bool activated_from_keyboard = false;
- args->GetBoolean(0, &activated_from_keyboard);
- int flags = activated_from_keyboard ? ui::EF_NONE : ui::EF_LEFT_MOUSE_BUTTON;
-
- arc::LaunchAndroidSettingsApp(profile, flags);
-}
-
-void BrowserOptionsHandler::ShowPlayStoreApps(const base::ListValue* args) {
- std::string apps_url;
- args->GetString(0, &apps_url);
- Profile* profile = Profile::FromWebUI(web_ui());
- if (!arc::IsArcAllowedForProfile(profile)) {
- VLOG(1) << "ARC is not enabled for this profile";
- return;
- }
-
- arc::LaunchPlayStoreWithUrl(apps_url);
-}
-
-void BrowserOptionsHandler::ShowAccessibilityTalkBackSettings(
- const base::ListValue *args) {
- Profile* profile = Profile::FromWebUI(web_ui());
- // Settings in secondary profile cannot access ARC.
- if (!arc::IsArcAllowedForProfile(profile)) {
- LOG(WARNING) << "Settings can't be invoked for non-primary profile";
- return;
- }
-
- arc::ShowTalkBackSettings();
-}
-
-void BrowserOptionsHandler::SetupAccessibilityFeatures() {
- PrefService* pref_service = g_browser_process->local_state();
- base::Value virtual_keyboard_enabled(
- pref_service->GetBoolean(prefs::kAccessibilityVirtualKeyboardEnabled));
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setVirtualKeyboardCheckboxState",
- virtual_keyboard_enabled);
-}
-#endif
-
-void BrowserOptionsHandler::SetupMetricsReportingSettingVisibility() {
-#if defined(GOOGLE_CHROME_BUILD)
- // Don't show the reporting setting if we are in the guest mode.
- if (Profile::FromWebUI(web_ui())->IsGuestSession()) {
- base::Value visible(false);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setMetricsReportingSettingVisibility", visible);
- }
-#endif
-}
-
-void BrowserOptionsHandler::SetupNetworkPredictionControl() {
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
-
- base::DictionaryValue dict;
- dict.SetInteger("value",
- pref_service->GetInteger(prefs::kNetworkPredictionOptions));
- dict.SetBoolean("disabled",
- !pref_service->IsUserModifiablePreference(
- prefs::kNetworkPredictionOptions));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setNetworkPredictionValue", dict);
-}
-
-void BrowserOptionsHandler::SetupFontSizeSelector() {
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
- const PrefService::Preference* default_font_size =
- pref_service->FindPreference(prefs::kWebKitDefaultFontSize);
- const PrefService::Preference* default_fixed_font_size =
- pref_service->FindPreference(prefs::kWebKitDefaultFixedFontSize);
-
- base::DictionaryValue dict;
- dict.SetInteger("value",
- pref_service->GetInteger(prefs::kWebKitDefaultFontSize));
-
- // The font size control displays the value of the default font size, but
- // setting it alters both the default font size and the default fixed font
- // size. So it must be disabled when either of those prefs is not user
- // modifiable.
- dict.SetBoolean("disabled",
- !default_font_size->IsUserModifiable() ||
- !default_fixed_font_size->IsUserModifiable());
-
- // This is a simplified version of CoreOptionsHandler::CreateValueForPref,
- // adapted to consider two prefs. It may be better to refactor
- // CreateValueForPref so it can be called from here.
- if (default_font_size->IsManaged() || default_fixed_font_size->IsManaged()) {
- dict.SetString("controlledBy", "policy");
- } else if (default_font_size->IsExtensionControlled() ||
- default_fixed_font_size->IsExtensionControlled()) {
- dict.SetString("controlledBy", "extension");
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.setFontSize", dict);
-}
-
-void BrowserOptionsHandler::SetupPageZoomSelector() {
- double default_zoom_level =
- content::HostZoomMap::GetDefaultForBrowserContext(
- Profile::FromWebUI(web_ui()))->GetDefaultZoomLevel();
- double default_zoom_factor =
- content::ZoomLevelToZoomFactor(default_zoom_level);
-
- // Generate a vector of zoom factors from an array of known presets along with
- // the default factor added if necessary.
- std::vector<double> zoom_factors =
- zoom::PageZoom::PresetZoomFactors(default_zoom_factor);
-
- // Iterate through the zoom factors and and build the contents of the
- // selector that will be sent to the javascript handler.
- // Each item in the list has the following parameters:
- // 1. Title (string).
- // 2. Value (double).
- // 3. Is selected? (bool).
- base::ListValue zoom_factors_value;
- for (std::vector<double>::const_iterator i = zoom_factors.begin();
- i != zoom_factors.end(); ++i) {
- std::unique_ptr<base::ListValue> option(new base::ListValue());
- double factor = *i;
- int percent = static_cast<int>(factor * 100 + 0.5);
- option->AppendString(base::FormatPercent(percent));
- option->AppendDouble(factor);
- bool selected = content::ZoomValuesEqual(factor, default_zoom_factor);
- option->AppendBoolean(selected);
- zoom_factors_value.Append(std::move(option));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.setupPageZoomSelector",
- zoom_factors_value);
-}
-
-void BrowserOptionsHandler::SetupAutoOpenFileTypes() {
- // Set the hidden state for the AutoOpenFileTypesResetToDefault button.
- // We show the button if the user has any auto-open file types registered.
- DownloadManager* manager = BrowserContext::GetDownloadManager(
- web_ui()->GetWebContents()->GetBrowserContext());
- bool display = DownloadPrefs::FromDownloadManager(manager)->IsAutoOpenUsed();
- base::Value value(display);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setAutoOpenFileTypesDisplayed", value);
-}
-
-void BrowserOptionsHandler::SetupProxySettingsSection() {
-#if !defined(OS_CHROMEOS)
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
- const PrefService::Preference* proxy_config =
- pref_service->FindPreference(proxy_config::prefs::kProxy);
- bool is_extension_controlled = (proxy_config &&
- proxy_config->IsExtensionControlled());
-
- base::Value disabled(proxy_config && !proxy_config->IsUserModifiable());
- base::Value extension_controlled(is_extension_controlled);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setupProxySettingsButton", disabled,
- extension_controlled);
-
-#if defined(OS_WIN)
- SetupExtensionControlledIndicators();
-#endif // defined(OS_WIN)
-
-#endif // !defined(OS_CHROMEOS)
-}
-
-void BrowserOptionsHandler::SetupManagingSupervisedUsers() {
- bool has_users = !Profile::FromWebUI(web_ui())->
- GetPrefs()->GetDictionary(prefs::kSupervisedUsers)->empty();
- base::Value has_users_value(has_users);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.updateManagesSupervisedUsers", has_users_value);
-}
-
-void BrowserOptionsHandler::SetupEasyUnlock() {
- base::Value is_enabled(
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->IsEnabled());
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.updateEasyUnlock",
- is_enabled);
-}
-
-void BrowserOptionsHandler::SetupExtensionControlledIndicators() {
- base::DictionaryValue extension_controlled;
-
- Profile* profile = Profile::FromWebUI(web_ui());
-
- // Check if an extension is overriding the Search Engine.
- const extensions::Extension* extension =
- extensions::GetExtensionOverridingSearchEngine(profile);
- AppendExtensionData("searchEngine", extension, &extension_controlled);
-
- // Check if an extension is overriding the Home page.
- extension = extensions::GetExtensionOverridingHomepage(profile);
- AppendExtensionData("homePage", extension, &extension_controlled);
-
- // Check if an extension is overriding the Startup pages.
- extension = extensions::GetExtensionOverridingStartupPages(profile);
- AppendExtensionData("startUpPage", extension, &extension_controlled);
-
- // Check if an extension is overriding the NTP page.
- extension = extensions::GetExtensionOverridingNewTabPage(profile);
- AppendExtensionData("newTabPage", extension, &extension_controlled);
-
- // Check if an extension is overwriting the proxy setting.
- extension = extensions::GetExtensionOverridingProxy(profile);
- AppendExtensionData("proxy", extension, &extension_controlled);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.toggleExtensionIndicators", extension_controlled);
-}
-
-void BrowserOptionsHandler::SetupMetricsReportingCheckbox() {
-// As the metrics and crash reporting checkbox only exists for official builds
-// it doesn't need to be set up for non-official builds.
-#if defined(GOOGLE_CHROME_BUILD)
- bool checked =
- ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled();
- bool policy_managed = IsMetricsReportingPolicyManaged();
- bool owner_managed = false;
-#if defined(OS_CHROMEOS)
- owner_managed = !IsDeviceOwnerProfile();
-#endif // defined(OS_CHROMEOS)
- SetMetricsReportingCheckbox(checked, policy_managed, owner_managed);
-#endif // defined(GOOGLE_CHROME_BUILD)
-}
-
-void BrowserOptionsHandler::HandleMetricsReportingChange(
- const base::ListValue* args) {
- bool enable;
- if (!args->GetBoolean(0, &enable))
- return;
- // Decline the change if current user shouldn't be able to change metrics
- // reporting.
- if (!IsDeviceOwnerProfile() || IsMetricsReportingPolicyManaged()) {
- NotifyUIOfMetricsReportingChange(
- ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
- return;
- }
-
-// For Chrome OS updating device settings will notify an observer to update
-// metrics pref, however we still need to call
-// |ChangeMetricsReportingStateWithReply| with a proper callback so that UI gets
-// updated in case of failure to update the metrics pref.
-// TODO(gayane): Don't call |ChangeMetricsReportingStateWithReply| twice so that
-// metrics service pref changes only as a result of device settings change for
-// Chrome OS .crbug.com/552550.
-#if defined(OS_CHROMEOS)
- chromeos::CrosSettings::Get()->SetBoolean(chromeos::kStatsReportingPref,
- enable);
-#endif // defined(OS_CHROMEOS)
- ChangeMetricsReportingStateWithReply(
- enable,
- base::Bind(&BrowserOptionsHandler::NotifyUIOfMetricsReportingChange,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void BrowserOptionsHandler::NotifyUIOfMetricsReportingChange(bool enabled) {
- SetMetricsReportingCheckbox(enabled, IsMetricsReportingPolicyManaged(),
- !IsDeviceOwnerProfile());
-}
-
-void BrowserOptionsHandler::SetMetricsReportingCheckbox(bool checked,
- bool policy_managed,
- bool owner_managed) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setMetricsReportingCheckboxState", base::Value(checked),
- base::Value(policy_managed), base::Value(owner_managed));
-}
-
-void BrowserOptionsHandler::SetupSafeBrowsingExtendedReporting() {
- base::Value is_enabled(safe_browsing::IsExtendedReportingEnabled(
- *Profile::FromWebUI(web_ui())->GetPrefs()));
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setExtendedReportingEnabledCheckboxState", is_enabled);
-}
-
-void BrowserOptionsHandler::HandleSafeBrowsingExtendedReporting(
- const base::ListValue* args) {
- bool checked;
- if (args->GetBoolean(0, &checked)) {
- safe_browsing::SetExtendedReportingPrefAndMetric(
- Profile::FromWebUI(web_ui())->GetPrefs(), checked,
- safe_browsing::SBER_OPTIN_SITE_CHROME_SETTINGS);
- }
-}
-
-void BrowserOptionsHandler::OnPolicyUpdated(const policy::PolicyNamespace& ns,
- const policy::PolicyMap& previous,
- const policy::PolicyMap& current) {
- std::set<std::string> different_keys;
- current.GetDifferingKeys(previous, &different_keys);
- if (base::ContainsKey(different_keys, policy::key::kMetricsReportingEnabled))
- SetupMetricsReportingCheckbox();
-}
-
-#if defined(OS_CHROMEOS)
-// static
-void BrowserOptionsHandler::DisablePolymerPreloadForTesting() {
- g_enable_polymer_preload = false;
-}
-#endif // defined(OS_CHROMEOS)
-
-bool BrowserOptionsHandler::IsDeviceOwnerProfile() {
-#if defined(OS_CHROMEOS)
- return chromeos::ProfileHelper::IsOwnerProfile(Profile::FromWebUI(web_ui()));
-#else
- return true;
-#endif
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/browser_options_handler.h b/chromium/chrome/browser/ui/webui/options/browser_options_handler.h
deleted file mode 100644
index 0fccab7731a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/browser_options_handler.h
+++ /dev/null
@@ -1,464 +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_OPTIONS_BROWSER_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_BROWSER_OPTIONS_HANDLER_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "base/scoped_observer.h"
-#include "build/build_config.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_attributes_storage.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
-#include "chrome/common/features.h"
-#include "components/policy/core/common/policy_service.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "components/prefs/pref_member.h"
-#include "components/search_engines/template_url_service_observer.h"
-#include "components/signin/core/browser/signin_manager_base.h"
-#include "components/signin/core/common/signin_pref_names.h"
-#include "components/sync/driver/sync_service_observer.h"
-#include "content/public/browser/notification_observer.h"
-#include "extensions/browser/extension_registry_observer.h"
-#include "google_apis/gaia/google_service_auth_error.h"
-#include "printing/features/features.h"
-#include "ui/base/models/table_model_observer.h"
-#include "ui/shell_dialogs/select_file_dialog.h"
-
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/browser/chromeos/system/pointer_device_observer.h"
-#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
-#include "components/user_manager/user_manager.h"
-#else // defined(OS_CHROMEOS)
-#include "chrome/browser/shell_integration.h"
-#endif // !defined(OS_CHROMEOS)
-
-class TemplateURLService;
-
-namespace base {
-class Value;
-}
-
-namespace policy {
-class PolicyChangeRegistrar;
-}
-
-namespace options {
-
-// Chrome browser options page UI handler.
-class BrowserOptionsHandler
- : public OptionsPageUIHandler,
- public ProfileAttributesStorage::Observer,
- public syncer::SyncServiceObserver,
- public SigninManagerBase::Observer,
- public ui::SelectFileDialog::Listener,
-#if defined(OS_CHROMEOS)
- public chromeos::system::PointerDeviceObserver::Observer,
- public ArcAppListPrefs::Observer,
- public user_manager::UserManager::Observer,
-#endif
- public TemplateURLServiceObserver,
- public extensions::ExtensionRegistryObserver,
- public content::NotificationObserver,
- public policy::PolicyService::Observer {
- public:
- BrowserOptionsHandler();
- ~BrowserOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* values) override;
- void PageLoadStarted() override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
- void Uninitialize() override;
-
- // syncer::SyncServiceObserver implementation.
- void OnStateChanged(syncer::SyncService* sync) override;
-
- // SigninManagerBase::Observer implementation.
- void GoogleSigninSucceeded(const std::string& account_id,
- const std::string& username) override;
- void GoogleSignedOut(const std::string& account_id,
- const std::string& username) override;
-
- // TemplateURLServiceObserver implementation.
- void OnTemplateURLServiceChanged() override;
-
- // extensions::ExtensionRegistryObserver:
- void OnExtensionLoaded(content::BrowserContext* browser_context,
- const extensions::Extension* extension) override;
- void OnExtensionUnloaded(content::BrowserContext* browser_context,
- const extensions::Extension* extension,
- extensions::UnloadedExtensionReason reason) override;
-
- // policy::PolicyService::Observer:
- void OnPolicyUpdated(const policy::PolicyNamespace& ns,
- const policy::PolicyMap& previous,
- const policy::PolicyMap& current) override;
-#if defined(OS_CHROMEOS)
- static void DisablePolymerPreloadForTesting();
-#endif // defined(OS_CHROMEOS)
-
- private:
- // content::NotificationObserver implementation.
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
-
- // ProfileAttributesStorage::Observer implementation.
- void OnProfileAdded(const base::FilePath& profile_path) override;
- void OnProfileWasRemoved(const base::FilePath& profile_path,
- const base::string16& profile_name) override;
- void OnProfileNameChanged(const base::FilePath& profile_path,
- const base::string16& old_profile_name) override;
- void OnProfileAvatarChanged(const base::FilePath& profile_path) override;
-
-#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
- void OnCloudPrintPrefsChanged();
-#endif
-
- // SelectFileDialog::Listener implementation
- void FileSelected(const base::FilePath& path,
- int index,
- void* params) override;
-
-#if defined(OS_CHROMEOS)
- // PointerDeviceObserver::Observer implementation.
- void TouchpadExists(bool exists) override;
- void MouseExists(bool exists) override;
-
- // Will be called when the policy::key::kUserAvatarImage policy changes.
- void OnUserImagePolicyChanged(const base::Value* previous_policy,
- const base::Value* current_policy);
-
- // Will be called when the policy::key::kWallpaperImage policy changes.
- void OnWallpaperPolicyChanged(const base::Value* previous_policy,
- const base::Value* current_policy);
-
- // Will be called when powerwash dialog is shown.
- void OnPowerwashDialogShow(const base::ListValue* args);
-
- // ArcAppListPrefs::Observer overrides.
- void OnAppReadyChanged(const std::string& app_id, bool ready) override;
- void OnAppRemoved(const std::string& app_id) override;
- void OnAppRegistered(const std::string& app_id,
- const ArcAppListPrefs::AppInfo& app_info) override;
-
- // user_manager::UserManager::Observer overrides.
- void OnUserImageChanged(const user_manager::User& user) override;
-#endif
-
- void UpdateSyncState();
-
- // Will be called when the kSigninAllowed pref has changed.
- void OnSigninAllowedPrefChange();
-
- // Sets the search engine at the given index to be default. Called from WebUI.
- void SetDefaultSearchEngine(const base::ListValue* args);
-
- // Returns if the "make Chrome default browser" button should be shown.
- bool ShouldShowSetDefaultBrowser();
-
- // Returns if profiles list should be shown on settings page.
- bool ShouldShowMultiProfilesUserList();
-
- // Returns if access to advanced settings should be allowed.
- bool ShouldAllowAdvancedSettings();
-
-#if !defined(OS_CHROMEOS)
- // Gets the current default browser state, and asynchronously reports it to
- // the WebUI page.
- void UpdateDefaultBrowserState();
-
- // Makes this the default browser. Called from WebUI.
- void BecomeDefaultBrowser(const base::ListValue* args);
-
- // Receives the default browser state when the worker is done.
- void OnDefaultBrowserWorkerFinished(
- shell_integration::DefaultWebClientState state);
-
- // Updates the UI with the given state for the default browser.
- void SetDefaultBrowserUIString(int status_string_id);
-#endif // !defined(OS_CHROMEOS)
-
- // Loads the possible default search engine list and reports it to the WebUI.
- void AddTemplateUrlServiceObserver();
-
- // Creates a list of dictionaries where each dictionary is of the form:
- // profileInfo = {
- // name: "Profile Name",
- // iconURL: "chrome://path/to/icon/image",
- // filePath: "/path/to/profile/data/on/disk",
- // isCurrentProfile: false
- // };
- std::unique_ptr<base::ListValue> GetProfilesInfoList();
-
- // Sends an array of Profile objects to javascript.
- void SendProfilesInfo();
-
- // Deletes the given profile. Expects one argument:
- // 0: profile file path (string)
- void DeleteProfile(const base::ListValue* args);
-
- void ObserveThemeChanged();
- void ThemesReset(const base::ListValue* args);
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
- void ThemesSetNative(const base::ListValue* args);
-#endif
-
-#if defined(OS_CHROMEOS)
- void UpdateAccountPicture();
-
- // Updates the UI, allowing the user to change the avatar image if |managed|
- // is |false| and preventing the user from changing the avatar image if
- // |managed| is |true|.
- void OnAccountPictureManagedChanged(bool managed);
-
- // Updates the UI, allowing the user to change the wallpaper if |managed| is
- // |false| and preventing the user from changing the wallpaper if |managed| is
- // |true|.
- void OnWallpaperManagedChanged(bool managed);
-
- // Updates the UI, allowing the user to change the system time zone if
- // kSystemTimezonePolicy is set, and preventing the user from changing the
- // system time zone if kSystemTimezonePolicy is not set.
- void OnSystemTimezonePolicyChanged();
-
- // Updates the UI, preventing the user from changing timezone or timezone
- // detection settings if kSystemTimezoneAutomaticDetectionPolicy is set, and
- // allowing the user to update these settings if
- // kSystemTimezoneAutomaticDetectionPolicy is not set.
- void OnSystemTimezoneAutomaticDetectionPolicyChanged();
-#endif
-
- // Callback for the "selectDownloadLocation" message. This will prompt the
- // user for a destination folder using platform-specific APIs.
- void HandleSelectDownloadLocation(const base::ListValue* args);
-
- // Callback for the "autoOpenFileTypesResetToDefault" message. This will
- // remove all auto-open file-type settings.
- void HandleAutoOpenButton(const base::ListValue* args);
-
- // Callback for the "defaultFontSizeAction" message. This is called if the
- // user changes the default font size. |args| is an array that contains
- // one item, the font size as a numeric value.
- void HandleDefaultFontSize(const base::ListValue* args);
-
- // Callback for the "defaultZoomFactorAction" message. This is called if the
- // user changes the default zoom factor. |args| is an array that contains
- // one item, the zoom factor as a numeric value.
- void HandleDefaultZoomFactor(const base::ListValue* args);
-
- // Callback for the "Use SSL 3.0" checkbox. This is called if the user toggles
- // the "Use SSL 3.0" checkbox.
- void HandleUseSSL3Checkbox(const base::ListValue* args);
-
- // Callback for the "Use TLS 1.0" checkbox. This is called if the user toggles
- // the "Use TLS 1.0" checkbox.
- void HandleUseTLS1Checkbox(const base::ListValue* args);
-
- // Callback for the "restartBrowser" message. Restores all tabs on restart.
- void HandleRestartBrowser(const base::ListValue* args);
-
- // Callback for "requestProfilesInfo" message.
- void HandleRequestProfilesInfo(const base::ListValue* args);
-
-#if !defined(OS_CHROMEOS)
- // Callback for the "showNetworkProxySettings" message. This will invoke
- // an appropriate dialog for configuring proxy settings.
- void ShowNetworkProxySettings(const base::ListValue* args);
-#endif
-
-#if !defined(USE_NSS_CERTS)
- // Callback for the "showManageSSLCertificates" message. This will invoke
- // an appropriate certificate management action based on the platform.
- void ShowManageSSLCertificates(const base::ListValue* args);
-#endif
-
-#if defined(OS_CHROMEOS)
- void ShowCupsPrintDevicesPage(const base::ListValue* args);
-#endif // defined(OS_CHROMEOS)
-
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- void ShowCloudPrintDevicesPage(const base::ListValue* args);
-#endif
-
-#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
- // Register localized values used by Cloud Print
- void RegisterCloudPrintValues(base::DictionaryValue* values);
-#endif
-
- // Check if hotword is available. If it is, tell the javascript to show
- // the hotword section of the settings page.
- void SendHotwordAvailable();
-
- // Callback that updates the visibility of the audio history upon completion
- // of a call to the server to the get the current value.
- void SetHotwordAudioHistorySectionVisible(
- const base::string16& audio_history_state,
- bool success,
- bool logging_enabled);
-
- // Callback for "requestHotwordAvailable" message.
- void HandleRequestHotwordAvailable(const base::ListValue* args);
-
- // Callback for "launchHotwordAudioVerificationApp" message.
- void HandleLaunchHotwordAudioVerificationApp(const base::ListValue* args);
-
- // Callback for "requestGoogleNowAvailable" message.
- void HandleRequestGoogleNowAvailable(const base::ListValue* args);
-
- // Callback for "launchEasyUnlockSetup" message.
- void HandleLaunchEasyUnlockSetup(const base::ListValue* args);
-
- // Callback for "refreshExtensionControlIndicators" message.
- void HandleRefreshExtensionControlIndicators(const base::ListValue* args);
-
-#if defined(OS_CHROMEOS)
- // Opens the wallpaper manager component extension.
- void HandleOpenWallpaperManager(const base::ListValue* args);
-
- // Called when the accessibility checkbox values are changed.
- // |args| will contain the checkbox checked state as a string
- // ("true" or "false").
- void VirtualKeyboardChangeCallback(const base::ListValue* args);
-
- // Called when the user confirmed factory reset. Chrome will
- // initiate asynchronous file operation and then log out.
- void PerformFactoryResetRestart(const base::ListValue* args);
-
- // Update visibility of Android apps settings section.
- void UpdateAndroidSettingsAppState(bool visible);
-
- // Called to show Android apps settings.
- void ShowAndroidAppsSettings(const base::ListValue* args);
-
- // Called to show apps based on a url for the Play Store.
- void ShowPlayStoreApps(const base::ListValue* args);
-
- // Called to show TalkBack settings.
- void ShowAccessibilityTalkBackSettings(const base::ListValue *args);
-#endif
-
- // Setup the visibility for the metrics reporting setting.
- void SetupMetricsReportingSettingVisibility();
-
- // Update value of predictive network actions UI element.
- void SetupNetworkPredictionControl();
-
- // Setup the font size selector control.
- void SetupFontSizeSelector();
-
- // Setup the page zoom selector control.
- void SetupPageZoomSelector();
-
- // Setup the visibility of the reset button.
- void SetupAutoOpenFileTypes();
-
- // Setup the proxy settings section UI.
- void SetupProxySettingsSection();
-
- // Setup the UI specific to managing supervised users.
- void SetupManagingSupervisedUsers();
-
- // Setup the UI for Easy Unlock.
- void SetupEasyUnlock();
-
- // Setup the UI for showing which settings are extension controlled.
- void SetupExtensionControlledIndicators();
-
- // Setup the value and the disabled property for metrics reporting for (except
- // Android).
- void SetupMetricsReportingCheckbox();
-
- // Called when the MetricsReportingEnabled checkbox values are changed.
- // |args| will contain the checkbox checked state as a boolean.
- void HandleMetricsReportingChange(const base::ListValue* args);
-
- // Notifies the result of MetricsReportingEnabled change to Javascript layer.
- void NotifyUIOfMetricsReportingChange(bool enabled);
-
- // Calls a Javascript function to set the state of MetricsReporting checkbox.
- void SetMetricsReportingCheckbox(bool checked,
- bool policy_managed,
- bool owner_managed);
-
-#if defined(OS_CHROMEOS)
- // Setup the accessibility features for ChromeOS.
- void SetupAccessibilityFeatures();
-#endif
-
- // Update the Extended Reporting Enabled checkbox based on the current state
- // of the opt-in.
- void SetupSafeBrowsingExtendedReporting();
-
- // Callback for "safeBrowsingExtentedReportingAction" message. This is called
- // if the user checks or unchecks the Extended Reporting checkbox. |args| is
- // an array that contains one item, the checked state of the checkbox.
- void HandleSafeBrowsingExtendedReporting(const base::ListValue* args);
-
- // Returns a newly created dictionary with a number of properties that
- // correspond to the status of sync.
- std::unique_ptr<base::DictionaryValue> GetSyncStateDictionary();
-
- // Checks whether on Chrome OS the current user is the device owner. Returns
- // true on other platforms.
- bool IsDeviceOwnerProfile();
-
-#if !defined(OS_CHROMEOS)
- scoped_refptr<shell_integration::DefaultBrowserWorker>
- default_browser_worker_;
- BooleanPrefMember default_browser_policy_;
-#endif
-
- bool page_initialized_;
-
- StringPrefMember homepage_;
-
- TemplateURLService* template_url_service_; // Weak.
-
- scoped_refptr<ui::SelectFileDialog> select_folder_dialog_;
-
- bool cloud_print_mdns_ui_enabled_;
-
- StringPrefMember auto_open_files_;
-
- std::unique_ptr<ChromeZoomLevelPrefs::DefaultZoomLevelSubscription>
- default_zoom_level_subscription_;
-
- PrefChangeRegistrar profile_pref_registrar_;
-#if defined(OS_CHROMEOS)
- std::unique_ptr<policy::PolicyChangeRegistrar> policy_registrar_;
-
- // Whether factory reset can be performed.
- bool enable_factory_reset_;
-
- PrefChangeRegistrar local_state_pref_change_registrar_;
-
- std::unique_ptr<chromeos::CrosSettings::ObserverSubscription>
- system_timezone_policy_observer_;
-#endif
-
- ScopedObserver<SigninManagerBase, SigninManagerBase::Observer>
- signin_observer_;
-
- // Used to get WeakPtr to self for use on the UI thread.
- base::WeakPtrFactory<BrowserOptionsHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(BrowserOptionsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_BROWSER_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/certificate_manager_handler.cc b/chromium/chrome/browser/ui/webui/options/certificate_manager_handler.cc
deleted file mode 100644
index 91f5f9f50d1..00000000000
--- a/chromium/chrome/browser/ui/webui/options/certificate_manager_handler.cc
+++ /dev/null
@@ -1,1239 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/certificate_manager_handler.h"
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include <algorithm>
-#include <map>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/files/file_util.h" // for FileAccessProvider
-#include "base/i18n/string_compare.h"
-#include "base/id_map.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/posix/safe_strerror.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/certificate_viewer.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/certificate_dialogs.h"
-#include "chrome/browser/ui/chrome_select_file_policy.h"
-#include "chrome/browser/ui/crypto_module_password_dialog_nss.h"
-#include "chrome/browser/ui/webui/certificate_viewer_webui.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/web_contents.h"
-#include "net/base/net_errors.h"
-#include "net/cert/x509_certificate.h"
-#include "net/der/input.h"
-#include "net/der/parser.h"
-#include "ui/base/l10n/l10n_util.h"
-
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/chromeos/policy/user_network_configuration_updater.h"
-#include "chrome/browser/chromeos/policy/user_network_configuration_updater_factory.h"
-#endif
-
-using base::UTF8ToUTF16;
-using content::BrowserThread;
-
-namespace {
-
-static const char kKeyId[] = "id";
-static const char kSubNodesId[] = "subnodes";
-static const char kNameId[] = "name";
-static const char kReadOnlyId[] = "readonly";
-static const char kUntrustedId[] = "untrusted";
-static const char kExtractableId[] = "extractable";
-static const char kErrorId[] = "error";
-static const char kPolicyTrustedId[] = "policy";
-
-// Enumeration of different callers of SelectFile. (Start counting at 1 so
-// if SelectFile is accidentally called with params=NULL it won't match any.)
-enum {
- EXPORT_PERSONAL_FILE_SELECTED = 1,
- IMPORT_PERSONAL_FILE_SELECTED,
- IMPORT_SERVER_FILE_SELECTED,
- IMPORT_CA_FILE_SELECTED,
-};
-
-std::string OrgNameToId(const std::string& org) {
- return "org-" + org;
-}
-
-bool CallbackArgsToBool(const base::ListValue* args, int index, bool* result) {
- std::string string_value;
- if (!args->GetString(index, &string_value))
- return false;
-
- *result = string_value[0] == 't';
- return true;
-}
-
-struct DictionaryIdComparator {
- explicit DictionaryIdComparator(icu::Collator* collator)
- : collator_(collator) {
- }
-
- bool operator()(const base::Value& a, const base::Value& b) const {
- const base::DictionaryValue* a_dict;
- bool a_is_dictionary = a.GetAsDictionary(&a_dict);
- DCHECK(a_is_dictionary);
- const base::DictionaryValue* b_dict;
- bool b_is_dictionary = b.GetAsDictionary(&b_dict);
- DCHECK(b_is_dictionary);
- base::string16 a_str;
- base::string16 b_str;
- a_dict->GetString(kNameId, &a_str);
- b_dict->GetString(kNameId, &b_str);
- if (collator_ == NULL)
- return a_str < b_str;
- return base::i18n::CompareString16WithCollator(*collator_, a_str, b_str) ==
- UCOL_LESS;
- }
-
- icu::Collator* collator_;
-};
-
-std::string NetErrorToString(int net_error) {
- switch (net_error) {
- // TODO(mattm): handle more cases.
- case net::ERR_IMPORT_CA_CERT_NOT_CA:
- return l10n_util::GetStringUTF8(IDS_CERT_MANAGER_ERROR_NOT_CA);
- case net::ERR_IMPORT_CERT_ALREADY_EXISTS:
- return l10n_util::GetStringUTF8(
- IDS_CERT_MANAGER_ERROR_CERT_ALREADY_EXISTS);
- default:
- return l10n_util::GetStringUTF8(IDS_CERT_MANAGER_UNKNOWN_ERROR);
- }
-}
-
-// Struct to bind the Equals member function to an object for use in find_if.
-struct CertEquals {
- explicit CertEquals(const net::X509Certificate* cert) : cert_(cert) {}
- bool operator()(const scoped_refptr<net::X509Certificate> cert) const {
- return cert_->Equals(cert.get());
- }
- const net::X509Certificate* cert_;
-};
-
-// Determine whether a certificate was stored with web trust by a policy.
-bool IsPolicyInstalledWithWebTrust(
- const net::CertificateList& web_trust_certs,
- net::X509Certificate* cert) {
- return std::find_if(web_trust_certs.begin(), web_trust_certs.end(),
- CertEquals(cert)) != web_trust_certs.end();
-}
-
-#if defined(OS_CHROMEOS)
-void ShowCertificateViewerModalDialog(content::WebContents* web_contents,
- gfx::NativeWindow parent,
- net::X509Certificate* cert) {
- CertificateViewerModalDialog* dialog = new CertificateViewerModalDialog(cert);
- dialog->Show(web_contents, parent);
-}
-#endif
-
-// Determine if |data| could be a PFX Protocol Data Unit.
-// This only does the minimum parsing necessary to distinguish a PFX file from a
-// DER encoded Certificate.
-//
-// From RFC 7292 section 4:
-// PFX ::= SEQUENCE {
-// version INTEGER {v3(3)}(v3,...),
-// authSafe ContentInfo,
-// macData MacData OPTIONAL
-// }
-// From RFC 5280 section 4.1:
-// Certificate ::= SEQUENCE {
-// tbsCertificate TBSCertificate,
-// signatureAlgorithm AlgorithmIdentifier,
-// signatureValue BIT STRING }
-//
-// Certificate must be DER encoded, while PFX may be BER encoded.
-// Therefore PFX can be distingushed by checking if the file starts with an
-// indefinite SEQUENCE, or a definite SEQUENCE { INTEGER, ... }.
-bool CouldBePFX(const std::string& data) {
- if (data.size() < 4)
- return false;
-
- // Indefinite length SEQUENCE.
- if (data[0] == 0x30 && static_cast<uint8_t>(data[1]) == 0x80)
- return true;
-
- // If the SEQUENCE is definite length, it can be parsed through the version
- // tag using DER parser, since INTEGER must be definite length, even in BER.
- net::der::Parser parser((net::der::Input(&data)));
- net::der::Parser sequence_parser;
- if (!parser.ReadSequence(&sequence_parser))
- return false;
- if (!sequence_parser.SkipTag(net::der::kInteger))
- return false;
- return true;
-}
-
-} // namespace
-
-namespace options {
-
-///////////////////////////////////////////////////////////////////////////////
-// CertIdMap
-
-class CertIdMap {
- public:
- CertIdMap() {}
- ~CertIdMap() {}
-
- std::string CertToId(net::X509Certificate* cert);
- net::X509Certificate* IdToCert(const std::string& id);
- net::X509Certificate* CallbackArgsToCert(const base::ListValue* args);
-
- private:
- typedef std::map<net::X509Certificate*, int32_t> CertMap;
-
- // Creates an ID for cert and looks up the cert for an ID.
- IDMap<net::X509Certificate*> id_map_;
-
- // Finds the ID for a cert.
- CertMap cert_map_;
-
- DISALLOW_COPY_AND_ASSIGN(CertIdMap);
-};
-
-std::string CertIdMap::CertToId(net::X509Certificate* cert) {
- CertMap::const_iterator iter = cert_map_.find(cert);
- if (iter != cert_map_.end())
- return base::IntToString(iter->second);
-
- int32_t new_id = id_map_.Add(cert);
- cert_map_[cert] = new_id;
- return base::IntToString(new_id);
-}
-
-net::X509Certificate* CertIdMap::IdToCert(const std::string& id) {
- int32_t cert_id = 0;
- if (!base::StringToInt(id, &cert_id))
- return NULL;
-
- return id_map_.Lookup(cert_id);
-}
-
-net::X509Certificate* CertIdMap::CallbackArgsToCert(
- const base::ListValue* args) {
- std::string node_id;
- if (!args->GetString(0, &node_id))
- return NULL;
-
- net::X509Certificate* cert = IdToCert(node_id);
- if (!cert) {
- NOTREACHED();
- return NULL;
- }
-
- return cert;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// FileAccessProvider
-
-// TODO(mattm): Move to some shared location?
-class FileAccessProvider
- : public base::RefCountedThreadSafe<FileAccessProvider> {
- public:
- // The first parameter is 0 on success or errno on failure. The second
- // parameter is read result.
- typedef base::Callback<void(const int*, const std::string*)> ReadCallback;
-
- // The first parameter is 0 on success or errno on failure. The second
- // parameter is the number of bytes written on success.
- typedef base::Callback<void(const int*, const int*)> WriteCallback;
-
- base::CancelableTaskTracker::TaskId StartRead(
- const base::FilePath& path,
- const ReadCallback& callback,
- base::CancelableTaskTracker* tracker);
- base::CancelableTaskTracker::TaskId StartWrite(
- const base::FilePath& path,
- const std::string& data,
- const WriteCallback& callback,
- base::CancelableTaskTracker* tracker);
-
- private:
- friend class base::RefCountedThreadSafe<FileAccessProvider>;
- virtual ~FileAccessProvider() {}
-
- // Reads file at |path|. |saved_errno| is 0 on success or errno on failure.
- // When success, |data| has file content.
- void DoRead(const base::FilePath& path,
- int* saved_errno,
- std::string* data);
- // Writes data to file at |path|. |saved_errno| is 0 on success or errno on
- // failure. When success, |bytes_written| has number of bytes written.
- void DoWrite(const base::FilePath& path,
- const std::string& data,
- int* saved_errno,
- int* bytes_written);
-};
-
-base::CancelableTaskTracker::TaskId FileAccessProvider::StartRead(
- const base::FilePath& path,
- const ReadCallback& callback,
- base::CancelableTaskTracker* tracker) {
- // Owned by reply callback posted below.
- int* saved_errno = new int(0);
- std::string* data = new std::string();
-
- // Post task to file thread to read file.
- return tracker->PostTaskAndReply(
- BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get(),
- FROM_HERE,
- base::Bind(&FileAccessProvider::DoRead, this, path, saved_errno, data),
- base::Bind(callback, base::Owned(saved_errno), base::Owned(data)));
-}
-
-base::CancelableTaskTracker::TaskId FileAccessProvider::StartWrite(
- const base::FilePath& path,
- const std::string& data,
- const WriteCallback& callback,
- base::CancelableTaskTracker* tracker) {
- // Owned by reply callback posted below.
- int* saved_errno = new int(0);
- int* bytes_written = new int(0);
-
- // Post task to file thread to write file.
- return tracker->PostTaskAndReply(
- BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get(),
- FROM_HERE, base::Bind(&FileAccessProvider::DoWrite, this, path, data,
- saved_errno, bytes_written),
- base::Bind(callback, base::Owned(saved_errno),
- base::Owned(bytes_written)));
-}
-
-void FileAccessProvider::DoRead(const base::FilePath& path,
- int* saved_errno,
- std::string* data) {
- bool success = base::ReadFileToString(path, data);
- *saved_errno = success ? 0 : errno;
-}
-
-void FileAccessProvider::DoWrite(const base::FilePath& path,
- const std::string& data,
- int* saved_errno,
- int* bytes_written) {
- *bytes_written = base::WriteFile(path, data.data(), data.size());
- *saved_errno = *bytes_written >= 0 ? 0 : errno;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// CertificateManagerHandler
-
-CertificateManagerHandler::CertificateManagerHandler(
- bool show_certs_in_modal_dialog)
- : show_certs_in_modal_dialog_(show_certs_in_modal_dialog),
- requested_certificate_manager_model_(false),
- use_hardware_backed_(false),
- file_access_provider_(new FileAccessProvider()),
- cert_id_map_(new CertIdMap),
- weak_ptr_factory_(this) {}
-
-CertificateManagerHandler::~CertificateManagerHandler() {
-}
-
-void CertificateManagerHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- RegisterTitle(localized_strings, "certificateManagerPage",
- IDS_CERTIFICATE_MANAGER_TITLE);
-
- // Tabs.
- localized_strings->SetString("personalCertsTabTitle",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_PERSONAL_CERTS_TAB_LABEL));
- localized_strings->SetString("serverCertsTabTitle",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_SERVER_CERTS_TAB_LABEL));
- localized_strings->SetString("caCertsTabTitle",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_CERT_AUTHORITIES_TAB_LABEL));
- localized_strings->SetString("otherCertsTabTitle",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_OTHER_TAB_LABEL));
-
- // Tab descriptions.
- localized_strings->SetString("personalCertsTabDescription",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_USER_TREE_DESCRIPTION));
- localized_strings->SetString("serverCertsTabDescription",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_SERVER_TREE_DESCRIPTION));
- localized_strings->SetString("caCertsTabDescription",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_AUTHORITIES_TREE_DESCRIPTION));
- localized_strings->SetString("otherCertsTabDescription",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_OTHER_TREE_DESCRIPTION));
-
- // Buttons.
- localized_strings->SetString("view_certificate",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_VIEW_CERT_BUTTON));
- localized_strings->SetString("import_certificate",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_IMPORT_BUTTON));
- localized_strings->SetString("export_certificate",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EXPORT_BUTTON));
- localized_strings->SetString("edit_certificate",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EDIT_BUTTON));
- localized_strings->SetString("delete_certificate",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_BUTTON));
-
- // Certificate Delete overlay strings.
- localized_strings->SetString("personalCertsTabDeleteConfirm",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_USER_FORMAT));
- localized_strings->SetString("personalCertsTabDeleteImpact",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_USER_DESCRIPTION));
- localized_strings->SetString("serverCertsTabDeleteConfirm",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_SERVER_FORMAT));
- localized_strings->SetString("serverCertsTabDeleteImpact",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_SERVER_DESCRIPTION));
- localized_strings->SetString("caCertsTabDeleteConfirm",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_CA_FORMAT));
- localized_strings->SetString("caCertsTabDeleteImpact",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_CA_DESCRIPTION));
- localized_strings->SetString("otherCertsTabDeleteConfirm",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_DELETE_OTHER_FORMAT));
- localized_strings->SetString("otherCertsTabDeleteImpact", std::string());
-
- // Certificate Restore overlay strings.
- localized_strings->SetString("certificateRestorePasswordDescription",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_RESTORE_PASSWORD_DESC));
- localized_strings->SetString("certificatePasswordLabel",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_PASSWORD_LABEL));
-
- // Personal Certificate Export overlay strings.
- localized_strings->SetString("certificateExportPasswordDescription",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EXPORT_PASSWORD_DESC));
- localized_strings->SetString("certificateExportPasswordHelp",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EXPORT_PASSWORD_HELP));
- localized_strings->SetString("certificateConfirmPasswordLabel",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_CONFIRM_PASSWORD_LABEL));
-
- // Edit CA Trust & Import CA overlay strings.
- localized_strings->SetString("certificateEditCaTitle",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EDIT_CA_TITLE));
- localized_strings->SetString("certificateEditTrustLabel",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EDIT_TRUST_LABEL));
- localized_strings->SetString("certificateEditCaTrustDescriptionFormat",
- l10n_util::GetStringUTF16(
- IDS_CERT_MANAGER_EDIT_CA_TRUST_DESCRIPTION_FORMAT));
- localized_strings->SetString("certificateImportCaDescriptionFormat",
- l10n_util::GetStringUTF16(
- IDS_CERT_MANAGER_IMPORT_CA_DESCRIPTION_FORMAT));
- localized_strings->SetString("certificateCaTrustSSLLabel",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EDIT_CA_TRUST_SSL_LABEL));
- localized_strings->SetString("certificateCaTrustEmailLabel",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EDIT_CA_TRUST_EMAIL_LABEL));
- localized_strings->SetString("certificateCaTrustObjSignLabel",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_EDIT_CA_TRUST_OBJSIGN_LABEL));
- localized_strings->SetString("certificateImportErrorFormat",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_IMPORT_ERROR_FORMAT));
-
- // Badges next to certificates
- localized_strings->SetString("badgeCertUntrusted",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_UNTRUSTED));
- localized_strings->SetString("certPolicyInstalled",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_POLICY_INSTALLED));
-
-#if defined(OS_CHROMEOS)
- localized_strings->SetString("importAndBindCertificate",
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_IMPORT_AND_BIND_BUTTON));
-#endif // defined(OS_CHROMEOS)
-}
-
-void CertificateManagerHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "viewCertificate",
- base::Bind(&CertificateManagerHandler::View, base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "getCaCertificateTrust",
- base::Bind(&CertificateManagerHandler::GetCATrust,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "editCaCertificateTrust",
- base::Bind(&CertificateManagerHandler::EditCATrust,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "editServerCertificate",
- base::Bind(&CertificateManagerHandler::EditServer,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "cancelImportExportCertificate",
- base::Bind(&CertificateManagerHandler::CancelImportExportProcess,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "exportPersonalCertificate",
- base::Bind(&CertificateManagerHandler::ExportPersonal,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "exportAllPersonalCertificates",
- base::Bind(&CertificateManagerHandler::ExportAllPersonal,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "exportPersonalCertificatePasswordSelected",
- base::Bind(&CertificateManagerHandler::ExportPersonalPasswordSelected,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "importPersonalCertificate",
- base::Bind(&CertificateManagerHandler::StartImportPersonal,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "importPersonalCertificatePasswordSelected",
- base::Bind(&CertificateManagerHandler::ImportPersonalPasswordSelected,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "importCaCertificate",
- base::Bind(&CertificateManagerHandler::ImportCA,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "importCaCertificateTrustSelected",
- base::Bind(&CertificateManagerHandler::ImportCATrustSelected,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "importServerCertificate",
- base::Bind(&CertificateManagerHandler::ImportServer,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "exportCertificate",
- base::Bind(&CertificateManagerHandler::Export,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "deleteCertificate",
- base::Bind(&CertificateManagerHandler::Delete,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback(
- "populateCertificateManager",
- base::Bind(&CertificateManagerHandler::Populate,
- base::Unretained(this)));
-}
-
-void CertificateManagerHandler::CertificatesRefreshed() {
- net::CertificateList web_trusted_certs;
-#if defined(OS_CHROMEOS)
- policy::UserNetworkConfigurationUpdater* service =
- policy::UserNetworkConfigurationUpdaterFactory::GetForProfile(
- Profile::FromWebUI(web_ui()));
- if (service)
- service->GetWebTrustedCertificates(&web_trusted_certs);
-#endif
- PopulateTree("personalCertsTab", net::USER_CERT, web_trusted_certs);
- PopulateTree("serverCertsTab", net::SERVER_CERT, web_trusted_certs);
- PopulateTree("caCertsTab", net::CA_CERT, web_trusted_certs);
- PopulateTree("otherCertsTab", net::OTHER_CERT, web_trusted_certs);
-}
-
-void CertificateManagerHandler::FileSelected(const base::FilePath& path,
- int index,
- void* params) {
- switch (reinterpret_cast<intptr_t>(params)) {
- case EXPORT_PERSONAL_FILE_SELECTED:
- ExportPersonalFileSelected(path);
- break;
- case IMPORT_PERSONAL_FILE_SELECTED:
- ImportPersonalFileSelected(path);
- break;
- case IMPORT_SERVER_FILE_SELECTED:
- ImportServerFileSelected(path);
- break;
- case IMPORT_CA_FILE_SELECTED:
- ImportCAFileSelected(path);
- break;
- default:
- NOTREACHED();
- }
-}
-
-void CertificateManagerHandler::FileSelectionCanceled(void* params) {
- switch (reinterpret_cast<intptr_t>(params)) {
- case EXPORT_PERSONAL_FILE_SELECTED:
- case IMPORT_PERSONAL_FILE_SELECTED:
- case IMPORT_SERVER_FILE_SELECTED:
- case IMPORT_CA_FILE_SELECTED:
- ImportExportCleanup();
- break;
- default:
- NOTREACHED();
- }
-}
-
-void CertificateManagerHandler::View(const base::ListValue* args) {
- net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
- if (!cert)
- return;
-#if defined(OS_CHROMEOS)
- if (show_certs_in_modal_dialog_) {
- ShowCertificateViewerModalDialog(web_ui()->GetWebContents(),
- GetParentWindow(),
- cert);
- return;
- }
-#endif
- ShowCertificateViewer(web_ui()->GetWebContents(), GetParentWindow(), cert);
-}
-
-void CertificateManagerHandler::GetCATrust(const base::ListValue* args) {
- net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
- if (!cert) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.dismiss");
- return;
- }
-
- net::NSSCertDatabase::TrustBits trust_bits =
- certificate_manager_model_->cert_db()->GetCertTrust(cert, net::CA_CERT);
- base::Value ssl_value(
- static_cast<bool>(trust_bits & net::NSSCertDatabase::TRUSTED_SSL));
- base::Value email_value(
- static_cast<bool>(trust_bits & net::NSSCertDatabase::TRUSTED_EMAIL));
- base::Value obj_sign_value(
- static_cast<bool>(trust_bits & net::NSSCertDatabase::TRUSTED_OBJ_SIGN));
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.populateTrust", ssl_value, email_value,
- obj_sign_value);
-}
-
-void CertificateManagerHandler::EditCATrust(const base::ListValue* args) {
- net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
- bool fail = !cert;
- bool trust_ssl = false;
- bool trust_email = false;
- bool trust_obj_sign = false;
- fail |= !CallbackArgsToBool(args, 1, &trust_ssl);
- fail |= !CallbackArgsToBool(args, 2, &trust_email);
- fail |= !CallbackArgsToBool(args, 3, &trust_obj_sign);
- if (fail) {
- LOG(ERROR) << "EditCATrust args fail";
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.dismiss");
- return;
- }
-
- bool result = certificate_manager_model_->SetCertTrust(
- cert,
- net::CA_CERT,
- trust_ssl * net::NSSCertDatabase::TRUSTED_SSL +
- trust_email * net::NSSCertDatabase::TRUSTED_EMAIL +
- trust_obj_sign * net::NSSCertDatabase::TRUSTED_OBJ_SIGN);
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.dismiss");
- if (!result) {
- // TODO(mattm): better error messages?
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_SET_TRUST_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_UNKNOWN_ERROR));
- }
-}
-
-void CertificateManagerHandler::EditServer(const base::ListValue* args) {
- NOTIMPLEMENTED();
-}
-
-void CertificateManagerHandler::ExportPersonal(const base::ListValue* args) {
- net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
- if (!cert)
- return;
-
- selected_cert_list_.push_back(cert);
-
- ui::SelectFileDialog::FileTypeInfo file_type_info;
- file_type_info.extensions.resize(1);
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("p12"));
- file_type_info.extension_description_overrides.push_back(
- l10n_util::GetStringUTF16(IDS_CERT_MANAGER_PKCS12_FILES));
- file_type_info.include_all_files = true;
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- select_file_dialog_->SelectFile(
- ui::SelectFileDialog::SELECT_SAVEAS_FILE, base::string16(),
- base::FilePath(), &file_type_info, 1, FILE_PATH_LITERAL("p12"),
- GetParentWindow(),
- reinterpret_cast<void*>(EXPORT_PERSONAL_FILE_SELECTED));
-}
-
-void CertificateManagerHandler::ExportAllPersonal(const base::ListValue* args) {
- NOTIMPLEMENTED();
-}
-
-void CertificateManagerHandler::ExportPersonalFileSelected(
- const base::FilePath& path) {
- file_path_ = path;
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateManager.exportPersonalAskPassword");
-}
-
-void CertificateManagerHandler::ExportPersonalPasswordSelected(
- const base::ListValue* args) {
- if (!args->GetString(0, &password_)) {
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- ImportExportCleanup();
- return;
- }
-
- // Currently, we don't support exporting more than one at a time. If we do,
- // this would need to either change this to use UnlockSlotsIfNecessary or
- // change UnlockCertSlotIfNecessary to take a CertificateList.
- DCHECK_EQ(selected_cert_list_.size(), 1U);
-
- // TODO(mattm): do something smarter about non-extractable keys
- chrome::UnlockCertSlotIfNecessary(
- selected_cert_list_[0].get(),
- chrome::kCryptoModulePasswordCertExport,
- net::HostPortPair(), // unused.
- GetParentWindow(),
- base::Bind(&CertificateManagerHandler::ExportPersonalSlotsUnlocked,
- base::Unretained(this)));
-}
-
-void CertificateManagerHandler::ExportPersonalSlotsUnlocked() {
- std::string output;
- int num_exported = certificate_manager_model_->cert_db()->ExportToPKCS12(
- selected_cert_list_,
- password_,
- &output);
- if (!num_exported) {
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_PKCS12_EXPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_UNKNOWN_ERROR));
- ImportExportCleanup();
- return;
- }
- file_access_provider_->StartWrite(
- file_path_,
- output,
- base::Bind(&CertificateManagerHandler::ExportPersonalFileWritten,
- base::Unretained(this)),
- &tracker_);
-}
-
-void CertificateManagerHandler::ExportPersonalFileWritten(
- const int* write_errno, const int* bytes_written) {
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- ImportExportCleanup();
- if (*write_errno) {
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_PKCS12_EXPORT_ERROR_TITLE),
- l10n_util::GetStringFUTF8(IDS_CERT_MANAGER_WRITE_ERROR_FORMAT,
- UTF8ToUTF16(
- base::safe_strerror(*write_errno))));
- }
-}
-
-void CertificateManagerHandler::StartImportPersonal(
- const base::ListValue* args) {
- ui::SelectFileDialog::FileTypeInfo file_type_info;
- if (!args->GetBoolean(0, &use_hardware_backed_)) {
- // Unable to retrieve the hardware backed attribute from the args,
- // so bail.
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- ImportExportCleanup();
- return;
- }
- file_type_info.extensions.resize(1);
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("p12"));
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("pfx"));
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("crt"));
- file_type_info.extension_description_overrides.push_back(
- l10n_util::GetStringUTF16(IDS_CERT_USAGE_SSL_CLIENT));
- file_type_info.include_all_files = true;
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- select_file_dialog_->SelectFile(
- ui::SelectFileDialog::SELECT_OPEN_FILE, base::string16(),
- base::FilePath(), &file_type_info, 1, FILE_PATH_LITERAL("p12"),
- GetParentWindow(),
- reinterpret_cast<void*>(IMPORT_PERSONAL_FILE_SELECTED));
-}
-
-void CertificateManagerHandler::ImportPersonalFileSelected(
- const base::FilePath& path) {
- file_access_provider_->StartRead(
- path, base::Bind(&CertificateManagerHandler::ImportPersonalFileRead,
- base::Unretained(this)),
- &tracker_);
-}
-
-void CertificateManagerHandler::ImportPersonalFileRead(
- const int* read_errno, const std::string* data) {
- if (*read_errno) {
- ImportExportCleanup();
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_IMPORT_ERROR_TITLE),
- l10n_util::GetStringFUTF8(IDS_CERT_MANAGER_READ_ERROR_FORMAT,
- UTF8ToUTF16(
- base::safe_strerror(*read_errno))));
- return;
- }
-
- file_data_ = *data;
-
- if (CouldBePFX(file_data_)) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateManager.importPersonalAskPassword");
- return;
- }
-
- // Non .p12/.pfx files are assumed to be single/chain certificates without
- // private key data. The default extension according to spec is '.crt',
- // however other extensions are also used in some places to represent these
- // certificates.
- int result = certificate_manager_model_->ImportUserCert(file_data_);
- ImportExportCleanup();
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- int string_id;
- switch (result) {
- case net::OK:
- return;
- case net::ERR_NO_PRIVATE_KEY_FOR_CERT:
- string_id = IDS_CERT_MANAGER_IMPORT_MISSING_KEY;
- break;
- case net::ERR_CERT_INVALID:
- string_id = IDS_CERT_MANAGER_IMPORT_INVALID_FILE;
- break;
- default:
- string_id = IDS_CERT_MANAGER_UNKNOWN_ERROR;
- break;
- }
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_IMPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(string_id));
-}
-
-void CertificateManagerHandler::ImportPersonalPasswordSelected(
- const base::ListValue* args) {
- if (!args->GetString(0, &password_)) {
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- ImportExportCleanup();
- return;
- }
-
- if (use_hardware_backed_) {
- slot_ = certificate_manager_model_->cert_db()->GetPrivateSlot();
- } else {
- slot_ = certificate_manager_model_->cert_db()->GetPublicSlot();
- }
-
- std::vector<crypto::ScopedPK11Slot> modules;
- modules.push_back(crypto::ScopedPK11Slot(PK11_ReferenceSlot(slot_.get())));
- chrome::UnlockSlotsIfNecessary(
- std::move(modules), chrome::kCryptoModulePasswordCertImport,
- net::HostPortPair(), // unused.
- GetParentWindow(),
- base::Bind(&CertificateManagerHandler::ImportPersonalSlotUnlocked,
- base::Unretained(this)));
-}
-
-void CertificateManagerHandler::ImportPersonalSlotUnlocked() {
- // Determine if the private key should be unextractable after the import.
- // We do this by checking the value of |use_hardware_backed_| which is set
- // to true if importing into a hardware module. Currently, this only happens
- // for Chrome OS when the "Import and Bind" option is chosen.
- bool is_extractable = !use_hardware_backed_;
- int result = certificate_manager_model_->ImportFromPKCS12(
- slot_.get(), file_data_, password_, is_extractable);
- ImportExportCleanup();
- web_ui()->CallJavascriptFunctionUnsafe("CertificateRestoreOverlay.dismiss");
- int string_id;
- switch (result) {
- case net::OK:
- return;
- case net::ERR_PKCS12_IMPORT_BAD_PASSWORD:
- // TODO(mattm): if the error was a bad password, we should reshow the
- // password dialog after the user dismisses the error dialog.
- string_id = IDS_CERT_MANAGER_BAD_PASSWORD;
- break;
- case net::ERR_PKCS12_IMPORT_INVALID_MAC:
- string_id = IDS_CERT_MANAGER_IMPORT_INVALID_MAC;
- break;
- case net::ERR_PKCS12_IMPORT_INVALID_FILE:
- string_id = IDS_CERT_MANAGER_IMPORT_INVALID_FILE;
- break;
- case net::ERR_PKCS12_IMPORT_UNSUPPORTED:
- string_id = IDS_CERT_MANAGER_IMPORT_UNSUPPORTED;
- break;
- default:
- string_id = IDS_CERT_MANAGER_UNKNOWN_ERROR;
- break;
- }
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_IMPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(string_id));
-}
-
-void CertificateManagerHandler::CancelImportExportProcess(
- const base::ListValue* args) {
- ImportExportCleanup();
-}
-
-void CertificateManagerHandler::ImportExportCleanup() {
- file_path_.clear();
- password_.clear();
- file_data_.clear();
- use_hardware_backed_ = false;
- selected_cert_list_.clear();
- slot_.reset();
- tracker_.TryCancelAll();
-
- // There may be pending file dialogs, we need to tell them that we've gone
- // away so they don't try and call back to us.
- if (select_file_dialog_.get())
- select_file_dialog_->ListenerDestroyed();
- select_file_dialog_ = NULL;
-}
-
-void CertificateManagerHandler::ImportServer(const base::ListValue* args) {
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- ShowCertSelectFileDialog(
- select_file_dialog_.get(),
- ui::SelectFileDialog::SELECT_OPEN_FILE,
- base::FilePath(),
- GetParentWindow(),
- reinterpret_cast<void*>(IMPORT_SERVER_FILE_SELECTED));
-}
-
-void CertificateManagerHandler::ImportServerFileSelected(
- const base::FilePath& path) {
- file_access_provider_->StartRead(
- path, base::Bind(&CertificateManagerHandler::ImportServerFileRead,
- base::Unretained(this)),
- &tracker_);
-}
-
-void CertificateManagerHandler::ImportServerFileRead(const int* read_errno,
- const std::string* data) {
- if (*read_errno) {
- ImportExportCleanup();
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_SERVER_IMPORT_ERROR_TITLE),
- l10n_util::GetStringFUTF8(IDS_CERT_MANAGER_READ_ERROR_FORMAT,
- UTF8ToUTF16(
- base::safe_strerror(*read_errno))));
- return;
- }
-
- selected_cert_list_ = net::X509Certificate::CreateCertificateListFromBytes(
- data->data(), data->size(), net::X509Certificate::FORMAT_AUTO);
- if (selected_cert_list_.empty()) {
- ImportExportCleanup();
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_SERVER_IMPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_CERT_PARSE_ERROR));
- return;
- }
-
- net::NSSCertDatabase::ImportCertFailureList not_imported;
- // TODO(mattm): Add UI for trust. http://crbug.com/76274
- bool result = certificate_manager_model_->ImportServerCert(
- selected_cert_list_,
- net::NSSCertDatabase::TRUST_DEFAULT,
- &not_imported);
- if (!result) {
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_SERVER_IMPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_UNKNOWN_ERROR));
- } else if (!not_imported.empty()) {
- ShowImportErrors(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_SERVER_IMPORT_ERROR_TITLE),
- not_imported);
- }
- ImportExportCleanup();
-}
-
-void CertificateManagerHandler::ImportCA(const base::ListValue* args) {
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- ShowCertSelectFileDialog(select_file_dialog_.get(),
- ui::SelectFileDialog::SELECT_OPEN_FILE,
- base::FilePath(),
- GetParentWindow(),
- reinterpret_cast<void*>(IMPORT_CA_FILE_SELECTED));
-}
-
-void CertificateManagerHandler::ImportCAFileSelected(
- const base::FilePath& path) {
- file_access_provider_->StartRead(
- path, base::Bind(&CertificateManagerHandler::ImportCAFileRead,
- base::Unretained(this)),
- &tracker_);
-}
-
-void CertificateManagerHandler::ImportCAFileRead(const int* read_errno,
- const std::string* data) {
- if (*read_errno) {
- ImportExportCleanup();
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_CA_IMPORT_ERROR_TITLE),
- l10n_util::GetStringFUTF8(IDS_CERT_MANAGER_READ_ERROR_FORMAT,
- UTF8ToUTF16(
- base::safe_strerror(*read_errno))));
- return;
- }
-
- selected_cert_list_ = net::X509Certificate::CreateCertificateListFromBytes(
- data->data(), data->size(), net::X509Certificate::FORMAT_AUTO);
- if (selected_cert_list_.empty()) {
- ImportExportCleanup();
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_CA_IMPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_CERT_PARSE_ERROR));
- return;
- }
-
- scoped_refptr<net::X509Certificate> root_cert =
- certificate_manager_model_->cert_db()->FindRootInList(
- selected_cert_list_);
-
- // TODO(mattm): check here if root_cert is not a CA cert and show error.
-
- base::Value cert_name(root_cert->subject().GetDisplayName());
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.showImport", cert_name);
-}
-
-void CertificateManagerHandler::ImportCATrustSelected(
- const base::ListValue* args) {
- bool fail = false;
- bool trust_ssl = false;
- bool trust_email = false;
- bool trust_obj_sign = false;
- fail |= !CallbackArgsToBool(args, 0, &trust_ssl);
- fail |= !CallbackArgsToBool(args, 1, &trust_email);
- fail |= !CallbackArgsToBool(args, 2, &trust_obj_sign);
- if (fail) {
- LOG(ERROR) << "ImportCATrustSelected args fail";
- ImportExportCleanup();
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.dismiss");
- return;
- }
-
- // TODO(mattm): add UI for setting explicit distrust, too.
- // http://crbug.com/128411
- net::NSSCertDatabase::ImportCertFailureList not_imported;
- bool result = certificate_manager_model_->ImportCACerts(
- selected_cert_list_,
- trust_ssl * net::NSSCertDatabase::TRUSTED_SSL +
- trust_email * net::NSSCertDatabase::TRUSTED_EMAIL +
- trust_obj_sign * net::NSSCertDatabase::TRUSTED_OBJ_SIGN,
- &not_imported);
- web_ui()->CallJavascriptFunctionUnsafe(
- "CertificateEditCaTrustOverlay.dismiss");
- if (!result) {
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_CA_IMPORT_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_UNKNOWN_ERROR));
- } else if (!not_imported.empty()) {
- ShowImportErrors(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_CA_IMPORT_ERROR_TITLE),
- not_imported);
- }
- ImportExportCleanup();
-}
-
-void CertificateManagerHandler::Export(const base::ListValue* args) {
- net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
- if (!cert)
- return;
- ShowCertExportDialog(web_ui()->GetWebContents(), GetParentWindow(), cert);
-}
-
-void CertificateManagerHandler::Delete(const base::ListValue* args) {
- net::X509Certificate* cert = cert_id_map_->CallbackArgsToCert(args);
- if (!cert)
- return;
- bool result = certificate_manager_model_->Delete(cert);
- if (!result) {
- // TODO(mattm): better error messages?
- ShowError(
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_DELETE_CERT_ERROR_TITLE),
- l10n_util::GetStringUTF8(IDS_CERT_MANAGER_UNKNOWN_ERROR));
- }
-}
-
-void CertificateManagerHandler::OnCertificateManagerModelCreated(
- std::unique_ptr<CertificateManagerModel> model) {
- certificate_manager_model_ = std::move(model);
- CertificateManagerModelReady();
-}
-
-void CertificateManagerHandler::CertificateManagerModelReady() {
- base::Value user_db_available_value(
- certificate_manager_model_->is_user_db_available());
- base::Value tpm_available_value(
- certificate_manager_model_->is_tpm_available());
- web_ui()->CallJavascriptFunctionUnsafe("CertificateManager.onModelReady",
- user_db_available_value,
- tpm_available_value);
- certificate_manager_model_->Refresh();
-}
-
-void CertificateManagerHandler::Populate(const base::ListValue* args) {
- if (certificate_manager_model_) {
- // Already have a model, the webui must be re-loading. Just re-run the
- // webui initialization.
- CertificateManagerModelReady();
- return;
- }
-
- if (!requested_certificate_manager_model_) {
- // Request that a model be created.
- CertificateManagerModel::Create(
- Profile::FromWebUI(web_ui()),
- this,
- base::Bind(&CertificateManagerHandler::OnCertificateManagerModelCreated,
- weak_ptr_factory_.GetWeakPtr()));
- requested_certificate_manager_model_ = true;
- return;
- }
-
- // We are already waiting for a CertificateManagerModel to be created, no need
- // to do anything.
-}
-
-void CertificateManagerHandler::PopulateTree(
- const std::string& tab_name,
- net::CertType type,
- const net::CertificateList& web_trust_certs) {
- const std::string tree_name = tab_name + "-tree";
-
- std::unique_ptr<icu::Collator> collator;
- UErrorCode error = U_ZERO_ERROR;
- collator.reset(
- icu::Collator::createInstance(
- icu::Locale(g_browser_process->GetApplicationLocale().c_str()),
- error));
- if (U_FAILURE(error))
- collator.reset(NULL);
- DictionaryIdComparator comparator(collator.get());
- CertificateManagerModel::OrgGroupingMap map;
-
- certificate_manager_model_->FilterAndBuildOrgGroupingMap(type, &map);
-
- {
- std::unique_ptr<base::ListValue> nodes(new base::ListValue);
- for (CertificateManagerModel::OrgGroupingMap::iterator i = map.begin();
- i != map.end(); ++i) {
- // Populate first level (org name).
- std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
- dict->SetString(kKeyId, OrgNameToId(i->first));
- dict->SetString(kNameId, i->first);
-
- // Populate second level (certs).
- auto subnodes = base::MakeUnique<base::ListValue>();
- for (net::CertificateList::const_iterator org_cert_it = i->second.begin();
- org_cert_it != i->second.end(); ++org_cert_it) {
- std::unique_ptr<base::DictionaryValue> cert_dict(
- new base::DictionaryValue);
- net::X509Certificate* cert = org_cert_it->get();
- cert_dict->SetString(kKeyId, cert_id_map_->CertToId(cert));
- cert_dict->SetString(kNameId, certificate_manager_model_->GetColumnText(
- *cert, CertificateManagerModel::COL_SUBJECT_NAME));
- cert_dict->SetBoolean(
- kReadOnlyId,
- certificate_manager_model_->cert_db()->IsReadOnly(cert));
- // Policy-installed certificates with web trust are trusted.
- bool policy_trusted =
- IsPolicyInstalledWithWebTrust(web_trust_certs, cert);
- cert_dict->SetBoolean(
- kUntrustedId,
- !policy_trusted &&
- certificate_manager_model_->cert_db()->IsUntrusted(cert));
- cert_dict->SetBoolean(kPolicyTrustedId, policy_trusted);
- // TODO(hshi): This should be determined by testing for PKCS #11
- // CKA_EXTRACTABLE attribute. We may need to use the NSS function
- // PK11_ReadRawAttribute to do that.
- cert_dict->SetBoolean(
- kExtractableId,
- !certificate_manager_model_->IsHardwareBacked(cert));
- // TODO(mattm): Other columns.
- subnodes->Append(std::move(cert_dict));
- }
- std::sort(subnodes->begin(), subnodes->end(), comparator);
-
- dict->Set(kSubNodesId, std::move(subnodes));
- nodes->Append(std::move(dict));
- }
- std::sort(nodes->begin(), nodes->end(), comparator);
-
- base::ListValue args;
- args.AppendString(tree_name);
- args.Append(std::move(nodes));
- web_ui()->CallJavascriptFunctionUnsafe("CertificateManager.onPopulateTree",
- args);
- }
-}
-
-void CertificateManagerHandler::ShowError(const std::string& title,
- const std::string& error) const {
- auto title_value = base::MakeUnique<base::Value>(title);
- auto error_value = base::MakeUnique<base::Value>(error);
- auto ok_title_value =
- base::MakeUnique<base::Value>(l10n_util::GetStringUTF8(IDS_OK));
- auto cancel_title_value = base::MakeUnique<base::Value>();
- auto ok_callback_value = base::MakeUnique<base::Value>();
- auto cancel_callback_value = base::MakeUnique<base::Value>();
- std::vector<const base::Value*> args = {
- title_value.get(), error_value.get(),
- ok_title_value.get(), cancel_title_value.get(),
- ok_callback_value.get(), cancel_callback_value.get()};
- web_ui()->CallJavascriptFunctionUnsafe("AlertOverlay.show", args);
-}
-
-void CertificateManagerHandler::ShowImportErrors(
- const std::string& title,
- const net::NSSCertDatabase::ImportCertFailureList& not_imported) const {
- std::string error;
- if (selected_cert_list_.size() == 1)
- error = l10n_util::GetStringUTF8(
- IDS_CERT_MANAGER_IMPORT_SINGLE_NOT_IMPORTED);
- else if (not_imported.size() == selected_cert_list_.size())
- error = l10n_util::GetStringUTF8(IDS_CERT_MANAGER_IMPORT_ALL_NOT_IMPORTED);
- else
- error = l10n_util::GetStringUTF8(IDS_CERT_MANAGER_IMPORT_SOME_NOT_IMPORTED);
-
- base::ListValue cert_error_list;
- for (size_t i = 0; i < not_imported.size(); ++i) {
- const net::NSSCertDatabase::ImportCertFailure& failure = not_imported[i];
- std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
- dict->SetString(kNameId, failure.certificate->subject().GetDisplayName());
- dict->SetString(kErrorId, NetErrorToString(failure.net_error));
- cert_error_list.Append(std::move(dict));
- }
-
- base::Value title_value(title);
- base::Value error_value(error);
- web_ui()->CallJavascriptFunctionUnsafe("CertificateImportErrorOverlay.show",
- title_value, error_value,
- cert_error_list);
-}
-
-gfx::NativeWindow CertificateManagerHandler::GetParentWindow() const {
- return web_ui()->GetWebContents()->GetTopLevelNativeWindow();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/certificate_manager_handler.h b/chromium/chrome/browser/ui/webui/options/certificate_manager_handler.h
deleted file mode 100644
index 392790bc1ba..00000000000
--- a/chromium/chrome/browser/ui/webui/options/certificate_manager_handler.h
+++ /dev/null
@@ -1,194 +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_OPTIONS_CERTIFICATE_MANAGER_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CERTIFICATE_MANAGER_HANDLER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/task/cancelable_task_tracker.h"
-#include "chrome/browser/certificate_manager_model.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "net/cert/nss_cert_database.h"
-#include "ui/gfx/native_widget_types.h"
-#include "ui/shell_dialogs/select_file_dialog.h"
-
-namespace options {
-
-class CertIdMap;
-class FileAccessProvider;
-
-class CertificateManagerHandler
- : public OptionsPageUIHandler,
- public CertificateManagerModel::Observer,
- public ui::SelectFileDialog::Listener {
- public:
- explicit CertificateManagerHandler(bool show_certs_in_modal_dialog);
- ~CertificateManagerHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void RegisterMessages() override;
-
- // CertificateManagerModel::Observer implementation.
- void CertificatesRefreshed() override;
-
- // SelectFileDialog::Listener implementation.
- void FileSelected(const base::FilePath& path,
- int index,
- void* params) override;
- void FileSelectionCanceled(void* params) override;
-
- private:
- // View certificate.
- void View(const base::ListValue* args);
-
- // Edit server certificate trust values.
- void EditServer(const base::ListValue* args);
-
- // Edit certificate authority trust values. The sequence goes like:
- // 1. user clicks edit button -> CertificateEditCaTrustOverlay.show ->
- // GetCATrust -> CertificateEditCaTrustOverlay.populateTrust
- // 2. user clicks ok -> EditCATrust -> CertificateEditCaTrustOverlay.dismiss
- void GetCATrust(const base::ListValue* args);
- void EditCATrust(const base::ListValue* args);
-
- // Cleanup state stored during import or export process.
- void CancelImportExportProcess(const base::ListValue* args);
- void ImportExportCleanup();
-
- // Export to PKCS #12 file. The sequence goes like:
- // 1a. user click on export button -> ExportPersonal -> launches file
- // selector
- // 1b. user click on export all button -> ExportAllPersonal -> launches file
- // selector
- // 2. user selects file -> ExportPersonalFileSelected -> launches password
- // dialog
- // 3. user enters password -> ExportPersonalPasswordSelected -> unlock slots
- // 4. slots unlocked -> ExportPersonalSlotsUnlocked -> exports to memory
- // buffer -> starts async write operation
- // 5. write finishes (or fails) -> ExportPersonalFileWritten
- void ExportPersonal(const base::ListValue* args);
- void ExportAllPersonal(const base::ListValue* args);
- void ExportPersonalFileSelected(const base::FilePath& path);
- void ExportPersonalPasswordSelected(const base::ListValue* args);
- void ExportPersonalSlotsUnlocked();
- void ExportPersonalFileWritten(const int* write_errno,
- const int* bytes_written);
-
- // Import from PKCS #12 or cert file. The sequence goes like:
- // 1. user click on import button -> StartImportPersonal -> launches file
- // selector
- // 2. user selects file -> ImportPersonalFileSelected -> starts async
- // read operation
- // 3. read operation completes -> ImportPersonalFileRead ->
- // If file is PFX -> launches password dialog, goto step 4
- // Else -> import as certificate, goto step 6
- // 4. user enters password -> ImportPersonalPasswordSelected -> unlock slot
- // 5. slot unlocked -> ImportPersonalSlotUnlocked attempts to
- // import with previously entered password
- // 6a. if import succeeds -> ImportExportCleanup
- // 6b. if import fails -> show error, ImportExportCleanup
- // TODO(mattm): allow retrying with different password
- void StartImportPersonal(const base::ListValue* args);
- void ImportPersonalFileSelected(const base::FilePath& path);
- void ImportPersonalFileRead(const int* read_errno, const std::string* data);
- void ImportPersonalPasswordSelected(const base::ListValue* args);
- void ImportPersonalSlotUnlocked();
-
- // Import Server certificates from file. Sequence goes like:
- // 1. user clicks on import button -> ImportServer -> launches file selector
- // 2. user selects file -> ImportServerFileSelected -> starts async read
- // 3. read completes -> ImportServerFileRead -> parse certs -> attempt import
- // 4a. if import succeeds -> ImportExportCleanup
- // 4b. if import fails -> show error, ImportExportCleanup
- void ImportServer(const base::ListValue* args);
- void ImportServerFileSelected(const base::FilePath& path);
- void ImportServerFileRead(const int* read_errno, const std::string* data);
-
- // Import Certificate Authorities from file. Sequence goes like:
- // 1. user clicks on import button -> ImportCA -> launches file selector
- // 2. user selects file -> ImportCAFileSelected -> starts async read
- // 3. read completes -> ImportCAFileRead -> parse certs ->
- // CertificateEditCaTrustOverlay.showImport
- // 4. user clicks ok -> ImportCATrustSelected -> attempt import
- // 5a. if import succeeds -> ImportExportCleanup
- // 5b. if import fails -> show error, ImportExportCleanup
- void ImportCA(const base::ListValue* args);
- void ImportCAFileSelected(const base::FilePath& path);
- void ImportCAFileRead(const int* read_errno, const std::string* data);
- void ImportCATrustSelected(const base::ListValue* args);
-
- // Export a certificate.
- void Export(const base::ListValue* args);
-
- // Delete certificate and private key (if any).
- void Delete(const base::ListValue* args);
-
- // Model initialization methods.
- void OnCertificateManagerModelCreated(
- std::unique_ptr<CertificateManagerModel> model);
- void CertificateManagerModelReady();
-
- // Populate the trees in all the tabs.
- void Populate(const base::ListValue* args);
-
- // Populate the given tab's tree.
- void PopulateTree(const std::string& tab_name,
- net::CertType type,
- const net::CertificateList& web_trust_certs);
-
- // Populate the tree after retrieving the list of policy-installed
- // web-trusted certificates.
- void OnPolicyWebTrustCertsRetrieved(
- const net::CertificateList& web_trust_certs);
-
- // Display a WebUI error message box.
- void ShowError(const std::string& title, const std::string& error) const;
-
- // Display a WebUI error message box for import failures.
- // Depends on |selected_cert_list_| being set to the imports that we
- // attempted to import.
- void ShowImportErrors(
- const std::string& title,
- const net::NSSCertDatabase::ImportCertFailureList& not_imported) const;
-
- gfx::NativeWindow GetParentWindow() const;
-
- // True if certificate viewer should be shown in modal instead of constrianed
- // dialog.
- bool show_certs_in_modal_dialog_;
- // The Certificates Manager model
- bool requested_certificate_manager_model_;
- std::unique_ptr<CertificateManagerModel> certificate_manager_model_;
-
- // For multi-step import or export processes, we need to store the path,
- // password, etc the user chose while we wait for them to enter a password,
- // wait for file to be read, etc.
- base::FilePath file_path_;
- base::string16 password_;
- bool use_hardware_backed_;
- std::string file_data_;
- net::CertificateList selected_cert_list_;
- scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
- crypto::ScopedPK11Slot slot_;
-
- // Used in reading and writing certificate files.
- base::CancelableTaskTracker tracker_;
- scoped_refptr<FileAccessProvider> file_access_provider_;
-
- std::unique_ptr<CertIdMap> cert_id_map_;
-
- base::WeakPtrFactory<CertificateManagerHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(CertificateManagerHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CERTIFICATE_MANAGER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/DEPS b/chromium/chrome/browser/ui/webui/options/chromeos/DEPS
deleted file mode 100644
index 273d26becd6..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/DEPS
+++ /dev/null
@@ -1,3 +0,0 @@
-include_rules = [
- "+components/onc",
-]
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/OWNERS b/chromium/chrome/browser/ui/webui/options/chromeos/OWNERS
deleted file mode 100644
index fff9165e69d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-# This UI is deprecated. See chrome/browser/ui/webui/settings/chromeos/ instead.
-achuith@chromium.org
-stevenjb@chromium.org
-
-# Display options.
-mukai@chromium.org
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc
deleted file mode 100644
index dfca5fd225a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.cc
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <string>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_metrics.h"
-#include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/settings/cros_settings_names.h"
-#include "components/prefs/pref_service.h"
-#include "components/user_manager/user_manager.h"
-#include "components/user_manager/user_names.h"
-#include "content/public/browser/web_ui.h"
-#include "google_apis/gaia/gaia_auth_util.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace chromeos {
-
-namespace {
-
-// Adds specified user to the whitelist. Returns false if that user is already
-// in the whitelist.
-bool WhitelistUser(OwnerSettingsServiceChromeOS* service,
- const std::string& username) {
- if (CrosSettings::Get()->FindEmailInList(kAccountsPrefUsers, username, NULL))
- return false;
- if (service) {
- base::Value username_value(username);
- service->AppendToList(kAccountsPrefUsers, username_value);
- }
- return true;
-}
-
-} // namespace
-
-namespace options {
-
-AccountsOptionsHandler::AccountsOptionsHandler() {
-}
-
-AccountsOptionsHandler::~AccountsOptionsHandler() {
-}
-
-void AccountsOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("whitelistUser",
- base::Bind(&AccountsOptionsHandler::HandleWhitelistUser,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("unwhitelistUser",
- base::Bind(&AccountsOptionsHandler::HandleUnwhitelistUser,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("updateWhitelist",
- base::Bind(&AccountsOptionsHandler::HandleUpdateWhitelist,
- base::Unretained(this)));
-}
-
-void AccountsOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- RegisterTitle(localized_strings, "accountsPage",
- IDS_OPTIONS_ACCOUNTS_TAB_LABEL);
-
- localized_strings->SetString("allow_BWSI", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_ALLOW_BWSI_DESCRIPTION));
- localized_strings->SetString(
- "allow_supervised_users",
- l10n_util::GetStringUTF16(IDS_OPTIONS_ACCOUNTS_ENABLE_SUPERVISED_USERS));
- localized_strings->SetString("use_whitelist", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_USE_WHITELIST_DESCRIPTION));
- localized_strings->SetString("show_user_on_signin", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_SHOW_USER_NAMES_ON_SINGIN_DESCRIPTION));
- localized_strings->SetString("username_edit_hint", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_USERNAME_EDIT_HINT));
- localized_strings->SetString("username_format", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_USERNAME_FORMAT));
- localized_strings->SetString("add_users", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_ADD_USERS));
- localized_strings->SetString("owner_only", l10n_util::GetStringUTF16(
- IDS_OPTIONS_ACCOUNTS_OWNER_ONLY));
-
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- localized_strings->SetBoolean("whitelist_is_managed",
- connector->IsEnterpriseManaged());
-
- AddAccountUITweaksLocalizedValues(localized_strings,
- Profile::FromWebUI(web_ui()));
-}
-
-void AccountsOptionsHandler::HandleWhitelistUser(const base::ListValue* args) {
- std::string typed_email;
- std::string name;
- if (!args->GetString(0, &typed_email) ||
- !args->GetString(1, &name)) {
- return;
- }
-
- if (OwnerSettingsServiceChromeOS* service =
- OwnerSettingsServiceChromeOS::FromWebUI(web_ui())) {
- WhitelistUser(service, gaia::CanonicalizeEmail(typed_email));
- }
-}
-
-void AccountsOptionsHandler::HandleUnwhitelistUser(
- const base::ListValue* args) {
- std::string email;
- if (!args->GetString(0, &email)) {
- return;
- }
-
- ProfileMetrics::LogProfileDeleteUser(ProfileMetrics::DELETE_PROFILE_SETTINGS);
-
- base::Value canonical_email(gaia::CanonicalizeEmail(email));
- if (OwnerSettingsServiceChromeOS* service =
- OwnerSettingsServiceChromeOS::FromWebUI(web_ui())) {
- service->RemoveFromList(kAccountsPrefUsers, canonical_email);
- }
- user_manager::UserManager::Get()->RemoveUser(AccountId::FromUserEmail(email),
- nullptr);
-}
-
-void AccountsOptionsHandler::HandleUpdateWhitelist(
- const base::ListValue* args) {
- DCHECK(args && args->empty());
-
- // Creates one list to set. This is needed because user white list update is
- // asynchronous and sequential. Before previous write comes back, cached list
- // is stale and should not be used for appending. See http://crbug.com/127215
- std::unique_ptr<base::ListValue> new_list;
-
- CrosSettings* cros_settings = CrosSettings::Get();
- const base::ListValue* existing = NULL;
- if (cros_settings->GetList(kAccountsPrefUsers, &existing) && existing)
- new_list.reset(existing->DeepCopy());
- else
- new_list.reset(new base::ListValue);
-
- // Remove all supervised users. On the next step only supervised users present
- // on the device will be added back. Thus not present SU are removed.
- // No need to remove usual users as they can simply login back.
- for (size_t i = 0; i < new_list->GetSize(); ++i) {
- std::string whitelisted_user;
- new_list->GetString(i, &whitelisted_user);
- if (gaia::ExtractDomainName(whitelisted_user) ==
- user_manager::kSupervisedUserDomain) {
- new_list->Remove(i, NULL);
- --i;
- }
- }
-
- const user_manager::UserList& users =
- user_manager::UserManager::Get()->GetUsers();
- for (const auto* user : users) {
- new_list->AppendIfNotPresent(
- base::MakeUnique<base::Value>(user->GetAccountId().GetUserEmail()));
- }
-
- if (OwnerSettingsServiceChromeOS* service =
- OwnerSettingsServiceChromeOS::FromWebUI(web_ui())) {
- service->Set(kAccountsPrefUsers, *new_list.get());
- }
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h
deleted file mode 100644
index 83212bbcc8d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h
+++ /dev/null
@@ -1,42 +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_OPTIONS_CHROMEOS_ACCOUNTS_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_ACCOUNTS_OPTIONS_HANDLER_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace chromeos {
-namespace options {
-
-// ChromeOS accounts options page handler.
-class AccountsOptionsHandler : public ::options::OptionsPageUIHandler {
- public:
- AccountsOptionsHandler();
- ~AccountsOptionsHandler() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- private:
- // Javascript callbacks to update whitelist/unwhitelist user.
- void HandleWhitelistUser(const base::ListValue* args);
- void HandleUnwhitelistUser(const base::ListValue* args);
-
- // Javascript callback to update the white list: auto add existing users,
- // remove not present supervised users.
- void HandleUpdateWhitelist(const base::ListValue* args);
-
- DISALLOW_COPY_AND_ASSIGN(AccountsOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_ACCOUNTS_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.cc
deleted file mode 100644
index ddff2c18054..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.cc
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/callback.h"
-#include "base/command_line.h"
-#include "base/macros.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-#include "third_party/cros_system_api/dbus/service_constants.h"
-
-namespace chromeos {
-namespace options {
-
-BluetoothOptionsHandler::BluetoothOptionsHandler() {
-}
-
-BluetoothOptionsHandler::~BluetoothOptionsHandler() {
-}
-
-void BluetoothOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "bluetooth", IDS_OPTIONS_SETTINGS_SECTION_TITLE_BLUETOOTH },
- { "disableBluetooth", IDS_OPTIONS_SETTINGS_BLUETOOTH_DISABLE },
- { "enableBluetooth", IDS_OPTIONS_SETTINGS_BLUETOOTH_ENABLE },
- { "addBluetoothDevice", IDS_OPTIONS_SETTINGS_ADD_BLUETOOTH_DEVICE },
- { "bluetoothAddDeviceTitle",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_ADD_DEVICE_TITLE },
- { "bluetoothOptionsPageTabTitle",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_ADD_DEVICE_TITLE },
- { "bluetoothNoDevices", IDS_OPTIONS_SETTINGS_BLUETOOTH_NO_DEVICES },
- { "bluetoothNoDevicesFound",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_NO_DEVICES_FOUND },
- { "bluetoothScanning", IDS_OPTIONS_SETTINGS_BLUETOOTH_SCANNING },
- { "bluetoothScanStopped", IDS_OPTIONS_SETTINGS_BLUETOOTH_SCAN_STOPPED },
- { "bluetoothDeviceConnecting", IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECTING },
- { "bluetoothConnectDevice", IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT },
- { "bluetoothDisconnectDevice", IDS_OPTIONS_SETTINGS_BLUETOOTH_DISCONNECT },
- { "bluetoothForgetDevice", IDS_OPTIONS_SETTINGS_BLUETOOTH_FORGET },
- { "bluetoothCancel", IDS_OPTIONS_SETTINGS_BLUETOOTH_CANCEL },
- { "bluetoothEnterKey", IDS_OPTIONS_SETTINGS_BLUETOOTH_ENTER_KEY },
- { "bluetoothDismissError", IDS_OPTIONS_SETTINGS_BLUETOOTH_DISMISS_ERROR },
-
- // Device connecting and pairing.
- { "bluetoothStartConnecting",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_START_CONNECTING },
- { "bluetoothAcceptPasskey",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_ACCEPT_PASSKEY },
- { "bluetoothRejectPasskey",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_REJECT_PASSKEY },
- { "bluetoothEnterPinCode",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_ENTER_PIN_CODE_REQUEST },
- { "bluetoothEnterPasskey",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_ENTER_PASSKEY_REQUEST },
- { "bluetoothRemotePinCode",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_REMOTE_PIN_CODE_REQUEST },
- { "bluetoothRemotePasskey",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_REMOTE_PASSKEY_REQUEST },
- { "bluetoothConfirmPasskey",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONFIRM_PASSKEY_REQUEST },
-
- // Error messages.
- { "bluetoothStartDiscoveryFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_START_DISCOVERY_FAILED },
- { "bluetoothStopDiscoveryFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_STOP_DISCOVERY_FAILED },
- { "bluetoothChangePowerFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CHANGE_POWER_FAILED },
- { "bluetoothConnectUnknownError",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_UNKNOWN_ERROR },
- { "bluetoothConnectInProgress",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_IN_PROGRESS },
- { "bluetoothConnectFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_FAILED },
- { "bluetoothConnectAuthFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_AUTH_FAILED },
- { "bluetoothConnectAuthCanceled",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_AUTH_CANCELED },
- { "bluetoothConnectAuthRejected",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_AUTH_REJECTED },
- { "bluetoothConnectAuthTimeout",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_AUTH_TIMEOUT },
- { "bluetoothConnectUnsupportedDevice",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT_UNSUPPORTED_DEVICE },
- { "bluetoothDisconnectFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_DISCONNECT_FAILED },
- { "bluetoothForgetFailed",
- IDS_OPTIONS_SETTINGS_BLUETOOTH_FORGET_FAILED }};
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h
deleted file mode 100644
index dfe8753008f..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h
+++ /dev/null
@@ -1,40 +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_OPTIONS_CHROMEOS_BLUETOOTH_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_BLUETOOTH_OPTIONS_HANDLER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/callback.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-}
-
-namespace chromeos {
-namespace options {
-
-// Handler for Bluetooth options on the system options page.
-class BluetoothOptionsHandler : public ::options::OptionsPageUIHandler {
- public:
- BluetoothOptionsHandler();
- ~BluetoothOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BluetoothOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_BLUETOOTH_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc
deleted file mode 100644
index bd265d2e10a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.cc
+++ /dev/null
@@ -1,461 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/path_service.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
-#include "chrome/browser/chromeos/camera_presence_notifier.h"
-#include "chrome/browser/chromeos/login/users/avatar/user_image_manager.h"
-#include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
-#include "chrome/browser/chromeos/login/users/default_user_image/default_user_images.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/chrome_select_file_policy.h"
-#include "chrome/common/chrome_paths.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/browser_resources.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/audio/chromeos_sounds.h"
-#include "components/user_manager/user.h"
-#include "components/user_manager/user_image/user_image.h"
-#include "components/user_manager/user_manager.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/common/url_constants.h"
-#include "media/audio/sounds/sounds_manager.h"
-#include "net/base/data_url.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/webui/web_ui_util.h"
-#include "ui/views/widget/widget.h"
-#include "url/gurl.h"
-
-using content::BrowserThread;
-
-namespace chromeos {
-namespace options {
-
-namespace {
-
-// Returns info about extensions for files we support as user images.
-ui::SelectFileDialog::FileTypeInfo GetUserImageFileTypeInfo() {
- ui::SelectFileDialog::FileTypeInfo file_type_info;
- file_type_info.extensions.resize(1);
-
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("bmp"));
-
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("jpg"));
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("jpeg"));
-
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("png"));
-
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("tif"));
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("tiff"));
-
- file_type_info.extension_description_overrides.resize(1);
- file_type_info.extension_description_overrides[0] =
- l10n_util::GetStringUTF16(IDS_IMAGE_FILES);
-
- return file_type_info;
-}
-
-// Time histogram suffix for profile image download.
-const char kProfileDownloadReason[] = "Preferences";
-
-} // namespace
-
-ChangePictureOptionsHandler::ChangePictureOptionsHandler()
- : previous_image_url_(url::kAboutBlankURL),
- previous_image_index_(user_manager::User::USER_IMAGE_INVALID) {
- user_manager::UserManager::Get()->AddObserver(this);
-
- ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
- media::SoundsManager* manager = media::SoundsManager::Get();
- manager->Initialize(SOUND_OBJECT_DELETE,
- bundle.GetRawDataResource(IDR_SOUND_OBJECT_DELETE_WAV));
- manager->Initialize(SOUND_CAMERA_SNAP,
- bundle.GetRawDataResource(IDR_SOUND_CAMERA_SNAP_WAV));
-}
-
-ChangePictureOptionsHandler::~ChangePictureOptionsHandler() {
- user_manager::UserManager::Get()->RemoveObserver(this);
- CameraPresenceNotifier::GetInstance()->RemoveObserver(this);
- if (select_file_dialog_.get())
- select_file_dialog_->ListenerDestroyed();
-}
-
-void ChangePictureOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- localized_strings->SetString("changePicturePage",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_DIALOG_TITLE));
- localized_strings->SetString("changePicturePageDescription",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_DIALOG_TEXT));
- localized_strings->SetString("takePhoto",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_TAKE_PHOTO));
- localized_strings->SetString("discardPhoto",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_DISCARD_PHOTO));
- localized_strings->SetString("flipPhoto",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_FLIP_PHOTO));
- localized_strings->SetString("chooseFile",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_CHOOSE_FILE));
- localized_strings->SetString("profilePhoto",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_PROFILE_PHOTO));
- localized_strings->SetString("profilePhotoLoading",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CHANGE_PICTURE_PROFILE_LOADING_PHOTO));
- localized_strings->SetString("previewAltText",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_PREVIEW_ALT));
- localized_strings->SetString("authorCredit",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_AUTHOR_TEXT));
- localized_strings->SetString("photoFromCamera",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CHANGE_PICTURE_PHOTO_FROM_CAMERA));
- localized_strings->SetString("photoFlippedAccessibleText",
- l10n_util::GetStringUTF16(IDS_OPTIONS_PHOTO_FLIP_ACCESSIBLE_TEXT));
- localized_strings->SetString("photoFlippedBackAccessibleText",
- l10n_util::GetStringUTF16(IDS_OPTIONS_PHOTO_FLIPBACK_ACCESSIBLE_TEXT));
- localized_strings->SetString("photoCaptureAccessibleText",
- l10n_util::GetStringUTF16(IDS_OPTIONS_PHOTO_CAPTURE_ACCESSIBLE_TEXT));
- localized_strings->SetString("photoDiscardAccessibleText",
- l10n_util::GetStringUTF16(IDS_OPTIONS_PHOTO_DISCARD_ACCESSIBLE_TEXT));
-}
-
-void ChangePictureOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("chooseFile",
- base::Bind(&ChangePictureOptionsHandler::HandleChooseFile,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("takePhoto",
- base::Bind(&ChangePictureOptionsHandler::HandleTakePhoto,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("photoTaken",
- base::Bind(&ChangePictureOptionsHandler::HandlePhotoTaken,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("discardPhoto",
- base::Bind(&ChangePictureOptionsHandler::HandleDiscardPhoto,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("onChangePicturePageShown",
- base::Bind(&ChangePictureOptionsHandler::HandlePageShown,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("onChangePicturePageHidden",
- base::Bind(&ChangePictureOptionsHandler::HandlePageHidden,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("onChangePicturePageInitialized",
- base::Bind(&ChangePictureOptionsHandler::HandlePageInitialized,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("selectImage",
- base::Bind(&ChangePictureOptionsHandler::HandleSelectImage,
- base::Unretained(this)));
-}
-
-void ChangePictureOptionsHandler::SendDefaultImages() {
- std::unique_ptr<base::ListValue> image_urls =
- default_user_image::GetAsDictionary(false /* all */);
- web_ui()->CallJavascriptFunctionUnsafe(
- "ChangePictureOptions.setDefaultImages", *image_urls);
-}
-
-void ChangePictureOptionsHandler::HandleChooseFile(
- const base::ListValue* args) {
- DCHECK(args && args->empty());
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
-
- base::FilePath downloads_path;
- if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_path)) {
- NOTREACHED();
- return;
- }
-
- // Static so we initialize it only once.
- CR_DEFINE_STATIC_LOCAL(ui::SelectFileDialog::FileTypeInfo, file_type_info,
- (GetUserImageFileTypeInfo()));
-
- select_file_dialog_->SelectFile(
- ui::SelectFileDialog::SELECT_OPEN_FILE,
- l10n_util::GetStringUTF16(IDS_DOWNLOAD_TITLE),
- downloads_path,
- &file_type_info,
- 0,
- FILE_PATH_LITERAL(""),
- GetBrowserWindow(),
- NULL);
-}
-
-void ChangePictureOptionsHandler::HandleTakePhoto(
- const base::ListValue* args) {
- DCHECK(args->empty());
- AccessibilityManager::Get()->PlayEarcon(
- SOUND_CAMERA_SNAP, PlaySoundOption::SPOKEN_FEEDBACK_ENABLED);
-}
-
-void ChangePictureOptionsHandler::HandleDiscardPhoto(
- const base::ListValue* args) {
- DCHECK(args->empty());
- AccessibilityManager::Get()->PlayEarcon(
- SOUND_OBJECT_DELETE, PlaySoundOption::SPOKEN_FEEDBACK_ENABLED);
-}
-
-void ChangePictureOptionsHandler::HandlePhotoTaken(
- const base::ListValue* args) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- std::string image_url;
- if (!args || args->GetSize() != 1 || !args->GetString(0, &image_url))
- NOTREACHED();
- DCHECK(!image_url.empty());
-
- std::string mime_type, charset, raw_data;
- if (!net::DataURL::Parse(GURL(image_url), &mime_type, &charset, &raw_data))
- NOTREACHED();
- DCHECK_EQ("image/png", mime_type);
-
- user_photo_ = gfx::ImageSkia();
- user_photo_data_url_ = image_url;
-
- ImageDecoder::Cancel(this);
- ImageDecoder::Start(this, raw_data);
-}
-
-void ChangePictureOptionsHandler::HandlePageInitialized(
- const base::ListValue* args) {
- DCHECK(args && args->empty());
- SendDefaultImages();
-}
-
-void ChangePictureOptionsHandler::HandlePageShown(const base::ListValue* args) {
- DCHECK(args && args->empty());
- SendSelectedImage();
- UpdateProfileImage();
- CameraPresenceNotifier::GetInstance()->AddObserver(this);
-}
-
-void ChangePictureOptionsHandler::HandlePageHidden(
- const base::ListValue* args) {
- CameraPresenceNotifier::GetInstance()->RemoveObserver(this);
-}
-
-void ChangePictureOptionsHandler::SendSelectedImage() {
- const user_manager::User* user = GetUser();
- DCHECK(user->GetAccountId().is_valid());
-
- previous_image_index_ = user->image_index();
- switch (previous_image_index_) {
- case user_manager::User::USER_IMAGE_EXTERNAL: {
- // User has image from camera/file, record it and add to the image list.
- previous_image_ = user->GetImage();
- SendOldImage(webui::GetBitmapDataUrl(*previous_image_.bitmap()));
- break;
- }
- case user_manager::User::USER_IMAGE_PROFILE: {
- // User has their Profile image as the current image.
- SendProfileImage(user->GetImage(), true);
- break;
- }
- default: {
- if (default_user_image::IsInCurrentImageSet(previous_image_index_)) {
- // User has image from the current set of default images.
- base::Value image_url(
- default_user_image::GetDefaultImageUrl(previous_image_index_));
- web_ui()->CallJavascriptFunctionUnsafe(
- "ChangePictureOptions.setSelectedImage", image_url);
- } else {
- // User has an old default image, so present it in the same manner as a
- // previous image from file.
- SendOldImage(
- default_user_image::GetDefaultImageUrl(previous_image_index_));
- }
- }
- }
-}
-
-void ChangePictureOptionsHandler::SendProfileImage(const gfx::ImageSkia& image,
- bool should_select) {
- base::Value data_url(webui::GetBitmapDataUrl(*image.bitmap()));
- base::Value select(should_select);
- web_ui()->CallJavascriptFunctionUnsafe("ChangePictureOptions.setProfileImage",
- data_url, select);
-}
-
-void ChangePictureOptionsHandler::UpdateProfileImage() {
- UserImageManager* user_image_manager =
- ChromeUserManager::Get()->GetUserImageManager(GetUser()->GetAccountId());
- // If we have a downloaded profile image and haven't sent it in
- // |SendSelectedImage|, send it now (without selecting).
- if (previous_image_index_ != user_manager::User::USER_IMAGE_PROFILE &&
- !user_image_manager->DownloadedProfileImage().isNull())
- SendProfileImage(user_image_manager->DownloadedProfileImage(), false);
-
- user_image_manager->DownloadProfileImage(kProfileDownloadReason);
-}
-
-void ChangePictureOptionsHandler::SendOldImage(const std::string& image_url) {
- previous_image_url_ = image_url;
- base::Value url(image_url);
- web_ui()->CallJavascriptFunctionUnsafe("ChangePictureOptions.setOldImage",
- url);
-}
-
-void ChangePictureOptionsHandler::HandleSelectImage(
- const base::ListValue* args) {
- std::string image_url;
- std::string image_type;
- if (!args ||
- args->GetSize() != 2 ||
- !args->GetString(0, &image_url) ||
- !args->GetString(1, &image_type)) {
- NOTREACHED();
- return;
- }
- DCHECK(!image_url.empty());
- DCHECK(!image_type.empty());
-
- UserImageManager* user_image_manager =
- ChromeUserManager::Get()->GetUserImageManager(GetUser()->GetAccountId());
- int image_index = user_manager::User::USER_IMAGE_INVALID;
- bool waiting_for_camera_photo = false;
-
- if (image_type == "old") {
- // Previous image (from camera or manually uploaded) re-selected.
- DCHECK(!previous_image_.isNull());
- user_image_manager->SaveUserImage(
- user_manager::UserImage::CreateAndEncode(
- previous_image_, user_manager::UserImage::FORMAT_JPEG));
-
- UMA_HISTOGRAM_EXACT_LINEAR("UserImage.ChangeChoice",
- default_user_image::kHistogramImageOld,
- default_user_image::kHistogramImagesCount);
- VLOG(1) << "Selected old user image";
- } else if (image_type == "default" &&
- default_user_image::IsDefaultImageUrl(image_url, &image_index)) {
- // One of the default user images.
- user_image_manager->SaveUserDefaultImageIndex(image_index);
-
- UMA_HISTOGRAM_EXACT_LINEAR(
- "UserImage.ChangeChoice",
- default_user_image::GetDefaultImageHistogramValue(image_index),
- default_user_image::kHistogramImagesCount);
- VLOG(1) << "Selected default user image: " << image_index;
- } else if (image_type == "camera") {
- // Camera image is selected.
- if (user_photo_.isNull()) {
- waiting_for_camera_photo = true;
- VLOG(1) << "Still waiting for camera image to decode";
- } else {
- SetImageFromCamera(user_photo_);
- }
- } else if (image_type == "profile") {
- // Profile image selected. Could be previous (old) user image.
- user_image_manager->SaveUserImageFromProfileImage();
-
- if (previous_image_index_ == user_manager::User::USER_IMAGE_PROFILE) {
- UMA_HISTOGRAM_EXACT_LINEAR("UserImage.ChangeChoice",
- default_user_image::kHistogramImageOld,
- default_user_image::kHistogramImagesCount);
- VLOG(1) << "Selected old (profile) user image";
- } else {
- UMA_HISTOGRAM_EXACT_LINEAR("UserImage.ChangeChoice",
- default_user_image::kHistogramImageFromProfile,
- default_user_image::kHistogramImagesCount);
- VLOG(1) << "Selected profile image";
- }
- } else {
- NOTREACHED() << "Unexpected image type: " << image_type;
- }
-
- // Ignore the result of the previous decoding if it's no longer needed.
- if (!waiting_for_camera_photo)
- ImageDecoder::Cancel(this);
-}
-
-void ChangePictureOptionsHandler::FileSelected(const base::FilePath& path,
- int index,
- void* params) {
- ChromeUserManager::Get()
- ->GetUserImageManager(GetUser()->GetAccountId())
- ->SaveUserImageFromFile(path);
- UMA_HISTOGRAM_EXACT_LINEAR("UserImage.ChangeChoice",
- default_user_image::kHistogramImageFromFile,
- default_user_image::kHistogramImagesCount);
- VLOG(1) << "Selected image from file";
-}
-
-void ChangePictureOptionsHandler::SetImageFromCamera(
- const gfx::ImageSkia& photo) {
- ChromeUserManager::Get()
- ->GetUserImageManager(GetUser()->GetAccountId())
- ->SaveUserImage(user_manager::UserImage::CreateAndEncode(
- photo, user_manager::UserImage::FORMAT_JPEG));
- UMA_HISTOGRAM_EXACT_LINEAR("UserImage.ChangeChoice",
- default_user_image::kHistogramImageFromCamera,
- default_user_image::kHistogramImagesCount);
- VLOG(1) << "Selected camera photo";
-}
-
-void ChangePictureOptionsHandler::SetCameraPresent(bool present) {
- base::Value present_value(present);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ChangePictureOptions.setCameraPresent", present_value);
-}
-
-void ChangePictureOptionsHandler::OnCameraPresenceCheckDone(
- bool is_camera_present) {
- SetCameraPresent(is_camera_present);
-}
-
-void ChangePictureOptionsHandler::OnUserImageChanged(
- const user_manager::User& user) {
- // Not initialized yet.
- if (previous_image_index_ == user_manager::User::USER_IMAGE_INVALID)
- return;
- SendSelectedImage();
-}
-
-void ChangePictureOptionsHandler::OnUserProfileImageUpdated(
- const user_manager::User& user,
- const gfx::ImageSkia& profile_image) {
- // User profile image has been updated.
- SendProfileImage(profile_image, false);
-}
-
-gfx::NativeWindow ChangePictureOptionsHandler::GetBrowserWindow() const {
- Browser* browser =
- chrome::FindBrowserWithWebContents(web_ui()->GetWebContents());
- return browser->window()->GetNativeWindow();
-}
-
-void ChangePictureOptionsHandler::OnImageDecoded(
- const SkBitmap& decoded_image) {
- user_photo_ = gfx::ImageSkia::CreateFrom1xBitmap(decoded_image);
- SetImageFromCamera(user_photo_);
-}
-
-void ChangePictureOptionsHandler::OnDecodeImageFailed() {
- NOTREACHED() << "Failed to decode PNG image from WebUI";
-}
-
-const user_manager::User* ChangePictureOptionsHandler::GetUser() const {
- Profile* profile = Profile::FromWebUI(web_ui());
- const user_manager::User* user =
- ProfileHelper::Get()->GetUserByProfile(profile);
- if (!user)
- return user_manager::UserManager::Get()->GetActiveUser();
- return user;
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.h
deleted file mode 100644
index 625ce3b945d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.h
+++ /dev/null
@@ -1,145 +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_OPTIONS_CHROMEOS_CHANGE_PICTURE_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CHANGE_PICTURE_OPTIONS_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/chromeos/camera_presence_notifier.h"
-#include "chrome/browser/image_decoder.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/user_manager/user_manager.h"
-#include "ui/gfx/image/image_skia.h"
-#include "ui/gfx/native_widget_types.h"
-#include "ui/shell_dialogs/select_file_dialog.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace user_manager {
-class User;
-}
-
-namespace chromeos {
-
-namespace options {
-
-// ChromeOS user image options page UI handler.
-class ChangePictureOptionsHandler : public ::options::OptionsPageUIHandler,
- public ui::SelectFileDialog::Listener,
- public user_manager::UserManager::Observer,
- public ImageDecoder::ImageRequest,
- public CameraPresenceNotifier::Observer {
- public:
- ChangePictureOptionsHandler();
- ~ChangePictureOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // CameraPresenceNotifier::Observer implementation:
- void OnCameraPresenceCheckDone(bool is_camera_present) override;
-
- private:
- // Sends list of available default images to the page.
- void SendDefaultImages();
-
- // Sends current selection to the page.
- void SendSelectedImage();
-
- // Sends the profile image to the page. If |should_select| is true then
- // the profile image element is selected.
- void SendProfileImage(const gfx::ImageSkia& image, bool should_select);
-
- // Starts profile image update and shows the last downloaded profile image,
- // if any, on the page. Shouldn't be called before |SendProfileImage|.
- void UpdateProfileImage();
-
- // Sends previous user image to the page.
- void SendOldImage(const std::string& image_url);
-
- // Starts camera presence check.
- void CheckCameraPresence();
-
- // Updates UI with camera presence state.
- void SetCameraPresent(bool present);
-
- // Opens a file selection dialog to choose user image from file.
- void HandleChooseFile(const base::ListValue* args);
-
- // Handles 'take-photo' button click.
- void HandleTakePhoto(const base::ListValue* args);
-
- // Handles photo taken with WebRTC UI.
- void HandlePhotoTaken(const base::ListValue* args);
-
- // Handles 'discard-photo' button click.
- void HandleDiscardPhoto(const base::ListValue* args);
-
- // Gets the list of available user images and sends it to the page.
- void HandleGetAvailableImages(const base::ListValue* args);
-
- // Handles page initialized event.
- void HandlePageInitialized(const base::ListValue* args);
-
- // Handles page shown event.
- void HandlePageShown(const base::ListValue* args);
-
- // Handles page hidden event.
- void HandlePageHidden(const base::ListValue* args);
-
- // Selects one of the available images as user's.
- void HandleSelectImage(const base::ListValue* args);
-
- // SelectFileDialog::Delegate implementation.
- void FileSelected(const base::FilePath& path,
- int index,
- void* params) override;
-
- // user_manager::UserManager::Observer implementation.
- void OnUserImageChanged(const user_manager::User& user) override;
- void OnUserProfileImageUpdated(const user_manager::User& user,
- const gfx::ImageSkia& profile_image) override;
-
- // Sets user image to photo taken from camera.
- void SetImageFromCamera(const gfx::ImageSkia& photo);
-
- // Returns handle to browser window or NULL if it can't be found.
- gfx::NativeWindow GetBrowserWindow() const;
-
- // Overriden from ImageDecoder::ImageRequest:
- void OnImageDecoded(const SkBitmap& decoded_image) override;
- void OnDecodeImageFailed() override;
-
- // Returns user related to current WebUI. If this user doesn't exist,
- // returns active user.
- const user_manager::User* GetUser() const;
-
- scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
-
- // Previous user image from camera/file and its data URL.
- gfx::ImageSkia previous_image_;
- std::string previous_image_url_;
-
- // Index of the previous user image.
- int previous_image_index_;
-
- // Last user photo, if taken.
- gfx::ImageSkia user_photo_;
-
- // Data URL for |user_photo_|.
- std::string user_photo_data_url_;
-
- DISALLOW_COPY_AND_ASSIGN(ChangePictureOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CHANGE_PICTURE_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc
deleted file mode 100644
index b21df5fcf9d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.cc
+++ /dev/null
@@ -1,427 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h"
-
-#include <stddef.h>
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/location.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/sys_info.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h"
-#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/chromeos/proxy_cros_settings_parser.h"
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/ash/session_controller_client.h"
-#include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h"
-#include "chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/network/network_handler.h"
-#include "chromeos/network/proxy/ui_proxy_config_service.h"
-#include "components/onc/onc_pref_names.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "components/proxy_config/proxy_config_pref_names.h"
-#include "components/user_manager/user_manager.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace chromeos {
-namespace options {
-
-namespace {
-
-// List of settings that should be changeable by all users.
-const char* kNonPrivilegedSettings[] = {
- kSystemTimezone
-};
-
-// List of settings that should only be changeable by the primary user.
-const char* kPrimaryUserSettings[] = {
- prefs::kWakeOnWifiDarkConnect,
-};
-
-// Returns true if |pref| can be controlled (e.g. by policy or owner).
-bool IsSettingPrivileged(const std::string& pref) {
- const char** end = kNonPrivilegedSettings + arraysize(kNonPrivilegedSettings);
- return std::find(kNonPrivilegedSettings, end, pref) == end;
-}
-
-// Returns true if |pref| is shared (controlled by the primary user).
-bool IsSettingShared(const std::string& pref) {
- const char** end = kPrimaryUserSettings + arraysize(kPrimaryUserSettings);
- return std::find(kPrimaryUserSettings, end, pref) != end;
-}
-
-// Creates a user info dictionary to be stored in the |ListValue| that is
-// passed to Javascript for the |kAccountsPrefUsers| preference.
-std::unique_ptr<base::DictionaryValue> CreateUserInfo(
- const std::string& username,
- const std::string& display_email,
- const std::string& display_name) {
- auto user_dict = base::MakeUnique<base::DictionaryValue>();
- user_dict->SetString("username", username);
- user_dict->SetString("name", display_email);
- user_dict->SetString("email", display_name);
-
- const bool is_owner =
- user_manager::UserManager::Get()->GetOwnerAccountId().GetUserEmail() ==
- username;
- user_dict->SetBoolean("owner", is_owner);
- return user_dict;
-}
-
-// This function decorates the bare list of emails with some more information
-// needed by the UI to properly display the Accounts page.
-std::unique_ptr<base::Value> CreateUsersWhitelist(
- const base::Value* pref_value) {
- const base::ListValue* list_value =
- static_cast<const base::ListValue*>(pref_value);
- auto user_list = base::MakeUnique<base::ListValue>();
- user_manager::UserManager* user_manager = user_manager::UserManager::Get();
-
- for (base::ListValue::const_iterator i = list_value->begin();
- i != list_value->end(); ++i) {
- std::string email;
- if (i->GetAsString(&email)) {
- // Translate email to the display email.
- const std::string display_email =
- user_manager->GetUserDisplayEmail(AccountId::FromUserEmail(email));
- // TODO(ivankr): fetch display name for existing users.
- user_list->Append(CreateUserInfo(email, display_email, std::string()));
- }
- }
- return std::move(user_list);
-}
-
-// Checks whether this is a secondary user in a multi-profile session.
-bool IsSecondaryUser(Profile* profile) {
- user_manager::UserManager* user_manager = user_manager::UserManager::Get();
- const user_manager::User* user =
- ProfileHelper::Get()->GetUserByProfile(profile);
- return user &&
- user->GetAccountId() != user_manager->GetPrimaryUser()->GetAccountId();
-}
-
-const char kSelectNetworkMessage[] = "selectNetwork";
-
-UIProxyConfigService* GetUiProxyConfigService() {
- return NetworkHandler::Get()->ui_proxy_config_service();
-}
-
-} // namespace
-
-CoreChromeOSOptionsHandler::CoreChromeOSOptionsHandler() {
- notification_registrar_.Add(this,
- chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
- content::NotificationService::AllSources());
-}
-
-CoreChromeOSOptionsHandler::~CoreChromeOSOptionsHandler() {
-}
-
-void CoreChromeOSOptionsHandler::RegisterMessages() {
- CoreOptionsHandler::RegisterMessages();
- web_ui()->RegisterMessageCallback(
- kSelectNetworkMessage,
- base::Bind(&CoreChromeOSOptionsHandler::SelectNetworkCallback,
- base::Unretained(this)));
-}
-
-void CoreChromeOSOptionsHandler::InitializeHandler() {
- // This function is both called on the initial page load and on each reload.
- CoreOptionsHandler::InitializeHandler();
-
- if (!ProfileHelper::IsSigninProfile(Profile::FromWebUI(web_ui())))
- ObservePref(onc::prefs::kOpenNetworkConfiguration);
- ObservePref(proxy_config::prefs::kProxy);
- ObservePref(onc::prefs::kDeviceOpenNetworkConfiguration);
-}
-
-void CoreChromeOSOptionsHandler::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- DCHECK_EQ(chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED, type);
-
- // Finish this asynchronously because the notification has to tricle in to all
- // Chrome components before we can reliably read the status on the other end.
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::Bind(&CoreChromeOSOptionsHandler::NotifyOwnershipChanged,
- base::Unretained(this)));
-}
-
-void CoreChromeOSOptionsHandler::NotifyOwnershipChanged() {
- for (auto it : pref_subscription_map_)
- NotifySettingsChanged(it.first);
-}
-
-std::unique_ptr<base::Value> CoreChromeOSOptionsHandler::FetchPref(
- const std::string& pref_name) {
- if (proxy_cros_settings_parser::IsProxyPref(pref_name)) {
- std::unique_ptr<base::Value> value;
- proxy_cros_settings_parser::GetProxyPrefValue(
- network_guid_, pref_name, GetUiProxyConfigService(), &value);
- return value;
- }
-
- Profile* profile = Profile::FromWebUI(web_ui());
- if (!CrosSettings::IsCrosSettings(pref_name)) {
- std::string controlling_pref =
- pref_name == proxy_config::prefs::kUseSharedProxies
- ? proxy_config::prefs::kProxy
- : std::string();
- std::unique_ptr<base::Value> value =
- CreateValueForPref(pref_name, controlling_pref);
- if (!IsSettingShared(pref_name) || !IsSecondaryUser(profile))
- return value;
- base::DictionaryValue* dict;
- if (!value->GetAsDictionary(&dict) || dict->HasKey("controlledBy"))
- return value;
- Profile* primary_profile = ProfileHelper::Get()->GetProfileByUser(
- user_manager::UserManager::Get()->GetPrimaryUser());
- if (!primary_profile)
- return value;
- dict->SetString("controlledBy", "shared");
- dict->SetBoolean("disabled", true);
- dict->SetBoolean("value", primary_profile->GetPrefs()->GetBoolean(
- pref_name));
- return value;
- }
-
- const base::Value* pref_value = CrosSettings::Get()->GetPref(pref_name);
- if (!pref_value)
- return base::MakeUnique<base::Value>();
-
- // Decorate pref value as CoreOptionsHandler::CreateValueForPref() does.
- // TODO(estade): seems that this should replicate CreateValueForPref less.
- auto dict = base::MakeUnique<base::DictionaryValue>();
- if (pref_name == kAccountsPrefUsers)
- dict->Set("value", CreateUsersWhitelist(pref_value));
- else
- dict->Set("value", base::MakeUnique<base::Value>(*pref_value));
-
- std::string controlled_by;
- if (IsSettingPrivileged(pref_name)) {
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- if (connector->IsEnterpriseManaged())
- controlled_by = "policy";
- else if (!ProfileHelper::IsOwnerProfile(profile))
- controlled_by = "owner";
- }
- dict->SetBoolean("disabled", !controlled_by.empty());
- if (!controlled_by.empty())
- dict->SetString("controlledBy", controlled_by);
- return std::move(dict);
-}
-
-void CoreChromeOSOptionsHandler::ObservePref(const std::string& pref_name) {
- if (proxy_cros_settings_parser::IsProxyPref(pref_name)) {
- // We observe those all the time.
- return;
- }
- if (!CrosSettings::IsCrosSettings(pref_name))
- return ::options::CoreOptionsHandler::ObservePref(pref_name);
-
- linked_ptr<CrosSettings::ObserverSubscription> subscription(
- CrosSettings::Get()->AddSettingsObserver(
- pref_name.c_str(),
- base::Bind(&CoreChromeOSOptionsHandler::NotifySettingsChanged,
- base::Unretained(this),
- pref_name)).release());
- pref_subscription_map_.insert(make_pair(pref_name, subscription));
-}
-
-void CoreChromeOSOptionsHandler::SetPref(const std::string& pref_name,
- const base::Value* value,
- const std::string& metric) {
- if (proxy_cros_settings_parser::IsProxyPref(pref_name)) {
- proxy_cros_settings_parser::SetProxyPrefValue(
- network_guid_, pref_name, value, GetUiProxyConfigService());
- base::Value proxy_type(pref_name);
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.internet.DetailsInternetPage.updateProxySettings", proxy_type);
- ProcessUserMetric(value, metric);
- return;
- }
- if (!CrosSettings::IsCrosSettings(pref_name))
- return ::options::CoreOptionsHandler::SetPref(pref_name, value, metric);
- OwnerSettingsServiceChromeOS* service =
- OwnerSettingsServiceChromeOS::FromWebUI(web_ui());
- if (service && service->HandlesSetting(pref_name))
- service->Set(pref_name, *value);
- else
- CrosSettings::Get()->Set(pref_name, *value);
-
- ProcessUserMetric(value, metric);
-}
-
-void CoreChromeOSOptionsHandler::StopObservingPref(const std::string& path) {
- if (proxy_cros_settings_parser::IsProxyPref(path))
- return; // We unregister those in the destructor.
- // Unregister this instance from observing prefs of chrome os settings.
- if (CrosSettings::IsCrosSettings(path))
- pref_subscription_map_.erase(path);
- else // Call base class to handle regular preferences.
- ::options::CoreOptionsHandler::StopObservingPref(path);
-}
-
-std::unique_ptr<base::Value> CoreChromeOSOptionsHandler::CreateValueForPref(
- const std::string& pref_name,
- const std::string& controlling_pref_name) {
- // The screen lock setting is shared if multiple users are logged in and at
- // least one has chosen to require passwords.
- if (pref_name == prefs::kEnableAutoScreenLock &&
- user_manager::UserManager::Get()->GetLoggedInUsers().size() > 1 &&
- controlling_pref_name.empty()) {
- PrefService* user_prefs = Profile::FromWebUI(web_ui())->GetPrefs();
- const PrefService::Preference* pref =
- user_prefs->FindPreference(prefs::kEnableAutoScreenLock);
-
- if (pref && pref->IsUserModifiable() &&
- SessionControllerClient::ShouldLockScreenAutomatically()) {
- bool screen_lock = false;
- bool success = pref->GetValue()->GetAsBoolean(&screen_lock);
- DCHECK(success);
- if (!screen_lock) {
- // Screen lock is enabled for the session, but not in the user's
- // preferences. Show the user's value in the checkbox, but indicate
- // that the password requirement is enabled by some other user.
- auto dict = base::MakeUnique<base::DictionaryValue>();
- dict->Set("value", base::MakeUnique<base::Value>(*pref->GetValue()));
- dict->SetString("controlledBy", "shared");
- return std::move(dict);
- }
- }
- }
-
- return CoreOptionsHandler::CreateValueForPref(pref_name,
- controlling_pref_name);
-}
-
-void CoreChromeOSOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- CoreOptionsHandler::GetLocalizedValues(localized_strings);
-
- Profile* profile = Profile::FromWebUI(web_ui());
- AddAccountUITweaksLocalizedValues(localized_strings, profile);
-
- user_manager::UserManager* user_manager = user_manager::UserManager::Get();
-
- if (IsSecondaryUser(profile)) {
- const std::string& primary_email =
- user_manager->GetPrimaryUser()->GetAccountId().GetUserEmail();
-
- // Set secondaryUser to show the shared icon by the network section header.
- localized_strings->SetBoolean("secondaryUser", true);
- localized_strings->SetString("secondaryUserBannerText",
- l10n_util::GetStringFUTF16(
- IDS_OPTIONS_SETTINGS_SECONDARY_USER_BANNER,
- base::ASCIIToUTF16(primary_email)));
- localized_strings->SetString("controlledSettingShared",
- l10n_util::GetStringFUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_SHARED,
- base::ASCIIToUTF16(primary_email)));
- localized_strings->SetString("controlledSettingsShared",
- l10n_util::GetStringFUTF16(
- IDS_OPTIONS_CONTROLLED_SETTINGS_SHARED,
- base::ASCIIToUTF16(primary_email)));
- } else {
- localized_strings->SetBoolean("secondaryUser", false);
- localized_strings->SetString("secondaryUserBannerText", base::string16());
- localized_strings->SetString("controlledSettingShared", base::string16());
- localized_strings->SetString("controlledSettingsShared", base::string16());
- }
-
- // Screen lock icon can show up as primary or secondary user.
- localized_strings->SetString("screenLockShared",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_SHARED_SCREEN_LOCK));
-
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- if (connector->IsEnterpriseManaged()) {
- // Managed machines have no "owner".
- localized_strings->SetString("controlledSettingOwner", base::string16());
- } else {
- localized_strings->SetString(
- "controlledSettingOwner",
- l10n_util::GetStringFUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_OWNER,
- base::ASCIIToUTF16(
- user_manager->GetOwnerAccountId().GetUserEmail())));
- }
-}
-
-void CoreChromeOSOptionsHandler::SelectNetworkCallback(
- const base::ListValue* args) {
- if (args->GetSize() != 1 || !args->GetString(0, &network_guid_)) {
- NOTREACHED();
- return;
- }
- NotifyProxyPrefsChanged();
-}
-
-void CoreChromeOSOptionsHandler::OnPreferenceChanged(
- PrefService* service,
- const std::string& pref_name) {
- // Redetermine the current proxy settings and notify the UI if any of these
- // preferences change.
- if (pref_name == onc::prefs::kOpenNetworkConfiguration ||
- pref_name == onc::prefs::kDeviceOpenNetworkConfiguration ||
- pref_name == proxy_config::prefs::kProxy) {
- NotifyProxyPrefsChanged();
- return;
- }
- if (pref_name == proxy_config::prefs::kUseSharedProxies) {
- // kProxy controls kUseSharedProxies and decides if it's managed by
- // policy/extension.
- NotifyPrefChanged(proxy_config::prefs::kUseSharedProxies,
- proxy_config::prefs::kProxy);
- return;
- }
- ::options::CoreOptionsHandler::OnPreferenceChanged(service, pref_name);
-}
-
-void CoreChromeOSOptionsHandler::NotifySettingsChanged(
- const std::string& setting_name) {
- DCHECK(CrosSettings::Get()->IsCrosSettings(setting_name));
- std::unique_ptr<base::Value> value(FetchPref(setting_name));
- if (!value.get())
- NOTREACHED();
- DispatchPrefChangeNotification(setting_name, std::move(value));
-}
-
-void CoreChromeOSOptionsHandler::NotifyProxyPrefsChanged() {
- GetUiProxyConfigService()->UpdateFromPrefs(network_guid_);
- for (size_t i = 0; i < proxy_cros_settings_parser::kProxySettingsCount; ++i) {
- std::unique_ptr<base::Value> value;
- proxy_cros_settings_parser::GetProxyPrefValue(
- network_guid_, proxy_cros_settings_parser::kProxySettings[i],
- GetUiProxyConfigService(), &value);
- DCHECK(value);
- DispatchPrefChangeNotification(
- proxy_cros_settings_parser::kProxySettings[i], std::move(value));
- }
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h
deleted file mode 100644
index 0bc9e74e00a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CORE_CHROMEOS_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CORE_CHROMEOS_OPTIONS_HANDLER_H_
-
-#include <map>
-#include <memory>
-#include <string>
-
-#include "base/macros.h"
-#include "base/memory/linked_ptr.h"
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/browser/ui/webui/options/core_options_handler.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-
-namespace chromeos {
-namespace options {
-
-// CoreChromeOSOptionsHandler handles ChromeOS settings.
-class CoreChromeOSOptionsHandler : public ::options::CoreOptionsHandler,
- public content::NotificationObserver {
- public:
- CoreChromeOSOptionsHandler();
- ~CoreChromeOSOptionsHandler() override;
-
- // ::CoreOptionsHandler overrides
- void RegisterMessages() override;
- std::unique_ptr<base::Value> FetchPref(const std::string& pref_name) override;
- void InitializeHandler() override;
- void ObservePref(const std::string& pref_name) override;
- void SetPref(const std::string& pref_name,
- const base::Value* value,
- const std::string& metric) override;
- void StopObservingPref(const std::string& path) override;
- std::unique_ptr<base::Value> CreateValueForPref(
- const std::string& pref_name,
- const std::string& controlling_pref_name) override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // content::NotificationObserver implementation.
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
-
- private:
- void OnPreferenceChanged(PrefService* service,
- const std::string& pref_name) override;
-
- // Called from Javascript to select the network to show proxy settings
- // for. Triggers pref notifications about the updated proxy settings.
- void SelectNetworkCallback(const base::ListValue* args);
-
- // Notifies registered JS callbacks on ChromeOS setting change.
- void NotifySettingsChanged(const std::string& setting_name);
- void NotifyProxyPrefsChanged();
-
- // Called on changes to the ownership status. Needed to update the interface
- // in case it has been shown before ownership has been fully established.
- void NotifyOwnershipChanged();
-
- typedef std::map<std::string, linked_ptr<CrosSettings::ObserverSubscription> >
- SubscriptionMap;
- SubscriptionMap pref_subscription_map_;
-
- content::NotificationRegistrar notification_registrar_;
-
- // Currently selected network id.
- std::string network_guid_;
-
- DISALLOW_COPY_AND_ASSIGN(CoreChromeOSOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CORE_CHROMEOS_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.cc
deleted file mode 100644
index 8811f6ac820..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/app/chrome_command_ids.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/extensions/extension_tab_util.h"
-#include "chrome/browser/lifetime/application_lifetime.h"
-#include "chrome/browser/profiles/profile.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/tabs/tab_strip_model.h"
-#include "chrome/browser/ui/webui/chromeos/login/l10n_util.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/user_manager/user_manager.h"
-#include "components/user_manager/user_type.h"
-#include "content/public/browser/navigation_controller.h"
-#include "content/public/browser/web_contents.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/common/extension.h"
-#include "extensions/common/manifest_url_handlers.h"
-#include "ui/base/ime/chromeos/component_extension_ime_manager.h"
-#include "ui/base/ime/chromeos/extension_ime_util.h"
-#include "ui/base/ime/chromeos/input_method_manager.h"
-#include "ui/base/ime/chromeos/input_method_util.h"
-#include "ui/base/l10n/l10n_util.h"
-
-using base::UserMetricsAction;
-
-namespace chromeos {
-namespace options {
-
-CrosLanguageOptionsHandler::CrosLanguageOptionsHandler() {
-}
-
-CrosLanguageOptionsHandler::~CrosLanguageOptionsHandler() {
-}
-
-void CrosLanguageOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- ::options::LanguageOptionsHandlerCommon::GetLocalizedValues(
- localized_strings);
-
- RegisterTitle(localized_strings, "languagePage",
- IDS_OPTIONS_SETTINGS_LANGUAGES_AND_INPUT_DIALOG_TITLE);
- localized_strings->SetString("okButton", l10n_util::GetStringUTF16(IDS_OK));
- localized_strings->SetString("configure",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_CONFIGURE));
- localized_strings->SetString("inputMethod",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD));
- localized_strings->SetString("pleaseAddAnotherInputMethod",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_PLEASE_ADD_ANOTHER_INPUT_METHOD));
- localized_strings->SetString("inputMethodInstructions",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_INSTRUCTIONS));
- localized_strings->SetString("switchInputMethodsHint",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_SWITCH_INPUT_METHODS_HINT));
- localized_strings->SetString("selectPreviousInputMethodHint",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_SELECT_PREVIOUS_INPUT_METHOD_HINT));
- localized_strings->SetString("restartButton",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_SIGN_OUT_BUTTON));
- localized_strings->SetString("extensionImeLable",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_EXTENSION_IME));
- localized_strings->SetString("extensionImeDescription",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_INPUT_METHOD_EXTENSION_DESCRIPTION));
- localized_strings->SetString("noInputMethods",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_NO_INPUT_METHODS));
- localized_strings->SetString("activateImeMenu",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_ACTIVATE_IME_MENU));
-
- // GetSupportedInputMethods() never returns NULL.
- localized_strings->Set("languageList", GetAcceptLanguageList());
- localized_strings->Set("inputMethodList", GetInputMethodList());
-
- input_method::InputMethodManager* manager =
- input_method::InputMethodManager::Get();
- input_method::InputMethodDescriptors ext_ime_descriptors;
- manager->GetActiveIMEState()->GetInputMethodExtensions(&ext_ime_descriptors);
-
- std::unique_ptr<base::ListValue> ext_ime_list =
- ConvertInputMethodDescriptorsToIMEList(ext_ime_descriptors);
- AddImeProvider(ext_ime_list.get());
- localized_strings->Set("extensionImeList", std::move(ext_ime_list));
-
- ComponentExtensionIMEManager* component_extension_manager =
- input_method::InputMethodManager::Get()
- ->GetComponentExtensionIMEManager();
- localized_strings->Set(
- "componentExtensionImeList",
- ConvertInputMethodDescriptorsToIMEList(
- component_extension_manager->GetAllIMEAsInputMethodDescriptor()));
-}
-
-void CrosLanguageOptionsHandler::RegisterMessages() {
- ::options::LanguageOptionsHandlerCommon::RegisterMessages();
-
- web_ui()->RegisterMessageCallback("inputMethodDisable",
- base::Bind(&CrosLanguageOptionsHandler::InputMethodDisableCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("inputMethodEnable",
- base::Bind(&CrosLanguageOptionsHandler::InputMethodEnableCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("inputMethodOptionsOpen",
- base::Bind(&CrosLanguageOptionsHandler::InputMethodOptionsOpenCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("uiLanguageRestart",
- base::Bind(&CrosLanguageOptionsHandler::RestartCallback,
- base::Unretained(this)));
-}
-
-// static
-std::unique_ptr<base::ListValue>
-CrosLanguageOptionsHandler::GetInputMethodList() {
- input_method::InputMethodManager* manager =
- input_method::InputMethodManager::Get();
- // GetSupportedInputMethods() never return NULL.
- std::unique_ptr<input_method::InputMethodDescriptors> descriptors(
- manager->GetSupportedInputMethods());
-
- auto input_method_list = base::MakeUnique<base::ListValue>();
-
- for (size_t i = 0; i < descriptors->size(); ++i) {
- const input_method::InputMethodDescriptor& descriptor =
- (*descriptors)[i];
- const std::string display_name =
- manager->GetInputMethodUtil()->GetInputMethodDisplayNameFromId(
- descriptor.id());
- auto dictionary = base::MakeUnique<base::DictionaryValue>();
- dictionary->SetString("id", descriptor.id());
- dictionary->SetString("displayName", display_name);
-
- // One input method can be associated with multiple languages, hence
- // we use a dictionary here.
- auto languages = base::MakeUnique<base::DictionaryValue>();
- for (size_t i = 0; i < descriptor.language_codes().size(); ++i) {
- languages->SetBoolean(descriptor.language_codes().at(i), true);
- }
- dictionary->Set("languageCodeSet", std::move(languages));
-
- input_method_list->Append(std::move(dictionary));
- }
-
- return input_method_list;
-}
-
-std::unique_ptr<base::ListValue>
-CrosLanguageOptionsHandler::ConvertInputMethodDescriptorsToIMEList(
- const input_method::InputMethodDescriptors& descriptors) {
- input_method::InputMethodUtil* util =
- input_method::InputMethodManager::Get()->GetInputMethodUtil();
- std::unique_ptr<base::ListValue> ime_ids_list(new base::ListValue());
- for (size_t i = 0; i < descriptors.size(); ++i) {
- const input_method::InputMethodDescriptor& descriptor = descriptors[i];
- std::unique_ptr<base::DictionaryValue> dictionary(
- new base::DictionaryValue());
- dictionary->SetString("id", descriptor.id());
- dictionary->SetString(
- "displayName", util->GetLocalizedDisplayName(descriptor));
- dictionary->SetString("optionsPage", descriptor.options_page_url().spec());
- std::unique_ptr<base::DictionaryValue> language_codes(
- new base::DictionaryValue());
- for (size_t i = 0; i < descriptor.language_codes().size(); ++i)
- language_codes->SetBoolean(descriptor.language_codes().at(i), true);
- dictionary->Set("languageCodeSet", std::move(language_codes));
- ime_ids_list->Append(std::move(dictionary));
- }
- return ime_ids_list;
-}
-
-void CrosLanguageOptionsHandler::SetApplicationLocale(
- const std::string& language_code) {
- Profile* profile = Profile::FromWebUI(web_ui());
- user_manager::UserManager* user_manager = user_manager::UserManager::Get();
-
- // Secondary users and public session users cannot change the locale.
- const user_manager::User* user =
- ProfileHelper::Get()->GetUserByProfile(profile);
- if (user &&
- user->GetAccountId() == user_manager->GetPrimaryUser()->GetAccountId() &&
- user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
- profile->ChangeAppLocale(language_code,
- Profile::APP_LOCALE_CHANGED_VIA_SETTINGS);
- }
-}
-
-void CrosLanguageOptionsHandler::RestartCallback(const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("LanguageOptions_SignOut"));
- chrome::AttemptUserExit();
-}
-
-void CrosLanguageOptionsHandler::InputMethodDisableCallback(
- const base::ListValue* args) {
- const std::string input_method_id =
- base::UTF16ToASCII(ExtractStringValue(args));
- const std::string action = base::StringPrintf(
- "LanguageOptions_DisableInputMethod_%s", input_method_id.c_str());
- base::RecordComputedAction(action);
-}
-
-void CrosLanguageOptionsHandler::InputMethodEnableCallback(
- const base::ListValue* args) {
- const std::string input_method_id =
- base::UTF16ToASCII(ExtractStringValue(args));
- const std::string action = base::StringPrintf(
- "LanguageOptions_EnableInputMethod_%s", input_method_id.c_str());
- base::RecordComputedAction(action);
-}
-
-void CrosLanguageOptionsHandler::InputMethodOptionsOpenCallback(
- const base::ListValue* args) {
- const std::string input_method_id =
- base::UTF16ToASCII(ExtractStringValue(args));
- const std::string extension_id =
- extension_ime_util::GetExtensionIDFromInputMethodID(input_method_id);
- if (extension_id.empty())
- return;
-
- const input_method::InputMethodDescriptor* ime =
- input_method::InputMethodManager::Get()
- ->GetActiveIMEState()
- ->GetInputMethodFromId(input_method_id);
- if (!ime)
- return;
-
- Browser* browser = chrome::FindBrowserWithWebContents(
- web_ui()->GetWebContents());
- content::OpenURLParams params(ime->options_page_url(), content::Referrer(),
- WindowOpenDisposition::SINGLETON_TAB,
- ui::PAGE_TRANSITION_LINK, false);
- browser->OpenURL(params);
-}
-
-void CrosLanguageOptionsHandler::AddImeProvider(base::ListValue* list) {
- Profile* profile = Profile::FromWebUI(web_ui());
- const extensions::ExtensionSet& enabled_extensions =
- extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
- for (size_t i = 0; i < list->GetSize(); ++i) {
- base::DictionaryValue* entry;
- list->GetDictionary(i, &entry);
-
- std::string input_method_id;
- entry->GetString("id", &input_method_id);
-
- std::string extension_id =
- extension_ime_util::GetExtensionIDFromInputMethodID(input_method_id);
- const extensions::Extension* extension =
- enabled_extensions.GetByID(extension_id);
- if (extension)
- entry->SetString("extensionName", extension->name());
- }
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h
deleted file mode 100644
index 0a657c14e9a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h
+++ /dev/null
@@ -1,86 +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_OPTIONS_CHROMEOS_CROS_LANGUAGE_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CROS_LANGUAGE_OPTIONS_HANDLER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/language_options_handler.h"
-#include "ui/base/ime/chromeos/component_extension_ime_manager.h"
-#include "ui/base/ime/chromeos/input_method_descriptor.h"
-
-namespace base {
-class ListValue;
-}
-
-namespace chromeos {
-namespace options {
-
-// Language options page UI handler for Chrome OS. For non-Chrome OS,
-// see LanguageOptionsHnadler.
-class CrosLanguageOptionsHandler
- : public ::options::LanguageOptionsHandlerCommon {
- public:
- CrosLanguageOptionsHandler();
- ~CrosLanguageOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // DOMMessageHandler implementation.
- void RegisterMessages() override;
-
- // The following static methods are public for ease of testing.
-
- // Gets the list of supported input methods.
- // The return value will look like:
- // [{'id': 'pinyin', 'displayName': 'Pinyin',
- // 'languageCodeSet': {'zh-CW': true}}, ...]
- //
- // Note that true in languageCodeSet does not mean anything. We just use
- // the dictionary as a set.
- static std::unique_ptr<base::ListValue> GetInputMethodList();
-
- // Converts input method descriptors to the list of input methods.
- // The return value will look like:
- // [{'id': '_ext_ime_nejguenhnsnjnwychcnsdsdjketest',
- // 'displayName': 'Sample IME'}, ...]
- static std::unique_ptr<base::ListValue>
- ConvertInputMethodDescriptorsToIMEList(
- const input_method::InputMethodDescriptors& descriptors);
-
- private:
- // LanguageOptionsHandlerCommon implementation.
- void SetApplicationLocale(const std::string& language_code) override;
-
- // Called when the sign-out button is clicked.
- void RestartCallback(const base::ListValue* args);
-
- // Called when the input method is disabled.
- // |args| will contain the input method ID as string (ex. "mozc").
- void InputMethodDisableCallback(const base::ListValue* args);
-
- // Called when the input method is enabled.
- // |args| will contain the input method ID as string (ex. "mozc").
- void InputMethodEnableCallback(const base::ListValue* args);
-
- // Called when the input method options page is opened.
- // |args| will contain the input method ID as string (ex. "mozc").
- void InputMethodOptionsOpenCallback(const base::ListValue* args);
-
- // Adds the name of the extension that provides the IME to each entry in the
- // |list| of extension IMEs.
- void AddImeProvider(base::ListValue* list);
-
- DISALLOW_COPY_AND_ASSIGN(CrosLanguageOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_CROS_LANGUAGE_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.cc
deleted file mode 100644
index c26fe069f5a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/date_time_options_handler.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/set_time_dialog.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/dbus/dbus_thread_manager.h"
-#include "chromeos/dbus/system_clock_client.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 options {
-
-DateTimeOptionsHandler::DateTimeOptionsHandler()
- : can_set_time_(false), page_initialized_(false) {
-}
-
-DateTimeOptionsHandler::~DateTimeOptionsHandler() {
- DBusThreadManager::Get()->GetSystemClockClient()->RemoveObserver(this);
-}
-
-void DateTimeOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- localized_strings->SetString(
- "setTimeButton",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_SET_TIME_BUTTON));
-}
-
-void DateTimeOptionsHandler::InitializeHandler() {
- SystemClockClient* system_clock_client =
- DBusThreadManager::Get()->GetSystemClockClient();
- system_clock_client->AddObserver(this);
-
- can_set_time_ = system_clock_client->CanSetTime();
- SystemClockCanSetTimeChanged(can_set_time_);
-}
-
-void DateTimeOptionsHandler::InitializePage() {
- page_initialized_ = true;
- SystemClockCanSetTimeChanged(can_set_time_);
-}
-
-void DateTimeOptionsHandler::RegisterMessages() {
- // Callback for set time button.
- web_ui()->RegisterMessageCallback(
- "showSetTime",
- base::Bind(&DateTimeOptionsHandler::HandleShowSetTime,
- base::Unretained(this)));
-}
-
-void DateTimeOptionsHandler::SystemClockCanSetTimeChanged(bool can_set_time) {
- if (page_initialized_) {
- web_ui()->CallJavascriptFunctionUnsafe("BrowserOptions.setCanSetTime",
- base::Value(can_set_time));
- }
- can_set_time_ = can_set_time;
-}
-
-void DateTimeOptionsHandler::HandleShowSetTime(const base::ListValue* args) {
- // Make sure the clock status hasn't changed since the button was clicked.
- if (can_set_time_) {
- SetTimeDialog::ShowDialogInParent(
- web_ui()->GetWebContents()->GetTopLevelNativeWindow());
- }
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.h
deleted file mode 100644
index 8313d8a83ab..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/date_time_options_handler.h
+++ /dev/null
@@ -1,47 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DATE_TIME_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DATE_TIME_OPTIONS_HANDLER_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chromeos/dbus/system_clock_client.h"
-
-namespace chromeos {
-namespace options {
-
-// Chrome OS handler for the set date/time link in the Advanced settings page.
-class DateTimeOptionsHandler : public ::options::OptionsPageUIHandler,
- public SystemClockClient::Observer {
- public:
- DateTimeOptionsHandler();
- ~DateTimeOptionsHandler() override;
-
- // OptionsPageUIHandler:
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- private:
- // SystemClockClient::Observer:
- void SystemClockCanSetTimeChanged(bool can_set_time) override;
-
- // Callback for the "showSetTime" message to show the set time dialog. No
- // arguments are expected.
- void HandleShowSetTime(const base::ListValue* args);
-
- // Only expose the button and dialog if the system time can be set.
- bool can_set_time_;
- bool page_initialized_;
-
- DISALLOW_COPY_AND_ASSIGN(DateTimeOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DATE_TIME_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.cc
deleted file mode 100644
index f18f3b2131e..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.cc
+++ /dev/null
@@ -1,581 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/display_options_handler.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "ash/display/display_configuration_controller.h"
-#include "ash/display/resolution_notification_controller.h"
-#include "ash/display/window_tree_host_manager.h"
-#include "ash/shell.h"
-#include "ash/strings/grit/ash_strings.h"
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/display/display_preferences.h"
-#include "chrome/browser/ui/ash/ash_util.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/chromeos_switches.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/display/display.h"
-#include "ui/display/display_layout.h"
-#include "ui/display/display_layout_builder.h"
-#include "ui/display/manager/display_manager.h"
-#include "ui/display/screen.h"
-#include "ui/display/types/display_constants.h"
-#include "ui/gfx/geometry/rect.h"
-#include "ui/gfx/geometry/size_conversions.h"
-
-namespace chromeos {
-namespace options {
-namespace {
-
-display::DisplayManager* GetDisplayManager() {
- return ash::Shell::Get()->display_manager();
-}
-
-ash::DisplayConfigurationController* GetDisplayConfigurationController() {
- return ash::Shell::Get()->display_configuration_controller();
-}
-
-int64_t GetDisplayIdFromValue(const base::Value* arg) {
- std::string id_value;
- if (!arg->GetAsString(&id_value))
- return display::kInvalidDisplayId;
- int64_t display_id = display::kInvalidDisplayId;
- if (!base::StringToInt64(id_value, &display_id))
- return display::kInvalidDisplayId;
- return display_id;
-}
-
-int64_t GetDisplayIdFromArgs(const base::ListValue* args) {
- const base::Value* arg;
- if (!args->Get(0, &arg)) {
- LOG(ERROR) << "No display id arg";
- return display::kInvalidDisplayId;
- }
- int64_t display_id = GetDisplayIdFromValue(arg);
- if (display_id == display::kInvalidDisplayId)
- LOG(ERROR) << "Invalid display id: " << *arg;
- return display_id;
-}
-
-int64_t GetDisplayIdFromDictionary(const base::DictionaryValue* dictionary,
- const std::string& key) {
- const base::Value* arg;
- if (!dictionary->Get(key, &arg))
- return display::kInvalidDisplayId;
- return GetDisplayIdFromValue(arg);
-}
-
-base::string16 GetColorProfileName(display::ColorCalibrationProfile profile) {
- switch (profile) {
- case display::COLOR_PROFILE_STANDARD:
- return l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_COLOR_PROFILE_STANDARD);
- case display::COLOR_PROFILE_DYNAMIC:
- return l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_COLOR_PROFILE_DYNAMIC);
- case display::COLOR_PROFILE_MOVIE:
- return l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_COLOR_PROFILE_MOVIE);
- case display::COLOR_PROFILE_READING:
- return l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_COLOR_PROFILE_READING);
- case display::NUM_COLOR_PROFILES:
- break;
- }
-
- NOTREACHED();
- return base::string16();
-}
-
-int GetIntOrDouble(const base::DictionaryValue* dict,
- const std::string& field) {
- double double_result = 0;
- if (dict->GetDouble(field, &double_result))
- return static_cast<int>(double_result);
-
- int result = 0;
- dict->GetInteger(field, &result);
- return result;
-}
-
-bool GetFloat(const base::DictionaryValue* dict,
- const std::string& field,
- float* result) {
- double double_result = 0;
- if (dict->GetDouble(field, &double_result)) {
- *result = static_cast<float>(double_result);
- return true;
- }
- return false;
-}
-
-scoped_refptr<display::ManagedDisplayMode> ConvertValueToManagedDisplayMode(
- const base::DictionaryValue* dict) {
- scoped_refptr<display::ManagedDisplayMode> mode;
-
- gfx::Size size;
- size.set_width(GetIntOrDouble(dict, "originalWidth"));
- size.set_height(GetIntOrDouble(dict, "originalHeight"));
-
- if (size.IsEmpty()) {
- LOG(ERROR) << "missing width or height.";
- return mode;
- }
-
- float refresh_rate, ui_scale, device_scale_factor;
- if (!GetFloat(dict, "refreshRate", &refresh_rate)) {
- LOG(ERROR) << "missing refreshRate.";
- return mode;
- }
- if (!GetFloat(dict, "scale", &ui_scale)) {
- LOG(ERROR) << "missing ui-scale.";
- return mode;
- }
- if (!GetFloat(dict, "deviceScaleFactor", &device_scale_factor)) {
- LOG(ERROR) << "missing deviceScaleFactor.";
- return mode;
- }
-
- // Used to select the actual mode.
- mode = new display::ManagedDisplayMode(
- size, refresh_rate, false /* interlaced */, false /* native */, ui_scale,
- device_scale_factor);
- return mode;
-}
-
-std::unique_ptr<base::DictionaryValue> ConvertDisplayModeToValue(
- int64_t display_id,
- const scoped_refptr<display::ManagedDisplayMode>& mode) {
- bool is_internal = display::Display::HasInternalDisplay() &&
- display::Display::InternalDisplayId() == display_id;
- auto result = base::MakeUnique<base::DictionaryValue>();
- gfx::Size size_dip = mode->GetSizeInDIP(is_internal);
- result->SetInteger("width", size_dip.width());
- result->SetInteger("height", size_dip.height());
- result->SetInteger("originalWidth", mode->size().width());
- result->SetInteger("originalHeight", mode->size().height());
- result->SetDouble("deviceScaleFactor", mode->device_scale_factor());
- result->SetDouble("scale", mode->ui_scale());
- result->SetDouble("refreshRate", mode->refresh_rate());
- result->SetBoolean("isBest",
- is_internal ? (mode->ui_scale() == 1.0f) : mode->native());
- result->SetBoolean("isNative", mode->native());
- result->SetBoolean(
- "selected",
- mode->IsEquivalent(
- GetDisplayManager()->GetActiveModeForDisplayId(display_id)));
- return result;
-}
-
-std::unique_ptr<base::DictionaryValue> ConvertBoundsToValue(
- const gfx::Rect& bounds) {
- auto result = base::MakeUnique<base::DictionaryValue>();
- result->SetInteger("left", bounds.x());
- result->SetInteger("top", bounds.y());
- result->SetInteger("width", bounds.width());
- result->SetInteger("height", bounds.height());
- return result;
-}
-
-} // namespace
-
-DisplayOptionsHandler::DisplayOptionsHandler() {
- // TODO(mash) Support Chrome display settings in Mash. crbug.com/548429
- if (!ash_util::IsRunningInMash())
- ash::Shell::Get()->window_tree_host_manager()->AddObserver(this);
-}
-
-DisplayOptionsHandler::~DisplayOptionsHandler() {
- // TODO(mash) Support Chrome display settings in Mash. crbug.com/548429
- if (!ash_util::IsRunningInMash())
- ash::Shell::Get()->window_tree_host_manager()->RemoveObserver(this);
-}
-
-void DisplayOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- RegisterTitle(localized_strings, "displayOptionsPage",
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_TAB_TITLE);
-
- localized_strings->SetString(
- "selectedDisplayTitleOptions", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_OPTIONS));
- localized_strings->SetString(
- "selectedDisplayTitleResolution", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_RESOLUTION));
- localized_strings->SetString(
- "selectedDisplayTitleOrientation", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_ORIENTATION));
- localized_strings->SetString(
- "selectedDisplayTitleOverscan", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_OVERSCAN));
-
- localized_strings->SetString("extendedMode", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_EXTENDED_MODE_LABEL));
- localized_strings->SetString("mirroringMode", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_MIRRORING_MODE_LABEL));
- localized_strings->SetString("mirroringDisplay", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_MIRRORING_DISPLAY_NAME));
- localized_strings->SetString("setPrimary", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_SET_PRIMARY));
- localized_strings->SetString("annotateBest", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_RESOLUTION_ANNOTATION_BEST));
- localized_strings->SetString("annotateNative", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_RESOLUTION_ANNOTATION_NATIVE));
- localized_strings->SetString("orientation0", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_STANDARD_ORIENTATION));
- localized_strings->SetString("orientation90", l10n_util::GetStringUTF16(
- IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90));
- localized_strings->SetString("orientation180", l10n_util::GetStringUTF16(
- IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180));
- localized_strings->SetString("orientation270", l10n_util::GetStringUTF16(
- IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270));
- localized_strings->SetString(
- "startCalibratingOverscan", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_START_CALIBRATING_OVERSCAN));
- localized_strings->SetString(
- "selectedDisplayColorProfile", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_COLOR_PROFILE));
- localized_strings->SetString(
- "enableUnifiedDesktop",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_ENABLE_UNIFIED_DESKTOP));
-}
-
-void DisplayOptionsHandler::InitializePage() {
- DCHECK(web_ui());
- UpdateDisplaySettingsEnabled();
-}
-
-void DisplayOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "getDisplayInfo",
- base::Bind(&DisplayOptionsHandler::HandleDisplayInfo,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setMirroring",
- base::Bind(&DisplayOptionsHandler::HandleMirroring,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setPrimary",
- base::Bind(&DisplayOptionsHandler::HandleSetPrimary,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setDisplayLayout",
- base::Bind(&DisplayOptionsHandler::HandleSetDisplayLayout,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setDisplayMode",
- base::Bind(&DisplayOptionsHandler::HandleSetDisplayMode,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setRotation",
- base::Bind(&DisplayOptionsHandler::HandleSetRotation,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setColorProfile",
- base::Bind(&DisplayOptionsHandler::HandleSetColorProfile,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "setUnifiedDesktopEnabled",
- base::Bind(&DisplayOptionsHandler::HandleSetUnifiedDesktopEnabled,
- base::Unretained(this)));
-}
-
-void DisplayOptionsHandler::OnDisplayConfigurationChanging() {
-}
-
-void DisplayOptionsHandler::OnDisplayConfigurationChanged() {
- UpdateDisplaySettingsEnabled();
- SendAllDisplayInfo();
-}
-
-void DisplayOptionsHandler::SendAllDisplayInfo() {
- display::DisplayManager* display_manager = GetDisplayManager();
-
- std::vector<display::Display> displays;
- for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i)
- displays.push_back(display_manager->GetDisplayAt(i));
-
- display::DisplayManager::MultiDisplayMode display_mode;
- if (display_manager->IsInMirrorMode())
- display_mode = display::DisplayManager::MIRRORING;
- else if (display_manager->IsInUnifiedMode())
- display_mode = display::DisplayManager::UNIFIED;
- else
- display_mode = display::DisplayManager::EXTENDED;
- base::Value mode(static_cast<int>(display_mode));
-
- int64_t primary_id = display::Screen::GetScreen()->GetPrimaryDisplay().id();
- std::unique_ptr<base::ListValue> js_displays(new base::ListValue);
- for (const display::Display& display : displays) {
- const display::ManagedDisplayInfo& display_info =
- display_manager->GetDisplayInfo(display.id());
- auto js_display = base::MakeUnique<base::DictionaryValue>();
- js_display->SetString("id", base::Int64ToString(display.id()));
- js_display->SetString("name",
- display_manager->GetDisplayNameForId(display.id()));
- js_display->Set("bounds", ConvertBoundsToValue(display.bounds()));
- js_display->SetBoolean("isPrimary", display.id() == primary_id);
- js_display->SetBoolean("isInternal", display.IsInternal());
- js_display->SetInteger("rotation", display.RotationAsDegree());
-
- auto js_resolutions = base::MakeUnique<base::ListValue>();
- for (const scoped_refptr<display::ManagedDisplayMode>& display_mode :
- display_info.display_modes()) {
- js_resolutions->Append(
- ConvertDisplayModeToValue(display.id(), display_mode));
- }
- js_display->Set("resolutions", std::move(js_resolutions));
-
- js_display->SetInteger("colorProfileId", display_info.color_profile());
- auto available_color_profiles = base::MakeUnique<base::ListValue>();
- for (const auto& color_profile : display_info.available_color_profiles()) {
- const base::string16 profile_name = GetColorProfileName(color_profile);
- if (profile_name.empty())
- continue;
- auto color_profile_dict = base::MakeUnique<base::DictionaryValue>();
- color_profile_dict->SetInteger("profileId", color_profile);
- color_profile_dict->SetString("name", profile_name);
- available_color_profiles->Append(std::move(color_profile_dict));
- }
- js_display->Set("availableColorProfiles",
- std::move(available_color_profiles));
-
- if (display_manager->GetNumDisplays() > 1) {
- // The settings UI must use the resolved display layout to show the
- // actual applied layout.
- const display::DisplayPlacement placement =
- display_manager->GetCurrentResolvedDisplayLayout().FindPlacementById(
- display.id());
- if (placement.display_id != display::kInvalidDisplayId) {
- js_display->SetString(
- "parentId", base::Int64ToString(placement.parent_display_id));
- js_display->SetInteger("layoutType", placement.position);
- js_display->SetInteger("offset", placement.offset);
- }
- }
-
- js_displays->Append(std::move(js_display));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.DisplayOptions.setDisplayInfo", mode, *js_displays);
-}
-
-void DisplayOptionsHandler::UpdateDisplaySettingsEnabled() {
- // TODO(mash) Support Chrome display settings in Mash. crbug.com/548429
- if (ash_util::IsRunningInMash())
- return;
-
- display::DisplayManager* display_manager = GetDisplayManager();
- bool disable_multi_display_layout =
- base::CommandLine::ForCurrentProcess()->HasSwitch(
- chromeos::switches::kDisableMultiDisplayLayout);
- bool ui_enabled = display_manager->num_connected_displays() <= 2 ||
- !disable_multi_display_layout;
- bool unified_enabled = display_manager->unified_desktop_enabled();
- bool mirrored_enabled = display_manager->num_connected_displays() == 2;
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.BrowserOptions.enableDisplaySettings", base::Value(ui_enabled),
- base::Value(unified_enabled), base::Value(mirrored_enabled));
-}
-
-void DisplayOptionsHandler::HandleDisplayInfo(
- const base::ListValue* unused_args) {
- SendAllDisplayInfo();
-}
-
-void DisplayOptionsHandler::HandleMirroring(const base::ListValue* args) {
- DCHECK(!args->empty());
- bool is_mirroring = false;
- if (!args->GetBoolean(0, &is_mirroring))
- NOTREACHED();
- base::RecordAction(base::UserMetricsAction("Options_DisplayToggleMirroring"));
- GetDisplayConfigurationController()->SetMirrorMode(is_mirroring);
-}
-
-void DisplayOptionsHandler::HandleSetPrimary(const base::ListValue* args) {
- DCHECK(!args->empty());
- int64_t display_id = GetDisplayIdFromArgs(args);
- if (display_id == display::kInvalidDisplayId)
- return;
-
- base::RecordAction(base::UserMetricsAction("Options_DisplaySetPrimary"));
- GetDisplayConfigurationController()->SetPrimaryDisplayId(display_id);
-}
-
-void DisplayOptionsHandler::HandleSetDisplayLayout(
- const base::ListValue* args) {
- const base::ListValue* layouts = nullptr;
- if (!args->GetList(0, &layouts))
- NOTREACHED();
- base::RecordAction(base::UserMetricsAction("Options_DisplayRearrange"));
-
- display::DisplayManager* display_manager = GetDisplayManager();
- display::DisplayLayoutBuilder builder(
- display_manager->GetCurrentDisplayLayout());
- builder.ClearPlacements();
- for (const auto& layout : *layouts) {
- const base::DictionaryValue* dictionary;
- if (!layout.GetAsDictionary(&dictionary)) {
- LOG(ERROR) << "Invalid layout dictionary: " << *dictionary;
- continue;
- }
-
- int64_t parent_id = GetDisplayIdFromDictionary(dictionary, "parentId");
- if (parent_id == display::kInvalidDisplayId)
- continue; // No placement for root (primary) display.
-
- int64_t display_id = GetDisplayIdFromDictionary(dictionary, "id");
- if (display_id == display::kInvalidDisplayId) {
- LOG(ERROR) << "Invalud display id in layout dictionary: " << *dictionary;
- continue;
- }
-
- int position = 0;
- dictionary->GetInteger("layoutType", &position);
- int offset = 0;
- dictionary->GetInteger("offset", &offset);
-
- builder.AddDisplayPlacement(
- display_id, parent_id,
- static_cast<display::DisplayPlacement::Position>(position), offset);
- }
- std::unique_ptr<display::DisplayLayout> layout = builder.Build();
- if (!display::DisplayLayout::Validate(
- display_manager->GetCurrentDisplayIdList(), *layout)) {
- LOG(ERROR) << "Invalid layout: " << layout->ToString();
- return;
- }
-
- VLOG(1) << "Updating display layout: " << layout->ToString();
- GetDisplayConfigurationController()->SetDisplayLayout(std::move(layout));
-}
-
-void DisplayOptionsHandler::HandleSetDisplayMode(const base::ListValue* args) {
- DCHECK(!args->empty());
-
- int64_t display_id = GetDisplayIdFromArgs(args);
- if (display_id == display::kInvalidDisplayId)
- return;
-
- const base::DictionaryValue* mode_data = nullptr;
- if (!args->GetDictionary(1, &mode_data)) {
- LOG(ERROR) << "Failed to get mode data";
- return;
- }
-
- scoped_refptr<display::ManagedDisplayMode> mode =
- ConvertValueToManagedDisplayMode(mode_data);
- if (!mode)
- return;
-
- base::RecordAction(base::UserMetricsAction("Options_DisplaySetResolution"));
- display::DisplayManager* display_manager = GetDisplayManager();
- scoped_refptr<display::ManagedDisplayMode> current_mode =
- display_manager->GetActiveModeForDisplayId(display_id);
-
- if (mode->IsEquivalent(current_mode)) {
- LOG(ERROR) << "New display mode matches current mode.";
- return;
- }
-
- if (!ash::Shell::Get()
- ->resolution_notification_controller()
- ->PrepareNotificationAndSetDisplayMode(
- display_id, current_mode, mode,
- base::Bind(&chromeos::StoreDisplayPrefs))) {
- LOG(ERROR) << "Unable to set display mode for: " << display_id
- << " Mode: " << *mode_data;
- }
-}
-
-void DisplayOptionsHandler::HandleSetRotation(const base::ListValue* args) {
- DCHECK(!args->empty());
-
- int64_t display_id = GetDisplayIdFromArgs(args);
- if (display_id == display::kInvalidDisplayId)
- return;
-
- int rotation_value = 0;
- if (!args->GetInteger(1, &rotation_value)) {
- LOG(ERROR) << "Can't parse rotation: " << args;
- return;
- }
- display::Display::Rotation new_rotation = display::Display::ROTATE_0;
- if (rotation_value == 90)
- new_rotation = display::Display::ROTATE_90;
- else if (rotation_value == 180)
- new_rotation = display::Display::ROTATE_180;
- else if (rotation_value == 270)
- new_rotation = display::Display::ROTATE_270;
- else if (rotation_value != 0)
- LOG(ERROR) << "Invalid rotation: " << rotation_value << " Falls back to 0";
-
- base::RecordAction(base::UserMetricsAction("Options_DisplaySetOrientation"));
- GetDisplayConfigurationController()->SetDisplayRotation(
- display_id, new_rotation, display::Display::ROTATION_SOURCE_USER);
-}
-
-void DisplayOptionsHandler::HandleSetColorProfile(const base::ListValue* args) {
- DCHECK(!args->empty());
- int64_t display_id = GetDisplayIdFromArgs(args);
- if (display_id == display::kInvalidDisplayId)
- return;
-
- std::string profile_value;
- if (!args->GetString(1, &profile_value)) {
- LOG(ERROR) << "Invalid profile_value";
- return;
- }
-
- int profile_id;
- if (!base::StringToInt(profile_value, &profile_id)) {
- LOG(ERROR) << "Invalid profile: " << profile_value;
- return;
- }
-
- if (profile_id < display::COLOR_PROFILE_STANDARD ||
- profile_id > display::COLOR_PROFILE_READING) {
- LOG(ERROR) << "Invalid profile_id: " << profile_id;
- return;
- }
-
- base::RecordAction(base::UserMetricsAction("Options_DisplaySetColorProfile"));
- GetDisplayManager()->SetColorCalibrationProfile(
- display_id, static_cast<display::ColorCalibrationProfile>(profile_id));
-
- SendAllDisplayInfo();
-}
-
-void DisplayOptionsHandler::HandleSetUnifiedDesktopEnabled(
- const base::ListValue* args) {
- DCHECK(GetDisplayManager()->unified_desktop_enabled());
- bool enable = false;
- if (!args->GetBoolean(0, &enable))
- NOTREACHED();
-
- GetDisplayManager()->SetDefaultMultiDisplayModeForCurrentDisplays(
- enable ? display::DisplayManager::UNIFIED
- : display::DisplayManager::EXTENDED);
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.h
deleted file mode 100644
index 3f93b9a64b6..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/display_options_handler.h
+++ /dev/null
@@ -1,63 +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_OPTIONS_CHROMEOS_DISPLAY_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DISPLAY_OPTIONS_HANDLER_H_
-
-#include <vector>
-
-#include "ash/display/window_tree_host_manager.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace chromeos {
-namespace options {
-
-// Display options overlay page UI handler.
-class DisplayOptionsHandler : public ::options::OptionsPageUIHandler,
- public ash::WindowTreeHostManager::Observer {
- public:
- DisplayOptionsHandler();
- ~DisplayOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // ash::WindowTreeHostManager::Observer implementation.
- void OnDisplayConfigurationChanging() override;
- void OnDisplayConfigurationChanged() override;
-
- private:
- // Sends all of the current display information to the web_ui of options page.
- void SendAllDisplayInfo();
-
- // Enables or disables the display settings UI.
- void UpdateDisplaySettingsEnabled();
-
- // Handlers of JS messages.
- void HandleDisplayInfo(const base::ListValue* unused_args);
- void HandleMirroring(const base::ListValue* args);
- void HandleSetPrimary(const base::ListValue* args);
- void HandleSetDisplayLayout(const base::ListValue* args);
- void HandleSetDisplayMode(const base::ListValue* args);
- void HandleSetRotation(const base::ListValue* args);
- void HandleSetColorProfile(const base::ListValue* args);
- void HandleSetUnifiedDesktopEnabled(const base::ListValue* args);
-
- DISALLOW_COPY_AND_ASSIGN(DisplayOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DISPLAY_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.cc
deleted file mode 100644
index 9616d7e97d0..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.cc
+++ /dev/null
@@ -1,211 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/display_overscan_handler.h"
-
-#include <string>
-
-#include "ash/display/window_tree_host_manager.h"
-#include "ash/shell.h"
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/display/overscan_calibrator.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/display/display.h"
-#include "ui/display/manager/display_manager.h"
-#include "ui/display/screen.h"
-#include "ui/display/types/display_constants.h"
-
-namespace chromeos {
-namespace options {
-namespace {
-
-// The value for the orientation of overscan operations.
-const char kOrientationHorizontal[] = "horizontal";
-const char kOrientationVertical[] = "vertical";
-
-}
-
-DisplayOverscanHandler::DisplayOverscanHandler() {
- display::Screen::GetScreen()->AddObserver(this);
-}
-
-DisplayOverscanHandler::~DisplayOverscanHandler() {
- display::Screen::GetScreen()->RemoveObserver(this);
-}
-
-void DisplayOverscanHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- RegisterTitle(localized_strings, "displayOverscanPage",
- IDS_OPTIONS_SETTINGS_DISPLAY_OVERSCAN_TAB_TITLE);
- localized_strings->SetString("shrinkAndExpand", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OVERSCAN_SHRINK_EXPAND));
- localized_strings->SetString("move", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OVERSCAN_MOVE));
- localized_strings->SetString("overscanReset", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OVERSCAN_RESET_BUTTON_LABEL));
- localized_strings->SetString("overscanOK", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OVERSCAN_OK_BUTTON_LABEL));
- localized_strings->SetString("overscanCancel", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_DISPLAY_OVERSCAN_CANCEL_BUTTON_LABEL));
-}
-
-void DisplayOverscanHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "start",
- base::Bind(&DisplayOverscanHandler::HandleStart,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "commit",
- base::Bind(&DisplayOverscanHandler::HandleCommit,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "reset",
- base::Bind(&DisplayOverscanHandler::HandleReset,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "cancel",
- base::Bind(&DisplayOverscanHandler::HandleCancel,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "move",
- base::Bind(&DisplayOverscanHandler::HandleMove,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "resize",
- base::Bind(&DisplayOverscanHandler::HandleResize,
- base::Unretained(this)));
-}
-
-void DisplayOverscanHandler::OnDisplayAdded(
- const display::Display& new_display) {
- if (!overscan_calibrator_)
- return;
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.DisplayOverscan.onOverscanCanceled");
-}
-
-void DisplayOverscanHandler::OnDisplayRemoved(
- const display::Display& old_display) {
- if (!overscan_calibrator_)
- return;
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.DisplayOverscan.onOverscanCanceled");
-}
-
-void DisplayOverscanHandler::OnDisplayMetricsChanged(const display::Display&,
- uint32_t) {}
-
-void DisplayOverscanHandler::HandleStart(const base::ListValue* args) {
- int64_t display_id = display::kInvalidDisplayId;
- std::string id_value;
- if (!args->GetString(0, &id_value)) {
- LOG(ERROR) << "Can't find ID";
- return;
- }
-
- if (!base::StringToInt64(id_value, &display_id) ||
- display_id == display::kInvalidDisplayId) {
- LOG(ERROR) << "Invalid parameter: " << id_value;
- return;
- }
-
- const display::Display& display =
- ash::Shell::Get()->display_manager()->GetDisplayForId(display_id);
- DCHECK(display.is_valid());
- if (!display.is_valid())
- return;
-
- ash::WindowTreeHostManager* window_tree_host_manager =
- ash::Shell::Get()->window_tree_host_manager();
- overscan_calibrator_.reset(new OverscanCalibrator(
- display, window_tree_host_manager->GetOverscanInsets(display_id)));
-}
-
-void DisplayOverscanHandler::HandleCommit(const base::ListValue* unused_args) {
- if (overscan_calibrator_.get()) {
- overscan_calibrator_->Commit();
- overscan_calibrator_.reset();
- }
-}
-
-void DisplayOverscanHandler::HandleReset(const base::ListValue* unused_args) {
- if (overscan_calibrator_.get())
- overscan_calibrator_->Reset();
-}
-
-void DisplayOverscanHandler::HandleCancel(const base::ListValue* unused_args) {
- overscan_calibrator_.reset();
-}
-
-void DisplayOverscanHandler::HandleMove(const base::ListValue* args) {
- std::string orientation;
- double length;
- if (!args->GetString(0, &orientation)) {
- LOG(ERROR) << "The first argument must be orientation";
- return;
- }
- if (!args->GetDouble(1, &length)) {
- LOG(ERROR) << "The second argument must be a numeric";
- return;
- }
-
- if (!overscan_calibrator_.get())
- return;
-
- gfx::Insets insets = overscan_calibrator_->insets();
- if (orientation == kOrientationHorizontal) {
- insets.Set(insets.top(), insets.left() + length,
- insets.bottom(), insets.right() - length);
- } else if (orientation == kOrientationVertical) {
- insets.Set(insets.top() + length, insets.left(),
- insets.bottom() - length, insets.right());
- } else {
- LOG(ERROR) << "The orientation must be '" << kOrientationHorizontal
- << "' or '" << kOrientationVertical << "': "
- << orientation;
- return;
- }
- overscan_calibrator_->UpdateInsets(insets);
-}
-
-void DisplayOverscanHandler::HandleResize(const base::ListValue* args) {
- std::string orientation;
- double length;
- if (!args->GetString(0, &orientation)) {
- LOG(ERROR) << "The first argument must be orientation";
- return;
- }
- if (!args->GetDouble(1, &length)) {
- LOG(ERROR) << "The second argument must be a numeric";
- return;
- }
-
- if (!overscan_calibrator_.get())
- return;
-
- gfx::Insets insets = overscan_calibrator_->insets();
- if (orientation == kOrientationHorizontal) {
- insets.Set(insets.top(), insets.left() + length,
- insets.bottom(), insets.right() + length);
- } else if (orientation == kOrientationVertical) {
- insets.Set(insets.top() + length, insets.left(),
- insets.bottom() + length, insets.right());
- } else {
- LOG(ERROR) << "The orientation must be '" << kOrientationHorizontal
- << "' or '" << kOrientationVertical << "': "
- << orientation;
- return;
- }
- overscan_calibrator_->UpdateInsets(insets);
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.h
deleted file mode 100644
index d46e527515c..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/display_overscan_handler.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DISPLAY_OVERSCAN_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DISPLAY_OVERSCAN_HANDLER_H_
-
-#include <stdint.h>
-
-#include <memory>
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "ui/display/display_observer.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace chromeos {
-class OverscanCalibrator;
-
-namespace options {
-
-// Display options overlay page UI handler.
-class DisplayOverscanHandler : public ::options::OptionsPageUIHandler,
- public display::DisplayObserver {
- public:
- DisplayOverscanHandler();
- ~DisplayOverscanHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // display::DisplayObserver implementation.
- void OnDisplayAdded(const display::Display& new_display) override;
- void OnDisplayRemoved(const display::Display& old_display) override;
- void OnDisplayMetricsChanged(const display::Display& display,
- uint32_t metrics) override;
-
- private:
- // Handlers of JS messages.
- void HandleStart(const base::ListValue* args);
- void HandleCommit(const base::ListValue* unused_args);
- void HandleReset(const base::ListValue* unused_args);
- void HandleCancel(const base::ListValue* unused_args);
- void HandleMove(const base::ListValue* args);
- void HandleResize(const base::ListValue* args);
-
- std::unique_ptr<OverscanCalibrator> overscan_calibrator_;
-
- DISALLOW_COPY_AND_ASSIGN(DisplayOverscanHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_DISPLAY_OVERSCAN_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc
deleted file mode 100644
index 75dab74707b..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/internet_options_handler.h"
-
-#include <ctype.h>
-
-#include <map>
-#include <string>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/enrollment_dialog_view.h"
-#include "chrome/browser/chromeos/mobile_config.h"
-#include "chrome/browser/chromeos/options/network_config_view.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/chromeos/settings/cros_settings.h"
-#include "chrome/browser/chromeos/sim_dialog_delegate.h"
-#include "chrome/browser/chromeos/ui/choose_mobile_network_dialog.h"
-#include "chrome/browser/chromeos/ui/mobile_config_ui.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h"
-#include "chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h"
-#include "chromeos/login/login_state.h"
-#include "chromeos/network/managed_network_configuration_handler.h"
-#include "chromeos/network/network_connect.h"
-#include "chromeos/network/network_state.h"
-#include "chromeos/network/network_state_handler.h"
-#include "components/onc/onc_constants.h"
-#include "components/user_manager/user_manager.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_ui.h"
-#include "extensions/browser/api/vpn_provider/vpn_service.h"
-#include "extensions/browser/api/vpn_provider/vpn_service_factory.h"
-#include "third_party/cros_system_api/dbus/service_constants.h"
-#include "ui/base/webui/web_ui_util.h"
-
-namespace chromeos {
-namespace options {
-
-namespace {
-
-const char kAllowOnlyPolicyNetworksToConnect[] =
- "allowOnlyPolicyNetworksToConnect";
-
-// Keys for the initial "localized" dictionary values.
-const char kLoggedInAsOwnerKey[] = "loggedInAsOwner";
-
-// JS methods to show additional UI.
-const char kShowMorePlanInfoMessage[] = "showMorePlanInfo";
-const char kSimOperationMessage[] = "simOperation";
-
-// TODO(stevenjb): Deprecate these and integrate with settings Web UI.
-const char kAddVPNConnectionMessage[] = "addVPNConnection";
-const char kAddNonVPNConnectionMessage[] = "addNonVPNConnection";
-const char kConfigureNetworkMessage[] = "configureNetwork";
-
-// These are strings used to communicate with JavaScript.
-const char kTagSimOpChangePin[] = "changePin";
-const char kTagSimOpConfigure[] = "configure";
-const char kTagSimOpSetLocked[] = "setLocked";
-const char kTagSimOpSetUnlocked[] = "setUnlocked";
-const char kTagSimOpUnlock[] = "unlock";
-
-Profile* GetProfileForPrimaryUser() {
- return chromeos::ProfileHelper::Get()->GetProfileByUser(
- user_manager::UserManager::Get()->GetPrimaryUser());
-}
-
-} // namespace
-
-InternetOptionsHandler::InternetOptionsHandler()
- : weak_factory_(this) {
-}
-
-InternetOptionsHandler::~InternetOptionsHandler() {
-}
-
-void InternetOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- internet_options_strings::RegisterLocalizedStrings(localized_strings);
-
- // TODO(stevenjb): Find a better way to populate initial data.
- std::string owner;
- chromeos::CrosSettings::Get()->GetString(chromeos::kDeviceOwner, &owner);
- bool logged_in_as_owner = LoginState::Get()->GetLoggedInUserType() ==
- LoginState::LOGGED_IN_USER_OWNER;
- localized_strings->SetBoolean(kLoggedInAsOwnerKey, logged_in_as_owner);
-
- // TODO(fqj/stevenjb): Make this a property of networkingPrivate
- const base::DictionaryValue* global_network_config =
- NetworkHandler::Get()
- ->managed_network_configuration_handler()
- ->GetGlobalConfigFromPolicy(
- std::string() /* no user hash, device policy*/);
- if (global_network_config) {
- bool only_policy_connect = false;
- global_network_config->GetBooleanWithoutPathExpansion(
- ::onc::global_network_config::kAllowOnlyPolicyNetworksToConnect,
- &only_policy_connect);
- localized_strings->SetBoolean(kAllowOnlyPolicyNetworksToConnect,
- only_policy_connect);
- }
-}
-
-void InternetOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(kAddVPNConnectionMessage,
- base::Bind(&InternetOptionsHandler::AddVPNConnection,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(kAddNonVPNConnectionMessage,
- base::Bind(&InternetOptionsHandler::AddNonVPNConnection,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(kConfigureNetworkMessage,
- base::Bind(&InternetOptionsHandler::ConfigureNetwork,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(kShowMorePlanInfoMessage,
- base::Bind(&InternetOptionsHandler::ShowMorePlanInfoCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(kSimOperationMessage,
- base::Bind(&InternetOptionsHandler::SimOperationCallback,
- base::Unretained(this)));
-}
-
-void InternetOptionsHandler::ShowMorePlanInfoCallback(
- const base::ListValue* args) {
- if (!web_ui())
- return;
- std::string guid;
- if (args->GetSize() != 1 || !args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
- NetworkConnect::Get()->ShowMobileSetup(guid);
-}
-
-void InternetOptionsHandler::SimOperationCallback(const base::ListValue* args) {
- std::string operation;
- if (args->GetSize() != 1 || !args->GetString(0, &operation)) {
- NOTREACHED();
- return;
- }
- if (operation == kTagSimOpConfigure) {
- mobile_config_ui::DisplayConfigDialog();
- return;
- }
- // 1. Bring up SIM unlock dialog, pass new RequirePin setting in URL.
- // 2. Dialog will ask for current PIN in any case.
- // 3. If card is locked it will first call PIN unlock operation
- // 4. Then it will call Set RequirePin, passing the same PIN.
- // 5. The dialog may change device properties, in which case
- // DevicePropertiesUpdated() will get called which will update the UI.
- SimDialogDelegate::SimDialogMode mode;
- if (operation == kTagSimOpSetLocked) {
- mode = SimDialogDelegate::SIM_DIALOG_SET_LOCK_ON;
- } else if (operation == kTagSimOpSetUnlocked) {
- mode = SimDialogDelegate::SIM_DIALOG_SET_LOCK_OFF;
- } else if (operation == kTagSimOpUnlock) {
- mode = SimDialogDelegate::SIM_DIALOG_UNLOCK;
- } else if (operation == kTagSimOpChangePin) {
- mode = SimDialogDelegate::SIM_DIALOG_CHANGE_PIN;
- } else {
- NOTREACHED();
- return;
- }
- SimDialogDelegate::ShowDialog(GetNativeWindow(), mode);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-gfx::NativeWindow InternetOptionsHandler::GetNativeWindow() const {
- return web_ui()->GetWebContents()->GetTopLevelNativeWindow();
-}
-
-const PrefService* InternetOptionsHandler::GetPrefs() const {
- return Profile::FromWebUI(web_ui())->GetPrefs();
-}
-
-
-void InternetOptionsHandler::AddVPNConnection(const base::ListValue* args) {
- if (args->empty()) {
- // Show the "add network" dialog for the built-in OpenVPN/L2TP provider.
- NetworkConfigView::ShowForType(shill::kTypeVPN);
- return;
- }
-
- std::string extension_id;
- if (args->GetSize() != 1 || !args->GetString(0, &extension_id)) {
- NOTREACHED();
- return;
- }
-
- // Request that the third-party VPN provider identified by |provider_id|
- // show its "add network" dialog.
- chromeos::VpnServiceFactory::GetForBrowserContext(
- GetProfileForPrimaryUser())->SendShowAddDialogToExtension(extension_id);
-}
-
-void InternetOptionsHandler::AddNonVPNConnection(const base::ListValue* args) {
- std::string onc_type;
- if (args->GetSize() != 1 || !args->GetString(0, &onc_type)) {
- NOTREACHED();
- return;
- }
- if (onc_type == ::onc::network_type::kWiFi) {
- NetworkConfigView::ShowForType(shill::kTypeWifi);
- } else if (onc_type == ::onc::network_type::kCellular) {
- ChooseMobileNetworkDialog::ShowDialog(GetNativeWindow());
- } else {
- LOG(ERROR) << "Unsupported type for AddConnection";
- }
-}
-
-void InternetOptionsHandler::ConfigureNetwork(const base::ListValue* args) {
- std::string guid;
- if (args->GetSize() < 1 || !args->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
- bool force_show = false;
- if (args->GetSize() >= 2)
- args->GetBoolean(1, &force_show);
-
- const NetworkState* network =
- NetworkHandler::Get()->network_state_handler()->GetNetworkStateFromGuid(
- guid);
- if (!network)
- return;
-
- if (network->type() == shill::kTypeVPN &&
- network->vpn_provider_type() == shill::kProviderThirdPartyVpn) {
- // Request that the third-party VPN provider used by the |network| show a
- // configuration dialog for it.
- VpnServiceFactory::GetForBrowserContext(GetProfileForPrimaryUser())
- ->SendShowConfigureDialogToExtension(
- network->third_party_vpn_provider_extension_id(), network->name());
- return;
- }
-
- // If a network is not connectable, show the enrollment dialog if available.
- if (!force_show && !network->connectable() &&
- enrollment::CreateEnrollmentDialog(guid, GetNativeWindow())) {
- return;
- }
-
- NetworkConfigView::ShowForNetworkId(guid);
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.h
deleted file mode 100644
index 383b977db54..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler.h
+++ /dev/null
@@ -1,60 +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_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_H_
-
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "ui/gfx/native_widget_types.h"
-
-class PrefService;
-
-namespace chromeos {
-namespace options {
-
-// ChromeOS internet options page UI handler.
-class InternetOptionsHandler : public ::options::OptionsPageUIHandler {
- public:
- InternetOptionsHandler();
- ~InternetOptionsHandler() override;
-
- private:
- // OptionsPageUIHandler
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler (from OptionsPageUIHandler)
- void RegisterMessages() override;
-
- // Callbacks to set network state properties.
- void ShowMorePlanInfoCallback(const base::ListValue* args);
- void SimOperationCallback(const base::ListValue* args);
-
- // Gets the native window for hosting dialogs, etc.
- gfx::NativeWindow GetNativeWindow() const;
-
- // Gets the user PrefService associated with the WebUI.
- const PrefService* GetPrefs() const;
-
- // Additional callbacks for managing networks.
- void AddVPNConnection(const base::ListValue* args);
- void AddNonVPNConnection(const base::ListValue* args);
- void ConfigureNetwork(const base::ListValue* args);
-
- // Weak pointer factory so we can start connections at a later time
- // without worrying that they will actually try to happen after the lifetime
- // of this object.
- base::WeakPtrFactory<InternetOptionsHandler> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(InternetOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.cc b/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.cc
deleted file mode 100644
index accea7676a2..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.cc
+++ /dev/null
@@ -1,208 +0,0 @@
-// Copyright (c) 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h"
-
-#include <stddef.h>
-
-#include "ash/strings/grit/ash_strings.h"
-#include "base/macros.h"
-#include "base/values.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/strings/grit/components_strings.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace chromeos {
-namespace internet_options_strings {
-
-namespace {
-
-struct StringResource {
- const char* name;
- int id;
-};
-
-StringResource kStringResources[] = {
- // Main settings page.
- {"ethernetName", IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET},
- {"ethernetTitle", IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET},
- {"wifiTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_WIFI_NETWORK},
- {"wimaxTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_WIMAX_NETWORK},
- {"cellularTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_CELLULAR_NETWORK},
- {"vpnTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_PRIVATE_NETWORK},
- {"vpnNameTemplate",
- IDS_OPTIONS_SETTINGS_SECTION_THIRD_PARTY_VPN_NAME_TEMPLATE},
- {"defaultThirdPartyProviderName",
- IDS_OPTIONS_SETTINGS_SECTION_DEFAULT_THIRD_PARTY_PROVIDER_NAME},
- {"vpnBuiltInProvider", IDS_ASH_STATUS_TRAY_VPN_BUILT_IN_PROVIDER},
- {"joinOtherNetwork", IDS_OPTIONS_SETTINGS_NETWORK_OTHER},
- {"networkDisabled", IDS_OPTIONS_SETTINGS_NETWORK_DISABLED},
- {"networkProhibited", IDS_OPTIONS_SETTINGS_NETWORK_PROHIBITED},
- {"turnOffWifi", IDS_OPTIONS_SETTINGS_NETWORK_DISABLE_WIFI},
- {"turnOffWimax", IDS_OPTIONS_SETTINGS_NETWORK_DISABLE_WIMAX},
- {"turnOffCellular", IDS_OPTIONS_SETTINGS_NETWORK_DISABLE_CELLULAR},
- {"disconnectNetwork", IDS_OPTIONS_SETTINGS_DISCONNECT},
- {"preferredNetworks", IDS_OPTIONS_SETTINGS_PREFERRED_NETWORKS_LABEL},
- {"preferredNetworksPage", IDS_OPTIONS_SETTINGS_PREFERRED_NETWORKS_TITLE},
- {"useSharedProxies", IDS_OPTIONS_SETTINGS_USE_SHARED_PROXIES},
- {"addConnectionTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_ADD_CONNECTION},
- {"addConnectionWifi", IDS_OPTIONS_SETTINGS_ADD_CONNECTION_WIFI},
- {"addConnectionVPNTemplate", IDS_OPTIONS_SETTINGS_ADD_VPN_TEMPLATE},
- {"otherCellularNetworks", IDS_OPTIONS_SETTINGS_OTHER_CELLULAR_NETWORKS},
- {"enableDataRoaming", IDS_OPTIONS_SETTINGS_ENABLE_DATA_ROAMING},
- {"disableDataRoaming", IDS_OPTIONS_SETTINGS_DISABLE_DATA_ROAMING},
- {"dataRoamingDisableToggleTooltip",
- IDS_OPTIONS_SETTINGS_TOGGLE_DATA_ROAMING_RESTRICTION},
- {"prohibitedNetwork", IDS_OPTIONS_SETTINGS_PROHIBITED_NETWORK},
- {"prohibitedNetworkOther", IDS_OPTIONS_SETTINGS_PROHIBITED_NETWORK_OTHER},
-
- // ONC network states. Format is 'Onc' + key + value.
- // Note: '.' must be replaced with '-', e.g. VPN.Type -> OncVPN-Type
- {"OncCellular-ActivationStateActivated",
- IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED},
- {"OncCellular-ActivationStateActivating",
- IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING},
- {"OncCellular-ActivationStateNotActivated",
- IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED},
- {"OncCellular-ActivationStatePartiallyActivated",
- IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED},
- {"OncConnectionStateConnected", IDS_CHROMEOS_NETWORK_STATE_CONNECTED},
- {"OncConnectionStateConnecting", IDS_CHROMEOS_NETWORK_STATE_CONNECTING},
- {"OncConnectionStateNotConnected",
- IDS_CHROMEOS_NETWORK_STATE_NOT_CONNECTED},
- {"OncCellular-RoamingStateHome", IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME},
- {"OncCellular-RoamingStateRoaming",
- IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING},
- {"OncTypeCellular", IDS_NETWORK_TYPE_MOBILE_DATA},
- {"OncTypeEthernet", IDS_NETWORK_TYPE_ETHERNET},
- {"OncTypeTether", IDS_NETWORK_TYPE_MOBILE_DATA},
- {"OncTypeWiFi", IDS_NETWORK_TYPE_WIFI},
- {"OncTypeWimax", IDS_NETWORK_TYPE_WIMAX},
- {"OncVPN-TypeL2TP-IPsecCert",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_L2TP_IPSEC_USER_CERT},
- {"OncVPN-TypeL2TP-IPsecPSK",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_L2TP_IPSEC_PSK},
- {"OncVPN-TypeOpenVPN", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_OPEN_VPN},
- {"OncVPN-TypeThirdPartyVPN",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_THIRD_PARTY_VPN},
-
- // Internet details dialog.
- {"restrictedNo", IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL},
- {"restrictedYes", IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL},
- {"managedNetwork", IDS_OPTIONS_SETTINGS_MANAGED_NETWORK},
- {"wifiNetworkTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_CONNECTION},
- {"vpnTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_VPN},
- {"cellularConnTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_CONNECTION},
- {"cellularDeviceTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_DEVICE},
- {"networkTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_NETWORK},
- {"securityTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_SECURITY},
- {"proxyTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_PROXY},
- {"connectionState", IDS_OPTIONS_SETTINGS_INTERNET_CONNECTION_STATE},
- // TODO(stevenjb): Rename the IDS constant when we redesign the UI.
- {"restrictedConnectivity",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_RESTRICTED_POOL},
- {"inetAddress", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_ADDRESS},
- {"ipv6Address", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_ADDRESS_IPV6},
- {"inetNetmask", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SUBNETMASK},
- {"inetGateway", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_GATEWAY},
- {"inetNameServers", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_DNSSERVER},
- {"ipAutomaticConfiguration",
- IDS_OPTIONS_SETTINGS_INTERNET_IP_AUTOMATIC_CONFIGURATION},
- {"automaticNameServers",
- IDS_OPTIONS_SETTINGS_INTERNET_AUTOMATIC_NAME_SERVERS},
- {"userNameServer1", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_1},
- {"userNameServer2", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_2},
- {"userNameServer3", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_3},
- {"userNameServer4", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_4},
- {"googleNameServers", IDS_OPTIONS_SETTINGS_INTERNET_GOOGLE_NAME_SERVERS},
- {"userNameServers", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVERS},
- {"hardwareAddress", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_HARDWARE_ADDRESS},
- {"detailsInternetDismiss", IDS_CLOSE},
- {"activateButton", IDS_OPTIONS_SETTINGS_ACTIVATE},
- {"connectButton", IDS_OPTIONS_SETTINGS_CONNECT},
- {"configureButton", IDS_OPTIONS_SETTINGS_CONFIGURE},
- {"disconnectButton", IDS_OPTIONS_SETTINGS_DISCONNECT},
- {"viewAccountButton", IDS_STATUSBAR_NETWORK_VIEW_ACCOUNT},
- {"wimaxConnTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_WIMAX},
-
- // Wifi Tab.
- {"inetSsid", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_ID},
- {"inetBssid", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_BSSID},
- {"inetEncryption",
- IDS_OPTIONS_SETTIGNS_INTERNET_OPTIONS_NETWORK_ENCRYPTION},
- {"inetFrequency", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_FREQUENCY},
- {"inetFrequencyFormat",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_FREQUENCY_MHZ},
- {"inetSignalStrength",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_STRENGTH},
- {"inetSignalStrengthFormat",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_STRENGTH_PERCENTAGE},
- {"inetPassProtected", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NET_PROTECTED},
- {"inetNetworkShared", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_SHARED},
- {"inetPreferredNetwork",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PREFER_NETWORK},
- {"inetAutoConnectNetwork",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_AUTO_CONNECT},
-
- // VPN Tab.
- {"inetServiceName", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_SERVICE_NAME},
- {"inetServerHostname",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_SERVER_HOSTNAME},
- {"inetProviderType",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_PROVIDER_TYPE},
- {"inetProviderName",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_PROVIDER_NAME},
- {"inetUsername", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_USERNAME},
-
- // Cellular Tab.
- {"serviceName", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_SERVICE_NAME},
- {"networkTechnology",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_NETWORK_TECHNOLOGY},
- {"operatorName", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_OPERATOR},
- {"operatorCode", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_OPERATOR_CODE},
- {"activationState",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ACTIVATION_STATE},
- {"roamingState", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ROAMING_STATE},
- {"errorState", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ERROR_STATE},
- {"cellularManufacturer",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_MANUFACTURER},
- {"modelId", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_MODEL_ID},
- {"firmwareRevision",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_FIRMWARE_REVISION},
- {"hardwareRevision",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_HARDWARE_REVISION},
- {"prlVersion", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_PRL_VERSION},
- {"cellularApnLabel", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN},
- {"cellularApnOther", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_OTHER},
- {"cellularApnUsername",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_USERNAME},
- {"cellularApnPassword",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_PASSWORD},
- {"cellularApnUseDefault", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_CLEAR},
- {"cellularApnSet", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_SET},
- {"cellularApnCancel", IDS_CANCEL},
-
- // Security Tab.
- {"lockSimCard", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_LOCK_SIM_CARD},
- {"changePinButton",
- IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_BUTTON},
-
- // Proxy Tab.
- {"webProxyAutoDiscoveryUrl", IDS_PROXY_WEB_PROXY_AUTO_DISCOVERY},
-};
-
-const size_t kStringResourcesLength = arraysize(kStringResources);
-
-} // namespace
-
-void RegisterLocalizedStrings(base::DictionaryValue* localized_strings) {
- for (size_t i = 0; i < kStringResourcesLength; ++i) {
- localized_strings->SetString(
- kStringResources[i].name,
- l10n_util::GetStringUTF16(kStringResources[i].id));
- }
-}
-
-} // namespace internet_options_strings
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h b/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h
deleted file mode 100644
index 2983f548e1b..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/internet_options_handler_strings.h
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_STRINGS_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_STRINGS_H_
-
-#include <string>
-
-namespace base {
-class DictionaryValue;
-}
-
-namespace chromeos {
-namespace internet_options_strings {
-
-void RegisterLocalizedStrings(base::DictionaryValue* localized_strings);
-
-} // namespace internet_options_strings
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_STRINGS_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.cc
deleted file mode 100644
index 1d6882b886d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.cc
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/keyboard_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-
-#include "ash/new_window_controller.h"
-#include "ash/shell.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/values.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/chromeos_switches.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/ime/chromeos/ime_keyboard.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/events/devices/input_device_manager.h"
-
-namespace {
-const struct ModifierKeysSelectItem {
- int message_id;
- chromeos::input_method::ModifierKey value;
-} kModifierKeysSelectItems[] = {
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH,
- chromeos::input_method::kSearchKey },
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL,
- chromeos::input_method::kControlKey },
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT,
- chromeos::input_method::kAltKey },
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_VOID,
- chromeos::input_method::kVoidKey },
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK,
- chromeos::input_method::kCapsLockKey },
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_ESCAPE,
- chromeos::input_method::kEscapeKey },
- { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_BACKSPACE,
- chromeos::input_method::kBackspaceKey },
-};
-
-const char* kDataValuesNames[] = {
- "remapSearchKeyToValue",
- "remapControlKeyToValue",
- "remapAltKeyToValue",
- "remapCapsLockKeyToValue",
- "remapDiamondKeyToValue",
- "remapEscapeKeyToValue",
- "remapBackspaceKeyToValue",
-};
-
-bool HasExternalKeyboard() {
- for (const ui::InputDevice& keyboard :
- ui::InputDeviceManager::GetInstance()->GetKeyboardDevices()) {
- if (keyboard.type == ui::InputDeviceType::INPUT_DEVICE_EXTERNAL)
- return true;
- }
-
- return false;
-}
-} // namespace
-
-namespace chromeos {
-namespace options {
-
-KeyboardHandler::KeyboardHandler() {
- ui::InputDeviceManager::GetInstance()->AddObserver(this);
-}
-
-KeyboardHandler::~KeyboardHandler() {
- ui::InputDeviceManager::GetInstance()->RemoveObserver(this);
-}
-
-void KeyboardHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- RegisterTitle(localized_strings, "keyboardOverlay",
- IDS_OPTIONS_KEYBOARD_OVERLAY_TITLE);
-
- localized_strings->SetString("remapSearchKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH_LABEL));
- localized_strings->SetString("remapControlKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL_LABEL));
- localized_strings->SetString("remapAltKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT_LABEL));
- localized_strings->SetString("remapCapsLockKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK_LABEL));
- localized_strings->SetString("remapDiamondKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_DIAMOND_KEY_LABEL));
- localized_strings->SetString("remapBackspaceKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_BACKSPACE_KEY_LABEL));
- localized_strings->SetString("remapEscapeKeyToContent",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_ESCAPE_KEY_LABEL));
- localized_strings->SetString("sendFunctionKeys",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_SEND_FUNCTION_KEYS));
- localized_strings->SetString("sendFunctionKeysDescription",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_SEND_FUNCTION_KEYS_DESCRIPTION));
- localized_strings->SetString("enableAutoRepeat",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_ENABLE));
- localized_strings->SetString("autoRepeatDelay",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_DELAY));
- localized_strings->SetString("autoRepeatDelayLong",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_DELAY_LONG));
- localized_strings->SetString("autoRepeatDelayShort",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_DELAY_SHORT));
- localized_strings->SetString("autoRepeatRate",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_RATE));
- localized_strings->SetString("autoRepeatRateSlow",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_RATE_SLOW));
- localized_strings->SetString("autoRepeatRateFast",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_AUTO_REPEAT_RATE_FAST));
- localized_strings->SetString("changeLanguageAndInputSettings",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_CHANGE_LANGUAGE_AND_INPUT_SETTINGS));
- localized_strings->SetString("showKeyboardShortcuts",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_SHOW_KEYBOARD_SHORTCUTS));
-
- for (size_t i = 0; i < arraysize(kDataValuesNames); ++i) {
- auto list_value = base::MakeUnique<base::ListValue>();
- for (size_t j = 0; j < arraysize(kModifierKeysSelectItems); ++j) {
- const input_method::ModifierKey value =
- kModifierKeysSelectItems[j].value;
- const int message_id = kModifierKeysSelectItems[j].message_id;
- auto option = base::MakeUnique<base::ListValue>();
- option->AppendInteger(value);
- option->AppendString(l10n_util::GetStringUTF16(message_id));
- list_value->Append(std::move(option));
- }
- localized_strings->Set(kDataValuesNames[i], std::move(list_value));
- }
-}
-
-void KeyboardHandler::InitializePage() {
- bool has_diamond_key = base::CommandLine::ForCurrentProcess()->HasSwitch(
- chromeos::switches::kHasChromeOSDiamondKey);
- const base::Value show_diamond_key_options(has_diamond_key);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.KeyboardOverlay.showDiamondKeyOptions",
- show_diamond_key_options);
-
- UpdateCapsLockOptions();
-}
-
-void KeyboardHandler::RegisterMessages() {
- // Callback to show keyboard overlay.
- web_ui()->RegisterMessageCallback(
- "showKeyboardShortcuts",
- base::Bind(&KeyboardHandler::HandleShowKeyboardShortcuts,
- base::Unretained(this)));
-}
-
-void KeyboardHandler::OnKeyboardDeviceConfigurationChanged() {
- UpdateCapsLockOptions();
-}
-
-void KeyboardHandler::HandleShowKeyboardShortcuts(const base::ListValue* args) {
- ash::Shell::Get()->new_window_controller()->ShowKeyboardOverlay();
-}
-
-void KeyboardHandler::UpdateCapsLockOptions() const {
- const base::Value show_caps_lock_options(HasExternalKeyboard());
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.KeyboardOverlay.showCapsLockOptions", show_caps_lock_options);
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.h
deleted file mode 100644
index 8f6501a0e81..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/keyboard_handler.h
+++ /dev/null
@@ -1,47 +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_OPTIONS_CHROMEOS_KEYBOARD_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_KEYBOARD_HANDLER_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/prefs/pref_member.h"
-#include "ui/events/devices/input_device_event_observer.h"
-
-namespace chromeos {
-namespace options {
-
-// Customize modifier keys overlay page UI handler.
-class KeyboardHandler
- : public ::options::OptionsPageUIHandler,
- public ui::InputDeviceEventObserver {
- public:
- KeyboardHandler();
- ~KeyboardHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // ui::InputDeviceEventObserver:
- void OnKeyboardDeviceConfigurationChanged() override;
-
- private:
- // Show the keyboard shortcuts overlay from the options page.
- void HandleShowKeyboardShortcuts(const base::ListValue* args);
-
- // Shows or hides the CapsLock options based on whether or not there is an
- // external keyboard connected.
- void UpdateCapsLockOptions() const;
-
- DISALLOW_COPY_AND_ASSIGN(KeyboardHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_KEYBOARD_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.cc
deleted file mode 100644
index e705e1f6748..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.cc
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright (c) 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/options_stylus_handler.h"
-
-#include "ash/system/palette/palette_utils.h"
-#include "base/values.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/grit/generated_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/events/devices/input_device_manager.h"
-
-namespace chromeos {
-namespace options {
-
-namespace {
-
-// Keys in objects passed to updateNoteTakingApps_.
-constexpr char kAppNameKey[] = "name";
-constexpr char kAppIdKey[] = "id";
-constexpr char kAppPreferredKey[] = "preferred";
-
-} // namespace
-
-OptionsStylusHandler::OptionsStylusHandler() : weak_ptr_factory_(this) {
- NoteTakingHelper::Get()->AddObserver(this);
- ui::InputDeviceManager::GetInstance()->AddObserver(this);
-}
-
-OptionsStylusHandler::~OptionsStylusHandler() {
- ui::InputDeviceManager::GetInstance()->RemoveObserver(this);
- NoteTakingHelper::Get()->RemoveObserver(this);
-}
-
-void OptionsStylusHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- RegisterTitle(localized_strings, "stylusOverlay", IDS_SETTINGS_STYLUS_TITLE);
-
- localized_strings->SetString(
- "stylusSettingsButtonTitle",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_DEVICE_GROUP_STYLUS_SETTINGS_BUTTON));
- localized_strings->SetString(
- "stylusAutoOpenStylusTools",
- l10n_util::GetStringUTF16(IDS_SETTINGS_STYLUS_AUTO_OPEN_STYLUS_TOOLS));
- localized_strings->SetString(
- "stylusEnableStylusTools",
- l10n_util::GetStringUTF16(IDS_SETTINGS_STYLUS_ENABLE_STYLUS_TOOLS));
- localized_strings->SetString(
- "stylusFindMoreApps",
- l10n_util::GetStringUTF16(IDS_SETTINGS_STYLUS_FIND_MORE_APPS_PRIMARY));
- localized_strings->SetString(
- "stylusNoteTakingApp",
- l10n_util::GetStringUTF16(IDS_OPTIONS_STYLUS_NOTE_TAKING_APP_LABEL));
- localized_strings->SetString(
- "stylusNoteTakingAppNoneAvailable",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_STYLUS_NOTE_TAKING_APP_NONE_AVAILABLE));
- localized_strings->SetString(
- "stylusNoteTakingAppWaitingForAndroid",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_STYLUS_NOTE_TAKING_APP_WAITING_FOR_ANDROID));
-}
-
-void OptionsStylusHandler::InitializePage() {
- UpdateNoteTakingApps();
-}
-
-void OptionsStylusHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "setPreferredNoteTakingApp",
- base::Bind(&OptionsStylusHandler::SetPreferredNoteTakingApp,
- weak_ptr_factory_.GetWeakPtr()));
- web_ui()->RegisterMessageCallback(
- "requestStylusHardwareState",
- base::Bind(&OptionsStylusHandler::RequestStylusHardwareState,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void OptionsStylusHandler::OnAvailableNoteTakingAppsUpdated() {
- UpdateNoteTakingApps();
-}
-
-void OptionsStylusHandler::OnPreferredNoteTakingAppUpdated(Profile* profile) {
- if (Profile::FromWebUI(web_ui()) == profile)
- UpdateNoteTakingApps();
-}
-
-void OptionsStylusHandler::OnDeviceListsComplete() {
- SendHasStylus();
-}
-
-void OptionsStylusHandler::RequestStylusHardwareState(
- const base::ListValue* args) {
- if (ui::InputDeviceManager::GetInstance()->AreDeviceListsComplete())
- SendHasStylus();
-}
-
-void OptionsStylusHandler::SendHasStylus() {
- DCHECK(ui::InputDeviceManager::GetInstance()->AreDeviceListsComplete());
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.setStylusInputStatus",
- base::Value(ash::palette_utils::HasStylusInput()));
-}
-
-void OptionsStylusHandler::UpdateNoteTakingApps() {
- bool waiting_for_android = false;
- note_taking_app_ids_.clear();
- base::ListValue apps_list;
-
- NoteTakingHelper* helper = NoteTakingHelper::Get();
- if (helper->play_store_enabled() && !helper->android_apps_received()) {
- // If Play Store is enabled but not ready yet, let the JS know so it can
- // disable the menu and display an explanatory message.
- waiting_for_android = true;
- } else {
- for (const NoteTakingAppInfo& info :
- NoteTakingHelper::Get()->GetAvailableApps(
- Profile::FromWebUI(web_ui()))) {
- std::unique_ptr<base::DictionaryValue> dict(
- new base::DictionaryValue());
- dict->SetString(kAppNameKey, info.name);
- dict->SetString(kAppIdKey, info.app_id);
- dict->SetBoolean(kAppPreferredKey, info.preferred);
- apps_list.Append(std::move(dict));
-
- note_taking_app_ids_.insert(info.app_id);
- }
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("StylusOverlay.updateNoteTakingApps",
- apps_list,
- base::Value(waiting_for_android));
-}
-
-void OptionsStylusHandler::SetPreferredNoteTakingApp(
- const base::ListValue* args) {
- std::string app_id;
- CHECK(args->GetString(0, &app_id));
-
- // Sanity check: make sure that the ID we got back from WebUI is in the
- // currently-available set.
- if (!note_taking_app_ids_.count(app_id)) {
- LOG(ERROR) << "Got unknown note-taking-app ID \"" << app_id << "\"";
- return;
- }
-
- NoteTakingHelper::Get()->SetPreferredApp(Profile::FromWebUI(web_ui()),
- app_id);
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.h
deleted file mode 100644
index 3a51832affe..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/options_stylus_handler.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_OPTIONS_STYLUS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_OPTIONS_STYLUS_HANDLER_H_
-
-#include <set>
-#include <string>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/chromeos/note_taking_helper.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "ui/events/devices/input_device_event_observer.h"
-
-class Profile;
-
-namespace base {
-class ListValue;
-} // namespace base
-
-namespace chromeos {
-namespace options {
-
-// Stylus-specific options C++ code.
-class OptionsStylusHandler : public ::options::OptionsPageUIHandler,
- public NoteTakingHelper::Observer,
- public ui::InputDeviceEventObserver {
- public:
- OptionsStylusHandler();
- ~OptionsStylusHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // NoteTakingHelper::Observer implementation.
- void OnAvailableNoteTakingAppsUpdated() override;
- void OnPreferredNoteTakingAppUpdated(Profile* profile) override;
-
- // ui::InputDeviceEventObserver implementation:
- void OnDeviceListsComplete() override;
-
- private:
- // Called from WebUI when the page is initialized to determine if stylus
- // settings should be shown.
- void RequestStylusHardwareState(const base::ListValue* args);
-
- // Sends if there is a stylus device to WebUI.
- void SendHasStylus();
-
- // Updates the note-taking app menu in the stylus overlay to display the
- // currently-available set of apps.
- void UpdateNoteTakingApps();
-
- // Called from WebUI when the user selects a note-taking app.
- void SetPreferredNoteTakingApp(const base::ListValue* args);
-
- // IDs of available note-taking apps.
- std::set<std::string> note_taking_app_ids_;
-
- base::WeakPtrFactory<OptionsStylusHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(OptionsStylusHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_OPTIONS_STYLUS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.cc
deleted file mode 100644
index a4ee792b43f..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/pointer_handler.h"
-
-#include "base/macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace chromeos {
-namespace options {
-
-PointerHandler::PointerHandler()
- : has_touchpad_(false),
- has_mouse_(false) {
-}
-
-PointerHandler::~PointerHandler() {
-}
-
-void PointerHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "pointerOverlayTitleTouchpadOnly",
- IDS_OPTIONS_POINTER_TOUCHPAD_OVERLAY_TITLE },
- { "pointerOverlayTitleMouseOnly",
- IDS_OPTIONS_POINTER_MOUSE_OVERLAY_TITLE },
- { "pointerOverlayTitleTouchpadMouse",
- IDS_OPTIONS_POINTER_TOUCHPAD_MOUSE_OVERLAY_TITLE },
- { "pointerOverlaySectionTitleTouchpad",
- IDS_OPTIONS_POINTER_OVERLAY_SECTION_TITLE_TOUCHPAD },
- { "pointerOverlaySectionTitleMouse",
- IDS_OPTIONS_POINTER_OVERLAY_SECTION_TITLE_MOUSE },
- { "enableTapToClick",
- IDS_OPTIONS_SETTINGS_TAP_TO_CLICK_ENABLED_DESCRIPTION },
- { "primaryMouseRight",
- IDS_OPTIONS_SETTINGS_PRIMARY_MOUSE_RIGHT_DESCRIPTION },
- { "traditionalScroll",
- IDS_OPTIONS_SETTINGS_TRADITIONAL_SCROLL_DESCRIPTION },
- };
-
- localized_strings->SetString("naturalScroll",
- l10n_util::GetStringFUTF16(
- IDS_OPTIONS_SETTINGS_NATURAL_SCROLL_DESCRIPTION,
- base::ASCIIToUTF16(chrome::kNaturalScrollHelpURL)));
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-}
-
-
-void PointerHandler::TouchpadExists(bool exists) {
- has_touchpad_ = exists;
- base::Value val(exists);
- web_ui()->CallJavascriptFunctionUnsafe("PointerOverlay.showTouchpadControls",
- val);
- UpdateTitle();
-}
-
-void PointerHandler::MouseExists(bool exists) {
- has_mouse_ = exists;
- base::Value val(exists);
- web_ui()->CallJavascriptFunctionUnsafe("PointerOverlay.showMouseControls",
- val);
- UpdateTitle();
-}
-
-void PointerHandler::UpdateTitle() {
- std::string label;
- if (has_touchpad_) {
- label = has_mouse_ ? "pointerOverlayTitleTouchpadMouse" :
- "pointerOverlayTitleTouchpadOnly";
- } else {
- label = has_mouse_ ? "pointerOverlayTitleMouseOnly" : "";
- }
- base::Value val(label);
- web_ui()->CallJavascriptFunctionUnsafe("PointerOverlay.setTitle", val);
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.h
deleted file mode 100644
index d0d4c48e4bd..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/pointer_handler.h
+++ /dev/null
@@ -1,47 +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_OPTIONS_CHROMEOS_POINTER_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POINTER_HANDLER_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/chromeos/system/pointer_device_observer.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/prefs/pref_member.h"
-
-namespace chromeos {
-namespace options {
-
-// Pointer settings overlay page UI handler.
-class PointerHandler
- : public ::options::OptionsPageUIHandler,
- public chromeos::system::PointerDeviceObserver::Observer {
- public:
- PointerHandler();
- ~PointerHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- private:
- // PointerDeviceObserver implementation.
- void TouchpadExists(bool exists) override;
- void MouseExists(bool exists) override;
-
- // Set the title dynamically based on whether a touchpad and/or mouse is
- // detected.
- void UpdateTitle();
-
- bool has_touchpad_;
- bool has_mouse_;
-
- DISALLOW_COPY_AND_ASSIGN(PointerHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POINTER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/power_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/power_handler.cc
deleted file mode 100644
index d5221833499..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/power_handler.cc
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/power_handler.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/ui/ash/ash_util.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/l10n/time_format.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/webui/web_ui_util.h"
-
-using ash::PowerStatus;
-
-namespace chromeos {
-namespace options {
-
-PowerHandler::PowerHandler() {
- // TODO(mash): Support Chrome power settings in Mash. crbug.com/644348
- this->show_power_status_ = !ash_util::IsRunningInMash() &&
- (switches::PowerOverlayEnabled() ||
- (PowerStatus::Get()->IsBatteryPresent() &&
- PowerStatus::Get()->SupportsDualRoleDevices()));
-}
-
-PowerHandler::~PowerHandler() {
- if (this->show_power_status_)
- PowerStatus::Get()->RemoveObserver(this);
-}
-
-void PowerHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- RegisterTitle(localized_strings, "powerOverlay",
- IDS_OPTIONS_POWER_OVERLAY_TITLE);
- localized_strings->SetString(
- "batteryStatusLabel",
- l10n_util::GetStringUTF16(IDS_OPTIONS_BATTERY_STATUS_LABEL));
- localized_strings->SetBoolean(
- "showPowerStatus", this->show_power_status_);
- localized_strings->SetString(
- "powerSourceLabel",
- l10n_util::GetStringUTF16(IDS_OPTIONS_POWER_SOURCE_LABEL));
- localized_strings->SetString(
- "powerSourceBattery",
- l10n_util::GetStringUTF16(IDS_OPTIONS_POWER_SOURCE_BATTERY));
- localized_strings->SetString(
- "powerSourceAcAdapter",
- l10n_util::GetStringUTF16(IDS_OPTIONS_POWER_SOURCE_AC_ADAPTER));
- localized_strings->SetString(
- "powerSourceLowPowerCharger",
- l10n_util::GetStringUTF16(IDS_OPTIONS_POWER_SOURCE_LOW_POWER_CHARGER));
- localized_strings->SetString(
- "calculatingPower",
- l10n_util::GetStringUTF16(IDS_OPTIONS_POWER_OVERLAY_CALCULATING));
-}
-
-void PowerHandler::InitializePage() {
- if (this->show_power_status_)
- PowerStatus::Get()->RequestStatusUpdate();
-}
-
-void PowerHandler::RegisterMessages() {
- if (this->show_power_status_)
- PowerStatus::Get()->AddObserver(this);
- // Callback to fetch the power info.
- web_ui()->RegisterMessageCallback(
- "updatePowerStatus",
- base::Bind(&PowerHandler::UpdatePowerStatus, base::Unretained(this)));
- // Callback to set the power source.
- web_ui()->RegisterMessageCallback(
- "setPowerSource",
- base::Bind(&PowerHandler::SetPowerSource, base::Unretained(this)));
-}
-
-void PowerHandler::OnPowerStatusChanged() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.PowerOverlay.setBatteryStatusText",
- base::Value(GetStatusValue()));
- UpdatePowerSources();
-}
-
-base::string16 PowerHandler::GetStatusValue() const {
- PowerStatus* status = PowerStatus::Get();
- if (!status->IsBatteryPresent())
- return base::string16();
-
- bool charging = status->IsBatteryCharging();
- bool calculating = status->IsBatteryTimeBeingCalculated();
- int percent = status->GetRoundedBatteryPercent();
- base::TimeDelta time_left;
- bool show_time = false;
-
- if (!calculating) {
- time_left = charging ? status->GetBatteryTimeToFull() :
- status->GetBatteryTimeToEmpty();
- show_time = PowerStatus::ShouldDisplayBatteryTime(time_left);
- }
-
- if (!show_time) {
- return l10n_util::GetStringFUTF16(IDS_OPTIONS_BATTERY_STATUS_SHORT,
- base::IntToString16(percent));
- } else {
- int hour = 0;
- int min = 0;
- PowerStatus::SplitTimeIntoHoursAndMinutes(time_left, &hour, &min);
-
- base::string16 time_text;
- if (hour == 0 || min == 0) {
- // Display only one unit ("2 hours" or "10 minutes").
- time_text = ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_DURATION,
- ui::TimeFormat::LENGTH_LONG,
- time_left);
- } else {
- time_text = ui::TimeFormat::Detailed(ui::TimeFormat::FORMAT_DURATION,
- ui::TimeFormat::LENGTH_LONG,
- -1, // force hour and minute output
- time_left);
- }
-
- return l10n_util::GetStringFUTF16(
- charging ? IDS_OPTIONS_BATTERY_STATUS_CHARGING :
- IDS_OPTIONS_BATTERY_STATUS,
- base::IntToString16(percent),
- time_text);
- }
-}
-
-void PowerHandler::UpdatePowerStatus(const base::ListValue* args) {
- PowerStatus::Get()->RequestStatusUpdate();
-}
-
-void PowerHandler::SetPowerSource(const base::ListValue* args) {
- std::string id;
- if (!args->GetString(0, &id)) {
- NOTREACHED();
- return;
- }
- PowerStatus::Get()->SetPowerSource(id);
-}
-
-void PowerHandler::UpdatePowerSources() {
- PowerStatus* status = PowerStatus::Get();
-
- base::ListValue sources_list;
- for (const auto& source : status->GetPowerSources()) {
- std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
- dict->SetString("id", source.id);
- dict->SetInteger("type", source.type);
- dict->SetString("description",
- l10n_util::GetStringUTF16(source.description_id));
- sources_list.Append(std::move(dict));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.PowerOverlay.setPowerSources", sources_list,
- base::Value(status->GetCurrentPowerSourceID()),
- base::Value(status->IsUsbChargerConnected()),
- base::Value(status->IsBatteryTimeBeingCalculated()));
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/power_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/power_handler.h
deleted file mode 100644
index 843749b8e08..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/power_handler.h
+++ /dev/null
@@ -1,54 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POWER_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POWER_HANDLER_H_
-
-#include "ash/system/power/power_status.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace chromeos {
-namespace options {
-
-// Shows battery status and power settings.
-class PowerHandler : public ::options::OptionsPageUIHandler,
- public ash::PowerStatus::Observer {
- public:
- PowerHandler();
- ~PowerHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // ash::PowerStatus::Observer implementation.
- void OnPowerStatusChanged() override;
-
-private:
- // Gets the battery status text, showing the percentage and time remaining if
- // calculated. Returns an empty string if there is no battery.
- base::string16 GetStatusValue() const;
-
- // Handler to request updating the power status.
- void UpdatePowerStatus(const base::ListValue* args);
-
- // Handler to change the power source.
- void SetPowerSource(const base::ListValue* args);
-
- // Updates the UI with the latest power source information.
- void UpdatePowerSources();
-
- // Whether the UI should show the power status.
- bool show_power_status_;
-
- DISALLOW_COPY_AND_ASSIGN(PowerHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_POWER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.cc
deleted file mode 100644
index 6a6a7062d91..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/proxy_handler.h"
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/stl_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/time/time.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/system/input_device_settings.h"
-#include "chrome/common/chrome_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/chromeos_constants.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace chromeos {
-namespace options {
-
-ProxyHandler::ProxyHandler() {
-}
-
-ProxyHandler::~ProxyHandler() {
-}
-
-void ProxyHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- // Proxy page - ChromeOS
- static OptionsStringResource resources[] = {
- { "proxyPage", IDS_OPTIONS_PROXY_TAB_LABEL },
- { "proxyDirectInternetConnection", IDS_PROXY_DIRECT_CONNECTION },
- { "proxyManual", IDS_PROXY_MANUAL_CONFIG },
- { "sameProxyProtocols", IDS_PROXY_SAME_FORALL },
- { "httpProxy", IDS_PROXY_HTTP_PROXY },
- { "secureHttpProxy", IDS_PROXY_HTTP_SECURE_HTTP_PROXY },
- { "ftpProxy", IDS_PROXY_FTP_PROXY },
- { "socksHost", IDS_PROXY_SOCKS_HOST },
- { "proxyAutomatic", IDS_PROXY_AUTOMATIC },
- { "proxyUseConfigUrl", IDS_PROXY_USE_AUTOCONFIG_URL },
- { "addHost", IDS_PROXY_ADD_HOST },
- { "removeHost", IDS_PROXY_REMOVE_HOST },
- { "proxyPort", IDS_PROXY_PORT },
- { "proxyBypass", IDS_PROXY_BYPASS },
- { "proxyBannerPolicy", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PROXY_POLICY },
- { "proxyBannerExtension",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PROXY_EXTENSION },
- { "proxyBannerOther",
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PROXY_OTHER_PRECEDE }
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-
- localized_strings->SetString("proxyBannerShared",
- l10n_util::GetStringFUTF16(
- IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PROXY_ENABLE_SHARED_HINT,
- l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_USE_SHARED_PROXIES)));
-}
-
-void ProxyHandler::InitializePage() {
- ::options::OptionsPageUIHandler::InitializePage();
-
- bool keyboard_driven_oobe =
- system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation();
- if (keyboard_driven_oobe) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "DetailsInternetPage.initializeKeyboardFlow");
- }
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.h
deleted file mode 100644
index 428020799ba..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/proxy_handler.h
+++ /dev/null
@@ -1,33 +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_OPTIONS_CHROMEOS_PROXY_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_PROXY_HANDLER_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace chromeos {
-namespace options {
-
-// ChromeOS proxy options page UI handler.
-class ProxyHandler : public ::options::OptionsPageUIHandler {
- public:
- explicit ProxyHandler();
- ~ProxyHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
-
- private:
-
- DISALLOW_COPY_AND_ASSIGN(ProxyHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_PROXY_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.cc
deleted file mode 100644
index 93048cbafeb..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/stats_options_handler.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "content/public/browser/web_ui.h"
-
-using base::UserMetricsAction;
-
-namespace chromeos {
-namespace options {
-
-StatsOptionsHandler::StatsOptionsHandler() {
-}
-
-// OptionsPageUIHandler implementation.
-void StatsOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
-}
-
-// WebUIMessageHandler implementation.
-void StatsOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("metricsReportingCheckboxAction",
- base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
- base::Unretained(this)));
-}
-
-void StatsOptionsHandler::HandleMetricsReportingCheckbox(
- const base::ListValue* args) {
-#if defined(GOOGLE_CHROME_BUILD)
- const std::string checked_str = base::UTF16ToUTF8(ExtractStringValue(args));
- const bool enabled = (checked_str == "true");
- base::RecordAction(
- enabled ? UserMetricsAction("Options_MetricsReportingCheckbox_Enable")
- : UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
-#endif
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.h
deleted file mode 100644
index 8c95f11229c..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/stats_options_handler.h
+++ /dev/null
@@ -1,38 +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_OPTIONS_CHROMEOS_STATS_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STATS_OPTIONS_HANDLER_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace chromeos {
-namespace options {
-
-// ChromeOS handler for "Stats/crash reporting to Google" option of the Advanced
-// settings page. This handler does only ChromeOS-specific actions while default
-// code is in Chrome's AdvancedOptionsHandler
-// (chrome/browser/webui/advanced_options_handler.cc).
-class StatsOptionsHandler : public ::options::OptionsPageUIHandler {
- public:
- StatsOptionsHandler();
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- void HandleMetricsReportingCheckbox(const base::ListValue* args);
-
- DISALLOW_COPY_AND_ASSIGN(StatsOptionsHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STATS_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.cc b/chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.cc
deleted file mode 100644
index d5d1da4f2bb..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.cc
+++ /dev/null
@@ -1,457 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/chromeos/storage_manager_handler.h"
-
-#include <algorithm>
-#include <numeric>
-#include <string>
-
-#include "base/files/file_util.h"
-#include "base/sys_info.h"
-#include "base/task_scheduler/post_task.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/browsing_data/browsing_data_appcache_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_cache_storage_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_cookie_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_database_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_file_system_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_flash_lso_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_indexed_db_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_local_storage_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_service_worker_helper.h"
-#include "chrome/browser/chromeos/arc/arc_util.h"
-#include "chrome/browser/chromeos/drive/file_system_util.h"
-#include "chrome/browser/chromeos/file_manager/path_util.h"
-#include "chrome/browser/platform_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/cryptohome/homedir_methods.h"
-#include "components/arc/arc_util.h"
-#include "components/browsing_data/content/conditional_cache_counting_helper.h"
-#include "components/drive/chromeos/file_system_interface.h"
-#include "components/user_manager/user_manager.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/storage_partition.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/text/bytes_formatting.h"
-
-namespace chromeos {
-namespace options {
-namespace {
-
-void GetSizeStatAsync(const base::FilePath& mount_path,
- int64_t* total_size,
- int64_t* available_size) {
- int64_t size = base::SysInfo::AmountOfTotalDiskSpace(mount_path);
- if (size >= 0)
- *total_size = size;
- size = base::SysInfo::AmountOfFreeDiskSpace(mount_path);
- if (size >= 0)
- *available_size = size;
-}
-
-// Threshold to show a message indicating space is critically low (512 MB).
-const int64_t kSpaceCriticallyLowBytes = 512 * 1024 * 1024;
-
-// Threshold to show a message indicating space is low (1 GB).
-const int64_t kSpaceLowBytes = 1 * 1024 * 1024 * 1024;
-
-} // namespace
-
-StorageManagerHandler::StorageManagerHandler()
- : browser_cache_size_(-1),
- has_browser_cache_size_(false),
- browser_site_data_size_(-1),
- has_browser_site_data_size_(false),
- updating_downloads_size_(false),
- updating_drive_cache_size_(false),
- updating_browsing_data_size_(false),
- updating_arc_size_(false),
- updating_other_users_size_(false),
- weak_ptr_factory_(this) {
-}
-
-StorageManagerHandler::~StorageManagerHandler() {
-}
-
-void StorageManagerHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- RegisterTitle(localized_strings, "storageManagerPage",
- IDS_OPTIONS_SETTINGS_STORAGE_MANAGER_TAB_TITLE);
- RegisterTitle(localized_strings, "storageClearDriveCachePage",
- IDS_OPTIONS_SETTINGS_STORAGE_CLEAR_DRIVE_CACHE_TAB_TITLE);
-
- localized_strings->SetString(
- "storageItemLabelCapacity", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_ITEM_LABEL_CAPACITY));
- localized_strings->SetString(
- "storageItemLabelInUse", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_ITEM_LABEL_IN_USE));
- localized_strings->SetString(
- "storageItemLabelAvailable", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_ITEM_LABEL_AVAILABLE));
- localized_strings->SetString(
- "storageSubitemLabelDownloads", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SUBITEM_LABEL_DOWNLOADS));
- localized_strings->SetString(
- "storageSubitemLabelDriveCache", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SUBITEM_LABEL_DRIVE_CACHE));
- localized_strings->SetString(
- "storageSubitemLabelBrowsingData", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SUBITEM_LABEL_BROWSING_DATA));
- localized_strings->SetString(
- "storageSubitemLabelOtherUsers", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SUBITEM_LABEL_OTHER_USERS));
- localized_strings->SetString(
- "storageSubitemLabelArc", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SUBITEM_LABEL_ARC));
- localized_strings->SetString(
- "storageSizeCalculating", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_CALCULATING));
- localized_strings->SetString(
- "storageClearDriveCacheDialogTitle", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_CLEAR_DRIVE_CACHE_DIALOG_TITLE));
- localized_strings->SetString(
- "storageClearDriveCacheDescription", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_CLEAR_DRIVE_CACHE_DESCRIPTION));
- localized_strings->SetString(
- "storageDeleteAllButtonTitle", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_DELETE_ALL_BUTTON_TITLE));
- localized_strings->SetString(
- "storageLowMessageTitle", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SPACE_LOW_MESSAGE_TITLE));
- localized_strings->SetString(
- "storageLowMessageLine1", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SPACE_LOW_MESSAGE_LINE_1));
- localized_strings->SetString(
- "storageLowMessageLine2", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SPACE_LOW_MESSAGE_LINE_2));
- localized_strings->SetString(
- "storageCriticallyLowMessageTitle", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SPACE_CRITICALLY_LOW_MESSAGE_TITLE));
- localized_strings->SetString(
- "storageCriticallyLowMessageLine1", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SPACE_CRITICALLY_LOW_MESSAGE_LINE_1));
- localized_strings->SetString(
- "storageCriticallyLowMessageLine2", l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SPACE_CRITICALLY_LOW_MESSAGE_LINE_2));
-}
-
-void StorageManagerHandler::InitializePage() {
- DCHECK(web_ui());
-}
-
-void StorageManagerHandler::RegisterMessages() {
- DCHECK(web_ui());
-
- web_ui()->RegisterMessageCallback(
- "updateStorageInfo",
- base::Bind(&StorageManagerHandler::HandleUpdateStorageInfo,
- weak_ptr_factory_.GetWeakPtr()));
- web_ui()->RegisterMessageCallback(
- "openDownloads",
- base::Bind(&StorageManagerHandler::HandleOpenDownloads,
- weak_ptr_factory_.GetWeakPtr()));
- web_ui()->RegisterMessageCallback(
- "openArcStorage",
- base::Bind(&StorageManagerHandler::HandleOpenArcStorage,
- weak_ptr_factory_.GetWeakPtr()));
- web_ui()->RegisterMessageCallback(
- "clearDriveCache",
- base::Bind(&StorageManagerHandler::HandleClearDriveCache,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void StorageManagerHandler::HandleUpdateStorageInfo(
- const base::ListValue* unused_args) {
- UpdateSizeStat();
- UpdateDownloadsSize();
- UpdateDriveCacheSize();
- UpdateBrowsingDataSize();
- UpdateOtherUsersSize();
- UpdateArcSize();
-}
-
-void StorageManagerHandler::HandleOpenDownloads(
- const base::ListValue* unused_args) {
- Profile* const profile = Profile::FromWebUI(web_ui());
- const base::FilePath downloads_path =
- file_manager::util::GetDownloadsFolderForProfile(profile);
- platform_util::OpenItem(
- profile,
- downloads_path,
- platform_util::OPEN_FOLDER,
- platform_util::OpenOperationCallback());
-}
-
-void StorageManagerHandler::HandleOpenArcStorage(
- const base::ListValue* unused_args) {
- auto* arc_storage_manager = arc::ArcStorageManager::GetForBrowserContext(
- Profile::FromWebUI(web_ui()));
- if (arc_storage_manager)
- arc_storage_manager->OpenPrivateVolumeSettings();
-}
-
-void StorageManagerHandler::HandleClearDriveCache(
- const base::ListValue* unused_args) {
- drive::FileSystemInterface* const file_system =
- drive::util::GetFileSystemByProfile(Profile::FromWebUI(web_ui()));
- file_system->FreeDiskSpaceIfNeededFor(
- std::numeric_limits<int64_t>::max(), // Removes as much as possible.
- base::Bind(&StorageManagerHandler::OnClearDriveCacheDone,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void StorageManagerHandler::UpdateSizeStat() {
- Profile* const profile = Profile::FromWebUI(web_ui());
- const base::FilePath downloads_path =
- file_manager::util::GetDownloadsFolderForProfile(profile);
-
- int64_t* total_size = new int64_t(0);
- int64_t* available_size = new int64_t(0);
- base::PostTaskWithTraitsAndReply(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&GetSizeStatAsync, downloads_path, total_size, available_size),
- base::Bind(&StorageManagerHandler::OnGetSizeStat,
- weak_ptr_factory_.GetWeakPtr(), base::Owned(total_size),
- base::Owned(available_size)));
-}
-
-void StorageManagerHandler::OnGetSizeStat(int64_t* total_size,
- int64_t* available_size) {
- int64_t used_size = *total_size - *available_size;
- base::DictionaryValue size_stat;
- size_stat.SetString("totalSize", ui::FormatBytes(*total_size));
- size_stat.SetString("availableSize", ui::FormatBytes(*available_size));
- size_stat.SetString("usedSize", ui::FormatBytes(used_size));
- size_stat.SetDouble("usedRatio",
- static_cast<double>(used_size) / *total_size);
- int storage_space_state = STORAGE_SPACE_NORMAL;
- if (*available_size < kSpaceCriticallyLowBytes)
- storage_space_state = STORAGE_SPACE_CRITICALLY_LOW;
- else if (*available_size < kSpaceLowBytes)
- storage_space_state = STORAGE_SPACE_LOW;
- size_stat.SetInteger("spaceState", storage_space_state);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.setSizeStat", size_stat);
-}
-
-void StorageManagerHandler::UpdateDownloadsSize() {
- if (updating_downloads_size_)
- return;
- updating_downloads_size_ = true;
-
- Profile* const profile = Profile::FromWebUI(web_ui());
- const base::FilePath downloads_path =
- file_manager::util::GetDownloadsFolderForProfile(profile);
-
- base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
- base::Bind(&base::ComputeDirectorySize, downloads_path),
- base::Bind(&StorageManagerHandler::OnGetDownloadsSize,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void StorageManagerHandler::OnGetDownloadsSize(int64_t size) {
- updating_downloads_size_ = false;
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.setDownloadsSize",
- base::Value(ui::FormatBytes(size)));
-}
-
-void StorageManagerHandler::UpdateDriveCacheSize() {
- if (updating_drive_cache_size_)
- return;
-
- drive::FileSystemInterface* const file_system =
- drive::util::GetFileSystemByProfile(Profile::FromWebUI(web_ui()));
- if (!file_system)
- return;
-
- // Shows the item "Offline cache" and start calculating size.
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.showDriveCacheItem");
- updating_drive_cache_size_ = true;
- file_system->CalculateCacheSize(
- base::Bind(&StorageManagerHandler::OnGetDriveCacheSize,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void StorageManagerHandler::OnGetDriveCacheSize(int64_t size) {
- updating_drive_cache_size_ = false;
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.setDriveCacheSize",
- base::Value(ui::FormatBytes(size)));
-}
-
-void StorageManagerHandler::UpdateBrowsingDataSize() {
- if (updating_browsing_data_size_)
- return;
- updating_browsing_data_size_ = true;
-
- has_browser_cache_size_ = false;
- has_browser_site_data_size_ = false;
- Profile* const profile = Profile::FromWebUI(web_ui());
- // Fetch the size of http cache in browsing data.
- // ConditionalCacheCountingHelper deletes itself when it is done.
- browsing_data::ConditionalCacheCountingHelper::CreateForRange(
- content::BrowserContext::GetDefaultStoragePartition(profile),
- base::Time(), base::Time::Max())
- ->CountAndDestroySelfWhenFinished(
- base::Bind(&StorageManagerHandler::OnGetCacheSize,
- weak_ptr_factory_.GetWeakPtr()));
-
- // Fetch the size of site data in browsing data.
- if (!site_data_size_collector_.get()) {
- content::StoragePartition* storage_partition =
- content::BrowserContext::GetDefaultStoragePartition(profile);
- site_data_size_collector_.reset(new SiteDataSizeCollector(
- storage_partition->GetPath(),
- new BrowsingDataCookieHelper(profile->GetRequestContext()),
- new BrowsingDataDatabaseHelper(profile),
- new BrowsingDataLocalStorageHelper(profile),
- new BrowsingDataAppCacheHelper(profile),
- new BrowsingDataIndexedDBHelper(
- storage_partition->GetIndexedDBContext()),
- BrowsingDataFileSystemHelper::Create(
- storage_partition->GetFileSystemContext()),
- BrowsingDataChannelIDHelper::Create(profile->GetRequestContext()),
- new BrowsingDataServiceWorkerHelper(
- storage_partition->GetServiceWorkerContext()),
- new BrowsingDataCacheStorageHelper(
- storage_partition->GetCacheStorageContext()),
- BrowsingDataFlashLSOHelper::Create(profile)));
- }
- site_data_size_collector_->Fetch(
- base::Bind(&StorageManagerHandler::OnGetBrowsingDataSize,
- weak_ptr_factory_.GetWeakPtr(), true));
-}
-
-void StorageManagerHandler::OnGetCacheSize(bool is_upper_limit, int64_t size) {
- DCHECK(!is_upper_limit);
- OnGetBrowsingDataSize(false, size);
-}
-
-void StorageManagerHandler::OnGetBrowsingDataSize(bool is_site_data,
- int64_t size) {
- if (is_site_data) {
- has_browser_site_data_size_ = true;
- browser_site_data_size_ = size;
- } else {
- has_browser_cache_size_ = true;
- browser_cache_size_ = size;
- }
- if (has_browser_cache_size_ && has_browser_site_data_size_) {
- base::string16 size_string;
- if (browser_cache_size_ >= 0 && browser_site_data_size_ >= 0) {
- size_string = ui::FormatBytes(
- browser_site_data_size_ + browser_cache_size_);
- } else {
- size_string = l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_UNKNOWN);
- }
- updating_browsing_data_size_ = false;
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.setBrowsingDataSize", base::Value(size_string));
- }
-}
-
-void StorageManagerHandler::UpdateOtherUsersSize() {
- if (updating_other_users_size_)
- return;
- updating_other_users_size_ = true;
-
- other_users_.clear();
- user_sizes_.clear();
- const user_manager::UserList& users =
- user_manager::UserManager::Get()->GetUsers();
- for (auto* user : users) {
- if (user->is_active())
- continue;
- other_users_.push_back(user);
- cryptohome::HomedirMethods::GetInstance()->GetAccountDiskUsage(
- cryptohome::Identification(user->GetAccountId()),
- base::Bind(&StorageManagerHandler::OnGetOtherUserSize,
- weak_ptr_factory_.GetWeakPtr()));
- }
- // We should show "0 B" if there is no other user.
- if (other_users_.empty()) {
- updating_other_users_size_ = false;
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.setOtherUsersSize",
- base::Value(ui::FormatBytes(0)));
- }
-}
-
-void StorageManagerHandler::OnGetOtherUserSize(bool success, int64_t size) {
- user_sizes_.push_back(success ? size : -1);
- if (user_sizes_.size() == other_users_.size()) {
- base::string16 size_string;
- // If all the requests succeed, shows the total bytes in the UI.
- if (std::count(user_sizes_.begin(), user_sizes_.end(), -1) == 0) {
- size_string = ui::FormatBytes(
- std::accumulate(user_sizes_.begin(), user_sizes_.end(), 0LL));
- } else {
- size_string = l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_UNKNOWN);
- }
- updating_other_users_size_ = false;
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.setOtherUsersSize", base::Value(size_string));
- }
-}
-
-void StorageManagerHandler::UpdateArcSize() {
- if (updating_arc_size_)
- return;
- updating_arc_size_ = true;
-
- Profile* const profile = Profile::FromWebUI(web_ui());
- if (!arc::IsArcPlayStoreEnabledForProfile(profile) ||
- arc::IsArcOptInVerificationDisabled()) {
- return;
- }
-
- // Shows the item "Android apps and cache" and start calculating size.
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.StorageManager.showArcItem");
- bool success = false;
- auto* arc_storage_manager =
- arc::ArcStorageManager::GetForBrowserContext(profile);
- if (arc_storage_manager) {
- success = arc_storage_manager->GetApplicationsSize(base::Bind(
- &StorageManagerHandler::OnGetArcSize, weak_ptr_factory_.GetWeakPtr()));
- }
- if (!success)
- updating_arc_size_ = false;
-}
-
-void StorageManagerHandler::OnGetArcSize(bool succeeded,
- arc::mojom::ApplicationsSizePtr size) {
- base::string16 size_string;
- if (succeeded) {
- uint64_t total_bytes = size->total_code_bytes +
- size->total_data_bytes +
- size->total_cache_bytes;
- size_string = ui::FormatBytes(total_bytes);
- } else {
- size_string = l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_UNKNOWN);
- }
- updating_arc_size_ = false;
- web_ui()->CallJavascriptFunctionUnsafe("options.StorageManager.setArcSize",
- base::Value(size_string));
-}
-
-void StorageManagerHandler::OnClearDriveCacheDone(bool success) {
- UpdateDriveCacheSize();
-}
-
-} // namespace options
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.h b/chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.h
deleted file mode 100644
index 052524e3518..00000000000
--- a/chromium/chrome/browser/ui/webui/options/chromeos/storage_manager_handler.h
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STORAGE_MANAGER_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STORAGE_MANAGER_HANDLER_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/browsing_data/site_data_size_collector.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/arc/storage_manager/arc_storage_manager.h"
-#include "components/user_manager/user.h"
-
-namespace chromeos {
-namespace options {
-
-// Storage manager overlay page UI handler.
-class StorageManagerHandler : public ::options::OptionsPageUIHandler {
- public:
- // Enumeration for device state about remaining space. These values must be
- // kept in sync with options.StorageSpaceState in JS code.
- enum StorageSpaceState {
- STORAGE_SPACE_NORMAL = 0,
- STORAGE_SPACE_LOW = 1,
- STORAGE_SPACE_CRITICALLY_LOW = 2,
- };
-
- StorageManagerHandler();
- ~StorageManagerHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- // Handlers of JS messages.
- void HandleUpdateStorageInfo(const base::ListValue* unused_args);
- void HandleOpenDownloads(const base::ListValue* unused_args);
- void HandleOpenArcStorage(const base::ListValue* unused_args);
- void HandleClearDriveCache(const base::ListValue* unused_args);
-
- // Requests updating disk space information.
- void UpdateSizeStat();
-
- // Callback to update the UI about disk space information.
- void OnGetSizeStat(int64_t* total_size, int64_t* available_size);
-
- // Requests updating the size of Downloads directory.
- void UpdateDownloadsSize();
-
- // Callback to update the UI about the size of Downloads directory.
- void OnGetDownloadsSize(int64_t size);
-
- // Requests updating the size of Drive Cache.
- void UpdateDriveCacheSize();
-
- // Callback to update the UI about the size of Drive Cache.
- void OnGetDriveCacheSize(int64_t size);
-
- // Requests updating the size of browsing data.
- void UpdateBrowsingDataSize();
-
- // Callback to receive the cache size.
- void OnGetCacheSize(bool is_upper_limit, int64_t size);
-
- // Callback to update the UI about the size of browsing data.
- void OnGetBrowsingDataSize(bool is_site_data, int64_t size);
-
- // Requests updating the total size of other users' data.
- void UpdateOtherUsersSize();
-
- // Callback to save the fetched user sizes and update the UI.
- void OnGetOtherUserSize(bool success, int64_t size);
-
- // Requests updating the space size used by Android apps and cache.
- void UpdateArcSize();
-
- // Callback to update the UI about Android apps and cache.
- void OnGetArcSize(bool succeeded, arc::mojom::ApplicationsSizePtr size);
-
- // Callback called when clearing Drive cache is done.
- void OnClearDriveCacheDone(bool success);
-
- // Total size of cache data in browsing data.
- int64_t browser_cache_size_;
-
- // True if we have already received the size of http cache.
- bool has_browser_cache_size_;
-
- // Total size of site data in browsing data.
- int64_t browser_site_data_size_;
-
- // True if we have already received the size of site data.
- bool has_browser_site_data_size_;
-
- // The list of other users whose directory sizes will be accumulated as the
- // size of "Other users".
- user_manager::UserList other_users_;
-
- // Fetched sizes of user directories.
- std::vector<int64_t> user_sizes_;
-
- // Helper to compute the total size of all types of site date.
- std::unique_ptr<SiteDataSizeCollector> site_data_size_collector_;
-
- // Flags indicating fetch operations for storage sizes are ongoing.
- bool updating_downloads_size_;
- bool updating_drive_cache_size_;
- bool updating_browsing_data_size_;
- bool updating_arc_size_;
- bool updating_other_users_size_;
-
- base::WeakPtrFactory<StorageManagerHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(StorageManagerHandler);
-};
-
-} // namespace options
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STORAGE_MANAGER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.cc b/chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.cc
deleted file mode 100644
index 0c3e07d5b2e..00000000000
--- a/chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.cc
+++ /dev/null
@@ -1,441 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/clear_browser_data_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/metrics/sparse_histogram.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/app/chrome_command_ids.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/browsing_data/browsing_data_counter_factory.h"
-#include "chrome/browser/browsing_data/browsing_data_counter_utils.h"
-#include "chrome/browser/browsing_data/browsing_data_helper.h"
-#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
-#include "chrome/browser/history/web_history_service_factory.h"
-#include "chrome/browser/prefs/incognito_mode_prefs.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/accelerator_utils.h"
-#include "chrome/common/channel_info.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "chrome/grit/locale_settings.h"
-#include "components/browsing_data/core/counters/browsing_data_counter.h"
-#include "components/browsing_data/core/history_notice_utils.h"
-#include "components/browsing_data/core/pref_names.h"
-#include "components/google/core/browser/google_util.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/browsing_data_remover.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/accelerators/accelerator.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/events/keycodes/keyboard_codes.h"
-
-namespace {
-
-const char kClearBrowsingDataLearnMoreUrl[] =
- "https://support.google.com/chrome/?p=settings_clear_browsing_data";
-
-const char kMyActivityUrlInFooter[] =
- "https://history.google.com/history/?utm_source=chrome_cbd";
-
-const char kMyActivityUrlInDialog[] =
- "https://history.google.com/history/?utm_source=chrome_n";
-
-const int kMaxTimesHistoryNoticeShown = 1;
-
-const char* kCounterPrefs[] = {
- browsing_data::prefs::kDeleteBrowsingHistory,
- browsing_data::prefs::kDeleteCache,
- browsing_data::prefs::kDeleteFormData,
- browsing_data::prefs::kDeleteMediaLicenses,
- browsing_data::prefs::kDeletePasswords,
-};
-
-} // namespace
-
-namespace options {
-
-ClearBrowserDataHandler::ClearBrowserDataHandler()
- : remover_(nullptr),
- sync_service_(nullptr),
- should_show_history_notice_(false),
- should_show_history_deletion_dialog_(false),
- weak_ptr_factory_(this) {
-}
-
-ClearBrowserDataHandler::~ClearBrowserDataHandler() {
- if (remover_)
- remover_->RemoveObserver(this);
- if (sync_service_)
- sync_service_->RemoveObserver(this);
-}
-
-void ClearBrowserDataHandler::InitializeHandler() {
- PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
- clear_plugin_lso_data_enabled_.Init(prefs::kClearPluginLSODataEnabled, prefs);
- allow_deleting_browser_history_.Init(
- prefs::kAllowDeletingBrowserHistory,
- prefs,
- base::Bind(&ClearBrowserDataHandler::OnBrowsingHistoryPrefChanged,
- base::Unretained(this)));
-
- if (AreCountersEnabled()) {
- Profile* profile = Profile::FromWebUI(web_ui());
- for (const std::string& pref : kCounterPrefs) {
- AddCounter(
- BrowsingDataCounterFactory::GetForProfileAndPref(profile, pref));
- }
-
- sync_service_ = ProfileSyncServiceFactory::GetForProfile(profile);
- if (sync_service_)
- sync_service_->AddObserver(this);
- }
-}
-
-void ClearBrowserDataHandler::InitializePage() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ClearBrowserDataOverlay.createFooter", base::Value(AreCountersEnabled()),
- base::Value(sync_service_ && sync_service_->IsSyncActive()),
- base::Value(should_show_history_notice_));
- RefreshHistoryNotice();
- UpdateInfoBannerVisibility();
- OnBrowsingHistoryPrefChanged();
- bool removal_in_progress = !!remover_;
- web_ui()->CallJavascriptFunctionUnsafe("ClearBrowserDataOverlay.setClearing",
- base::Value(removal_in_progress));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ClearBrowserDataOverlay.markInitializationComplete");
-}
-
-void ClearBrowserDataHandler::UpdateInfoBannerVisibility() {
- base::string16 text;
-
- Profile* profile = Profile::FromWebUI(web_ui());
- auto availability = IncognitoModePrefs::GetAvailability(profile->GetPrefs());
- if (availability == IncognitoModePrefs::ENABLED) {
- base::Time last_clear_time = base::Time::FromInternalValue(
- profile->GetPrefs()->GetInt64(
- browsing_data::prefs::kLastClearBrowsingDataTime));
-
- const base::TimeDelta since_clear = base::Time::Now() - last_clear_time;
- if (since_clear < base::TimeDelta::FromHours(base::Time::kHoursPerDay)) {
- ui::Accelerator acc = chrome::GetPrimaryChromeAcceleratorForCommandId(
- IDC_NEW_INCOGNITO_WINDOW);
- DCHECK_NE(ui::VKEY_UNKNOWN, acc.key_code());
- text = l10n_util::GetStringFUTF16(IDS_CLEAR_BROWSING_DATA_INFO_BAR_TEXT,
- acc.GetShortcutText());
- }
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ClearBrowserDataOverlay.setBannerText", base::Value(text));
-}
-
-void ClearBrowserDataHandler::OnPageOpened(const base::ListValue* value) {
- for (const auto& counter : counters_) {
- DCHECK(AreCountersEnabled());
- counter->Restart();
- }
-}
-
-void ClearBrowserDataHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- {"clearBrowserDataLabel", IDS_CLEAR_BROWSING_DATA_LABEL},
- {"clearBrowserDataSyncWarning", IDS_CLEAR_BROWSING_DATA_SYNCED_DELETION},
- {"clearBrowserDataSupportString",
- AreCountersEnabled() ? IDS_CLEAR_BROWSING_DATA_SOME_STUFF_REMAINS_SIMPLE
- : IDS_CLEAR_BROWSING_DATA_SOME_STUFF_REMAINS},
- {"clearBrowserDataHistoryNoticeTitle",
- IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_TITLE},
- {"clearBrowserDataHistoryNoticeOk",
- IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_OK},
- {"deleteBrowsingHistoryCheckbox", IDS_DEL_BROWSING_HISTORY_CHKBOX},
- {"deleteDownloadHistoryCheckbox", IDS_DEL_DOWNLOAD_HISTORY_CHKBOX},
- {"deleteCacheCheckbox", IDS_DEL_CACHE_CHKBOX},
- {"deleteCookiesCheckbox", IDS_DEL_COOKIES_CHKBOX},
- {"deleteCookiesFlashCheckbox", IDS_DEL_COOKIES_FLASH_CHKBOX},
- {"deletePasswordsCheckbox", IDS_DEL_PASSWORDS_CHKBOX},
- {"deleteFormDataCheckbox", IDS_DEL_FORM_DATA_CHKBOX},
- {"deleteHostedAppsDataCheckbox", IDS_DEL_HOSTED_APPS_DATA_CHKBOX},
- {"deleteMediaLicensesCheckbox", IDS_DEL_MEDIA_LICENSES_CHKBOX},
- {"clearBrowserDataCommit", IDS_CLEAR_BROWSING_DATA_COMMIT},
- {"flashStorageUrl", IDS_FLASH_STORAGE_URL},
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "clearBrowserDataOverlay",
- IDS_CLEAR_BROWSING_DATA_TITLE);
- localized_strings->SetString("clearBrowsingDataLearnMoreUrl",
- kClearBrowsingDataLearnMoreUrl);
- localized_strings->SetString(
- "clearBrowserDataHistoryFooter",
- l10n_util::GetStringFUTF16(
- IDS_CLEAR_BROWSING_DATA_HISTORY_FOOTER,
- base::ASCIIToUTF16(kMyActivityUrlInFooter)));
- localized_strings->SetString(
- "clearBrowserDataHistoryNotice",
- l10n_util::GetStringFUTF16(
- IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE,
- base::ASCIIToUTF16(kMyActivityUrlInDialog)));
-
- auto time_list = base::MakeUnique<base::ListValue>();
- for (int i = 0; i < 5; i++) {
- base::string16 label_string;
- switch (i) {
- case 0:
- label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_HOUR);
- break;
- case 1:
- label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DAY);
- break;
- case 2:
- label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_WEEK);
- break;
- case 3:
- label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_4WEEKS);
- break;
- case 4:
- label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_EVERYTHING);
- break;
- }
- std::unique_ptr<base::ListValue> option(new base::ListValue());
- option->AppendInteger(i);
- option->AppendString(label_string);
- time_list->Append(std::move(option));
- }
- localized_strings->Set("clearBrowserDataTimeList", std::move(time_list));
- localized_strings->SetBoolean("showDeleteBrowsingHistoryCheckboxes",
- !Profile::FromWebUI(web_ui())->IsSupervised());
-}
-
-void ClearBrowserDataHandler::RegisterMessages() {
- // Setup handlers specific to this panel.
- web_ui()->RegisterMessageCallback("performClearBrowserData",
- base::Bind(&ClearBrowserDataHandler::HandleClearBrowserData,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("openedClearBrowserData",
- base::Bind(&ClearBrowserDataHandler::OnPageOpened,
- base::Unretained(this)));
-}
-
-void ClearBrowserDataHandler::HandleClearBrowserData(
- const base::ListValue* value) {
- // We should never be called when the previous clearing has not yet finished.
- CHECK(!remover_);
-
- Profile* profile = Profile::FromWebUI(web_ui());
- PrefService* prefs = profile->GetPrefs();
-
- int site_data_mask = ChromeBrowsingDataRemoverDelegate::DATA_TYPE_SITE_DATA;
- // Don't try to clear LSO data if it's not supported.
- if (!*clear_plugin_lso_data_enabled_)
- site_data_mask &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA;
-
- int remove_mask = 0;
- int origin_mask = 0;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory) &&
- *allow_deleting_browser_history_) {
- remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY;
- }
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory) &&
- *allow_deleting_browser_history_) {
- remove_mask |= content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS;
- }
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteCache))
- remove_mask |= content::BrowsingDataRemover::DATA_TYPE_CACHE;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteCookies)) {
- remove_mask |= site_data_mask;
- origin_mask |= content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
- }
- if (prefs->GetBoolean(browsing_data::prefs::kDeletePasswords))
- remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PASSWORDS;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteFormData))
- remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteMediaLicenses))
- remove_mask |= content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteHostedAppsData)) {
- remove_mask |= site_data_mask;
- origin_mask |= content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
- }
-
- // Record the deletion of cookies and cache.
- content::BrowsingDataRemover::CookieOrCacheDeletionChoice choice =
- content::BrowsingDataRemover::NEITHER_COOKIES_NOR_CACHE;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteCookies)) {
- choice = prefs->GetBoolean(browsing_data::prefs::kDeleteCache)
- ? content::BrowsingDataRemover::BOTH_COOKIES_AND_CACHE
- : content::BrowsingDataRemover::ONLY_COOKIES;
- } else if (prefs->GetBoolean(browsing_data::prefs::kDeleteCache)) {
- choice = content::BrowsingDataRemover::ONLY_CACHE;
- }
- UMA_HISTOGRAM_ENUMERATION(
- "History.ClearBrowsingData.UserDeletedCookieOrCacheFromDialog", choice,
- content::BrowsingDataRemover::MAX_CHOICE_VALUE);
-
- // Record the circumstances under which passwords are deleted.
- if (prefs->GetBoolean(browsing_data::prefs::kDeletePasswords)) {
- static const char* other_types[] = {
- browsing_data::prefs::kDeleteBrowsingHistory,
- browsing_data::prefs::kDeleteDownloadHistory,
- browsing_data::prefs::kDeleteCache,
- browsing_data::prefs::kDeleteCookies,
- browsing_data::prefs::kDeleteFormData,
- browsing_data::prefs::kDeleteHostedAppsData,
- browsing_data::prefs::kDeleteMediaLicenses,
- };
- static size_t num_other_types = arraysize(other_types);
- int checked_other_types = std::count_if(
- other_types,
- other_types + num_other_types,
- [prefs](const std::string& pref) { return prefs->GetBoolean(pref); });
- UMA_HISTOGRAM_SPARSE_SLOWLY(
- "History.ClearBrowsingData.PasswordsDeletion.AdditionalDatatypesCount",
- checked_other_types);
- }
-
- remover_ = content::BrowserContext::GetBrowsingDataRemover(profile);
- remover_->AddObserver(this);
- int period_selected =
- prefs->GetInteger(browsing_data::prefs::kDeleteTimePeriod);
- browsing_data::TimePeriod time_period =
- static_cast<browsing_data::TimePeriod>(period_selected);
- browsing_data::RecordDeletionForPeriod(time_period);
- remover_->RemoveAndReply(
- browsing_data::CalculateBeginDeleteTime(time_period),
- browsing_data::CalculateEndDeleteTime(time_period),
- remove_mask, origin_mask, this);
-
- // Store the clear browsing data time. Next time the clear browsing data
- // dialog is open, this time is used to decide whether to display an info
- // banner or not.
- prefs->SetInt64(browsing_data::prefs::kLastClearBrowsingDataTime,
- base::Time::Now().ToInternalValue());
-}
-
-void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() {
- remover_->RemoveObserver(this);
- remover_ = nullptr;
-
- PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
- int notice_shown_times = prefs->GetInteger(
- browsing_data::prefs::kClearBrowsingDataHistoryNoticeShownTimes);
-
- // When the deletion is complete, we might show an additional dialog with
- // a notice about other forms of browsing history. This is the case if
- const bool show_notice =
- // 1. The dialog is relevant for the user.
- should_show_history_deletion_dialog_ &&
- // 2. The selected data types contained browsing history.
- prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory) &&
- // 3. The notice has been shown less than |kMaxTimesHistoryNoticeShown|.
- notice_shown_times < kMaxTimesHistoryNoticeShown;
-
- if (show_notice) {
- // Increment the preference.
- prefs->SetInteger(
- browsing_data::prefs::kClearBrowsingDataHistoryNoticeShownTimes,
- notice_shown_times + 1);
- }
-
- UMA_HISTOGRAM_BOOLEAN(
- "History.ClearBrowsingData.ShownHistoryNoticeAfterClearing", show_notice);
-
- web_ui()->CallJavascriptFunctionUnsafe("ClearBrowserDataOverlay.doneClearing",
- base::Value(show_notice));
-}
-
-void ClearBrowserDataHandler::OnBrowsingHistoryPrefChanged() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ClearBrowserDataOverlay.setAllowDeletingHistory",
- base::Value(*allow_deleting_browser_history_));
-}
-
-void ClearBrowserDataHandler::AddCounter(
- std::unique_ptr<browsing_data::BrowsingDataCounter> counter) {
- DCHECK(AreCountersEnabled());
-
- counter->Init(Profile::FromWebUI(web_ui())->GetPrefs(),
- browsing_data::ClearBrowsingDataTab::ADVANCED,
- base::Bind(&ClearBrowserDataHandler::UpdateCounterText,
- base::Unretained(this)));
- counters_.push_back(std::move(counter));
-}
-
-void ClearBrowserDataHandler::UpdateCounterText(
- std::unique_ptr<browsing_data::BrowsingDataCounter::Result> result) {
- DCHECK(AreCountersEnabled());
- web_ui()->CallJavascriptFunctionUnsafe(
- "ClearBrowserDataOverlay.updateCounter",
- base::Value(result->source()->GetPrefName()),
- base::Value(GetChromeCounterTextFromResult(result.get())));
-}
-
-void ClearBrowserDataHandler::OnStateChanged(syncer::SyncService* sync) {
- UpdateSyncState();
-}
-
-void ClearBrowserDataHandler::UpdateSyncState() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ClearBrowserDataOverlay.updateSyncWarningAndHistoryFooter",
- base::Value(sync_service_ && sync_service_->IsSyncActive()),
- base::Value(should_show_history_notice_));
-}
-
-void ClearBrowserDataHandler::RefreshHistoryNotice() {
- browsing_data::ShouldShowNoticeAboutOtherFormsOfBrowsingHistory(
- sync_service_,
- WebHistoryServiceFactory::GetForProfile(Profile::FromWebUI(web_ui())),
- base::Bind(&ClearBrowserDataHandler::UpdateHistoryNotice,
- weak_ptr_factory_.GetWeakPtr()));
-
- // If the dialog with history notice has been shown less than
- // |kMaxTimesHistoryNoticeShown| times, we might have to show it when the
- // user deletes history. Find out if the conditions are met.
- int notice_shown_times = Profile::FromWebUI(web_ui())->GetPrefs()->GetInteger(
- browsing_data::prefs::kClearBrowsingDataHistoryNoticeShownTimes);
-
- if (notice_shown_times < kMaxTimesHistoryNoticeShown) {
- browsing_data::ShouldPopupDialogAboutOtherFormsOfBrowsingHistory(
- sync_service_,
- WebHistoryServiceFactory::GetForProfile(Profile::FromWebUI(web_ui())),
- chrome::GetChannel(),
- base::Bind(&ClearBrowserDataHandler::UpdateHistoryDeletionDialog,
- weak_ptr_factory_.GetWeakPtr()));
- }
-}
-
-void ClearBrowserDataHandler::UpdateHistoryNotice(bool show) {
- should_show_history_notice_ = show;
- UpdateSyncState();
-
- UMA_HISTOGRAM_BOOLEAN(
- "History.ClearBrowsingData.HistoryNoticeShownInFooterWhenUpdated",
- should_show_history_notice_);
-}
-
-void ClearBrowserDataHandler::UpdateHistoryDeletionDialog(bool show) {
- // This is used by OnBrowsingDataRemoverDone (when the deletion finishes).
- should_show_history_deletion_dialog_ = show;
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.h b/chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.h
deleted file mode 100644
index 8c6a259f66c..00000000000
--- a/chromium/chrome/browser/ui/webui/options/clear_browser_data_handler.h
+++ /dev/null
@@ -1,108 +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_OPTIONS_CLEAR_BROWSER_DATA_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CLEAR_BROWSER_DATA_HANDLER_H_
-
-#include <memory>
-#include <vector>
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/browser_sync/profile_sync_service.h"
-#include "components/browsing_data/core/counters/browsing_data_counter.h"
-#include "components/prefs/pref_member.h"
-#include "content/public/browser/browsing_data_remover.h"
-
-namespace options {
-
-// Clear browser data handler page UI handler.
-class ClearBrowserDataHandler : public OptionsPageUIHandler,
- public content::BrowsingDataRemover::Observer,
- public syncer::SyncServiceObserver {
- public:
- ClearBrowserDataHandler();
- ~ClearBrowserDataHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- void UpdateInfoBannerVisibility();
-
- private:
- // Javascript callback for when the CBD dialog is opened. The caller does
- // not provide any parameters, so |value| is unused.
- void OnPageOpened(const base::ListValue* value);
-
- // Javascript callback to start clearing data.
- void HandleClearBrowserData(const base::ListValue* value);
-
- // BrowsingDataRemover::Observer implementation.
- // Closes the dialog once all requested data has been removed.
- void OnBrowsingDataRemoverDone() override;
-
- // Updates UI when the pref to allow clearing history changes.
- virtual void OnBrowsingHistoryPrefChanged();
-
- // Adds a |counter| for browsing data.
- void AddCounter(std::unique_ptr<browsing_data::BrowsingDataCounter> counter);
-
- // Updates a counter in the UI according to the |result|.
- void UpdateCounterText(
- std::unique_ptr<browsing_data::BrowsingDataCounter::Result> result);
-
- // Implementation of SyncServiceObserver.
- void OnStateChanged(syncer::SyncService* sync) override;
-
- // Updates the support string at the bottom of the dialog.
- void UpdateSyncState();
-
- // Finds out whether we should show a notice informing the user about other
- // forms of browsing history. Responds with an asynchronous callback to
- // |UpdateHistoryNotice|.
- void RefreshHistoryNotice();
-
- // Shows or hides the notice about other forms of browsing history.
- void UpdateHistoryNotice(bool show);
-
- // Remembers whether we should popup a dialog about other forms of browsing
- // history when the user deletes the history for the first time.
- void UpdateHistoryDeletionDialog(bool show);
-
- // If non-null it means removal is in progress.
- content::BrowsingDataRemover* remover_;
-
- // Keeps track of whether clearing LSO data is supported.
- BooleanPrefMember clear_plugin_lso_data_enabled_;
-
- // Keeps track of whether deleting browsing history and downloads is allowed.
- BooleanPrefMember allow_deleting_browser_history_;
-
- // Counters that calculate the data volume for some of the data types.
- std::vector<std::unique_ptr<browsing_data::BrowsingDataCounter>> counters_;
-
- // Informs us whether the user is syncing their data.
- browser_sync::ProfileSyncService* sync_service_;
-
- // Whether we should show a notice about other forms of browsing history.
- bool should_show_history_notice_;
-
- // Whether we should popup a dialog about other forms of browsing history
- // when the user deletes their browsing history for the first time.
- bool should_show_history_deletion_dialog_;
-
- // A weak pointer factory for asynchronous calls referencing this class.
- base::WeakPtrFactory<ClearBrowserDataHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(ClearBrowserDataHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CLEAR_BROWSER_DATA_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/content_settings_handler.cc b/chromium/chrome/browser/ui/webui/options/content_settings_handler.cc
deleted file mode 100644
index 074fa9710d7..00000000000
--- a/chromium/chrome/browser/ui/webui/options/content_settings_handler.cc
+++ /dev/null
@@ -1,1492 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/content_settings_handler.h"
-
-#include <stddef.h>
-
-#include <algorithm>
-#include <map>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/i18n/number_formatting.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/user_metrics.h"
-#include "base/stl_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
-#include "chrome/browser/content_settings/web_site_settings_uma_util.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
-#include "chrome/browser/extensions/extension_special_storage_policy.h"
-#include "chrome/browser/notifications/desktop_notification_profile_util.h"
-#include "chrome/browser/permissions/chooser_context_base.h"
-#include "chrome/browser/permissions/permission_uma_util.h"
-#include "chrome/browser/permissions/permission_util.h"
-#include "chrome/browser/plugins/plugin_utils.h"
-#include "chrome/browser/plugins/plugins_field_trial.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/browser_list.h"
-#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
-#include "chrome/browser/ui/webui/site_settings_helper.h"
-#include "chrome/browser/usb/usb_chooser_context.h"
-#include "chrome/browser/usb/usb_chooser_context_factory.h"
-#include "chrome/common/chrome_features.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
-#include "chrome/common/features.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "chrome/grit/locale_settings.h"
-#include "components/content_settings/core/browser/content_settings_details.h"
-#include "components/content_settings/core/browser/content_settings_utils.h"
-#include "components/content_settings/core/browser/host_content_settings_map.h"
-#include "components/content_settings/core/browser/website_settings_info.h"
-#include "components/content_settings/core/browser/website_settings_registry.h"
-#include "components/content_settings/core/common/content_settings.h"
-#include "components/content_settings/core/common/content_settings_pattern.h"
-#include "components/google/core/browser/google_util.h"
-#include "components/prefs/pref_service.h"
-#include "components/signin/core/common/profile_management_switches.h"
-#include "components/user_prefs/user_prefs.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/notification_source.h"
-#include "content/public/browser/notification_types.h"
-#include "content/public/browser/storage_partition.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/common/content_switches.h"
-#include "content/public/common/page_zoom.h"
-#include "content/public/common/url_constants.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/common/extension_set.h"
-#include "extensions/common/permissions/api_permission.h"
-#include "extensions/common/permissions/permissions_data.h"
-#include "ppapi/features/features.h"
-#include "ui/base/l10n/l10n_util.h"
-
-#if defined(OS_CHROMEOS)
-#include "components/user_manager/user_manager.h"
-#endif
-
-using base::UserMetricsAction;
-using content_settings::ContentSettingToString;
-using content_settings::ContentSettingFromString;
-using extensions::APIPermission;
-
-namespace options {
-
-namespace {
-
-struct ContentSettingWithExceptions {
- ContentSettingWithExceptions(bool otr, UserMetricsAction action)
- : has_otr_exceptions(otr), uma(action) {}
- bool has_otr_exceptions;
- UserMetricsAction uma;
-};
-
-// The AppFilter is used in AddExceptionsGrantedByHostedApps() to choose
-// extensions which should have their extent displayed.
-typedef bool (*AppFilter)(const extensions::Extension& app,
- content::BrowserContext* profile);
-
-const char kAppName[] = "appName";
-const char kAppId[] = "appId";
-const char kZoom[] = "zoom";
-
-// A pseudo content type. We use it to display data like a content setting even
-// though it is not a real content setting.
-const char kZoomContentType[] = "zoomlevels";
-
-// Maps from a content settings type to a content setting with exceptions
-// struct.
-typedef std::map<ContentSettingsType, ContentSettingWithExceptions>
- ExceptionsInfoMap;
-
-const ExceptionsInfoMap& GetExceptionsInfoMap() {
- CR_DEFINE_STATIC_LOCAL(ExceptionsInfoMap, exceptions_info_map, ());
- if (exceptions_info_map.empty()) {
- // With OTR exceptions.
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_COOKIES,
- ContentSettingWithExceptions(
- true, UserMetricsAction("Options_DefaultCookieSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_IMAGES,
- ContentSettingWithExceptions(
- true, UserMetricsAction("Options_DefaultImagesSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_JAVASCRIPT,
- ContentSettingWithExceptions(
- true,
- UserMetricsAction("Options_DefaultJavaScriptSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_PLUGINS,
- ContentSettingWithExceptions(
- true, UserMetricsAction("Options_DefaultPluginsSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_POPUPS,
- ContentSettingWithExceptions(
- true, UserMetricsAction("Options_DefaultPopupsSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_PPAPI_BROKER,
- ContentSettingWithExceptions(
- true,
- UserMetricsAction("Options_DefaultPPAPIBrokerSettingChanged"))));
-#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER,
- ContentSettingWithExceptions(
- true,
- UserMetricsAction(
- "Options_DefaultProtectedMediaIdentifierSettingChanged"))));
-#endif
-
- // Without OTR exceptions.
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
- ContentSettingWithExceptions(
- false,
- UserMetricsAction("Options_DefaultNotificationsSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_GEOLOCATION,
- ContentSettingWithExceptions(
- false,
- UserMetricsAction("Options_DefaultGeolocationSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC,
- ContentSettingWithExceptions(
- false,
- UserMetricsAction("Options_DefaultMediaStreamMicSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA,
- ContentSettingWithExceptions(
- false, UserMetricsAction(
- "Options_DefaultMediaStreamCameraSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_AUTOMATIC_DOWNLOADS,
- ContentSettingWithExceptions(
- false, UserMetricsAction(
- "Options_DefaultMultipleAutomaticDLSettingChange"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_MIDI_SYSEX,
- ContentSettingWithExceptions(
- false,
- UserMetricsAction("Options_DefaultMIDISysExSettingChanged"))));
- exceptions_info_map.insert(std::make_pair(
- CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC,
- ContentSettingWithExceptions(
- false,
- UserMetricsAction("Options_DefaultBackgroundSyncSettingChanged"))));
- }
-
- return exceptions_info_map;
-}
-
-content::BrowserContext* GetBrowserContext(content::WebUI* web_ui) {
- return web_ui->GetWebContents()->GetBrowserContext();
-}
-
-// Create a DictionaryValue* that will act as a data source for a single row
-// in the Geolocation exceptions table.
-std::unique_ptr<base::DictionaryValue> GetGeolocationExceptionForPage(
- const ContentSettingsPattern& origin,
- const ContentSettingsPattern& embedding_origin,
- ContentSetting setting) {
- auto exception = base::MakeUnique<base::DictionaryValue>();
-
- std::string setting_string =
- content_settings::ContentSettingToString(setting);
- DCHECK(!setting_string.empty());
-
- exception->SetString(site_settings::kSetting, setting_string);
- exception->SetString(site_settings::kOrigin, origin.ToString());
- exception->SetString(
- site_settings::kEmbeddingOrigin, embedding_origin.ToString());
- return exception;
-}
-
-// Create a DictionaryValue* that will act as a data source for a single row
-// in the desktop notifications exceptions table.
-std::unique_ptr<base::DictionaryValue> GetNotificationExceptionForPage(
- const ContentSettingsPattern& primary_pattern,
- const ContentSettingsPattern& secondary_pattern,
- ContentSetting setting,
- const std::string& provider_name) {
- std::string embedding_origin;
- if (secondary_pattern != ContentSettingsPattern::Wildcard())
- embedding_origin = secondary_pattern.ToString();
-
- auto exception = base::MakeUnique<base::DictionaryValue>();
-
- std::string setting_string =
- content_settings::ContentSettingToString(setting);
- DCHECK(!setting_string.empty());
-
- exception->SetString(site_settings::kSetting, setting_string);
- exception->SetString(site_settings::kOrigin, primary_pattern.ToString());
- exception->SetString(site_settings::kEmbeddingOrigin, embedding_origin);
- exception->SetString(site_settings::kSource, provider_name);
- return exception;
-}
-
-// Returns true whenever the |extension| is hosted and has |permission|.
-// Must have the AppFilter signature.
-template <APIPermission::ID permission>
-bool HostedAppHasPermission(const extensions::Extension& extension,
- content::BrowserContext* /* context */) {
- return extension.is_hosted_app() &&
- extension.permissions_data()->HasAPIPermission(permission);
-}
-
-// Add an "Allow"-entry to the list of |exceptions| for a |url_pattern| from
-// the web extent of a hosted |app|.
-void AddExceptionForHostedApp(const std::string& url_pattern,
- const extensions::Extension& app, base::ListValue* exceptions) {
- std::unique_ptr<base::DictionaryValue> exception(new base::DictionaryValue());
-
- std::string setting_string =
- content_settings::ContentSettingToString(CONTENT_SETTING_ALLOW);
- DCHECK(!setting_string.empty());
-
- exception->SetString(site_settings::kSetting, setting_string);
- exception->SetString(site_settings::kOrigin, url_pattern);
- exception->SetString(site_settings::kEmbeddingOrigin, url_pattern);
- exception->SetString(site_settings::kSource, "HostedApp");
- exception->SetString(kAppName, app.name());
- exception->SetString(kAppId, app.id());
- exceptions->Append(std::move(exception));
-}
-
-// Asks the |profile| for hosted apps which have the |permission| set, and
-// adds their web extent and launch URL to the |exceptions| list.
-void AddExceptionsGrantedByHostedApps(content::BrowserContext* context,
- AppFilter app_filter,
- base::ListValue* exceptions) {
- const extensions::ExtensionSet& extensions =
- extensions::ExtensionRegistry::Get(context)->enabled_extensions();
- for (extensions::ExtensionSet::const_iterator extension = extensions.begin();
- extension != extensions.end(); ++extension) {
- if (!app_filter(*extension->get(), context))
- continue;
-
- extensions::URLPatternSet web_extent = (*extension)->web_extent();
- // Add patterns from web extent.
- for (extensions::URLPatternSet::const_iterator pattern = web_extent.begin();
- pattern != web_extent.end(); ++pattern) {
- std::string url_pattern = pattern->GetAsString();
- AddExceptionForHostedApp(url_pattern, *extension->get(), exceptions);
- }
- // Retrieve the launch URL.
- GURL launch_url =
- extensions::AppLaunchInfo::GetLaunchWebURL(extension->get());
- // Skip adding the launch URL if it is part of the web extent.
- if (web_extent.MatchesURL(launch_url))
- continue;
- AddExceptionForHostedApp(launch_url.spec(), *extension->get(), exceptions);
- }
-}
-
-} // namespace
-
-ContentSettingsHandler::MediaSettingsInfo::MediaSettingsInfo() {
-}
-
-ContentSettingsHandler::MediaSettingsInfo::~MediaSettingsInfo() {
-}
-
-ContentSettingsHandler::MediaSettingsInfo::ForFlash::ForFlash()
- : default_setting(CONTENT_SETTING_DEFAULT),
- initialized(false),
- last_refresh_request_id(0) {
-}
-
-ContentSettingsHandler::MediaSettingsInfo::ForFlash::~ForFlash() {
-}
-
-ContentSettingsHandler::MediaSettingsInfo::ForFlash&
- ContentSettingsHandler::MediaSettingsInfo::forFlash() {
- return flash_settings_;
-}
-
-ContentSettingsHandler::MediaSettingsInfo::ForOneType&
- ContentSettingsHandler::MediaSettingsInfo::forType(
- ContentSettingsType type) {
- if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC)
- return mic_settings_;
- else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA)
- return camera_settings_;
-
- NOTREACHED();
- return mic_settings_;
-}
-
-ContentSettingsHandler::MediaSettingsInfo::ForOneType::ForOneType()
- : show_flash_default_link(false),
- show_flash_exceptions_link(false),
- default_setting(CONTENT_SETTING_DEFAULT),
- policy_disable(false),
- default_setting_initialized(false),
- exceptions_initialized(false) {
-}
-
-ContentSettingsHandler::MediaSettingsInfo::ForOneType::~ForOneType() {
-}
-
-ContentSettingsHandler::ContentSettingsHandler() : observer_(this) {
-}
-
-ContentSettingsHandler::~ContentSettingsHandler() {
-}
-
-void ContentSettingsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- {"allowException", IDS_EXCEPTIONS_ALLOW_BUTTON},
- {"blockException", IDS_EXCEPTIONS_BLOCK_BUTTON},
- {"sessionException", IDS_EXCEPTIONS_SESSION_ONLY_BUTTON},
- {"askException", IDS_EXCEPTIONS_ASK_BUTTON},
- {"otrExceptionsExplanation", IDS_EXCEPTIONS_OTR_LABEL},
- {"addNewExceptionInstructions", IDS_EXCEPTIONS_ADD_NEW_INSTRUCTIONS},
- {"manageExceptions", IDS_EXCEPTIONS_MANAGE},
- {"manageHandlers", IDS_HANDLERS_MANAGE},
- {"exceptionPatternHeader", IDS_EXCEPTIONS_PATTERN_HEADER},
- {"exceptionBehaviorHeader", IDS_EXCEPTIONS_ACTION_HEADER},
- {"exceptionUsbDeviceHeader", IDS_EXCEPTIONS_USB_DEVICE_HEADER},
- {"exceptionZoomHeader", IDS_EXCEPTIONS_ZOOM_HEADER},
- {"embeddedOnHost", IDS_EXCEPTIONS_GEOLOCATION_EMBEDDED_ON_HOST},
- // Cookies filter.
- {"cookiesTabLabel", IDS_COOKIES_TAB_LABEL},
- {"cookiesHeader", IDS_COOKIES_HEADER},
- {"cookiesAllow", IDS_COOKIES_ALLOW_RADIO},
- {"cookiesBlock", IDS_COOKIES_BLOCK_RADIO},
- {"cookiesSessionOnly", IDS_COOKIES_SESSION_ONLY_RADIO},
- {"cookiesBlock3rdParty", IDS_COOKIES_BLOCK_3RDPARTY_CHKBOX},
- {"cookiesShowCookies", IDS_COOKIES_SHOW_COOKIES_BUTTON},
- {"flashStorageSettings", IDS_FLASH_STORAGE_SETTINGS},
- {"flashStorageUrl", IDS_FLASH_STORAGE_URL},
-#if BUILDFLAG(ENABLE_GOOGLE_NOW)
- {"googleGeolocationAccessEnable",
- IDS_GEOLOCATION_GOOGLE_ACCESS_ENABLE_CHKBOX},
-#endif
- // Image filter.
- {"imagesTabLabel", IDS_IMAGES_TAB_LABEL},
- {"imagesHeader", IDS_IMAGES_HEADER},
- {"imagesAllow", IDS_IMAGES_LOAD_RADIO},
- {"imagesBlock", IDS_IMAGES_NOLOAD_RADIO},
- // JavaScript filter.
- {"javascriptTabLabel", IDS_JAVASCRIPT_TAB_LABEL},
- {"javascriptHeader", IDS_JAVASCRIPT_HEADER},
- {"javascriptAllow", IDS_JS_ALLOW_RADIO},
- {"javascriptBlock", IDS_JS_DONOTALLOW_RADIO},
- // Plugins filter.
- {"pluginsTabLabel", IDS_FLASH_TAB_LABEL},
- {"pluginsHeader", IDS_FLASH_HEADER},
- {"pluginsAllow", IDS_FLASH_ALLOW_RADIO},
- {"pluginsBlock", IDS_FLASH_BLOCK_RADIO},
- // Pop-ups filter.
- {"popupsTabLabel", IDS_POPUP_TAB_LABEL},
- {"popupsHeader", IDS_POPUP_HEADER},
- {"popupsAllow", IDS_POPUP_ALLOW_RADIO},
- {"popupsBlock", IDS_POPUP_BLOCK_RADIO},
- // Location filter.
- {"locationTabLabel", IDS_GEOLOCATION_TAB_LABEL},
- {"locationHeader", IDS_GEOLOCATION_HEADER},
- {"locationAllow", IDS_GEOLOCATION_ALLOW_RADIO},
- {"locationAsk", IDS_GEOLOCATION_ASK_RADIO},
- {"locationBlock", IDS_GEOLOCATION_BLOCK_RADIO},
- {"setBy", IDS_GEOLOCATION_SET_BY_HOVER},
- // Notifications filter.
- {"notificationsTabLabel", IDS_NOTIFICATIONS_TAB_LABEL},
- {"notificationsHeader", IDS_NOTIFICATIONS_HEADER},
- {"notificationsAllow", IDS_NOTIFICATIONS_ALLOW_RADIO},
- {"notificationsAsk", IDS_NOTIFICATIONS_ASK_RADIO},
- {"notificationsBlock", IDS_NOTIFICATIONS_BLOCK_RADIO},
- // Protected Content filter
- {"protectedContentTabLabel", IDS_PROTECTED_CONTENT_TAB_LABEL},
- {"protectedContentEnableCheckbox", IDS_PROTECTED_CONTENT_ENABLE_CHECKBOX},
-#if defined(OS_CHROMEOS) || defined(OS_WIN)
- {"protectedContentInfo", IDS_PROTECTED_CONTENT_INFO},
- {"protectedContentEnableIdentifiersCheckbox",
- IDS_PROTECTED_CONTENT_ENABLE_IDENTIFIERS_CHECKBOX},
- {"protectedContentHeader", IDS_PROTECTED_CONTENT_HEADER},
-#endif // defined(OS_CHROMEOS) || defined(OS_WIN)
- // Microphone filter.
- {"mediaStreamMicTabLabel", IDS_MEDIA_STREAM_MIC_TAB_LABEL},
- {"mediaStreamMicHeader", IDS_MEDIA_STREAM_MIC_HEADER},
- {"mediaStreamMicAsk", IDS_MEDIA_STREAM_ASK_AUDIO_ONLY_RADIO},
- {"mediaStreamMicBlock", IDS_MEDIA_STREAM_BLOCK_AUDIO_ONLY_RADIO},
- // Camera filter.
- {"mediaStreamCameraTabLabel", IDS_MEDIA_STREAM_CAMERA_TAB_LABEL},
- {"mediaStreamCameraHeader", IDS_MEDIA_STREAM_CAMERA_HEADER},
- {"mediaStreamCameraAsk", IDS_MEDIA_STREAM_ASK_VIDEO_ONLY_RADIO},
- {"mediaStreamCameraBlock", IDS_MEDIA_STREAM_BLOCK_VIDEO_ONLY_RADIO},
- // Flash media settings.
- {"mediaPepperFlashMicDefaultDivergedLabel",
- IDS_MEDIA_PEPPER_FLASH_MIC_DEFAULT_DIVERGED_LABEL},
- {"mediaPepperFlashCameraDefaultDivergedLabel",
- IDS_MEDIA_PEPPER_FLASH_CAMERA_DEFAULT_DIVERGED_LABEL},
- {"mediaPepperFlashMicExceptionsDivergedLabel",
- IDS_MEDIA_PEPPER_FLASH_MIC_EXCEPTIONS_DIVERGED_LABEL},
- {"mediaPepperFlashCameraExceptionsDivergedLabel",
- IDS_MEDIA_PEPPER_FLASH_CAMERA_EXCEPTIONS_DIVERGED_LABEL},
- {"mediaPepperFlashChangeLink", IDS_MEDIA_PEPPER_FLASH_CHANGE_LINK},
- {"mediaPepperFlashGlobalPrivacyURL", IDS_FLASH_GLOBAL_PRIVACY_URL},
- {"mediaPepperFlashWebsitePrivacyURL", IDS_FLASH_WEBSITE_PRIVACY_URL},
- // PPAPI broker filter.
- {"ppapiBrokerHeader", IDS_PPAPI_BROKER_HEADER},
- {"ppapiBrokerTabLabel", IDS_PPAPI_BROKER_TAB_LABEL},
- {"ppapiBrokerAllow", IDS_PPAPI_BROKER_ALLOW_RADIO},
- {"ppapiBrokerAsk", IDS_PPAPI_BROKER_ASK_RADIO},
- {"ppapiBrokerBlock", IDS_PPAPI_BROKER_BLOCK_RADIO},
- // Multiple automatic downloads.
- {"multipleAutomaticDownloadsTabLabel", IDS_AUTOMATIC_DOWNLOADS_TAB_LABEL},
- {"multipleAutomaticDownloadsHeader", IDS_AUTOMATIC_DOWNLOADS_TAB_LABEL},
- {"multipleAutomaticDownloadsAllow", IDS_AUTOMATIC_DOWNLOADS_ALLOW_RADIO},
- {"multipleAutomaticDownloadsAsk", IDS_AUTOMATIC_DOWNLOADS_ASK_RADIO},
- {"multipleAutomaticDownloadsBlock", IDS_AUTOMATIC_DOWNLOADS_BLOCK_RADIO},
- // MIDI system exclusive messages.
- {"midiSysexHeader", IDS_MIDI_SYSEX_TAB_LABEL},
- {"midiSysExAllow", IDS_MIDI_SYSEX_ALLOW_RADIO},
- {"midiSysExAsk", IDS_MIDI_SYSEX_ASK_RADIO},
- {"midiSysExBlock", IDS_MIDI_SYSEX_BLOCK_RADIO},
- // Push messaging strings.
- {"pushMessagingHeader", IDS_PUSH_MESSAGES_TAB_LABEL},
- {"pushMessagingAllow", IDS_PUSH_MESSSAGING_ALLOW_RADIO},
- {"pushMessagingAsk", IDS_PUSH_MESSSAGING_ASK_RADIO},
- {"pushMessagingBlock", IDS_PUSH_MESSSAGING_BLOCK_RADIO},
- // USB devices.
- {"usbDevicesHeader", IDS_USB_DEVICES_HEADER_AND_TAB_LABEL},
- {"usbDevicesManage", IDS_USB_DEVICES_MANAGE_BUTTON},
- // Background sync.
- {"backgroundSyncHeader", IDS_BACKGROUND_SYNC_HEADER},
- {"backgroundSyncAllow", IDS_BACKGROUND_SYNC_ALLOW_RADIO},
- {"backgroundSyncBlock", IDS_BACKGROUND_SYNC_BLOCK_RADIO},
- // Zoom levels.
- {"zoomlevelsHeader", IDS_ZOOMLEVELS_HEADER_AND_TAB_LABEL},
- {"zoomLevelsManage", IDS_ZOOMLEVELS_MANAGE_BUTTON},
- // PDF Plugin filter.
- {"pdfTabLabel", IDS_PDF_TAB_LABEL},
- {"pdfEnable", IDS_PDF_ENABLE_CHECKBOX},
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-
- // TODO(tommycli): When the HTML5 By Default feature flag is on, we want to
- // display strings that begin with "Ask...", even though the setting remains
- // DETECT. Once this feature is finalized, then we migrate the setting to ASK.
- Profile* profile = Profile::FromWebUI(web_ui());
- bool is_hbd = PluginUtils::ShouldPreferHtmlOverPlugins(
- HostContentSettingsMapFactory::GetForProfile(profile));
- static OptionsStringResource flash_strings[] = {
- {"pluginsDetectImportantContent",
- is_hbd ? IDS_FLASH_ASK_RECOMMENDED_RADIO
- : IDS_FLASH_DETECT_RECOMMENDED_RADIO},
- {"detectException",
- is_hbd ? IDS_EXCEPTIONS_ASK_BUTTON
- : IDS_EXCEPTIONS_DETECT_IMPORTANT_CONTENT_BUTTON},
- };
- RegisterStrings(localized_strings, flash_strings, arraysize(flash_strings));
-
- PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
- const base::Value* default_pref = prefs->GetDefaultPrefValue(
- content_settings::WebsiteSettingsRegistry::GetInstance()
- ->Get(CONTENT_SETTINGS_TYPE_PLUGINS)
- ->default_value_pref_name());
-
- int default_value = CONTENT_SETTING_DEFAULT;
- bool success = default_pref->GetAsInteger(&default_value);
- DCHECK(success);
- DCHECK_NE(CONTENT_SETTING_DEFAULT, default_value);
-
- RegisterTitle(localized_strings, "contentSettingsPage",
- IDS_CONTENT_SETTINGS_TITLE);
-
- // Register titles for each of the individual settings whose exception
- // dialogs will be processed by |ContentSettingsHandler|.
- RegisterTitle(localized_strings, "cookies",
- IDS_COOKIES_TAB_LABEL);
- RegisterTitle(localized_strings, "images",
- IDS_IMAGES_TAB_LABEL);
- RegisterTitle(localized_strings, "javascript",
- IDS_JAVASCRIPT_TAB_LABEL);
- RegisterTitle(localized_strings, "plugins", IDS_FLASH_TAB_LABEL);
- RegisterTitle(localized_strings, "popups",
- IDS_POPUP_TAB_LABEL);
- RegisterTitle(localized_strings, "location",
- IDS_GEOLOCATION_TAB_LABEL);
- RegisterTitle(localized_strings, "notifications",
- IDS_NOTIFICATIONS_TAB_LABEL);
-#if defined(OS_CHROMEOS)
- RegisterTitle(localized_strings, "protectedContent",
- IDS_PROTECTED_CONTENT_TAB_LABEL);
-#endif
- RegisterTitle(localized_strings, "media-stream-mic",
- IDS_MEDIA_STREAM_MIC_TAB_LABEL);
- RegisterTitle(localized_strings, "media-stream-camera",
- IDS_MEDIA_STREAM_CAMERA_TAB_LABEL);
- RegisterTitle(localized_strings, "ppapi-broker",
- IDS_PPAPI_BROKER_TAB_LABEL);
- RegisterTitle(localized_strings, "multiple-automatic-downloads",
- IDS_AUTOMATIC_DOWNLOADS_TAB_LABEL);
- RegisterTitle(localized_strings, "midi-sysex",
- IDS_MIDI_SYSEX_TAB_LABEL);
- RegisterTitle(localized_strings, "usb-devices",
- IDS_USB_DEVICES_HEADER_AND_TAB_LABEL);
- RegisterTitle(localized_strings, "background-sync",
- IDS_BACKGROUND_SYNC_HEADER);
- RegisterTitle(localized_strings, "zoomlevels",
- IDS_ZOOMLEVELS_HEADER_AND_TAB_LABEL);
-
- localized_strings->SetString("exceptionsLearnMoreUrl",
- chrome::kContentSettingsExceptionsLearnMoreURL);
-}
-
-void ContentSettingsHandler::InitializeHandler() {
- notification_registrar_.Add(
- this, chrome::NOTIFICATION_PROFILE_CREATED,
- content::NotificationService::AllSources());
- notification_registrar_.Add(
- this, chrome::NOTIFICATION_PROFILE_DESTROYED,
- content::NotificationService::AllSources());
-
- content::BrowserContext* context = GetBrowserContext(web_ui());
- notification_registrar_.Add(
- this, chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
- content::Source<content::BrowserContext>(context));
-
- PrefService* prefs = user_prefs::UserPrefs::Get(context);
- pref_change_registrar_.Init(prefs);
- pref_change_registrar_.Add(
- prefs::kPepperFlashSettingsEnabled,
- base::Bind(&ContentSettingsHandler::OnPepperFlashPrefChanged,
- base::Unretained(this)));
- pref_change_registrar_.Add(
- prefs::kAudioCaptureAllowed,
- base::Bind(&ContentSettingsHandler::UpdateSettingDefaultFromModel,
- base::Unretained(this),
- CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC));
- pref_change_registrar_.Add(
- prefs::kAudioCaptureAllowedUrls,
- base::Bind(&ContentSettingsHandler::UpdateExceptionsViewFromModel,
- base::Unretained(this),
- CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC));
- pref_change_registrar_.Add(
- prefs::kVideoCaptureAllowed,
- base::Bind(&ContentSettingsHandler::UpdateSettingDefaultFromModel,
- base::Unretained(this),
- CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA));
- pref_change_registrar_.Add(
- prefs::kVideoCaptureAllowedUrls,
- base::Bind(&ContentSettingsHandler::UpdateExceptionsViewFromModel,
- base::Unretained(this),
- CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA));
- pref_change_registrar_.Add(
- prefs::kEnableDRM,
- base::Bind(
- &ContentSettingsHandler::UpdateProtectedContentExceptionsButton,
- base::Unretained(this)));
-
- // Here we only subscribe to the HostZoomMap for the default storage partition
- // since we don't allow the user to manage the zoom levels for apps.
- // We're only interested in zoom-levels that are persisted, since the user
- // is given the opportunity to view/delete these in the content-settings page.
- host_zoom_map_subscription_ =
- content::HostZoomMap::GetDefaultForBrowserContext(context)
- ->AddZoomLevelChangedCallback(
- base::Bind(&ContentSettingsHandler::OnZoomLevelChanged,
- base::Unretained(this)));
-
- flash_settings_manager_.reset(new PepperFlashSettingsManager(this, context));
-
- Profile* profile = Profile::FromWebUI(web_ui());
- observer_.Add(HostContentSettingsMapFactory::GetForProfile(profile));
- if (profile->HasOffTheRecordProfile()) {
- auto* map = HostContentSettingsMapFactory::GetForProfile(
- profile->GetOffTheRecordProfile());
- if (!observer_.IsObserving(map))
- observer_.Add(map);
- }
-}
-
-void ContentSettingsHandler::InitializePage() {
- media_settings_.reset(new MediaSettingsInfo());
- RefreshFlashMediaSettings();
-
- UpdateHandlersEnabledRadios();
- UpdateAllExceptionsViewsFromModel();
- UpdateAllChooserExceptionsViewsFromModel();
- UpdateProtectedContentExceptionsButton();
-}
-
-void ContentSettingsHandler::OnContentSettingChanged(
- const ContentSettingsPattern& primary_pattern,
- const ContentSettingsPattern& secondary_pattern,
- ContentSettingsType content_type,
- std::string resource_identifier) {
- const ContentSettingsDetails details(
- primary_pattern, secondary_pattern, content_type, resource_identifier);
- // TODO(estade): we pretend update_all() is always true.
- if (details.update_all_types()) {
- UpdateAllExceptionsViewsFromModel();
- UpdateAllChooserExceptionsViewsFromModel();
- } else {
- if (base::ContainsKey(GetExceptionsInfoMap(), details.type()))
- UpdateExceptionsViewFromModel(details.type());
- }
-}
-
-void ContentSettingsHandler::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- switch (type) {
- case chrome::NOTIFICATION_PROFILE_DESTROYED: {
- Profile* profile = content::Source<Profile>(source).ptr();
- HostContentSettingsMap* settings_map =
- HostContentSettingsMapFactory::GetForProfile(profile);
- if (profile->IsOffTheRecord() &&
- observer_.IsObserving(settings_map)) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettingsExceptionsArea.OTRProfileDestroyed");
- observer_.Remove(settings_map);
- }
- break;
- }
-
- case chrome::NOTIFICATION_PROFILE_CREATED: {
- Profile* profile = content::Source<Profile>(source).ptr();
- if (profile->IsOffTheRecord()) {
- UpdateAllOTRExceptionsViewsFromModel();
- UpdateAllOTRChooserExceptionsViewsFromModel();
- observer_.Add(HostContentSettingsMapFactory::GetForProfile(profile));
- }
- break;
- }
-
- case chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED: {
- UpdateHandlersEnabledRadios();
- break;
- }
- }
-}
-
-void ContentSettingsHandler::OnGetPermissionSettingsCompleted(
- uint32_t request_id,
- bool success,
- PP_Flash_BrowserOperations_Permission default_permission,
- const ppapi::FlashSiteSettings& sites) {
- MediaSettingsInfo::ForFlash& settings = media_settings_->forFlash();
- if (success && request_id == settings.last_refresh_request_id) {
- settings.initialized = true;
- settings.default_setting =
- PepperFlashContentSettingsUtils::FlashPermissionToContentSetting(
- default_permission);
- PepperFlashContentSettingsUtils::FlashSiteSettingsToMediaExceptions(
- sites, &settings.exceptions);
- PepperFlashContentSettingsUtils::SortMediaExceptions(
- &settings.exceptions);
-
- UpdateFlashMediaLinksVisibility(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
- UpdateFlashMediaLinksVisibility(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
- }
-}
-
-void ContentSettingsHandler::UpdateSettingDefaultFromModel(
- ContentSettingsType type) {
- std::string provider_id;
- HostContentSettingsMap* host_content_settings_map =
- HostContentSettingsMapFactory::GetForProfile(GetProfile());
- ContentSetting default_setting =
- host_content_settings_map->GetDefaultContentSetting(type, &provider_id);
-
-#if BUILDFLAG(ENABLE_PLUGINS)
- default_setting = PluginsFieldTrial::EffectiveContentSetting(
- host_content_settings_map, type, default_setting);
-#endif
-
- // Camera and microphone default content settings cannot be set by the policy.
- // However, the policy can disable them. Treat this case visually in the same
- // way as if the policy set the default setting to BLOCK. Furthermore, compare
- // the settings with Flash settings and show links to the Flash settings site
- // if they differ.
- if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC ||
- type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
- UpdateMediaSettingsFromPrefs(type);
- if (media_settings_->forType(type).policy_disable) {
- default_setting = CONTENT_SETTING_BLOCK;
- provider_id = site_settings::kPolicyProviderId;
- }
- }
-
- base::DictionaryValue filter_settings;
-
- std::string setting_string =
- content_settings::ContentSettingToString(default_setting);
- DCHECK(!setting_string.empty());
-
- filter_settings.SetString(
- site_settings::ContentSettingsTypeToGroupName(type) + ".value",
- setting_string);
- filter_settings.SetString(
- site_settings::ContentSettingsTypeToGroupName(type) + ".managedBy",
- provider_id);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettings.setContentFilterSettingsValue", filter_settings);
-}
-
-void ContentSettingsHandler::UpdateMediaSettingsFromPrefs(
- ContentSettingsType type) {
- PrefService* prefs = user_prefs::UserPrefs::Get(GetBrowserContext(web_ui()));
- HostContentSettingsMap* settings_map =
- HostContentSettingsMapFactory::GetForProfile(GetProfile());
- MediaSettingsInfo::ForOneType& settings = media_settings_->forType(type);
- std::string policy_pref = (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC)
- ? prefs::kAudioCaptureAllowed
- : prefs::kVideoCaptureAllowed;
-
- settings.policy_disable = !prefs->GetBoolean(policy_pref) &&
- prefs->IsManagedPreference(policy_pref);
- settings.default_setting =
- settings_map->GetDefaultContentSetting(type, nullptr);
- settings.default_setting_initialized = true;
-
- UpdateFlashMediaLinksVisibility(type);
- UpdateMediaDeviceDropdownVisibility(type);
-}
-
-void ContentSettingsHandler::UpdateHandlersEnabledRadios() {
- base::Value handlers_enabled(GetProtocolHandlerRegistry()->enabled());
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettings.updateHandlersEnabledRadios", handlers_enabled);
-}
-
-void ContentSettingsHandler::UpdateAllExceptionsViewsFromModel() {
- const ExceptionsInfoMap& exceptions_info_map = GetExceptionsInfoMap();
- for (const auto& exceptions_info_pair : exceptions_info_map)
- UpdateExceptionsViewFromModel(exceptions_info_pair.first);
-
- // Zoom levels are not actually a content type so we need to handle them
- // separately.
- UpdateZoomLevelsExceptionsView();
-}
-
-void ContentSettingsHandler::UpdateAllOTRExceptionsViewsFromModel() {
- const ExceptionsInfoMap& exceptions_info_map = GetExceptionsInfoMap();
- for (const auto& exceptions_info_pair : exceptions_info_map) {
- if (exceptions_info_pair.second.has_otr_exceptions) {
- UpdateExceptionsViewFromOTRHostContentSettingsMap(
- exceptions_info_pair.first);
- }
- }
-}
-
-void ContentSettingsHandler::UpdateExceptionsViewFromModel(
- ContentSettingsType type) {
- if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) {
- UpdateGeolocationExceptionsView();
- } else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
- UpdateNotificationExceptionsView();
- } else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC ||
- type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
- CompareMediaExceptionsWithFlash(type);
- UpdateExceptionsViewFromHostContentSettingsMap(type);
- } else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) {
- UpdateMIDISysExExceptionsView();
- } else {
- UpdateExceptionsViewFromHostContentSettingsMap(type);
- }
-}
-
-// TODO(estade): merge with GetExceptionsFromHostContentSettingsMap.
-void ContentSettingsHandler::UpdateGeolocationExceptionsView() {
- Profile* profile = Profile::FromWebUI(web_ui());
- HostContentSettingsMap* map =
- HostContentSettingsMapFactory::GetForProfile(profile);
-
- ContentSettingsForOneType all_settings;
- map->GetSettingsForOneType(
- CONTENT_SETTINGS_TYPE_GEOLOCATION,
- std::string(),
- &all_settings);
-
- // Group geolocation settings by primary_pattern.
- site_settings::AllPatternsSettings all_patterns_settings;
- for (ContentSettingsForOneType::iterator i = all_settings.begin();
- i != all_settings.end(); ++i) {
- // Don't add default settings.
- if (i->primary_pattern == ContentSettingsPattern::Wildcard() &&
- i->secondary_pattern == ContentSettingsPattern::Wildcard() &&
- i
- ->source != site_settings::kPreferencesSource) {
- continue;
- }
- all_patterns_settings[std::make_pair(i->primary_pattern, i->source)]
- [i->secondary_pattern] = i->GetContentSetting();
- }
-
- base::ListValue exceptions;
- AddExceptionsGrantedByHostedApps(
- profile,
- HostedAppHasPermission<APIPermission::kGeolocation>,
- &exceptions);
-
- for (site_settings::AllPatternsSettings::iterator i =
- all_patterns_settings.begin(); i != all_patterns_settings.end(); ++i) {
- const ContentSettingsPattern& primary_pattern = i->first.first;
- const site_settings::OnePatternSettings& one_settings = i->second;
-
- site_settings::OnePatternSettings::const_iterator parent =
- one_settings.find(primary_pattern);
-
- // Add the "parent" entry for the non-embedded setting.
- ContentSetting parent_setting =
- parent == one_settings.end() ? CONTENT_SETTING_DEFAULT : parent->second;
- exceptions.Append(GetGeolocationExceptionForPage(primary_pattern,
- primary_pattern,
- parent_setting));
-
- // Add the "children" for any embedded settings.
- for (site_settings::OnePatternSettings::const_iterator j =
- one_settings.begin();
- j != one_settings.end();
- ++j) {
- // Skip the non-embedded setting which we already added above.
- if (j == parent)
- continue;
-
- exceptions.Append(GetGeolocationExceptionForPage(
- primary_pattern, j->first, j->second));
- }
- }
-
- base::Value type_string(site_settings::ContentSettingsTypeToGroupName(
- CONTENT_SETTINGS_TYPE_GEOLOCATION));
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setExceptions",
- type_string, exceptions);
-
- // This is mainly here to keep this function ideologically parallel to
- // UpdateExceptionsViewFromHostContentSettingsMap().
- UpdateSettingDefaultFromModel(CONTENT_SETTINGS_TYPE_GEOLOCATION);
-}
-
-void ContentSettingsHandler::UpdateNotificationExceptionsView() {
- Profile* profile = Profile::FromWebUI(web_ui());
- ContentSettingsForOneType settings;
- DesktopNotificationProfileUtil::GetNotificationsSettings(profile, &settings);
-
- base::ListValue exceptions;
- AddExceptionsGrantedByHostedApps(
- profile,
- HostedAppHasPermission<APIPermission::kNotifications>,
- &exceptions);
-
- for (ContentSettingsForOneType::const_iterator i =
- settings.begin();
- i != settings.end();
- ++i) {
- // Don't add default settings.
- if (i->primary_pattern == ContentSettingsPattern::Wildcard() &&
- i->secondary_pattern == ContentSettingsPattern::Wildcard() &&
- i
- ->source != site_settings::kPreferencesSource) {
- continue;
- }
-
- exceptions.Append(GetNotificationExceptionForPage(
- i->primary_pattern, i->secondary_pattern, i->GetContentSetting(),
- i->source));
- }
-
- base::Value type_string(site_settings::ContentSettingsTypeToGroupName(
- CONTENT_SETTINGS_TYPE_NOTIFICATIONS));
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setExceptions",
- type_string, exceptions);
-
- // This is mainly here to keep this function ideologically parallel to
- // UpdateExceptionsViewFromHostContentSettingsMap().
- UpdateSettingDefaultFromModel(CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
-}
-
-void ContentSettingsHandler::CompareMediaExceptionsWithFlash(
- ContentSettingsType type) {
- MediaSettingsInfo::ForOneType& settings = media_settings_->forType(type);
- HostContentSettingsMap* settings_map =
- HostContentSettingsMapFactory::GetForProfile(GetProfile());
- const auto* extension_registry =
- extensions::ExtensionRegistry::Get(GetProfile());
- base::ListValue exceptions;
- site_settings::GetExceptionsFromHostContentSettingsMap(
- settings_map, type, extension_registry, web_ui(), /*incognito=*/false,
- /*filter=*/nullptr, &exceptions);
-
- settings.exceptions.clear();
- for (base::ListValue::const_iterator entry = exceptions.begin();
- entry != exceptions.end(); ++entry) {
- const base::DictionaryValue* dict = nullptr;
- bool valid_dict = entry->GetAsDictionary(&dict);
- DCHECK(valid_dict);
-
- std::string origin;
- std::string setting;
- dict->GetString(site_settings::kOrigin, &origin);
- dict->GetString(site_settings::kSetting, &setting);
-
- ContentSetting setting_type;
- bool result =
- content_settings::ContentSettingFromString(setting, &setting_type);
- DCHECK(result);
-
- settings.exceptions.push_back(MediaException(
- ContentSettingsPattern::FromString(origin),
- setting_type));
- }
-
- PepperFlashContentSettingsUtils::SortMediaExceptions(
- &settings.exceptions);
-
- settings.exceptions_initialized = true;
- UpdateFlashMediaLinksVisibility(type);
-}
-
-void ContentSettingsHandler::UpdateMIDISysExExceptionsView() {
- UpdateSettingDefaultFromModel(CONTENT_SETTINGS_TYPE_MIDI_SYSEX);
- UpdateExceptionsViewFromHostContentSettingsMap(
- CONTENT_SETTINGS_TYPE_MIDI_SYSEX);
-}
-
-void ContentSettingsHandler::UpdateAllChooserExceptionsViewsFromModel() {
- for (const site_settings::ChooserTypeNameEntry& chooser_type :
- site_settings::kChooserTypeGroupNames)
- UpdateChooserExceptionsViewFromModel(chooser_type);
-}
-
-void ContentSettingsHandler::UpdateAllOTRChooserExceptionsViewsFromModel() {
- for (const site_settings::ChooserTypeNameEntry& chooser_type :
- site_settings::kChooserTypeGroupNames)
- UpdateOTRChooserExceptionsViewFromModel(chooser_type);
-}
-
-void ContentSettingsHandler::UpdateChooserExceptionsViewFromModel(
- const site_settings::ChooserTypeNameEntry& chooser_type) {
- base::ListValue exceptions;
- site_settings::GetChooserExceptionsFromProfile(
- Profile::FromWebUI(web_ui()), false, chooser_type, &exceptions);
- base::Value type_string(chooser_type.name);
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setExceptions",
- type_string, exceptions);
-
- UpdateOTRChooserExceptionsViewFromModel(chooser_type);
-}
-
-void ContentSettingsHandler::UpdateOTRChooserExceptionsViewFromModel(
- const site_settings::ChooserTypeNameEntry& chooser_type) {
- if (!Profile::FromWebUI(web_ui())->HasOffTheRecordProfile())
- return;
-
- base::ListValue exceptions;
- site_settings::GetChooserExceptionsFromProfile(
- Profile::FromWebUI(web_ui()), true, chooser_type, &exceptions);
- base::Value type_string(chooser_type.name);
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setOTRExceptions",
- type_string, exceptions);
-}
-
-void ContentSettingsHandler::UpdateZoomLevelsExceptionsView() {
- base::ListValue zoom_levels_exceptions;
-
- content::HostZoomMap* host_zoom_map =
- content::HostZoomMap::GetDefaultForBrowserContext(
- GetBrowserContext(web_ui()));
- content::HostZoomMap::ZoomLevelVector zoom_levels(
- host_zoom_map->GetAllZoomLevels());
-
- // Sort ZoomLevelChanges by host and scheme
- // (a.com < http://a.com < https://a.com < b.com).
- std::sort(zoom_levels.begin(), zoom_levels.end(),
- [](const content::HostZoomMap::ZoomLevelChange& a,
- const content::HostZoomMap::ZoomLevelChange& b) {
- return a.host == b.host ? a.scheme < b.scheme : a.host < b.host;
- });
-
- for (content::HostZoomMap::ZoomLevelVector::const_iterator i =
- zoom_levels.begin();
- i != zoom_levels.end();
- ++i) {
- std::unique_ptr<base::DictionaryValue> exception(new base::DictionaryValue);
- switch (i->mode) {
- case content::HostZoomMap::ZOOM_CHANGED_FOR_HOST: {
- exception->SetString(site_settings::kOrigin, i->host);
- std::string host = i->host;
- if (host == content::kUnreachableWebDataURL) {
- host =
- l10n_util::GetStringUTF8(IDS_ZOOMLEVELS_CHROME_ERROR_PAGES_LABEL);
- }
- exception->SetString(site_settings::kOrigin, host);
- break;
- }
- case content::HostZoomMap::ZOOM_CHANGED_FOR_SCHEME_AND_HOST:
- // These are not stored in preferences and get cleared on next browser
- // start. Therefore, we don't care for them.
- continue;
- case content::HostZoomMap::PAGE_SCALE_IS_ONE_CHANGED:
- continue;
- case content::HostZoomMap::ZOOM_CHANGED_TEMPORARY_ZOOM:
- NOTREACHED();
- }
-
- std::string setting_string =
- content_settings::ContentSettingToString(CONTENT_SETTING_DEFAULT);
- DCHECK(!setting_string.empty());
-
- exception->SetString(site_settings::kSetting, setting_string);
-
- // Calculate the zoom percent from the factor. Round up to the nearest whole
- // number.
- int zoom_percent = static_cast<int>(
- content::ZoomLevelToZoomFactor(i->zoom_level) * 100 + 0.5);
- exception->SetString(kZoom, base::FormatPercent(zoom_percent));
- exception->SetString(
- site_settings::kSource, site_settings::kPreferencesSource);
- // Append the new entry to the list and map.
- zoom_levels_exceptions.Append(std::move(exception));
- }
-
- base::Value type_string(kZoomContentType);
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setExceptions",
- type_string, zoom_levels_exceptions);
-}
-
-void ContentSettingsHandler::UpdateExceptionsViewFromHostContentSettingsMap(
- ContentSettingsType type) {
- base::ListValue exceptions;
- HostContentSettingsMap* settings_map =
- HostContentSettingsMapFactory::GetForProfile(GetProfile());
- const auto* extension_registry =
- extensions::ExtensionRegistry::Get(GetProfile());
- site_settings::GetExceptionsFromHostContentSettingsMap(
- settings_map, type, extension_registry, web_ui(), /*incognito=*/false,
- /*filter=*/nullptr, &exceptions);
- base::Value type_string(site_settings::ContentSettingsTypeToGroupName(type));
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setExceptions",
- type_string, exceptions);
-
- UpdateExceptionsViewFromOTRHostContentSettingsMap(type);
-
-#if defined(OS_CHROMEOS)
- // Also the default for protected contents is managed in another place.
- if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER)
- return;
-#endif
-
- // The default may also have changed (we won't get a separate notification).
- // If it hasn't changed, this call will be harmless.
- UpdateSettingDefaultFromModel(type);
-}
-
-void ContentSettingsHandler::UpdateExceptionsViewFromOTRHostContentSettingsMap(
- ContentSettingsType type) {
- const HostContentSettingsMap* otr_settings_map =
- HostContentSettingsMapFactory::GetForProfile(GetOTRProfile());
- if (!otr_settings_map)
- return;
- const auto* extension_registry =
- extensions::ExtensionRegistry::Get(GetOTRProfile());
- base::ListValue exceptions;
- site_settings::GetExceptionsFromHostContentSettingsMap(
- otr_settings_map, type, extension_registry, web_ui(), /*incognito=*/true,
- /*filter=*/nullptr, &exceptions);
- base::Value type_string(site_settings::ContentSettingsTypeToGroupName(type));
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.setOTRExceptions",
- type_string, exceptions);
-}
-
-void ContentSettingsHandler::RemoveExceptionFromHostContentSettingsMap(
- const base::ListValue* args,
- ContentSettingsType type) {
- std::string mode;
- bool rv = args->GetString(1, &mode);
- DCHECK(rv);
-
- std::string pattern;
- rv = args->GetString(2, &pattern);
- DCHECK(rv);
-
- // The fourth argument to this handler is optional.
- std::string secondary_pattern_string;
- if (args->GetSize() >= 4U) {
- rv = args->GetString(3, &secondary_pattern_string);
- DCHECK(rv);
- }
-
- Profile* profile = mode == "normal" ? GetProfile() : GetOTRProfile();
- if (!profile)
- return;
-
- HostContentSettingsMap* settings_map =
- HostContentSettingsMapFactory::GetForProfile(profile);
- ContentSettingsPattern primary_pattern =
- ContentSettingsPattern::FromString(pattern);
- ContentSettingsPattern secondary_pattern =
- secondary_pattern_string.empty()
- ? ContentSettingsPattern::Wildcard()
- : ContentSettingsPattern::FromString(secondary_pattern_string);
- PermissionUtil::ScopedRevocationReporter scoped_revocation_reporter(
- profile, primary_pattern, secondary_pattern, type,
- PermissionSourceUI::SITE_SETTINGS);
-
- settings_map->SetContentSettingCustomScope(
- primary_pattern, secondary_pattern, type, std::string(),
- CONTENT_SETTING_DEFAULT);
-}
-
-void ContentSettingsHandler::RemoveZoomLevelException(
- const base::ListValue* args) {
- std::string mode;
- bool rv = args->GetString(1, &mode);
- DCHECK(rv);
-
- std::string pattern;
- rv = args->GetString(2, &pattern);
- DCHECK(rv);
-
- if (pattern ==
- l10n_util::GetStringUTF8(IDS_ZOOMLEVELS_CHROME_ERROR_PAGES_LABEL)) {
- pattern = content::kUnreachableWebDataURL;
- }
-
- content::HostZoomMap* host_zoom_map;
- host_zoom_map =
- content::HostZoomMap::GetDefaultForBrowserContext(
- GetBrowserContext(web_ui()));
- double default_level = host_zoom_map->GetDefaultZoomLevel();
- host_zoom_map->SetZoomLevelForHost(pattern, default_level);
-}
-
-void ContentSettingsHandler::RemoveChooserException(
- const site_settings::ChooserTypeNameEntry* chooser_type,
- const base::ListValue* args) {
- std::string mode;
- bool rv = args->GetString(1, &mode);
- DCHECK(rv);
-
- std::string requesting_origin_string;
- rv = args->GetString(2, &requesting_origin_string);
- DCHECK(rv);
- GURL requesting_origin(requesting_origin_string);
- DCHECK(requesting_origin.is_valid());
-
- std::string embedding_origin_string;
- rv = args->GetString(3, &embedding_origin_string);
- DCHECK(rv);
- GURL embedding_origin(embedding_origin_string);
- DCHECK(embedding_origin.is_valid());
-
- const base::DictionaryValue* object = nullptr;
- rv = args->GetDictionary(4, &object);
- DCHECK(rv);
-
- Profile* profile = Profile::FromWebUI(web_ui());
- if (mode != "normal")
- profile = profile->GetOffTheRecordProfile();
-
- ChooserContextBase* chooser_context = chooser_type->get_context(profile);
- chooser_context->RevokeObjectPermission(requesting_origin, embedding_origin,
- *object);
- UpdateChooserExceptionsViewFromModel(*chooser_type);
- // TODO(reillyg): Create metrics for revocations. crbug.com/556845
-}
-
-void ContentSettingsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("setContentFilter",
- base::Bind(&ContentSettingsHandler::SetContentFilter,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("removeException",
- base::Bind(&ContentSettingsHandler::RemoveException,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setException",
- base::Bind(&ContentSettingsHandler::SetException,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("checkExceptionPatternValidity",
- base::Bind(&ContentSettingsHandler::CheckExceptionPatternValidity,
- base::Unretained(this)));
-}
-
-void ContentSettingsHandler::SetContentFilter(const base::ListValue* args) {
- DCHECK_EQ(2U, args->GetSize());
- std::string group, setting;
- if (!(args->GetString(0, &group) &&
- args->GetString(1, &setting))) {
- NOTREACHED();
- return;
- }
-
- ContentSetting default_setting;
- bool result =
- content_settings::ContentSettingFromString(setting, &default_setting);
- DCHECK(result);
-
- ContentSettingsType content_type =
- site_settings::ContentSettingsTypeFromGroupName(group);
- Profile* profile = Profile::FromWebUI(web_ui());
-
-#if defined(OS_CHROMEOS)
- // ChromeOS special case : in Guest mode settings are opened in Incognito
- // mode, so we need original profile to actually modify settings.
- if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
- profile = profile->GetOriginalProfile();
-#endif
-
- HostContentSettingsMap* map =
- HostContentSettingsMapFactory::GetForProfile(profile);
- map->SetDefaultContentSetting(content_type, default_setting);
-
- const ExceptionsInfoMap& exceptions_info_map = GetExceptionsInfoMap();
- const auto& it = exceptions_info_map.find(content_type);
- if (it != exceptions_info_map.end())
- base::RecordAction(it->second.uma);
-}
-
-void ContentSettingsHandler::RemoveException(const base::ListValue* args) {
- std::string type_string;
- CHECK(args->GetString(0, &type_string));
-
- // Zoom levels are no actual content type so we need to handle them
- // separately. They would not be recognized by
- // ContentSettingsTypeFromGroupName.
- if (type_string == kZoomContentType) {
- RemoveZoomLevelException(args);
- return;
- }
-
- const site_settings::ChooserTypeNameEntry* chooser_type =
- site_settings::ChooserTypeFromGroupName(type_string);
- if (chooser_type) {
- RemoveChooserException(chooser_type, args);
- return;
- }
-
- ContentSettingsType type =
- site_settings::ContentSettingsTypeFromGroupName(type_string);
- RemoveExceptionFromHostContentSettingsMap(args, type);
-
- WebSiteSettingsUmaUtil::LogPermissionChange(
- type, ContentSetting::CONTENT_SETTING_DEFAULT);
-}
-
-void ContentSettingsHandler::SetException(const base::ListValue* args) {
- std::string type_string;
- CHECK(args->GetString(0, &type_string));
- std::string mode;
- CHECK(args->GetString(1, &mode));
- std::string pattern;
- CHECK(args->GetString(2, &pattern));
- std::string setting;
- CHECK(args->GetString(3, &setting));
-
- ContentSettingsType type =
- site_settings::ContentSettingsTypeFromGroupName(type_string);
-
- DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION &&
- type != CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC &&
- type != CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
-
- Profile* profile = mode == "normal" ? GetProfile() : GetOTRProfile();
-
- // The profile could be nullptr if the mode was OTR but the OTR profile
- // got destroyed before we received this message.
- if (!profile)
- return;
-
- ContentSetting setting_type;
- bool result =
- content_settings::ContentSettingFromString(setting, &setting_type);
- DCHECK(result);
-
- HostContentSettingsMap* settings_map =
- HostContentSettingsMapFactory::GetForProfile(profile);
-
- PermissionUtil::ScopedRevocationReporter scoped_revocation_reporter(
- profile, ContentSettingsPattern::FromString(pattern),
- ContentSettingsPattern::Wildcard(), type,
- PermissionSourceUI::SITE_SETTINGS);
-
- settings_map->SetContentSettingCustomScope(
- ContentSettingsPattern::FromString(pattern),
- ContentSettingsPattern::Wildcard(), type, std::string(), setting_type);
- WebSiteSettingsUmaUtil::LogPermissionChange(type, setting_type);
-}
-
-void ContentSettingsHandler::CheckExceptionPatternValidity(
- const base::ListValue* args) {
- std::string type_string;
- CHECK(args->GetString(0, &type_string));
- std::string mode_string;
- CHECK(args->GetString(1, &mode_string));
- std::string pattern_string;
- CHECK(args->GetString(2, &pattern_string));
-
- ContentSettingsPattern pattern =
- ContentSettingsPattern::FromString(pattern_string);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettings.patternValidityCheckComplete", base::Value(type_string),
- base::Value(mode_string), base::Value(pattern_string),
- base::Value(pattern.IsValid()));
-}
-
-Profile* ContentSettingsHandler::GetProfile() {
- return Profile::FromWebUI(web_ui());
-}
-
-ProtocolHandlerRegistry* ContentSettingsHandler::GetProtocolHandlerRegistry() {
- return ProtocolHandlerRegistryFactory::GetForBrowserContext(
- GetBrowserContext(web_ui()));
-}
-
-Profile* ContentSettingsHandler::GetOTRProfile() {
- return GetProfile()->HasOffTheRecordProfile()
- ? GetProfile()->GetOffTheRecordProfile()
- : nullptr;
-}
-
-void ContentSettingsHandler::RefreshFlashMediaSettings() {
- MediaSettingsInfo::ForFlash& settings = media_settings_->forFlash();
- settings.initialized = false;
-
- settings.last_refresh_request_id =
- flash_settings_manager_->GetPermissionSettings(
- PP_FLASH_BROWSEROPERATIONS_SETTINGTYPE_CAMERAMIC);
-}
-
-void ContentSettingsHandler::OnPepperFlashPrefChanged() {
- ShowFlashMediaLink(
- DEFAULT_SETTING, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, false);
- ShowFlashMediaLink(
- DEFAULT_SETTING, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, false);
- ShowFlashMediaLink(
- EXCEPTIONS, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, false);
- ShowFlashMediaLink(
- EXCEPTIONS, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, false);
-
- PrefService* prefs = user_prefs::UserPrefs::Get(GetBrowserContext(web_ui()));
- if (prefs->GetBoolean(prefs::kPepperFlashSettingsEnabled))
- RefreshFlashMediaSettings();
- else
- media_settings_->forFlash().initialized = false;
-}
-
-void ContentSettingsHandler::OnZoomLevelChanged(
- const content::HostZoomMap::ZoomLevelChange& change) {
- UpdateZoomLevelsExceptionsView();
-}
-
-void ContentSettingsHandler::ShowFlashMediaLink(
- LinkType link_type, ContentSettingsType content_type, bool show) {
- MediaSettingsInfo::ForOneType& settings =
- media_settings_->forType(content_type);
-
- bool& show_link = link_type == DEFAULT_SETTING ?
- settings.show_flash_default_link :
- settings.show_flash_exceptions_link;
-
- if (show_link != show) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettings.showMediaPepperFlashLink",
- base::Value(link_type == DEFAULT_SETTING ? "default" : "exceptions"),
- base::Value(content_type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC
- ? "mic"
- : "camera"),
- base::Value(show));
- show_link = show;
- }
-}
-
-void ContentSettingsHandler::UpdateFlashMediaLinksVisibility(
- ContentSettingsType type) {
- MediaSettingsInfo::ForOneType& settings = media_settings_->forType(type);
- MediaSettingsInfo::ForFlash& flash_settings = media_settings_->forFlash();
-
- if (!flash_settings.initialized)
- return;
-
- // We handle four cases - default settings and exceptions for microphone
- // and camera. We use the following criteria to determine whether to show
- // the links.
- //
- // 1. Flash won't send us notifications when its settings get changed, which
- // means the Flash settings in |media_settings_| may be out-dated, especially
- // after we show links to change Flash settings.
- // In order to avoid confusion, we won't hide the links once they are showed.
- // One exception is that we will hide them when Pepper Flash is disabled
- // (handled in OnPepperFlashPrefChanged()).
- //
- // 2. If audio or video capture are disabled by policy, the respective link
- // shouldn't be showed. Flash conforms to the policy in this case because
- // it cannot open those devices.
- //
- // 3. Otherwise, we show the link if the corresponding setting is different
- // in HostContentSettingsMap than it is in Flash.
- if (settings.policy_disable)
- return;
-
- if (settings.default_setting_initialized &&
- !settings.show_flash_default_link &&
- (flash_settings.default_setting !=
- settings.default_setting)) {
- ShowFlashMediaLink(DEFAULT_SETTING, type, true);
- }
-
- if (settings.exceptions_initialized &&
- !settings.show_flash_exceptions_link &&
- !PepperFlashContentSettingsUtils::AreMediaExceptionsEqual(
- settings.default_setting,
- settings.exceptions,
- flash_settings.default_setting,
- flash_settings.exceptions)) {
- ShowFlashMediaLink(EXCEPTIONS, type, true);
- }
-}
-
-void ContentSettingsHandler::UpdateMediaDeviceDropdownVisibility(
- ContentSettingsType type) {
- MediaSettingsInfo::ForOneType& settings = media_settings_->forType(type);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettings.setDevicesMenuVisibility",
- base::Value(site_settings::ContentSettingsTypeToGroupName(type)),
- base::Value(!settings.policy_disable));
-}
-
-void ContentSettingsHandler::UpdateProtectedContentExceptionsButton() {
-#if defined(OS_CHROMEOS)
- // Guests cannot modify exceptions. UIAccountTweaks will disabled the button.
- if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
- return;
-#endif
-
- // Exceptions apply only when the feature is enabled.
- PrefService* prefs = user_prefs::UserPrefs::Get(GetBrowserContext(web_ui()));
- bool enable_exceptions = prefs->GetBoolean(prefs::kEnableDRM);
- web_ui()->CallJavascriptFunctionUnsafe(
- "ContentSettings.enableProtectedContentExceptions",
- base::Value(enable_exceptions));
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/content_settings_handler.h b/chromium/chrome/browser/ui/webui/options/content_settings_handler.h
deleted file mode 100644
index 768ff702a69..00000000000
--- a/chromium/chrome/browser/ui/webui/options/content_settings_handler.h
+++ /dev/null
@@ -1,285 +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_OPTIONS_CONTENT_SETTINGS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CONTENT_SETTINGS_HANDLER_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "base/macros.h"
-#include "base/scoped_observer.h"
-#include "base/values.h"
-#include "chrome/browser/pepper_flash_settings_manager.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.h"
-#include "components/content_settings/core/browser/content_settings_observer.h"
-#include "components/content_settings/core/common/content_settings.h"
-#include "components/content_settings/core/common/content_settings_types.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "content/public/browser/host_zoom_map.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-
-class HostContentSettingsMap;
-class Profile;
-class ProtocolHandlerRegistry;
-
-namespace site_settings {
-struct ChooserTypeNameEntry;
-}
-
-namespace options {
-
-class ContentSettingsHandler : public OptionsPageUIHandler,
- public content_settings::Observer,
- public content::NotificationObserver,
- public PepperFlashSettingsManager::Client {
- public:
- ContentSettingsHandler();
- ~ContentSettingsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // content_settings::Observer implementation.
- void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern,
- const ContentSettingsPattern& secondary_pattern,
- ContentSettingsType content_type,
- std::string resource_identifier) override;
-
- // content::NotificationObserver implementation.
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
-
- // PepperFlashSettingsManager::Client implementation.
- void OnGetPermissionSettingsCompleted(
- uint32_t request_id,
- bool success,
- PP_Flash_BrowserOperations_Permission default_permission,
- const ppapi::FlashSiteSettings& sites) override;
-
- private:
- // Used to determine whether we should show links to Flash camera and
- // microphone settings.
- class MediaSettingsInfo {
- public:
- MediaSettingsInfo();
- ~MediaSettingsInfo();
-
- // Cached Pepper Flash settings.
- struct ForFlash {
- ForFlash();
- ~ForFlash();
-
- ContentSetting default_setting;
- MediaExceptions exceptions;
- bool initialized;
- uint32_t last_refresh_request_id;
- };
-
- struct ForOneType {
- ForOneType();
- ~ForOneType();
-
- // Whether the links to Flash settings pages are showed.
- bool show_flash_default_link;
- bool show_flash_exceptions_link;
-
- // Cached Chrome media settings.
- ContentSetting default_setting;
- bool policy_disable;
- bool default_setting_initialized;
- MediaExceptions exceptions;
- bool exceptions_initialized;
- };
-
- ForOneType& forType(ContentSettingsType type);
- ForFlash& forFlash();
-
- private:
- ForOneType mic_settings_;
- ForOneType camera_settings_;
- ForFlash flash_settings_;
-
- DISALLOW_COPY_AND_ASSIGN(MediaSettingsInfo);
- };
-
- // Used by ShowFlashMediaLink() to specify which link to show/hide.
- enum LinkType {
- DEFAULT_SETTING = 0,
- EXCEPTIONS,
- };
-
- // Functions that call into the page -----------------------------------------
-
- // Updates the page with the default settings (allow, ask, block, etc.)
- void UpdateSettingDefaultFromModel(ContentSettingsType type);
-
- // Compares the microphone or camera |type| default settings with Flash
- // and updates the Flash links' visibility accordingly.
- void UpdateMediaSettingsFromPrefs(ContentSettingsType type);
-
- // Clobbers and rebuilds the specific content setting type exceptions table.
- void UpdateExceptionsViewFromModel(ContentSettingsType type);
-
- // Clobbers and rebuilds the specific content setting type exceptions
- // OTR table.
- void UpdateOTRExceptionsViewFromModel(ContentSettingsType type);
-
- // Clobbers and rebuilds all the exceptions tables in the page (both normal
- // and OTR tables).
- void UpdateAllExceptionsViewsFromModel();
-
- // As above, but only OTR tables.
- void UpdateAllOTRExceptionsViewsFromModel();
-
- // Clobbers and rebuilds just the geolocation exception table.
- void UpdateGeolocationExceptionsView();
-
- // Clobbers and rebuilds just the desktop notification exception table.
- void UpdateNotificationExceptionsView();
-
- // Compares the exceptions of the camera or microphone |type| with its Flash
- // counterparts and updates the Flash links' visibility accordingly.
- void CompareMediaExceptionsWithFlash(ContentSettingsType type);
-
- // Clobbers and rebuilds just the MIDI SysEx exception table.
- void UpdateMIDISysExExceptionsView();
-
- // Clobbers and rebuilds all chooser-based exception tables.
- void UpdateAllChooserExceptionsViewsFromModel();
-
- // As above, but only OTR tables.
- void UpdateAllOTRChooserExceptionsViewsFromModel();
-
- // Clobbers and rebuilds the exception table for a particular chooser-based
- // permission.
- void UpdateChooserExceptionsViewFromModel(
- const site_settings::ChooserTypeNameEntry& chooser_type);
-
- // As above, but only OTR tables.
- void UpdateOTRChooserExceptionsViewFromModel(
- const site_settings::ChooserTypeNameEntry& chooser_type);
-
- // Modifies the zoom level exceptions list to display correct chrome
- // signin page entry. When the legacy (non-WebView-based) signin page
- // goes away, this function can be removed.
- void AdjustZoomLevelsListForSigninPageIfNecessary(
- content::HostZoomMap::ZoomLevelVector* zoom_levels);
-
- // Clobbers and rebuilds just the zoom levels exception table.
- void UpdateZoomLevelsExceptionsView();
-
- // Clobbers and rebuilds an exception table that's managed by the host content
- // settings map.
- void UpdateExceptionsViewFromHostContentSettingsMap(ContentSettingsType type);
-
- // As above, but acts on the OTR table for the content setting type.
- void UpdateExceptionsViewFromOTRHostContentSettingsMap(
- ContentSettingsType type);
-
- // Updates the radio buttons for enabling / disabling handlers.
- void UpdateHandlersEnabledRadios();
-
- // Removes one geolocation exception. |args| contains the parameters passed to
- // RemoveException().
- void RemoveGeolocationException(const base::ListValue* args);
-
- // Removes one notification exception. |args| contains the parameters passed
- // to RemoveException().
- void RemoveNotificationException(const base::ListValue* args);
-
- // Removes one exception of |type| from the host content settings map. |args|
- // contains the parameters passed to RemoveException().
- void RemoveExceptionFromHostContentSettingsMap(
- const base::ListValue* args,
- ContentSettingsType type);
-
- // Removes one zoom level exception. |args| contains the parameters passed to
- // RemoveException().
- void RemoveZoomLevelException(const base::ListValue* args);
-
- // Removes one exception for a chooser-based permission. |args| contains the
- // parameters passed to RemoveException().
- void RemoveChooserException(
- const site_settings::ChooserTypeNameEntry* chooser_type,
- const base::ListValue* args);
-
- // Callbacks used by the page ------------------------------------------------
-
- // Sets the default value for a specific content type. |args| includes the
- // content type and a string describing the new default the user has
- // chosen.
- void SetContentFilter(const base::ListValue* args);
-
- // Removes the given row from the table. The first entry in |args| is the
- // content type, and the rest of the arguments depend on the content type
- // to be removed.
- void RemoveException(const base::ListValue* args);
-
- // Changes the value of an exception. Called after the user is done editing an
- // exception.
- void SetException(const base::ListValue* args);
-
- // Called to decide whether a given pattern is valid, or if it should be
- // rejected. Called while the user is editing an exception pattern.
- void CheckExceptionPatternValidity(const base::ListValue* args);
-
- // Utility functions ---------------------------------------------------------
-
- // Applies content settings whitelists to reduce breakage / user confusion.
- void ApplyWhitelist(ContentSettingsType content_type,
- ContentSetting default_setting);
-
- // Gets the normal profile.
- Profile* GetProfile();
-
- // Gets the incognito profile, or nullptr if there is no active incognito
- // session.
- Profile* GetOTRProfile();
-
- // Gets the ProtocolHandlerRegistry for the normal profile.
- ProtocolHandlerRegistry* GetProtocolHandlerRegistry();
-
- void RefreshFlashMediaSettings();
-
- void OnPepperFlashPrefChanged();
-
- // content::HostZoomMap subscription.
- void OnZoomLevelChanged(const content::HostZoomMap::ZoomLevelChange& change);
-
- void ShowFlashMediaLink(
- LinkType link_type, ContentSettingsType content_type, bool show);
-
- void UpdateFlashMediaLinksVisibility(ContentSettingsType type);
-
- void UpdateMediaDeviceDropdownVisibility(ContentSettingsType type);
-
- void UpdateProtectedContentExceptionsButton();
-
- // Member variables ---------------------------------------------------------
-
- content::NotificationRegistrar notification_registrar_;
- PrefChangeRegistrar pref_change_registrar_;
- std::unique_ptr<PepperFlashSettingsManager> flash_settings_manager_;
- std::unique_ptr<MediaSettingsInfo> media_settings_;
- std::unique_ptr<content::HostZoomMap::Subscription>
- host_zoom_map_subscription_;
- std::unique_ptr<content::HostZoomMap::Subscription>
- signin_host_zoom_map_subscription_;
- ScopedObserver<HostContentSettingsMap, content_settings::Observer> observer_;
-
- DISALLOW_COPY_AND_ASSIGN(ContentSettingsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CONTENT_SETTINGS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/cookies_view_handler.cc b/chromium/chrome/browser/ui/webui/options/cookies_view_handler.cc
deleted file mode 100644
index 7b1a4bb686f..00000000000
--- a/chromium/chrome/browser/ui/webui/options/cookies_view_handler.cc
+++ /dev/null
@@ -1,297 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/cookies_view_handler.h"
-
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/browsing_data/browsing_data_appcache_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_cache_storage_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_cookie_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_database_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_file_system_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_flash_lso_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_indexed_db_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_local_storage_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_media_license_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_quota_helper.h"
-#include "chrome/browser/browsing_data/browsing_data_service_worker_helper.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/cookies_tree_model_util.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/render_process_host.h"
-#include "content/public/browser/site_instance.h"
-#include "content/public/browser/storage_partition.h"
-#include "content/public/browser/web_ui.h"
-
-namespace storage {
-class FileSystemContext;
-}
-
-namespace options {
-
-CookiesViewHandler::CookiesViewHandler()
- : batch_update_(false),
- model_util_(new CookiesTreeModelUtil) {
-}
-
-CookiesViewHandler::~CookiesViewHandler() {
-}
-
-void CookiesViewHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- {"label_cookie_name", IDS_COOKIES_COOKIE_NAME_LABEL},
- {"label_cookie_content", IDS_COOKIES_COOKIE_CONTENT_LABEL},
- {"label_cookie_domain", IDS_COOKIES_COOKIE_DOMAIN_LABEL},
- {"label_cookie_path", IDS_COOKIES_COOKIE_PATH_LABEL},
- {"label_cookie_send_for", IDS_COOKIES_COOKIE_SENDFOR_LABEL},
- {"label_cookie_accessible_to_script",
- IDS_COOKIES_COOKIE_ACCESSIBLE_TO_SCRIPT_LABEL},
- {"label_cookie_created", IDS_COOKIES_COOKIE_CREATED_LABEL},
- {"label_cookie_expires", IDS_COOKIES_COOKIE_EXPIRES_LABEL},
- {"label_webdb_desc", IDS_COOKIES_WEB_DATABASE_DESCRIPTION_LABEL},
- {"label_local_storage_size",
- IDS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL},
- {"label_local_storage_last_modified",
- IDS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL},
- {"label_local_storage_origin", IDS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL},
- {"label_indexed_db_size", IDS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL},
- {"label_indexed_db_last_modified",
- IDS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL},
- {"label_indexed_db_origin", IDS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL},
- {"label_service_worker_origin", IDS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL},
- {"label_service_worker_size",
- IDS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL},
- {"label_service_worker_scopes", IDS_COOKIES_SERVICE_WORKER_SCOPES_LABEL},
- {"label_cache_storage_origin", IDS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL},
- {"label_cache_storage_size",
- IDS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL},
- {"label_cache_storage_last_modified",
- IDS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL},
- {"label_app_cache_manifest",
- IDS_COOKIES_APPLICATION_CACHE_MANIFEST_LABEL},
- {"label_cookie_last_accessed", IDS_COOKIES_LAST_ACCESSED_LABEL},
- {"cookie_domain", IDS_COOKIES_DOMAIN_COLUMN_HEADER},
- {"cookie_local_data", IDS_COOKIES_DATA_COLUMN_HEADER},
- {"cookie_singular", IDS_COOKIES_SINGLE_COOKIE},
- {"cookie_plural", IDS_COOKIES_PLURAL_COOKIES},
- {"cookie_database_storage", IDS_COOKIES_DATABASE_STORAGE},
- {"cookie_indexed_db", IDS_COOKIES_INDEXED_DB},
- {"cookie_local_storage", IDS_COOKIES_LOCAL_STORAGE},
- {"cookie_app_cache", IDS_COOKIES_APPLICATION_CACHE},
- {"cookie_service_worker", IDS_COOKIES_SERVICE_WORKER},
- {"cookie_cache_storage", IDS_COOKIES_CACHE_STORAGE},
- {"cookie_flash_lso", IDS_COOKIES_FLASH_LSO},
- {"search_cookies", IDS_COOKIES_SEARCH_COOKIES},
- {"remove_cookie", IDS_COOKIES_REMOVE_LABEL},
- {"remove_all_cookie", IDS_COOKIES_REMOVE_ALL_LABEL},
- {"remove_all_shown_cookie", IDS_COOKIES_REMOVE_ALL_SHOWN_LABEL},
- {"cookie_file_system", IDS_COOKIES_FILE_SYSTEM},
- {"label_file_system_origin", IDS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL},
- {"label_file_system_temporary_usage",
- IDS_COOKIES_FILE_SYSTEM_TEMPORARY_USAGE_LABEL},
- {"label_file_system_persistent_usage",
- IDS_COOKIES_FILE_SYSTEM_PERSISTENT_USAGE_LABEL},
- {"cookie_channel_id", IDS_COOKIES_CHANNEL_ID},
- {"label_channel_id_server_id", IDS_COOKIES_CHANNEL_ID_ORIGIN_LABEL},
- {"label_channel_id_type", IDS_COOKIES_CHANNEL_ID_TYPE_LABEL},
- {"label_channel_id_created", IDS_COOKIES_CHANNEL_ID_CREATED_LABEL},
- {"label_channel_id_expires", IDS_COOKIES_CHANNEL_ID_EXPIRES_LABEL},
- {"label_protected_by_apps",
- IDS_GEOLOCATION_SET_BY_HOVER}, // TODO(bauerb): Use a better string
- {"cookie_media_license", IDS_COOKIES_MEDIA_LICENSE},
- {"label_media_license_origin", IDS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL},
- {"label_media_license_size",
- IDS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL},
- {"label_media_license_last_modified",
- IDS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL},
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "cookiesViewPage",
- IDS_COOKIES_WEBSITE_PERMISSIONS_WINDOW_TITLE);
-}
-
-void CookiesViewHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("updateCookieSearchResults",
- base::Bind(&CookiesViewHandler::UpdateSearchResults,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("removeAllCookies",
- base::Bind(&CookiesViewHandler::RemoveAll,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("removeCookie",
- base::Bind(&CookiesViewHandler::Remove,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("loadCookie",
- base::Bind(&CookiesViewHandler::LoadChildren,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("reloadCookies",
- base::Bind(&CookiesViewHandler::ReloadCookies,
- base::Unretained(this)));
-}
-
-void CookiesViewHandler::TreeNodesAdded(ui::TreeModel* model,
- ui::TreeModelNode* parent,
- int start,
- int count) {
- // Skip if there is a batch update in progress.
- if (batch_update_)
- return;
-
- CookiesTreeModel* tree_model = static_cast<CookiesTreeModel*>(model);
- CookieTreeNode* parent_node = tree_model->AsNode(parent);
-
- std::unique_ptr<base::ListValue> children(new base::ListValue);
- model_util_->GetChildNodeList(
- parent_node, start, count, /*include_quota_nodes=*/true, children.get());
-
- base::ListValue args;
- if (parent == tree_model->GetRoot())
- args.Append(base::MakeUnique<base::Value>());
- else
- args.AppendString(model_util_->GetTreeNodeId(parent_node));
- args.AppendInteger(start);
- args.Append(std::move(children));
- web_ui()->CallJavascriptFunctionUnsafe("CookiesView.onTreeItemAdded", args);
-}
-
-void CookiesViewHandler::TreeNodesRemoved(ui::TreeModel* model,
- ui::TreeModelNode* parent,
- int start,
- int count) {
- // Skip if there is a batch update in progress.
- if (batch_update_)
- return;
-
- CookiesTreeModel* tree_model = static_cast<CookiesTreeModel*>(model);
-
- base::ListValue args;
- if (parent == tree_model->GetRoot())
- args.Append(base::MakeUnique<base::Value>());
- else
- args.AppendString(model_util_->GetTreeNodeId(tree_model->AsNode(parent)));
- args.AppendInteger(start);
- args.AppendInteger(count);
- web_ui()->CallJavascriptFunctionUnsafe("CookiesView.onTreeItemRemoved", args);
-}
-
-void CookiesViewHandler::TreeModelBeginBatch(CookiesTreeModel* model) {
- DCHECK(!batch_update_); // There should be no nested batch begin.
- batch_update_ = true;
-}
-
-void CookiesViewHandler::TreeModelEndBatch(CookiesTreeModel* model) {
- DCHECK(batch_update_);
- batch_update_ = false;
-
- SendChildren(model->GetRoot());
-}
-
-void CookiesViewHandler::EnsureCookiesTreeModelCreated() {
- if (!cookies_tree_model_.get()) {
- Profile* profile = Profile::FromWebUI(web_ui());
- content::StoragePartition* storage_partition =
- content::BrowserContext::GetDefaultStoragePartition(profile);
- content::IndexedDBContext* indexed_db_context =
- storage_partition->GetIndexedDBContext();
- content::ServiceWorkerContext* service_worker_context =
- storage_partition->GetServiceWorkerContext();
- content::CacheStorageContext* cache_storage_context =
- storage_partition->GetCacheStorageContext();
- storage::FileSystemContext* file_system_context =
- storage_partition->GetFileSystemContext();
- LocalDataContainer* container = new LocalDataContainer(
- new BrowsingDataCookieHelper(profile->GetRequestContext()),
- new BrowsingDataDatabaseHelper(profile),
- new BrowsingDataLocalStorageHelper(profile), NULL,
- new BrowsingDataAppCacheHelper(profile),
- new BrowsingDataIndexedDBHelper(indexed_db_context),
- BrowsingDataFileSystemHelper::Create(file_system_context),
- BrowsingDataQuotaHelper::Create(profile),
- BrowsingDataChannelIDHelper::Create(profile->GetRequestContext()),
- new BrowsingDataServiceWorkerHelper(service_worker_context),
- new BrowsingDataCacheStorageHelper(cache_storage_context),
- BrowsingDataFlashLSOHelper::Create(profile),
- BrowsingDataMediaLicenseHelper::Create(file_system_context));
- cookies_tree_model_.reset(new CookiesTreeModel(
- container, profile->GetExtensionSpecialStoragePolicy()));
- cookies_tree_model_->AddCookiesTreeObserver(this);
- }
-}
-
-void CookiesViewHandler::UpdateSearchResults(const base::ListValue* args) {
- base::string16 query;
- if (!args->GetString(0, &query))
- return;
-
- EnsureCookiesTreeModelCreated();
-
- cookies_tree_model_->UpdateSearchResults(query);
-}
-
-void CookiesViewHandler::RemoveAll(const base::ListValue* args) {
- EnsureCookiesTreeModelCreated();
- cookies_tree_model_->DeleteAllStoredObjects();
-}
-
-void CookiesViewHandler::Remove(const base::ListValue* args) {
- std::string node_path;
- if (!args->GetString(0, &node_path))
- return;
-
- EnsureCookiesTreeModelCreated();
-
- const CookieTreeNode* node = model_util_->GetTreeNodeFromPath(
- cookies_tree_model_->GetRoot(), node_path);
- if (node)
- cookies_tree_model_->DeleteCookieNode(const_cast<CookieTreeNode*>(node));
-}
-
-void CookiesViewHandler::LoadChildren(const base::ListValue* args) {
- std::string node_path;
- if (!args->GetString(0, &node_path))
- return;
-
- EnsureCookiesTreeModelCreated();
-
- const CookieTreeNode* node = model_util_->GetTreeNodeFromPath(
- cookies_tree_model_->GetRoot(), node_path);
- if (node)
- SendChildren(node);
-}
-
-void CookiesViewHandler::SendChildren(const CookieTreeNode* parent) {
- std::unique_ptr<base::ListValue> children(new base::ListValue);
- model_util_->GetChildNodeList(parent, /*start=*/0, parent->child_count(),
- /*include_quota_nodes=*/true, children.get());
-
- base::ListValue args;
- if (parent == cookies_tree_model_->GetRoot())
- args.Append(base::MakeUnique<base::Value>());
- else
- args.AppendString(model_util_->GetTreeNodeId(parent));
- args.Append(std::move(children));
-
- web_ui()->CallJavascriptFunctionUnsafe("CookiesView.loadChildren", args);
-}
-
-void CookiesViewHandler::ReloadCookies(const base::ListValue* args) {
- cookies_tree_model_.reset();
-
- EnsureCookiesTreeModelCreated();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/cookies_view_handler.h b/chromium/chrome/browser/ui/webui/options/cookies_view_handler.h
deleted file mode 100644
index 4e440ae49c1..00000000000
--- a/chromium/chrome/browser/ui/webui/options/cookies_view_handler.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_COOKIES_VIEW_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_COOKIES_VIEW_HANDLER_H_
-
-#include <memory>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/browsing_data/cookies_tree_model.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-class CookiesTreeModelUtil;
-
-namespace options {
-
-class CookiesViewHandler : public OptionsPageUIHandler,
- public CookiesTreeModel::Observer {
- public:
- CookiesViewHandler();
- ~CookiesViewHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void RegisterMessages() override;
-
- // CookiesTreeModel::Observer implementation.
- void TreeNodesAdded(ui::TreeModel* model,
- ui::TreeModelNode* parent,
- int start,
- int count) override;
- void TreeNodesRemoved(ui::TreeModel* model,
- ui::TreeModelNode* parent,
- int start,
- int count) override;
- void TreeNodeChanged(ui::TreeModel* model, ui::TreeModelNode* node) override {
- }
- void TreeModelBeginBatch(CookiesTreeModel* model) override;
- void TreeModelEndBatch(CookiesTreeModel* model) override;
-
- private:
- // Creates the CookiesTreeModel if neccessary.
- void EnsureCookiesTreeModelCreated();
-
- // Updates search filter for cookies tree model.
- void UpdateSearchResults(const base::ListValue* args);
-
- // Remove all sites data.
- void RemoveAll(const base::ListValue* args);
-
- // Remove selected sites data.
- void Remove(const base::ListValue* args);
-
- // Get the tree node using the tree path info in |args| and call
- // SendChildren to pass back children nodes data to WebUI.
- void LoadChildren(const base::ListValue* args);
-
- // Get children nodes data and pass it to 'CookiesView.loadChildren' to
- // update the WebUI.
- void SendChildren(const CookieTreeNode* parent);
-
- // Reloads the CookiesTreeModel and passes the nodes to
- // 'CookiesView.loadChildren' to update the WebUI.
- void ReloadCookies(const base::ListValue* args);
-
- // The Cookies Tree model
- std::unique_ptr<CookiesTreeModel> cookies_tree_model_;
-
- // Flag to indicate whether there is a batch update in progress.
- bool batch_update_;
-
- std::unique_ptr<CookiesTreeModelUtil> model_util_;
-
- DISALLOW_COPY_AND_ASSIGN(CookiesViewHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_COOKIES_VIEW_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/core_options_handler.cc b/chromium/chrome/browser/ui/webui/options/core_options_handler.cc
deleted file mode 100644
index 45ca990799b..00000000000
--- a/chromium/chrome/browser/ui/webui/options/core_options_handler.cc
+++ /dev/null
@@ -1,664 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/core_options_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/extensions/extension_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/chrome_switches.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 "components/proxy_config/proxy_config_pref_names.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/url_formatter/url_fixer.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/notification_types.h"
-#include "content/public/browser/web_ui.h"
-#include "extensions/browser/extension_pref_value_map.h"
-#include "extensions/browser/extension_pref_value_map_factory.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/browser/extension_system.h"
-#include "extensions/common/extension.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "url/gurl.h"
-
-using base::UserMetricsAction;
-
-namespace options {
-
-namespace {
-
-// Whether "controlledBy" property of pref value sent to options web UI needs to
-// be set to "extension" when the preference is controlled by an extension.
-bool CanSetExtensionControlledPrefValue(
- const PrefService::Preference* preference) {
-#if defined(OS_WIN)
- // These have more obvious UI than the standard one for extension controlled
- // values (an extension puzzle piece) on the settings page. To avoiding
- // showing the extension puzzle piece for these settings, their "controlledBy"
- // value should never be set to "extension".
- return preference->name() != prefs::kURLsToRestoreOnStartup &&
- preference->name() != prefs::kRestoreOnStartup &&
- preference->name() != prefs::kHomePage &&
- preference->name() != prefs::kHomePageIsNewTabPage;
-#else
- return true;
-#endif
-}
-
-} // namespace
-
-CoreOptionsHandler::CoreOptionsHandler()
- : handlers_host_(NULL) {
-}
-
-CoreOptionsHandler::~CoreOptionsHandler() {}
-
-void CoreOptionsHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
-
- plugin_status_pref_setter_.Init(
- profile,
- base::Bind(&CoreOptionsHandler::OnPreferenceChanged,
- base::Unretained(this),
- profile->GetPrefs()));
-
- pref_change_filters_[prefs::kBrowserGuestModeEnabled] =
- base::Bind(&CoreOptionsHandler::IsUserUnsupervised,
- base::Unretained(this));
- pref_change_filters_[prefs::kBrowserAddPersonEnabled] =
- base::Bind(&CoreOptionsHandler::IsUserUnsupervised,
- base::Unretained(this));
-}
-
-void CoreOptionsHandler::InitializePage() {
- UpdateClearPluginLSOData();
- UpdatePepperFlashSettingsEnabled();
-}
-
-void CoreOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- GetStaticLocalizedValues(localized_strings);
-}
-
-void CoreOptionsHandler::GetStaticLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- // Main
- localized_strings->SetString("optionsPageTitle",
- l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE));
-
- // Controlled settings bubble.
- localized_strings->SetString("controlledSettingPolicy",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CONTROLLED_SETTING_POLICY));
- localized_strings->SetString("controlledSettingExtension",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CONTROLLED_SETTING_EXTENSION));
- localized_strings->SetString("controlledSettingExtensionWithName",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_EXTENSION_WITH_NAME));
- localized_strings->SetString("controlledSettingManageExtension",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_MANAGE_EXTENSION));
- localized_strings->SetString("controlledSettingDisableExtension",
- l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE));
- localized_strings->SetString("controlledSettingRecommended",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CONTROLLED_SETTING_RECOMMENDED));
- localized_strings->SetString("controlledSettingHasRecommendation",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_HAS_RECOMMENDATION));
- localized_strings->SetString("controlledSettingFollowRecommendation",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CONTROLLED_SETTING_FOLLOW_RECOMMENDATION));
- localized_strings->SetString("controlledSettingsPolicy",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CONTROLLED_SETTINGS_POLICY));
- localized_strings->SetString("controlledSettingsExtension",
- l10n_util::GetStringUTF16(IDS_OPTIONS_CONTROLLED_SETTINGS_EXTENSION));
- localized_strings->SetString("controlledSettingsExtensionWithName",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_CONTROLLED_SETTINGS_EXTENSION_WITH_NAME));
-
- // Search
- RegisterTitle(localized_strings, "searchPage", IDS_OPTIONS_SEARCH_PAGE_TITLE);
- localized_strings->SetString("searchPlaceholder",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SEARCH_PLACEHOLDER));
- localized_strings->SetString("searchPageNoMatches",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SEARCH_PAGE_NO_MATCHES));
- localized_strings->SetString("searchPageHelpLabel",
- l10n_util::GetStringUTF16(IDS_OPTIONS_SEARCH_PAGE_HELP_LABEL));
- localized_strings->SetString("searchPageHelpTitle",
- l10n_util::GetStringFUTF16(IDS_OPTIONS_SEARCH_PAGE_HELP_TITLE,
- l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
- localized_strings->SetString("searchPageHelpURL",
- chrome::kSettingsSearchHelpURL);
-
- // About
- localized_strings->SetString("aboutButton",
- l10n_util::GetStringUTF16(IDS_ABOUT_BUTTON));
-
- // Common
- localized_strings->SetString("ok",
- l10n_util::GetStringUTF16(IDS_OK));
- localized_strings->SetString("cancel",
- l10n_util::GetStringUTF16(IDS_CANCEL));
- localized_strings->SetString("learnMore",
- l10n_util::GetStringUTF16(IDS_LEARN_MORE));
- localized_strings->SetString("close",
- l10n_util::GetStringUTF16(IDS_CLOSE));
- localized_strings->SetString("done",
- l10n_util::GetStringUTF16(IDS_DONE));
- localized_strings->SetString("deletableItemDeleteButtonTitle",
- l10n_util::GetStringUTF16(IDS_OPTIONS_DELETABLE_ITEM_DELETE_BUTTON));
-}
-
-void CoreOptionsHandler::Uninitialize() {
- std::string last_pref;
- for (PreferenceCallbackMap::const_iterator iter = pref_callback_map_.begin();
- iter != pref_callback_map_.end();
- ++iter) {
- if (last_pref != iter->first) {
- StopObservingPref(iter->first);
- last_pref = iter->first;
- }
- }
-}
-
-void CoreOptionsHandler::OnPreferenceChanged(PrefService* service,
- const std::string& pref_name) {
- if (pref_name == prefs::kClearPluginLSODataEnabled) {
- // This preference is stored in Local State, not in the user preferences.
- UpdateClearPluginLSOData();
- return;
- }
- if (pref_name == prefs::kPepperFlashSettingsEnabled) {
- UpdatePepperFlashSettingsEnabled();
- return;
- }
- NotifyPrefChanged(pref_name, std::string());
-}
-
-void CoreOptionsHandler::RegisterMessages() {
- registrar_.Init(Profile::FromWebUI(web_ui())->GetPrefs());
- local_state_registrar_.Init(g_browser_process->local_state());
-
- web_ui()->RegisterMessageCallback("coreOptionsInitialize",
- base::Bind(&CoreOptionsHandler::HandleInitialize,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("onFinishedLoadingOptions",
- base::Bind(&CoreOptionsHandler::OnFinishedLoading,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("fetchPrefs",
- base::Bind(&CoreOptionsHandler::HandleFetchPrefs,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("observePrefs",
- base::Bind(&CoreOptionsHandler::HandleObservePrefs,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setBooleanPref",
- base::Bind(&CoreOptionsHandler::HandleSetBooleanPref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setIntegerPref",
- base::Bind(&CoreOptionsHandler::HandleSetIntegerPref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setDoublePref",
- base::Bind(&CoreOptionsHandler::HandleSetDoublePref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setStringPref",
- base::Bind(&CoreOptionsHandler::HandleSetStringPref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setURLPref",
- base::Bind(&CoreOptionsHandler::HandleSetURLPref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setListPref",
- base::Bind(&CoreOptionsHandler::HandleSetListPref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("clearPref",
- base::Bind(&CoreOptionsHandler::HandleClearPref,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("coreOptionsUserMetricsAction",
- base::Bind(&CoreOptionsHandler::HandleUserMetricsAction,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("disableExtension",
- base::Bind(&CoreOptionsHandler::HandleDisableExtension,
- base::Unretained(this)));
-}
-
-void CoreOptionsHandler::HandleInitialize(const base::ListValue* args) {
- DCHECK(handlers_host_);
- handlers_host_->InitializeHandlers();
-}
-
-void CoreOptionsHandler::OnFinishedLoading(const base::ListValue* args) {
- DCHECK(handlers_host_);
- handlers_host_->OnFinishedLoading();
-}
-
-std::unique_ptr<base::Value> CoreOptionsHandler::FetchPref(
- const std::string& pref_name) {
- return CreateValueForPref(pref_name, std::string());
-}
-
-void CoreOptionsHandler::ObservePref(const std::string& pref_name) {
- if (g_browser_process->local_state()->FindPreference(pref_name)) {
- local_state_registrar_.Add(
- pref_name,
- base::Bind(&CoreOptionsHandler::OnPreferenceChanged,
- base::Unretained(this),
- local_state_registrar_.prefs()));
- }
- // TODO(pneubeck): change this to if/else once kProxy is only used as a user
- // pref. Currently, it is both a user and a local state pref.
- if (Profile::FromWebUI(web_ui())->GetPrefs()->FindPreference(pref_name)) {
- registrar_.Add(
- pref_name,
- base::Bind(&CoreOptionsHandler::OnPreferenceChanged,
- base::Unretained(this),
- registrar_.prefs()));
- }
-}
-
-void CoreOptionsHandler::StopObservingPref(const std::string& pref_name) {
- if (g_browser_process->local_state()->FindPreference(pref_name))
- local_state_registrar_.Remove(pref_name);
- else
- registrar_.Remove(pref_name);
-}
-
-void CoreOptionsHandler::SetPref(const std::string& pref_name,
- const base::Value* value,
- const std::string& metric) {
- PrefService* pref_service = FindServiceForPref(pref_name);
- PrefChangeFilterMap::iterator iter = pref_change_filters_.find(pref_name);
- if (iter != pref_change_filters_.end()) {
- // Also check if the pref is user modifiable (don't even try to run the
- // filter function if the user is not allowed to change the pref).
- const PrefService::Preference* pref =
- pref_service->FindPreference(pref_name);
- if ((pref && !pref->IsUserModifiable()) || !iter->second.Run(value)) {
- // Reject the change; remind the page of the true value.
- NotifyPrefChanged(pref_name, std::string());
- return;
- }
- }
-
- switch (value->GetType()) {
- case base::Value::Type::BOOLEAN:
- case base::Value::Type::INTEGER:
- case base::Value::Type::DOUBLE:
- case base::Value::Type::STRING:
- case base::Value::Type::LIST:
- pref_service->Set(pref_name, *value);
- break;
-
- default:
- NOTREACHED();
- return;
- }
-
- ProcessUserMetric(value, metric);
-}
-
-void CoreOptionsHandler::ClearPref(const std::string& pref_name,
- const std::string& metric) {
- PrefService* pref_service = FindServiceForPref(pref_name);
- pref_service->ClearPref(pref_name);
-
- if (!metric.empty())
- base::RecordComputedAction(metric);
-}
-
-void CoreOptionsHandler::ProcessUserMetric(const base::Value* value,
- const std::string& metric) {
- if (metric.empty())
- return;
-
- std::string metric_string = metric;
- if (value->IsType(base::Value::Type::BOOLEAN)) {
- bool bool_value;
- CHECK(value->GetAsBoolean(&bool_value));
- metric_string += bool_value ? "_Enable" : "_Disable";
- }
-
- base::RecordComputedAction(metric_string);
-}
-
-void CoreOptionsHandler::NotifyPrefChanged(
- const std::string& pref_name,
- const std::string& controlling_pref_name) {
- std::unique_ptr<base::Value> value(
- CreateValueForPref(pref_name, controlling_pref_name));
- DispatchPrefChangeNotification(pref_name, std::move(value));
-}
-
-void CoreOptionsHandler::DispatchPrefChangeNotification(
- const std::string& name,
- std::unique_ptr<base::Value> value) {
- std::pair<PreferenceCallbackMap::const_iterator,
- PreferenceCallbackMap::const_iterator> range =
- pref_callback_map_.equal_range(name);
- base::ListValue result_value;
- result_value.AppendString(name);
- result_value.Append(std::move(value));
- for (PreferenceCallbackMap::const_iterator iter = range.first;
- iter != range.second; ++iter) {
- const std::string& callback_function = iter->second;
- web_ui()->CallJavascriptFunctionUnsafe(callback_function, result_value);
- }
-}
-
-std::unique_ptr<base::Value> CoreOptionsHandler::CreateValueForPref(
- const std::string& pref_name,
- const std::string& controlling_pref_name) {
- const PrefService* pref_service = FindServiceForPref(pref_name);
- const PrefService::Preference* pref =
- pref_service->FindPreference(pref_name);
- if (!pref) {
- NOTREACHED();
- return base::MakeUnique<base::Value>();
- }
- const PrefService::Preference* controlling_pref =
- pref_service->FindPreference(controlling_pref_name);
- if (!controlling_pref)
- controlling_pref = pref;
-
- auto dict = base::MakeUnique<base::DictionaryValue>();
- dict->Set("value", base::MakeUnique<base::Value>(*pref->GetValue()));
- if (controlling_pref->IsManaged()) {
- dict->SetString("controlledBy", "policy");
- } else if (controlling_pref->IsExtensionControlled() &&
- CanSetExtensionControlledPrefValue(controlling_pref)) {
- Profile* profile = Profile::FromWebUI(web_ui());
- ExtensionPrefValueMap* extension_pref_value_map =
- ExtensionPrefValueMapFactory::GetForBrowserContext(profile);
- std::string extension_id =
- extension_pref_value_map->GetExtensionControllingPref(
- controlling_pref->name());
-
- const extensions::Extension* extension =
- extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
- extension_id, extensions::ExtensionRegistry::EVERYTHING);
- if (extension) {
- dict->SetString("controlledBy", "extension");
- dict->Set("extension", extensions::util::GetExtensionInfo(extension));
- }
- } else if (controlling_pref->IsRecommended()) {
- dict->SetString("controlledBy", "recommended");
- }
-
- const base::Value* recommended_value =
- controlling_pref->GetRecommendedValue();
- if (recommended_value)
- dict->Set("recommendedValue",
- base::MakeUnique<base::Value>(*recommended_value));
- dict->SetBoolean("disabled", !controlling_pref->IsUserModifiable());
- return std::move(dict);
-}
-
-PrefService* CoreOptionsHandler::FindServiceForPref(
- const std::string& pref_name) {
- // Proxy is a peculiar case: on ChromeOS, settings exist in both user
- // prefs and local state, but chrome://settings should affect only user prefs.
- // Elsewhere the proxy settings are stored in local state.
- // See http://crbug.com/157147
- PrefService* user_prefs = Profile::FromWebUI(web_ui())->GetPrefs();
- if (pref_name == proxy_config::prefs::kProxy)
-#if defined(OS_CHROMEOS)
- return user_prefs;
-#else
- return g_browser_process->local_state();
-#endif
-
- // Find which PrefService contains the given pref. Pref names should not
- // be duplicated across services, however if they are, prefer the user's
- // prefs.
- if (user_prefs->FindPreference(pref_name))
- return user_prefs;
-
- if (g_browser_process->local_state()->FindPreference(pref_name))
- return g_browser_process->local_state();
-
- return user_prefs;
-}
-
-void CoreOptionsHandler::HandleFetchPrefs(const base::ListValue* args) {
- // First param is name of callback function, so, there needs to be at least
- // one more element for the actual preference identifier.
- DCHECK_GE(static_cast<int>(args->GetSize()), 2);
-
- // Get callback JS function name.
- const base::Value* callback;
- if (!args->Get(0, &callback) || !callback->IsType(base::Value::Type::STRING))
- return;
-
- base::string16 callback_function;
- if (!callback->GetAsString(&callback_function))
- return;
-
- // Get the list of name for prefs to build the response dictionary.
- base::DictionaryValue result_value;
- const base::Value* list_member;
-
- for (size_t i = 1; i < args->GetSize(); i++) {
- if (!args->Get(i, &list_member))
- break;
-
- if (!list_member->IsType(base::Value::Type::STRING))
- continue;
-
- std::string pref_name;
- if (!list_member->GetAsString(&pref_name))
- continue;
-
- result_value.Set(pref_name, FetchPref(pref_name));
- }
- web_ui()->CallJavascriptFunctionUnsafe(base::UTF16ToASCII(callback_function),
- result_value);
-}
-
-void CoreOptionsHandler::HandleObservePrefs(const base::ListValue* args) {
- // First param is name is JS callback function name, the rest are pref
- // identifiers that we are observing.
- DCHECK_GE(static_cast<int>(args->GetSize()), 2);
-
- // Get preference change callback function name.
- std::string callback_func_name;
- if (!args->GetString(0, &callback_func_name))
- return;
-
- // Get all other parameters - pref identifiers.
- for (size_t i = 1; i < args->GetSize(); i++) {
- const base::Value* list_member;
- if (!args->Get(i, &list_member))
- break;
-
- // Just ignore bad pref identifiers for now.
- std::string pref_name;
- if (!list_member->IsType(base::Value::Type::STRING) ||
- !list_member->GetAsString(&pref_name))
- continue;
-
- if (pref_callback_map_.find(pref_name) == pref_callback_map_.end())
- ObservePref(pref_name);
-
- pref_callback_map_.insert(
- PreferenceCallbackMap::value_type(pref_name, callback_func_name));
- }
-}
-
-void CoreOptionsHandler::HandleSetBooleanPref(const base::ListValue* args) {
- HandleSetPref(args, TYPE_BOOLEAN);
-}
-
-void CoreOptionsHandler::HandleSetIntegerPref(const base::ListValue* args) {
- HandleSetPref(args, TYPE_INTEGER);
-}
-
-void CoreOptionsHandler::HandleSetDoublePref(const base::ListValue* args) {
- HandleSetPref(args, TYPE_DOUBLE);
-}
-
-void CoreOptionsHandler::HandleSetStringPref(const base::ListValue* args) {
- HandleSetPref(args, TYPE_STRING);
-}
-
-void CoreOptionsHandler::HandleSetURLPref(const base::ListValue* args) {
- HandleSetPref(args, TYPE_URL);
-}
-
-void CoreOptionsHandler::HandleSetListPref(const base::ListValue* args) {
- HandleSetPref(args, TYPE_LIST);
-}
-
-void CoreOptionsHandler::HandleSetPref(const base::ListValue* args,
- PrefType type) {
- DCHECK_GT(static_cast<int>(args->GetSize()), 1);
-
- std::string pref_name;
- if (!args->GetString(0, &pref_name))
- return;
-
- const base::Value* value;
- if (!args->Get(1, &value))
- return;
-
- std::unique_ptr<base::Value> temp_value;
-
- switch (type) {
- case TYPE_BOOLEAN:
- if (!value->IsType(base::Value::Type::BOOLEAN)) {
- NOTREACHED();
- return;
- }
- break;
- case TYPE_INTEGER: {
- // In JS all numbers are doubles.
- double double_value;
- if (!value->GetAsDouble(&double_value)) {
- NOTREACHED();
- return;
- }
- int int_value = static_cast<int>(double_value);
- temp_value.reset(new base::Value(int_value));
- value = temp_value.get();
- break;
- }
- case TYPE_DOUBLE:
- if (!value->IsType(base::Value::Type::DOUBLE)) {
- NOTREACHED();
- return;
- }
- break;
- case TYPE_STRING:
- if (!value->IsType(base::Value::Type::STRING)) {
- NOTREACHED();
- return;
- }
- break;
- case TYPE_URL: {
- std::string original;
- if (!value->GetAsString(&original)) {
- NOTREACHED();
- return;
- }
- GURL fixed = url_formatter::FixupURL(original, std::string());
- temp_value.reset(new base::Value(fixed.spec()));
- value = temp_value.get();
- break;
- }
- case TYPE_LIST: {
- // In case we have a List pref we got a JSON string.
- std::string json_string;
- if (!value->GetAsString(&json_string)) {
- NOTREACHED();
- return;
- }
- temp_value = base::JSONReader::Read(json_string);
- value = temp_value.get();
- if (!value || !value->IsType(base::Value::Type::LIST)) {
- NOTREACHED();
- return;
- }
- break;
- }
- default:
- NOTREACHED();
- }
-
- std::string metric;
- if (args->GetSize() > 2 && !args->GetString(2, &metric))
- LOG(WARNING) << "Invalid metric parameter: " << pref_name;
- SetPref(pref_name, value, metric);
-}
-
-void CoreOptionsHandler::HandleClearPref(const base::ListValue* args) {
- DCHECK_GT(static_cast<int>(args->GetSize()), 0);
-
- std::string pref_name;
- if (!args->GetString(0, &pref_name))
- return;
-
- std::string metric;
- if (args->GetSize() > 1) {
- if (!args->GetString(1, &metric))
- NOTREACHED();
- }
-
- ClearPref(pref_name, metric);
-}
-
-void CoreOptionsHandler::HandleUserMetricsAction(const base::ListValue* args) {
- std::string metric = base::UTF16ToUTF8(ExtractStringValue(args));
- if (!metric.empty())
- base::RecordComputedAction(metric);
-}
-
-void CoreOptionsHandler::HandleDisableExtension(const base::ListValue* args) {
- std::string extension_id;
- if (args->GetString(0, &extension_id)) {
- ExtensionService* extension_service = extensions::ExtensionSystem::Get(
- Profile::FromWebUI(web_ui()))->extension_service();
- DCHECK(extension_service);
- extension_service->DisableExtension(
- extension_id, extensions::Extension::DISABLE_USER_ACTION);
- } else {
- NOTREACHED();
- }
-}
-
-void CoreOptionsHandler::UpdateClearPluginLSOData() {
- base::Value enabled(plugin_status_pref_setter_.IsClearPluginLSODataEnabled());
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.OptionsPage.setClearPluginLSODataEnabled", enabled);
-}
-
-void CoreOptionsHandler::UpdatePepperFlashSettingsEnabled() {
- base::Value enabled(
- plugin_status_pref_setter_.IsPepperFlashSettingsEnabled());
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.OptionsPage.setPepperFlashSettingsEnabled", enabled);
-}
-
-bool CoreOptionsHandler::IsUserUnsupervised(const base::Value* to_value) {
- return !Profile::FromWebUI(web_ui())->IsSupervised();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/core_options_handler.h b/chromium/chrome/browser/ui/webui/options/core_options_handler.h
deleted file mode 100644
index 1ff2c16f664..00000000000
--- a/chromium/chrome/browser/ui/webui/options/core_options_handler.h
+++ /dev/null
@@ -1,191 +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_OPTIONS_CORE_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CORE_OPTIONS_HANDLER_H_
-
-#include <map>
-#include <memory>
-#include <string>
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/values.h"
-#include "chrome/browser/plugins/plugin_status_pref_setter.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "components/prefs/pref_service.h"
-
-namespace options {
-
-// Core options UI handler.
-// Handles resource and JS calls common to all options sub-pages.
-class CoreOptionsHandler : public OptionsPageUIHandler {
- public:
- CoreOptionsHandler();
- ~CoreOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void Uninitialize() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- void set_handlers_host(OptionsPageUIHandlerHost* handlers_host) {
- handlers_host_ = handlers_host;
- }
-
- // Adds localized strings to |localized_strings|.
- static void GetStaticLocalizedValues(
- base::DictionaryValue* localized_strings);
-
- protected:
- // Fetches a pref value of given |pref_name|.
- // Note that caller owns the returned Value.
- virtual std::unique_ptr<base::Value> FetchPref(const std::string& pref_name);
-
- // Observes a pref of given |pref_name|.
- virtual void ObservePref(const std::string& pref_name);
-
- // Stops observing given preference identified by |pref_name|.
- virtual void StopObservingPref(const std::string& pref_name);
-
- // Sets a pref |value| to given |pref_name|.
- virtual void SetPref(const std::string& pref_name,
- const base::Value* value,
- const std::string& metric);
-
- // Clears pref value for given |pref_name|.
- void ClearPref(const std::string& pref_name, const std::string& metric);
-
- // Records a user metric action for the given value.
- void ProcessUserMetric(const base::Value* value,
- const std::string& metric);
-
- // Virtual dispatch is needed as handling of some prefs may be
- // finessed in subclasses. The PrefService pointer is included
- // so that subclasses can know whether the observed pref is from the
- // local state or not.
- virtual void OnPreferenceChanged(PrefService* service,
- const std::string& pref_name);
-
- // Notifies registered JS callbacks on change in |pref_name| preference.
- // |controlling_pref_name| controls if |pref_name| is managed by
- // policy/extension; empty |controlling_pref_name| indicates no other pref is
- // controlling |pref_name|.
- void NotifyPrefChanged(const std::string& pref_name,
- const std::string& controlling_pref_name);
-
- // Calls JS callbacks to report a change in the value of the |name|
- // preference. |value| is the new value for |name|. Called from
- // Notify*Changed methods to fire off the notifications.
- void DispatchPrefChangeNotification(const std::string& name,
- std::unique_ptr<base::Value> value);
-
- // Creates dictionary value for the pref described by |pref_name|.
- // If |controlling_pref| is not empty, it describes the pref that manages
- // |pref| via policy or extension.
- virtual std::unique_ptr<base::Value> CreateValueForPref(
- const std::string& pref_name,
- const std::string& controlling_pref_name);
-
- typedef std::multimap<std::string, std::string> PreferenceCallbackMap;
- PreferenceCallbackMap pref_callback_map_;
-
- private:
- // Type of preference value received from the page. This doesn't map 1:1 to
- // Value::Type, since a TYPE_STRING can require custom processing.
- enum PrefType {
- TYPE_BOOLEAN = 0,
- TYPE_INTEGER,
- TYPE_DOUBLE,
- TYPE_STRING,
- TYPE_URL,
- TYPE_LIST,
- };
-
- // Finds the pref service that holds the given pref. If the pref is not found,
- // it will return user prefs.
- PrefService* FindServiceForPref(const std::string& pref_name);
-
- // Callback for the "coreOptionsInitialize" message. This message will
- // trigger the Initialize() method of all other handlers so that final
- // setup can be performed before the page is shown.
- void HandleInitialize(const base::ListValue* args);
-
- // Callback for the "onFinishedLoadingOptions" message. This message is sent
- // when the load() handler for the options frame, along with all asynchronous
- // calls it has spawned, have finished running.
- void OnFinishedLoading(const base::ListValue* args);
-
- // Callback for the "fetchPrefs" message. This message accepts the list of
- // preference names passed as the |args| parameter (ListValue). It passes
- // results dictionary of preference values by calling prefsFetched() JS method
- // on the page.
- void HandleFetchPrefs(const base::ListValue* args);
-
- // Callback for the "observePrefs" message. This message initiates
- // notification observing for given array of preference names.
- void HandleObservePrefs(const base::ListValue* args);
-
- // Callbacks for the "set<type>Pref" message. This message saves the new
- // preference value. |args| is an array of parameters as follows:
- // item 0 - name of the preference.
- // item 1 - the value of the preference in string form.
- // item 2 - name of the metric identifier (optional).
- void HandleSetBooleanPref(const base::ListValue* args);
- void HandleSetIntegerPref(const base::ListValue* args);
- void HandleSetDoublePref(const base::ListValue* args);
- void HandleSetStringPref(const base::ListValue* args);
- void HandleSetURLPref(const base::ListValue* args);
- void HandleSetListPref(const base::ListValue* args);
-
- void HandleSetPref(const base::ListValue* args, PrefType type);
-
- // Callback for the "clearPref" message. This message clears a preference
- // value. |args| is an array of parameters as follows:
- // item 0 - name of the preference.
- // item 1 - name of the metric identifier (optional).
- void HandleClearPref(const base::ListValue* args);
-
- // Callback for the "coreOptionsUserMetricsAction" message. This records
- // an action that should be tracked if metrics recording is enabled. |args|
- // is an array that contains a single item, the name of the metric identifier.
- void HandleUserMetricsAction(const base::ListValue* args);
-
- // Callback for the "disableExtension" message. The extension ID string is the
- // only argument in the |args| list.
- void HandleDisableExtension(const base::ListValue* args);
-
- void UpdateClearPluginLSOData();
- void UpdatePepperFlashSettingsEnabled();
-
- // Checks that the current profile is not supervised. Used as a pref filter.
- bool IsUserUnsupervised(const base::Value* to_value);
-
- OptionsPageUIHandlerHost* handlers_host_;
- // This registrar keeps track of user prefs.
- PrefChangeRegistrar registrar_;
- // This registrar keeps track of local state.
- PrefChangeRegistrar local_state_registrar_;
-
- PluginStatusPrefSetter plugin_status_pref_setter_;
-
- // This maps pref names to filter functions. The callbacks should take the
- // value that the user has attempted to set for the pref, and should return
- // true if that value may be applied. If the return value is false, the
- // change will be ignored.
- typedef std::map<std::string, base::Callback<bool(const base::Value*)> >
- PrefChangeFilterMap;
- PrefChangeFilterMap pref_change_filters_;
-
- DISALLOW_COPY_AND_ASSIGN(CoreOptionsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CORE_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/create_profile_handler.cc b/chromium/chrome/browser/ui/webui/options/create_profile_handler.cc
deleted file mode 100644
index f820a9943e0..00000000000
--- a/chromium/chrome/browser/ui/webui/options/create_profile_handler.cc
+++ /dev/null
@@ -1,483 +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 "chrome/browser/ui/webui/options/create_profile_handler.h"
-
-#include <stddef.h>
-
-#include <vector>
-
-#include "base/bind.h"
-#include "base/files/file_path.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/string_util.h"
-#include "base/value_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/profiles/profile_attributes_entry.h"
-#include "chrome/browser/profiles/profile_attributes_storage.h"
-#include "chrome/browser/profiles/profile_avatar_icon_util.h"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/profiles/profile_metrics.h"
-#include "chrome/browser/profiles/profiles_state.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/webui/profile_helper.h"
-#include "chrome/common/features.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/browser_sync/profile_sync_service.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
-#include "chrome/browser/supervised_user/legacy/supervised_user_registration_utility.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service_factory.h"
-#include "chrome/browser/supervised_user/supervised_user_service.h"
-#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
-#endif
-
-namespace options {
-
-CreateProfileHandler::CreateProfileHandler()
- : profile_creation_type_(NO_CREATION_IN_PROGRESS),
- weak_ptr_factory_(this) {
-}
-
-CreateProfileHandler::~CreateProfileHandler() {
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- // Cancellation is only supported for supervised users.
- CancelProfileRegistration(false);
-#endif
-}
-
-void CreateProfileHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
-}
-
-void CreateProfileHandler::RegisterMessages() {
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- // Cancellation is only supported for supervised users.
- web_ui()->RegisterMessageCallback(
- "cancelCreateProfile",
- base::Bind(&CreateProfileHandler::HandleCancelProfileCreation,
- base::Unretained(this)));
-#endif
- web_ui()->RegisterMessageCallback(
- "createProfile",
- base::Bind(&CreateProfileHandler::CreateProfile,
- base::Unretained(this)));
-}
-
-void CreateProfileHandler::CreateProfile(const base::ListValue* args) {
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- // This handler could have been called for a supervised user, for example
- // because the user fiddled with the web inspector. Silently return.
- if (Profile::FromWebUI(web_ui())->IsSupervised())
- return;
-#endif
-
- if (!profiles::IsMultipleProfilesEnabled())
- return;
-
- // We can have only one in progress profile creation
- // at any given moment, if new ones are initiated just
- // ignore them until we are done with the old one.
- if (profile_creation_type_ != NO_CREATION_IN_PROGRESS)
- return;
-
- profile_creation_type_ = NON_SUPERVISED_PROFILE_CREATION;
-
- DCHECK(profile_path_being_created_.empty());
- profile_creation_start_time_ = base::TimeTicks::Now();
-
- base::string16 name;
- std::string icon_url;
- bool create_shortcut = false;
- if (args->GetString(0, &name) && args->GetString(1, &icon_url)) {
- DCHECK(base::IsStringASCII(icon_url));
- base::TrimWhitespace(name, base::TRIM_ALL, &name);
- CHECK(!name.empty());
-#ifndef NDEBUG
- size_t icon_index;
- DCHECK(profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index));
-#endif
- args->GetBoolean(2, &create_shortcut);
- }
- std::string supervised_user_id;
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- if (!ProcessSupervisedCreateProfileArgs(args, &supervised_user_id))
- return;
-#endif
-
- ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_USER_DIALOG);
-
- profile_path_being_created_ = ProfileManager::CreateMultiProfileAsync(
- name, icon_url, base::Bind(&CreateProfileHandler::OnProfileCreated,
- weak_ptr_factory_.GetWeakPtr(),
- create_shortcut, supervised_user_id),
- supervised_user_id);
-}
-
-void CreateProfileHandler::OnProfileCreated(
- bool create_shortcut,
- const std::string& supervised_user_id,
- Profile* profile,
- Profile::CreateStatus status) {
- if (status != Profile::CREATE_STATUS_CREATED)
- RecordProfileCreationMetrics(status);
-
- switch (status) {
- case Profile::CREATE_STATUS_LOCAL_FAIL: {
- ShowProfileCreationError(profile, GetProfileCreationErrorMessageLocal());
- break;
- }
- case Profile::CREATE_STATUS_CREATED: {
- // Do nothing for an intermediate status.
- break;
- }
- case Profile::CREATE_STATUS_INITIALIZED: {
- HandleProfileCreationSuccess(create_shortcut, supervised_user_id,
- profile);
- break;
- }
- // User-initiated cancellation is handled in CancelProfileRegistration and
- // does not call this callback.
- case Profile::CREATE_STATUS_CANCELED:
- // Supervised user registration errors are handled in
- // OnSupervisedUserRegistered().
- case Profile::CREATE_STATUS_REMOTE_FAIL:
- case Profile::MAX_CREATE_STATUS: {
- NOTREACHED();
- break;
- }
- }
-}
-
-void CreateProfileHandler::HandleProfileCreationSuccess(
- bool create_shortcut,
- const std::string& supervised_user_id,
- Profile* profile) {
- switch (profile_creation_type_) {
- case NON_SUPERVISED_PROFILE_CREATION: {
- DCHECK(supervised_user_id.empty());
- CreateShortcutAndShowSuccess(create_shortcut, profile);
- break;
- }
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- case SUPERVISED_PROFILE_CREATION:
- case SUPERVISED_PROFILE_IMPORT:
- RegisterSupervisedUser(create_shortcut, supervised_user_id, profile);
- break;
-#endif
- case NO_CREATION_IN_PROGRESS:
- NOTREACHED();
- break;
- }
-}
-
-void CreateProfileHandler::CreateShortcutAndShowSuccess(bool create_shortcut,
- Profile* profile) {
- if (create_shortcut) {
- ProfileShortcutManager* shortcut_manager =
- g_browser_process->profile_manager()->profile_shortcut_manager();
-
- if (shortcut_manager)
- shortcut_manager->CreateProfileShortcut(profile->GetPath());
- }
-
- DCHECK_EQ(profile_path_being_created_.value(), profile->GetPath().value());
- profile_path_being_created_.clear();
- DCHECK_NE(NO_CREATION_IN_PROGRESS, profile_creation_type_);
- base::DictionaryValue dict;
- dict.SetString("name",
- profile->GetPrefs()->GetString(prefs::kProfileName));
- dict.Set("filePath", base::CreateFilePathValue(profile->GetPath()));
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- bool is_supervised =
- profile_creation_type_ == SUPERVISED_PROFILE_CREATION ||
- profile_creation_type_ == SUPERVISED_PROFILE_IMPORT;
- dict.SetBoolean("isSupervised", is_supervised);
-#endif
- web_ui()->CallJavascriptFunctionUnsafe(
- GetJavascriptMethodName(PROFILE_CREATION_SUCCESS), dict);
-
- // If the new profile is a supervised user, instead of opening a new window
- // right away, a confirmation overlay will be shown by JS from the creation
- // dialog. If we are importing an existing supervised profile or creating a
- // new non-supervised user profile we don't show any confirmation, so open
- // the new window now.
- bool should_open_new_window = true;
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- if (profile_creation_type_ == SUPERVISED_PROFILE_CREATION)
- should_open_new_window = false;
-#endif
-
- if (should_open_new_window) {
- // Opening the new window must be the last action, after all callbacks
- // have been run, to give them a chance to initialize the profile.
- webui::OpenNewWindowForProfile(profile);
- }
- profile_creation_type_ = NO_CREATION_IN_PROGRESS;
-}
-
-void CreateProfileHandler::ShowProfileCreationError(
- Profile* profile,
- const base::string16& error) {
- DCHECK_NE(NO_CREATION_IN_PROGRESS, profile_creation_type_);
- profile_creation_type_ = NO_CREATION_IN_PROGRESS;
- profile_path_being_created_.clear();
- web_ui()->CallJavascriptFunctionUnsafe(
- GetJavascriptMethodName(PROFILE_CREATION_ERROR), base::Value(error));
- // The ProfileManager calls us back with a NULL profile in some cases.
- if (profile) {
- webui::DeleteProfileAtPath(profile->GetPath(),
- web_ui(),
- ProfileMetrics::DELETE_PROFILE_SETTINGS);
- }
-}
-
-void CreateProfileHandler::RecordProfileCreationMetrics(
- Profile::CreateStatus status) {
- UMA_HISTOGRAM_ENUMERATION("Profile.CreateResult",
- status,
- Profile::MAX_CREATE_STATUS);
- UMA_HISTOGRAM_MEDIUM_TIMES(
- "Profile.CreateTimeNoTimeout",
- base::TimeTicks::Now() - profile_creation_start_time_);
-}
-
-base::string16 CreateProfileHandler::GetProfileCreationErrorMessageLocal()
- const {
- int message_id = IDS_PROFILES_CREATE_LOCAL_ERROR;
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- // Local errors can occur during supervised profile import.
- if (profile_creation_type_ == SUPERVISED_PROFILE_IMPORT)
- message_id = IDS_LEGACY_SUPERVISED_USER_IMPORT_LOCAL_ERROR;
-#endif
- return l10n_util::GetStringUTF16(message_id);
-}
-
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
-base::string16 CreateProfileHandler::GetProfileCreationErrorMessageRemote()
- const {
- return l10n_util::GetStringUTF16(
- profile_creation_type_ == SUPERVISED_PROFILE_IMPORT ?
- IDS_LEGACY_SUPERVISED_USER_IMPORT_REMOTE_ERROR :
- IDS_PROFILES_CREATE_REMOTE_ERROR);
-}
-
-base::string16 CreateProfileHandler::GetProfileCreationErrorMessageSignin()
- const {
- return l10n_util::GetStringUTF16(
- profile_creation_type_ == SUPERVISED_PROFILE_IMPORT ?
- IDS_LEGACY_SUPERVISED_USER_IMPORT_SIGN_IN_ERROR :
- IDS_PROFILES_CREATE_SIGN_IN_ERROR);
-}
-#endif
-
-std::string CreateProfileHandler::GetJavascriptMethodName(
- ProfileCreationStatus status) const {
- switch (profile_creation_type_) {
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- case SUPERVISED_PROFILE_IMPORT:
- switch (status) {
- case PROFILE_CREATION_SUCCESS:
- return "BrowserOptions.showSupervisedUserImportSuccess";
- case PROFILE_CREATION_ERROR:
- return "BrowserOptions.showSupervisedUserImportError";
- }
- break;
-#endif
- default:
- switch (status) {
- case PROFILE_CREATION_SUCCESS:
- return "BrowserOptions.showCreateProfileSuccess";
- case PROFILE_CREATION_ERROR:
- return "BrowserOptions.showCreateProfileError";
- }
- break;
- }
-
- NOTREACHED();
- return std::string();
-}
-
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
-bool CreateProfileHandler::ProcessSupervisedCreateProfileArgs(
- const base::ListValue* args, std::string* supervised_user_id) {
- bool supervised_user = false;
- if (args->GetSize() >= 5) {
- bool success = args->GetBoolean(3, &supervised_user);
- DCHECK(success);
-
- success = args->GetString(4, supervised_user_id);
- DCHECK(success);
- }
-
- if (supervised_user) {
- if (!IsValidExistingSupervisedUserId(*supervised_user_id))
- return false;
-
- profile_creation_type_ = SUPERVISED_PROFILE_IMPORT;
- if (supervised_user_id->empty()) {
- profile_creation_type_ = SUPERVISED_PROFILE_CREATION;
- *supervised_user_id =
- SupervisedUserRegistrationUtility::GenerateNewSupervisedUserId();
-
- // If sync is not yet fully initialized, the creation may take extra time,
- // so show a message. Import doesn't wait for an acknowledgment, so it
- // won't have the same potential delay.
- browser_sync::ProfileSyncService* sync_service =
- ProfileSyncServiceFactory::GetInstance()->GetForProfile(
- Profile::FromWebUI(web_ui()));
- browser_sync::ProfileSyncService::SyncStatusSummary status =
- sync_service->QuerySyncStatusSummary();
- if (status ==
- browser_sync::ProfileSyncService::DATATYPES_NOT_INITIALIZED) {
- ShowProfileCreationWarning(l10n_util::GetStringUTF16(
- IDS_PROFILES_CREATE_SUPERVISED_JUST_SIGNED_IN));
- }
- }
- }
- return true;
-}
-
-void CreateProfileHandler::HandleCancelProfileCreation(
- const base::ListValue* args) {
- CancelProfileRegistration(true);
-}
-
-// Non-supervised user creation cannot be canceled. (Creating a non-supervised
-// profile shouldn't take significant time, and it can easily be deleted
-// afterward.)
-void CreateProfileHandler::CancelProfileRegistration(bool user_initiated) {
- if (profile_path_being_created_.empty())
- return;
-
- ProfileManager* manager = g_browser_process->profile_manager();
- Profile* new_profile = manager->GetProfileByPath(profile_path_being_created_);
- if (!new_profile || !new_profile->IsSupervised())
- return;
-
- DCHECK(supervised_user_registration_utility_.get());
- supervised_user_registration_utility_.reset();
-
- if (user_initiated) {
- UMA_HISTOGRAM_MEDIUM_TIMES(
- "Profile.CreateTimeCanceledNoTimeout",
- base::TimeTicks::Now() - profile_creation_start_time_);
- RecordProfileCreationMetrics(Profile::CREATE_STATUS_CANCELED);
- }
-
- DCHECK_NE(NO_CREATION_IN_PROGRESS, profile_creation_type_);
- profile_creation_type_ = NO_CREATION_IN_PROGRESS;
-
- // Cancelling registration means the callback passed into
- // RegisterAndInitSync() won't be called, so the cleanup must be done here.
- profile_path_being_created_.clear();
- webui::DeleteProfileAtPath(new_profile->GetPath(),
- web_ui(),
- ProfileMetrics::DELETE_PROFILE_SETTINGS);
-}
-
-void CreateProfileHandler::RegisterSupervisedUser(
- bool create_shortcut,
- const std::string& supervised_user_id,
- Profile* new_profile) {
- DCHECK_EQ(profile_path_being_created_.value(),
- new_profile->GetPath().value());
-
- SupervisedUserService* supervised_user_service =
- SupervisedUserServiceFactory::GetForProfile(new_profile);
-
- // Register the supervised user using the profile of the custodian.
- supervised_user_registration_utility_ =
- SupervisedUserRegistrationUtility::Create(Profile::FromWebUI(web_ui()));
- supervised_user_service->RegisterAndInitSync(
- supervised_user_registration_utility_.get(),
- Profile::FromWebUI(web_ui()),
- supervised_user_id,
- base::Bind(&CreateProfileHandler::OnSupervisedUserRegistered,
- weak_ptr_factory_.GetWeakPtr(),
- create_shortcut,
- new_profile));
-}
-
-void CreateProfileHandler::OnSupervisedUserRegistered(
- bool create_shortcut,
- Profile* profile,
- const GoogleServiceAuthError& error) {
- GoogleServiceAuthError::State state = error.state();
- RecordSupervisedProfileCreationMetrics(state);
- if (state == GoogleServiceAuthError::NONE) {
- CreateShortcutAndShowSuccess(create_shortcut, profile);
- return;
- }
-
- base::string16 error_msg;
- if (state == GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS ||
- state == GoogleServiceAuthError::USER_NOT_SIGNED_UP ||
- state == GoogleServiceAuthError::ACCOUNT_DELETED ||
- state == GoogleServiceAuthError::ACCOUNT_DISABLED) {
- error_msg = GetProfileCreationErrorMessageSignin();
- } else {
- error_msg = GetProfileCreationErrorMessageRemote();
- }
- ShowProfileCreationError(profile, error_msg);
-}
-
-void CreateProfileHandler::ShowProfileCreationWarning(
- const base::string16& warning) {
- DCHECK_EQ(SUPERVISED_PROFILE_CREATION, profile_creation_type_);
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.showCreateProfileWarning", base::Value(warning));
-}
-
-void CreateProfileHandler::RecordSupervisedProfileCreationMetrics(
- GoogleServiceAuthError::State error_state) {
- if (profile_creation_type_ == SUPERVISED_PROFILE_CREATION) {
- UMA_HISTOGRAM_ENUMERATION("Profile.SupervisedProfileCreateError",
- error_state,
- GoogleServiceAuthError::NUM_STATES);
- UMA_HISTOGRAM_MEDIUM_TIMES(
- "Profile.SupervisedProfileTotalCreateTime",
- base::TimeTicks::Now() - profile_creation_start_time_);
- } else {
- DCHECK_EQ(SUPERVISED_PROFILE_IMPORT, profile_creation_type_);
- UMA_HISTOGRAM_ENUMERATION("Profile.SupervisedProfileImportError",
- error_state,
- GoogleServiceAuthError::NUM_STATES);
- UMA_HISTOGRAM_MEDIUM_TIMES(
- "Profile.SupervisedProfileTotalImportTime",
- base::TimeTicks::Now() - profile_creation_start_time_);
- }
-}
-
-bool CreateProfileHandler::IsValidExistingSupervisedUserId(
- const std::string& existing_supervised_user_id) const {
- if (existing_supervised_user_id.empty())
- return true;
-
- Profile* profile = Profile::FromWebUI(web_ui());
- const base::DictionaryValue* dict =
- SupervisedUserSyncServiceFactory::GetForProfile(profile)->
- GetSupervisedUsers();
- if (!dict->HasKey(existing_supervised_user_id))
- return false;
-
- // Check if this supervised user already exists on this machine.
- std::vector<ProfileAttributesEntry*> entries =
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().GetAllProfilesAttributes();
- for (const ProfileAttributesEntry* entry : entries) {
- if (existing_supervised_user_id == entry->GetSupervisedUserId())
- return false;
- }
- return true;
-}
-#endif
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/create_profile_handler.h b/chromium/chrome/browser/ui/webui/options/create_profile_handler.h
deleted file mode 100644
index 29795ca6856..00000000000
--- a/chromium/chrome/browser/ui/webui/options/create_profile_handler.h
+++ /dev/null
@@ -1,171 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CREATE_PROFILE_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_CREATE_PROFILE_HANDLER_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/time/time.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_window.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chrome/common/features.h"
-#include "google_apis/gaia/google_service_auth_error.h"
-
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
-class SupervisedUserRegistrationUtility;
-#endif
-
-namespace options {
-
-// Handler for the 'create profile' overlay.
-class CreateProfileHandler: public OptionsPageUIHandler {
- public:
- CreateProfileHandler();
- ~CreateProfileHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- // Represents the final profile creation status. It is used to map
- // the status to the javascript method to be called.
- enum ProfileCreationStatus {
- PROFILE_CREATION_SUCCESS,
- PROFILE_CREATION_ERROR,
- };
-
- // Represents the type of the in progress profile creation operation.
- // It is used to map the type of the profile creation operation to the
- // correct UMA metric name.
- enum ProfileCreationOperationType {
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- SUPERVISED_PROFILE_CREATION,
- SUPERVISED_PROFILE_IMPORT,
-#endif
- NON_SUPERVISED_PROFILE_CREATION,
- NO_CREATION_IN_PROGRESS
- };
-
- // Asynchronously creates and initializes a new profile.
- // The arguments are as follows:
- // 0: name (string)
- // 1: icon (string)
- // 2: a flag stating whether we should create a profile desktop shortcut
- // (optional, boolean)
- // 3: a flag stating whether the user should be supervised
- // (optional, boolean)
- // 4: a string representing the supervised user ID.
- void CreateProfile(const base::ListValue* args);
-
- // If a local error occurs during profile creation, then show an appropriate
- // error message. However, if profile creation succeeded and the
- // profile being created/imported is a supervised user profile,
- // then proceed with the registration step. Otherwise, update the UI
- // as the final task after a new profile has been created.
- void OnProfileCreated(bool create_shortcut,
- const std::string& supervised_user_id,
- Profile* profile,
- Profile::CreateStatus status);
-
- void HandleProfileCreationSuccess(bool create_shortcut,
- const std::string& supervised_user_id,
- Profile* profile);
-
- // Creates desktop shortcut and updates the UI to indicate success
- // when creating a profile.
- void CreateShortcutAndShowSuccess(bool create_shortcut, Profile* profile);
-
- // Updates the UI to show an error when creating a profile.
- void ShowProfileCreationError(Profile* profile, const base::string16& error);
-
- // Updates the UI to show a non-fatal warning when creating a profile.
- void ShowProfileCreationWarning(const base::string16& warning);
-
- // Records UMA histograms relevant to profile creation.
- void RecordProfileCreationMetrics(Profile::CreateStatus status);
-
- base::string16 GetProfileCreationErrorMessageLocal() const;
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- // The following error messages only apply to supervised profiles.
- base::string16 GetProfileCreationErrorMessageRemote() const;
- base::string16 GetProfileCreationErrorMessageSignin() const;
-#endif
-
- std::string GetJavascriptMethodName(ProfileCreationStatus status) const;
-
- // Used to allow cancelling a profile creation (particularly a supervised-user
- // registration) in progress. Set when profile creation is begun, and
- // cleared when all the callbacks have been run and creation is complete.
- base::FilePath profile_path_being_created_;
-
- // Used to track how long profile creation takes.
- base::TimeTicks profile_creation_start_time_;
-
- // Indicates the type of the in progress profile creation operation.
- // The value is only relevant while we are creating/importing a profile.
- ProfileCreationOperationType profile_creation_type_;
-
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- // Extracts the supervised user ID from the args passed into CreateProfile,
- // sets |profile_creation_type_| if necessary, and returns true if the
- // supervised user id specified in |args| are valid.
- bool ProcessSupervisedCreateProfileArgs(const base::ListValue* args,
- std::string* supervised_user_id);
-
- // Cancels creation of a supervised-user profile currently in progress, as
- // indicated by profile_path_being_created_, removing the object and files
- // and canceling supervised-user registration. This is the handler for the
- // "cancelCreateProfile" message. |args| is not used.
- void HandleCancelProfileCreation(const base::ListValue* args);
-
- // Internal implementation. This may safely be called whether profile creation
- // or registration is in progress or not. |user_initiated| should be true if
- // the cancellation was deliberately requested by the user, and false if it
- // was caused implicitly, e.g. by shutting down the browser.
- void CancelProfileRegistration(bool user_initiated);
-
- // After a new supervised-user profile has been created, registers the user
- // with the management server.
- void RegisterSupervisedUser(bool create_shortcut,
- const std::string& managed_user_id,
- Profile* new_profile);
-
- // Called back with the result of the supervised user registration.
- void OnSupervisedUserRegistered(bool create_shortcut,
- Profile* profile,
- const GoogleServiceAuthError& error);
-
- // Records UMA histograms relevant to supervised user profiles
- // creation and registration.
- void RecordSupervisedProfileCreationMetrics(
- GoogleServiceAuthError::State error_state);
-
- bool IsValidExistingSupervisedUserId(
- const std::string& existing_supervised_user_id) const;
-
- std::unique_ptr<SupervisedUserRegistrationUtility>
- supervised_user_registration_utility_;
-#endif
-
- base::WeakPtrFactory<CreateProfileHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(CreateProfileHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CREATE_PROFILE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/easy_unlock_handler.cc b/chromium/chrome/browser/ui/webui/options/easy_unlock_handler.cc
deleted file mode 100644
index ff3cf2ddc27..00000000000
--- a/chromium/chrome/browser/ui/webui/options/easy_unlock_handler.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/easy_unlock_handler.h"
-
-#include <string>
-
-#include "base/bind.h"
-#include "base/macros.h"
-#include "base/values.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/signin/easy_unlock_service.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-
-namespace options {
-
-EasyUnlockHandler::EasyUnlockHandler() {
-}
-
-EasyUnlockHandler::~EasyUnlockHandler() {
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->RemoveObserver(this);
-}
-
-void EasyUnlockHandler::GetLocalizedValues(base::DictionaryValue* values) {
- static OptionsStringResource resources[] = {
- {"easyUnlockTurnOffButton", IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_BUTTON},
- {"easyUnlockTurnOffTitle", IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_TITLE},
- {"easyUnlockTurnOffDescription",
- IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_DESCRIPTION},
- {"easyUnlockTurnOffOfflineTitle",
- IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_OFFLINE_TITLE},
- {"easyUnlockTurnOffOfflineMessage",
- IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_OFFLINE_MESSAGE},
- {"easyUnlockTurnOffErrorTitle",
- IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_ERROR_TITLE},
- {"easyUnlockTurnOffErrorMessage",
- IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_ERROR_MESSAGE},
- {"easyUnlockTurnOffRetryButton",
- IDS_OPTIONS_EASY_UNLOCK_TURN_OFF_RETRY_BUTTON},
- };
-
- RegisterStrings(values, resources, arraysize(resources));
-}
-
-void EasyUnlockHandler::InitializeHandler() {
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->AddObserver(this);
-}
-
-void EasyUnlockHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "easyUnlockGetTurnOffFlowStatus",
- base::Bind(&EasyUnlockHandler::HandleGetTurnOffFlowStatus,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "easyUnlockRequestTurnOff",
- base::Bind(&EasyUnlockHandler::HandleRequestTurnOff,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "easyUnlockTurnOffOverlayDismissed",
- base::Bind(&EasyUnlockHandler::HandlePageDismissed,
- base::Unretained(this)));
-}
-
-void EasyUnlockHandler::OnTurnOffOperationStatusChanged() {
- SendTurnOffOperationStatus();
-}
-
-void EasyUnlockHandler::SendTurnOffOperationStatus() {
- EasyUnlockService::TurnOffFlowStatus status =
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))
- ->GetTurnOffFlowStatus();
-
- // Translate status into JS UI state string. Note the translated string
- // should match UIState defined in easy_unlock_turn_off_overlay.js.
- std::string status_string;
- switch (status) {
- case EasyUnlockService::IDLE:
- status_string = "idle";
- break;
- case EasyUnlockService::PENDING:
- status_string = "pending";
- break;
- case EasyUnlockService::FAIL:
- status_string = "server-error";
- break;
- default:
- LOG(ERROR) << "Unknown Easy unlock turn-off operation status: " << status;
- status_string = "idle";
- break;
- }
- web_ui()->CallJavascriptFunctionUnsafe(
- "EasyUnlockTurnOffOverlay.updateUIState", base::Value(status_string));
-}
-
-void EasyUnlockHandler::HandleGetTurnOffFlowStatus(
- const base::ListValue* args) {
- SendTurnOffOperationStatus();
-}
-
-void EasyUnlockHandler::HandleRequestTurnOff(const base::ListValue* args) {
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->RunTurnOffFlow();
-}
-
-void EasyUnlockHandler::HandlePageDismissed(const base::ListValue* args) {
- EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->ResetTurnOffFlow();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/easy_unlock_handler.h b/chromium/chrome/browser/ui/webui/options/easy_unlock_handler.h
deleted file mode 100644
index c8feb5f59b4..00000000000
--- a/chromium/chrome/browser/ui/webui/options/easy_unlock_handler.h
+++ /dev/null
@@ -1,43 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_EASY_UNLOCK_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_EASY_UNLOCK_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/signin/easy_unlock_service_observer.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace options {
-
-class EasyUnlockHandler : public OptionsPageUIHandler,
- public EasyUnlockServiceObserver {
- public:
- EasyUnlockHandler();
- ~EasyUnlockHandler() override;
-
- // OptionsPageUIHandler
- void InitializeHandler() override;
- void GetLocalizedValues(base::DictionaryValue* values) override;
-
- // WebUIMessageHandler
- void RegisterMessages() override;
-
- // EasyUnlockServiceObserver
- void OnTurnOffOperationStatusChanged() override;
-
- private:
- void SendTurnOffOperationStatus();
-
- // JS callbacks.
- void HandleGetTurnOffFlowStatus(const base::ListValue* args);
- void HandleRequestTurnOff(const base::ListValue* args);
- void HandlePageDismissed(const base::ListValue* args);
-
- DISALLOW_COPY_AND_ASSIGN(EasyUnlockHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_EASY_UNLOCK_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/font_settings_handler.cc b/chromium/chrome/browser/ui/webui/options/font_settings_handler.cc
deleted file mode 100644
index 7b1ca1ff248..00000000000
--- a/chromium/chrome/browser/ui/webui/options/font_settings_handler.cc
+++ /dev/null
@@ -1,279 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/font_settings_handler.h"
-
-#include <stddef.h>
-
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/i18n/rtl.h"
-#include "base/macros.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/extensions/extension_tab_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/webui/settings_utils.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/font_list_async.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/web_ui.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/browser/extension_system.h"
-#include "extensions/common/extension.h"
-#include "extensions/common/extension_urls.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "url/gurl.h"
-
-namespace {
-
-const char kAdvancedFontSettingsExtensionId[] =
- "caclkomlalccbpcdllchkeecicepbmbm";
-
-} // namespace
-
-
-namespace options {
-
-FontSettingsHandler::FontSettingsHandler()
- : extension_registry_observer_(this),
- weak_ptr_factory_(this) {
-}
-
-FontSettingsHandler::~FontSettingsHandler() {
-}
-
-void FontSettingsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "fontSettingsStandard",
- IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_STANDARD_LABEL },
- { "fontSettingsSerif",
- IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SERIF_LABEL },
- { "fontSettingsSansSerif",
- IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SANS_SERIF_LABEL },
- { "fontSettingsFixedWidth",
- IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_FIXED_WIDTH_LABEL },
- { "fontSettingsMinimumSize",
- IDS_FONT_LANGUAGE_SETTING_MINIMUM_FONT_SIZE_TITLE },
- { "fontSettings",
- IDS_FONT_LANGUAGE_SETTING_FONT_SUB_DIALOG_TITLE },
- { "fontSettingsSizeTiny",
- IDS_FONT_LANGUAGE_SETTING_FONT_SIZE_TINY },
- { "fontSettingsSizeHuge",
- IDS_FONT_LANGUAGE_SETTING_FONT_SIZE_HUGE },
- { "fontSettingsLoremIpsum",
- IDS_FONT_LANGUAGE_SETTING_LOREM_IPSUM },
- { "advancedFontSettingsOptions",
- IDS_FONT_LANGUAGE_SETTING_ADVANCED_FONT_SETTINGS_OPTIONS }
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "fontSettingsPage",
- IDS_FONT_LANGUAGE_SETTING_FONT_TAB_TITLE);
- localized_strings->SetString("fontSettingsPlaceholder",
- l10n_util::GetStringUTF16(
- IDS_FONT_LANGUAGE_SETTING_PLACEHOLDER));
-
- GURL install_url(extension_urls::GetWebstoreItemDetailURLPrefix());
- localized_strings->SetString("advancedFontSettingsInstall",
- l10n_util::GetStringFUTF16(
- IDS_FONT_LANGUAGE_SETTING_ADVANCED_FONT_SETTINGS_INSTALL,
- base::UTF8ToUTF16(
- install_url.Resolve(kAdvancedFontSettingsExtensionId).spec())));
-}
-
-void FontSettingsHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
- extension_registry_observer_.Add(extensions::ExtensionRegistry::Get(profile));
-}
-
-void FontSettingsHandler::InitializePage() {
- DCHECK(web_ui());
- SetUpStandardFontSample();
- SetUpSerifFontSample();
- SetUpSansSerifFontSample();
- SetUpFixedFontSample();
- SetUpMinimumFontSample();
- NotifyAdvancedFontSettingsAvailability();
-}
-
-void FontSettingsHandler::RegisterMessages() {
- // Perform validation for saved fonts.
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
-#if defined(OS_MACOSX)
- settings_utils::ValidateSavedFonts(pref_service);
-#endif
-
- // Register for preferences that we need to observe manually.
- standard_font_.Init(prefs::kWebKitStandardFontFamily,
- pref_service,
- base::Bind(&FontSettingsHandler::SetUpStandardFontSample,
- base::Unretained(this)));
- serif_font_.Init(prefs::kWebKitSerifFontFamily,
- pref_service,
- base::Bind(&FontSettingsHandler::SetUpSerifFontSample,
- base::Unretained(this)));
- sans_serif_font_.Init(
- prefs::kWebKitSansSerifFontFamily,
- pref_service,
- base::Bind(&FontSettingsHandler::SetUpSansSerifFontSample,
- base::Unretained(this)));
-
- base::Closure callback = base::Bind(
- &FontSettingsHandler::SetUpFixedFontSample, base::Unretained(this));
-
- fixed_font_.Init(prefs::kWebKitFixedFontFamily, pref_service, callback);
- default_fixed_font_size_.Init(prefs::kWebKitDefaultFixedFontSize,
- pref_service, callback);
- default_font_size_.Init(
- prefs::kWebKitDefaultFontSize,
- pref_service,
- base::Bind(&FontSettingsHandler::OnWebKitDefaultFontSizeChanged,
- base::Unretained(this)));
- minimum_font_size_.Init(
- prefs::kWebKitMinimumFontSize,
- pref_service,
- base::Bind(&FontSettingsHandler::SetUpMinimumFontSample,
- base::Unretained(this)));
-
- web_ui()->RegisterMessageCallback("fetchFontsData",
- base::Bind(&FontSettingsHandler::HandleFetchFontsData,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("openAdvancedFontSettingsOptions",
- base::Bind(&FontSettingsHandler::HandleOpenAdvancedFontSettingsOptions,
- base::Unretained(this)));
-}
-
-void FontSettingsHandler::OnExtensionLoaded(
- content::BrowserContext* browser_context,
- const extensions::Extension* extension) {
- NotifyAdvancedFontSettingsAvailability();
-}
-
-void FontSettingsHandler::OnExtensionUnloaded(
- content::BrowserContext* browser_context,
- const extensions::Extension* extension,
- extensions::UnloadedExtensionReason reason) {
- NotifyAdvancedFontSettingsAvailability();
-}
-
-void FontSettingsHandler::HandleFetchFontsData(const base::ListValue* args) {
- content::GetFontListAsync(
- base::Bind(&FontSettingsHandler::FontsListHasLoaded,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void FontSettingsHandler::FontsListHasLoaded(
- std::unique_ptr<base::ListValue> list) {
- // Selects the directionality for the fonts in the given list.
- for (size_t i = 0; i < list->GetSize(); i++) {
- base::ListValue* font;
- bool has_font = list->GetList(i, &font);
- DCHECK(has_font);
- base::string16 value;
- bool has_value = font->GetString(1, &value);
- DCHECK(has_value);
- bool has_rtl_chars = base::i18n::StringContainsStrongRTLChars(value);
- font->AppendString(has_rtl_chars ? "rtl" : "ltr");
- }
-
- base::ListValue selected_values;
- selected_values.AppendString(
- settings_utils::MaybeGetLocalizedFontName(standard_font_.GetValue()));
- selected_values.AppendString(
- settings_utils::MaybeGetLocalizedFontName(serif_font_.GetValue()));
- selected_values.AppendString(
- settings_utils::MaybeGetLocalizedFontName(sans_serif_font_.GetValue()));
- selected_values.AppendString(
- settings_utils::MaybeGetLocalizedFontName(fixed_font_.GetValue()));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "FontSettings.setFontsData", *list.get(), selected_values);
-}
-
-void FontSettingsHandler::SetUpStandardFontSample() {
- base::Value font_value(
- settings_utils::ResolveFontList(standard_font_.GetValue()));
- base::Value size_value(default_font_size_.GetValue());
- web_ui()->CallJavascriptFunctionUnsafe("FontSettings.setUpStandardFontSample",
- font_value, size_value);
-}
-
-void FontSettingsHandler::SetUpSerifFontSample() {
- base::Value font_value(
- settings_utils::ResolveFontList(serif_font_.GetValue()));
- base::Value size_value(default_font_size_.GetValue());
- web_ui()->CallJavascriptFunctionUnsafe("FontSettings.setUpSerifFontSample",
- font_value, size_value);
-}
-
-void FontSettingsHandler::SetUpSansSerifFontSample() {
- base::Value font_value(
- settings_utils::ResolveFontList(sans_serif_font_.GetValue()));
- base::Value size_value(default_font_size_.GetValue());
- web_ui()->CallJavascriptFunctionUnsafe(
- "FontSettings.setUpSansSerifFontSample", font_value, size_value);
-}
-
-void FontSettingsHandler::SetUpFixedFontSample() {
- base::Value font_value(
- settings_utils::ResolveFontList(fixed_font_.GetValue()));
- base::Value size_value(default_fixed_font_size_.GetValue());
- web_ui()->CallJavascriptFunctionUnsafe("FontSettings.setUpFixedFontSample",
- font_value, size_value);
-}
-
-void FontSettingsHandler::SetUpMinimumFontSample() {
- base::Value size_value(minimum_font_size_.GetValue());
- web_ui()->CallJavascriptFunctionUnsafe("FontSettings.setUpMinimumFontSample",
- size_value);
-}
-
-const extensions::Extension*
-FontSettingsHandler::GetAdvancedFontSettingsExtension() {
- Profile* profile = Profile::FromWebUI(web_ui());
- ExtensionService* service =
- extensions::ExtensionSystem::Get(profile)->extension_service();
- if (!service->IsExtensionEnabled(kAdvancedFontSettingsExtensionId))
- return NULL;
- return service->GetInstalledExtension(kAdvancedFontSettingsExtensionId);
-}
-
-void FontSettingsHandler::NotifyAdvancedFontSettingsAvailability() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "FontSettings.notifyAdvancedFontSettingsAvailability",
- base::Value(GetAdvancedFontSettingsExtension() != NULL));
-}
-
-void FontSettingsHandler::HandleOpenAdvancedFontSettingsOptions(
- const base::ListValue* args) {
- const extensions::Extension* extension = GetAdvancedFontSettingsExtension();
- if (!extension)
- return;
- extensions::ExtensionTabUtil::OpenOptionsPage(extension,
- chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()));
-}
-
-void FontSettingsHandler::OnWebKitDefaultFontSizeChanged() {
- SetUpStandardFontSample();
- SetUpSerifFontSample();
- SetUpSansSerifFontSample();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/font_settings_handler.h b/chromium/chrome/browser/ui/webui/options/font_settings_handler.h
deleted file mode 100644
index adcd8e8b2df..00000000000
--- a/chromium/chrome/browser/ui/webui/options/font_settings_handler.h
+++ /dev/null
@@ -1,91 +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_OPTIONS_FONT_SETTINGS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_FONT_SETTINGS_HANDLER_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/scoped_observer.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/prefs/pref_member.h"
-#include "extensions/browser/extension_registry_observer.h"
-
-namespace base {
-class ListValue;
-}
-
-namespace extensions {
-class Extension;
-class ExtensionRegistry;
-}
-
-namespace options {
-
-// Font settings overlay page UI handler.
-class FontSettingsHandler : public OptionsPageUIHandler,
- public extensions::ExtensionRegistryObserver {
- public:
- FontSettingsHandler();
- ~FontSettingsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // ExtensionRegistryObserver implementation.
- void OnExtensionLoaded(content::BrowserContext* browser_context,
- const extensions::Extension* extension) override;
- void OnExtensionUnloaded(content::BrowserContext* browser_context,
- const extensions::Extension* extension,
- extensions::UnloadedExtensionReason reason) override;
-
- private:
- void HandleFetchFontsData(const base::ListValue* args);
-
- void FontsListHasLoaded(std::unique_ptr<base::ListValue> list);
-
- void SetUpStandardFontSample();
- void SetUpSerifFontSample();
- void SetUpSansSerifFontSample();
- void SetUpFixedFontSample();
- void SetUpMinimumFontSample();
-
- // Returns the Advanced Font Settings Extension if it's installed and enabled,
- // or NULL otherwise.
- const extensions::Extension* GetAdvancedFontSettingsExtension();
- // Notifies the web UI about whether the Advanced Font Settings Extension is
- // installed and enabled.
- void NotifyAdvancedFontSettingsAvailability();
- // Opens the options page of the Advanced Font Settings Extension.
- void HandleOpenAdvancedFontSettingsOptions(const base::ListValue* args);
-
- void OnWebKitDefaultFontSizeChanged();
-
- StringPrefMember standard_font_;
- StringPrefMember serif_font_;
- StringPrefMember sans_serif_font_;
- StringPrefMember fixed_font_;
- IntegerPrefMember default_font_size_;
- IntegerPrefMember default_fixed_font_size_;
- IntegerPrefMember minimum_font_size_;
-
- ScopedObserver<extensions::ExtensionRegistry,
- extensions::ExtensionRegistryObserver>
- extension_registry_observer_;
-
- base::WeakPtrFactory<FontSettingsHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(FontSettingsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_FONT_SETTINGS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/geolocation_options_handler.cc b/chromium/chrome/browser/ui/webui/options/geolocation_options_handler.cc
deleted file mode 100644
index 05a04ebbf02..00000000000
--- a/chromium/chrome/browser/ui/webui/options/geolocation_options_handler.cc
+++ /dev/null
@@ -1,40 +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 "chrome/browser/ui/webui/options/geolocation_options_handler.h"
-
-#include "base/command_line.h"
-#include "base/metrics/field_trial.h"
-#include "chrome/common/chrome_switches.h"
-#include "content/public/browser/web_ui.h"
-
-namespace options {
-
-GeolocationOptionsHandler::GeolocationOptionsHandler() {}
-
-GeolocationOptionsHandler::~GeolocationOptionsHandler() {}
-
-void GeolocationOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
-}
-
-void GeolocationOptionsHandler::InitializePage() {
- DCHECK(web_ui());
-
- const char kEnablePrefix[] = "Enable";
- const char kFieldTrialName[] = "GoogleNow";
- std::string enable_prefix(kEnablePrefix);
- std::string field_trial_result =
- base::FieldTrialList::FindFullName(kFieldTrialName);
- if (field_trial_result.compare(
- 0,
- enable_prefix.length(),
- enable_prefix) == 0) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "GeolocationOptions.showGeolocationOption");
- }
-}
-
-} // namespace options
-
diff --git a/chromium/chrome/browser/ui/webui/options/geolocation_options_handler.h b/chromium/chrome/browser/ui/webui/options/geolocation_options_handler.h
deleted file mode 100644
index aeb4e7640c1..00000000000
--- a/chromium/chrome/browser/ui/webui/options/geolocation_options_handler.h
+++ /dev/null
@@ -1,31 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_GEOLOCATION_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_GEOLOCATION_OPTIONS_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/prefs/pref_member.h"
-
-namespace options {
-
-// Handles processing of the geolocation options on settings page load.
-class GeolocationOptionsHandler : public OptionsPageUIHandler {
- public:
- GeolocationOptionsHandler();
- ~GeolocationOptionsHandler() override;
-
- // OptionsPageUIHandler implementation
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializePage() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(GeolocationOptionsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_GEOLOCATION_OPTIONS_HANDLER_H_
-
diff --git a/chromium/chrome/browser/ui/webui/options/handler_options_handler.cc b/chromium/chrome/browser/ui/webui/options/handler_options_handler.cc
deleted file mode 100644
index 73b3fdea0a3..00000000000
--- a/chromium/chrome/browser/ui/webui/options/handler_options_handler.cc
+++ /dev/null
@@ -1,224 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/handler_options_handler.h"
-
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/google/core/browser/google_util.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/web_ui.h"
-
-namespace options {
-
-HandlerOptionsHandler::HandlerOptionsHandler() {
-}
-
-HandlerOptionsHandler::~HandlerOptionsHandler() {
-}
-
-void HandlerOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "handlersTabLabel", IDS_HANDLERS_TAB_LABEL },
- { "handlersAllow", IDS_HANDLERS_ALLOW_RADIO },
- { "handlersBlock", IDS_HANDLERS_DONOTALLOW_RADIO },
- { "handlersTypeColumnHeader", IDS_HANDLERS_TYPE_COLUMN_HEADER },
- { "handlersSiteColumnHeader", IDS_HANDLERS_SITE_COLUMN_HEADER },
- { "handlersRemoveLink", IDS_HANDLERS_REMOVE_HANDLER_LINK },
- { "handlersNoneHandler", IDS_HANDLERS_NONE_HANDLER },
- { "handlersActiveHeading", IDS_HANDLERS_ACTIVE_HEADING },
- { "handlersIgnoredHeading", IDS_HANDLERS_IGNORED_HEADING },
- };
- RegisterTitle(localized_strings, "handlersPage",
- IDS_HANDLER_OPTIONS_WINDOW_TITLE);
- RegisterStrings(localized_strings, resources, arraysize(resources));
-
- localized_strings->SetString("handlersLearnMoreUrl",
- chrome::kLearnMoreRegisterProtocolHandlerURL);
-}
-
-void HandlerOptionsHandler::InitializeHandler() {
- notification_registrar_.Add(
- this, chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
- content::Source<Profile>(Profile::FromWebUI(web_ui())));
-}
-
-void HandlerOptionsHandler::InitializePage() {
- UpdateHandlerList();
-}
-
-void HandlerOptionsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("clearDefault",
- base::Bind(&HandlerOptionsHandler::ClearDefault,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("removeHandler",
- base::Bind(&HandlerOptionsHandler::RemoveHandler,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setHandlersEnabled",
- base::Bind(&HandlerOptionsHandler::SetHandlersEnabled,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setDefault",
- base::Bind(&HandlerOptionsHandler::SetDefault,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("removeIgnoredHandler",
- base::Bind(&HandlerOptionsHandler::RemoveIgnoredHandler,
- base::Unretained(this)));
-}
-
-ProtocolHandlerRegistry* HandlerOptionsHandler::GetProtocolHandlerRegistry() {
- return ProtocolHandlerRegistryFactory::GetForBrowserContext(
- Profile::FromWebUI(web_ui()));
-}
-
-static void GetHandlersAsListValue(
- const ProtocolHandlerRegistry::ProtocolHandlerList& handlers,
- base::ListValue* handler_list) {
- ProtocolHandlerRegistry::ProtocolHandlerList::const_iterator handler;
- for (handler = handlers.begin(); handler != handlers.end(); ++handler) {
- std::unique_ptr<base::ListValue> handler_value(new base::ListValue());
- handler_value->AppendString(handler->protocol());
- handler_value->AppendString(handler->url().spec());
- handler_value->AppendString(handler->url().host());
- handler_list->Append(std::move(handler_value));
- }
-}
-
-void HandlerOptionsHandler::GetHandlersForProtocol(
- const std::string& protocol,
- base::DictionaryValue* handlers_value) {
- ProtocolHandlerRegistry* registry = GetProtocolHandlerRegistry();
- // The items which are to be written into |handlers_value| are also described
- // in chrome/browser/resources/options/handler_options.js in @typedef
- // for Handlers. Please update them whenever you add or remove any keys here.
- handlers_value->SetString("protocol", protocol);
- handlers_value->SetInteger("default_handler",
- registry->GetHandlerIndex(protocol));
- handlers_value->SetBoolean(
- "is_default_handler_set_by_user",
- registry->IsRegisteredByUser(registry->GetHandlerFor(protocol)));
- handlers_value->SetBoolean("has_policy_recommendations",
- registry->HasPolicyRegisteredHandler(protocol));
-
- auto handlers_list = base::MakeUnique<base::ListValue>();
- GetHandlersAsListValue(registry->GetHandlersFor(protocol),
- handlers_list.get());
- handlers_value->Set("handlers", std::move(handlers_list));
-}
-
-void HandlerOptionsHandler::GetIgnoredHandlers(base::ListValue* handlers) {
- ProtocolHandlerRegistry* registry = GetProtocolHandlerRegistry();
- ProtocolHandlerRegistry::ProtocolHandlerList ignored_handlers =
- registry->GetIgnoredHandlers();
- return GetHandlersAsListValue(ignored_handlers, handlers);
-}
-
-void HandlerOptionsHandler::UpdateHandlerList() {
- ProtocolHandlerRegistry* registry = GetProtocolHandlerRegistry();
- std::vector<std::string> protocols;
- registry->GetRegisteredProtocols(&protocols);
-
- base::ListValue handlers;
- for (std::vector<std::string>::iterator protocol = protocols.begin();
- protocol != protocols.end(); protocol++) {
- std::unique_ptr<base::DictionaryValue> handler_value(
- new base::DictionaryValue());
- GetHandlersForProtocol(*protocol, handler_value.get());
- handlers.Append(std::move(handler_value));
- }
-
- std::unique_ptr<base::ListValue> ignored_handlers(new base::ListValue());
- GetIgnoredHandlers(ignored_handlers.get());
- web_ui()->CallJavascriptFunctionUnsafe("HandlerOptions.setHandlers",
- handlers);
- web_ui()->CallJavascriptFunctionUnsafe("HandlerOptions.setIgnoredHandlers",
- *ignored_handlers);
-}
-
-void HandlerOptionsHandler::RemoveHandler(const base::ListValue* args) {
- const base::ListValue* list;
- if (!args->GetList(0, &list)) {
- NOTREACHED();
- return;
- }
-
- ProtocolHandler handler(ParseHandlerFromArgs(list));
- GetProtocolHandlerRegistry()->RemoveHandler(handler);
-
- // No need to call UpdateHandlerList() - we should receive a notification
- // that the ProtocolHandlerRegistry has changed and we will update the view
- // then.
-}
-
-void HandlerOptionsHandler::RemoveIgnoredHandler(const base::ListValue* args) {
- const base::ListValue* list;
- if (!args->GetList(0, &list)) {
- NOTREACHED();
- return;
- }
-
- ProtocolHandler handler(ParseHandlerFromArgs(list));
- GetProtocolHandlerRegistry()->RemoveIgnoredHandler(handler);
-}
-
-void HandlerOptionsHandler::SetHandlersEnabled(const base::ListValue* args) {
- bool enabled = true;
- CHECK(args->GetBoolean(0, &enabled));
- if (enabled)
- GetProtocolHandlerRegistry()->Enable();
- else
- GetProtocolHandlerRegistry()->Disable();
-}
-
-void HandlerOptionsHandler::ClearDefault(const base::ListValue* args) {
- const base::Value* value;
- CHECK(args->Get(0, &value));
- std::string protocol_to_clear;
- CHECK(value->GetAsString(&protocol_to_clear));
- GetProtocolHandlerRegistry()->ClearDefault(protocol_to_clear);
-}
-
-void HandlerOptionsHandler::SetDefault(const base::ListValue* args) {
- const base::ListValue* list;
- CHECK(args->GetList(0, &list));
- const ProtocolHandler& handler(ParseHandlerFromArgs(list));
- CHECK(!handler.IsEmpty());
- GetProtocolHandlerRegistry()->OnAcceptRegisterProtocolHandler(handler);
-}
-
-ProtocolHandler HandlerOptionsHandler::ParseHandlerFromArgs(
- const base::ListValue* args) const {
- base::string16 protocol;
- base::string16 url;
- bool ok = args->GetString(0, &protocol) && args->GetString(1, &url);
- if (!ok)
- return ProtocolHandler::EmptyProtocolHandler();
- return ProtocolHandler::CreateProtocolHandler(base::UTF16ToUTF8(protocol),
- GURL(base::UTF16ToUTF8(url)));
-}
-
-void HandlerOptionsHandler::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- DCHECK_EQ(chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED, type);
- UpdateHandlerList();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/handler_options_handler.h b/chromium/chrome/browser/ui/webui/options/handler_options_handler.h
deleted file mode 100644
index f1b49acbabc..00000000000
--- a/chromium/chrome/browser/ui/webui/options/handler_options_handler.h
+++ /dev/null
@@ -1,90 +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_OPTIONS_HANDLER_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_HANDLER_OPTIONS_HANDLER_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chrome/common/custom_handlers/protocol_handler.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-
-////////////////////////////////////////////////////////////////////////////////
-// HandlerOptionsHandler
-
-// Listen for changes to protocol handlers (i.e. registerProtocolHandler()).
-// This get triggered whenever a user allows a specific website or application
-// to handle clicks on a link with a specified protocol (i.e. mailto: -> Gmail).
-
-namespace base {
-class DictionaryValue;
-}
-
-namespace options {
-
-class HandlerOptionsHandler : public OptionsPageUIHandler,
- public content::NotificationObserver {
- public:
- HandlerOptionsHandler();
- ~HandlerOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // content::NotificationObserver implementation.
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
-
- private:
- // Called when the user toggles whether custom handlers are enabled.
- void SetHandlersEnabled(const base::ListValue* args);
-
- // Called when the user sets a new default handler for a protocol.
- void SetDefault(const base::ListValue* args);
-
- // Called when the user clears the default handler for a protocol.
- // |args| is the string name of the protocol to clear.
- void ClearDefault(const base::ListValue* args);
-
- // Parses a ProtocolHandler out of the arguments passed back from the view.
- // |args| is a list of [protocol, url, title].
- ProtocolHandler ParseHandlerFromArgs(const base::ListValue* args) const;
-
- // Returns a JSON object describing the set of protocol handlers for the
- // given protocol.
- void GetHandlersForProtocol(const std::string& protocol,
- base::DictionaryValue* value);
-
- // Returns a JSON list of the ignored protocol handlers.
- void GetIgnoredHandlers(base::ListValue* handlers);
-
- // Called when the JS PasswordManager object is initialized.
- void UpdateHandlerList();
-
- // Remove a handler.
- // |args| is a list of [protocol, url, title].
- void RemoveHandler(const base::ListValue* args);
-
- // Remove an ignored handler.
- // |args| is a list of [protocol, url, title].
- void RemoveIgnoredHandler(const base::ListValue* args);
-
- ProtocolHandlerRegistry* GetProtocolHandlerRegistry();
-
- content::NotificationRegistrar notification_registrar_;
-
- DISALLOW_COPY_AND_ASSIGN(HandlerOptionsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_HANDLER_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/help_overlay_handler.cc b/chromium/chrome/browser/ui/webui/options/help_overlay_handler.cc
deleted file mode 100644
index fafc0fc6220..00000000000
--- a/chromium/chrome/browser/ui/webui/options/help_overlay_handler.cc
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/help_overlay_handler.h"
-
-#include "base/memory/ptr_util.h"
-#include "base/values.h"
-#include "chrome/browser/ui/webui/help/help_handler.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-
-namespace options {
-
-HelpOverlayHandler::HelpOverlayHandler() {
-}
-
-HelpOverlayHandler::~HelpOverlayHandler() {
-}
-
-void HelpOverlayHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- if (::switches::SettingsWindowEnabled())
- RegisterTitle(localized_strings, "aboutOverlay", IDS_ABOUT_TITLE);
- HelpHandler::GetLocalizedValues(localized_strings);
-}
-
-void HelpOverlayHandler::RegisterMessages() {
- if (::switches::SettingsWindowEnabled())
- web_ui()->AddMessageHandler(base::MakeUnique<HelpHandler>());
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/help_overlay_handler.h b/chromium/chrome/browser/ui/webui/options/help_overlay_handler.h
deleted file mode 100644
index 08b9973ad42..00000000000
--- a/chromium/chrome/browser/ui/webui/options/help_overlay_handler.h
+++ /dev/null
@@ -1,32 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_HELP_OVERLAY_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_HELP_OVERLAY_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace options {
-
-// Help UI page handler to support About in Settings when using Settings in a
-// window. Defers to ::HelpHandler.
-class HelpOverlayHandler : public ::options::OptionsPageUIHandler {
- public:
- HelpOverlayHandler();
- ~HelpOverlayHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(HelpOverlayHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_HELP_OVERLAY_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.cc b/chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.cc
deleted file mode 100644
index e062ed3b876..00000000000
--- a/chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.cc
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/home_page_overlay_handler.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/memory/ptr_util.h"
-#include "base/values.h"
-#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h"
-#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/metrics/proto/omnibox_event.pb.h"
-#include "components/omnibox/browser/autocomplete_classifier.h"
-#include "components/omnibox/browser/autocomplete_controller.h"
-#include "components/omnibox/browser/autocomplete_input.h"
-#include "components/omnibox/browser/autocomplete_result.h"
-#include "content/public/browser/web_ui.h"
-
-namespace options {
-
-HomePageOverlayHandler::HomePageOverlayHandler() {
-}
-
-HomePageOverlayHandler::~HomePageOverlayHandler() {
-}
-
-void HomePageOverlayHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "requestAutocompleteSuggestionsForHomePage",
- base::Bind(&HomePageOverlayHandler::RequestAutocompleteSuggestions,
- base::Unretained(this)));
-}
-
-void HomePageOverlayHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
- autocomplete_controller_.reset(new AutocompleteController(
- base::MakeUnique<ChromeAutocompleteProviderClient>(profile), this,
- AutocompleteClassifier::DefaultOmniboxProviders()));
-}
-
-void HomePageOverlayHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- RegisterTitle(localized_strings, "homePageOverlay",
- IDS_OPTIONS_HOMEPAGE_TITLE);
-}
-
-void HomePageOverlayHandler::RequestAutocompleteSuggestions(
- const base::ListValue* args) {
- base::string16 input;
- CHECK_EQ(args->GetSize(), 1U);
- CHECK(args->GetString(0, &input));
-
- autocomplete_controller_->Start(AutocompleteInput(
- input, base::string16::npos, std::string(), GURL(), base::string16(),
- metrics::OmniboxEventProto::INVALID_SPEC, true, false, false, true, false,
- ChromeAutocompleteSchemeClassifier(Profile::FromWebUI(web_ui()))));
-}
-
-void HomePageOverlayHandler::OnResultChanged(bool default_match_changed) {
- const AutocompleteResult& result = autocomplete_controller_->result();
- base::ListValue suggestions;
- OptionsUI::ProcessAutocompleteSuggestions(result, &suggestions);
- web_ui()->CallJavascriptFunctionUnsafe(
- "HomePageOverlay.updateAutocompleteSuggestions", suggestions);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.h b/chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.h
deleted file mode 100644
index 852e3f9731b..00000000000
--- a/chromium/chrome/browser/ui/webui/options/home_page_overlay_handler.h
+++ /dev/null
@@ -1,48 +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_OPTIONS_HOME_PAGE_OVERLAY_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_HOME_PAGE_OVERLAY_HANDLER_H_
-
-#include <memory>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/omnibox/browser/autocomplete_controller_delegate.h"
-
-class AutocompleteController;
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace options {
-
-class HomePageOverlayHandler : public OptionsPageUIHandler,
- public AutocompleteControllerDelegate {
- public:
- HomePageOverlayHandler();
- ~HomePageOverlayHandler() override;
-
- // OptionsPageUIHandler implementation
- void GetLocalizedValues(base::DictionaryValue*) override;
- void InitializeHandler() override;
- void RegisterMessages() override;
-
- // AutocompleteControllerDelegate implementation.
- void OnResultChanged(bool default_match_changed) override;
-
- private:
- void RequestAutocompleteSuggestions(const base::ListValue* args);
-
- std::unique_ptr<AutocompleteController> autocomplete_controller_;
-
- DISALLOW_COPY_AND_ASSIGN(HomePageOverlayHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_HOME_PAGE_OVERLAY_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/import_data_handler.cc b/chromium/chrome/browser/ui/webui/options/import_data_handler.cc
deleted file mode 100644
index 0b49c9824fd..00000000000
--- a/chromium/chrome/browser/ui/webui/options/import_data_handler.cc
+++ /dev/null
@@ -1,272 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/import_data_handler.h"
-
-#include <stddef.h>
-
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/importer/external_process_importer_host.h"
-#include "chrome/browser/importer/importer_list.h"
-#include "chrome/browser/importer/importer_uma.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/chrome_select_file_policy.h"
-#include "chrome/grit/chromium_strings.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/web_ui.h"
-
-using content::BrowserThread;
-
-namespace options {
-
-ImportDataHandler::ImportDataHandler()
- : importer_host_(NULL),
- import_did_succeed_(false) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-}
-
-ImportDataHandler::~ImportDataHandler() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (importer_host_)
- importer_host_->set_observer(NULL);
-
- if (select_file_dialog_.get())
- select_file_dialog_->ListenerDestroyed();
-}
-
-void ImportDataHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- {"importFromLabel", IDS_IMPORT_FROM_LABEL},
- {"importLoading", IDS_IMPORT_LOADING_PROFILES},
- {"importDescription", IDS_IMPORT_ITEMS_LABEL},
- {"importHistory", IDS_IMPORT_HISTORY_CHKBOX},
- {"importFavorites", IDS_IMPORT_FAVORITES_CHKBOX},
- {"importSearch", IDS_IMPORT_SEARCH_ENGINES_CHKBOX},
- {"importPasswords", IDS_IMPORT_PASSWORDS_CHKBOX},
- {"importAutofillFormData", IDS_IMPORT_AUTOFILL_FORM_DATA_CHKBOX},
- {"importChooseFile", IDS_IMPORT_CHOOSE_FILE},
- {"importCommit", IDS_IMPORT_COMMIT},
- {"noProfileFound", IDS_IMPORT_NO_PROFILE_FOUND},
- {"importSucceeded", IDS_IMPORT_SUCCEEDED},
- {"findYourImportedBookmarks", IDS_IMPORT_FIND_YOUR_BOOKMARKS},
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "importDataOverlay",
- IDS_IMPORT_SETTINGS_TITLE);
-}
-
-void ImportDataHandler::InitializeHandler() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- importer_list_.reset(new ImporterList());
- importer_list_->DetectSourceProfiles(
- g_browser_process->GetApplicationLocale(),
- true, // include_interactive_profiles?
- base::Bind(&ImportDataHandler::InitializePage, base::Unretained(this)));
-}
-
-void ImportDataHandler::RegisterMessages() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- web_ui()->RegisterMessageCallback(
- "importData",
- base::Bind(&ImportDataHandler::ImportData, base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "chooseBookmarksFile",
- base::Bind(&ImportDataHandler::HandleChooseBookmarksFile,
- base::Unretained(this)));
-}
-
-void ImportDataHandler::StartImport(
- const importer::SourceProfile& source_profile,
- uint16_t imported_items) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- if (!imported_items)
- return;
-
- // If another import is already ongoing, let it finish silently.
- if (importer_host_)
- importer_host_->set_observer(NULL);
-
- base::Value importing(true);
- web_ui()->CallJavascriptFunctionUnsafe("ImportDataOverlay.setImportingState",
- importing);
- import_did_succeed_ = false;
-
- importer_host_ = new ExternalProcessImporterHost();
- importer_host_->set_observer(this);
- Profile* profile = Profile::FromWebUI(web_ui());
- importer_host_->StartImportSettings(source_profile, profile,
- imported_items,
- new ProfileWriter(profile));
-
- importer::LogImporterUseToMetrics("ImportDataHandler",
- source_profile.importer_type);
-}
-
-void ImportDataHandler::ImportData(const base::ListValue* args) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- std::string string_value;
-
- int browser_index;
- if (!args->GetString(0, &string_value) ||
- !base::StringToInt(string_value, &browser_index)) {
- NOTREACHED();
- return;
- }
-
- uint16_t selected_items = importer::NONE;
- if (args->GetString(1, &string_value) && string_value == "true") {
- selected_items |= importer::HISTORY;
- }
- if (args->GetString(2, &string_value) && string_value == "true") {
- selected_items |= importer::FAVORITES;
- }
- if (args->GetString(3, &string_value) && string_value == "true") {
- selected_items |= importer::PASSWORDS;
- }
- if (args->GetString(4, &string_value) && string_value == "true") {
- selected_items |= importer::SEARCH_ENGINES;
- }
- if (args->GetString(5, &string_value) && string_value == "true") {
- selected_items |= importer::AUTOFILL_FORM_DATA;
- }
-
- const importer::SourceProfile& source_profile =
- importer_list_->GetSourceProfileAt(browser_index);
- uint16_t supported_items = source_profile.services_supported;
-
- uint16_t imported_items = (selected_items & supported_items);
- if (imported_items) {
- StartImport(source_profile, imported_items);
- } else {
- LOG(WARNING) << "There were no settings to import from '"
- << source_profile.importer_name << "'.";
- }
-}
-
-void ImportDataHandler::InitializePage() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- base::ListValue browser_profiles;
- for (size_t i = 0; i < importer_list_->count(); ++i) {
- const importer::SourceProfile& source_profile =
- importer_list_->GetSourceProfileAt(i);
- uint16_t browser_services = source_profile.services_supported;
-
- std::unique_ptr<base::DictionaryValue> browser_profile(
- new base::DictionaryValue());
- browser_profile->SetString("name", source_profile.importer_name);
- browser_profile->SetInteger("index", i);
- browser_profile->SetBoolean("history",
- (browser_services & importer::HISTORY) != 0);
- browser_profile->SetBoolean("favorites",
- (browser_services & importer::FAVORITES) != 0);
- browser_profile->SetBoolean("passwords",
- (browser_services & importer::PASSWORDS) != 0);
- browser_profile->SetBoolean("search",
- (browser_services & importer::SEARCH_ENGINES) != 0);
- browser_profile->SetBoolean("autofill-form-data",
- (browser_services & importer::AUTOFILL_FORM_DATA) != 0);
-
- browser_profiles.Append(std::move(browser_profile));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ImportDataOverlay.updateSupportedBrowsers", browser_profiles);
-}
-
-void ImportDataHandler::ImportStarted() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-}
-
-void ImportDataHandler::ImportItemStarted(importer::ImportItem item) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- // TODO(csilv): show progress detail in the web view.
-}
-
-void ImportDataHandler::ImportItemEnded(importer::ImportItem item) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- // TODO(csilv): show progress detail in the web view.
- import_did_succeed_ = true;
-}
-
-void ImportDataHandler::ImportEnded() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- importer_host_->set_observer(NULL);
- importer_host_ = NULL;
-
- if (import_did_succeed_) {
- web_ui()->CallJavascriptFunctionUnsafe("ImportDataOverlay.confirmSuccess");
- } else {
- base::Value state(false);
- web_ui()->CallJavascriptFunctionUnsafe(
- "ImportDataOverlay.setImportingState", state);
- web_ui()->CallJavascriptFunctionUnsafe("ImportDataOverlay.dismiss");
- }
-}
-
-void ImportDataHandler::FileSelected(const base::FilePath& path,
- int /*index*/,
- void* /*params*/) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- importer::SourceProfile source_profile;
- source_profile.importer_type = importer::TYPE_BOOKMARKS_FILE;
- source_profile.source_path = path;
-
- StartImport(source_profile, importer::FAVORITES);
-}
-
-void ImportDataHandler::HandleChooseBookmarksFile(const base::ListValue* args) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- DCHECK(args && args->empty());
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
-
- ui::SelectFileDialog::FileTypeInfo file_type_info;
- file_type_info.extensions.resize(1);
- file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html"));
-
- Browser* browser =
- chrome::FindBrowserWithWebContents(web_ui()->GetWebContents());
-
- select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
- base::string16(),
- base::FilePath(),
- &file_type_info,
- 0,
- base::FilePath::StringType(),
- browser->window()->GetNativeWindow(),
- NULL);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/import_data_handler.h b/chromium/chrome/browser/ui/webui/options/import_data_handler.h
deleted file mode 100644
index 32bea2b08f3..00000000000
--- a/chromium/chrome/browser/ui/webui/options/import_data_handler.h
+++ /dev/null
@@ -1,75 +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_OPTIONS_IMPORT_DATA_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_IMPORT_DATA_HANDLER_H_
-
-#include <stdint.h>
-
-#include <memory>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "chrome/browser/importer/importer_progress_observer.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chrome/common/importer/importer_data_types.h"
-#include "ui/shell_dialogs/select_file_dialog.h"
-
-class ExternalProcessImporterHost;
-class ImporterList;
-
-namespace options {
-
-// Chrome personal stuff import data overlay UI handler.
-class ImportDataHandler : public OptionsPageUIHandler,
- public importer::ImporterProgressObserver,
- public ui::SelectFileDialog::Listener {
- public:
- ImportDataHandler();
- ~ImportDataHandler() override;
-
- // OptionsPageUIHandler:
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
-
- // content::WebUIMessageHandler:
- void RegisterMessages() override;
-
- private:
- void StartImport(const importer::SourceProfile& source_profile,
- uint16_t imported_items);
-
- void ImportData(const base::ListValue* args);
-
- // importer::ImporterProgressObserver:
- void ImportStarted() override;
- void ImportItemStarted(importer::ImportItem item) override;
- void ImportItemEnded(importer::ImportItem item) override;
- void ImportEnded() override;
-
- // ui::SelectFileDialog::Listener:
- void FileSelected(const base::FilePath& path,
- int index,
- void* params) override;
-
- // Opens a file selection dialog to choose the bookmarks HTML file.
- void HandleChooseBookmarksFile(const base::ListValue* args);
-
- std::unique_ptr<ImporterList> importer_list_;
-
- // If non-null it means importing is in progress. ImporterHost takes care
- // of deleting itself when import is complete.
- ExternalProcessImporterHost* importer_host_; // weak
-
- bool import_did_succeed_;
-
- scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
-
- DISALLOW_COPY_AND_ASSIGN(ImportDataHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_IMPORT_DATA_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.cc b/chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.cc
deleted file mode 100644
index 247383effce..00000000000
--- a/chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.cc
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/language_dictionary_overlay_handler.h"
-
-#include <string>
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/values.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/spellchecker/spellcheck_factory.h"
-#include "chrome/browser/spellchecker/spellcheck_service.h"
-#include "chrome/grit/generated_resources.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace options {
-
-LanguageDictionaryOverlayHandler::LanguageDictionaryOverlayHandler()
- : overlay_initialized_(false),
- dictionary_(NULL) {
-}
-
-LanguageDictionaryOverlayHandler::~LanguageDictionaryOverlayHandler() {
-}
-
-void LanguageDictionaryOverlayHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- RegisterTitle(localized_strings,
- "languageDictionaryOverlayPage",
- IDS_LANGUAGE_DICTIONARY_OVERLAY_TITLE);
- localized_strings->SetString(
- "languageDictionaryOverlayTitle",
- l10n_util::GetStringUTF16(IDS_LANGUAGE_DICTIONARY_OVERLAY_TITLE));
- localized_strings->SetString(
- "languageDictionaryOverlayAddWordLabel",
- l10n_util::GetStringUTF16(
- IDS_LANGUAGE_DICTIONARY_OVERLAY_ADD_WORD_LABEL));
- localized_strings->SetString(
- "languageDictionaryOverlaySearchPlaceholder",
- l10n_util::GetStringUTF16(
- IDS_LANGUAGE_DICTIONARY_OVERLAY_SEARCH_PLACEHOLDER));
- localized_strings->SetString(
- "languageDictionaryOverlayNoMatches",
- l10n_util::GetStringUTF16(IDS_LANGUAGE_DICTIONARY_OVERLAY_NO_MATCHES));
-}
-
-void LanguageDictionaryOverlayHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "addDictionaryWord",
- base::Bind(&LanguageDictionaryOverlayHandler::AddWord,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "removeDictionaryWord",
- base::Bind(&LanguageDictionaryOverlayHandler::RemoveWord,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "refreshDictionaryWords",
- base::Bind(&LanguageDictionaryOverlayHandler::RefreshWords,
- base::Unretained(this)));
-}
-
-void LanguageDictionaryOverlayHandler::Uninitialize() {
- overlay_initialized_ = false;
- if (dictionary_)
- dictionary_->RemoveObserver(this);
-}
-
-void LanguageDictionaryOverlayHandler::OnCustomDictionaryLoaded() {
- ResetDictionaryWords();
-}
-
-void LanguageDictionaryOverlayHandler::OnCustomDictionaryChanged(
- const SpellcheckCustomDictionary::Change& dictionary_change) {
- base::ListValue add_words;
- for (const std::string& word : dictionary_change.to_add()) {
- add_words.AppendString(word);
- }
-
- base::ListValue remove_words;
- for (const std::string& word : dictionary_change.to_remove()) {
- remove_words.AppendString(word);
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("EditDictionaryOverlay.updateWords",
- add_words, remove_words);
-}
-
-void LanguageDictionaryOverlayHandler::ResetDictionaryWords() {
- if (!overlay_initialized_)
- return;
-
- if (!dictionary_) {
- SpellcheckService* service = SpellcheckServiceFactory::GetForContext(
- Profile::FromWebUI(web_ui()));
- dictionary_ = service->GetCustomDictionary();
- dictionary_->AddObserver(this);
- }
-
- base::ListValue list_value;
- for (const std::string& word : dictionary_->GetWords()) {
- list_value.AppendString(word);
- }
- web_ui()->CallJavascriptFunctionUnsafe("EditDictionaryOverlay.setWordList",
- list_value);
-}
-
-void LanguageDictionaryOverlayHandler::RefreshWords(
- const base::ListValue* args) {
- overlay_initialized_ = true;
- ResetDictionaryWords();
-}
-
-void LanguageDictionaryOverlayHandler::AddWord(const base::ListValue* args) {
- std::string new_word;
- if (!args->GetString(0, &new_word) || new_word.empty() || !dictionary_) {
- NOTREACHED();
- return;
- }
- dictionary_->AddWord(new_word);
-}
-
-void LanguageDictionaryOverlayHandler::RemoveWord(const base::ListValue* args) {
- std::string old_word;
- if (!args->GetString(0, &old_word) || old_word.empty() || !dictionary_) {
- NOTREACHED();
- return;
- }
- dictionary_->RemoveWord(old_word);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.h b/chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.h
deleted file mode 100644
index 742272f386a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/language_dictionary_overlay_handler.h
+++ /dev/null
@@ -1,61 +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_OPTIONS_LANGUAGE_DICTIONARY_OVERLAY_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_LANGUAGE_DICTIONARY_OVERLAY_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace options {
-
-class LanguageDictionaryOverlayHandler
- : public OptionsPageUIHandler,
- public SpellcheckCustomDictionary::Observer {
- public:
- LanguageDictionaryOverlayHandler();
- ~LanguageDictionaryOverlayHandler() override;
-
- // Overridden from OptionsPageUIHandler:
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void RegisterMessages() override;
- void Uninitialize() override;
-
- // Overridden from SpellcheckCustomDictionary::Observer:
- void OnCustomDictionaryLoaded() override;
- void OnCustomDictionaryChanged(
- const SpellcheckCustomDictionary::Change& dictionary_change) override;
-
- private:
- // Sends the dictionary words to WebUI.
- void ResetDictionaryWords();
-
- // Refreshes the displayed words. Called from WebUI.
- void RefreshWords(const base::ListValue* args);
-
- // Adds a new word to the dictionary. Called from WebUI.
- void AddWord(const base::ListValue* args);
-
- // Removes a word from the dictionary. Called from WebUI.
- void RemoveWord(const base::ListValue* args);
-
- // Whether the overlay is initialized and ready to show data.
- bool overlay_initialized_;
-
- // The custom spelling dictionary. Used for adding, removing, and reading
- // words in custom dictionary file.
- SpellcheckCustomDictionary* dictionary_;
-
- DISALLOW_COPY_AND_ASSIGN(LanguageDictionaryOverlayHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_LANGUAGE_DICTIONARY_OVERLAY_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/language_options_handler.cc b/chromium/chrome/browser/ui/webui/options/language_options_handler.cc
deleted file mode 100644
index 1549192785d..00000000000
--- a/chromium/chrome/browser/ui/webui/options/language_options_handler.cc
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/language_options_handler.h"
-
-#include <stddef.h>
-
-#include <map>
-#include <memory>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/i18n/rtl.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/lifetime/application_lifetime.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-using base::UserMetricsAction;
-
-namespace options {
-
-LanguageOptionsHandler::LanguageOptionsHandler() {
-}
-
-LanguageOptionsHandler::~LanguageOptionsHandler() {
-}
-
-void LanguageOptionsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings);
-
- RegisterTitle(localized_strings, "languagePage",
- IDS_OPTIONS_SETTINGS_LANGUAGES_DIALOG_TITLE);
- localized_strings->SetString("restart_button",
- l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON));
- localized_strings->Set("languageList", GetLanguageList());
-}
-
-void LanguageOptionsHandler::RegisterMessages() {
- LanguageOptionsHandlerCommon::RegisterMessages();
-
- web_ui()->RegisterMessageCallback("uiLanguageRestart",
- base::Bind(&LanguageOptionsHandler::RestartCallback,
- base::Unretained(this)));
-}
-
-std::unique_ptr<base::ListValue> LanguageOptionsHandler::GetLanguageList() {
- // Collect the language codes from the supported accept-languages.
- const std::string app_locale = g_browser_process->GetApplicationLocale();
- std::vector<std::string> language_codes;
- l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes);
-
- // Map of display name -> {language code, native_display_name}.
- // In theory, we should be able to create a map that is sorted by
- // display names using ICU comparator, but doing it is hard, thus we'll
- // use an auxiliary vector to achieve the same result.
- typedef std::pair<std::string, base::string16> LanguagePair;
- typedef std::map<base::string16, LanguagePair> LanguageMap;
- LanguageMap language_map;
- // The auxiliary vector mentioned above.
- std::vector<base::string16> display_names;
-
- // Build the list of display names, and build the language map.
- for (size_t i = 0; i < language_codes.size(); ++i) {
- base::string16 display_name =
- l10n_util::GetDisplayNameForLocale(language_codes[i], app_locale,
- false);
- base::string16 native_display_name =
- l10n_util::GetDisplayNameForLocale(language_codes[i], language_codes[i],
- false);
- display_names.push_back(display_name);
- language_map[display_name] =
- std::make_pair(language_codes[i], native_display_name);
- }
- DCHECK_EQ(display_names.size(), language_map.size());
-
- // Sort display names using locale specific sorter.
- l10n_util::SortStrings16(app_locale, &display_names);
-
- // Build the language list from the language map.
- auto language_list = base::MakeUnique<base::ListValue>();
- for (size_t i = 0; i < display_names.size(); ++i) {
- base::string16& display_name = display_names[i];
- base::string16 adjusted_display_name(display_name);
- base::i18n::AdjustStringForLocaleDirection(&adjusted_display_name);
-
- const LanguagePair& pair = language_map[display_name];
- base::string16 adjusted_native_display_name(pair.second);
- base::i18n::AdjustStringForLocaleDirection(&adjusted_native_display_name);
-
- bool has_rtl_chars = base::i18n::StringContainsStrongRTLChars(display_name);
- std::string directionality = has_rtl_chars ? "rtl" : "ltr";
-
- std::unique_ptr<base::DictionaryValue> dictionary(
- new base::DictionaryValue());
- dictionary->SetString("code", pair.first);
- dictionary->SetString("displayName", adjusted_display_name);
- dictionary->SetString("textDirection", directionality);
- dictionary->SetString("nativeDisplayName", adjusted_native_display_name);
- language_list->Append(std::move(dictionary));
- }
-
- return language_list;
-}
-
-void LanguageOptionsHandler::SetApplicationLocale(
- const std::string& language_code) {
- PrefService* pref_service = g_browser_process->local_state();
- pref_service->SetString(prefs::kApplicationLocale, language_code);
-}
-
-void LanguageOptionsHandler::RestartCallback(const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("LanguageOptions_Restart"));
- chrome::AttemptRestart();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/language_options_handler.h b/chromium/chrome/browser/ui/webui/options/language_options_handler.h
deleted file mode 100644
index 93943cd6744..00000000000
--- a/chromium/chrome/browser/ui/webui/options/language_options_handler.h
+++ /dev/null
@@ -1,52 +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_OPTIONS_LANGUAGE_OPTIONS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_LANGUAGE_OPTIONS_HANDLER_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/language_options_handler_common.h"
-
-namespace base {
-class ListValue;
-}
-
-namespace options {
-
-// Language options UI page handler for non-Chrome OS platforms. For Chrome OS,
-// see chromeos::CrosLanguageOptionsHandler.
-class LanguageOptionsHandler : public LanguageOptionsHandlerCommon {
- public:
- LanguageOptionsHandler();
- ~LanguageOptionsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // The following static method is public for ease of testing.
-
- // Gets the list of languages from the given input descriptors.
- // The return value will look like:
- // [{'code': 'fi', 'displayName': 'Finnish', 'nativeDisplayName': 'suomi'},
- // ...]
- static std::unique_ptr<base::ListValue> GetLanguageList();
-
- private:
- // LanguageOptionsHandlerCommon implementation.
- void SetApplicationLocale(const std::string& language_code) override;
-
- // Called when the restart button is clicked.
- void RestartCallback(const base::ListValue* args);
-
- DISALLOW_COPY_AND_ASSIGN(LanguageOptionsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_LANGUAGE_OPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/language_options_handler_common.cc b/chromium/chrome/browser/ui/webui/options/language_options_handler_common.cc
deleted file mode 100644
index fd127384e77..00000000000
--- a/chromium/chrome/browser/ui/webui/options/language_options_handler_common.cc
+++ /dev/null
@@ -1,302 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/language_options_handler_common.h"
-
-#include <stddef.h>
-
-#include <map>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/spellchecker/spellcheck_factory.h"
-#include "chrome/browser/spellchecker/spellcheck_service.h"
-#include "chrome/browser/translate/chrome_translate_client.h"
-#include "chrome/browser/translate/translate_service.h"
-#include "chrome/browser/ui/browser_list.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/chromium_strings.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "components/spellcheck/common/spellcheck_common.h"
-#include "components/translate/core/browser/translate_download_manager.h"
-#include "components/translate/core/browser/translate_prefs.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-using base::UserMetricsAction;
-
-namespace options {
-
-LanguageOptionsHandlerCommon::LanguageOptionsHandlerCommon() {
-}
-
-LanguageOptionsHandlerCommon::~LanguageOptionsHandlerCommon() {
-}
-
-void LanguageOptionsHandlerCommon::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
-#if defined(OS_CHROMEOS)
- const int product_id = IDS_PRODUCT_OS_NAME;
-#else
- const int product_id = IDS_PRODUCT_NAME;
-#endif
-
- static OptionsStringResource resources[] = {
- { "addButton", IDS_OPTIONS_SETTINGS_LANGUAGES_ADD_BUTTON },
- { "languages", IDS_OPTIONS_SETTINGS_LANGUAGES_LANGUAGES },
- { "addLanguageInstructions",
- IDS_OPTIONS_SETTINGS_LANGUAGES_ADD_LANGUAGE_INSTRUCTIONS },
- { "cannotBeDisplayedInThisLanguage",
- IDS_OPTIONS_SETTINGS_LANGUAGES_CANNOT_BE_DISPLAYED_IN_THIS_LANGUAGE,
- product_id },
- { "isDisplayedInThisLanguage",
- IDS_OPTIONS_SETTINGS_LANGUAGES_IS_DISPLAYED_IN_THIS_LANGUAGE,
- product_id },
- { "displayInThisLanguage",
- IDS_OPTIONS_SETTINGS_LANGUAGES_DISPLAY_IN_THIS_LANGUAGE,
- product_id },
- { "restartRequired", IDS_OPTIONS_RELAUNCH_REQUIRED },
- // OS X uses the OS native spellchecker so no need for these strings.
-#if !defined(OS_MACOSX)
- { "useThisForSpellChecking",
- IDS_OPTIONS_SETTINGS_USE_THIS_FOR_SPELL_CHECKING },
- { "cannotBeUsedForSpellChecking",
- IDS_OPTIONS_SETTINGS_CANNOT_BE_USED_FOR_SPELL_CHECKING },
- { "enableSpellCheck", IDS_OPTIONS_ENABLE_SPELLCHECK },
- { "downloadingDictionary", IDS_OPTIONS_DICTIONARY_DOWNLOADING },
- { "downloadFailed", IDS_OPTIONS_DICTIONARY_DOWNLOAD_FAILED },
- { "retryButton", IDS_OPTIONS_DICTIONARY_DOWNLOAD_RETRY },
- { "downloadFailHelp", IDS_OPTIONS_DICTIONARY_DOWNLOAD_FAIL_HELP },
-#endif // !OS_MACOSX
- { "addLanguageTitle", IDS_OPTIONS_LANGUAGES_ADD_TITLE },
- { "addLanguageSelectLabel", IDS_OPTIONS_LANGUAGES_ADD_SELECT_LABEL },
- { "restartButton", IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON },
- { "offerToTranslateInThisLanguage",
- IDS_OPTIONS_LANGUAGES_OFFER_TO_TRANSLATE_IN_THIS_LANGUAGE },
- { "cannotTranslateInThisLanguage",
- IDS_OPTIONS_LANGUAGES_CANNOT_TRANSLATE_IN_THIS_LANGUAGE },
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-
- // The following are resources, rather than local strings.
- std::string application_locale = g_browser_process->GetApplicationLocale();
- localized_strings->SetString("currentUiLanguageCode", application_locale);
- std::string prospective_locale =
- g_browser_process->local_state()->GetString(prefs::kApplicationLocale);
- localized_strings->SetString("prospectiveUiLanguageCode",
- !prospective_locale.empty() ? prospective_locale : application_locale);
- localized_strings->Set("spellCheckLanguageCodeSet",
- GetSpellCheckLanguageCodeSet());
- localized_strings->Set("uiLanguageCodeSet", GetUILanguageCodeSet());
-
- Profile* profile = Profile::FromWebUI(web_ui());
- PrefService* prefs = profile->GetPrefs();
- std::string default_target_language =
- TranslateService::GetTargetLanguage(prefs);
- localized_strings->SetString("defaultTargetLanguage",
- default_target_language);
-
- std::vector<std::string> languages;
- translate::TranslateDownloadManager::GetSupportedLanguages(&languages);
-
- auto languages_list = base::MakeUnique<base::ListValue>();
- for (std::vector<std::string>::iterator it = languages.begin();
- it != languages.end(); ++it) {
- languages_list->AppendString(*it);
- }
-
- localized_strings->Set("translateSupportedLanguages",
- std::move(languages_list));
-}
-
-void LanguageOptionsHandlerCommon::Uninitialize() {
- SpellcheckService* service = GetSpellcheckService();
- if (!service)
- return;
-
- for (const auto& dict : service->GetHunspellDictionaries())
- dict->RemoveObserver(this);
-}
-
-void LanguageOptionsHandlerCommon::RegisterMessages() {
- web_ui()->RegisterMessageCallback("languageOptionsOpen",
- base::Bind(
- &LanguageOptionsHandlerCommon::LanguageOptionsOpenCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("spellCheckLanguageChange",
- base::Bind(
- &LanguageOptionsHandlerCommon::SpellCheckLanguageChangeCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("uiLanguageChange",
- base::Bind(
- &LanguageOptionsHandlerCommon::UiLanguageChangeCallback,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("retryDictionaryDownload",
- base::Bind(
- &LanguageOptionsHandlerCommon::RetrySpellcheckDictionaryDownload,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("updateLanguageList",
- base::Bind(
- &LanguageOptionsHandlerCommon::UpdateLanguageListCallback,
- base::Unretained(this)));
-}
-
-void LanguageOptionsHandlerCommon::OnHunspellDictionaryInitialized(
- const std::string& language) {
-}
-
-void LanguageOptionsHandlerCommon::OnHunspellDictionaryDownloadBegin(
- const std::string& language) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.LanguageOptions.onDictionaryDownloadBegin",
- base::Value(language));
-}
-
-void LanguageOptionsHandlerCommon::OnHunspellDictionaryDownloadSuccess(
- const std::string& language) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.LanguageOptions.onDictionaryDownloadSuccess",
- base::Value(language));
-}
-
-void LanguageOptionsHandlerCommon::OnHunspellDictionaryDownloadFailure(
- const std::string& language) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.LanguageOptions.onDictionaryDownloadFailure",
- base::Value(language));
-}
-
-std::unique_ptr<base::DictionaryValue>
-LanguageOptionsHandlerCommon::GetUILanguageCodeSet() {
- auto dictionary = base::MakeUnique<base::DictionaryValue>();
- const std::vector<std::string>& available_locales =
- l10n_util::GetAvailableLocales();
- for (size_t i = 0; i < available_locales.size(); ++i)
- dictionary->SetBoolean(available_locales[i], true);
- return dictionary;
-}
-
-std::unique_ptr<base::DictionaryValue>
-LanguageOptionsHandlerCommon::GetSpellCheckLanguageCodeSet() {
- auto dictionary = base::MakeUnique<base::DictionaryValue>();
- std::vector<std::string> spell_check_languages;
- spellcheck::SpellCheckLanguages(&spell_check_languages);
- for (size_t i = 0; i < spell_check_languages.size(); ++i) {
- dictionary->SetBoolean(spell_check_languages[i], true);
- }
- return dictionary;
-}
-
-void LanguageOptionsHandlerCommon::LanguageOptionsOpenCallback(
- const base::ListValue* args) {
- base::RecordAction(UserMetricsAction("LanguageOptions_Open"));
- SpellcheckService* service = GetSpellcheckService();
- if (!service)
- return;
-
- for (const auto& dictionary : service->GetHunspellDictionaries()) {
- dictionary->RemoveObserver(this);
- dictionary->AddObserver(this);
-
- if (dictionary->IsDownloadInProgress())
- OnHunspellDictionaryDownloadBegin(dictionary->GetLanguage());
- else if (dictionary->IsDownloadFailure())
- OnHunspellDictionaryDownloadFailure(dictionary->GetLanguage());
- else
- OnHunspellDictionaryDownloadSuccess(dictionary->GetLanguage());
- }
-}
-
-void LanguageOptionsHandlerCommon::UiLanguageChangeCallback(
- const base::ListValue* args) {
- const std::string language_code =
- base::UTF16ToASCII(ExtractStringValue(args));
- CHECK(!language_code.empty());
- const std::string action = base::StringPrintf(
- "LanguageOptions_UiLanguageChange_%s", language_code.c_str());
- base::RecordComputedAction(action);
- SetApplicationLocale(language_code);
- base::Value language_value(language_code);
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.LanguageOptions.uiLanguageSaved", language_value);
-}
-
-void LanguageOptionsHandlerCommon::SpellCheckLanguageChangeCallback(
- const base::ListValue* args) {
- const std::string language_code =
- base::UTF16ToASCII(ExtractStringValue(args));
- const std::string action = base::StringPrintf(
- "LanguageOptions_SpellCheckLanguageChange_%s", language_code.c_str());
- base::RecordComputedAction(action);
-
- SpellcheckService* service = GetSpellcheckService();
- if (!service)
- return;
-
- for (const auto& dictionary : service->GetHunspellDictionaries()) {
- dictionary->RemoveObserver(this);
- dictionary->AddObserver(this);
- }
-}
-
-void LanguageOptionsHandlerCommon::UpdateLanguageListCallback(
- const base::ListValue* args) {
- CHECK_EQ(args->GetSize(), 1u);
- const base::ListValue* language_list;
- args->GetList(0, &language_list);
- DCHECK(language_list);
-
- std::vector<std::string> languages;
- for (base::ListValue::const_iterator it = language_list->begin();
- it != language_list->end(); ++it) {
- std::string lang;
- it->GetAsString(&lang);
- languages.push_back(lang);
- }
-
- Profile* profile = Profile::FromWebUI(web_ui());
- std::unique_ptr<translate::TranslatePrefs> translate_prefs =
- ChromeTranslateClient::CreateTranslatePrefs(profile->GetPrefs());
- translate_prefs->UpdateLanguageList(languages);
-}
-
-void LanguageOptionsHandlerCommon::RetrySpellcheckDictionaryDownload(
- const base::ListValue* args) {
- std::string language = base::UTF16ToUTF8(ExtractStringValue(args));
- SpellcheckService* service = GetSpellcheckService();
- if (!service)
- return;
-
- for (const auto& dictionary : service->GetHunspellDictionaries()) {
- if (dictionary->GetLanguage() == language) {
- dictionary->RetryDownloadDictionary(
- Profile::FromWebUI(web_ui())->GetRequestContext());
- return;
- }
- }
-}
-
-SpellcheckService* LanguageOptionsHandlerCommon::GetSpellcheckService() {
- return SpellcheckServiceFactory::GetForContext(Profile::FromWebUI(web_ui()));
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/language_options_handler_common.h b/chromium/chrome/browser/ui/webui/options/language_options_handler_common.h
deleted file mode 100644
index 18e33557576..00000000000
--- a/chromium/chrome/browser/ui/webui/options/language_options_handler_common.h
+++ /dev/null
@@ -1,96 +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_OPTIONS_LANGUAGE_OPTIONS_HANDLER_COMMON_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_LANGUAGE_OPTIONS_HANDLER_COMMON_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-namespace options {
-
-// The base class for language options page UI handlers. This class has code
-// common to the Chrome OS and non-Chrome OS implementation of the handler.
-class LanguageOptionsHandlerCommon
- : public OptionsPageUIHandler,
- public SpellcheckHunspellDictionary::Observer {
- public:
- LanguageOptionsHandlerCommon();
- ~LanguageOptionsHandlerCommon() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void Uninitialize() override;
-
- // DOMMessageHandler implementation.
- void RegisterMessages() override;
-
- // SpellcheckHunspellDictionary::Observer implementation.
- void OnHunspellDictionaryInitialized(const std::string& language) override;
- void OnHunspellDictionaryDownloadBegin(const std::string& language) override;
- void OnHunspellDictionaryDownloadSuccess(
- const std::string& language) override;
- void OnHunspellDictionaryDownloadFailure(
- const std::string& language) override;
-
- // The following static methods are public for ease of testing.
-
- // Gets the set of language codes that can be used as UI language.
- // The return value will look like:
- // {'en-US': true, 'fi': true, 'fr': true, ...}
- //
- // Note that true in values does not mean anything. We just use the
- // dictionary as a set.
- static std::unique_ptr<base::DictionaryValue> GetUILanguageCodeSet();
-
- // Gets the set of language codes that can be used for spellchecking.
- // The return value will look like:
- // {'en-US': true, 'fi': true, 'fr': true, ...}
- //
- // Note that true in values does not mean anything. We just use the
- // dictionary as a set.
- static std::unique_ptr<base::DictionaryValue> GetSpellCheckLanguageCodeSet();
-
- private:
- // Sets the application locale.
- virtual void SetApplicationLocale(const std::string& language_code) = 0;
-
- // Called when the language options is opened.
- void LanguageOptionsOpenCallback(const base::ListValue* args);
-
- // Called when the UI language is changed.
- // |args| will contain the language code as string (ex. "fr").
- void UiLanguageChangeCallback(const base::ListValue* args);
-
- // Called when the spell check language is changed.
- // |args| will contain the language code as string (ex. "fr").
- void SpellCheckLanguageChangeCallback(const base::ListValue* args);
-
- // Called when the user clicks "Retry" button for a spellcheck dictionary that
- // has failed to download. |args| will contain the language code as a string
- // (ex. "fr").
- void RetrySpellcheckDictionaryDownload(const base::ListValue* args);
-
- // Called when the user saves the language list preferences.
- void UpdateLanguageListCallback(const base::ListValue* args);
-
- // Returns a pointer to the browser SpellcheckService. Can be null if the
- // service has already shut down.
- SpellcheckService* GetSpellcheckService();
-
- DISALLOW_COPY_AND_ASSIGN(LanguageOptionsHandlerCommon);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_LANGUAGE_OPTIONS_HANDLER_COMMON_H_
diff --git a/chromium/chrome/browser/ui/webui/options/manage_profile_handler.cc b/chromium/chrome/browser/ui/webui/options/manage_profile_handler.cc
deleted file mode 100644
index 61f6b8ebbdb..00000000000
--- a/chromium/chrome/browser/ui/webui/options/manage_profile_handler.cc
+++ /dev/null
@@ -1,547 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/manage_profile_handler.h"
-
-#include <stddef.h>
-
-#include <vector>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#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 "build/build_config.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/profiles/gaia_info_update_service.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_attributes_entry.h"
-#include "chrome/browser/profiles/profile_avatar_icon_util.h"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/profiles/profile_metrics.h"
-#include "chrome/browser/profiles/profile_shortcut_manager.h"
-#include "chrome/browser/profiles/profile_window.h"
-#include "chrome/browser/profiles/profiles_state.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/browser_finder.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 "components/browser_sync/profile_sync_service.h"
-#include "components/prefs/pref_service.h"
-#include "components/prefs/scoped_user_pref_update.h"
-#include "components/signin/core/browser/signin_manager.h"
-#include "components/signin/core/common/profile_management_switches.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/web_ui.h"
-#include "google_apis/gaia/gaia_auth_util.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/webui/web_ui_util.h"
-
-namespace options {
-
-namespace {
-
-const char kCreateProfileIdentifier[] = "create";
-const char kManageProfileIdentifier[] = "manage";
-
-// Given |args| from the WebUI, parses value 0 as a FilePath |profile_file_path|
-// and returns true on success.
-bool GetProfilePathFromArgs(const base::ListValue* args,
- base::FilePath* profile_file_path) {
- const base::Value* file_path_value;
- if (!args->Get(0, &file_path_value))
- return false;
- return base::GetValueAsFilePath(*file_path_value, profile_file_path);
-}
-
-void HandleLogDeleteUserDialogShown(const base::ListValue* args) {
- ProfileMetrics::LogProfileDeleteUser(
- ProfileMetrics::DELETE_PROFILE_SETTINGS_SHOW_WARNING);
-}
-
-} // namespace
-
-ManageProfileHandler::ManageProfileHandler()
- : weak_factory_(this) {
-}
-
-ManageProfileHandler::~ManageProfileHandler() {
- browser_sync::ProfileSyncService* service =
- ProfileSyncServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()));
- // Sync may be disabled in tests.
- if (service)
- service->RemoveObserver(this);
-}
-
-void ManageProfileHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "manageProfilesNameLabel", IDS_PROFILES_MANAGE_NAME_LABEL },
- { "manageProfilesIconLabel", IDS_PROFILES_MANAGE_ICON_LABEL },
- { "manageProfilesExistingSupervisedUser",
- IDS_PROFILES_CREATE_LEGACY_SUPERVISED_USER_ERROR_EXISTS_REMOTELY },
- { "managedProfilesExistingLocalSupervisedUser",
- IDS_PROFILES_CREATE_LEGACY_SUPERVISED_USER_ERROR_EXISTS_LOCALLY },
- { "manageProfilesSupervisedSignedInLabel",
- IDS_PROFILES_CREATE_SUPERVISED_SIGNED_IN_LABEL },
- { "manageProfilesSupervisedNotSignedIn",
- IDS_PROFILES_CREATE_SUPERVISED_NOT_SIGNED_IN_HTML },
- { "manageProfilesSupervisedAccountDetailsOutOfDate",
- IDS_PROFILES_CREATE_SUPERVISED_ACCOUNT_DETAILS_OUT_OF_DATE_LABEL },
- { "manageProfilesSupervisedSignInAgainLink",
- IDS_PROFILES_GAIA_REAUTH_TITLE },
- { "manageProfilesConfirm", IDS_SAVE },
- { "deleteProfileTitle", IDS_PROFILES_DELETE_TITLE },
- { "deleteProfileOK", IDS_PROFILES_DELETE_OK_BUTTON_LABEL },
- { "deleteProfileMessage", IDS_PROFILES_DELETE_MESSAGE },
- { "disconnectManagedProfileTitle",
- IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_TITLE },
- { "disconnectManagedProfileOK",
- IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_OK_BUTTON_LABEL },
- { "createProfileTitle", IDS_PROFILES_CREATE_TITLE },
- { "createProfileInstructions", IDS_PROFILES_CREATE_INSTRUCTIONS },
- { "createProfileConfirm", IDS_ADD },
- { "createProfileShortcutCheckbox", IDS_PROFILES_CREATE_SHORTCUT_CHECKBOX },
- { "createProfileShortcutButton", IDS_PROFILES_CREATE_SHORTCUT_BUTTON },
- { "removeProfileShortcutButton", IDS_PROFILES_REMOVE_SHORTCUT_BUTTON },
- { "importExistingSupervisedUserLink",
- IDS_IMPORT_EXISTING_LEGACY_SUPERVISED_USER_TITLE },
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "manageProfile", IDS_PROFILES_MANAGE_TITLE);
- RegisterTitle(localized_strings, "createProfile", IDS_PROFILES_CREATE_TITLE);
- RegisterTitle(localized_strings, "disconnectAccount",
- IDS_DISCONNECT_ACCOUNT_TITLE);
-
- base::string16 supervised_user_dashboard_url =
- base::ASCIIToUTF16(chrome::kLegacySupervisedUserManagementURL);
- base::string16 supervised_user_dashboard_display =
- base::ASCIIToUTF16(chrome::kLegacySupervisedUserManagementDisplayURL);
- localized_strings->SetString("deleteSupervisedProfileAddendum",
- l10n_util::GetStringFUTF16(IDS_PROFILES_DELETE_LEGACY_SUPERVISED_ADDENDUM,
- supervised_user_dashboard_url,
- supervised_user_dashboard_display));
-
- localized_strings->SetBoolean("profileShortcutsEnabled",
- ProfileShortcutManager::IsFeatureEnabled());
-
- GenerateSignedinUserSpecificStrings(localized_strings);
-}
-
-void ManageProfileHandler::InitializeHandler() {
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().AddObserver(this);
-
- Profile* profile = Profile::FromWebUI(web_ui());
- pref_change_registrar_.Init(profile->GetPrefs());
- pref_change_registrar_.Add(
- prefs::kSupervisedUserCreationAllowed,
- base::Bind(&ManageProfileHandler::OnCreateSupervisedUserPrefChange,
- base::Unretained(this)));
- browser_sync::ProfileSyncService* service =
- ProfileSyncServiceFactory::GetForProfile(profile);
- // Sync may be disabled for tests.
- if (service)
- service->AddObserver(this);
-}
-
-void ManageProfileHandler::InitializePage() {
- SendExistingProfileNames();
- OnCreateSupervisedUserPrefChange();
-}
-
-void ManageProfileHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("setProfileIconAndName",
- base::Bind(&ManageProfileHandler::SetProfileIconAndName,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("requestDefaultProfileIcons",
- base::Bind(&ManageProfileHandler::RequestDefaultProfileIcons,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("requestNewProfileDefaults",
- base::Bind(&ManageProfileHandler::RequestNewProfileDefaults,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("requestHasProfileShortcuts",
- base::Bind(&ManageProfileHandler::RequestHasProfileShortcuts,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("requestCreateProfileUpdate",
- base::Bind(&ManageProfileHandler::RequestCreateProfileUpdate,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("profileIconSelectionChanged",
- base::Bind(&ManageProfileHandler::ProfileIconSelectionChanged,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("addProfileShortcut",
- base::Bind(&ManageProfileHandler::AddProfileShortcut,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("removeProfileShortcut",
- base::Bind(&ManageProfileHandler::RemoveProfileShortcut,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("refreshGaiaPicture",
- base::Bind(&ManageProfileHandler::RefreshGaiaPicture,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "showDisconnectManagedProfileDialog",
- base::Bind(&ManageProfileHandler::ShowDisconnectManagedProfileDialog,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("logDeleteUserDialogShown",
- base::Bind(&HandleLogDeleteUserDialogShown));
-}
-
-void ManageProfileHandler::Uninitialize() {
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().RemoveObserver(this);
-}
-
-void ManageProfileHandler::OnProfileAdded(const base::FilePath& profile_path) {
- SendExistingProfileNames();
-}
-
-void ManageProfileHandler::OnProfileWasRemoved(
- const base::FilePath& profile_path,
- const base::string16& profile_name) {
- SendExistingProfileNames();
-}
-
-void ManageProfileHandler::OnProfileNameChanged(
- const base::FilePath& profile_path,
- const base::string16& old_profile_name) {
- base::Value value(kManageProfileIdentifier);
- SendProfileIconsAndNames(value);
-}
-
-void ManageProfileHandler::OnProfileAvatarChanged(
- const base::FilePath& profile_path) {
- base::Value value(kManageProfileIdentifier);
- SendProfileIconsAndNames(value);
-}
-
-void ManageProfileHandler::OnStateChanged(syncer::SyncService* sync) {
- RequestCreateProfileUpdate(NULL);
-}
-
-void ManageProfileHandler::GenerateSignedinUserSpecificStrings(
- base::DictionaryValue* dictionary) {
- std::string username;
- std::string domain_name;
-
-#if !defined(OS_CHROMEOS)
- Profile* profile = Profile::FromWebUI(web_ui());
- DCHECK(profile);
- SigninManagerBase* manager = SigninManagerFactory::GetForProfile(profile);
- if (manager) {
- username = manager->GetAuthenticatedAccountInfo().email;
- // If there is no one logged in or if the profile name is empty then the
- // domain name is empty. This happens in browser tests.
- if (!username.empty()) {
- domain_name = "<span id=disconnect-managed-profile-domain-name>" +
- gaia::ExtractDomainName(username) + "</span>";
- }
- }
-#endif
-
- dictionary->SetString(
- "disconnectManagedProfileDomainInformation",
- l10n_util::GetStringFUTF16(
- IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_DOMAIN_INFORMATION,
- base::ASCIIToUTF16(domain_name)));
-
- dictionary->SetString(
- "disconnectManagedProfileText",
- l10n_util::GetStringFUTF16(
- IDS_PROFILES_DISCONNECT_MANAGED_PROFILE_TEXT,
- base::UTF8ToUTF16(username),
- base::UTF8ToUTF16(chrome::kSyncGoogleDashboardURL)));
-}
-
-void ManageProfileHandler::RequestDefaultProfileIcons(
- const base::ListValue* args) {
- std::string mode;
- bool ok = args->GetString(0, &mode);
- DCHECK(ok);
- DCHECK(mode == kCreateProfileIdentifier || mode == kManageProfileIdentifier);
- if (ok) {
- base::Value value(mode);
- SendProfileIconsAndNames(value);
- }
-}
-
-void ManageProfileHandler::RequestNewProfileDefaults(
- const base::ListValue* args) {
- const ProfileAttributesStorage& storage =
- g_browser_process->profile_manager()->GetProfileAttributesStorage();
- const size_t icon_index = storage.ChooseAvatarIconIndexForNewProfile();
-
- base::DictionaryValue profile_info;
- profile_info.SetString("name", storage.ChooseNameForNewProfile(icon_index));
- profile_info.SetString("iconURL",
- profiles::GetDefaultAvatarIconUrl(icon_index));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ManageProfileOverlay.receiveNewProfileDefaults", profile_info);
-}
-
-void ManageProfileHandler::SendProfileIconsAndNames(const base::Value& mode) {
- base::ListValue image_url_list;
- base::ListValue default_name_list;
-
- ProfileAttributesStorage& storage =
- g_browser_process->profile_manager()->GetProfileAttributesStorage();
-
- // In manage mode, first add the GAIA picture if it is available. No GAIA
- // picture in create mode.
- if (mode.GetString() == kManageProfileIdentifier) {
- Profile* profile = Profile::FromWebUI(web_ui());
- ProfileAttributesEntry* entry = nullptr;
- bool success = storage.GetProfileAttributesWithPath(profile->GetPath(),
- &entry);
- const gfx::Image* icon = success ? entry->GetGAIAPicture() : nullptr;
- if (icon) {
- gfx::Image icon2 = profiles::GetAvatarIconForWebUI(*icon, true);
- gaia_picture_url_ = webui::GetBitmapDataUrl(icon2.AsBitmap());
- image_url_list.AppendString(gaia_picture_url_);
- default_name_list.AppendString(std::string());
- }
- }
-
- // Next add the default avatar icons and names.
- for (size_t i = 0; i < profiles::GetDefaultAvatarIconCount(); i++) {
- std::string url = profiles::GetDefaultAvatarIconUrl(i);
- image_url_list.AppendString(url);
- default_name_list.AppendString(storage.ChooseNameForNewProfile(i));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ManageProfileOverlay.receiveDefaultProfileIconsAndNames", mode,
- image_url_list, default_name_list);
-}
-
-void ManageProfileHandler::SendExistingProfileNames() {
- std::vector<ProfileAttributesEntry*> entries =
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().GetAllProfilesAttributes();
- base::DictionaryValue profile_name_dict;
- for (const ProfileAttributesEntry* entry : entries)
- profile_name_dict.SetBoolean(base::UTF16ToUTF8(entry->GetName()), true);
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "ManageProfileOverlay.receiveExistingProfileNames", profile_name_dict);
-}
-
-void ManageProfileHandler::ShowDisconnectManagedProfileDialog(
- const base::ListValue* args) {
- base::DictionaryValue replacements;
- GenerateSignedinUserSpecificStrings(&replacements);
- web_ui()->CallJavascriptFunctionUnsafe(
- "ManageProfileOverlay.showDisconnectManagedProfileDialog", replacements);
-}
-
-void ManageProfileHandler::SetProfileIconAndName(const base::ListValue* args) {
- DCHECK(args);
-
- base::FilePath profile_file_path;
- if (!GetProfilePathFromArgs(args, &profile_file_path))
- return;
-
- Profile* profile =
- g_browser_process->profile_manager()->GetProfile(profile_file_path);
- if (!profile)
- return;
-
- std::string icon_url;
- if (!args->GetString(1, &icon_url))
- return;
-
- PrefService* pref_service = profile->GetPrefs();
- // Updating the profile preferences will cause the cache to be updated.
-
- // Metrics logging variable.
- bool previously_using_gaia_icon =
- pref_service->GetBoolean(prefs::kProfileUsingGAIAAvatar);
-
- size_t new_icon_index;
- if (icon_url == gaia_picture_url_) {
- pref_service->SetBoolean(prefs::kProfileUsingDefaultAvatar, false);
- pref_service->SetBoolean(prefs::kProfileUsingGAIAAvatar, true);
- if (!previously_using_gaia_icon) {
- // Only log if they changed to the GAIA photo.
- // Selection of GAIA photo as avatar is logged as part of the function
- // below.
- ProfileMetrics::LogProfileSwitchGaia(ProfileMetrics::GAIA_OPT_IN);
- }
- } else if (profiles::IsDefaultAvatarIconUrl(icon_url, &new_icon_index)) {
- ProfileMetrics::LogProfileAvatarSelection(new_icon_index);
- pref_service->SetInteger(prefs::kProfileAvatarIndex, new_icon_index);
- pref_service->SetBoolean(prefs::kProfileUsingDefaultAvatar, false);
- pref_service->SetBoolean(prefs::kProfileUsingGAIAAvatar, false);
- } else {
- // Only default avatars and Gaia account photos are supported.
- CHECK(false);
- }
- ProfileMetrics::LogProfileUpdate(profile_file_path);
-
- if (profile->IsLegacySupervised())
- return;
-
- base::string16 new_profile_name;
- if (!args->GetString(2, &new_profile_name))
- return;
-
- base::TrimWhitespace(new_profile_name, base::TRIM_ALL, &new_profile_name);
- CHECK(!new_profile_name.empty());
- profiles::UpdateProfileName(profile, new_profile_name);
-}
-
-void ManageProfileHandler::ProfileIconSelectionChanged(
- const base::ListValue* args) {
- DCHECK(args);
-
- base::FilePath profile_file_path;
- if (!GetProfilePathFromArgs(args, &profile_file_path))
- return;
-
- // Currently this only supports editing the current profile's info.
- if (profile_file_path != Profile::FromWebUI(web_ui())->GetPath())
- return;
-
- std::string icon_url;
- if (!args->GetString(1, &icon_url))
- return;
-
- if (icon_url != gaia_picture_url_)
- return;
-
- // If the selection is the GAIA picture then also show the profile name in the
- // text field. This will display either the GAIA given name, if available,
- // or the first name.
- ProfileAttributesEntry* entry = nullptr;
- if (!g_browser_process->profile_manager()->GetProfileAttributesStorage().
- GetProfileAttributesWithPath(profile_file_path, &entry))
- return;
- base::string16 gaia_name = entry->GetName();
- if (gaia_name.empty())
- return;
-
- base::Value gaia_name_value(gaia_name);
- base::Value mode_value(kManageProfileIdentifier);
- web_ui()->CallJavascriptFunctionUnsafe("ManageProfileOverlay.setProfileName",
- gaia_name_value, mode_value);
-}
-
-void ManageProfileHandler::RequestHasProfileShortcuts(
- const base::ListValue* args) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- DCHECK(ProfileShortcutManager::IsFeatureEnabled());
-
- base::FilePath profile_file_path;
- if (!GetProfilePathFromArgs(args, &profile_file_path))
- return;
-
- ProfileAttributesStorage& storage =
- g_browser_process->profile_manager()->GetProfileAttributesStorage();
- ProfileAttributesEntry* entry;
- if (!storage.GetProfileAttributesWithPath(profile_file_path, &entry))
- return;
-
- // Don't show the add/remove desktop shortcut button in the single user case.
- if (storage.GetNumberOfProfiles() <= 1u)
- return;
-
- ProfileShortcutManager* shortcut_manager =
- g_browser_process->profile_manager()->profile_shortcut_manager();
- shortcut_manager->HasProfileShortcuts(
- entry->GetPath(), base::Bind(&ManageProfileHandler::OnHasProfileShortcuts,
- weak_factory_.GetWeakPtr()));
-}
-
-void ManageProfileHandler::RequestCreateProfileUpdate(
- const base::ListValue* args) {
- Profile* profile = Profile::FromWebUI(web_ui());
- SigninManagerBase* manager =
- SigninManagerFactory::GetForProfile(profile);
- base::string16 username =
- base::UTF8ToUTF16(manager->GetAuthenticatedAccountInfo().email);
- browser_sync::ProfileSyncService* service =
- ProfileSyncServiceFactory::GetForProfile(profile);
- GoogleServiceAuthError::State state = GoogleServiceAuthError::NONE;
-
- // |service| might be null if Sync is disabled from the command line.
- if (service)
- state = service->GetAuthError().state();
-
- bool has_error = (!service ||
- state == GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS ||
- state == GoogleServiceAuthError::USER_NOT_SIGNED_UP ||
- state == GoogleServiceAuthError::ACCOUNT_DELETED ||
- state == GoogleServiceAuthError::ACCOUNT_DISABLED);
- web_ui()->CallJavascriptFunctionUnsafe(
- "CreateProfileOverlay.updateSignedInStatus", base::Value(username),
- base::Value(has_error));
-
- OnCreateSupervisedUserPrefChange();
-}
-
-void ManageProfileHandler::OnCreateSupervisedUserPrefChange() {
- PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
- base::Value allowed(prefs->GetBoolean(prefs::kSupervisedUserCreationAllowed));
- web_ui()->CallJavascriptFunctionUnsafe(
- "CreateProfileOverlay.updateSupervisedUsersAllowed", allowed);
-}
-
-void ManageProfileHandler::OnHasProfileShortcuts(bool has_shortcuts) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- const base::Value has_shortcuts_value(has_shortcuts);
- web_ui()->CallJavascriptFunctionUnsafe(
- "ManageProfileOverlay.receiveHasProfileShortcuts", has_shortcuts_value);
-}
-
-void ManageProfileHandler::AddProfileShortcut(const base::ListValue* args) {
- base::FilePath profile_file_path;
- if (!GetProfilePathFromArgs(args, &profile_file_path))
- return;
-
- DCHECK(ProfileShortcutManager::IsFeatureEnabled());
- ProfileShortcutManager* shortcut_manager =
- g_browser_process->profile_manager()->profile_shortcut_manager();
- DCHECK(shortcut_manager);
-
- shortcut_manager->CreateProfileShortcut(profile_file_path);
-
- // Update the UI buttons.
- OnHasProfileShortcuts(true);
-}
-
-void ManageProfileHandler::RemoveProfileShortcut(const base::ListValue* args) {
- base::FilePath profile_file_path;
- if (!GetProfilePathFromArgs(args, &profile_file_path))
- return;
-
- DCHECK(ProfileShortcutManager::IsFeatureEnabled());
- ProfileShortcutManager* shortcut_manager =
- g_browser_process->profile_manager()->profile_shortcut_manager();
- DCHECK(shortcut_manager);
-
- shortcut_manager->RemoveProfileShortcuts(profile_file_path);
-
- // Update the UI buttons.
- OnHasProfileShortcuts(false);
-}
-
-void ManageProfileHandler::RefreshGaiaPicture(const base::ListValue* args) {
- profiles::UpdateGaiaProfileInfoIfNeeded(Profile::FromWebUI(web_ui()));
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/manage_profile_handler.h b/chromium/chrome/browser/ui/webui/options/manage_profile_handler.h
deleted file mode 100644
index b0688bfc520..00000000000
--- a/chromium/chrome/browser/ui/webui/options/manage_profile_handler.h
+++ /dev/null
@@ -1,144 +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_OPTIONS_MANAGE_PROFILE_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_MANAGE_PROFILE_HANDLER_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/profiles/profile_attributes_storage.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "components/sync/driver/sync_service_observer.h"
-
-namespace base {
-class Value;
-}
-
-namespace options {
-
-// Chrome personal stuff profiles manage overlay UI handler.
-class ManageProfileHandler : public OptionsPageUIHandler,
- public ProfileAttributesStorage::Observer,
- public syncer::SyncServiceObserver {
- public:
- ManageProfileHandler();
- ~ManageProfileHandler() override;
-
- // OptionsPageUIHandler:
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void Uninitialize() override;
-
- // WebUIMessageHandler:
- void RegisterMessages() override;
-
- // ProfileAttributesStorage::Observer:
- void OnProfileAdded(const base::FilePath& profile_path) override;
- void OnProfileWasRemoved(const base::FilePath& profile_path,
- const base::string16& profile_name) override;
- void OnProfileNameChanged(const base::FilePath& profile_path,
- const base::string16& old_profile_name) override;
- void OnProfileAvatarChanged(const base::FilePath& profile_path) override;
-
- // syncer::SyncServiceObserver:
- void OnStateChanged(syncer::SyncService* sync) override;
-
- private:
- // This function creates signed in user specific strings in loadTimeData.
- void GenerateSignedinUserSpecificStrings(base::DictionaryValue* dictionary);
-
- // Callback for the "requestDefaultProfileIcons" message.
- // Sends the array of default profile icon URLs and profile names to WebUI.
- // First item of |args| is the dialog mode, i.e. "create" or "manage".
- void RequestDefaultProfileIcons(const base::ListValue* args);
-
- // Callback for the "requestNewProfileDefaults" message.
- // Sends an object to WebUI of the form:
- // { "name": profileName, "iconURL": iconURL }
- void RequestNewProfileDefaults(const base::ListValue* args);
-
- // Send all profile icons and their default names to the overlay.
- // |mode| is the dialog mode, i.e. "create" or "manage".
- void SendProfileIconsAndNames(const base::Value& mode);
-
- // Sends an object to WebUI of the form:
- // profileNames = {
- // "Profile Name 1": true,
- // "Profile Name 2": true,
- // ...
- // };
- // This is used to detect duplicate profile names.
- void SendExistingProfileNames();
-
- // Show disconnect managed profile dialog after generating domain and user
- // specific strings.
- void ShowDisconnectManagedProfileDialog(const base::ListValue* args);
-
- // Callback for the "setProfileIconAndName" message. Sets the name and icon
- // of a given profile.
- // |args| is of the form: [
- // /*string*/ profileFilePath,
- // /*string*/ newProfileIconURL
- // /*string*/ newProfileName,
- // ]
- void SetProfileIconAndName(const base::ListValue* args);
-
- // Callback for the 'profileIconSelectionChanged' message. Used to update the
- // name in the manager profile dialog based on the selected icon.
- void ProfileIconSelectionChanged(const base::ListValue* args);
-
- // Callback for the "requestHasProfileShortcuts" message, which is called
- // when editing an existing profile. Asks the profile shortcut manager whether
- // the profile has shortcuts and gets the result in |OnHasProfileShortcuts()|.
- // |args| is of the form: [ {string} profileFilePath ]
- void RequestHasProfileShortcuts(const base::ListValue* args);
-
- // Callback for the "RequestCreateProfileUpdate" message.
- // Sends the email address of the signed-in user, or an empty string if the
- // user is not signed in. Also sends information about whether supervised
- // users may be created.
- void RequestCreateProfileUpdate(const base::ListValue* args);
-
- // When the pref allowing supervised-user creation changes, sends the new
- // value to the UI.
- void OnCreateSupervisedUserPrefChange();
-
- // Callback invoked from the profile manager indicating whether the profile
- // being edited has any desktop shortcuts.
- void OnHasProfileShortcuts(bool has_shortcuts);
-
- // Callback for the "addProfileShortcut" message, which is called when editing
- // an existing profile and the user clicks the "Add desktop shortcut" button.
- // Adds a desktop shortcut for the profile.
- void AddProfileShortcut(const base::ListValue* args);
-
- // Callback for the "removeProfileShortcut" message, which is called when
- // editing an existing profile and the user clicks the "Remove desktop
- // shortcut" button. Removes the desktop shortcut for the profile.
- void RemoveProfileShortcut(const base::ListValue* args);
-
- // Callback for the "refreshGaiaPicture" message, which is called when the
- // user is editing an existing profile.
- void RefreshGaiaPicture(const base::ListValue* args);
-
- // URL for the current profile's GAIA picture.
- std::string gaia_picture_url_;
-
- // Used to observe the preference that allows creating supervised users, which
- // can be changed by policy.
- PrefChangeRegistrar pref_change_registrar_;
-
- // For generating weak pointers to itself for callbacks.
- base::WeakPtrFactory<ManageProfileHandler> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(ManageProfileHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_MANAGE_PROFILE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.cc b/chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.cc
deleted file mode 100644
index df8b4597f0f..00000000000
--- a/chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.cc
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/media_devices_selection_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/macros.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-
-#if BUILDFLAG(ENABLE_EXTENSIONS)
-#include "extensions/strings/grit/extensions_strings.h"
-#include "ui/base/l10n/l10n_util.h"
-#endif
-
-namespace {
-
-const char kAudio[] = "mic";
-const char kVideo[] = "camera";
-
-} // namespace
-
-namespace options {
-
-MediaDevicesSelectionHandler::MediaDevicesSelectionHandler() {}
-
-MediaDevicesSelectionHandler::~MediaDevicesSelectionHandler() {
- MediaCaptureDevicesDispatcher::GetInstance()->RemoveObserver(this);
-}
-
-void MediaDevicesSelectionHandler::GetLocalizedValues(
- base::DictionaryValue* values) {
- DCHECK(values);
-
- static OptionsStringResource resources[] = {
- { "mediaSelectMicLabel", IDS_MEDIA_SELECTED_MIC_LABEL },
- { "mediaSelectCameraLabel", IDS_MEDIA_SELECTED_CAMERA_LABEL },
- };
-
- RegisterStrings(values, resources, arraysize(resources));
-}
-
-void MediaDevicesSelectionHandler::InitializePage() {
- // Register to the device observer list to get up-to-date device lists.
- MediaCaptureDevicesDispatcher::GetInstance()->AddObserver(this);
-
- // Update the device selection menus.
- UpdateDevicesMenuForType(AUDIO);
- UpdateDevicesMenuForType(VIDEO);
-}
-
-void MediaDevicesSelectionHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("setDefaultCaptureDevice",
- base::Bind(&MediaDevicesSelectionHandler::SetDefaultCaptureDevice,
- base::Unretained(this)));
-}
-
-void MediaDevicesSelectionHandler::OnUpdateAudioDevices(
- const content::MediaStreamDevices& devices) {
- UpdateDevicesMenu(AUDIO, devices);
-}
-
-void MediaDevicesSelectionHandler::OnUpdateVideoDevices(
- const content::MediaStreamDevices& devices) {
- UpdateDevicesMenu(VIDEO, devices);
-}
-
-void MediaDevicesSelectionHandler::SetDefaultCaptureDevice(
- const base::ListValue* args) {
- DCHECK_EQ(2U, args->GetSize());
- std::string type, device;
- if (!(args->GetString(0, &type) && args->GetString(1, &device))) {
- NOTREACHED();
- return;
- }
-
- DCHECK(!type.empty());
- DCHECK(!device.empty());
-
- Profile* profile = Profile::FromWebUI(web_ui());
- PrefService* prefs = profile->GetPrefs();
- if (type == kAudio)
- prefs->SetString(prefs::kDefaultAudioCaptureDevice, device);
- else if (type == kVideo)
- prefs->SetString(prefs::kDefaultVideoCaptureDevice, device);
- else
- NOTREACHED();
-}
-
-void MediaDevicesSelectionHandler::UpdateDevicesMenu(
- DeviceType type, const content::MediaStreamDevices& devices) {
- // Get the default device unique id from prefs.
- Profile* profile = Profile::FromWebUI(web_ui());
- PrefService* prefs = profile->GetPrefs();
- std::string default_device;
- std::string device_type;
- switch (type) {
- case AUDIO:
- default_device = prefs->GetString(prefs::kDefaultAudioCaptureDevice);
- device_type = kAudio;
- break;
- case VIDEO:
- default_device = prefs->GetString(prefs::kDefaultVideoCaptureDevice);
- device_type = kVideo;
- break;
- }
-
- // Build the list of devices to send to JS.
- std::string default_id;
- base::ListValue device_list;
- for (size_t i = 0; i < devices.size(); ++i) {
- std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
- entry->SetString("name", GetDeviceDisplayName(devices[i]));
- entry->SetString("id", devices[i].id);
- device_list.Append(std::move(entry));
- if (devices[i].id == default_device)
- default_id = default_device;
- }
-
- // Use the first device as the default device if the preferred default device
- // does not exist in the OS.
- if (!devices.empty() && default_id.empty())
- default_id = devices[0].id;
-
- base::Value default_value(default_id);
- base::Value type_value(device_type);
- web_ui()->CallJavascriptFunctionUnsafe("ContentSettings.updateDevicesMenu",
- type_value, device_list,
- default_value);
-}
-
-std::string MediaDevicesSelectionHandler::GetDeviceDisplayName(
- const content::MediaStreamDevice& device) const {
- std::string facing_info;
-
-#if BUILDFLAG(ENABLE_EXTENSIONS)
- switch (device.video_facing) {
- case media::VideoFacingMode::MEDIA_VIDEO_FACING_USER:
- facing_info = l10n_util::GetStringUTF8(IDS_CAMERA_FACING_USER);
- break;
- case media::VideoFacingMode::MEDIA_VIDEO_FACING_ENVIRONMENT:
- facing_info = l10n_util::GetStringUTF8(IDS_CAMERA_FACING_ENVIRONMENT);
- break;
- case media::VideoFacingMode::MEDIA_VIDEO_FACING_NONE:
- break;
- case media::VideoFacingMode::NUM_MEDIA_VIDEO_FACING_MODES:
- NOTREACHED();
- break;
- }
-#endif
-
- if (facing_info.empty())
- return device.name;
- return device.name + " " + facing_info;
-}
-
-void MediaDevicesSelectionHandler::UpdateDevicesMenuForType(DeviceType type) {
- content::MediaStreamDevices devices;
- switch (type) {
- case AUDIO:
- devices = MediaCaptureDevicesDispatcher::GetInstance()->
- GetAudioCaptureDevices();
- break;
- case VIDEO:
- devices = MediaCaptureDevicesDispatcher::GetInstance()->
- GetVideoCaptureDevices();
- break;
- }
-
- UpdateDevicesMenu(type, devices);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.h b/chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.h
deleted file mode 100644
index ff1355ad633..00000000000
--- a/chromium/chrome/browser/ui/webui/options/media_devices_selection_handler.h
+++ /dev/null
@@ -1,59 +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_OPTIONS_MEDIA_DEVICES_SELECTION_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_MEDIA_DEVICES_SELECTION_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "content/public/browser/web_contents.h"
-
-namespace options {
-
-// Handler for media devices selection in content settings.
-class MediaDevicesSelectionHandler
- : public MediaCaptureDevicesDispatcher::Observer,
- public OptionsPageUIHandler {
- public:
- MediaDevicesSelectionHandler();
- ~MediaDevicesSelectionHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* values) override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // MediaCaptureDevicesDispatcher::Observer implementation.
- void OnUpdateAudioDevices(
- const content::MediaStreamDevices& devices) override;
- void OnUpdateVideoDevices(
- const content::MediaStreamDevices& devices) override;
-
- private:
- enum DeviceType {
- AUDIO,
- VIDEO,
- };
-
- // Sets the default audio/video capture device for media. |args| includes the
- // media type (kAuudio/kVideo) and the unique id of the new default device
- // that the user has chosen.
- void SetDefaultCaptureDevice(const base::ListValue* args);
-
- // Helpers methods to update the device menus.
- void UpdateDevicesMenuForType(DeviceType type);
- void UpdateDevicesMenu(DeviceType type,
- const content::MediaStreamDevices& devices);
-
- // Gets the human readable name of the device.
- std::string GetDeviceDisplayName(
- const content::MediaStreamDevice& device) const;
-
- DISALLOW_COPY_AND_ASSIGN(MediaDevicesSelectionHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_MEDIA_DEVICES_SELECTION_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/options_ui.cc b/chromium/chrome/browser/ui/webui/options/options_ui.cc
deleted file mode 100644
index aaf5474e7fc..00000000000
--- a/chromium/chrome/browser/ui/webui/options/options_ui.cc
+++ /dev/null
@@ -1,662 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-#include <algorithm>
-#include <utility>
-#include <vector>
-
-#include "base/callback.h"
-#include "base/command_line.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted_memory.h"
-#include "base/memory/singleton.h"
-#include "base/message_loop/message_loop.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_util.h"
-#include "base/threading/thread.h"
-#include "base/time/time.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/browser_about_handler.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/extensions/tab_helper.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/metrics_handler.h"
-#include "chrome/browser/ui/webui/options/autofill_options_handler.h"
-#include "chrome/browser/ui/webui/options/automatic_settings_reset_handler.h"
-#include "chrome/browser/ui/webui/options/browser_options_handler.h"
-#include "chrome/browser/ui/webui/options/clear_browser_data_handler.h"
-#include "chrome/browser/ui/webui/options/content_settings_handler.h"
-#include "chrome/browser/ui/webui/options/cookies_view_handler.h"
-#include "chrome/browser/ui/webui/options/core_options_handler.h"
-#include "chrome/browser/ui/webui/options/create_profile_handler.h"
-#include "chrome/browser/ui/webui/options/easy_unlock_handler.h"
-#include "chrome/browser/ui/webui/options/font_settings_handler.h"
-#include "chrome/browser/ui/webui/options/handler_options_handler.h"
-#include "chrome/browser/ui/webui/options/help_overlay_handler.h"
-#include "chrome/browser/ui/webui/options/home_page_overlay_handler.h"
-#include "chrome/browser/ui/webui/options/import_data_handler.h"
-#include "chrome/browser/ui/webui/options/language_dictionary_overlay_handler.h"
-#include "chrome/browser/ui/webui/options/language_options_handler.h"
-#include "chrome/browser/ui/webui/options/manage_profile_handler.h"
-#include "chrome/browser/ui/webui/options/media_devices_selection_handler.h"
-#include "chrome/browser/ui/webui/options/password_manager_handler.h"
-#include "chrome/browser/ui/webui/options/reset_profile_settings_handler.h"
-#include "chrome/browser/ui/webui/options/search_engine_manager_handler.h"
-#include "chrome/browser/ui/webui/options/startup_pages_handler.h"
-#include "chrome/browser/ui/webui/options/sync_setup_handler.h"
-#include "chrome/browser/ui/webui/theme_source.h"
-#include "chrome/common/features.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "chrome/grit/options_resources.h"
-#include "components/omnibox/browser/autocomplete_match.h"
-#include "components/omnibox/browser/autocomplete_result.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/navigation_handle.h"
-#include "content/public/browser/notification_types.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/url_data_source.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_contents_delegate.h"
-#include "content/public/browser/web_ui.h"
-#include "net/base/escape.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/template_expressions.h"
-#include "ui/base/webui/jstemplate_builder.h"
-#include "ui/base/webui/web_ui_util.h"
-#include "url/gurl.h"
-
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
-#include "chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.h"
-#include "chrome/browser/ui/webui/options/supervised_user_import_handler.h"
-#include "chrome/browser/ui/webui/options/supervised_user_learn_more_handler.h"
-#endif
-
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/browser_process_platform_part.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/system/pointer_device_observer.h"
-#include "chrome/browser/ui/webui/chromeos/user_image_source.h"
-#include "chrome/browser/ui/webui/options/chromeos/accounts_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/bluetooth_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/change_picture_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/core_chromeos_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/date_time_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/display_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/display_overscan_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/internet_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/keyboard_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/options_stylus_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/pointer_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/power_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/proxy_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/stats_options_handler.h"
-#include "chrome/browser/ui/webui/options/chromeos/storage_manager_handler.h"
-#endif
-
-#if defined(USE_NSS_CERTS)
-#include "chrome/browser/ui/webui/options/certificate_manager_handler.h"
-#endif
-
-#if BUILDFLAG(ENABLE_GOOGLE_NOW)
-#include "chrome/browser/ui/webui/options/geolocation_options_handler.h"
-#endif
-
-using content::RenderViewHost;
-
-namespace {
-
-const char kLocalizedStringsFile[] = "strings.js";
-const char kOptionsBundleJsFile[] = "options_bundle.js";
-
-#if defined(OS_CHROMEOS)
-constexpr char kIconsHTMLPath[] = "icons.html";
-constexpr char kPinKeyboardHTMLPath[] = "people_page/pin_keyboard.html";
-constexpr char kPinKeyboardJSPath[] = "people_page/pin_keyboard.js";
-constexpr char kPasswordPromptDialogHTMLPath[] =
- "people_page/password_prompt_dialog.html";
-constexpr char kPasswordPromptDialogJSPath[] =
- "people_page/password_prompt_dialog.js";
-constexpr char kLockScreenConstantsHTMLPath[] =
- "people_page/lock_screen_constants.html";
-constexpr char kLockScreenConstantsJSPath[] =
- "people_page/lock_screen_constants.js";
-constexpr char kLockStateBehaviorHTMLPath[] =
- "people_page/lock_state_behavior.html";
-constexpr char kLockStateBehaviorJSPath[] =
- "people_page/lock_state_behavior.js";
-constexpr char kLockScreenHTMLPath[] = "people_page/lock_screen.html";
-constexpr char kLockScreenJSPath[] = "people_page/lock_screen.js";
-constexpr char kSetupPinHTMLPath[] = "people_page/setup_pin_dialog.html";
-constexpr char kSetupPinJSPath[] = "people_page/setup_pin_dialog.js";
-constexpr char kEasyUnlockBrowserProxyHTMLPath[] =
- "people_page/easy_unlock_browser_proxy.html";
-constexpr char kEasyUnlockBrowserProxyJSPath[] =
- "people_page/easy_unlock_browser_proxy.js";
-constexpr char kEasyUnlockTurnOffDialogHTMLPath[] =
- "people_page/easy_unlock_turn_off_dialog.html";
-constexpr char kEasyUnlockTurnOffDialogJSPath[] =
- "people_page/easy_unlock_turn_off_dialog.js";
-constexpr char kFingerprintListHTMLPath[] = "people_page/fingerprint_list.html";
-constexpr char kFingerprintListJSPath[] = "people_page/fingerprint_list.js";
-constexpr char kSetupFingerprintHTMLPath[] =
- "people_page/setup_fingerprint_dialog.html";
-constexpr char kSetupFingerprintJSPath[] =
- "people_page/setup_fingerprint_dialog.js";
-constexpr char kFingerprintBrowserProxyHTMLPath[] =
- "people_page/fingerprint_browser_proxy.html";
-constexpr char kFingerprintBrowserProxyJSPath[] =
- "people_page/fingerprint_browser_proxy.js";
-constexpr char kFingerprintProgressArcHTMLPath[] =
- "people_page/fingerprint_progress_arc.html";
-constexpr char kFingerprintProgressArcJSPath[] =
- "people_page/fingerprint_progress_arc.js";
-constexpr char kSettingsRouteHTMLPath[] = "route.html";
-constexpr char kSettingsRouteJSPath[] = "route.js";
-constexpr char kSettingsSharedCSSHTMLPath[] = "settings_shared_css.html";
-constexpr char kSettingsBooleanControlBehaviorHTMLPath[] =
- "controls/settings_boolean_control_behavior.html";
-constexpr char kSettingsBooleanControlBehaviorJSPath[] =
- "controls/settings_boolean_control_behavior.js";
-constexpr char kSettingsPrefControlBehaviorHTMLPath[] =
- "controls/pref_control_behavior.html";
-constexpr char kSettingsPrefControlBehaviorJSPath[] =
- "controls/pref_control_behavior.js";
-constexpr char kSettingsToggleButtonHTMLPath[] =
- "controls/settings_toggle_button.html";
-constexpr char kSettingsToggleButtonJSPath[] =
- "controls/settings_toggle_button.js";
-constexpr char kSettingsVarsCSSHTMLPath[] = "settings_vars_css.html";
-constexpr char kSettingsPrefsBehaviorHTMLPath[] = "prefs/prefs_behavior.html";
-constexpr char kSettingsPrefsBehaviorJSPath[] = "prefs/prefs_behavior.js";
-constexpr char kSettingsPrefsTypesHTMLPath[] = "prefs/prefs_types.html";
-constexpr char kSettingsPrefsTypesJSPath[] = "prefs/prefs_types.js";
-constexpr char kSettingsPrefsHTMLPath[] = "prefs/prefs.html";
-constexpr char kSettingsPrefsJSPath[] = "prefs/prefs.js";
-constexpr char kSettingsI18nHTMLPath[] = "i18n_setup.html";
-constexpr char kOptionsPolymerHTMLPath[] = "options_polymer.html";
-#endif
-
-} // namespace
-
-namespace options {
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// OptionsUIHTMLSource
-//
-////////////////////////////////////////////////////////////////////////////////
-
-class OptionsUIHTMLSource : public content::URLDataSource {
- public:
- // The constructor takes over ownership of |localized_strings|.
- explicit OptionsUIHTMLSource(base::DictionaryValue* localized_strings);
-
- // content::URLDataSource implementation.
- std::string GetSource() const override;
- void StartDataRequest(
- const std::string& path,
- const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
- const content::URLDataSource::GotDataCallback& callback) override;
- bool AllowCaching() const override;
- std::string GetMimeType(const std::string&) const override;
- bool ShouldDenyXFrameOptions() const override;
-
- private:
- ~OptionsUIHTMLSource() override;
- void CreateDataSourceMap();
-
- // Localized strings collection.
- std::unique_ptr<base::DictionaryValue> localized_strings_;
- std::map<std::string, int> path_to_idr_map_;
- ui::TemplateReplacements replacements_;
-
- DISALLOW_COPY_AND_ASSIGN(OptionsUIHTMLSource);
-};
-
-OptionsUIHTMLSource::OptionsUIHTMLSource(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
- localized_strings_.reset(localized_strings);
- CreateDataSourceMap();
-}
-
-std::string OptionsUIHTMLSource::GetSource() const {
- // TODO(stevenjb): Remove this file. Because everything in this directory
- // depends on this, we will remove the entire directory at once after
- // the old CrOS oobe/login UI dependencies are removed. crbug.com/748164.
- NOTREACHED();
- return "settings-frame";
-}
-
-void OptionsUIHTMLSource::StartDataRequest(
- const std::string& path,
- const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
- const content::URLDataSource::GotDataCallback& callback) {
- scoped_refptr<base::RefCountedMemory> response_bytes;
- const std::string& app_locale = g_browser_process->GetApplicationLocale();
- webui::SetLoadTimeDataDefaults(app_locale, localized_strings_.get());
- ui::TemplateReplacementsFromDictionaryValue(*localized_strings_,
- &replacements_);
-
- std::map<std::string, int>::iterator result;
- result = path_to_idr_map_.find(path);
-
- if (path == kLocalizedStringsFile) {
- // Return dynamically-generated strings from memory.
- std::string strings_js;
- webui::AppendJsonJS(localized_strings_.get(), &strings_js);
- response_bytes = base::RefCountedString::TakeString(&strings_js);
- } else if (path == kOptionsBundleJsFile) {
- // Return (and cache) the options javascript code.
- response_bytes = ui::ResourceBundle::GetSharedInstance().
- LoadDataResourceBytes(IDR_OPTIONS_BUNDLE_JS);
- } else if (result != path_to_idr_map_.end()) {
- response_bytes =
- ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
- result->second);
- } else {
- // Return (and cache) the main options html page as the default.
- response_bytes = ui::ResourceBundle::GetSharedInstance().
- LoadDataResourceBytes(IDR_OPTIONS_HTML);
- }
-
- // pre-process i18n strings
- if (GetMimeType(path) == "text/html") {
- std::string replaced = ui::ReplaceTemplateExpressions(
- base::StringPiece(response_bytes->front_as<char>(),
- response_bytes->size()),
- replacements_);
- response_bytes = base::RefCountedString::TakeString(&replaced);
- }
-
- callback.Run(response_bytes.get());
-}
-
-bool OptionsUIHTMLSource::AllowCaching() const {
- // Should not be cached to reflect dynamically-generated contents that depends
- // on the current locale.
- return false;
-}
-
-std::string OptionsUIHTMLSource::GetMimeType(const std::string& path) const {
- if (base::EndsWith(path, ".js", base::CompareCase::INSENSITIVE_ASCII))
- return "application/javascript";
-
- return "text/html";
-}
-
-bool OptionsUIHTMLSource::ShouldDenyXFrameOptions() const {
- return false;
-}
-
-OptionsUIHTMLSource::~OptionsUIHTMLSource() {}
-
-void OptionsUIHTMLSource::CreateDataSourceMap() {
-#if defined(OS_CHROMEOS)
- path_to_idr_map_[kIconsHTMLPath] = IDR_OPTIONS_ICONS_HTML;
-
- // These are part of the LockScreen UI.
- path_to_idr_map_[kPinKeyboardHTMLPath] = IDR_OPTIONS_PIN_KEYBOARD_HTML;
- path_to_idr_map_[kPinKeyboardJSPath] = IDR_OPTIONS_PIN_KEYBOARD_JS;
- path_to_idr_map_[kPasswordPromptDialogHTMLPath] =
- IDR_OPTIONS_PASSWORD_PROMPT_DIALOG_HTML;
- path_to_idr_map_[kPasswordPromptDialogJSPath] =
- IDR_OPTIONS_PASSWORD_PROMPT_DIALOG_JS;
- path_to_idr_map_[kLockScreenConstantsHTMLPath] =
- IDR_OPTIONS_LOCK_SCREEN_CONSTANTS_HTML;
- path_to_idr_map_[kLockScreenConstantsJSPath] =
- IDR_OPTIONS_LOCK_SCREEN_CONSTANTS_JS;
- path_to_idr_map_[kLockStateBehaviorHTMLPath] =
- IDR_OPTIONS_LOCK_STATE_BEHAVIOR_HTML;
- path_to_idr_map_[kLockStateBehaviorJSPath] =
- IDR_OPTIONS_LOCK_STATE_BEHAVIOR_JS;
- path_to_idr_map_[kLockScreenHTMLPath] = IDR_OPTIONS_LOCK_SCREEN_HTML;
- path_to_idr_map_[kLockScreenJSPath] = IDR_OPTIONS_LOCK_SCREEN_JS;
- path_to_idr_map_[kEasyUnlockBrowserProxyHTMLPath] =
- IDR_OPTIONS_EASY_UNLOCK_BROWSER_PROXY_HTML;
- path_to_idr_map_[kEasyUnlockBrowserProxyJSPath] =
- IDR_OPTIONS_EASY_UNLOCK_BROWSER_PROXY_JS;
- path_to_idr_map_[kEasyUnlockTurnOffDialogHTMLPath] =
- IDR_OPTIONS_EASY_UNLOCK_TURN_OFF_DIALOG_HTML;
- path_to_idr_map_[kEasyUnlockTurnOffDialogJSPath] =
- IDR_OPTIONS_EASY_UNLOCK_TURN_OFF_DIALOG_JS;
- path_to_idr_map_[kSetupPinHTMLPath] = IDR_OPTIONS_SETUP_PIN_DIALOG_HTML;
- path_to_idr_map_[kSetupPinJSPath] = IDR_OPTIONS_SETUP_PIN_DIALOG_JS;
- path_to_idr_map_[kFingerprintListHTMLPath] =
- IDR_OPTIONS_FINGERPRINT_LIST_HTML;
- path_to_idr_map_[kFingerprintListJSPath] = IDR_OPTIONS_FINGERPRINT_LIST_JS;
- path_to_idr_map_[kSetupFingerprintHTMLPath] =
- IDR_OPTIONS_SETUP_FINGERPRINT_DIALOG_HTML;
- path_to_idr_map_[kSetupFingerprintJSPath] =
- IDR_OPTIONS_SETUP_FINGERPRINT_DIALOG_JS;
-
- path_to_idr_map_[kSettingsRouteHTMLPath] = IDR_OPTIONS_ROUTE_HTML;
- path_to_idr_map_[kSettingsRouteJSPath] = IDR_OPTIONS_ROUTE_JS;
- path_to_idr_map_[kSettingsSharedCSSHTMLPath] = IDR_SETTINGS_SHARED_CSS_HTML;
- path_to_idr_map_[kSettingsBooleanControlBehaviorHTMLPath] =
- IDR_SETTINGS_BOOLEAN_CONTROL_BEHAVIOR_HTML;
- path_to_idr_map_[kSettingsBooleanControlBehaviorJSPath] =
- IDR_SETTINGS_BOOLEAN_CONTROL_BEHAVIOR_JS;
- path_to_idr_map_[kSettingsPrefControlBehaviorHTMLPath] =
- IDR_SETTINGS_PREF_CONTROL_BEHAVIOR_HTML;
- path_to_idr_map_[kSettingsPrefControlBehaviorJSPath] =
- IDR_SETTINGS_PREF_CONTROL_BEHAVIOR_JS;
- path_to_idr_map_[kSettingsToggleButtonHTMLPath] =
- IDR_SETTINGS_TOGGLE_BUTTON_HTML;
- path_to_idr_map_[kSettingsToggleButtonJSPath] = IDR_SETTINGS_TOGGLE_BUTTON_JS;
- path_to_idr_map_[kSettingsVarsCSSHTMLPath] = IDR_SETTINGS_VARS_CSS_HTML;
- path_to_idr_map_[kSettingsPrefsBehaviorHTMLPath] =
- IDR_SETTINGS_PREFS_BEHAVIOR_HTML;
- path_to_idr_map_[kSettingsPrefsBehaviorJSPath] =
- IDR_SETTINGS_PREFS_BEHAVIOR_JS;
- path_to_idr_map_[kSettingsPrefsTypesHTMLPath] = IDR_SETTINGS_PREFS_TYPES_HTML;
- path_to_idr_map_[kSettingsPrefsTypesJSPath] = IDR_SETTINGS_PREFS_TYPES_JS;
- path_to_idr_map_[kOptionsPolymerHTMLPath] = IDR_OPTIONS_POLYMER_ELEMENTS_HTML;
- path_to_idr_map_[kSettingsPrefsHTMLPath] = IDR_SETTINGS_PREFS_HTML;
- path_to_idr_map_[kSettingsPrefsJSPath] = IDR_SETTINGS_PREFS_JS;
- path_to_idr_map_[kSettingsI18nHTMLPath] = IDR_OPTIONS_I18N_SETUP_HTML;
- path_to_idr_map_[kFingerprintBrowserProxyHTMLPath] =
- IDR_OPTIONS_FINGERPRINT_BROWSER_PROXY_HTML;
- path_to_idr_map_[kFingerprintBrowserProxyJSPath] =
- IDR_OPTIONS_FINGERPRINT_BROWSER_PROXY_JS;
- path_to_idr_map_[kFingerprintProgressArcHTMLPath] =
- IDR_OPTIONS_FINGERPRINT_PROGRESS_ARC_HTML;
- path_to_idr_map_[kFingerprintProgressArcJSPath] =
- IDR_OPTIONS_FINGERPRINT_PROGRESS_ARC_JS;
-#endif
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// OptionsPageUIHandler
-//
-////////////////////////////////////////////////////////////////////////////////
-
-OptionsPageUIHandler::OptionsPageUIHandler() {
-}
-
-OptionsPageUIHandler::~OptionsPageUIHandler() {
-}
-
-bool OptionsPageUIHandler::IsEnabled() {
- return true;
-}
-
-// static
-void OptionsPageUIHandler::RegisterStrings(
- base::DictionaryValue* localized_strings,
- const OptionsStringResource* resources,
- size_t length) {
- for (size_t i = 0; i < length; ++i) {
- base::string16 value;
- if (resources[i].substitution_id == 0) {
- value = l10n_util::GetStringUTF16(resources[i].id);
- } else {
- value = l10n_util::GetStringFUTF16(
- resources[i].id,
- l10n_util::GetStringUTF16(resources[i].substitution_id));
- }
- localized_strings->SetString(resources[i].name, value);
- }
-}
-
-void OptionsPageUIHandler::RegisterTitle(
- base::DictionaryValue* localized_strings,
- const std::string& variable_name,
- int title_id) {
- localized_strings->SetString(variable_name,
- l10n_util::GetStringUTF16(title_id));
- localized_strings->SetString(variable_name + "TabTitle",
- l10n_util::GetStringFUTF16(IDS_OPTIONS_TAB_TITLE,
- l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE),
- l10n_util::GetStringUTF16(title_id)));
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// OptionsUI
-//
-////////////////////////////////////////////////////////////////////////////////
-
-OptionsUI::OptionsUI(content::WebUI* web_ui)
- : WebUIController(web_ui),
- WebContentsObserver(web_ui->GetWebContents()),
- initialized_handlers_(false) {
- base::DictionaryValue* localized_strings = new base::DictionaryValue();
- CoreOptionsHandler* core_handler;
-#if defined(OS_CHROMEOS)
- core_handler = new chromeos::options::CoreChromeOSOptionsHandler();
-#else
- core_handler = new CoreOptionsHandler();
-#endif
- core_handler->set_handlers_host(this);
- AddOptionsPageUIHandler(localized_strings, core_handler);
-
- AddOptionsPageUIHandler(localized_strings, new AutofillOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new AutomaticSettingsResetHandler());
-
- BrowserOptionsHandler* browser_options_handler = new BrowserOptionsHandler();
- AddOptionsPageUIHandler(localized_strings, browser_options_handler);
-
- AddOptionsPageUIHandler(localized_strings, new ClearBrowserDataHandler());
- AddOptionsPageUIHandler(localized_strings, new ContentSettingsHandler());
- AddOptionsPageUIHandler(localized_strings, new CookiesViewHandler());
- AddOptionsPageUIHandler(localized_strings, new CreateProfileHandler());
- AddOptionsPageUIHandler(localized_strings, new EasyUnlockHandler());
- AddOptionsPageUIHandler(localized_strings, new FontSettingsHandler());
-#if BUILDFLAG(ENABLE_GOOGLE_NOW)
- AddOptionsPageUIHandler(localized_strings, new GeolocationOptionsHandler());
-#endif
- AddOptionsPageUIHandler(localized_strings, new options::HelpOverlayHandler());
- AddOptionsPageUIHandler(localized_strings, new HomePageOverlayHandler());
- AddOptionsPageUIHandler(localized_strings,
- new MediaDevicesSelectionHandler());
-#if defined(OS_CHROMEOS)
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::CrosLanguageOptionsHandler());
-#else
- AddOptionsPageUIHandler(localized_strings, new LanguageOptionsHandler());
-#endif
- AddOptionsPageUIHandler(localized_strings,
- new LanguageDictionaryOverlayHandler());
- AddOptionsPageUIHandler(localized_strings, new ManageProfileHandler());
- AddOptionsPageUIHandler(localized_strings, new PasswordManagerHandler());
- AddOptionsPageUIHandler(localized_strings, new ResetProfileSettingsHandler());
- AddOptionsPageUIHandler(localized_strings, new SearchEngineManagerHandler());
- AddOptionsPageUIHandler(localized_strings, new ImportDataHandler());
- AddOptionsPageUIHandler(localized_strings, new StartupPagesHandler());
-#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- AddOptionsPageUIHandler(localized_strings,
- new SupervisedUserCreateConfirmHandler());
- AddOptionsPageUIHandler(localized_strings, new SupervisedUserImportHandler());
- AddOptionsPageUIHandler(localized_strings,
- new SupervisedUserLearnMoreHandler());
-#endif
- AddOptionsPageUIHandler(localized_strings, new SyncSetupHandler());
-#if defined(OS_CHROMEOS)
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::AccountsOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::BluetoothOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::DateTimeOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::DisplayOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::DisplayOverscanHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::PowerHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::InternetOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::KeyboardHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::OptionsStylusHandler());
-
- chromeos::options::PointerHandler* pointer_handler =
- new chromeos::options::PointerHandler();
- AddOptionsPageUIHandler(localized_strings, pointer_handler);
-
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::ProxyHandler());
- AddOptionsPageUIHandler(
- localized_strings,
- new chromeos::options::ChangePictureOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::StatsOptionsHandler());
- AddOptionsPageUIHandler(localized_strings,
- new chromeos::options::StorageManagerHandler());
-#endif
-#if defined(USE_NSS_CERTS)
- AddOptionsPageUIHandler(localized_strings,
- new CertificateManagerHandler(false));
-#endif
- AddOptionsPageUIHandler(localized_strings, new HandlerOptionsHandler());
-
- web_ui->AddMessageHandler(base::MakeUnique<MetricsHandler>());
-
- // Enable extension API calls in the WebUI.
- extensions::TabHelper::CreateForWebContents(web_ui->GetWebContents());
-
- // |localized_strings| ownership is taken over by this constructor.
- OptionsUIHTMLSource* html_source =
- new OptionsUIHTMLSource(localized_strings);
-
- // Set up the chrome://settings-frame/ source.
- Profile* profile = Profile::FromWebUI(web_ui);
- content::URLDataSource::Add(profile, html_source);
-
- // Set up the chrome://theme/ source.
- ThemeSource* theme = new ThemeSource(profile);
- content::URLDataSource::Add(profile, theme);
-
-#if defined(OS_CHROMEOS)
- // Set up the chrome://userimage/ source.
- chromeos::UserImageSource* user_image_source =
- new chromeos::UserImageSource();
- content::URLDataSource::Add(profile, user_image_source);
-
- pointer_device_observer_.reset(
- new chromeos::system::PointerDeviceObserver());
- pointer_device_observer_->AddObserver(browser_options_handler);
- pointer_device_observer_->AddObserver(pointer_handler);
-#endif
-}
-
-OptionsUI::~OptionsUI() {
- // Uninitialize all registered handlers. Deleted by WebUIImpl.
- for (size_t i = 0; i < handlers_.size(); ++i)
- handlers_[i]->Uninitialize();
-}
-
-std::unique_ptr<OptionsUI::OnFinishedLoadingCallbackList::Subscription>
-OptionsUI::RegisterOnFinishedLoadingCallback(const base::Closure& callback) {
- return on_finished_loading_callbacks_.Add(callback);
-}
-
-// static
-void OptionsUI::ProcessAutocompleteSuggestions(
- const AutocompleteResult& result,
- base::ListValue* const suggestions) {
- for (size_t i = 0; i < result.size(); ++i) {
- const AutocompleteMatch& match = result.match_at(i);
- AutocompleteMatchType::Type type = match.type;
- if (type != AutocompleteMatchType::HISTORY_URL &&
- type != AutocompleteMatchType::HISTORY_TITLE &&
- type != AutocompleteMatchType::HISTORY_BODY &&
- type != AutocompleteMatchType::HISTORY_KEYWORD &&
- type != AutocompleteMatchType::NAVSUGGEST &&
- type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED) {
- continue;
- }
- std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
- entry->SetString("title", match.description);
- entry->SetString("displayURL", match.contents);
- entry->SetString("url", match.destination_url.spec());
- suggestions->Append(std::move(entry));
- }
-}
-
-void OptionsUI::ReadyToCommitNavigation(
- content::NavigationHandle* navigation_handle) {
- if (navigation_handle->IsSameDocument())
- return;
-
- load_start_time_ = base::Time::Now();
- if (navigation_handle->GetRenderFrameHost()->GetRenderViewHost() ==
- web_ui()->GetWebContents()->GetRenderViewHost() &&
- navigation_handle->GetURL().host_piece() == "settings-frame") {
- for (size_t i = 0; i < handlers_.size(); ++i)
- handlers_[i]->PageLoadStarted();
- }
-}
-
-void OptionsUI::DocumentLoadedInFrame(
- content::RenderFrameHost *render_frame_host) {
- UMA_HISTOGRAM_TIMES("Settings.LoadDocumentTime",
- base::Time::Now() - load_start_time_);
-}
-
-void OptionsUI::DocumentOnLoadCompletedInMainFrame() {
- UMA_HISTOGRAM_TIMES("Settings.LoadCompletedTime",
- base::Time::Now() - load_start_time_);
-}
-
-void OptionsUI::InitializeHandlers() {
- Profile* profile = Profile::FromWebUI(web_ui());
- DCHECK(!profile->IsOffTheRecord() || profile->IsGuestSession());
-
- // A new web page DOM has been brought up in an existing renderer, causing
- // this method to be called twice. If that happens, ignore the second call.
- if (!initialized_handlers_) {
- for (size_t i = 0; i < handlers_.size(); ++i)
- handlers_[i]->InitializeHandler();
- initialized_handlers_ = true;
-
-#if defined(OS_CHROMEOS)
- pointer_device_observer_->Init();
-#endif
- }
-
-#if defined(OS_CHROMEOS)
- pointer_device_observer_->CheckDevices();
-#endif
-
- // Always initialize the page as when handlers are left over we still need to
- // do various things like show/hide sections and send data to the Javascript.
- for (size_t i = 0; i < handlers_.size(); ++i)
- handlers_[i]->InitializePage();
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "BrowserOptions.notifyInitializationComplete");
-}
-
-void OptionsUI::OnFinishedLoading() {
- on_finished_loading_callbacks_.Notify();
-}
-
-void OptionsUI::AddOptionsPageUIHandler(
- base::DictionaryValue* localized_strings,
- OptionsPageUIHandler* handler_raw) {
- std::unique_ptr<OptionsPageUIHandler> handler(handler_raw);
- DCHECK(handler.get());
- // Add only if handler's service is enabled.
- if (handler->IsEnabled()) {
- // Add handler to the list and also pass the ownership.
- web_ui()->AddMessageHandler(std::move(handler));
- handler_raw->GetLocalizedValues(localized_strings);
- handlers_.push_back(handler_raw);
- }
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/options_ui.h b/chromium/chrome/browser/ui/webui/options/options_ui.h
deleted file mode 100644
index 9a597f0157f..00000000000
--- a/chromium/chrome/browser/ui/webui/options/options_ui.h
+++ /dev/null
@@ -1,164 +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_OPTIONS_OPTIONS_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_OPTIONS_UI_H_
-
-#include <stddef.h>
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/callback_list.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/time/time.h"
-#include "build/build_config.h"
-#include "content/public/browser/notification_registrar.h"
-#include "content/public/browser/web_contents_observer.h"
-#include "content/public/browser/web_ui_controller.h"
-#include "content/public/browser/web_ui_message_handler.h"
-
-class AutocompleteResult;
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-#if defined(OS_CHROMEOS)
-namespace chromeos {
-namespace system {
-class PointerDeviceObserver;
-} // namespace system
-} // namespace chromeos
-#endif
-
-namespace options {
-
-// The base class handler of Javascript messages of options pages.
-class OptionsPageUIHandler : public content::WebUIMessageHandler {
- public:
- OptionsPageUIHandler();
- ~OptionsPageUIHandler() override;
-
- // Is this handler enabled?
- virtual bool IsEnabled();
-
- // Collects localized strings for options page.
- virtual void GetLocalizedValues(base::DictionaryValue* localized_strings) = 0;
-
- virtual void PageLoadStarted() {}
-
- // Will be called only once in the life time of the handler. Generally used to
- // add observers, initializes preferences, or start asynchronous calls from
- // various services.
- virtual void InitializeHandler() {}
-
- // Initialize the page. Called once the DOM is available for manipulation.
- // This will be called when a RenderView is re-used (when navigated to with
- // back/forward or session restored in some cases) or when created.
- virtual void InitializePage() {}
-
- // Uninitializes the page. Called just before the object is destructed.
- virtual void Uninitialize() {}
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override {}
-
- protected:
- struct OptionsStringResource {
- // The name of the resource in templateData.
- const char* name;
- // The .grd ID for the resource (IDS_*).
- int id;
- // The .grd ID of the string to replace $1 in |id|'s string. If zero or
- // omitted (default initialized), no substitution is attempted.
- int substitution_id;
- };
-
- // A helper to simplify string registration in WebUI for strings which do not
- // change at runtime and optionally contain a single substitution.
- static void RegisterStrings(base::DictionaryValue* localized_strings,
- const OptionsStringResource* resources,
- size_t length);
-
- // Registers string resources for a page's header and tab title.
- static void RegisterTitle(base::DictionaryValue* localized_strings,
- const std::string& variable_name,
- int title_id);
-
- content::NotificationRegistrar registrar_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(OptionsPageUIHandler);
-};
-
-// An interface for common operations that a host of OptionsPageUIHandlers
-// should provide.
-class OptionsPageUIHandlerHost {
- public:
- virtual void InitializeHandlers() = 0;
- virtual void OnFinishedLoading() {}
-
- protected:
- virtual ~OptionsPageUIHandlerHost() {}
-};
-
-// The WebUI for chrome:settings-frame.
-class OptionsUI : public content::WebUIController,
- public content::WebContentsObserver,
- public OptionsPageUIHandlerHost {
- public:
- typedef base::CallbackList<void()> OnFinishedLoadingCallbackList;
-
- explicit OptionsUI(content::WebUI* web_ui);
- ~OptionsUI() override;
-
- // Registers a callback to be called once the settings frame has finished
- // loading on the HTML/JS side.
- std::unique_ptr<OnFinishedLoadingCallbackList::Subscription>
- RegisterOnFinishedLoadingCallback(const base::Closure& callback);
-
- // Takes the suggestions from |result| and adds them to |suggestions| so that
- // they can be passed to a JavaScript function.
- static void ProcessAutocompleteSuggestions(
- const AutocompleteResult& result,
- base::ListValue* const suggestions);
-
- // Overridden from content::WebContentsObserver:
- void ReadyToCommitNavigation(
- content::NavigationHandle* navigation_handle) override;
- void DocumentLoadedInFrame(
- content::RenderFrameHost *render_frame_host) override;
- void DocumentOnLoadCompletedInMainFrame() override;
-
- // Overridden from OptionsPageUIHandlerHost:
- void InitializeHandlers() override;
- void OnFinishedLoading() override;
-
- private:
- // Adds OptionsPageUiHandler to the handlers list if handler is enabled.
- void AddOptionsPageUIHandler(base::DictionaryValue* localized_strings,
- OptionsPageUIHandler* handler);
-
- bool initialized_handlers_;
-
- std::vector<OptionsPageUIHandler*> handlers_;
- OnFinishedLoadingCallbackList on_finished_loading_callbacks_;
-
-#if defined(OS_CHROMEOS)
- std::unique_ptr<chromeos::system::PointerDeviceObserver>
- pointer_device_observer_;
-#endif
-
- base::Time load_start_time_;
-
- DISALLOW_COPY_AND_ASSIGN(OptionsUI);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_OPTIONS_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/options/password_manager_handler.cc b/chromium/chrome/browser/ui/webui/options/password_manager_handler.cc
deleted file mode 100644
index 85035294649..00000000000
--- a/chromium/chrome/browser/ui/webui/options/password_manager_handler.cc
+++ /dev/null
@@ -1,398 +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 "chrome/browser/ui/webui/options/password_manager_handler.h"
-
-#include <memory>
-#include <tuple>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/feature_list.h"
-#include "base/files/file_path.h"
-#include "base/macros.h"
-#include "base/metrics/field_trial.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_split.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/password_manager/password_store_factory.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/chrome_select_file_policy.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/autofill/core/common/password_form.h"
-#include "components/browser_sync/profile_sync_service.h"
-#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h"
-#include "components/password_manager/core/browser/export/password_exporter.h"
-#include "components/password_manager/core/browser/password_bubble_experiment.h"
-#include "components/password_manager/core/browser/password_manager_constants.h"
-#include "components/password_manager/core/browser/password_store.h"
-#include "components/password_manager/core/browser/password_ui_utils.h"
-#include "components/password_manager/core/common/experiments.h"
-#include "components/password_manager/core/common/password_manager_features.h"
-#include "components/prefs/pref_service.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/url_formatter/url_formatter.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/notification_source.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/common/origin_util.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "url/gurl.h"
-
-namespace options {
-
-namespace {
-// The following constants should be synchronized with the constants in
-// chrome/browser/resources/options/password_manager_list.js.
-const char kUrlField[] = "url";
-const char kShownOriginField[] = "shownOrigin";
-const char kIsAndroidUriField[] = "isAndroidUri";
-const char kIsClickable[] = "isClickable";
-const char kIsSecureField[] = "isSecure";
-const char kUsernameField[] = "username";
-const char kPasswordField[] = "password";
-const char kFederationField[] = "federation";
-
-// Copies from |form| to |entry| the origin, shown origin, whether the origin is
-// Android URI, and whether the origin is secure.
-void CopyOriginInfoOfPasswordForm(const autofill::PasswordForm& form,
- base::DictionaryValue* entry) {
- std::string shown_origin;
- GURL link_url;
- std::tie(shown_origin, link_url) =
- password_manager::GetShownOriginAndLinkUrl(form);
- entry->SetString(kShownOriginField, shown_origin);
- DCHECK(link_url.is_valid());
- entry->SetString(kUrlField,
- url_formatter::FormatUrl(
- link_url, url_formatter::kFormatUrlOmitNothing,
- net::UnescapeRule::SPACES, nullptr, nullptr, nullptr));
- entry->SetBoolean(
- kIsAndroidUriField,
- password_manager::IsValidAndroidFacetURI(form.signon_realm));
- entry->SetBoolean(kIsClickable, true);
- entry->SetBoolean(kIsSecureField, content::IsOriginSecure(link_url));
-}
-
-} // namespace
-
-PasswordManagerHandler::PasswordManagerHandler() {
- password_manager_presenter_.reset(new PasswordManagerPresenter(this));
-}
-
-PasswordManagerHandler::PasswordManagerHandler(
- std::unique_ptr<PasswordManagerPresenter> presenter)
- : password_manager_presenter_(std::move(presenter)) {}
-
-PasswordManagerHandler::~PasswordManagerHandler() {}
-
-Profile* PasswordManagerHandler::GetProfile() {
- return Profile::FromWebUI(web_ui());
-}
-
-#if !defined(OS_ANDROID)
-gfx::NativeWindow PasswordManagerHandler::GetNativeWindow() const {
- return web_ui()->GetWebContents()->GetTopLevelNativeWindow();
-}
-#endif
-
-void PasswordManagerHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static const OptionsStringResource resources[] = {
- {"androidUriSuffix", IDS_PASSWORDS_ANDROID_URI_SUFFIX},
- {"autoSigninTitle", IDS_PASSWORDS_AUTO_SIGNIN_TITLE},
- {"autoSigninDescription", IDS_PASSWORDS_AUTO_SIGNIN_DESCRIPTION},
- {"savedPasswordsTitle", IDS_PASSWORD_MANAGER_SHOW_PASSWORDS_TAB_TITLE},
- {"passwordExceptionsTitle", IDS_PASSWORD_MANAGER_EXCEPTIONS_TAB_TITLE},
- {"passwordSearchPlaceholder", IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS},
- {"passwordShowButton", IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON},
- {"passwordHideButton", IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON},
- {"passwordsNoPasswordsDescription",
- IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION},
- {"passwordsNoExceptionsDescription",
- IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION},
- {"passwordManagerImportPasswordButtonText",
- IDS_PASSWORD_MANAGER_IMPORT_BUTTON},
- {"passwordManagerExportPasswordButtonText",
- IDS_PASSWORD_MANAGER_EXPORT_BUTTON},
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-
- RegisterTitle(localized_strings, "passwordsPage",
- IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);
-
- localized_strings->SetString("passwordManagerLearnMoreURL",
- chrome::kPasswordManagerLearnMoreURL);
- localized_strings->SetString(
- "passwordsManagePasswordsLink",
- password_manager::kPasswordManagerAccountDashboardURL);
-
- std::string management_hostname =
- GURL(password_manager::kPasswordManagerAccountDashboardURL).host();
- base::string16 link_text = base::UTF8ToUTF16(management_hostname);
- size_t offset;
- base::string16 full_text = l10n_util::GetStringFUTF16(
- IDS_MANAGE_PASSWORDS_REMOTE_TEXT, link_text, &offset);
-
- localized_strings->SetString("passwordsManagePasswordsBeforeLinkText",
- full_text.substr(0, offset));
- localized_strings->SetString("passwordsManagePasswordsLinkText",
- full_text.substr(offset, link_text.size()));
- localized_strings->SetString("passwordsManagePasswordsAfterLinkText",
- full_text.substr(offset + link_text.size()));
-
- bool disable_show_passwords = false;
-
-#if defined(OS_WIN) && defined(USE_ASH)
- // We disable the ability to show passwords when running in Windows Metro
- // interface. This is because we cannot pop native Win32 dialogs from the
- // Metro process.
- // TODO(wfh): Revisit this if Metro usage grows.
- if (chrome::IsNativeWindowInAsh(GetNativeWindow()))
- disable_show_passwords = true;
-#endif
-
- localized_strings->SetBoolean("disableShowPasswords", disable_show_passwords);
-}
-
-void PasswordManagerHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "updatePasswordLists",
- base::Bind(&PasswordManagerHandler::HandleUpdatePasswordLists,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "removeSavedPassword",
- base::Bind(&PasswordManagerHandler::HandleRemoveSavedPassword,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "removePasswordException",
- base::Bind(&PasswordManagerHandler::HandleRemovePasswordException,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "requestShowPassword",
- base::Bind(&PasswordManagerHandler::HandleRequestShowPassword,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "importPassword",
- base::Bind(&PasswordManagerHandler::HandlePasswordImport,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "exportPassword",
- base::Bind(&PasswordManagerHandler::HandlePasswordExport,
- base::Unretained(this)));
-}
-
-void PasswordManagerHandler::InitializeHandler() {
- password_manager_presenter_->Initialize();
-}
-
-void PasswordManagerHandler::InitializePage() {
- if (base::FeatureList::IsEnabled(
- password_manager::features::kPasswordImportExport)) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "PasswordManager.showImportExportButton");
- }
-}
-
-void PasswordManagerHandler::HandleRemoveSavedPassword(
- const base::ListValue* args) {
- std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));
- int index;
- if (base::StringToInt(string_value, &index) && index >= 0) {
- password_manager_presenter_->RemoveSavedPassword(
- static_cast<size_t>(index));
- }
-}
-
-void PasswordManagerHandler::HandleRemovePasswordException(
- const base::ListValue* args) {
- std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));
- int index;
- if (base::StringToInt(string_value, &index) && index >= 0) {
- password_manager_presenter_->RemovePasswordException(
- static_cast<size_t>(index));
- }
-}
-
-void PasswordManagerHandler::HandleRequestShowPassword(
- const base::ListValue* args) {
- int index;
- if (!ExtractIntegerValue(args, &index))
- NOTREACHED();
-
- password_manager_presenter_->RequestShowPassword(static_cast<size_t>(index));
-}
-
-void PasswordManagerHandler::ShowPassword(
- size_t index,
- const std::string& origin_url,
- const std::string& username,
- const base::string16& password_value) {
- // Call back the front end to reveal the password.
- web_ui()->CallJavascriptFunctionUnsafe("PasswordManager.showPassword",
- base::Value(static_cast<int>(index)),
- base::Value(password_value));
-}
-
-void PasswordManagerHandler::HandleUpdatePasswordLists(
- const base::ListValue* args) {
- password_manager_presenter_->UpdatePasswordLists();
-}
-
-void PasswordManagerHandler::SetPasswordList(
- const std::vector<std::unique_ptr<autofill::PasswordForm>>& password_list) {
- base::ListValue entries;
- base::string16 placeholder(base::ASCIIToUTF16(" "));
- for (const auto& saved_password : password_list) {
- std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue);
- CopyOriginInfoOfPasswordForm(*saved_password, entry.get());
-
- entry->SetString(kUsernameField, saved_password->username_value);
- // Use a placeholder value with the same length as the password.
- entry->SetString(
- kPasswordField,
- base::string16(saved_password->password_value.length(), ' '));
- if (!saved_password->federation_origin.unique()) {
- entry->SetString(
- kFederationField,
- l10n_util::GetStringFUTF16(
- IDS_PASSWORDS_VIA_FEDERATION,
- base::UTF8ToUTF16(saved_password->federation_origin.host())));
- }
-
- entries.Append(std::move(entry));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "PasswordManager.setSavedPasswordsList", entries);
-}
-
-void PasswordManagerHandler::SetPasswordExceptionList(
- const std::vector<std::unique_ptr<autofill::PasswordForm>>&
- password_exception_list) {
- base::ListValue entries;
- for (const auto& exception : password_exception_list) {
- std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue);
- CopyOriginInfoOfPasswordForm(*exception, entry.get());
- entries.Append(std::move(entry));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "PasswordManager.setPasswordExceptionsList", entries);
-}
-
-void PasswordManagerHandler::FileSelected(const base::FilePath& path,
- int index,
- void* params) {
- switch (static_cast<FileSelectorCaller>(reinterpret_cast<intptr_t>(params))) {
- case IMPORT_FILE_SELECTED:
- ImportPasswordFileSelected(path);
- break;
- case EXPORT_FILE_SELECTED:
- ExportPasswordFileSelected(path);
- break;
- }
-}
-
-void PasswordManagerHandler::HandlePasswordImport(const base::ListValue* args) {
-#if !defined(OS_ANDROID) // This is never called on Android.
- ui::SelectFileDialog::FileTypeInfo file_type_info;
-
- file_type_info.extensions =
- password_manager::PasswordImporter::GetSupportedFileExtensions();
- DCHECK(!file_type_info.extensions.empty() &&
- !file_type_info.extensions[0].empty());
- file_type_info.include_all_files = true;
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- select_file_dialog_->SelectFile(
- ui::SelectFileDialog::SELECT_OPEN_FILE,
- l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_IMPORT_DIALOG_TITLE),
- base::FilePath(), &file_type_info, 1, file_type_info.extensions[0][0],
- web_ui()->GetWebContents()->GetTopLevelNativeWindow(),
- reinterpret_cast<void*>(IMPORT_FILE_SELECTED));
-#endif
-}
-
-void PasswordManagerHandler::ImportPasswordFileSelected(
- const base::FilePath& path) {
- scoped_refptr<ImportPasswordResultConsumer> form_consumer(
- new ImportPasswordResultConsumer(GetProfile()));
-
- password_manager::PasswordImporter::Import(
- path, base::Bind(&ImportPasswordResultConsumer::ConsumePassword,
- form_consumer));
-}
-
-PasswordManagerHandler::ImportPasswordResultConsumer::
- ImportPasswordResultConsumer(Profile* profile)
- : profile_(profile) {}
-
-void PasswordManagerHandler::ImportPasswordResultConsumer::ConsumePassword(
- password_manager::PasswordImporter::Result result,
- const std::vector<autofill::PasswordForm>& forms) {
- UMA_HISTOGRAM_ENUMERATION(
- "PasswordManager.ImportPasswordFromCSVResult", result,
- password_manager::PasswordImporter::NUM_IMPORT_RESULTS);
- if (result != password_manager::PasswordImporter::SUCCESS)
- return;
-
- UMA_HISTOGRAM_COUNTS("PasswordManager.ImportedPasswordsPerUserInCSV",
- forms.size());
-
- scoped_refptr<password_manager::PasswordStore> store(
- PasswordStoreFactory::GetForProfile(profile_,
- ServiceAccessType::EXPLICIT_ACCESS));
- if (store) {
- for (const autofill::PasswordForm& form : forms) {
- store->AddLogin(form);
- }
- }
- UMA_HISTOGRAM_BOOLEAN("PasswordManager.StorePasswordImportedFromCSVResult",
- static_cast<bool>(store));
-}
-
-void PasswordManagerHandler::HandlePasswordExport(const base::ListValue* args) {
-#if !defined(OS_ANDROID) // This is never called on Android.
- if (!password_manager_presenter_->IsUserAuthenticated())
- return;
-
- ui::SelectFileDialog::FileTypeInfo file_type_info;
- file_type_info.extensions =
- password_manager::PasswordExporter::GetSupportedFileExtensions();
- DCHECK(!file_type_info.extensions.empty() &&
- !file_type_info.extensions[0].empty());
- file_type_info.include_all_files = true;
- select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
- select_file_dialog_->SelectFile(
- ui::SelectFileDialog::SELECT_SAVEAS_FILE,
- l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_EXPORT_DIALOG_TITLE),
- base::FilePath(), &file_type_info, 1, file_type_info.extensions[0][0],
- GetNativeWindow(), reinterpret_cast<void*>(EXPORT_FILE_SELECTED));
-#endif
-}
-
-void PasswordManagerHandler::ExportPasswordFileSelected(
- const base::FilePath& path) {
- std::vector<std::unique_ptr<autofill::PasswordForm>> password_list =
- password_manager_presenter_->GetAllPasswords();
- UMA_HISTOGRAM_COUNTS("PasswordManager.ExportedPasswordsPerUserInCSV",
- password_list.size());
- password_manager::PasswordExporter::Export(path, password_list);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/password_manager_handler.h b/chromium/chrome/browser/ui/webui/options/password_manager_handler.h
deleted file mode 100644
index 5442df96ad0..00000000000
--- a/chromium/chrome/browser/ui/webui/options/password_manager_handler.h
+++ /dev/null
@@ -1,138 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_PASSWORD_MANAGER_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_PASSWORD_MANAGER_HANDLER_H_
-
-#include <stddef.h>
-
-#include <string>
-#include <vector>
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-#include "chrome/browser/ui/passwords/password_manager_presenter.h"
-#include "chrome/browser/ui/passwords/password_ui_view.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/password_manager/core/browser/import/password_importer.h"
-#include "components/prefs/pref_member.h"
-#include "ui/shell_dialogs/select_file_dialog.h"
-
-namespace options {
-
-// The WebUI based PasswordUIView. Displays passwords in the web ui.
-class PasswordManagerHandler : public OptionsPageUIHandler,
- public PasswordUIView,
- public ui::SelectFileDialog::Listener {
- public:
- // Enumeration of different callers of SelectFile.
- enum FileSelectorCaller {
- IMPORT_FILE_SELECTED,
- EXPORT_FILE_SELECTED,
- };
-
- PasswordManagerHandler();
- ~PasswordManagerHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // ui::SelectFileDialog::Listener implementation.
- // |params| is of type FileSelectorCaller which indicates direction of IO.
- void FileSelected(const base::FilePath& path,
- int index,
- void* params) override;
-
- // PasswordUIView implementation.
- Profile* GetProfile() override;
- void ShowPassword(
- size_t index,
- const std::string& origin_url,
- const std::string& username,
- const base::string16& password_value) override;
- void SetPasswordList(
- const std::vector<std::unique_ptr<autofill::PasswordForm>>& password_list)
- override;
- void SetPasswordExceptionList(
- const std::vector<std::unique_ptr<autofill::PasswordForm>>&
- password_exception_list) override;
-#if !defined(OS_ANDROID)
- gfx::NativeWindow GetNativeWindow() const override;
-#endif
-
- protected:
- // This constructor is used for testing only.
- explicit PasswordManagerHandler(
- std::unique_ptr<PasswordManagerPresenter> presenter);
-
- private:
- // Clears and then populates the list of passwords and password exceptions.
- // Called when the JS PasswordManager object is initialized.
- void HandleUpdatePasswordLists(const base::ListValue* args);
-
- // Removes a saved password entry.
- // |value| the entry index to be removed.
- void HandleRemoveSavedPassword(const base::ListValue* args);
-
- // Removes a saved password exception.
- // |value| the entry index to be removed.
- void HandleRemovePasswordException(const base::ListValue* args);
-
- // Requests the plain text password for an entry to be revealed.
- // |index| The index of the entry.
- void HandleRequestShowPassword(const base::ListValue* args);
-
- // Import from CSV/JSON file. The steps are:
- // 1. user click import button -> HandlePasswordImport() ->
- // start file selector
- // 2. user selects file -> ImportPasswordFileSeleted() -> read to memory
- // 3. read completes -> ImportPasswordFileRead() -> store to PasswordStore
- void HandlePasswordImport(const base::ListValue* args);
- void ImportPasswordFileSelected(const base::FilePath& path);
- void ImportPasswordFileRead(password_manager::PasswordImporter::Result result,
- const std::vector<autofill::PasswordForm>& forms);
-
- // Export to CSV/JSON file. The steps are:
- // 1. user click export button -> HandlePasswordExport() ->
- // check OS password if necessary -> start file selector
- // 2. user selects file -> ExportPasswordFileSeleted() ->
- // write to memory buffer -> start write operation
- void HandlePasswordExport(const base::ListValue* args);
- void ExportPasswordFileSelected(const base::FilePath& path);
-
- // A short class to persist imported password forms to password store.
- class ImportPasswordResultConsumer
- : public base::RefCountedThreadSafe<ImportPasswordResultConsumer> {
- public:
- explicit ImportPasswordResultConsumer(Profile* profile);
-
- void ConsumePassword(password_manager::PasswordImporter::Result result,
- const std::vector<autofill::PasswordForm>& forms);
-
- private:
- friend class base::RefCountedThreadSafe<ImportPasswordResultConsumer>;
-
- ~ImportPasswordResultConsumer() {}
-
- Profile* profile_;
- };
-
- // User pref for storing accept languages.
- std::string languages_;
-
- std::unique_ptr<PasswordManagerPresenter> password_manager_presenter_;
-
- // File picker to import/export file path.
- scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
-
- DISALLOW_COPY_AND_ASSIGN(PasswordManagerHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_PASSWORD_MANAGER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.cc b/chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.cc
deleted file mode 100644
index 542498b7447..00000000000
--- a/chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.cc
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.h"
-
-#include <algorithm>
-#include <memory>
-
-namespace options {
-
-namespace {
-
-int CompareMediaException(const MediaException& i, const MediaException& j) {
- return i.pattern.Compare(j.pattern);
-}
-
-bool MediaExceptionSortFunc(const MediaException& i, const MediaException& j) {
- return CompareMediaException(i, j) < 0;
-}
-
-} // namespace
-
-MediaException::MediaException(const ContentSettingsPattern& in_pattern,
- ContentSetting in_setting)
- : pattern(in_pattern),
- setting(in_setting) {
-}
-
-MediaException::~MediaException() {
-}
-
-bool MediaException::operator==(const MediaException& other) const {
- return pattern == other.pattern && setting == other.setting;
-}
-
-// static
-ContentSetting PepperFlashContentSettingsUtils::FlashPermissionToContentSetting(
- PP_Flash_BrowserOperations_Permission permission) {
- switch (permission) {
- case PP_FLASH_BROWSEROPERATIONS_PERMISSION_DEFAULT:
- return CONTENT_SETTING_DEFAULT;
- case PP_FLASH_BROWSEROPERATIONS_PERMISSION_ALLOW:
- return CONTENT_SETTING_ALLOW;
- case PP_FLASH_BROWSEROPERATIONS_PERMISSION_BLOCK:
- return CONTENT_SETTING_BLOCK;
- case PP_FLASH_BROWSEROPERATIONS_PERMISSION_ASK:
- return CONTENT_SETTING_ASK;
- // No default so the compiler will warn us if a new type is added.
- }
- return CONTENT_SETTING_DEFAULT;
-}
-
-// static
-void PepperFlashContentSettingsUtils::FlashSiteSettingsToMediaExceptions(
- const ppapi::FlashSiteSettings& site_settings,
- MediaExceptions* media_exceptions) {
- media_exceptions->clear();
-
- std::unique_ptr<ContentSettingsPattern::BuilderInterface> builder =
- ContentSettingsPattern::CreateBuilder();
- builder->WithSchemeWildcard()->WithPortWildcard();
- for (ppapi::FlashSiteSettings::const_iterator iter = site_settings.begin();
- iter != site_settings.end(); ++iter) {
- builder->WithHost(iter->site);
-
- ContentSettingsPattern pattern = builder->Build();
- if (!pattern.IsValid())
- continue;
-
- ContentSetting setting = FlashPermissionToContentSetting(iter->permission);
-
- media_exceptions->push_back(MediaException(pattern, setting));
- }
-}
-
-// static
-void PepperFlashContentSettingsUtils::SortMediaExceptions(
- MediaExceptions* media_exceptions) {
- std::sort(media_exceptions->begin(), media_exceptions->end(),
- MediaExceptionSortFunc);
-}
-
-// static
-bool PepperFlashContentSettingsUtils::AreMediaExceptionsEqual(
- ContentSetting default_setting_1,
- const MediaExceptions& exceptions_1,
- ContentSetting default_setting_2,
- const MediaExceptions& exceptions_2) {
- MediaExceptions::const_iterator iter_1 = exceptions_1.begin();
- MediaExceptions::const_iterator iter_2 = exceptions_2.begin();
-
- MediaException default_exception_1(ContentSettingsPattern(),
- default_setting_1);
- MediaException default_exception_2(ContentSettingsPattern(),
- default_setting_2);
-
- while (iter_1 != exceptions_1.end() && iter_2 != exceptions_2.end()) {
- int compare_result = CompareMediaException(*iter_1, *iter_2);
- if (compare_result < 0) {
- if (iter_1->setting != default_exception_2.setting)
- return false;
- ++iter_1;
- } else if (compare_result > 0) {
- if (iter_2->setting != default_exception_1.setting) {
- return false;
- }
- ++iter_2;
- } else {
- if (iter_1->setting != iter_2->setting)
- return false;
- ++iter_1;
- ++iter_2;
- }
- }
-
- while (iter_1 != exceptions_1.end()) {
- if (iter_1->setting != default_exception_2.setting)
- return false;
- ++iter_1;
- }
- while (iter_2 != exceptions_2.end()) {
- if (iter_2->setting != default_exception_1.setting)
- return false;
- ++iter_2;
- }
- return true;
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.h b/chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.h
deleted file mode 100644
index 1e488239a3c..00000000000
--- a/chromium/chrome/browser/ui/webui/options/pepper_flash_content_settings_utils.h
+++ /dev/null
@@ -1,62 +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_OPTIONS_PEPPER_FLASH_CONTENT_SETTINGS_UTILS_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_PEPPER_FLASH_CONTENT_SETTINGS_UTILS_H_
-
-#include <vector>
-
-#include "base/macros.h"
-#include "components/content_settings/core/common/content_settings.h"
-#include "components/content_settings/core/common/content_settings_pattern.h"
-#include "ppapi/c/private/ppp_flash_browser_operations.h"
-#include "ppapi/shared_impl/ppp_flash_browser_operations_shared.h"
-
-namespace options {
-
-struct MediaException {
- MediaException(const ContentSettingsPattern& in_pattern,
- ContentSetting in_setting);
- ~MediaException();
-
- bool operator==(const MediaException& other) const;
-
- ContentSettingsPattern pattern;
- ContentSetting setting;
-};
-
-typedef std::vector<MediaException> MediaExceptions;
-
-class PepperFlashContentSettingsUtils {
- public:
- static ContentSetting FlashPermissionToContentSetting(
- PP_Flash_BrowserOperations_Permission permission);
-
- static void FlashSiteSettingsToMediaExceptions(
- const ppapi::FlashSiteSettings& site_settings,
- MediaExceptions* media_exceptions);
-
- // Sorts |media_exceptions| in ascending order by comparing the |pattern|
- // field of the elements.
- static void SortMediaExceptions(MediaExceptions* media_exceptions);
-
- // Checks whether |exceptions_1| and |exceptions_2| describe the same set of
- // exceptions. |exceptions_1| and |exceptions_2| should be sorted by
- // SortMediaExceptions() before passing into this method.
- //
- // When an element of |exceptions_1| has a pattern that doesn't match any
- // element of |exceptions_2|, it would be compared with |default_setting_2|,
- // and vice versa.
- static bool AreMediaExceptionsEqual(ContentSetting default_setting_1,
- const MediaExceptions& exceptions_1,
- ContentSetting default_setting_2,
- const MediaExceptions& exceptions_2);
-
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(PepperFlashContentSettingsUtils);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_PEPPER_FLASH_CONTENT_SETTINGS_UTILS_H_
diff --git a/chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.cc b/chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.cc
deleted file mode 100644
index bc254c3631b..00000000000
--- a/chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.cc
+++ /dev/null
@@ -1,269 +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 "chrome/browser/ui/webui/options/reset_profile_settings_handler.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/macros.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string16.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/google/google_brand.h"
-#include "chrome/browser/profile_resetter/brandcode_config_fetcher.h"
-#include "chrome/browser/profile_resetter/brandcoded_default_settings.h"
-#include "chrome/browser/profile_resetter/profile_resetter.h"
-#include "chrome/browser/profile_resetter/resettable_settings_snapshot.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/chromium_strings.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-#if defined(OS_WIN)
-#include "chrome/browser/profile_resetter/triggered_profile_resetter.h"
-#include "chrome/browser/profile_resetter/triggered_profile_resetter_factory.h"
-#endif // defined(OS_WIN)
-
-namespace options {
-
-namespace {
-
-reset_report::ChromeResetReport::ResetRequestOrigin
-ResetRequestOriginFromString(const std::string& reset_request_origin) {
- static const char kOriginUserClick[] = "userclick";
- static const char kOriginTriggeredReset[] = "triggeredreset";
-
- if (reset_request_origin ==
- ResetProfileSettingsHandler::kCctResetSettingsHash) {
- return reset_report::ChromeResetReport::RESET_REQUEST_ORIGIN_CCT;
- }
- if (reset_request_origin == kOriginUserClick)
- return reset_report::ChromeResetReport::RESET_REQUEST_ORIGIN_USER_CLICK;
- if (reset_request_origin == kOriginTriggeredReset) {
- return reset_report::ChromeResetReport::
- RESET_REQUEST_ORIGIN_TRIGGERED_RESET;
- }
- if (!reset_request_origin.empty())
- NOTREACHED();
-
- return reset_report::ChromeResetReport::RESET_REQUEST_ORIGIN_UNKNOWN;
-}
-
-} // namespace
-
-const char ResetProfileSettingsHandler::kCctResetSettingsHash[] = "cct";
-
-ResetProfileSettingsHandler::ResetProfileSettingsHandler() {
- google_brand::GetBrand(&brandcode_);
-}
-
-ResetProfileSettingsHandler::~ResetProfileSettingsHandler() {}
-
-void ResetProfileSettingsHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
- resetter_.reset(new ProfileResetter(profile));
-}
-
-void ResetProfileSettingsHandler::InitializePage() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ResetProfileSettingsOverlay.setResettingState",
- base::Value(resetter_->IsActive()));
-}
-
-void ResetProfileSettingsHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "resetProfileSettingsCommit", IDS_RESET_PROFILE_SETTINGS_COMMIT_BUTTON },
- { "resetProfileSettingsExplanation",
- IDS_RESET_PROFILE_SETTINGS_EXPLANATION },
- { "resetProfileSettingsFeedback", IDS_RESET_PROFILE_SETTINGS_FEEDBACK }
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "resetProfileSettingsOverlay",
- IDS_RESET_PROFILE_SETTINGS_TITLE);
- localized_strings->SetString(
- "resetProfileSettingsLearnMoreUrl",
- chrome::kResetProfileSettingsLearnMoreURL);
-
- // Set up the localized strings for the triggered profile reset overlay.
- // The reset tool name can currently only have a custom value on Windows.
- base::string16 reset_tool_name;
-#if defined(OS_WIN)
- Profile* profile = Profile::FromWebUI(web_ui());
- TriggeredProfileResetter* triggered_profile_resetter =
- TriggeredProfileResetterFactory::GetForBrowserContext(profile);
- // TriggeredProfileResetter instance will be nullptr for incognito profiles.
- if (triggered_profile_resetter) {
- reset_tool_name = triggered_profile_resetter->GetResetToolName();
-
- // Now that a reset UI has been shown, don't trigger again for this profile.
- triggered_profile_resetter->ClearResetTrigger();
- }
-#endif
-
- if (reset_tool_name.empty()) {
- reset_tool_name = l10n_util::GetStringUTF16(
- IDS_TRIGGERED_RESET_PROFILE_SETTINGS_DEFAULT_TOOL_NAME);
- }
- localized_strings->SetString(
- "triggeredResetProfileSettingsOverlay",
- l10n_util::GetStringFUTF16(IDS_TRIGGERED_RESET_PROFILE_SETTINGS_TITLE,
- reset_tool_name));
- // Set the title manually since RegisterTitle() wants an id.
- base::string16 title_string(l10n_util::GetStringFUTF16(
- IDS_TRIGGERED_RESET_PROFILE_SETTINGS_TITLE, reset_tool_name));
- localized_strings->SetString("triggeredResetProfileSettingsOverlay",
- title_string);
- localized_strings->SetString(
- "triggeredResetProfileSettingsOverlayTabTitle",
- l10n_util::GetStringFUTF16(IDS_OPTIONS_TAB_TITLE,
- l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE),
- title_string));
- localized_strings->SetString(
- "triggeredResetProfileSettingsExplanation",
- l10n_util::GetStringFUTF16(
- IDS_TRIGGERED_RESET_PROFILE_SETTINGS_EXPLANATION, reset_tool_name));
-}
-
-void ResetProfileSettingsHandler::RegisterMessages() {
- // Setup handlers specific to this panel.
- web_ui()->RegisterMessageCallback("performResetProfileSettings",
- base::Bind(&ResetProfileSettingsHandler::HandleResetProfileSettings,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("onShowResetProfileDialog",
- base::Bind(&ResetProfileSettingsHandler::OnShowResetProfileDialog,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("onHideResetProfileDialog",
- base::Bind(&ResetProfileSettingsHandler::OnHideResetProfileDialog,
- base::Unretained(this)));
-}
-
-void ResetProfileSettingsHandler::HandleResetProfileSettings(
- const base::ListValue* value) {
- bool send_settings = false;
- std::string request_origin_string;
- bool success = value->GetBoolean(0, &send_settings) &&
- value->GetString(1, &request_origin_string);
- DCHECK(success);
-
- DCHECK(brandcode_.empty() || config_fetcher_);
- reset_report::ChromeResetReport::ResetRequestOrigin request_origin =
- ResetRequestOriginFromString(request_origin_string);
- if (config_fetcher_ && config_fetcher_->IsActive()) {
- // Reset once the prefs are fetched.
- config_fetcher_->SetCallback(
- base::Bind(&ResetProfileSettingsHandler::ResetProfile, Unretained(this),
- send_settings, request_origin));
- } else {
- ResetProfile(send_settings, request_origin);
- }
-}
-
-void ResetProfileSettingsHandler::OnResetProfileSettingsDone(
- bool send_feedback,
- reset_report::ChromeResetReport::ResetRequestOrigin request_origin) {
- web_ui()->CallJavascriptFunctionUnsafe(
- "ResetProfileSettingsOverlay.doneResetting");
-
- if (send_feedback && setting_snapshot_) {
- Profile* profile = Profile::FromWebUI(web_ui());
- ResettableSettingsSnapshot current_snapshot(profile);
- int difference = setting_snapshot_->FindDifferentFields(current_snapshot);
- if (difference) {
- setting_snapshot_->Subtract(current_snapshot);
- std::unique_ptr<reset_report::ChromeResetReport> report_proto =
- SerializeSettingsReportToProto(*setting_snapshot_, difference);
- if (report_proto) {
- report_proto->set_reset_request_origin(request_origin);
- SendSettingsFeedbackProto(*report_proto, profile);
- }
- }
- }
- setting_snapshot_.reset();
-}
-
-void ResetProfileSettingsHandler::OnShowResetProfileDialog(
- const base::ListValue* value) {
- if (!resetter_->IsActive()) {
- setting_snapshot_.reset(
- new ResettableSettingsSnapshot(Profile::FromWebUI(web_ui())));
- setting_snapshot_->RequestShortcuts(base::Bind(
- &ResetProfileSettingsHandler::UpdateFeedbackUI, AsWeakPtr()));
- UpdateFeedbackUI();
- }
-
- if (brandcode_.empty())
- return;
- config_fetcher_.reset(new BrandcodeConfigFetcher(
- base::Bind(&ResetProfileSettingsHandler::OnSettingsFetched,
- Unretained(this)),
- GURL("https://tools.google.com/service/update2"),
- brandcode_));
-}
-
-void ResetProfileSettingsHandler::OnHideResetProfileDialog(
- const base::ListValue* value) {
- if (!resetter_->IsActive())
- setting_snapshot_.reset();
-}
-
-void ResetProfileSettingsHandler::OnSettingsFetched() {
- DCHECK(config_fetcher_);
- DCHECK(!config_fetcher_->IsActive());
- // The master prefs is fetched. We are waiting for user pressing 'Reset'.
-}
-
-void ResetProfileSettingsHandler::ResetProfile(
- bool send_settings,
- reset_report::ChromeResetReport::ResetRequestOrigin request_origin) {
- DCHECK(resetter_);
- DCHECK(!resetter_->IsActive());
-
- std::unique_ptr<BrandcodedDefaultSettings> default_settings;
- if (config_fetcher_) {
- DCHECK(!config_fetcher_->IsActive());
- default_settings = config_fetcher_->GetSettings();
- config_fetcher_.reset();
- } else {
- DCHECK(brandcode_.empty());
- }
-
- // If failed to fetch BrandcodedDefaultSettings or this is an organic
- // installation, use default settings.
- if (!default_settings)
- default_settings.reset(new BrandcodedDefaultSettings);
- resetter_->Reset(
- ProfileResetter::ALL, std::move(default_settings),
- base::Bind(&ResetProfileSettingsHandler::OnResetProfileSettingsDone,
- AsWeakPtr(), send_settings, request_origin));
- base::RecordAction(base::UserMetricsAction("ResetProfile"));
- UMA_HISTOGRAM_BOOLEAN("ProfileReset.SendFeedback", send_settings);
- UMA_HISTOGRAM_ENUMERATION(
- "ProfileReset.ResetRequestOrigin", request_origin,
- reset_report::ChromeResetReport::ResetRequestOrigin_MAX + 1);
-}
-
-void ResetProfileSettingsHandler::UpdateFeedbackUI() {
- if (!setting_snapshot_)
- return;
- std::unique_ptr<base::ListValue> list = GetReadableFeedbackForSnapshot(
- Profile::FromWebUI(web_ui()), *setting_snapshot_);
- base::DictionaryValue feedback_info;
- feedback_info.Set("feedbackInfo", std::move(list));
- web_ui()->CallJavascriptFunctionUnsafe(
- "ResetProfileSettingsOverlay.setFeedbackInfo", feedback_info);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.h b/chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.h
deleted file mode 100644
index d0e3405bf64..00000000000
--- a/chromium/chrome/browser/ui/webui/options/reset_profile_settings_handler.h
+++ /dev/null
@@ -1,91 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_RESET_PROFILE_SETTINGS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_RESET_PROFILE_SETTINGS_HANDLER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/profile_resetter/profile_reset_report.pb.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-} // namespace base
-
-class BrandcodeConfigFetcher;
-class ProfileResetter;
-class ResettableSettingsSnapshot;
-
-namespace options {
-
-// Handler for both the 'Reset Profile Settings' overlay page and also the
-// corresponding banner that is shown at the top of the options page.
-class ResetProfileSettingsHandler
- : public OptionsPageUIHandler,
- public base::SupportsWeakPtr<ResetProfileSettingsHandler> {
- public:
- // Hash used by the Chrome Cleanup Tool when launching chrome with the reset
- // profile settings URL.
- static const char kCctResetSettingsHash[];
-
- ResetProfileSettingsHandler();
- ~ResetProfileSettingsHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- // Javascript callback to start clearing data.
- void HandleResetProfileSettings(const base::ListValue* value);
-
- // Closes the dialog once all requested settings has been reset.
- void OnResetProfileSettingsDone(
- bool send_feedback,
- reset_report::ChromeResetReport::ResetRequestOrigin request_origin);
-
- // Called when the confirmation box appears.
- void OnShowResetProfileDialog(const base::ListValue* value);
-
- // Called when the confirmation box disappears.
- void OnHideResetProfileDialog(const base::ListValue* value);
-
- // Called when BrandcodeConfigFetcher completed fetching settings.
- void OnSettingsFetched();
-
- // Resets profile settings to default values. |send_settings| is true if user
- // gave their consent to upload broken settings to Google for analysis.
- void ResetProfile(
- bool send_settings,
- reset_report::ChromeResetReport::ResetRequestOrigin request_origin);
-
- // Sets new values for the feedback area.
- void UpdateFeedbackUI();
-
- std::unique_ptr<ProfileResetter> resetter_;
-
- std::unique_ptr<BrandcodeConfigFetcher> config_fetcher_;
-
- // Snapshot of settings before profile was reseted.
- std::unique_ptr<ResettableSettingsSnapshot> setting_snapshot_;
-
- // Contains Chrome brand code; empty for organic Chrome.
- std::string brandcode_;
-
- DISALLOW_COPY_AND_ASSIGN(ResetProfileSettingsHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_RESET_PROFILE_SETTINGS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.cc b/chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.cc
deleted file mode 100644
index a9d43ebca26..00000000000
--- a/chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.cc
+++ /dev/null
@@ -1,329 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/search_engine_manager_handler.h"
-
-#include "base/bind.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/extensions/extension_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
-#include "chrome/browser/ui/search_engines/keyword_editor_controller.h"
-#include "chrome/browser/ui/search_engines/template_url_table_model.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/search_engines/template_url.h"
-#include "components/search_engines/template_url_service.h"
-#include "content/public/browser/web_ui.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/common/extension.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace {
-
-enum EngineInfoIndexes {
- ENGINE_NAME,
- ENGINE_KEYWORD,
- ENGINE_URL,
-};
-
-}; // namespace
-
-namespace options {
-
-SearchEngineManagerHandler::SearchEngineManagerHandler() {
-}
-
-SearchEngineManagerHandler::~SearchEngineManagerHandler() {
- if (list_controller_.get() && list_controller_->table_model())
- list_controller_->table_model()->SetObserver(NULL);
-}
-
-void SearchEngineManagerHandler::InitializeHandler() {
- list_controller_.reset(
- new KeywordEditorController(Profile::FromWebUI(web_ui())));
- DCHECK(list_controller_.get());
- list_controller_->table_model()->SetObserver(this);
-}
-
-void SearchEngineManagerHandler::InitializePage() {
- OnModelChanged();
-}
-
-void SearchEngineManagerHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- RegisterTitle(localized_strings, "searchEngineManagerPage",
- IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE);
- localized_strings->SetString("defaultSearchEngineListTitle",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAIN_SEPARATOR));
- localized_strings->SetString("otherSearchEngineListTitle",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_OTHER_SEPARATOR));
- localized_strings->SetString("extensionKeywordsListTitle",
- l10n_util::GetStringUTF16(
- IDS_SEARCH_ENGINES_EDITOR_EXTENSIONS_SEPARATOR));
- localized_strings->SetString("makeDefaultSearchEngineButton",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));
- localized_strings->SetString("searchEngineTableNamePlaceholder",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_NAME_PLACEHOLDER));
- localized_strings->SetString("searchEngineTableKeywordPlaceholder",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_KEYWORD_PLACEHOLDER));
- localized_strings->SetString("searchEngineTableURLPlaceholder",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_URL_PLACEHOLDER));
- localized_strings->SetString("editSearchEngineInvalidTitleToolTip",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_TITLE_TT));
- localized_strings->SetString("editSearchEngineInvalidKeywordToolTip",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT));
- localized_strings->SetString("editSearchEngineInvalidURLToolTip",
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_URL_TT));
-}
-
-void SearchEngineManagerHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "managerSetDefaultSearchEngine",
- base::Bind(&SearchEngineManagerHandler::SetDefaultSearchEngine,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "removeSearchEngine",
- base::Bind(&SearchEngineManagerHandler::RemoveSearchEngine,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "editSearchEngine",
- base::Bind(&SearchEngineManagerHandler::EditSearchEngine,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "checkSearchEngineInfoValidity",
- base::Bind(&SearchEngineManagerHandler::CheckSearchEngineInfoValidity,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "searchEngineEditCancelled",
- base::Bind(&SearchEngineManagerHandler::EditCancelled,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "searchEngineEditCompleted",
- base::Bind(&SearchEngineManagerHandler::EditCompleted,
- base::Unretained(this)));
-}
-
-void SearchEngineManagerHandler::OnModelChanged() {
- DCHECK(list_controller_.get());
- if (!list_controller_->loaded())
- return;
-
- // Find the default engine.
- const TemplateURL* default_engine =
- list_controller_->GetDefaultSearchProvider();
- int default_index = list_controller_->table_model()->IndexOfTemplateURL(
- default_engine);
-
- // Build the first list (default search engine options).
- base::ListValue defaults_list;
- int last_default_engine_index =
- list_controller_->table_model()->last_search_engine_index();
- for (int i = 0; i < last_default_engine_index; ++i) {
- // Third argument is false, as the engine is not from an extension.
- defaults_list.Append(CreateDictionaryForEngine(
- i, i == default_index));
- }
-
- // Build the second list (other search templates).
- base::ListValue others_list;
- int last_other_engine_index =
- list_controller_->table_model()->last_other_engine_index();
- if (last_default_engine_index < 0)
- last_default_engine_index = 0;
- for (int i = last_default_engine_index; i < last_other_engine_index; ++i) {
- others_list.Append(CreateDictionaryForEngine(i, i == default_index));
- }
-
- // Build the extension keywords list.
- base::ListValue keyword_list;
- if (last_other_engine_index < 0)
- last_other_engine_index = 0;
- int engine_count = list_controller_->table_model()->RowCount();
- for (int i = last_other_engine_index; i < engine_count; ++i) {
- keyword_list.Append(CreateDictionaryForEngine(i, i == default_index));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "SearchEngineManager.updateSearchEngineList", defaults_list, others_list,
- keyword_list);
-}
-
-void SearchEngineManagerHandler::OnItemsChanged(int start, int length) {
- OnModelChanged();
-}
-
-void SearchEngineManagerHandler::OnItemsAdded(int start, int length) {
- OnModelChanged();
-}
-
-void SearchEngineManagerHandler::OnItemsRemoved(int start, int length) {
- OnModelChanged();
-}
-
-std::unique_ptr<base::DictionaryValue>
-SearchEngineManagerHandler::CreateDictionaryForEngine(int index,
- bool is_default) {
- TemplateURLTableModel* table_model = list_controller_->table_model();
- const TemplateURL* template_url = list_controller_->GetTemplateURL(index);
-
- // The items which are to be written into |dict| are also described in
- // chrome/browser/resources/options/search_engine_manager_engine_list.js
- // in @typedef for SearchEngine. Please update it whenever you add or remove
- // any keys here.
- std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
- dict->SetString("name", template_url->short_name());
- dict->SetString("displayName", table_model->GetText(
- index, IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN));
- dict->SetString("keyword", table_model->GetText(
- index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN));
- dict->SetString("url", template_url->url_ref().DisplayURL(
- UIThreadSearchTermsData(Profile::FromWebUI(web_ui()))));
- dict->SetBoolean("urlLocked", template_url->prepopulate_id() > 0);
- GURL icon_url = template_url->favicon_url();
- if (icon_url.is_valid())
- dict->SetString("iconURL", icon_url.spec());
- dict->SetString("modelIndex", base::IntToString(index));
-
- dict->SetBoolean("canBeRemoved",
- list_controller_->CanRemove(template_url));
- dict->SetBoolean("canBeDefault",
- list_controller_->CanMakeDefault(template_url));
- dict->SetBoolean("default", is_default);
- dict->SetBoolean("canBeEdited", list_controller_->CanEdit(template_url));
- TemplateURL::Type type = template_url->type();
- dict->SetBoolean("isOmniboxExtension",
- type == TemplateURL::OMNIBOX_API_EXTENSION);
- if (type == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION ||
- type == TemplateURL::OMNIBOX_API_EXTENSION) {
- const extensions::Extension* extension =
- extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
- ->GetExtensionById(template_url->GetExtensionId(),
- extensions::ExtensionRegistry::EVERYTHING);
- if (extension) {
- dict->Set("extension", extensions::util::GetExtensionInfo(extension));
- }
- }
- return dict;
-}
-
-void SearchEngineManagerHandler::SetDefaultSearchEngine(
- const base::ListValue* args) {
- int index;
- if (!ExtractIntegerValue(args, &index)) {
- NOTREACHED();
- return;
- }
- if (index < 0 || index >= list_controller_->table_model()->RowCount())
- return;
-
- list_controller_->MakeDefaultTemplateURL(index);
-
- base::RecordAction(base::UserMetricsAction("Options_SearchEngineSetDefault"));
-}
-
-void SearchEngineManagerHandler::RemoveSearchEngine(
- const base::ListValue* args) {
- int index;
- if (!ExtractIntegerValue(args, &index)) {
- NOTREACHED();
- return;
- }
- if (index < 0 || index >= list_controller_->table_model()->RowCount())
- return;
-
- if (list_controller_->CanRemove(list_controller_->GetTemplateURL(index))) {
- list_controller_->RemoveTemplateURL(index);
- base::RecordAction(base::UserMetricsAction("Options_SearchEngineRemoved"));
- }
-}
-
-void SearchEngineManagerHandler::EditSearchEngine(const base::ListValue* args) {
- int index;
- if (!ExtractIntegerValue(args, &index)) {
- NOTREACHED();
- return;
- }
-
- // Allow -1, which means we are adding a new engine.
- if (index < -1 || index >= list_controller_->table_model()->RowCount())
- return;
-
- edit_controller_.reset(new EditSearchEngineController(
- (index == -1) ? NULL : list_controller_->GetTemplateURL(index), this,
- Profile::FromWebUI(web_ui())));
-}
-
-void SearchEngineManagerHandler::OnEditedKeyword(
- TemplateURL* template_url,
- const base::string16& title,
- const base::string16& keyword,
- const std::string& url) {
- DCHECK(!url.empty());
- if (template_url)
- list_controller_->ModifyTemplateURL(template_url, title, keyword, url);
- else
- list_controller_->AddTemplateURL(title, keyword, url);
- edit_controller_.reset();
-}
-
-void SearchEngineManagerHandler::CheckSearchEngineInfoValidity(
- const base::ListValue* args) {
- if (!edit_controller_.get())
- return;
- base::string16 name;
- base::string16 keyword;
- std::string url;
- std::string modelIndex;
- if (!args->GetString(ENGINE_NAME, &name) ||
- !args->GetString(ENGINE_KEYWORD, &keyword) ||
- !args->GetString(ENGINE_URL, &url) ||
- !args->GetString(3, &modelIndex)) {
- NOTREACHED();
- return;
- }
-
- base::DictionaryValue validity;
- validity.SetBoolean("name", edit_controller_->IsTitleValid(name));
- validity.SetBoolean("keyword", edit_controller_->IsKeywordValid(keyword));
- validity.SetBoolean("url", edit_controller_->IsURLValid(url));
- base::Value indexValue(modelIndex);
- web_ui()->CallJavascriptFunctionUnsafe(
- "SearchEngineManager.validityCheckCallback", validity, indexValue);
-}
-
-void SearchEngineManagerHandler::EditCancelled(const base::ListValue* args) {
- if (!edit_controller_.get())
- return;
- edit_controller_->CleanUpCancelledAdd();
- edit_controller_.reset();
-}
-
-void SearchEngineManagerHandler::EditCompleted(const base::ListValue* args) {
- if (!edit_controller_.get())
- return;
- base::string16 name;
- base::string16 keyword;
- std::string url;
- if (!args->GetString(ENGINE_NAME, &name) ||
- !args->GetString(ENGINE_KEYWORD, &keyword) ||
- !args->GetString(ENGINE_URL, &url)) {
- NOTREACHED();
- return;
- }
-
- // Recheck validity. It's possible to get here with invalid input if e.g. the
- // user calls the right JS functions directly from the web inspector.
- if (edit_controller_->IsTitleValid(name) &&
- edit_controller_->IsKeywordValid(keyword) &&
- edit_controller_->IsURLValid(url))
- edit_controller_->AcceptAddOrEdit(name, keyword, url);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.h b/chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.h
deleted file mode 100644
index 9de72bfac3c..00000000000
--- a/chromium/chrome/browser/ui/webui/options/search_engine_manager_handler.h
+++ /dev/null
@@ -1,90 +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_OPTIONS_SEARCH_ENGINE_MANAGER_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_SEARCH_ENGINE_MANAGER_HANDLER_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "chrome/browser/ui/search_engines/edit_search_engine_controller.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "ui/base/models/table_model_observer.h"
-
-class KeywordEditorController;
-
-namespace extensions {
-class Extension;
-}
-
-namespace options {
-
-class SearchEngineManagerHandler : public OptionsPageUIHandler,
- public ui::TableModelObserver,
- public EditSearchEngineControllerDelegate {
- public:
- SearchEngineManagerHandler();
- ~SearchEngineManagerHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
-
- // ui::TableModelObserver implementation.
- void OnModelChanged() override;
- void OnItemsChanged(int start, int length) override;
- void OnItemsAdded(int start, int length) override;
- void OnItemsRemoved(int start, int length) override;
-
- // EditSearchEngineControllerDelegate implementation.
- void OnEditedKeyword(TemplateURL* template_url,
- const base::string16& title,
- const base::string16& keyword,
- const std::string& url) override;
-
- void RegisterMessages() override;
-
- private:
- std::unique_ptr<KeywordEditorController> list_controller_;
- std::unique_ptr<EditSearchEngineController> edit_controller_;
-
- // Removes the search engine at the given index. Called from WebUI.
- void RemoveSearchEngine(const base::ListValue* args);
-
- // Sets the search engine at the given index to be default. Called from WebUI.
- void SetDefaultSearchEngine(const base::ListValue* args);
-
- // Starts an edit session for the search engine at the given index. If the
- // index is -1, starts editing a new search engine instead of an existing one.
- // Called from WebUI.
- void EditSearchEngine(const base::ListValue* args);
-
- // Validates the given search engine values, and reports the results back
- // to WebUI. Called from WebUI.
- void CheckSearchEngineInfoValidity(const base::ListValue* args);
-
- // Called when an edit is cancelled.
- // Called from WebUI.
- void EditCancelled(const base::ListValue* args);
-
- // Called when an edit is finished and should be saved.
- // Called from WebUI.
- void EditCompleted(const base::ListValue* args);
-
- // Returns a dictionary to pass to WebUI representing the given search engine.
- std::unique_ptr<base::DictionaryValue> CreateDictionaryForEngine(
- int index,
- bool is_default);
-
- // Returns a dictionary to pass to WebUI representing the extension.
- base::DictionaryValue* CreateDictionaryForExtension(
- const extensions::Extension& extension);
-
- DISALLOW_COPY_AND_ASSIGN(SearchEngineManagerHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_SEARCH_ENGINE_MANAGER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/startup_pages_handler.cc b/chromium/chrome/browser/ui/webui/options/startup_pages_handler.cc
deleted file mode 100644
index 70e46552469..00000000000
--- a/chromium/chrome/browser/ui/webui/options/startup_pages_handler.cc
+++ /dev/null
@@ -1,272 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/startup_pages_handler.h"
-
-#include <stddef.h>
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h"
-#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/custom_home_pages_table_model.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-#include "chrome/browser/ui/webui/settings_utils.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/metrics/proto/omnibox_event.pb.h"
-#include "components/omnibox/browser/autocomplete_classifier.h"
-#include "components/omnibox/browser/autocomplete_controller.h"
-#include "components/omnibox/browser/autocomplete_input.h"
-#include "components/omnibox/browser/autocomplete_result.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/web_ui.h"
-#include "url/gurl.h"
-
-namespace options {
-
-StartupPagesHandler::StartupPagesHandler() {
-}
-
-StartupPagesHandler::~StartupPagesHandler() {
-}
-
-void StartupPagesHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "startupAddLabel", IDS_OPTIONS_STARTUP_ADD_LABEL },
- { "startupUseCurrent", IDS_OPTIONS_STARTUP_USE_CURRENT },
- { "startupPagesPlaceholder", IDS_OPTIONS_STARTUP_PAGES_PLACEHOLDER },
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "startupPagesOverlay",
- IDS_OPTIONS_STARTUP_PAGES_DIALOG_TITLE);
-}
-
-void StartupPagesHandler::RegisterMessages() {
- // Guest profiles should never have been displayed the option to set these
- // values.
- if (Profile::FromWebUI(web_ui())->IsOffTheRecord())
- return;
-
- web_ui()->RegisterMessageCallback("removeStartupPages",
- base::Bind(&StartupPagesHandler::RemoveStartupPages,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("addStartupPage",
- base::Bind(&StartupPagesHandler::AddStartupPage,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("editStartupPage",
- base::Bind(&StartupPagesHandler::EditStartupPage,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("setStartupPagesToCurrentPages",
- base::Bind(&StartupPagesHandler::SetStartupPagesToCurrentPages,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("dragDropStartupPage",
- base::Bind(&StartupPagesHandler::DragDropStartupPage,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "requestAutocompleteSuggestionsForStartupPages",
- base::Bind(&StartupPagesHandler::RequestAutocompleteSuggestions,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("commitStartupPrefChanges",
- base::Bind(&StartupPagesHandler::CommitChanges,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("cancelStartupPrefChanges",
- base::Bind(&StartupPagesHandler::CancelChanges,
- base::Unretained(this)));
-}
-
-void StartupPagesHandler::UpdateStartupPages() {
- Profile* profile = Profile::FromWebUI(web_ui());
- const SessionStartupPref startup_pref =
- SessionStartupPref::GetStartupPref(profile->GetPrefs());
- startup_custom_pages_table_model_->SetURLs(startup_pref.urls);
-}
-
-void StartupPagesHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
-
- startup_custom_pages_table_model_.reset(
- new CustomHomePagesTableModel(profile));
- startup_custom_pages_table_model_->SetObserver(this);
-
- pref_change_registrar_.Init(profile->GetPrefs());
- pref_change_registrar_.Add(
- prefs::kURLsToRestoreOnStartup,
- base::Bind(&StartupPagesHandler::UpdateStartupPages,
- base::Unretained(this)));
-
- autocomplete_controller_.reset(new AutocompleteController(
- base::MakeUnique<ChromeAutocompleteProviderClient>(profile), this,
- AutocompleteClassifier::DefaultOmniboxProviders()));
-}
-
-void StartupPagesHandler::InitializePage() {
- UpdateStartupPages();
-}
-
-void StartupPagesHandler::OnModelChanged() {
- base::ListValue startup_pages;
- int page_count = startup_custom_pages_table_model_->RowCount();
- std::vector<GURL> urls = startup_custom_pages_table_model_->GetURLs();
- for (int i = 0; i < page_count; ++i) {
- std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
- entry->SetString("title", startup_custom_pages_table_model_->GetText(i, 0));
- entry->SetString("url", urls[i].spec());
- entry->SetString("tooltip",
- startup_custom_pages_table_model_->GetTooltip(i));
- entry->SetInteger("modelIndex", i);
- startup_pages.Append(std::move(entry));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe("StartupOverlay.updateStartupPages",
- startup_pages);
-}
-
-void StartupPagesHandler::OnItemsChanged(int start, int length) {
- OnModelChanged();
-}
-
-void StartupPagesHandler::OnItemsAdded(int start, int length) {
- OnModelChanged();
-}
-
-void StartupPagesHandler::OnItemsRemoved(int start, int length) {
- OnModelChanged();
-}
-
-void StartupPagesHandler::SetStartupPagesToCurrentPages(
- const base::ListValue* args) {
- startup_custom_pages_table_model_->SetToCurrentlyOpenPages(
- web_ui()->GetWebContents());
-}
-
-void StartupPagesHandler::RemoveStartupPages(const base::ListValue* args) {
- for (int i = args->GetSize() - 1; i >= 0; --i) {
- int selected_index;
- CHECK(args->GetInteger(i, &selected_index));
-
- if (selected_index < 0 ||
- selected_index >= startup_custom_pages_table_model_->RowCount()) {
- NOTREACHED();
- return;
- }
- startup_custom_pages_table_model_->Remove(selected_index);
- }
-}
-
-void StartupPagesHandler::AddStartupPage(const base::ListValue* args) {
- std::string url_string;
- CHECK(args->GetString(0, &url_string));
-
- GURL fixed_url;
- if (!settings_utils::FixupAndValidateStartupPage(url_string, &fixed_url)) {
- NOTREACHED();
- return;
- }
-
- int row_count = startup_custom_pages_table_model_->RowCount();
- int index;
- if (!args->GetInteger(1, &index) || index > row_count)
- index = row_count;
-
- startup_custom_pages_table_model_->Add(index, fixed_url);
-}
-
-void StartupPagesHandler::EditStartupPage(const base::ListValue* args) {
- CHECK_EQ(args->GetSize(), 2U);
- int index;
- CHECK(args->GetInteger(0, &index));
-
- if (index < 0 || index > startup_custom_pages_table_model_->RowCount()) {
- NOTREACHED();
- return;
- }
-
- std::string url_string;
- CHECK(args->GetString(1, &url_string));
-
- GURL fixed_url;
- if (settings_utils::FixupAndValidateStartupPage(url_string, &fixed_url)) {
- std::vector<GURL> urls = startup_custom_pages_table_model_->GetURLs();
- urls[index] = fixed_url;
- startup_custom_pages_table_model_->SetURLs(urls);
- } else {
- startup_custom_pages_table_model_->Remove(index);
- }
-}
-
-void StartupPagesHandler::DragDropStartupPage(const base::ListValue* args) {
- CHECK_EQ(args->GetSize(), 2U);
-
- int to_index;
-
- CHECK(args->GetInteger(0, &to_index));
-
- const base::ListValue* selected;
- CHECK(args->GetList(1, &selected));
-
- std::vector<int> index_list;
- for (size_t i = 0; i < selected->GetSize(); ++i) {
- int index;
- CHECK(selected->GetInteger(i, &index));
- index_list.push_back(index);
- }
-
- startup_custom_pages_table_model_->MoveURLs(to_index, index_list);
-}
-
-void StartupPagesHandler::SaveStartupPagesPref() {
- PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
-
- SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs);
- pref.urls = startup_custom_pages_table_model_->GetURLs();
-
- if (pref.urls.empty())
- pref.type = SessionStartupPref::DEFAULT;
-
- SessionStartupPref::SetStartupPref(prefs, pref);
-}
-
-void StartupPagesHandler::CommitChanges(const base::ListValue* args) {
- SaveStartupPagesPref();
-}
-
-void StartupPagesHandler::CancelChanges(const base::ListValue* args) {
- UpdateStartupPages();
-}
-
-void StartupPagesHandler::RequestAutocompleteSuggestions(
- const base::ListValue* args) {
- base::string16 input;
- CHECK_EQ(args->GetSize(), 1U);
- CHECK(args->GetString(0, &input));
-
- autocomplete_controller_->Start(AutocompleteInput(
- input, base::string16::npos, std::string(), GURL(), base::string16(),
- metrics::OmniboxEventProto::INVALID_SPEC, true, false, false, true, false,
- ChromeAutocompleteSchemeClassifier(Profile::FromWebUI(web_ui()))));
-}
-
-void StartupPagesHandler::OnResultChanged(bool default_match_changed) {
- const AutocompleteResult& result = autocomplete_controller_->result();
- base::ListValue suggestions;
- OptionsUI::ProcessAutocompleteSuggestions(result, &suggestions);
- web_ui()->CallJavascriptFunctionUnsafe(
- "StartupOverlay.updateAutocompleteSuggestions", suggestions);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/startup_pages_handler.h b/chromium/chrome/browser/ui/webui/options/startup_pages_handler.h
deleted file mode 100644
index 2f181744f30..00000000000
--- a/chromium/chrome/browser/ui/webui/options/startup_pages_handler.h
+++ /dev/null
@@ -1,95 +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_OPTIONS_STARTUP_PAGES_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_STARTUP_PAGES_HANDLER_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/omnibox/browser/autocomplete_controller_delegate.h"
-#include "components/prefs/pref_change_registrar.h"
-#include "components/prefs/pref_member.h"
-#include "ui/base/models/table_model_observer.h"
-
-class AutocompleteController;
-class CustomHomePagesTableModel;
-
-namespace options {
-
-// Chrome browser options page UI handler.
-class StartupPagesHandler : public OptionsPageUIHandler,
- public AutocompleteControllerDelegate,
- public ui::TableModelObserver {
- public:
- StartupPagesHandler();
- ~StartupPagesHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
- void InitializePage() override;
- void RegisterMessages() override;
-
- // AutocompleteControllerDelegate implementation.
- void OnResultChanged(bool default_match_changed) override;
-
- // ui::TableModelObserver implementation.
- void OnModelChanged() override;
- void OnItemsChanged(int start, int length) override;
- void OnItemsAdded(int start, int length) override;
- void OnItemsRemoved(int start, int length) override;
-
- private:
- // Saves the changes that have been made. Called from WebUI.
- void CommitChanges(const base::ListValue* args);
-
- // Cancels the changes that have been made. Called from WebUI.
- void CancelChanges(const base::ListValue* args);
-
- // Removes the startup page at the given indexes. Called from WebUI.
- void RemoveStartupPages(const base::ListValue* args);
-
- // Adds a startup page with the given URL after the given index.
- // Called from WebUI.
- void AddStartupPage(const base::ListValue* args);
-
- // Changes the startup page at the given index to the given URL.
- // Called from WebUI.
- void EditStartupPage(const base::ListValue* args);
-
- // Sets the startup page set to the current pages. Called from WebUI.
- void SetStartupPagesToCurrentPages(const base::ListValue* args);
-
- // Writes the current set of startup pages to prefs. Called from WebUI.
- void DragDropStartupPage(const base::ListValue* args);
-
- // Gets autocomplete suggestions asychronously for the given string.
- // Called from WebUI.
- void RequestAutocompleteSuggestions(const base::ListValue* args);
-
- // Loads the current set of custom startup pages and reports it to the WebUI.
- void UpdateStartupPages();
-
- // Writes the current set of startup pages to prefs.
- void SaveStartupPagesPref();
-
- std::unique_ptr<AutocompleteController> autocomplete_controller_;
-
- // Used to observe updates to the preference of the list of URLs to load
- // on startup, which can be updated via sync.
- PrefChangeRegistrar pref_change_registrar_;
-
- // The set of pages to launch on startup.
- std::unique_ptr<CustomHomePagesTableModel> startup_custom_pages_table_model_;
-
- DISALLOW_COPY_AND_ASSIGN(StartupPagesHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_STARTUP_PAGES_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.cc b/chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.cc
deleted file mode 100644
index 9ff957d40f6..00000000000
--- a/chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.cc
+++ /dev/null
@@ -1,168 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.h"
-
-#include <stddef.h>
-
-#include <string>
-
-#include "base/bind.h"
-#include "base/files/file_path.h"
-#include "base/macros.h"
-#include "base/scoped_observer.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/profile.h"
-#include "chrome/browser/profiles/profile_attributes_entry.h"
-#include "chrome/browser/profiles/profile_attributes_storage.h"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/profiles/profile_window.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/startup/startup_types.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/signin/core/browser/signin_manager.h"
-#include "components/signin/core/browser/signin_manager_base.h"
-#include "content/public/browser/web_ui.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace options {
-
-// ProfileUpdateObserver------------------------------------------------------
-
-class SupervisedUserCreateConfirmHandler::ProfileUpdateObserver
- : public ProfileAttributesStorage::Observer {
- public:
- ProfileUpdateObserver(ProfileAttributesStorage* profile_attributes_storage,
- SupervisedUserCreateConfirmHandler* handler)
- : profile_attributes_storage_(profile_attributes_storage),
- create_confirm_handler_(handler),
- scoped_observer_(this) {
- DCHECK(profile_attributes_storage_);
- DCHECK(create_confirm_handler_);
- scoped_observer_.Add(profile_attributes_storage_);
- }
-
- private:
- // ProfileAttributesStorage::Observer implementation:
- // Forward possibly relevant changes to the dialog, which will check the
- // affected profile and update or close as needed.
- void OnProfileWasRemoved(const base::FilePath& profile_path,
- const base::string16& profile_name) override {
- std::unique_ptr<base::Value> profile_path_value(
- base::CreateFilePathValue(profile_path));
- create_confirm_handler_->web_ui()->CallJavascriptFunctionUnsafe(
- "SupervisedUserCreateConfirmOverlay.onDeletedProfile",
- *profile_path_value);
- }
-
- void OnProfileNameChanged(const base::FilePath& profile_path,
- const base::string16& old_profile_name) override {
- ProfileAttributesEntry* entry;
- if (!profile_attributes_storage_->
- GetProfileAttributesWithPath(profile_path, &entry))
- return;
- base::string16 new_profile_name = entry->GetName();
- std::unique_ptr<base::Value> profile_path_value(
- base::CreateFilePathValue(profile_path));
- create_confirm_handler_->web_ui()->CallJavascriptFunctionUnsafe(
- "SupervisedUserCreateConfirmOverlay.onUpdatedProfileName",
- *profile_path_value, base::Value(new_profile_name));
- }
-
- // Weak.
- ProfileAttributesStorage* profile_attributes_storage_;
-
- // Weak; owns us.
- SupervisedUserCreateConfirmHandler* create_confirm_handler_;
-
- // Manages any sources we're observing, ensuring that they're all removed
- // on destruction.
- ScopedObserver<ProfileAttributesStorage, ProfileUpdateObserver>
- scoped_observer_;
-
- DISALLOW_COPY_AND_ASSIGN(ProfileUpdateObserver);
-};
-
-
-// SupervisedUserCreateConfirmHandler-----------------------------------------
-
-SupervisedUserCreateConfirmHandler::SupervisedUserCreateConfirmHandler() {
- profile_update_observer_.reset(
- new SupervisedUserCreateConfirmHandler::ProfileUpdateObserver(
- &g_browser_process->profile_manager()->GetProfileAttributesStorage(),
- this));
-}
-
-SupervisedUserCreateConfirmHandler::~SupervisedUserCreateConfirmHandler() {
-}
-
-void SupervisedUserCreateConfirmHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "supervisedUserCreatedTitle", IDS_LEGACY_SUPERVISED_USER_CREATED_TITLE },
- { "supervisedUserCreatedDone",
- IDS_LEGACY_SUPERVISED_USER_CREATED_DONE_BUTTON },
- { "supervisedUserCreatedSwitch",
- IDS_LEGACY_SUPERVISED_USER_CREATED_SWITCH_BUTTON },
- };
-
- SigninManagerBase* signin =
- SigninManagerFactory::GetForProfile(Profile::FromWebUI(web_ui()));
- if (signin) {
- localized_strings->SetString("custodianEmail",
- signin->GetAuthenticatedAccountInfo().email);
- } else {
- localized_strings->SetString("custodianEmail", std::string());
- }
-
- base::string16 supervised_user_dashboard_url =
- base::ASCIIToUTF16(chrome::kLegacySupervisedUserManagementURL);
- base::string16 supervised_user_dashboard_display =
- base::ASCIIToUTF16(chrome::kLegacySupervisedUserManagementDisplayURL);
- // The first two substitution parameters need to remain; they will be filled
- // by the page's JS.
- localized_strings->SetString("supervisedUserCreatedText",
- l10n_util::GetStringFUTF16(IDS_LEGACY_SUPERVISED_USER_CREATED_TEXT,
- base::ASCIIToUTF16("$1"),
- base::ASCIIToUTF16("$2"),
- supervised_user_dashboard_url,
- supervised_user_dashboard_display));
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-}
-
-void SupervisedUserCreateConfirmHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("switchToProfile",
- base::Bind(&SupervisedUserCreateConfirmHandler::SwitchToProfile,
- base::Unretained(this)));
-}
-
-void SupervisedUserCreateConfirmHandler::SwitchToProfile(
- const base::ListValue* args) {
- DCHECK(args);
- const base::Value* file_path_value;
- if (!args->Get(0, &file_path_value))
- return;
-
- base::FilePath profile_file_path;
- if (!base::GetValueAsFilePath(*file_path_value, &profile_file_path))
- return;
-
- Profile* profile = g_browser_process->profile_manager()->
- GetProfileByPath(profile_file_path);
- DCHECK(profile);
-
- profiles::FindOrCreateNewWindowForProfile(
- profile, chrome::startup::IS_PROCESS_STARTUP,
- chrome::startup::IS_FIRST_RUN, false);
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.h b/chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.h
deleted file mode 100644
index cf18d3c260f..00000000000
--- a/chromium/chrome/browser/ui/webui/options/supervised_user_create_confirm_handler.h
+++ /dev/null
@@ -1,49 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_CREATE_CONFIRM_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_CREATE_CONFIRM_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-}
-
-namespace options {
-
-// Handler for the confirmation dialog after successful creation of a supervised
-// user.
-class SupervisedUserCreateConfirmHandler : public OptionsPageUIHandler {
- public:
- SupervisedUserCreateConfirmHandler();
- ~SupervisedUserCreateConfirmHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- private:
- // An observer for any changes to Profiles in the ProfileAttributesStorage so
- // that this dialog can be updated or closed.
- class ProfileUpdateObserver;
-
- // Callback for the "switchToProfile" message.
- // Opens a new window for the profile.
- // |args| is of the form [ {string} profileFilePath ]
- void SwitchToProfile(const base::ListValue* args);
-
- // Observes the ProfileAttributesStorage and gets notified when a profile has
- // been modified, so that the dialog can be updated or closed.
- std::unique_ptr<ProfileUpdateObserver> profile_update_observer_;
-
- DISALLOW_COPY_AND_ASSIGN(SupervisedUserCreateConfirmHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_CREATE_CONFIRM_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.cc b/chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.cc
deleted file mode 100644
index e768ff1ca90..00000000000
--- a/chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.cc
+++ /dev/null
@@ -1,304 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/supervised_user_import_handler.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <set>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/macros.h"
-#include "base/values.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_attributes_entry.h"
-#include "chrome/browser/profiles/profile_avatar_icon_util.h"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/signin/signin_error_controller_factory.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service_factory.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service_factory.h"
-#include "chrome/browser/supervised_user/supervised_user_constants.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "chrome/grit/theme_resources.h"
-#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_error_controller.h"
-#include "components/signin/core/browser/signin_manager.h"
-#include "content/public/browser/web_ui.h"
-
-namespace {
-
-std::unique_ptr<base::ListValue> GetAvatarIcons() {
- std::unique_ptr<base::ListValue> avatar_icons(new base::ListValue);
- for (size_t i = 0; i < profiles::GetDefaultAvatarIconCount(); ++i) {
- std::string avatar_url = profiles::GetDefaultAvatarIconUrl(i);
- avatar_icons->AppendString(avatar_url);
- }
-
- return avatar_icons;
-}
-
-bool ProfileIsLegacySupervised(const base::FilePath& profile_path) {
- ProfileAttributesEntry* entry;
-
- return g_browser_process->profile_manager()->GetProfileAttributesStorage().
- GetProfileAttributesWithPath(profile_path, &entry) &&
- entry->IsLegacySupervised();
-}
-
-} // namespace
-
-namespace options {
-
-SupervisedUserImportHandler::SupervisedUserImportHandler()
- : profile_observer_(this),
- signin_error_observer_(this),
- supervised_user_sync_service_observer_(this),
- removed_profile_is_supervised_(false),
- weak_ptr_factory_(this) {
-}
-
-SupervisedUserImportHandler::~SupervisedUserImportHandler() {
-}
-
-void SupervisedUserImportHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "supervisedUserImportTitle",
- IDS_IMPORT_EXISTING_LEGACY_SUPERVISED_USER_TITLE },
- { "supervisedUserImportText",
- IDS_IMPORT_EXISTING_LEGACY_SUPERVISED_USER_TEXT },
- { "createNewUserLink", IDS_CREATE_NEW_LEGACY_SUPERVISED_USER_LINK },
- { "supervisedUserImportOk",
- IDS_IMPORT_EXISTING_LEGACY_SUPERVISED_USER_OK },
- { "supervisedUserImportSigninError",
- IDS_LEGACY_SUPERVISED_USER_IMPORT_SIGN_IN_ERROR },
- { "supervisedUserAlreadyOnThisDevice",
- IDS_LEGACY_SUPERVISED_USER_ALREADY_ON_THIS_DEVICE },
- { "noExistingSupervisedUsers",
- IDS_LEGACY_SUPERVISED_USER_NO_EXISTING_ERROR },
- { "supervisedUserSelectAvatarTitle",
- IDS_LEGACY_SUPERVISED_USER_SELECT_AVATAR_TITLE },
- { "supervisedUserSelectAvatarText",
- IDS_LEGACY_SUPERVISED_USER_SELECT_AVATAR_TEXT },
- { "supervisedUserSelectAvatarOk",
- IDS_LEGACY_SUPERVISED_USER_SELECT_AVATAR_OK },
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- localized_strings->Set("avatarIcons", GetAvatarIcons());
-}
-
-void SupervisedUserImportHandler::InitializeHandler() {
- Profile* profile = Profile::FromWebUI(web_ui());
- if (!profile->IsSupervised()) {
- profile_observer_.Add(
- &g_browser_process->profile_manager()->GetProfileAttributesStorage());
- SupervisedUserSyncService* sync_service =
- SupervisedUserSyncServiceFactory::GetForProfile(profile);
- if (sync_service) {
- supervised_user_sync_service_observer_.Add(sync_service);
- signin_error_observer_.Add(
- SigninErrorControllerFactory::GetForProfile(profile));
- SupervisedUserSharedSettingsService* settings_service =
- SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext(
- profile);
- subscription_ = settings_service->Subscribe(
- base::Bind(&SupervisedUserImportHandler::OnSharedSettingChanged,
- weak_ptr_factory_.GetWeakPtr()));
- } else {
- DCHECK(!SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext(
- profile));
- DCHECK(!SigninErrorControllerFactory::GetForProfile(profile));
- }
- }
-}
-
-void SupervisedUserImportHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback("requestSupervisedUserImportUpdate",
- base::Bind(&SupervisedUserImportHandler::
- RequestSupervisedUserImportUpdate,
- base::Unretained(this)));
-}
-
-void SupervisedUserImportHandler::OnProfileAdded(
- const base::FilePath& profile_path) {
- // When a supervised profile is added, re-send the list to update the
- // the "already on this device" status.
- if (ProfileIsLegacySupervised(profile_path))
- FetchSupervisedUsers();
-}
-
-void SupervisedUserImportHandler::OnProfileWillBeRemoved(
- const base::FilePath& profile_path) {
- DCHECK(!removed_profile_is_supervised_);
- // When a supervised profile is removed, re-send the list to update the
- // "already on this device" status. We can't do that right now because the
- // profile still exists, so defer to OnProfileWasRemoved.
- if (ProfileIsLegacySupervised(profile_path))
- removed_profile_is_supervised_ = true;
-}
-
-void SupervisedUserImportHandler::OnProfileWasRemoved(
- const base::FilePath& profile_path,
- const base::string16& profile_name) {
- if (removed_profile_is_supervised_) {
- removed_profile_is_supervised_ = false;
- FetchSupervisedUsers();
- }
-}
-
-void SupervisedUserImportHandler::OnProfileIsOmittedChanged(
- const base::FilePath& profile_path) {
- if (ProfileIsLegacySupervised(profile_path))
- FetchSupervisedUsers();
-}
-
-void SupervisedUserImportHandler::OnSupervisedUsersChanged() {
- FetchSupervisedUsers();
-}
-
-void SupervisedUserImportHandler::FetchSupervisedUsers() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.SupervisedUserListData.resetPromise");
- RequestSupervisedUserImportUpdate(NULL);
-}
-
-void SupervisedUserImportHandler::RequestSupervisedUserImportUpdate(
- const base::ListValue* /* args */) {
- if (Profile::FromWebUI(web_ui())->IsSupervised())
- return;
-
- if (!IsAccountConnected() || HasAuthError()) {
- ClearSupervisedUsersAndShowError();
- } else {
- SupervisedUserSyncService* supervised_user_sync_service =
- SupervisedUserSyncServiceFactory::GetForProfile(
- Profile::FromWebUI(web_ui()));
- if (supervised_user_sync_service) {
- supervised_user_sync_service->GetSupervisedUsersAsync(
- base::Bind(&SupervisedUserImportHandler::SendExistingSupervisedUsers,
- weak_ptr_factory_.GetWeakPtr()));
- }
- }
-}
-
-void SupervisedUserImportHandler::SendExistingSupervisedUsers(
- const base::DictionaryValue* dict) {
- DCHECK(dict);
- std::vector<ProfileAttributesEntry*> entries =
- g_browser_process->profile_manager()->
- GetProfileAttributesStorage().GetAllProfilesAttributes();
-
- // Collect the ids of local supervised user profiles.
- std::set<std::string> supervised_user_ids;
- for (const ProfileAttributesEntry* entry : entries) {
- // Filter out omitted profiles. These are currently being imported, and
- // shouldn't show up as "already on this device" just yet.
- if (entry->IsLegacySupervised() && !entry->IsOmitted()) {
- supervised_user_ids.insert(entry->GetSupervisedUserId());
- }
- }
-
- base::ListValue supervised_users;
- Profile* profile = Profile::FromWebUI(web_ui());
- SupervisedUserSharedSettingsService* service =
- SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext(profile);
- for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
- const base::DictionaryValue* value = NULL;
- bool success = it.value().GetAsDictionary(&value);
- DCHECK(success);
- std::string name;
- value->GetString(SupervisedUserSyncService::kName, &name);
-
- std::unique_ptr<base::DictionaryValue> supervised_user(
- new base::DictionaryValue);
- supervised_user->SetString("id", it.key());
- supervised_user->SetString("name", name);
-
- int avatar_index = SupervisedUserSyncService::kNoAvatar;
- const base::Value* avatar_index_value =
- service->GetValue(it.key(), supervised_users::kChromeAvatarIndex);
- if (avatar_index_value) {
- success = avatar_index_value->GetAsInteger(&avatar_index);
- } else {
- // Check if there is a legacy avatar index stored.
- std::string avatar_str;
- value->GetString(SupervisedUserSyncService::kChromeAvatar, &avatar_str);
- success =
- SupervisedUserSyncService::GetAvatarIndex(avatar_str, &avatar_index);
- }
- DCHECK(success);
- supervised_user->SetBoolean(
- "needAvatar",
- avatar_index == SupervisedUserSyncService::kNoAvatar);
-
- std::string supervised_user_icon =
- std::string(chrome::kChromeUIThemeURL) +
- "IDR_SUPERVISED_USER_PLACEHOLDER";
- std::string avatar_url =
- avatar_index == SupervisedUserSyncService::kNoAvatar ?
- supervised_user_icon :
- profiles::GetDefaultAvatarIconUrl(avatar_index);
- supervised_user->SetString("iconURL", avatar_url);
- bool on_current_device =
- supervised_user_ids.find(it.key()) != supervised_user_ids.end();
- supervised_user->SetBoolean("onCurrentDevice", on_current_device);
-
- supervised_users.Append(std::move(supervised_user));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.SupervisedUserListData.receiveExistingSupervisedUsers",
- supervised_users);
-}
-
-void SupervisedUserImportHandler::ClearSupervisedUsersAndShowError() {
- web_ui()->CallJavascriptFunctionUnsafe(
- "options.SupervisedUserListData.onSigninError");
-}
-
-bool SupervisedUserImportHandler::IsAccountConnected() const {
- Profile* profile = Profile::FromWebUI(web_ui());
- SigninManagerBase* signin_manager =
- SigninManagerFactory::GetForProfile(profile);
- return signin_manager && signin_manager->IsAuthenticated();
-}
-
-bool SupervisedUserImportHandler::HasAuthError() const {
- Profile* profile = Profile::FromWebUI(web_ui());
- SigninErrorController* error_controller =
- SigninErrorControllerFactory::GetForProfile(profile);
- if (!error_controller)
- return true;
-
- GoogleServiceAuthError::State state = error_controller->auth_error().state();
-
- return state == GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS ||
- state == GoogleServiceAuthError::USER_NOT_SIGNED_UP ||
- state == GoogleServiceAuthError::ACCOUNT_DELETED ||
- state == GoogleServiceAuthError::ACCOUNT_DISABLED;
-}
-
-void SupervisedUserImportHandler::OnSharedSettingChanged(
- const std::string& supervised_user_id,
- const std::string& key) {
- if (key == supervised_users::kChromeAvatarIndex)
- FetchSupervisedUsers();
-}
-
-void SupervisedUserImportHandler::OnErrorChanged() {
- FetchSupervisedUsers();
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.h b/chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.h
deleted file mode 100644
index 9b972e1c96a..00000000000
--- a/chromium/chrome/browser/ui/webui/options/supervised_user_import_handler.h
+++ /dev/null
@@ -1,118 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_IMPORT_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_IMPORT_HANDLER_H_
-
-#include <string>
-
-#include "base/callback_list.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/scoped_observer.h"
-#include "base/strings/string16.h"
-#include "chrome/browser/profiles/profile_attributes_storage.h"
-#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service_observer.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "components/signin/core/browser/signin_error_controller.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-}
-
-class ProfileAttributesStorage;
-class SupervisedUserSyncService;
-
-namespace options {
-
-// Handler for the 'import existing supervised user' dialog.
-class SupervisedUserImportHandler : public OptionsPageUIHandler,
- public ProfileAttributesStorage::Observer,
- public SupervisedUserSyncServiceObserver,
- public SigninErrorController::Observer {
- public:
- typedef base::CallbackList<void(const std::string&, const std::string&)>
- CallbackList;
-
- SupervisedUserImportHandler();
- ~SupervisedUserImportHandler() override;
-
- private:
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void InitializeHandler() override;
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // ProfileAttributesStorage::Observer implementation.
- void OnProfileAdded(const base::FilePath& profile_path) override;
- void OnProfileWillBeRemoved(const base::FilePath& profile_path) override;
- void OnProfileWasRemoved(const base::FilePath& profile_path,
- const base::string16& profile_name) override;
- void OnProfileIsOmittedChanged(const base::FilePath& profile_path) override;
-
- // SupervisedUserSyncServiceObserver implementation.
- void OnSupervisedUserAcknowledged(
- const std::string& supervised_user_id) override {}
- void OnSupervisedUsersSyncingStopped() override {}
- void OnSupervisedUsersChanged() override;
-
- // SigninErrorController::Observer implementation.
- void OnErrorChanged() override;
-
- // Clears the cached list of supervised users and fetches the new list of
- // supervised users.
- void FetchSupervisedUsers();
-
- // Callback for the "requestSupervisedUserImportUpdate" message.
- // Checks the sign-in status of the custodian and accordingly
- // sends an update to the WebUI. The update can be to show/hide
- // an error bubble and update/clear the supervised user list.
- void RequestSupervisedUserImportUpdate(const base::ListValue* args);
-
- // Sends an array of supervised users to WebUI. Each entry is of the form:
- // supervisedProfile = {
- // id: "Supervised User ID",
- // name: "Supervised User Name",
- // iconURL: "chrome://path/to/icon/image",
- // onCurrentDevice: true or false,
- // needAvatar: true or false
- // }
- // The array holds all existing supervised users attached to the
- // custodian's profile which initiated the request.
- void SendExistingSupervisedUsers(const base::DictionaryValue* dict);
-
- // Sends messages to the JS side to clear supervised users and show an error
- // bubble.
- void ClearSupervisedUsersAndShowError();
-
- bool IsAccountConnected() const;
- bool HasAuthError() const;
-
- // Called when a supervised user shared setting is changed. If the avatar was
- // changed, FetchSupervisedUsers() is called.
- void OnSharedSettingChanged(const std::string& supervised_user_id,
- const std::string& key);
-
- std::unique_ptr<CallbackList::Subscription> subscription_;
-
- ScopedObserver<ProfileAttributesStorage, SupervisedUserImportHandler>
- profile_observer_;
- ScopedObserver<SigninErrorController, SupervisedUserImportHandler>
- signin_error_observer_;
- ScopedObserver<SupervisedUserSyncService, SupervisedUserImportHandler>
- supervised_user_sync_service_observer_;
-
- bool removed_profile_is_supervised_;
-
- base::WeakPtrFactory<SupervisedUserImportHandler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(SupervisedUserImportHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_IMPORT_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.cc b/chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.cc
deleted file mode 100644
index f7707e890b3..00000000000
--- a/chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.cc
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/supervised_user_learn_more_handler.h"
-
-#include "base/macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace options {
-
-SupervisedUserLearnMoreHandler::SupervisedUserLearnMoreHandler() {
-}
-
-SupervisedUserLearnMoreHandler::~SupervisedUserLearnMoreHandler() {
-}
-
-void SupervisedUserLearnMoreHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- DCHECK(localized_strings);
-
- static OptionsStringResource resources[] = {
- { "supervisedUserLearnMoreTitle",
- IDS_LEGACY_SUPERVISED_USER_LEARN_MORE_TITLE },
- { "supervisedUserLearnMoreDone",
- IDS_LEGACY_SUPERVISED_USER_LEARN_MORE_DONE_BUTTON },
- };
-
- base::string16 supervised_user_dashboard_display =
- base::ASCIIToUTF16(chrome::kLegacySupervisedUserManagementDisplayURL);
- localized_strings->SetString("supervisedUserLearnMoreText",
- l10n_util::GetStringFUTF16(IDS_LEGACY_SUPERVISED_USER_LEARN_MORE_TEXT,
- supervised_user_dashboard_display));
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
-}
-
-} // namespace options
diff --git a/chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.h b/chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.h
deleted file mode 100644
index 4d17286816e..00000000000
--- a/chromium/chrome/browser/ui/webui/options/supervised_user_learn_more_handler.h
+++ /dev/null
@@ -1,33 +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.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_LEARN_MORE_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_LEARN_MORE_HANDLER_H_
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-
-namespace base {
-class DictionaryValue;
-}
-
-namespace options {
-
-// Handler for the "Learn more" dialog available during creation of a supervised
-// user.
-class SupervisedUserLearnMoreHandler : public OptionsPageUIHandler {
- public:
- SupervisedUserLearnMoreHandler();
- ~SupervisedUserLearnMoreHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SupervisedUserLearnMoreHandler);
-};
-
-} // namespace options
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_SUPERVISED_USER_LEARN_MORE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/options/sync_setup_handler.cc b/chromium/chrome/browser/ui/webui/options/sync_setup_handler.cc
deleted file mode 100644
index de91eaf7914..00000000000
--- a/chromium/chrome/browser/ui/webui/options/sync_setup_handler.cc
+++ /dev/null
@@ -1,955 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/options/sync_setup_handler.h"
-
-#include <string>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/command_line.h"
-#include "base/compiler_specific.h"
-#include "base/i18n/time_formatting.h"
-#include "base/json/json_reader.h"
-#include "base/json/json_writer.h"
-#include "base/macros.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/app/chrome_command_ids.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_metrics.h"
-#include "chrome/browser/signin/chrome_signin_helper.h"
-#include "chrome/browser/signin/signin_error_controller_factory.h"
-#include "chrome/browser/signin/signin_manager_factory.h"
-#include "chrome/browser/signin/signin_promo.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/singleton_tabs.h"
-#include "chrome/browser/ui/webui/profile_helper.h"
-#include "chrome/browser/ui/webui/signin/login_ui_service.h"
-#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/chromium_strings.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/autofill/core/common/autofill_constants.h"
-#include "components/autofill/core/common/autofill_pref_names.h"
-#include "components/browser_sync/profile_sync_service.h"
-#include "components/google/core/browser/google_util.h"
-#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_error_controller.h"
-#include "components/signin/core/browser/signin_header_helper.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "components/signin/core/common/profile_management_switches.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/sync/base/sync_prefs.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_contents_delegate.h"
-#include "google_apis/gaia/gaia_auth_util.h"
-#include "google_apis/gaia/gaia_constants.h"
-#include "net/base/url_util.h"
-#include "ui/base/l10n/l10n_util.h"
-
-#if defined(OS_CHROMEOS)
-#include "components/signin/core/browser/signin_manager_base.h"
-#else
-#include "components/signin/core/browser/signin_manager.h"
-#endif
-
-using browser_sync::ProfileSyncService;
-using content::WebContents;
-using l10n_util::GetStringFUTF16;
-using l10n_util::GetStringUTF16;
-
-namespace {
-
-// A structure which contains all the configuration information for sync.
-struct SyncConfigInfo {
- SyncConfigInfo();
- ~SyncConfigInfo();
-
- bool encrypt_all;
- bool sync_everything;
- syncer::ModelTypeSet data_types;
- bool payments_integration_enabled;
- std::string passphrase;
- bool passphrase_is_gaia;
-};
-
-SyncConfigInfo::SyncConfigInfo()
- : encrypt_all(false),
- sync_everything(false),
- payments_integration_enabled(false),
- passphrase_is_gaia(false) {}
-
-SyncConfigInfo::~SyncConfigInfo() {}
-
-bool GetConfiguration(const std::string& json, SyncConfigInfo* config) {
- std::unique_ptr<base::Value> parsed_value = base::JSONReader::Read(json);
- base::DictionaryValue* result;
- if (!parsed_value || !parsed_value->GetAsDictionary(&result)) {
- DLOG(ERROR) << "GetConfiguration() not passed a Dictionary";
- return false;
- }
-
- if (!result->GetBoolean("syncAllDataTypes", &config->sync_everything)) {
- DLOG(ERROR) << "GetConfiguration() not passed a syncAllDataTypes value";
- return false;
- }
-
- if (!result->GetBoolean("paymentsIntegrationEnabled",
- &config->payments_integration_enabled)) {
- DLOG(ERROR) << "GetConfiguration() not passed a paymentsIntegrationEnabled "
- << "value";
- return false;
- }
-
- syncer::ModelTypeNameMap type_names = syncer::GetUserSelectableTypeNameMap();
-
- for (syncer::ModelTypeNameMap::const_iterator it = type_names.begin();
- it != type_names.end(); ++it) {
- std::string key_name = it->second + std::string("Synced");
- bool sync_value;
- if (!result->GetBoolean(key_name, &sync_value)) {
- DLOG(ERROR) << "GetConfiguration() not passed a value for " << key_name;
- return false;
- }
- if (sync_value)
- config->data_types.Put(it->first);
- }
-
- // Encryption settings.
- if (!result->GetBoolean("encryptAllData", &config->encrypt_all)) {
- DLOG(ERROR) << "GetConfiguration() not passed a value for encryptAllData";
- return false;
- }
-
- // Passphrase settings.
- bool have_passphrase;
- if (!result->GetBoolean("usePassphrase", &have_passphrase)) {
- DLOG(ERROR) << "GetConfiguration() not passed a usePassphrase value";
- return false;
- }
-
- if (have_passphrase) {
- if (!result->GetBoolean("isGooglePassphrase",
- &config->passphrase_is_gaia)) {
- DLOG(ERROR) << "GetConfiguration() not passed isGooglePassphrase value";
- return false;
- }
- if (!result->GetString("passphrase", &config->passphrase)) {
- DLOG(ERROR) << "GetConfiguration() not passed a passphrase value";
- return false;
- }
- }
- return true;
-}
-
-} // namespace
-
-SyncSetupHandler::SyncSetupHandler()
- : configuring_sync_(false) {
-}
-
-SyncSetupHandler::~SyncSetupHandler() {
- // Just exit if running unit tests (no actual WebUI is attached).
- if (!web_ui())
- return;
-
- // This case is hit when the user performs a back navigation.
- CloseSyncSetup();
-}
-
-void SyncSetupHandler::GetLocalizedValues(
- base::DictionaryValue* localized_strings) {
- GetStaticLocalizedValues(localized_strings, web_ui());
-}
-
-void SyncSetupHandler::GetStaticLocalizedValues(
- base::DictionaryValue* localized_strings,
- content::WebUI* web_ui) {
- DCHECK(localized_strings);
-
- base::string16 product_name(GetStringUTF16(IDS_PRODUCT_NAME));
- localized_strings->SetString(
- "chooseDataTypesInstructions",
- GetStringFUTF16(IDS_SYNC_CHOOSE_DATATYPES_INSTRUCTIONS, product_name));
- localized_strings->SetString("autofillHelpURL", autofill::kHelpURL);
- localized_strings->SetString(
- "encryptionInstructions",
- GetStringFUTF16(IDS_SYNC_ENCRYPTION_INSTRUCTIONS, product_name));
- localized_strings->SetString(
- "encryptionHelpURL", chrome::kSyncEncryptionHelpURL);
- localized_strings->SetString(
- "encryptionSectionMessage",
- GetStringFUTF16(IDS_SYNC_ENCRYPTION_SECTION_MESSAGE, product_name));
- localized_strings->SetString(
- "personalizeGoogleServicesTitle",
- GetStringUTF16(IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE));
- localized_strings->SetString(
- "personalizeGoogleServicesMessage",
- GetStringFUTF16(
- IDS_SYNC_PERSONALIZE_GOOGLE_SERVICES_MESSAGE,
- base::ASCIIToUTF16(chrome::kGoogleAccountActivityControlsURL)));
- localized_strings->SetString(
- "passphraseRecover",
- GetStringFUTF16(
- IDS_SYNC_PASSPHRASE_RECOVER,
- base::ASCIIToUTF16(
- google_util::AppendGoogleLocaleParam(
- GURL(chrome::kSyncGoogleDashboardURL),
- g_browser_process->GetApplicationLocale()).spec())));
- localized_strings->SetString(
- "stopSyncingExplanation",
- l10n_util::GetStringFUTF16(
- IDS_SYNC_STOP_SYNCING_EXPLANATION_LABEL,
- l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
- base::ASCIIToUTF16(
- google_util::AppendGoogleLocaleParam(
- GURL(chrome::kSyncGoogleDashboardURL),
- g_browser_process->GetApplicationLocale()).spec())));
- localized_strings->SetString("deleteProfileLabel",
- l10n_util::GetStringUTF16(IDS_SYNC_STOP_DELETE_PROFILE_LABEL));
- localized_strings->SetString("stopSyncingTitle",
- l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_DIALOG_TITLE));
- localized_strings->SetString("stopSyncingConfirm",
- l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_CONFIRM_BUTTON_LABEL));
-
- localized_strings->SetString(
- "syncEverythingHelpURL", chrome::kSyncEverythingLearnMoreURL);
- localized_strings->SetString(
- "syncErrorHelpURL", chrome::kSyncErrorsHelpURL);
-
- static OptionsStringResource resources[] = {
- {"syncSetupConfigureTitle", IDS_SYNC_SETUP_CONFIGURE_TITLE},
- {"syncSetupSpinnerTitle", IDS_SYNC_SETUP_SPINNER_TITLE},
- {"syncSetupTimeoutTitle", IDS_SYNC_SETUP_TIME_OUT_TITLE},
- {"syncSetupTimeoutContent", IDS_SYNC_SETUP_TIME_OUT_CONTENT},
- {"errorLearnMore", IDS_LEARN_MORE},
- {"cancel", IDS_CANCEL},
- {"loginSuccess", IDS_SYNC_SUCCESS},
- {"settingUp", IDS_SYNC_LOGIN_SETTING_UP},
- {"syncAllDataTypes", IDS_SYNC_EVERYTHING},
- {"chooseDataTypes", IDS_SYNC_CHOOSE_DATATYPES},
- {"bookmarks", IDS_SYNC_DATATYPE_BOOKMARKS},
- {"preferences", IDS_SYNC_DATATYPE_PREFERENCES},
- {"autofill", IDS_SYNC_DATATYPE_AUTOFILL},
- {"themes", IDS_SYNC_DATATYPE_THEMES},
- {"passwords", IDS_SYNC_DATATYPE_PASSWORDS},
- {"extensions", IDS_SYNC_DATATYPE_EXTENSIONS},
- {"typedURLs", IDS_SYNC_DATATYPE_TYPED_URLS},
- {"apps", IDS_SYNC_DATATYPE_APPS},
- {"openTabs", IDS_SYNC_DATATYPE_TABS},
- {"enablePaymentsIntegration", IDS_AUTOFILL_USE_PAYMENTS_DATA},
- {"serviceUnavailableError", IDS_SYNC_SETUP_ABORTED_BY_PENDING_CLEAR},
- {"confirmLabel", IDS_SYNC_CONFIRM_PASSPHRASE_LABEL},
- {"emptyErrorMessage", IDS_SYNC_EMPTY_PASSPHRASE_ERROR},
- {"mismatchErrorMessage", IDS_SYNC_PASSPHRASE_MISMATCH_ERROR},
- {"customizeLinkLabel", IDS_SYNC_CUSTOMIZE_LINK_LABEL},
- {"confirmSyncPreferences", IDS_SYNC_CONFIRM_SYNC_PREFERENCES},
- {"syncEverything", IDS_SYNC_SYNC_EVERYTHING},
- {"useDefaultSettings", IDS_SYNC_USE_DEFAULT_SETTINGS},
- {"enterPassphraseBody", IDS_SYNC_ENTER_PASSPHRASE_BODY},
- {"enterGooglePassphraseBody", IDS_SYNC_ENTER_GOOGLE_PASSPHRASE_BODY},
- {"passphraseLabel", IDS_SYNC_PASSPHRASE_LABEL},
- {"incorrectPassphrase", IDS_SYNC_INCORRECT_PASSPHRASE},
- {"passphraseWarning", IDS_SYNC_PASSPHRASE_WARNING},
- {"yes", IDS_SYNC_PASSPHRASE_CANCEL_YES},
- {"no", IDS_SYNC_PASSPHRASE_CANCEL_NO},
- {"sectionExplicitMessagePrefix", IDS_SYNC_PASSPHRASE_MSG_EXPLICIT_PREFIX},
- {"sectionExplicitMessagePostfix",
- IDS_SYNC_PASSPHRASE_MSG_EXPLICIT_POSTFIX},
- // TODO(rogerta): browser/resource/sync_promo/sync_promo.html and related
- // file may not be needed any more. If not, then the following promo
- // strings can also be removed.
- {"promoPageTitle", IDS_SYNC_PROMO_TAB_TITLE},
- {"promoSkipButton", IDS_SYNC_PROMO_SKIP_BUTTON},
- {"promoAdvanced", IDS_SYNC_PROMO_ADVANCED},
- {"promoLearnMore", IDS_LEARN_MORE},
- {"promoTitleShort", IDS_SYNC_PROMO_MESSAGE_TITLE_SHORT},
- {"encryptionSectionTitle", IDS_SYNC_ENCRYPTION_SECTION_TITLE},
- {"basicEncryptionOption", IDS_SYNC_BASIC_ENCRYPTION_DATA},
- {"fullEncryptionOption", IDS_SYNC_FULL_ENCRYPTION_DATA},
- };
-
- RegisterStrings(localized_strings, resources, arraysize(resources));
- RegisterTitle(localized_strings, "syncSetupOverlay", IDS_SYNC_SETUP_TITLE);
-}
-
-void SyncSetupHandler::ConfigureSyncDone() {
- base::Value page("done");
- web_ui()->CallJavascriptFunctionUnsafe("SyncSetupOverlay.showSyncSetupPage",
- page);
-
- // Suppress the sign in promo once the user starts sync. This way the user
- // doesn't see the sign in promo even if they sign out later on.
- signin::SetUserSkippedPromo(GetProfile());
-
- ProfileSyncService* service = GetSyncService();
- DCHECK(service);
- if (!service->IsFirstSetupComplete()) {
- // This is the first time configuring sync, so log it.
- base::FilePath profile_file_path = GetProfile()->GetPath();
- ProfileMetrics::LogProfileSyncSignIn(profile_file_path);
-
- // We're done configuring, so notify ProfileSyncService that it is OK to
- // start syncing.
- sync_blocker_.reset();
- service->SetFirstSetupComplete();
- }
-}
-
-bool SyncSetupHandler::IsActiveLogin() const {
- // LoginUIService can be NULL if page is brought up in incognito mode
- // (i.e. if the user is running in guest mode in cros and brings up settings).
- LoginUIService* service = GetLoginUIService();
- return service && (service->current_login_ui() == this);
-}
-
-void SyncSetupHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "SyncSetupDidClosePage",
- base::Bind(&SyncSetupHandler::OnDidClosePage,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "SyncSetupConfigure",
- base::Bind(&SyncSetupHandler::HandleConfigure,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "SyncSetupShowSetupUI",
- base::Bind(&SyncSetupHandler::HandleShowSetupUI,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("CloseTimeout",
- base::Bind(&SyncSetupHandler::HandleCloseTimeout,
- base::Unretained(this)));
-#if defined(OS_CHROMEOS)
- web_ui()->RegisterMessageCallback(
- "AttemptUserExit",
- base::Bind(&SyncSetupHandler::HandleAttemptUserExit,
- base::Unretained(this)));
-#else
- web_ui()->RegisterMessageCallback("SyncSetupStopSyncing",
- base::Bind(&SyncSetupHandler::HandleStopSyncing,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("SyncSetupStartSignIn",
- base::Bind(&SyncSetupHandler::HandleStartSignin,
- base::Unretained(this)));
-#endif
-}
-
-#if !defined(OS_CHROMEOS)
-void SyncSetupHandler::DisplayGaiaLogin(
- signin_metrics::AccessPoint access_point) {
- DCHECK(!sync_startup_tracker_);
- // Advanced options are no longer being configured if the login screen is
- // visible. If the user exits the signin wizard after this without
- // configuring sync, CloseSyncSetup() will ensure they are logged out.
- configuring_sync_ = false;
- DisplayGaiaLoginInNewTabOrWindow(access_point);
-}
-
-void SyncSetupHandler::DisplayGaiaLoginInNewTabOrWindow(
- signin_metrics::AccessPoint access_point) {
- Browser* browser = chrome::FindBrowserWithWebContents(
- web_ui()->GetWebContents());
- bool force_new_tab = false;
- if (!browser) {
- // Settings is not displayed in a browser window. Open a new window.
- browser = new Browser(
- Browser::CreateParams(Browser::TYPE_TABBED, GetProfile(), true));
- force_new_tab = true;
- }
-
- // If the signin manager already has an authenticated username, this is a
- // re-auth scenario, and we need to ensure that the user signs in with the
- // same email address.
- GURL url;
- if (SigninManagerFactory::GetForProfile(
- browser->profile())->IsAuthenticated()) {
- UMA_HISTOGRAM_ENUMERATION("Signin.Reauth",
- signin_metrics::HISTOGRAM_REAUTH_SHOWN,
- signin_metrics::HISTOGRAM_REAUTH_MAX);
-
- SigninErrorController* error_controller =
- SigninErrorControllerFactory::GetForProfile(browser->profile());
- DCHECK(error_controller->HasError());
- if (!force_new_tab) {
- browser->window()->ShowAvatarBubbleFromAvatarButton(
- BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH,
- signin::ManageAccountsParams(), access_point, false);
- } else {
- url = signin::GetReauthURL(
- access_point, signin_metrics::Reason::REASON_REAUTHENTICATION,
- browser->profile(), error_controller->error_account_id());
- }
- } else {
- if (!force_new_tab) {
- browser->window()->ShowAvatarBubbleFromAvatarButton(
- BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN,
- signin::ManageAccountsParams(), access_point, false);
- } else {
- url = signin::GetPromoURL(
- access_point, signin_metrics::Reason::REASON_SIGNIN_PRIMARY_ACCOUNT,
- true);
- }
- }
-
- if (url.is_valid())
- chrome::ShowSingletonTab(browser, url);
-}
-#endif
-
-bool SyncSetupHandler::PrepareSyncSetup() {
- // If the wizard is already visible, just focus that one.
- if (FocusExistingWizardIfPresent()) {
- if (!IsActiveLogin())
- CloseSyncSetup();
- return false;
- }
-
- // Notify services that login UI is now active.
- GetLoginUIService()->SetLoginUI(this);
-
- ProfileSyncService* service = GetSyncService();
- if (service)
- sync_blocker_ = service->GetSetupInProgressHandle();
-
- return true;
-}
-
-void SyncSetupHandler::DisplaySpinner() {
- configuring_sync_ = true;
- base::Value page("spinner");
- base::DictionaryValue args;
-
- const int kTimeoutSec = 30;
- DCHECK(!engine_start_timer_);
- engine_start_timer_.reset(new base::OneShotTimer());
- engine_start_timer_->Start(FROM_HERE,
- base::TimeDelta::FromSeconds(kTimeoutSec), this,
- &SyncSetupHandler::DisplayTimeout);
-
- web_ui()->CallJavascriptFunctionUnsafe("SyncSetupOverlay.showSyncSetupPage",
- page, args);
-}
-
-// TODO(kochi): Handle error conditions other than timeout.
-// http://crbug.com/128692
-void SyncSetupHandler::DisplayTimeout() {
- // Stop a timer to handle timeout in waiting for checking network connection.
- engine_start_timer_.reset();
-
- // Do not listen to sync startup events.
- sync_startup_tracker_.reset();
-
- base::Value page("timeout");
- base::DictionaryValue args;
- web_ui()->CallJavascriptFunctionUnsafe("SyncSetupOverlay.showSyncSetupPage",
- page, args);
-}
-
-void SyncSetupHandler::OnDidClosePage(const base::ListValue* args) {
- CloseSyncSetup();
-}
-
-void SyncSetupHandler::SyncStartupFailed() {
- // Stop a timer to handle timeout in waiting for checking network connection.
- engine_start_timer_.reset();
-
- // Just close the sync overlay (the idea is that the base settings page will
- // display the current error.)
- CloseUI();
-}
-
-void SyncSetupHandler::SyncStartupCompleted() {
- ProfileSyncService* service = GetSyncService();
- DCHECK(service->IsEngineInitialized());
-
- // Stop a timer to handle timeout in waiting for checking network connection.
- engine_start_timer_.reset();
-
- DisplayConfigureSync(false);
-}
-
-Profile* SyncSetupHandler::GetProfile() const {
- return Profile::FromWebUI(web_ui());
-}
-
-ProfileSyncService* SyncSetupHandler::GetSyncService() const {
- Profile* profile = GetProfile();
- return profile->IsSyncAllowed() ?
- ProfileSyncServiceFactory::GetForProfile(GetProfile()) : NULL;
-}
-
-void SyncSetupHandler::HandleConfigure(const base::ListValue* args) {
- DCHECK(!sync_startup_tracker_);
- std::string json;
- if (!args->GetString(0, &json)) {
- NOTREACHED() << "Could not read JSON argument";
- return;
- }
- if (json.empty()) {
- NOTREACHED();
- return;
- }
-
- SyncConfigInfo configuration;
- if (!GetConfiguration(json, &configuration)) {
- // The page sent us something that we didn't understand.
- // This probably indicates a programming error.
- NOTREACHED();
- return;
- }
-
- // Start configuring the ProfileSyncService using the configuration passed
- // to us from the JS layer.
- ProfileSyncService* service = GetSyncService();
-
- // If the sync engine has shutdown for some reason, just close the sync
- // dialog.
- if (!service || !service->IsEngineInitialized()) {
- CloseUI();
- return;
- }
-
- // Don't allow "encrypt all" if the ProfileSyncService doesn't allow it.
- // The UI is hidden, but the user may have enabled it e.g. by fiddling with
- // the web inspector.
- if (!service->IsEncryptEverythingAllowed())
- configuration.encrypt_all = false;
-
- // Note: Data encryption will not occur until configuration is complete
- // (when the PSS receives its CONFIGURE_DONE notification from the sync
- // engine), so the user still has a chance to cancel out of the operation
- // if (for example) some kind of passphrase error is encountered.
- if (configuration.encrypt_all)
- service->EnableEncryptEverything();
-
- bool passphrase_failed = false;
- if (!configuration.passphrase.empty()) {
- // We call IsPassphraseRequired() here (instead of
- // IsPassphraseRequiredForDecryption()) because the user may try to enter
- // a passphrase even though no encrypted data types are enabled.
- if (service->IsPassphraseRequired()) {
- // If we have pending keys, try to decrypt them with the provided
- // passphrase. We track if this succeeds or fails because a failed
- // decryption should result in an error even if there aren't any encrypted
- // data types.
- passphrase_failed =
- !service->SetDecryptionPassphrase(configuration.passphrase);
- } else {
- // OK, the user sent us a passphrase, but we don't have pending keys. So
- // it either means that the pending keys were resolved somehow since the
- // time the UI was displayed (re-encryption, pending passphrase change,
- // etc) or the user wants to re-encrypt.
- if (!configuration.passphrase_is_gaia &&
- !service->IsUsingSecondaryPassphrase()) {
- // User passed us a secondary passphrase, and the data is encrypted
- // with a GAIA passphrase so they must want to encrypt.
- service->SetEncryptionPassphrase(configuration.passphrase,
- ProfileSyncService::EXPLICIT);
- }
- }
- }
-
- bool user_was_prompted_for_passphrase =
- service->IsPassphraseRequiredForDecryption();
- service->OnUserChoseDatatypes(configuration.sync_everything,
- configuration.data_types);
-
- PrefService* pref_service = GetProfile()->GetPrefs();
- pref_service->SetBoolean(autofill::prefs::kAutofillWalletImportEnabled,
- configuration.payments_integration_enabled);
-
- // Need to call IsPassphraseRequiredForDecryption() *after* calling
- // OnUserChoseDatatypes() because the user may have just disabled the
- // encrypted datatypes (in which case we just want to exit, not prompt the
- // user for a passphrase).
- if (passphrase_failed || service->IsPassphraseRequiredForDecryption()) {
- // We need a passphrase, or the user's attempt to set a passphrase failed -
- // prompt them again. This covers a few subtle cases:
- // 1) The user enters an incorrect passphrase *and* disabled the encrypted
- // data types. In that case we want to notify the user that the
- // passphrase was incorrect even though there are no longer any encrypted
- // types enabled (IsPassphraseRequiredForDecryption() == false).
- // 2) The user doesn't enter any passphrase. In this case, we won't call
- // SetDecryptionPassphrase() (passphrase_failed == false), but we still
- // want to display an error message to let the user know that their
- // blank passphrase entry is not acceptable.
- // 3) The user just enabled an encrypted data type - in this case we don't
- // want to display an "invalid passphrase" error, since it's the first
- // time the user is seeing the prompt.
- DisplayConfigureSync(passphrase_failed || user_was_prompted_for_passphrase);
- } else {
- // No passphrase is required from the user so mark the configuration as
- // complete and close the sync setup overlay.
- ConfigureSyncDone();
- }
-
- ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CUSTOMIZE);
- if (configuration.encrypt_all)
- ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_ENCRYPT);
- if (configuration.passphrase_is_gaia && !configuration.passphrase.empty())
- ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_PASSPHRASE);
- if (!configuration.sync_everything)
- ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CHOOSE);
-}
-
-void SyncSetupHandler::HandleShowSetupUI(const base::ListValue* args) {
- if (!GetSyncService()) {
- DLOG(WARNING) << "Cannot display sync UI when sync is disabled";
- CloseUI();
- return;
- }
-
- SigninManagerBase* signin =
- SigninManagerFactory::GetForProfile(GetProfile());
- if (!signin->IsAuthenticated()) {
- // For web-based signin, the signin page is not displayed in an overlay
- // on the settings page. So if we get here, it must be due to the user
- // cancelling signin (by reloading the sync settings page during initial
- // signin) or by directly navigating to settings/syncSetup
- // (http://crbug.com/229836). So just exit and go back to the settings page.
- DLOG(WARNING) << "Cannot display sync setup UI when not signed in";
- CloseUI();
- return;
- }
-
- // If a setup wizard is already present, but not on this page, close the
- // blank setup overlay on this page by showing the "done" page. This can
- // happen if the user navigates to chrome://settings/syncSetup in more than
- // one tab. See crbug.com/261566.
- // Note: The following block will transfer focus to the existing wizard.
- if (IsExistingWizardPresent() && !IsActiveLogin())
- CloseUI();
-
- // If a setup wizard is present on this page or another, bring it to focus.
- // Otherwise, display a new one on this page.
- if (!FocusExistingWizardIfPresent())
- OpenSyncSetup(false /* creating_supervised_user */);
-}
-
-#if defined(OS_CHROMEOS)
-// On ChromeOS, we need to sign out the user session to fix an auth error, so
-// the user goes through the real signin flow to generate a new auth token.
-void SyncSetupHandler::HandleAttemptUserExit(const base::ListValue* args) {
- chrome::AttemptUserExit();
-}
-#endif
-
-#if !defined(OS_CHROMEOS)
-void SyncSetupHandler::HandleStartSignin(const base::ListValue* args) {
- // Should only be called if the user is not already signed in or has an auth
- // error.
- DCHECK(
- !SigninManagerFactory::GetForProfile(GetProfile())->IsAuthenticated() ||
- SigninErrorControllerFactory::GetForProfile(GetProfile())->HasError());
- bool creating_supervised_user = false;
- args->GetBoolean(0, &creating_supervised_user);
- OpenSyncSetup(creating_supervised_user);
-}
-
-void SyncSetupHandler::HandleStopSyncing(const base::ListValue* args) {
- if (GetSyncService())
- ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS);
-
- bool delete_profile = false;
- args->GetBoolean(0, &delete_profile);
- signin_metrics::SignoutDelete delete_metric =
- delete_profile ? signin_metrics::SignoutDelete::DELETED
- : signin_metrics::SignoutDelete::KEEPING;
- SigninManagerFactory::GetForProfile(GetProfile())
- ->SignOut(signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric);
-
- if (delete_profile) {
- // Do as BrowserOptionsHandler::DeleteProfile().
- webui::DeleteProfileAtPath(GetProfile()->GetPath(),
- web_ui(),
- ProfileMetrics::DELETE_PROFILE_SETTINGS);
- }
-}
-#endif
-
-void SyncSetupHandler::HandleCloseTimeout(const base::ListValue* args) {
- CloseSyncSetup();
-}
-
-void SyncSetupHandler::CloseSyncSetup() {
- // Stop a timer to handle timeout in waiting for checking network connection.
- engine_start_timer_.reset();
-
- // Clear the sync startup tracker, since the setup wizard is being closed.
- sync_startup_tracker_.reset();
-
- ProfileSyncService* sync_service = GetSyncService();
- if (IsActiveLogin()) {
- // Don't log a cancel event if the sync setup dialog is being
- // automatically closed due to an auth error.
- if (!sync_service || (!sync_service->IsFirstSetupComplete() &&
- sync_service->GetAuthError().state() ==
- GoogleServiceAuthError::NONE)) {
- if (configuring_sync_) {
- ProfileSyncService::SyncEvent(
- ProfileSyncService::CANCEL_DURING_CONFIGURE);
-
- // If the user clicked "Cancel" while setting up sync, disable sync
- // because we don't want the sync engine to remain in the
- // first-setup-incomplete state.
- // Note: In order to disable sync across restarts on Chrome OS,
- // we must call RequestStop(CLEAR_DATA), which suppresses sync startup
- // in addition to disabling it.
- if (sync_service) {
- DVLOG(1) << "Sync setup aborted by user action";
- sync_service->RequestStop(ProfileSyncService::CLEAR_DATA);
- #if !defined(OS_CHROMEOS)
- // Sign out the user on desktop Chrome if they click cancel during
- // initial setup.
- // TODO(rsimha): Revisit this for M30. See http://crbug.com/252049.
- if (sync_service->IsFirstSetupInProgress()) {
- SigninManagerFactory::GetForProfile(GetProfile())
- ->SignOut(signin_metrics::ABORT_SIGNIN,
- signin_metrics::SignoutDelete::IGNORE_METRIC);
- }
- #endif
- }
- }
- }
- }
-
- LoginUIService* service = GetLoginUIService();
- if (service)
- service->LoginUIClosed(this);
-
- // Alert the sync service anytime the sync setup dialog is closed. This can
- // happen due to the user clicking the OK or Cancel button, or due to the
- // dialog being closed by virtue of sync being disabled in the background.
- sync_blocker_.reset();
-
- configuring_sync_ = false;
-}
-
-void SyncSetupHandler::OpenSyncSetup(bool creating_supervised_user) {
- if (!PrepareSyncSetup())
- return;
-
- // There are several different UI flows that can bring the user here:
- // 1) Signin promo.
- // 2) Normal signin through settings page (IsAuthenticated() is false).
- // 3) Previously working credentials have expired.
- // 4) User is signed in, but has stopped sync via the google dashboard, and
- // signout is prohibited by policy so we need to force a re-auth.
- // 5) User clicks [Advanced Settings] button on options page while already
- // logged in.
- // 6) One-click signin (credentials are already available, so should display
- // sync configure UI, not login UI).
- // 7) User re-enables sync after disabling it via advanced settings.
-#if !defined(OS_CHROMEOS)
- SigninManagerBase* signin =
- SigninManagerFactory::GetForProfile(GetProfile());
-
- if (!signin->IsAuthenticated() ||
- SigninErrorControllerFactory::GetForProfile(GetProfile())->HasError()) {
- // User is not logged in (cases 1-2), or login has been specially requested
- // because previously working credentials have expired (case 3). Close sync
- // setup including any visible overlays, and display the gaia auth page.
- // Control will be returned to the sync settings page once auth is complete.
- CloseUI();
- DisplayGaiaLogin(
- creating_supervised_user ?
- signin_metrics::AccessPoint::ACCESS_POINT_SUPERVISED_USER :
- signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS);
- return;
- }
-#endif
- if (!GetSyncService()) {
- // This can happen if the user directly navigates to /settings/syncSetup.
- DLOG(WARNING) << "Cannot display sync UI when sync is disabled";
- CloseUI();
- return;
- }
-
- // User is already logged in. They must have brought up the config wizard
- // via the "Advanced..." button or through One-Click signin (cases 4-6), or
- // they are re-enabling sync after having disabled it (case 7).
- DisplayConfigureSync(false);
-}
-
-void SyncSetupHandler::OpenConfigureSync() {
- if (!PrepareSyncSetup())
- return;
-
- DisplayConfigureSync(false);
-}
-
-void SyncSetupHandler::FocusUI() {
- DCHECK(IsActiveLogin());
- WebContents* web_contents = web_ui()->GetWebContents();
- web_contents->GetDelegate()->ActivateContents(web_contents);
-}
-
-void SyncSetupHandler::CloseUI() {
- CloseSyncSetup();
- base::Value page("done");
- web_ui()->CallJavascriptFunctionUnsafe("SyncSetupOverlay.showSyncSetupPage",
- page);
-}
-
-bool SyncSetupHandler::IsExistingWizardPresent() {
- LoginUIService* service = GetLoginUIService();
- DCHECK(service);
- return service->current_login_ui() != NULL;
-}
-
-bool SyncSetupHandler::FocusExistingWizardIfPresent() {
- if (!IsExistingWizardPresent())
- return false;
-
- LoginUIService* service = GetLoginUIService();
- DCHECK(service);
- service->current_login_ui()->FocusUI();
- return true;
-}
-
-void SyncSetupHandler::DisplayConfigureSync(bool passphrase_failed) {
- // Should never call this when we are not signed in.
- DCHECK(SigninManagerFactory::GetForProfile(
- GetProfile())->IsAuthenticated());
- ProfileSyncService* service = GetSyncService();
- DCHECK(service);
- if (!service->IsEngineInitialized()) {
- service->RequestStart();
-
- // See if it's even possible to bring up the sync engine - if not
- // (unrecoverable error?), don't bother displaying a spinner that will be
- // immediately closed because this leads to some ugly infinite UI loop (see
- // http://crbug.com/244769).
- if (SyncStartupTracker::GetSyncServiceState(GetProfile()) !=
- SyncStartupTracker::SYNC_STARTUP_ERROR) {
- DisplaySpinner();
- }
-
- // Start SyncSetupTracker to wait for sync to initialize.
- sync_startup_tracker_.reset(
- new SyncStartupTracker(GetProfile(), this));
- return;
- }
-
- // Should only get here if user is signed in and sync is initialized, so no
- // longer need a SyncStartupTracker.
- sync_startup_tracker_.reset();
- configuring_sync_ = true;
- DCHECK(service->IsEngineInitialized())
- << "Cannot configure sync until the sync engine is initialized";
-
- // Setup args for the sync configure screen:
- // syncAllDataTypes: true if the user wants to sync everything
- // syncNothing: true if the user wants to sync nothing
- // <data_type>Registered: true if the associated data type is supported
- // <data_type>Synced: true if the user wants to sync that specific data type
- // paymentsIntegrationEnabled: true if the user wants Payments integration
- // encryptionEnabled: true if sync supports encryption
- // encryptAllData: true if user wants to encrypt all data (not just
- // passwords)
- // usePassphrase: true if the data is encrypted with a secondary passphrase
- // show_passphrase: true if a passphrase is needed to decrypt the sync data
- base::DictionaryValue args;
-
- // Tell the UI layer which data types are registered/enabled by the user.
- const syncer::ModelTypeSet registered_types =
- service->GetRegisteredDataTypes();
- const syncer::ModelTypeSet preferred_types = service->GetPreferredDataTypes();
- const syncer::ModelTypeSet enforced_types = service->GetForcedDataTypes();
- syncer::ModelTypeNameMap type_names = syncer::GetUserSelectableTypeNameMap();
- for (syncer::ModelTypeNameMap::const_iterator it = type_names.begin();
- it != type_names.end(); ++it) {
- syncer::ModelType sync_type = it->first;
- const std::string key_name = it->second;
- args.SetBoolean(key_name + "Registered", registered_types.Has(sync_type));
- args.SetBoolean(key_name + "Synced", preferred_types.Has(sync_type));
- args.SetBoolean(key_name + "Enforced", enforced_types.Has(sync_type));
- // TODO(treib): How do we want to handle pref groups, i.e. when only some of
- // the sync types behind a checkbox are force-enabled? crbug.com/403326
- }
- PrefService* pref_service = GetProfile()->GetPrefs();
- syncer::SyncPrefs sync_prefs(pref_service);
- args.SetBoolean("passphraseFailed", passphrase_failed);
- args.SetBoolean("syncAllDataTypes", sync_prefs.HasKeepEverythingSynced());
- args.SetBoolean("syncNothing", false); // Always false during initial setup.
- args.SetBoolean(
- "paymentsIntegrationEnabled",
- pref_service->GetBoolean(autofill::prefs::kAutofillWalletImportEnabled));
- args.SetBoolean("encryptAllData", service->IsEncryptEverythingEnabled());
- args.SetBoolean("encryptAllDataAllowed",
- service->IsEncryptEverythingAllowed());
-
- // We call IsPassphraseRequired() here, instead of calling
- // IsPassphraseRequiredForDecryption(), because we want to show the passphrase
- // UI even if no encrypted data types are enabled.
- args.SetBoolean("showPassphrase", service->IsPassphraseRequired());
-
- // To distinguish between FROZEN_IMPLICIT_PASSPHRASE and CUSTOM_PASSPHRASE
- // we only set usePassphrase for PassphraseType::CUSTOM_PASSPHRASE.
- args.SetBoolean("usePassphrase",
- service->GetPassphraseType() ==
- syncer::PassphraseType::CUSTOM_PASSPHRASE);
- base::Time passphrase_time = service->GetExplicitPassphraseTime();
- syncer::PassphraseType passphrase_type = service->GetPassphraseType();
- if (!passphrase_time.is_null()) {
- base::string16 passphrase_time_str =
- base::TimeFormatShortDate(passphrase_time);
- args.SetString(
- "enterPassphraseBody",
- GetStringFUTF16(IDS_SYNC_ENTER_PASSPHRASE_BODY_WITH_DATE,
- passphrase_time_str));
- args.SetString(
- "enterGooglePassphraseBody",
- GetStringFUTF16(IDS_SYNC_ENTER_GOOGLE_PASSPHRASE_BODY_WITH_DATE,
- passphrase_time_str));
- switch (passphrase_type) {
- case syncer::PassphraseType::FROZEN_IMPLICIT_PASSPHRASE:
- args.SetString(
- "fullEncryptionBody",
- GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_GOOGLE_WITH_DATE,
- passphrase_time_str));
- break;
- case syncer::PassphraseType::CUSTOM_PASSPHRASE:
- args.SetString(
- "fullEncryptionBody",
- GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM_WITH_DATE,
- passphrase_time_str));
- break;
- default:
- args.SetString(
- "fullEncryptionBody",
- GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM));
- break;
- }
- } else if (passphrase_type == syncer::PassphraseType::CUSTOM_PASSPHRASE) {
- args.SetString(
- "fullEncryptionBody",
- GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM));
- } else {
- args.SetString(
- "fullEncryptionBody",
- GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_DATA));
- }
-
- base::Value page("configure");
- web_ui()->CallJavascriptFunctionUnsafe("SyncSetupOverlay.showSyncSetupPage",
- page, args);
-
- // Make sure the tab used for the Gaia sign in does not cover the settings
- // tab.
- FocusUI();
-}
-
-LoginUIService* SyncSetupHandler::GetLoginUIService() const {
- return LoginUIServiceFactory::GetForProfile(GetProfile());
-}
diff --git a/chromium/chrome/browser/ui/webui/options/sync_setup_handler.h b/chromium/chrome/browser/ui/webui/options/sync_setup_handler.h
deleted file mode 100644
index 993293f3633..00000000000
--- a/chromium/chrome/browser/ui/webui/options/sync_setup_handler.h
+++ /dev/null
@@ -1,175 +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_OPTIONS_SYNC_SETUP_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_OPTIONS_SYNC_SETUP_HANDLER_H_
-
-#include <memory>
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/timer/timer.h"
-#include "build/build_config.h"
-#include "chrome/browser/sync/sync_startup_tracker.h"
-#include "chrome/browser/ui/webui/options/options_ui.h"
-#include "chrome/browser/ui/webui/signin/login_ui_service.h"
-
-class LoginUIService;
-
-namespace browser_sync {
-class ProfileSyncService;
-} // namespace browser_sync
-
-namespace signin_metrics {
-enum class AccessPoint;
-} // namespace signin_metrics
-
-namespace syncer {
-class SyncSetupInProgressHandle;
-} // namespace syncer
-
-class SyncSetupHandler : public options::OptionsPageUIHandler,
- public SyncStartupTracker::Observer,
- public LoginUIService::LoginUI {
- public:
- SyncSetupHandler();
- ~SyncSetupHandler() override;
-
- // OptionsPageUIHandler implementation.
- void GetLocalizedValues(base::DictionaryValue* localized_strings) override;
- void RegisterMessages() override;
-
- // SyncStartupTracker::Observer implementation;
- void SyncStartupCompleted() override;
- void SyncStartupFailed() override;
-
- // LoginUIService::LoginUI implementation.
- void FocusUI() override;
-
- static void GetStaticLocalizedValues(
- base::DictionaryValue* localized_strings,
- content::WebUI* web_ui);
-
- // Initializes the sync setup flow and shows the setup UI.
- void OpenSyncSetup(bool creating_supervised_user);
-
- // Shows advanced configuration dialog without going through sign in dialog.
- // Kicks the sync engine if necessary with showing spinner dialog until it
- // gets ready.
- void OpenConfigureSync();
-
- // Terminates the sync setup flow.
- void CloseSyncSetup();
-
- protected:
- friend class SyncSetupHandlerTest;
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest,
- DisplayConfigureWithEngineDisabledAndCancel);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, HandleSetupUIWhenSyncDisabled);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, SelectCustomEncryption);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, ShowSyncSetupWhenNotSignedIn);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, SuccessfullySetPassphrase);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TestSyncEverything);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TestSyncNothing);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TestSyncAllManually);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TestPassphraseStillRequired);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TestSyncIndividualTypes);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TurnOnEncryptAll);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, TurnOnEncryptAllDisallowed);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerTest, UnsuccessfullySetPassphrase);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerNonCrosTest,
- UnrecoverableErrorInitializingSync);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerNonCrosTest,
- GaiaErrorInitializingSync);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerNonCrosTest, HandleCaptcha);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerNonCrosTest, HandleGaiaAuthFailure);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerNonCrosTest,
- SubmitAuthWithInvalidUsername);
- FRIEND_TEST_ALL_PREFIXES(SyncSetupHandlerFirstSigninTest, DisplayBasicLogin);
-
- bool is_configuring_sync() const { return configuring_sync_; }
-
- // Called when configuring sync is done to close the dialog and start syncing.
- void ConfigureSyncDone();
-
- // Helper routine that gets the ProfileSyncService associated with the parent
- // profile.
- browser_sync::ProfileSyncService* GetSyncService() const;
-
- // Returns the LoginUIService for the parent profile.
- LoginUIService* GetLoginUIService() const;
-
- private:
- // Callbacks from the page.
- void OnDidClosePage(const base::ListValue* args);
- void HandleConfigure(const base::ListValue* args);
- void HandlePassphraseEntry(const base::ListValue* args);
- void HandlePassphraseCancel(const base::ListValue* args);
- void HandleShowSetupUI(const base::ListValue* args);
- void HandleAttemptUserExit(const base::ListValue* args);
- void HandleStartSignin(const base::ListValue* args);
- void HandleStopSyncing(const base::ListValue* args);
- void HandleCloseTimeout(const base::ListValue* args);
-#if !defined(OS_CHROMEOS)
- // Displays the GAIA login form.
- void DisplayGaiaLogin(signin_metrics::AccessPoint access_point);
-
- // When web-flow is enabled, displays the Gaia login form in a new tab.
- // This function is virtual so that tests can override.
- virtual void DisplayGaiaLoginInNewTabOrWindow(
- signin_metrics::AccessPoint access_point);
-#endif
-
- // Helper routine that gets the Profile associated with this object (virtual
- // so tests can override).
- virtual Profile* GetProfile() const;
-
- // A utility function to call before actually showing setup dialog. Makes sure
- // that a new dialog can be shown and sets flag that setup is in progress.
- bool PrepareSyncSetup();
-
- // Displays spinner-only UI indicating that something is going on in the
- // background.
- // TODO(kochi): better to show some message that the user can understand what
- // is running in the background.
- void DisplaySpinner();
-
- // Displays an error dialog which shows timeout of starting the sync engine.
- void DisplayTimeout();
-
- // Closes the associated sync settings page.
- void CloseUI();
-
- // Returns true if this object is the active login object.
- bool IsActiveLogin() const;
-
- // If a wizard already exists, return true. Otherwise, return false.
- bool IsExistingWizardPresent();
-
- // If a wizard already exists, focus it and return true.
- bool FocusExistingWizardIfPresent();
-
- // Display the configure sync UI. If |passphrase_failed| is true, the account
- // requires a passphrase and one hasn't been provided or it was invalid.
- void DisplayConfigureSync(bool passphrase_failed);
-
- // Helper object used to wait for the sync engine to startup.
- std::unique_ptr<SyncStartupTracker> sync_startup_tracker_;
-
- // Prevents Sync from running until configuration is complete.
- std::unique_ptr<syncer::SyncSetupInProgressHandle> sync_blocker_;
-
- // Set to true whenever the sync configure UI is visible. This is used to tell
- // what stage of the setup wizard the user was in and to update the UMA
- // histograms in the case that the user cancels out.
- bool configuring_sync_;
-
- // The OneShotTimer object used to timeout of starting the sync engine
- // service.
- std::unique_ptr<base::OneShotTimer> engine_start_timer_;
-
- DISALLOW_COPY_AND_ASSIGN(SyncSetupHandler);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_SYNC_SETUP_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc
index 5315755617c..5cc0cefebf9 100644
--- a/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc
@@ -12,19 +12,18 @@ namespace policy_indicator {
void AddLocalizedStrings(content::WebUIDataSource* html_source) {
html_source->AddLocalizedString("controlledSettingPolicy",
- IDS_OPTIONS_CONTROLLED_SETTING_POLICY);
+ IDS_CONTROLLED_SETTING_POLICY);
html_source->AddLocalizedString("controlledSettingRecommendedMatches",
- IDS_OPTIONS_CONTROLLED_SETTING_RECOMMENDED);
- html_source->AddLocalizedString(
- "controlledSettingRecommendedDiffers",
- IDS_OPTIONS_CONTROLLED_SETTING_HAS_RECOMMENDATION);
+ IDS_CONTROLLED_SETTING_RECOMMENDED);
+ html_source->AddLocalizedString("controlledSettingRecommendedDiffers",
+ IDS_CONTROLLED_SETTING_HAS_RECOMMENDATION);
html_source->AddLocalizedString("controlledSettingExtension",
- IDS_OPTIONS_CONTROLLED_SETTING_EXTENSION);
+ IDS_CONTROLLED_SETTING_EXTENSION);
#if defined(OS_CHROMEOS)
html_source->AddLocalizedString("controlledSettingShared",
- IDS_OPTIONS_CONTROLLED_SETTING_SHARED);
+ IDS_CONTROLLED_SETTING_SHARED);
html_source->AddLocalizedString("controlledSettingOwner",
- IDS_OPTIONS_CONTROLLED_SETTING_OWNER);
+ IDS_CONTROLLED_SETTING_OWNER);
#endif
}
diff --git a/chromium/chrome/browser/ui/webui/policy_material_design_ui.cc b/chromium/chrome/browser/ui/webui/policy_material_design_ui.cc
deleted file mode 100644
index d6f0cccf381..00000000000
--- a/chromium/chrome/browser/ui/webui/policy_material_design_ui.cc
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright (c) 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/policy_material_design_ui.h"
-
-#include <stddef.h>
-#include <utility>
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/policy_ui_handler.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/policy_resources.h"
-#include "chrome/grit/policy_resources_map.h"
-#include "components/policy/core/common/policy_types.h"
-#include "components/policy/policy_constants.h"
-#include "components/policy/risk_tag.h"
-#include "components/strings/grit/components_strings.h"
-
-namespace {
-
-// Strings that map from policy::RiskTag enum to i18n string keys and their IDs.
-// Their order has to follow the order of the policy::RiskTag enum.
-const PolicyStringMap kPolicyRiskTags[policy::RISK_TAG_COUNT] = {
- {"fullAdminAccess", IDS_POLICY_RISK_TAG_FULL_ADMIN_ACCESS},
- {"systemSecurity", IDS_POLICY_RISK_TAG_SYSTEM_SECURITY},
- {"websiteSharing", IDS_POLICY_RISK_TAG_WEBSITE_SHARING},
- {"adminSharing", IDS_POLICY_RISK_TAG_ADMIN_SHARING},
- {"filtering", IDS_POLICY_RISK_TAG_FILTERING},
- {"localDataAccess", IDS_POLICY_RISK_TAG_LOCAL_DATA_ACCESS},
- {"googleSharing", IDS_POLICY_RISK_TAG_GOOGLE_SHARING},
-};
-
-content::WebUIDataSource* CreatePolicyMaterialDesignUIHtmlSource() {
- content::WebUIDataSource* source =
- content::WebUIDataSource::Create(chrome::kChromeUIMdPolicyHost);
- PolicyUIHandler::AddCommonLocalizedStringsToSource(source);
- PolicyUIHandler::AddLocalizedPolicyStrings(
- source, kPolicyRiskTags, static_cast<size_t>(policy::RISK_TAG_COUNT));
- for (size_t i = 0; i < kPolicyResourcesSize; ++i) {
- source->AddResourcePath(kPolicyResources[i].name,
- kPolicyResources[i].value);
- }
- source->SetDefaultResource(IDR_MD_POLICY_HTML);
- return source;
-}
-
-} // namespace
-
-// The JavaScript message handler for the chrome://md-policy page.
-class PolicyMaterialDesignUIHandler : public PolicyUIHandler {
- public:
- PolicyMaterialDesignUIHandler();
- ~PolicyMaterialDesignUIHandler() override;
-
- protected:
- // PolicyUIHandler:
- void AddPolicyName(const std::string& name,
- base::DictionaryValue* names) const override;
- void SendPolicyNames() const override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(PolicyMaterialDesignUIHandler);
-};
-
-PolicyMaterialDesignUIHandler::PolicyMaterialDesignUIHandler() {
-}
-
-PolicyMaterialDesignUIHandler::~PolicyMaterialDesignUIHandler() {
-}
-
-void PolicyMaterialDesignUIHandler::AddPolicyName(
- const std::string& name, base::DictionaryValue* names) const {
- std::unique_ptr<base::ListValue> list(new base::ListValue());
- const policy::RiskTag* tags = policy::GetChromePolicyDetails(name)->risk_tags;
- for (size_t i = 0; i < policy::kMaxRiskTagCount; ++i) {
- if (tags[i] != policy::RISK_TAG_NONE)
- list->AppendString(kPolicyRiskTags[tags[i]].key);
- }
- names->SetWithoutPathExpansion(name, std::move(list));
-}
-
-void PolicyMaterialDesignUIHandler::SendPolicyNames() const {
- base::ListValue tags;
- for (size_t tag = 0; tag < policy::RISK_TAG_COUNT; ++tag)
- tags.AppendString(kPolicyRiskTags[tag].key);
-
- web_ui()->CallJavascriptFunctionUnsafe("policy.Page.setPolicyGroups", tags);
- PolicyUIHandler::SendPolicyNames();
-}
-
-PolicyMaterialDesignUI::PolicyMaterialDesignUI(content::WebUI* web_ui) :
- WebUIController(web_ui) {
- web_ui->AddMessageHandler(base::MakeUnique<PolicyMaterialDesignUIHandler>());
- content::WebUIDataSource::Add(Profile::FromWebUI(web_ui),
- CreatePolicyMaterialDesignUIHtmlSource());
-}
-
-PolicyMaterialDesignUI::~PolicyMaterialDesignUI() {
-}
diff --git a/chromium/chrome/browser/ui/webui/policy_material_design_ui.h b/chromium/chrome/browser/ui/webui/policy_material_design_ui.h
deleted file mode 100644
index ecf7eb1a678..00000000000
--- a/chromium/chrome/browser/ui/webui/policy_material_design_ui.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_POLICY_MATERIAL_DESIGN_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_POLICY_MATERIAL_DESIGN_UI_H_
-
-#include "base/macros.h"
-#include "content/public/browser/web_ui_controller.h"
-
-namespace content {
-class WebUI;
-}
-
-// The Web UI controller for the chrome://md-policy page.
-class PolicyMaterialDesignUI : public content::WebUIController {
- public:
- explicit PolicyMaterialDesignUI(content::WebUI* web_ui);
- ~PolicyMaterialDesignUI() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(PolicyMaterialDesignUI);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_POLICY_MATERIAL_DESIGN_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/policy_ui.cc b/chromium/chrome/browser/ui/webui/policy_ui.cc
index 35c90bc0941..855530dff07 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui.cc
@@ -5,6 +5,7 @@
#include "chrome/browser/ui/webui/policy_ui.h"
#include "base/memory/ptr_util.h"
+#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/policy_ui_handler.h"
#include "chrome/common/url_constants.h"
@@ -21,6 +22,7 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
source->AddLocalizedString("filterPlaceholder",
IDS_POLICY_FILTER_PLACEHOLDER);
source->AddLocalizedString("reloadPolicies", IDS_POLICY_RELOAD_POLICIES);
+ source->AddLocalizedString("exportPoliciesJSON", IDS_EXPORT_POLICIES_JSON);
source->AddLocalizedString("chromeForWork", IDS_POLICY_CHROME_FOR_WORK);
source->AddLocalizedString("status", IDS_POLICY_STATUS);
source->AddLocalizedString("statusDevice", IDS_POLICY_STATUS_DEVICE);
@@ -47,7 +49,11 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
source->AddLocalizedString("hideExpandedValue",
IDS_POLICY_HIDE_EXPANDED_VALUE);
// Add required resources.
+#if !defined(OS_ANDROID)
+ source->AddResourcePath("policy_common.css", IDR_POLICY_COMMON_CSS);
+#endif
source->AddResourcePath("policy.css", IDR_POLICY_CSS);
+ source->AddResourcePath("policy_base.js", IDR_POLICY_BASE_JS);
source->AddResourcePath("policy.js", IDR_POLICY_JS);
source->SetDefaultResource(IDR_POLICY_HTML);
return source;
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc
index 38dbbb45d6f..fd94cc90af9 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc
@@ -11,6 +11,7 @@
#include "base/callback.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
+#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
@@ -38,6 +39,9 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
+#include "ui/shell_dialogs/select_file_dialog.h"
+#include "ui/shell_dialogs/select_file_dialog_factory.h"
+#include "ui/shell_dialogs/select_file_policy.h"
#include "url/gurl.h"
using testing::Return;
@@ -93,6 +97,23 @@ std::vector<std::string> PopulateExpectedPolicy(
return expected_policy;
}
+void SetExpectedPolicy(base::DictionaryValue* expected,
+ const std::string& name,
+ const std::string& level,
+ const std::string& scope,
+ const std::string& source,
+ const base::Value& value) {
+ const char prefix[] = "chromePolicies";
+ expected->SetPath({prefix, name.c_str(), "level"}, base::Value(level));
+ expected->SetPath({prefix, name.c_str(), "scope"}, base::Value(scope));
+ expected->SetPath({prefix, name.c_str(), "source"}, base::Value(source));
+ expected->SetPath({prefix, name.c_str(), "value"}, value.Clone());
+}
+
+// The temporary directory and file paths for policy saving.
+base::ScopedTempDir export_policies_test_dir;
+base::FilePath export_policies_test_file_path;
+
} // namespace
class PolicyUITest : public InProcessBrowserTest {
@@ -108,6 +129,8 @@ class PolicyUITest : public InProcessBrowserTest {
void VerifyPolicies(const std::vector<std::vector<std::string> >& expected);
+ void VerifyExportingPolicies(const base::DictionaryValue& expected);
+
protected:
policy::MockConfigurationPolicyProvider provider_;
@@ -115,6 +138,47 @@ class PolicyUITest : public InProcessBrowserTest {
DISALLOW_COPY_AND_ASSIGN(PolicyUITest);
};
+// An artificial SelectFileDialog that immediately returns the location of test
+// file instead of showing the UI file picker.
+class TestSelectFileDialog : public ui::SelectFileDialog {
+ public:
+ TestSelectFileDialog(ui::SelectFileDialog::Listener* listener,
+ std::unique_ptr<ui::SelectFilePolicy> policy)
+ : ui::SelectFileDialog(listener, std::move(policy)) {}
+
+ void SelectFileImpl(Type type,
+ const base::string16& title,
+ const base::FilePath& default_path,
+ const FileTypeInfo* file_types,
+ int file_type_index,
+ const base::FilePath::StringType& default_extension,
+ gfx::NativeWindow owning_window,
+ void* params) override {
+ listener_->FileSelected(export_policies_test_file_path, 0, nullptr);
+ }
+
+ bool IsRunning(gfx::NativeWindow owning_window) const override {
+ return false;
+ }
+
+ void ListenerDestroyed() override {}
+
+ bool HasMultipleFileTypeChoicesImpl() override { return false; }
+
+ private:
+ ~TestSelectFileDialog() override {}
+};
+
+// A factory associated with the artificial file picker.
+class TestSelectFileDialogFactory : public ui::SelectFileDialogFactory {
+ private:
+ ui::SelectFileDialog* Create(
+ ui::SelectFileDialog::Listener* listener,
+ std::unique_ptr<ui::SelectFilePolicy> policy) override {
+ return new TestSelectFileDialog(listener, std::move(policy));
+ }
+};
+
PolicyUITest::PolicyUITest() {
}
@@ -125,6 +189,12 @@ void PolicyUITest::SetUpInProcessBrowserTestFixture() {
EXPECT_CALL(provider_, IsInitializationComplete(_))
.WillRepeatedly(Return(true));
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
+
+ // Create a directory for testing exporting policies.
+ ASSERT_TRUE(export_policies_test_dir.CreateUniqueTempDir());
+ const std::string filename = "policy.json";
+ export_policies_test_file_path =
+ export_policies_test_dir.GetPath().AppendASCII(filename);
}
void PolicyUITest::UpdateProviderPolicy(const policy::PolicyMap& policy) {
@@ -183,6 +253,119 @@ void PolicyUITest::VerifyPolicies(
}
}
+void PolicyUITest::VerifyExportingPolicies(
+ const base::DictionaryValue& expected) {
+ // Set SelectFileDialog to use our factory.
+ ui::SelectFileDialog::SetFactory(new TestSelectFileDialogFactory());
+
+ // Navigate to the about:policy page.
+ ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy"));
+
+ // Click on 'save policies' button.
+ const std::string javascript =
+ "document.getElementById(\"export-policies\").click()";
+
+ content::WebContents* contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ EXPECT_TRUE(content::ExecuteScript(contents, javascript));
+
+ base::TaskScheduler::GetInstance()->FlushForTesting();
+ // Open the created file.
+ base::ThreadRestrictions::ScopedAllowIO allow_io;
+ std::string file_contents;
+ EXPECT_TRUE(
+ base::ReadFileToString(export_policies_test_file_path, &file_contents));
+
+ std::unique_ptr<base::Value> value_ptr =
+ base::JSONReader::Read(file_contents);
+
+ // Check that the file contains a valid dictionary.
+ EXPECT_TRUE(value_ptr.get());
+ base::DictionaryValue* actual_policies = nullptr;
+ EXPECT_TRUE(value_ptr->GetAsDictionary(&actual_policies));
+
+ // Check that this dictionary is the same as expected.
+ EXPECT_EQ(expected, *actual_policies);
+}
+
+IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) {
+ // Set policy values and generate expected dictionary.
+ policy::PolicyMap values;
+ base::DictionaryValue expected_values;
+
+ base::ListValue popups_blocked_for_urls;
+ popups_blocked_for_urls.AppendString("aaa");
+ popups_blocked_for_urls.AppendString("bbb");
+ popups_blocked_for_urls.AppendString("ccc");
+ values.Set(policy::key::kPopupsBlockedForUrls, policy::POLICY_LEVEL_MANDATORY,
+ policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM,
+ popups_blocked_for_urls.CreateDeepCopy(), nullptr);
+ SetExpectedPolicy(&expected_values, policy::key::kPopupsBlockedForUrls,
+ "mandatory", "machine", "sourcePlatform",
+ popups_blocked_for_urls);
+
+ values.Set(policy::key::kDefaultImagesSetting, policy::POLICY_LEVEL_MANDATORY,
+ policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
+ base::MakeUnique<base::Value>(2), nullptr);
+ SetExpectedPolicy(&expected_values, policy::key::kDefaultImagesSetting,
+ "mandatory", "machine", "sourceCloud", base::Value(2));
+
+ // This also checks that we save complex policies correctly.
+ base::DictionaryValue unknown_policy;
+ base::DictionaryValue body;
+ body.SetInteger("first", 0);
+ body.SetBoolean("second", true);
+ unknown_policy.SetInteger("head", 12);
+ unknown_policy.SetDictionary("body", body.CreateDeepCopy());
+ const std::string kUnknownPolicy = "NoSuchThing";
+ values.Set(kUnknownPolicy, policy::POLICY_LEVEL_RECOMMENDED,
+ policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
+ unknown_policy.CreateDeepCopy(), nullptr);
+ SetExpectedPolicy(&expected_values, kUnknownPolicy, "recommended", "user",
+ "sourceCloud", unknown_policy);
+
+ // Set the extension policies to an empty dictionary as we haven't added any
+ // such policies.
+ expected_values.SetDictionary("extensionPolicies",
+ base::MakeUnique<base::DictionaryValue>());
+
+ UpdateProviderPolicy(values);
+
+ // Check writing those policies to a newly created file.
+ VerifyExportingPolicies(expected_values);
+
+ // Change policy values.
+ values.Erase(policy::key::kDefaultImagesSetting);
+ expected_values.RemovePath(
+ std::string("chromePolicies.") +
+ std::string(policy::key::kDefaultImagesSetting),
+ nullptr);
+
+ // This also checks that we bypass the policy that blocks file selection
+ // dialogs.
+ values.Set(policy::key::kAllowFileSelectionDialogs,
+ policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
+ policy::POLICY_SOURCE_PLATFORM,
+ base::MakeUnique<base::Value>(false), nullptr);
+ SetExpectedPolicy(&expected_values, policy::key::kAllowFileSelectionDialogs,
+ "mandatory", "machine", "sourcePlatform",
+ base::Value(false));
+
+ popups_blocked_for_urls.AppendString("ddd");
+ values.Set(policy::key::kPopupsBlockedForUrls, policy::POLICY_LEVEL_MANDATORY,
+ policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM,
+ popups_blocked_for_urls.CreateDeepCopy(), nullptr);
+ SetExpectedPolicy(&expected_values, policy::key::kPopupsBlockedForUrls,
+ "mandatory", "machine", "sourcePlatform",
+ popups_blocked_for_urls);
+
+ UpdateProviderPolicy(values);
+
+ // Check writing changed policies to the same file (should overwrite the
+ // contents).
+ VerifyExportingPolicies(expected_values);
+}
+
IN_PROC_BROWSER_TEST_F(PolicyUITest, SendPolicyNames) {
// Verifies that the names of known policies are sent to the UI and processed
// there correctly by checking that the policy table contains all policies in
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
index 8f3a4dca664..9e74f6e8f1b 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
@@ -12,16 +12,20 @@
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
+#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string16.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/task_scheduler/task_traits.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
+#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/profile_policy_connector_factory.h"
#include "chrome/browser/policy/schema_registry_service.h"
@@ -50,6 +54,7 @@
#include "google_apis/gaia/gaia_auth_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/time_format.h"
+#include "ui/shell_dialogs/select_file_policy.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/browser_process_platform_part.h"
@@ -180,9 +185,13 @@ std::unique_ptr<base::Value> DictionaryToJSONString(
return base::MakeUnique<base::Value>(json_string);
}
-// Returns a copy of |value| with some values converted to a representation that
-// i18n_template.js will display in a nicer way.
-std::unique_ptr<base::Value> CopyAndConvert(const base::Value* value) {
+// Returns a copy of |value|. If necessary (which is specified by
+// |convert_values|), converts some values to a representation that
+// i18n_template.js will display.
+std::unique_ptr<base::Value> CopyAndMaybeConvert(const base::Value* value,
+ bool convert_values) {
+ if (!convert_values)
+ return value->CreateDeepCopy();
const base::DictionaryValue* dict = NULL;
if (value->GetAsDictionary(&dict))
return DictionaryToJSONString(*dict);
@@ -597,6 +606,10 @@ void PolicyUIHandler::RegisterMessages() {
"reloadPolicies",
base::Bind(&PolicyUIHandler::HandleReloadPolicies,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "exportPoliciesJSON",
+ base::Bind(&PolicyUIHandler::HandleExportPoliciesJSON,
+ base::Unretained(this)));
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
@@ -632,7 +645,7 @@ void PolicyUIHandler::OnPolicyUpdated(const policy::PolicyNamespace& ns,
void PolicyUIHandler::AddPolicyName(const std::string& name,
base::DictionaryValue* names) const {
- names->SetBooleanWithoutPathExpansion(name, true);
+ names->SetKey(name, base::Value(true));
}
void PolicyUIHandler::SendPolicyNames() const {
@@ -687,12 +700,13 @@ void PolicyUIHandler::SendPolicyNames() const {
web_ui()->CallJavascriptFunctionUnsafe("policy.Page.setPolicyNames", names);
}
-void PolicyUIHandler::SendPolicyValues() const {
+std::unique_ptr<base::DictionaryValue> PolicyUIHandler::GetAllPolicyValues(
+ bool convert_values) const {
base::DictionaryValue all_policies;
// Add Chrome policy values.
auto chrome_policies = base::MakeUnique<base::DictionaryValue>();
- GetChromePolicyValues(chrome_policies.get());
+ GetChromePolicyValues(chrome_policies.get(), convert_values);
all_policies.Set("chromePolicies", std::move(chrome_policies));
#if BUILDFLAG(ENABLE_EXTENSIONS)
@@ -712,21 +726,29 @@ void PolicyUIHandler::SendPolicyValues() const {
policy::POLICY_DOMAIN_EXTENSIONS, extension->id());
policy::PolicyErrorMap empty_error_map;
GetPolicyValues(GetPolicyService()->GetPolicies(policy_namespace),
- &empty_error_map, extension_policies.get());
+ &empty_error_map, extension_policies.get(), convert_values);
extension_values->Set(extension->id(), std::move(extension_policies));
}
all_policies.Set("extensionPolicies", std::move(extension_values));
#endif
+ return base::MakeUnique<base::DictionaryValue>(std::move(all_policies));
+}
+
+void PolicyUIHandler::SendPolicyValues() const {
+ std::unique_ptr<base::DictionaryValue> all_policies =
+ GetAllPolicyValues(true);
web_ui()->CallJavascriptFunctionUnsafe("policy.Page.setPolicyValues",
- all_policies);
+ *all_policies);
}
void PolicyUIHandler::GetPolicyValues(const policy::PolicyMap& map,
policy::PolicyErrorMap* errors,
- base::DictionaryValue* values) const {
+ base::DictionaryValue* values,
+ bool convert_values) const {
for (const auto& entry : map) {
std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
- value->Set("value", CopyAndConvert(entry.second.value.get()));
+ value->Set("value",
+ CopyAndMaybeConvert(entry.second.value.get(), convert_values));
if (entry.second.scope == policy::POLICY_SCOPE_USER)
value->SetString("scope", "user");
else
@@ -743,8 +765,8 @@ void PolicyUIHandler::GetPolicyValues(const policy::PolicyMap& map,
}
}
-void PolicyUIHandler::GetChromePolicyValues(
- base::DictionaryValue* values) const {
+void PolicyUIHandler::GetChromePolicyValues(base::DictionaryValue* values,
+ bool convert_values) const {
policy::PolicyService* policy_service = GetPolicyService();
policy::PolicyMap map;
@@ -762,7 +784,7 @@ void PolicyUIHandler::GetChromePolicyValues(
// Convert dictionary values to strings for display.
handler_list->PrepareForDisplaying(&map);
- GetPolicyValues(map, &errors, values);
+ GetPolicyValues(map, &errors, values, convert_values);
}
void PolicyUIHandler::SendStatus() const {
@@ -815,6 +837,70 @@ 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::WritePoliciesToJSONFile(
+ const base::FilePath& path) const {
+ std::unique_ptr<base::DictionaryValue> all_policies =
+ GetAllPolicyValues(false);
+ std::string json_policies =
+ DictionaryToJSONString(*all_policies)->GetString();
+
+ base::PostTaskWithTraits(
+ FROM_HERE,
+ {base::MayBlock(), base::TaskPriority::BACKGROUND,
+ base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
+ base::BindOnce(&DoWritePoliciesToJSONFile, path, json_policies));
+}
+
+void PolicyUIHandler::FileSelected(const base::FilePath& path,
+ int index,
+ void* params) {
+ DCHECK(export_policies_select_file_dialog_);
+
+ WritePoliciesToJSONFile(path);
+
+ export_policies_select_file_dialog_ = nullptr;
+}
+
+void PolicyUIHandler::FileSelectionCanceled(void* params) {
+ DCHECK(export_policies_select_file_dialog_);
+ export_policies_select_file_dialog_ = nullptr;
+}
+
+void PolicyUIHandler::HandleExportPoliciesJSON(const base::ListValue* args) {
+ // If the "select file" dialog window is already opened, we don't want to open
+ // it again.
+ if (export_policies_select_file_dialog_)
+ return;
+
+ content::WebContents* webcontents = web_ui()->GetWebContents();
+
+ // Building initial path based on download preferences.
+ base::FilePath initial_dir =
+ DownloadPrefs::FromBrowserContext(webcontents->GetBrowserContext())
+ ->DownloadPath();
+ base::FilePath initial_path =
+ initial_dir.Append(FILE_PATH_LITERAL("policies.json"));
+
+ // Here we overwrite the actual value of SelectFileDialog policy by passing a
+ // nullptr to ui::SelectFileDialog::Create instead of the actual policy value.
+ // This is done for the following reason: the admin might want to set this
+ // policy for the user to forbid the select file dialogs, but this shouldn't
+ // block the possibility to export the policies.
+ export_policies_select_file_dialog_ = ui::SelectFileDialog::Create(
+ this, std::unique_ptr<ui::SelectFilePolicy>());
+ ui::SelectFileDialog::FileTypeInfo file_type_info;
+ file_type_info.extensions = {{FILE_PATH_LITERAL("json")}};
+ gfx::NativeWindow owning_window = webcontents->GetTopLevelNativeWindow();
+ export_policies_select_file_dialog_->SelectFile(
+ ui::SelectFileDialog::SELECT_SAVEAS_FILE, base::string16(), initial_path,
+ &file_type_info, 0, base::FilePath::StringType(), owning_window, nullptr);
+}
+
void PolicyUIHandler::OnRefreshPoliciesDone() const {
web_ui()->CallJavascriptFunctionUnsafe("policy.Page.reloadPoliciesDone");
}
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.h b/chromium/chrome/browser/ui/webui/policy_ui_handler.h
index 1201ce0de84..e181e42208e 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_handler.h
+++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.h
@@ -21,6 +21,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "extensions/features/features.h"
+#include "ui/shell_dialogs/select_file_dialog.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/browser/extension_registry_observer.h"
@@ -39,7 +40,8 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
public extensions::ExtensionRegistryObserver,
#endif
public policy::PolicyService::Observer,
- public policy::SchemaRegistry::Observer {
+ public policy::SchemaRegistry::Observer,
+ public ui::SelectFileDialog::Listener {
public:
PolicyUIHandler();
~PolicyUIHandler() override;
@@ -79,6 +81,12 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
// Send a dictionary containing the names of all known policies to the UI.
virtual void SendPolicyNames() const;
+ // ui::SelectFileDialog::Listener implementation.
+ void FileSelected(const base::FilePath& path,
+ int index,
+ void* params) override;
+ void FileSelectionCanceled(void* params) override;
+
private:
// 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
@@ -91,15 +99,26 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
void SendStatus() const;
// Inserts a description of each policy in |policy_map| into |values|, using
- // the optional errors in |errors| to determine the status of each policy.
+ // the optional errors in |errors| to determine the status of each policy. If
+ // |convert_values| is true, converts the values to show them in javascript.
void GetPolicyValues(const policy::PolicyMap& policy_map,
policy::PolicyErrorMap* errors,
- base::DictionaryValue* values) const;
+ base::DictionaryValue* values,
+ bool convert_values) const;
+
+ // Returns a dictionary with the values of all set policies, with some values
+ // converted to be shown in javascript, if it is specified.
+ std::unique_ptr<base::DictionaryValue> GetAllPolicyValues(
+ bool convert_values) const;
- void GetChromePolicyValues(base::DictionaryValue* values) const;
+ void GetChromePolicyValues(base::DictionaryValue* values,
+ bool convert_values) const;
+
+ void WritePoliciesToJSONFile(const base::FilePath& path) const;
void HandleInitialized(const base::ListValue* args);
void HandleReloadPolicies(const base::ListValue* args);
+ void HandleExportPoliciesJSON(const base::ListValue* args);
void OnRefreshPoliciesDone() const;
@@ -107,6 +126,8 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
std::string device_domain_;
+ scoped_refptr<ui::SelectFileDialog> export_policies_select_file_dialog_;
+
// Providers that supply status dictionaries for user and device policy,
// respectively. These are created on initialization time as appropriate for
// the platform (Chrome OS / desktop) and type of policy that is in effect.
diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc
index af7cbcc2d35..b584ae74afe 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc
@@ -18,6 +18,7 @@
#include "base/strings/string_split.h"
#include "base/task_scheduler/post_task.h"
#include "chrome/browser/printing/pwg_raster_converter.h"
+#include "chrome/browser/profiles/profile.h"
#include "components/cloud_devices/common/cloud_device_description.h"
#include "components/cloud_devices/common/printer_description.h"
#include "device/base/device_client.h"
@@ -120,9 +121,8 @@ bool ParseProvisionalUsbPrinterId(const std::string& printer_id,
} // namespace
-ExtensionPrinterHandler::ExtensionPrinterHandler(
- content::BrowserContext* browser_context)
- : browser_context_(browser_context), weak_ptr_factory_(this) {}
+ExtensionPrinterHandler::ExtensionPrinterHandler(Profile* profile)
+ : profile_(profile), weak_ptr_factory_(this) {}
ExtensionPrinterHandler::~ExtensionPrinterHandler() {
}
@@ -141,7 +141,7 @@ void ExtensionPrinterHandler::StartGetPrinters(
pending_enumeration_count_ = 1;
bool extension_supports_usb_printers = false;
- ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
+ ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
for (const auto& extension : registry->enabled_extensions()) {
if (UsbPrinterManifestData::Get(extension.get()) &&
HasUsbPrinterProviderPermissions(extension.get())) {
@@ -159,7 +159,7 @@ void ExtensionPrinterHandler::StartGetPrinters(
}
extensions::PrinterProviderAPIFactory::GetInstance()
- ->GetForBrowserContext(browser_context_)
+ ->GetForBrowserContext(profile_)
->DispatchGetPrintersRequested(
base::Bind(&ExtensionPrinterHandler::WrapGetPrintersCallback,
weak_ptr_factory_.GetWeakPtr(), callback));
@@ -169,7 +169,7 @@ void ExtensionPrinterHandler::StartGetCapability(
const std::string& destination_id,
const PrinterHandler::GetCapabilityCallback& callback) {
extensions::PrinterProviderAPIFactory::GetInstance()
- ->GetForBrowserContext(browser_context_)
+ ->GetForBrowserContext(profile_)
->DispatchGetCapabilityRequested(
destination_id,
base::Bind(&ExtensionPrinterHandler::WrapGetCapabilityCallback,
@@ -182,10 +182,9 @@ void ExtensionPrinterHandler::StartPrint(
const base::string16& job_title,
const std::string& ticket_json,
const gfx::Size& page_size,
- const scoped_refptr<base::RefCountedMemory>& print_data,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
const PrinterHandler::PrintCallback& callback) {
- std::unique_ptr<extensions::PrinterProviderPrintJob> print_job(
- new extensions::PrinterProviderPrintJob());
+ auto print_job = base::MakeUnique<extensions::PrinterProviderPrintJob>();
print_job->printer_id = destination_id;
print_job->job_title = job_title;
print_job->ticket_json = ticket_json;
@@ -239,11 +238,11 @@ void ExtensionPrinterHandler::StartGrantPrinterAccess(
}
DevicePermissionsManager* permissions_manager =
- DevicePermissionsManager::Get(browser_context_);
+ DevicePermissionsManager::Get(profile_);
permissions_manager->AllowUsbDevice(extension_id, device);
extensions::PrinterProviderAPIFactory::GetInstance()
- ->GetForBrowserContext(browser_context_)
+ ->GetForBrowserContext(profile_)
->DispatchGetUsbPrinterInfoRequested(
extension_id, device,
base::Bind(&ExtensionPrinterHandler::WrapGetPrinterInfoCallback,
@@ -281,7 +280,7 @@ void ExtensionPrinterHandler::DispatchPrintJob(
}
extensions::PrinterProviderAPIFactory::GetInstance()
- ->GetForBrowserContext(browser_context_)
+ ->GetForBrowserContext(profile_)
->DispatchPrintRequested(
*print_job, base::Bind(&ExtensionPrinterHandler::WrapPrintCallback,
weak_ptr_factory_.GetWeakPtr(), callback));
@@ -308,7 +307,7 @@ void ExtensionPrinterHandler::WrapPrintCallback(
const PrinterHandler::PrintCallback& callback,
bool success,
const std::string& status) {
- callback.Run(success, status);
+ callback.Run(success, base::Value(status));
}
void ExtensionPrinterHandler::WrapGetPrinterInfoCallback(
@@ -320,9 +319,9 @@ void ExtensionPrinterHandler::WrapGetPrinterInfoCallback(
void ExtensionPrinterHandler::OnUsbDevicesEnumerated(
const PrinterHandler::GetPrintersCallback& callback,
const std::vector<scoped_refptr<UsbDevice>>& devices) {
- ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
+ ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
DevicePermissionsManager* permissions_manager =
- DevicePermissionsManager::Get(browser_context_);
+ DevicePermissionsManager::Get(profile_);
ListBuilder printer_list;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h
index 266cc1179eb..f17453dc0db 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h
@@ -18,12 +18,11 @@
namespace base {
class DictionaryValue;
class ListValue;
+class RefCountedBytes;
class RefCountedMemory;
}
-namespace content {
-class BrowserContext;
-}
+class Profile;
namespace cloud_devices {
class CloudDeviceDescription;
@@ -48,7 +47,7 @@ class ExtensionPrinterHandler : public PrinterHandler {
using PrintJobCallback = base::Callback<void(
std::unique_ptr<extensions::PrinterProviderPrintJob>)>;
- explicit ExtensionPrinterHandler(content::BrowserContext* browser_context);
+ explicit ExtensionPrinterHandler(Profile* profile);
~ExtensionPrinterHandler() override;
@@ -58,14 +57,14 @@ class ExtensionPrinterHandler : public PrinterHandler {
const PrinterHandler::GetPrintersCallback& callback) override;
void StartGetCapability(
const std::string& destination_id,
- const PrinterHandler::GetCapabilityCallback& calback) override;
+ const PrinterHandler::GetCapabilityCallback& callback) override;
// TODO(tbarzic): It might make sense to have the strings in a single struct.
void StartPrint(const std::string& destination_id,
const std::string& capability,
const base::string16& job_title,
const std::string& ticket_json,
const gfx::Size& page_size,
- const scoped_refptr<base::RefCountedMemory>& print_data,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
const PrinterHandler::PrintCallback& callback) override;
void StartGrantPrinterAccess(
const std::string& printer_id,
@@ -113,7 +112,7 @@ class ExtensionPrinterHandler : public PrinterHandler {
const PrinterHandler::GetPrintersCallback& callback,
const std::vector<scoped_refptr<device::UsbDevice>>& devices);
- content::BrowserContext* browser_context_;
+ Profile* profile_;
std::unique_ptr<printing::PWGRasterConverter> pwg_raster_converter_;
int pending_enumeration_count_ = 0;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc
index 94d1ab74df5..b45c0b79da8 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc
@@ -10,6 +10,7 @@
#include <memory>
#include <queue>
#include <string>
+#include <utility>
#include "base/bind.h"
#include "base/files/file_util.h"
@@ -17,6 +18,7 @@
#include "base/json/json_string_value_serializer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
+#include "base/memory/ref_counted_memory.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/stringprintf.h"
@@ -188,6 +190,9 @@ const char kContentTypePWG[] = "image/pwg-raster";
// Print request status considered to be successful by fake PrinterProviderAPI.
const char kPrintRequestSuccess[] = "OK";
+constexpr unsigned char kPrintData[] = "print data, PDF";
+constexpr size_t kPrintDataLength = sizeof(kPrintData);
+
// Used as a callback to StartGetPrinters in tests.
// Increases |*call_count| and records values returned by StartGetPrinters.
void RecordPrinterList(size_t* call_count,
@@ -215,10 +220,10 @@ void RecordPrintResult(size_t* call_count,
bool* success_out,
std::string* status_out,
bool success,
- const std::string& status) {
+ const base::Value& status) {
++(*call_count);
*success_out = success;
- *status_out = status;
+ *status_out = status.GetString();
}
// Used as a callback to StartGrantPrinterAccess in tests.
@@ -453,18 +458,19 @@ std::unique_ptr<KeyedService> BuildTestingPrinterProviderAPI(
class ExtensionPrinterHandlerTest : public testing::Test {
public:
- ExtensionPrinterHandlerTest() : pwg_raster_converter_(NULL) {}
+ ExtensionPrinterHandlerTest() = default;
~ExtensionPrinterHandlerTest() override = default;
void SetUp() override {
extensions::PrinterProviderAPIFactory::GetInstance()->SetTestingFactory(
env_.profile(), &BuildTestingPrinterProviderAPI);
- extension_printer_handler_.reset(
- new ExtensionPrinterHandler(env_.profile()));
+ extension_printer_handler_ =
+ base::MakeUnique<ExtensionPrinterHandler>(env_.profile());
- pwg_raster_converter_ = new FakePWGRasterConverter();
+ auto pwg_raster_converter = base::MakeUnique<FakePWGRasterConverter>();
+ pwg_raster_converter_ = pwg_raster_converter.get();
extension_printer_handler_->SetPWGRasterConverterForTesting(
- std::unique_ptr<PWGRasterConverter>(pwg_raster_converter_));
+ std::move(pwg_raster_converter));
}
protected:
@@ -482,7 +488,8 @@ class ExtensionPrinterHandlerTest : public testing::Test {
TestExtensionEnvironment env_;
std::unique_ptr<ExtensionPrinterHandler> extension_printer_handler_;
- FakePWGRasterConverter* pwg_raster_converter_;
+ // Owned by |extension_printer_handler_|.
+ FakePWGRasterConverter* pwg_raster_converter_ = nullptr;
private:
DISALLOW_COPY_AND_ASSIGN(ExtensionPrinterHandlerTest);
@@ -541,11 +548,11 @@ TEST_F(ExtensionPrinterHandlerTest, GetPrinters_Reset) {
}
TEST_F(ExtensionPrinterHandlerTest, GetUsbPrinters) {
- scoped_refptr<MockUsbDevice> device0 =
- new MockUsbDevice(0, 0, "Google", "USB Printer", "");
+ auto device0 =
+ base::MakeRefCounted<MockUsbDevice>(0, 0, "Google", "USB Printer", "");
usb_service().AddDevice(device0);
- scoped_refptr<MockUsbDevice> device1 =
- new MockUsbDevice(0, 1, "Google", "USB Printer", "");
+ auto device1 =
+ base::MakeRefCounted<MockUsbDevice>(0, 1, "Google", "USB Printer", "");
usb_service().AddDevice(device1);
const Extension* extension_1 = env_.MakeExtension(
@@ -662,9 +669,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pdf) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -686,7 +692,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pdf) {
EXPECT_EQ(kContentTypePDF, print_job->content_type);
EXPECT_TRUE(print_job->document_path.empty());
ASSERT_TRUE(print_job->document_bytes);
- EXPECT_EQ(print_data->data(),
+ EXPECT_EQ(RefCountedMemoryToString(print_data),
RefCountedMemoryToString(print_job->document_bytes));
fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
@@ -701,9 +707,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pdf_Reset) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -728,9 +733,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_All) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -753,7 +757,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_All) {
EXPECT_EQ(kContentTypePDF, print_job->content_type);
EXPECT_TRUE(print_job->document_path.empty());
ASSERT_TRUE(print_job->document_bytes);
- EXPECT_EQ(print_data->data(),
+ EXPECT_EQ(RefCountedMemoryToString(print_data),
RefCountedMemoryToString(print_job->document_bytes));
fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
@@ -768,9 +772,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -822,9 +825,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_NonDefaultSettings) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -876,9 +878,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_Reset) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -906,9 +907,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_InvalidTicket) {
bool success = false;
std::string status;
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -929,9 +929,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_FailedConversion) {
pwg_raster_converter_->FailConversion();
- scoped_refptr<base::RefCountedString> print_data(
- new base::RefCountedString());
- print_data->data() = "print data, PDF";
+ auto print_data =
+ base::MakeRefCounted<base::RefCountedBytes>(kPrintData, kPrintDataLength);
base::string16 title = base::ASCIIToUTF16("Title");
extension_printer_handler_->StartPrint(
@@ -946,8 +945,8 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_FailedConversion) {
}
TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess) {
- scoped_refptr<MockUsbDevice> device =
- new MockUsbDevice(0, 0, "Google", "USB Printer", "");
+ auto device =
+ base::MakeRefCounted<MockUsbDevice>(0, 0, "Google", "USB Printer", "");
usb_service().AddDevice(device);
size_t call_count = 0;
@@ -978,8 +977,8 @@ TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess) {
}
TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess_Reset) {
- scoped_refptr<MockUsbDevice> device =
- new MockUsbDevice(0, 0, "Google", "USB Printer", "");
+ auto device =
+ base::MakeRefCounted<MockUsbDevice>(0, 0, "Google", "USB Printer", "");
usb_service().AddDevice(device);
size_t call_count = 0;
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 e9a5a4fef1d..b16000c0b65 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc
@@ -16,6 +16,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
+#include "base/files/file_util.h"
#include "base/i18n/file_util_icu.h"
#include "base/i18n/number_formatting.h"
#include "base/json/json_reader.h"
@@ -32,6 +33,7 @@
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/app_mode/app_mode_utils.h"
+#include "chrome/browser/bad_message.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/platform_util.h"
@@ -94,14 +96,11 @@
#include "chromeos/printing/printer_configuration.h"
#endif
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
-#include "chrome/browser/printing/cloud_print/privet_constants.h"
-#endif
-
using content::BrowserThread;
using content::RenderFrameHost;
using content::WebContents;
using printing::PrintViewManager;
+using printing::PrinterType;
namespace {
@@ -195,9 +194,6 @@ const char kDefaultDestinationSelectionRules[] =
// Id of the predefined PDF printer.
const char kLocalPdfPrinterId[] = "Save as PDF";
-// Timeout for searching for privet printers, in seconds.
-const int kPrivetTimeoutSec = 5;
-
// Get the print job settings dictionary from |json_str|. Returns NULL on
// failure.
std::unique_ptr<base::DictionaryValue> GetSettingsDictionary(
@@ -454,14 +450,6 @@ void CreateDirectoryIfNeeded(const base::FilePath& path) {
base::CreateDirectory(path);
}
-bool PrivetPrintingEnabled() {
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- return true;
-#else
- return false;
-#endif
-}
-
} // namespace
class PrintPreviewHandler::AccessTokenService
@@ -616,27 +604,34 @@ void PrintPreviewHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("forceOpenNewTab",
base::Bind(&PrintPreviewHandler::HandleForceOpenNewTab,
base::Unretained(this)));
- web_ui()->RegisterMessageCallback("getPrivetPrinters",
- base::Bind(&PrintPreviewHandler::HandleGetPrivetPrinters,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback("getPrivetPrinterCapabilities",
- base::Bind(&PrintPreviewHandler::HandleGetPrivetPrinterCapabilities,
- base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "getExtensionPrinters",
- base::Bind(&PrintPreviewHandler::HandleGetExtensionPrinters,
+ "getExtensionOrPrivetPrinters",
+ base::Bind(&PrintPreviewHandler::HandleGetExtensionOrPrivetPrinters,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "getExtensionPrinterCapabilities",
- base::Bind(&PrintPreviewHandler::HandleGetExtensionPrinterCapabilities,
- base::Unretained(this)));
+ "getExtensionOrPrivetPrinterCapabilities",
+ base::Bind(
+ &PrintPreviewHandler::HandleGetExtensionOrPrivetPrinterCapabilities,
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"grantExtensionPrinterAccess",
base::Bind(&PrintPreviewHandler::HandleGrantExtensionPrinterAccess,
base::Unretained(this)));
+}
+
+void PrintPreviewHandler::OnJavascriptAllowed() {
+ // Now that the UI is initialized, any future account changes will require
+ // a printer list refresh.
RegisterForGaiaCookieChanges();
}
+void PrintPreviewHandler::OnJavascriptDisallowed() {
+ // Normally the handler and print preview will be destroyed together, but
+ // this is necessary for refresh or navigation from the chrome://print page.
+ weak_factory_.InvalidateWeakPtrs();
+ UnregisterForGaiaCookieChanges();
+}
+
WebContents* PrintPreviewHandler::preview_web_contents() const {
return web_ui()->GetWebContents();
}
@@ -672,69 +667,26 @@ void PrintPreviewHandler::HandleGetPrinters(const base::ListValue* args) {
weak_factory_.GetWeakPtr(), callback_id));
}
-void PrintPreviewHandler::HandleGetPrivetPrinters(const base::ListValue* args) {
+void PrintPreviewHandler::HandleGetExtensionOrPrivetPrinters(
+ const base::ListValue* args) {
std::string callback_id;
CHECK(args->GetString(0, &callback_id));
CHECK(!callback_id.empty());
- if (!PrivetPrintingEnabled()) {
- RejectJavascriptCallback(base::Value(callback_id), base::Value());
- return;
- }
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- using local_discovery::ServiceDiscoverySharedClient;
- scoped_refptr<ServiceDiscoverySharedClient> service_discovery =
- ServiceDiscoverySharedClient::GetInstance();
- DCHECK(privet_search_callback_id_.empty());
- privet_search_callback_id_ = callback_id;
- StartPrivetLister(service_discovery);
-#endif
-}
+ int type;
+ CHECK(args->GetInteger(1, &type));
+ PrinterType printer_type = static_cast<PrinterType>(type);
-void PrintPreviewHandler::StopPrivetLister() {
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- privet_lister_timer_.reset();
- if (PrivetPrintingEnabled() && printer_lister_) {
- printer_lister_->Stop();
- }
- ResolveJavascriptCallback(base::Value(privet_search_callback_id_),
- base::Value());
- privet_search_callback_id_.clear();
-#endif
-}
-
-void PrintPreviewHandler::HandleGetPrivetPrinterCapabilities(
- const base::ListValue* args) {
- std::string callback_id;
- std::string printer_name;
- if (!args->GetString(0, &callback_id) || !args->GetString(1, &printer_name) ||
- callback_id.empty() || printer_name.empty()) {
+ PrinterHandler* handler = GetPrinterHandler(printer_type);
+ if (!handler) {
RejectJavascriptCallback(base::Value(callback_id), base::Value());
return;
}
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- if (CreatePrivetHTTP(
- printer_name,
- base::Bind(&PrintPreviewHandler::PrivetCapabilitiesUpdateClient,
- weak_factory_.GetWeakPtr(), callback_id))) {
- return;
- }
-#endif
- RejectJavascriptCallback(base::Value(callback_id), base::Value());
-}
-
-void PrintPreviewHandler::HandleGetExtensionPrinters(
- const base::ListValue* args) {
- std::string callback_id;
- CHECK(args->GetString(0, &callback_id));
- CHECK(!callback_id.empty());
-
- EnsureExtensionPrinterHandlerSet();
// Make sure all in progress requests are canceled before new printer search
// starts.
- extension_printer_handler_->Reset();
- extension_printer_handler_->StartGetPrinters(
- base::Bind(&PrintPreviewHandler::OnGotPrintersForExtension,
- weak_factory_.GetWeakPtr(), callback_id));
+ handler->Reset();
+ handler->StartGetPrinters(
+ base::Bind(&PrintPreviewHandler::OnGotPrintersForExtensionOrPrivet,
+ weak_factory_.GetWeakPtr(), callback_id, printer_type));
}
void PrintPreviewHandler::HandleGrantExtensionPrinterAccess(
@@ -745,27 +697,35 @@ void PrintPreviewHandler::HandleGrantExtensionPrinterAccess(
args->GetString(1, &printer_id) && !callback_id.empty();
DCHECK(ok);
- EnsureExtensionPrinterHandlerSet();
- extension_printer_handler_->StartGrantPrinterAccess(
- printer_id, base::Bind(&PrintPreviewHandler::OnGotExtensionPrinterInfo,
- weak_factory_.GetWeakPtr(), callback_id));
+ GetPrinterHandler(PrinterType::kExtensionPrinter)
+ ->StartGrantPrinterAccess(
+ printer_id,
+ base::Bind(&PrintPreviewHandler::OnGotExtensionPrinterInfo,
+ weak_factory_.GetWeakPtr(), callback_id));
}
-void PrintPreviewHandler::HandleGetExtensionPrinterCapabilities(
+void PrintPreviewHandler::HandleGetExtensionOrPrivetPrinterCapabilities(
const base::ListValue* args) {
std::string callback_id;
std::string printer_name;
+ int type;
if (!args->GetString(0, &callback_id) || !args->GetString(1, &printer_name) ||
- callback_id.empty() || printer_name.empty()) {
+ !args->GetInteger(2, &type) || callback_id.empty() ||
+ printer_name.empty()) {
RejectJavascriptCallback(base::Value(callback_id), base::Value());
return;
}
+ PrinterType printer_type = static_cast<PrinterType>(type);
- EnsureExtensionPrinterHandlerSet();
- extension_printer_handler_->StartGetCapability(
- printer_name,
- base::Bind(&PrintPreviewHandler::OnGotExtensionPrinterCapabilities,
- weak_factory_.GetWeakPtr(), callback_id));
+ PrinterHandler* handler = GetPrinterHandler(printer_type);
+ if (!handler) {
+ RejectJavascriptCallback(base::Value(callback_id), base::Value());
+ return;
+ }
+
+ handler->StartGetCapability(
+ printer_name, base::Bind(&PrintPreviewHandler::OnGotPrinterCapabilities,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void PrintPreviewHandler::HandleGetPreview(const base::ListValue* args) {
@@ -914,39 +874,28 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) {
}
#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- if (print_with_privet && PrivetPrintingEnabled()) {
- std::string printer_name;
- std::string print_ticket;
- std::string capabilities;
+ if (print_with_privet) {
UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintWithPrivet", page_count);
ReportUserActionHistogram(PRINT_WITH_PRIVET);
-
- int width = 0;
- int height = 0;
- if (!settings->GetString(printing::kSettingDeviceName, &printer_name) ||
- !settings->GetString(printing::kSettingTicket, &print_ticket) ||
- !settings->GetString(printing::kSettingCapabilities, &capabilities) ||
- !settings->GetInteger(printing::kSettingPageWidth, &width) ||
- !settings->GetInteger(printing::kSettingPageHeight, &height) ||
- width <= 0 || height <= 0) {
- NOTREACHED();
- RejectJavascriptCallback(base::Value(callback_id), base::Value(-1));
- return;
- }
-
- DCHECK(privet_print_callback_id_.empty());
- privet_print_callback_id_ = callback_id;
- PrintToPrivetPrinter(callback_id, printer_name, print_ticket, capabilities,
- gfx::Size(width, height));
- return;
}
#endif
-
if (print_with_extension) {
UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintWithExtension",
page_count);
ReportUserActionHistogram(PRINT_WITH_EXTENSION);
+ }
+ scoped_refptr<base::RefCountedBytes> data;
+ base::string16 title;
+ if (!GetPreviewDataAndTitle(&data, &title)) {
+ // Nothing to print, no preview available.
+ RejectJavascriptCallback(
+ base::Value(callback_id),
+ print_with_privet ? base::Value(-1) : base::Value("NO_DATA"));
+ return;
+ }
+
+ if (print_with_privet || print_with_extension) {
std::string destination_id;
std::string print_ticket;
std::string capabilities;
@@ -959,33 +908,19 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) {
!settings->GetInteger(printing::kSettingPageHeight, &height) ||
width <= 0 || height <= 0) {
NOTREACHED();
- RejectJavascriptCallback(base::Value(callback_id), base::Value("FAILED"));
- return;
- }
-
- base::string16 title;
- scoped_refptr<base::RefCountedBytes> data;
- if (!GetPreviewDataAndTitle(&data, &title)) {
- LOG(ERROR) << "Nothing to print; no preview available.";
- RejectJavascriptCallback(base::Value(callback_id),
- base::Value("NO_DATA"));
+ RejectJavascriptCallback(
+ base::Value(callback_id),
+ print_with_privet ? base::Value(-1) : base::Value("FAILED"));
return;
}
- EnsureExtensionPrinterHandlerSet();
- extension_printer_handler_->StartPrint(
- destination_id, capabilities, title, print_ticket,
- gfx::Size(width, height), data,
- base::Bind(&PrintPreviewHandler::OnExtensionPrintResult,
- weak_factory_.GetWeakPtr(), callback_id));
- return;
- }
-
- scoped_refptr<base::RefCountedBytes> data;
- base::string16 title;
- if (!GetPreviewDataAndTitle(&data, &title)) {
- // Nothing to print, no preview available.
- RejectJavascriptCallback(base::Value(callback_id), base::Value());
+ PrinterHandler* handler =
+ GetPrinterHandler(print_with_privet ? PrinterType::kPrivetPrinter
+ : PrinterType::kExtensionPrinter);
+ handler->StartPrint(destination_id, capabilities, title, print_ticket,
+ gfx::Size(width, height), data,
+ base::Bind(&PrintPreviewHandler::OnPrintResult,
+ weak_factory_.GetWeakPtr(), callback_id));
return;
}
@@ -1067,6 +1002,7 @@ void PrintPreviewHandler::PrintToPdf() {
}
void PrintPreviewHandler::HandleHidePreview(const base::ListValue* /*args*/) {
+ print_preview_ui()->OnHidePreviewDialog();
if (settings_) {
// Print preview is responding to a resolution of "print" promise. Send the
// print message to the renderer.
@@ -1080,15 +1016,13 @@ void PrintPreviewHandler::HandleHidePreview(const base::ListValue* /*args*/) {
WebContents* initiator = GetInitiator();
ClearInitiatorDetails();
- // Since the preview dialog will be hidden and not closed, we need to make
- // this call.
+ // Since the preview dialog is hidden and not closed, we need to make this
+ // call.
if (initiator) {
auto* print_view_manager = PrintViewManager::FromWebContents(initiator);
print_view_manager->PrintPreviewDone();
}
}
-
- print_preview_ui()->OnHidePreviewDialog();
}
void PrintPreviewHandler::HandleCancelPendingPrintRequest(
@@ -1516,16 +1450,23 @@ void PrintPreviewHandler::OnGotUniqueFileName(const base::FilePath& path) {
}
void PrintPreviewHandler::OnPrintPreviewReady(int preview_uid, int request_id) {
- if (request_id < 0) // invalid ID.
+ if (request_id < 0 || preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ // invalid ID or extra message
+ BadMessageReceived();
return;
- CHECK(!preview_callbacks_.empty());
+ }
+
ResolveJavascriptCallback(base::Value(preview_callbacks_.front()),
base::Value(preview_uid));
preview_callbacks_.pop();
}
void PrintPreviewHandler::OnPrintPreviewFailed() {
- CHECK(!preview_callbacks_.empty());
+ if (preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
if (!reported_failed_preview_) {
reported_failed_preview_ = true;
ReportUserActionHistogram(PREVIEW_FAILED);
@@ -1536,7 +1477,11 @@ void PrintPreviewHandler::OnPrintPreviewFailed() {
}
void PrintPreviewHandler::OnInvalidPrinterSettings() {
- CHECK(!preview_callbacks_.empty());
+ if (preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
RejectJavascriptCallback(base::Value(preview_callbacks_.front()),
base::Value("SETTINGS_INVALID"));
preview_callbacks_.pop();
@@ -1545,6 +1490,11 @@ void PrintPreviewHandler::OnInvalidPrinterSettings() {
void PrintPreviewHandler::SendPrintPresetOptions(bool disable_scaling,
int copies,
int duplex) {
+ if (preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
FireWebUIListener("print-preset-options", base::Value(disable_scaling),
base::Value(copies), base::Value(duplex));
}
@@ -1552,6 +1502,11 @@ void PrintPreviewHandler::SendPrintPresetOptions(bool disable_scaling,
void PrintPreviewHandler::SendPageCountReady(int page_count,
int request_id,
int fit_to_page_scaling) {
+ if (preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
FireWebUIListener("page-count-ready", base::Value(page_count),
base::Value(request_id), base::Value(fit_to_page_scaling));
}
@@ -1559,6 +1514,11 @@ void PrintPreviewHandler::SendPageCountReady(int page_count,
void PrintPreviewHandler::SendPageLayoutReady(
const base::DictionaryValue& layout,
bool has_custom_page_size_style) {
+ if (preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
FireWebUIListener("page-layout-ready", layout,
base::Value(has_custom_page_size_style));
}
@@ -1566,12 +1526,21 @@ void PrintPreviewHandler::SendPageLayoutReady(
void PrintPreviewHandler::SendPagePreviewReady(int page_index,
int preview_uid,
int preview_response_id) {
+ if (!IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
FireWebUIListener("page-preview-ready", base::Value(page_index),
base::Value(preview_uid), base::Value(preview_response_id));
}
void PrintPreviewHandler::OnPrintPreviewCancelled() {
- CHECK(!preview_callbacks_.empty());
+ if (preview_callbacks_.empty() || !IsJavascriptAllowed()) {
+ BadMessageReceived();
+ return;
+ }
+
RejectJavascriptCallback(base::Value(preview_callbacks_.front()),
base::Value("CANCELLED"));
preview_callbacks_.pop();
@@ -1658,236 +1627,43 @@ bool PrintPreviewHandler::GetPreviewDataAndTitle(
return true;
}
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
-void PrintPreviewHandler::StartPrivetLister(const scoped_refptr<
- local_discovery::ServiceDiscoverySharedClient>& client) {
- Profile* profile = Profile::FromWebUI(web_ui());
- DCHECK(!service_discovery_client_.get() ||
- service_discovery_client_.get() == client.get());
- service_discovery_client_ = client;
- printer_lister_ = base::MakeUnique<cloud_print::PrivetLocalPrinterLister>(
- service_discovery_client_.get(), profile->GetRequestContext(), this);
- privet_lister_timer_.reset(new base::OneShotTimer());
- privet_lister_timer_->Start(FROM_HERE,
- base::TimeDelta::FromSeconds(kPrivetTimeoutSec),
- this, &PrintPreviewHandler::StopPrivetLister);
- printer_lister_->Start();
-}
-
-void PrintPreviewHandler::LocalPrinterChanged(
- const std::string& name,
- bool has_local_printing,
- const cloud_print::DeviceDescription& description) {
- base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
- if (has_local_printing ||
- command_line->HasSwitch(switches::kEnablePrintPreviewRegisterPromos)) {
- base::DictionaryValue info;
- FillPrinterDescription(name, description, has_local_printing, &info);
- FireWebUIListener("privet-printer-added", info);
- }
-}
-
-void PrintPreviewHandler::LocalPrinterRemoved(const std::string& name) {
-}
-
-void PrintPreviewHandler::LocalPrinterCacheFlushed() {
-}
-
-void PrintPreviewHandler::PrivetCapabilitiesUpdateClient(
- const std::string& callback_id,
- std::unique_ptr<cloud_print::PrivetHTTPClient> http_client) {
- if (!PrivetUpdateClient(callback_id, std::move(http_client)))
- return;
-
- privet_capabilities_operation_ =
- privet_http_client_->CreateCapabilitiesOperation(
- base::Bind(&PrintPreviewHandler::OnPrivetCapabilities,
- weak_factory_.GetWeakPtr(), callback_id));
- privet_capabilities_operation_->Start();
-}
-
-bool PrintPreviewHandler::PrivetUpdateClient(
- const std::string& callback_id,
- std::unique_ptr<cloud_print::PrivetHTTPClient> http_client) {
- if (!http_client) {
- RejectJavascriptCallback(base::Value(callback_id), base::Value());
- privet_http_resolution_.reset();
- if (callback_id == privet_print_callback_id_)
- privet_print_callback_id_.clear();
- return false;
- }
-
- privet_local_print_operation_.reset();
- privet_capabilities_operation_.reset();
- privet_http_client_ = cloud_print::PrivetV1HTTPClient::CreateDefault(
- std::move(http_client));
-
- privet_http_resolution_.reset();
-
- return true;
-}
-
-void PrintPreviewHandler::PrivetLocalPrintUpdateClient(
- const std::string& callback_id,
- std::string print_ticket,
- std::string capabilities,
- gfx::Size page_size,
- std::unique_ptr<cloud_print::PrivetHTTPClient> http_client) {
- if (!PrivetUpdateClient(callback_id, std::move(http_client)))
- return;
-
- StartPrivetLocalPrint(print_ticket, capabilities, page_size);
-}
-
-void PrintPreviewHandler::StartPrivetLocalPrint(const std::string& print_ticket,
- const std::string& capabilities,
- const gfx::Size& page_size) {
- privet_local_print_operation_ =
- privet_http_client_->CreateLocalPrintOperation(this);
-
- privet_local_print_operation_->SetTicket(print_ticket);
- privet_local_print_operation_->SetCapabilities(capabilities);
-
- scoped_refptr<base::RefCountedBytes> data;
- base::string16 title;
-
- if (!GetPreviewDataAndTitle(&data, &title)) {
- RejectJavascriptCallback(base::Value(privet_print_callback_id_),
- base::Value(-1));
- privet_print_callback_id_.clear();
- return;
- }
-
- privet_local_print_operation_->SetJobname(base::UTF16ToUTF8(title));
- privet_local_print_operation_->SetPageSize(page_size);
- privet_local_print_operation_->SetData(data.get());
-
- Profile* profile = Profile::FromWebUI(web_ui());
- SigninManagerBase* signin_manager =
- SigninManagerFactory::GetForProfileIfExists(profile);
-
- if (signin_manager) {
- privet_local_print_operation_->SetUsername(
- signin_manager->GetAuthenticatedAccountInfo().email);
- }
-
- privet_local_print_operation_->Start();
-}
-
-void PrintPreviewHandler::OnPrivetCapabilities(
- const std::string& callback_id,
- const base::DictionaryValue* capabilities) {
- std::string name = privet_capabilities_operation_->GetHTTPClient()->GetName();
-
- if (!capabilities || capabilities->HasKey(cloud_print::kPrivetKeyError) ||
- !printer_lister_) {
- RejectJavascriptCallback(base::Value(callback_id), base::Value());
- return;
+PrinterHandler* PrintPreviewHandler::GetPrinterHandler(
+ PrinterType printer_type) {
+ if (printer_type == PrinterType::kExtensionPrinter) {
+ if (!extension_printer_handler_) {
+ extension_printer_handler_ = PrinterHandler::CreateForExtensionPrinters(
+ Profile::FromWebUI(web_ui()));
+ }
+ return extension_printer_handler_.get();
}
-
- const cloud_print::DeviceDescription* description =
- printer_lister_->GetDeviceDescription(name);
-
- if (!description) {
- RejectJavascriptCallback(base::Value(callback_id), base::Value());
- return;
+#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
+ if (printer_type == PrinterType::kPrivetPrinter) {
+ if (!privet_printer_handler_) {
+ privet_printer_handler_ =
+ PrinterHandler::CreateForPrivetPrinters(Profile::FromWebUI(web_ui()));
+ }
+ return privet_printer_handler_.get();
}
-
- std::unique_ptr<base::DictionaryValue> printer_info =
- base::MakeUnique<base::DictionaryValue>();
- FillPrinterDescription(name, *description, true, printer_info.get());
- base::DictionaryValue printer_info_and_caps;
- printer_info_and_caps.SetDictionary("printer", std::move(printer_info));
- std::unique_ptr<base::DictionaryValue> capabilities_copy =
- capabilities->CreateDeepCopy();
- printer_info_and_caps.SetDictionary("capabilities",
- std::move(capabilities_copy));
- ResolveJavascriptCallback(base::Value(callback_id), printer_info_and_caps);
-
- privet_capabilities_operation_.reset();
-}
-
-void PrintPreviewHandler::PrintToPrivetPrinter(const std::string& callback_id,
- const std::string& device_name,
- const std::string& ticket,
- const std::string& capabilities,
- const gfx::Size& page_size) {
- if (!CreatePrivetHTTP(
- device_name,
- base::Bind(&PrintPreviewHandler::PrivetLocalPrintUpdateClient,
- weak_factory_.GetWeakPtr(), callback_id, ticket,
- capabilities, page_size))) {
- RejectJavascriptCallback(base::Value(privet_print_callback_id_),
- base::Value(-1));
- privet_print_callback_id_.clear();
- }
-}
-
-bool PrintPreviewHandler::CreatePrivetHTTP(
- const std::string& name,
- const cloud_print::PrivetHTTPAsynchronousFactory::ResultCallback&
- callback) {
- const cloud_print::DeviceDescription* device_description =
- printer_lister_ ? printer_lister_->GetDeviceDescription(name) : NULL;
-
- if (!device_description)
- return false;
-
- privet_http_factory_ =
- cloud_print::PrivetHTTPAsynchronousFactory::CreateInstance(
- Profile::FromWebUI(web_ui())->GetRequestContext());
- privet_http_resolution_ = privet_http_factory_->CreatePrivetHTTP(name);
- privet_http_resolution_->Start(device_description->address, callback);
-
- return true;
-}
-
-void PrintPreviewHandler::OnPrivetPrintingDone(
- const cloud_print::PrivetLocalPrintOperation* print_operation) {
- ResolveJavascriptCallback(base::Value(privet_print_callback_id_),
- base::Value());
- privet_print_callback_id_.clear();
-}
-
-void PrintPreviewHandler::OnPrivetPrintingError(
- const cloud_print::PrivetLocalPrintOperation* print_operation,
- int http_code) {
- RejectJavascriptCallback(base::Value(privet_print_callback_id_),
- base::Value(http_code));
- privet_print_callback_id_.clear();
-}
-
-void PrintPreviewHandler::FillPrinterDescription(
- const std::string& name,
- const cloud_print::DeviceDescription& description,
- bool has_local_printing,
- base::DictionaryValue* printer_value) {
- base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
-
- printer_value->SetString("serviceName", name);
- printer_value->SetString("name", description.name);
- printer_value->SetBoolean("hasLocalPrinting", has_local_printing);
- printer_value->SetBoolean(
- "isUnregistered",
- description.id.empty() &&
- command_line->HasSwitch(switches::kEnablePrintPreviewRegisterPromos));
- printer_value->SetString("cloudID", description.id);
-}
-#endif // BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
-
-void PrintPreviewHandler::EnsureExtensionPrinterHandlerSet() {
- if (extension_printer_handler_)
- return;
-
- extension_printer_handler_ =
- PrinterHandler::CreateForExtensionPrinters(Profile::FromWebUI(web_ui()));
+#endif
+ return nullptr;
}
-void PrintPreviewHandler::OnGotPrintersForExtension(
+void PrintPreviewHandler::OnGotPrintersForExtensionOrPrivet(
const std::string& callback_id,
+ printing::PrinterType printer_type,
const base::ListValue& printers,
bool done) {
- FireWebUIListener("extension-printers-added", printers);
+ DCHECK(printer_type == PrinterType::kExtensionPrinter ||
+ printer_type == PrinterType::kPrivetPrinter);
+ if (!printers.empty()) {
+ if (printer_type == PrinterType::kExtensionPrinter) {
+ FireWebUIListener("extension-printers-added", printers);
+ } else {
+ const base::Value* printer;
+ CHECK(printers.Get(0, &printer));
+ FireWebUIListener("privet-printer-added", *printer);
+ }
+ }
if (done) {
ResolveJavascriptCallback(base::Value(callback_id), base::Value());
}
@@ -1903,7 +1679,7 @@ void PrintPreviewHandler::OnGotExtensionPrinterInfo(
ResolveJavascriptCallback(base::Value(callback_id), printer_info);
}
-void PrintPreviewHandler::OnGotExtensionPrinterCapabilities(
+void PrintPreviewHandler::OnGotPrinterCapabilities(
const std::string& callback_id,
const base::DictionaryValue& capabilities) {
if (capabilities.empty()) {
@@ -1913,20 +1689,20 @@ void PrintPreviewHandler::OnGotExtensionPrinterCapabilities(
ResolveJavascriptCallback(base::Value(callback_id), capabilities);
}
-void PrintPreviewHandler::OnExtensionPrintResult(const std::string& callback_id,
- bool success,
- const std::string& status) {
+void PrintPreviewHandler::OnPrintResult(const std::string& callback_id,
+ bool success,
+ const base::Value& error) {
if (success) {
ResolveJavascriptCallback(base::Value(callback_id), base::Value());
return;
}
- RejectJavascriptCallback(base::Value(callback_id), base::Value(status));
+ RejectJavascriptCallback(base::Value(callback_id), error);
}
void PrintPreviewHandler::RegisterForGaiaCookieChanges() {
DCHECK(!gaia_cookie_manager_service_);
Profile* profile = Profile::FromWebUI(web_ui());
- if (switches::IsAccountConsistencyMirrorEnabled() &&
+ if (signin::IsAccountConsistencyMirrorEnabled() &&
!profile->IsOffTheRecord()) {
gaia_cookie_manager_service_ =
GaiaCookieManagerServiceFactory::GetForProfile(profile);
@@ -1940,6 +1716,12 @@ void PrintPreviewHandler::UnregisterForGaiaCookieChanges() {
gaia_cookie_manager_service_->RemoveObserver(this);
}
+void PrintPreviewHandler::BadMessageReceived() {
+ bad_message::ReceivedBadMessage(
+ GetInitiator()->GetRenderProcessHost(),
+ bad_message::BadMessageReason::PPH_EXTRA_PREVIEW_MESSAGE);
+}
+
void PrintPreviewHandler::SetPdfSavedClosureForTesting(
const base::Closure& closure) {
pdf_file_saved_closure_ = closure;
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 c638f650756..9cf1bd3e023 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
@@ -22,11 +22,6 @@
#include "printing/features/features.h"
#include "ui/shell_dialogs/select_file_dialog.h"
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
-#include "chrome/browser/local_discovery/service_discovery_shared_client.h"
-#include "chrome/browser/printing/cloud_print/privet_local_printer_lister.h"
-#endif
-
class PrinterHandler;
class PrintPreviewUI;
@@ -39,21 +34,18 @@ namespace content {
class WebContents;
}
-namespace gfx {
-class Size;
-}
-
namespace printing {
+
+// Must match print_preview.PrinterType in
+// chrome/browser/resources/print_preview/native_layer.js
+enum PrinterType { kPrivetPrinter, kExtensionPrinter };
+
class PrinterBackendProxy;
}
// The handler for Javascript messages related to the print preview dialog.
class PrintPreviewHandler
: public content::WebUIMessageHandler,
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- public cloud_print::PrivetLocalPrinterLister::Delegate,
- public cloud_print::PrivetLocalPrintOperation::Delegate,
-#endif
public ui::SelectFileDialog::Listener,
public GaiaCookieManagerService::Observer {
public:
@@ -62,6 +54,8 @@ class PrintPreviewHandler
// WebUIMessageHandler implementation.
void RegisterMessages() override;
+ void OnJavascriptAllowed() override;
+ void OnJavascriptDisallowed() override;
// SelectFileDialog::Listener implementation.
void FileSelected(const base::FilePath& path,
@@ -112,27 +106,14 @@ class PrintPreviewHandler
void ShowSystemDialog();
#endif // BUILDFLAG(ENABLE_BASIC_PRINTING)
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- // PrivetLocalPrinterLister::Delegate implementation.
- void LocalPrinterChanged(
- const std::string& name,
- bool has_local_printing,
- const cloud_print::DeviceDescription& description) override;
- void LocalPrinterRemoved(const std::string& name) override;
- void LocalPrinterCacheFlushed() override;
-
- // PrivetLocalPrintOperation::Delegate implementation.
- void OnPrivetPrintingDone(
- const cloud_print::PrivetLocalPrintOperation* print_operation) override;
- void OnPrivetPrintingError(
- const cloud_print::PrivetLocalPrintOperation* print_operation,
- int http_code) override;
-#endif
-
int regenerate_preview_request_count() const {
return regenerate_preview_request_count_;
}
+ // Shuts down the initiator renderer. Called when a bad IPC message is
+ // received.
+ void BadMessageReceived();
+
// Sets |pdf_file_saved_closure_| to |closure|.
void SetPdfSavedClosureForTesting(const base::Closure& closure);
@@ -171,11 +152,9 @@ class PrintPreviewHandler
// Gets the list of printers. |args| is unused.
void HandleGetPrinters(const base::ListValue* args);
- // Starts getting all local privet printers. |args| is unused.
- void HandleGetPrivetPrinters(const base::ListValue* args);
-
- // Starts getting all local extension managed printers. |args| is unused.
- void HandleGetExtensionPrinters(const base::ListValue* args);
+ // Starts getting all extension managed or local privet printers.
+ // |args| contains the type of printers and the Javascript callback.
+ void HandleGetExtensionOrPrivetPrinters(const base::ListValue* args);
// Grants an extension access to a provisional printer. First element of
// |args| is the provisional printer ID.
@@ -251,11 +230,11 @@ class PrintPreviewHandler
// window opens behind the initiator window.
void HandleForceOpenNewTab(const base::ListValue* args);
- void HandleGetPrivetPrinterCapabilities(const base::ListValue* arg);
-
- // Requests an extension managed printer's capabilities.
- // |arg| contains the ID of the printer whose capabilities are requested.
- void HandleGetExtensionPrinterCapabilities(const base::ListValue* args);
+ // Requests a privet or extension managed printer's capabilities.
+ // |args| contains the ID and type of the printer whose capabilities are
+ // requested.
+ void HandleGetExtensionOrPrivetPrinterCapabilities(
+ const base::ListValue* args);
void SendInitialSettings(const std::string& callback_id,
const std::string& default_printer);
@@ -328,57 +307,20 @@ class PrintPreviewHandler
base::DictionaryValue* settings) const;
#endif
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- void StartPrivetLister(const scoped_refptr<
- local_discovery::ServiceDiscoverySharedClient>& client);
- void StopPrivetLister();
- void OnPrivetCapabilities(const std::string& callback_id,
- const base::DictionaryValue* capabilities);
- void PrivetCapabilitiesUpdateClient(
- const std::string& callback_id,
- std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
- void PrivetLocalPrintUpdateClient(
- const std::string& callback_id,
- std::string print_ticket,
- std::string capabilities,
- gfx::Size page_size,
- std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
- bool PrivetUpdateClient(
- const std::string& callback_id,
- std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
- void StartPrivetLocalPrint(const std::string& print_ticket,
- const std::string& capabilities,
- const gfx::Size& page_size);
- void SendPrivetCapabilitiesError(const std::string& id);
- void PrintToPrivetPrinter(const std::string& callback_id,
- const std::string& printer_name,
- const std::string& print_ticket,
- const std::string& capabilities,
- const gfx::Size& page_size);
- bool CreatePrivetHTTP(
- const std::string& name,
- const cloud_print::PrivetHTTPAsynchronousFactory::ResultCallback&
- callback);
- void FillPrinterDescription(
- const std::string& name,
- const cloud_print::DeviceDescription& description,
- bool has_local_printing,
- base::DictionaryValue* printer_value);
-#endif
-
- // Lazily creates |extension_printer_handler_| that can be used to handle
- // extension printers requests.
- void EnsureExtensionPrinterHandlerSet();
-
- // Called when a list of printers is reported by an extension.
- // |callback_id|: The javascript callback to call if all extension printers
- // are loaded (when |done| = true)
- // |printers|: The list of printers managed by the extension.
- // |done|: Whether all the extensions have reported the list of printers
- // they manage.
- void OnGotPrintersForExtension(const std::string& callback_id,
- const base::ListValue& printers,
- bool done);
+ PrinterHandler* GetPrinterHandler(printing::PrinterType printer_type);
+
+ // Called when a privet printer or extension printers are detected.
+ // |callback_id|: The javascript callback to call if all printers have been
+ // loaded (when |done| = true).
+ // |printer_type|: The type of printers that were added.
+ // |printers|: A list containing extension printers or a privet printer that
+ // has been found.
+ // |done|: Whether the printers are done being loaded (all extensions
+ // have responded, or privet printer search has timed out).
+ void OnGotPrintersForExtensionOrPrivet(const std::string& callback_id,
+ printing::PrinterType printer_type,
+ const base::ListValue& printers,
+ bool done);
// Called when an extension reports information requested for a provisional
// printer.
@@ -387,22 +329,21 @@ class PrintPreviewHandler
void OnGotExtensionPrinterInfo(const std::string& callback_id,
const base::DictionaryValue& printer_info);
- // Called when an extension reports the set of print capabilites for a
- // printer.
+ // Called when an extension or the privet printing service reports the set of
+ // print capabilities for a printer.
// |callback_id|: The Javascript callback to reject or resolve
// |capabilities|: The printer capabilities.
- void OnGotExtensionPrinterCapabilities(
- const std::string& callback_id,
- const base::DictionaryValue& capabilities);
+ void OnGotPrinterCapabilities(const std::string& callback_id,
+ const base::DictionaryValue& capabilities);
- // Called when an extension print job is completed.
+ // Called when an extension or privet print job is completed.
// |callback_id|: The javascript callback to run.
// |success|: Whether the job succeeded.
- // |status|: The returned print job status. Useful for reporting a specific
+ // |error|: The returned print job error. Useful for reporting a specific
// error.
- void OnExtensionPrintResult(const std::string& callback_id,
- bool success,
- const std::string& status);
+ void OnPrintResult(const std::string& callback_id,
+ bool success,
+ const base::Value& error);
// Register/unregister from notifications of changes done to the GAIA
// cookie.
@@ -434,39 +375,20 @@ class PrintPreviewHandler
// cookie changes.
GaiaCookieManagerService* gaia_cookie_manager_service_;
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- scoped_refptr<local_discovery::ServiceDiscoverySharedClient>
- service_discovery_client_;
- std::unique_ptr<cloud_print::PrivetLocalPrinterLister> printer_lister_;
- std::unique_ptr<base::OneShotTimer> privet_lister_timer_;
- std::unique_ptr<cloud_print::PrivetHTTPAsynchronousFactory>
- privet_http_factory_;
- std::unique_ptr<cloud_print::PrivetHTTPResolution> privet_http_resolution_;
- std::unique_ptr<cloud_print::PrivetV1HTTPClient> privet_http_client_;
- std::unique_ptr<cloud_print::PrivetJSONOperation>
- privet_capabilities_operation_;
- std::unique_ptr<cloud_print::PrivetLocalPrintOperation>
- privet_local_print_operation_;
-#endif
-
// Handles requests for extension printers. Created lazily by calling
- // |EnsureExtensionPrinterHandlerSet|.
+ // |GetPrinterHandler|.
std::unique_ptr<PrinterHandler> extension_printer_handler_;
+ // Handles requests for privet printers. Created lazily by calling
+ // |GetPrinterHandler|.
+ std::unique_ptr<PrinterHandler> privet_printer_handler_;
+
// Notifies tests that want to know if the PDF has been saved. This doesn't
// notify the test if it was a successful save, only that it was attempted.
base::Closure pdf_file_saved_closure_;
std::queue<std::string> preview_callbacks_;
-#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
- // Callback ID to be used to notify UI that privet search is finished.
- std::string privet_search_callback_id_;
-
- // Callback ID to be used to notify UI that privet printing is finished.
- std::string privet_print_callback_id_;
-#endif
-
// Callback ID to be used to notify UI that PDF file selection has finished.
std::string pdf_callback_id_;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_win_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_win_unittest.cc
index c7b6e5c29e5..61a1d1ae872 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_win_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_win_unittest.cc
@@ -20,6 +20,7 @@
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/web_contents.h"
#include "ui/shell_dialogs/select_file_dialog_win.h"
+#include "ui/shell_dialogs/select_file_policy.h"
using content::WebContents;
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 2294f9ca85b..6cabe3985a9 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
@@ -9,8 +9,8 @@
#include <utility>
#include <vector>
+#include "base/containers/id_map.h"
#include "base/feature_list.h"
-#include "base/id_map.h"
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
@@ -112,7 +112,7 @@ base::LazyInstance<PrintPreviewRequestIdMapWithLock>::DestructorAtExit
// PrintPreviewUI IDMap used to avoid exposing raw pointer addresses to WebUI.
// Only accessed on the UI thread.
-base::LazyInstance<IDMap<PrintPreviewUI*>>::DestructorAtExit
+base::LazyInstance<base::IDMap<PrintPreviewUI*>>::DestructorAtExit
g_print_preview_ui_id_map = LAZY_INSTANCE_INITIALIZER;
// PrintPreviewUI serves data for chrome://print requests.
@@ -158,7 +158,7 @@ bool HandleRequestCallback(
return true;
}
// Invalid request.
- scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
+ auto empty_bytes = base::MakeRefCounted<base::RefCountedBytes>();
callback.Run(empty_bytes.get());
return true;
}
@@ -336,18 +336,6 @@ content::WebUIDataSource* CreatePrintPreviewUISource(Profile* profile) {
source->AddLocalizedString("offlineForWeek",
IDS_PRINT_PREVIEW_OFFLINE_FOR_WEEK);
source->AddLocalizedString("offline", IDS_PRINT_PREVIEW_OFFLINE);
- source->AddLocalizedString("noDestsPromoTitle",
- IDS_PRINT_PREVIEW_NO_DESTS_PROMO_TITLE);
- source->AddLocalizedString("noDestsPromoBody",
- IDS_PRINT_PREVIEW_NO_DESTS_PROMO_BODY);
- source->AddLocalizedString("noDestsPromoGcpDesc",
- IDS_PRINT_PREVIEW_NO_DESTS_GCP_DESC);
- source->AddLocalizedString("learnMore",
- IDS_LEARN_MORE);
- source->AddLocalizedString(
- "noDestsPromoAddPrinterButtonLabel",
- IDS_PRINT_PREVIEW_NO_DESTS_PROMO_ADD_PRINTER_BUTTON_LABEL);
- source->AddLocalizedString("noDestsPromoNotNowButtonLabel", IDS_NOT_NOW);
source->AddLocalizedString("couldNotPrint",
IDS_PRINT_PREVIEW_COULD_NOT_PRINT);
source->AddLocalizedString("registerPromoButtonText",
diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc
index 12910fae0f9..b374eda8358 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_ui_unittest.cc
@@ -28,11 +28,11 @@ using web_modal::WebContentsModalDialogManager;
namespace {
-base::RefCountedBytes* CreateTestData() {
+scoped_refptr<base::RefCountedBytes> CreateTestData() {
const unsigned char blob1[] =
"12346102356120394751634516591348710478123649165419234519234512349134";
std::vector<unsigned char> preview_data(blob1, blob1 + sizeof(blob1));
- return new base::RefCountedBytes(preview_data);
+ return base::MakeRefCounted<base::RefCountedBytes>(preview_data);
}
bool IsShowingWebContentsModalDialog(WebContents* tab) {
@@ -105,7 +105,7 @@ TEST_F(PrintPreviewUIUnitTest, PrintPreviewData) {
EXPECT_EQ(dummy_data.get(), data.get());
// This should not cause any memory leaks.
- dummy_data = new base::RefCountedBytes();
+ dummy_data = base::MakeRefCounted<base::RefCountedBytes>();
preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX,
dummy_data.get());
diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc
index f06e3f26e6f..06de50cd0f8 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/printer_capabilities_unittest.cc
@@ -23,7 +23,7 @@ class PrinterCapabilitiesTest : public testing::Test {
protected:
void SetUp() override {
- test_backend_ = new TestPrintBackend();
+ test_backend_ = base::MakeRefCounted<TestPrintBackend>();
PrintBackend::SetPrintBackendForTesting(test_backend_.get());
}
diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc
index 14dad1238b3..f949ac80b85 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.cc
@@ -4,11 +4,24 @@
#include "chrome/browser/ui/webui/print_preview/printer_handler.h"
+#include "build/buildflag.h"
#include "chrome/browser/ui/webui/print_preview/extension_printer_handler.h"
+#include "chrome/common/features.h"
+
+#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
+#include "chrome/browser/ui/webui/print_preview/privet_printer_handler.h"
+#endif
// static
std::unique_ptr<PrinterHandler> PrinterHandler::CreateForExtensionPrinters(
- content::BrowserContext* browser_context) {
- return std::unique_ptr<ExtensionPrinterHandler>(
- new ExtensionPrinterHandler(browser_context));
+ Profile* profile) {
+ return base::MakeUnique<ExtensionPrinterHandler>(profile);
+}
+
+#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
+// static
+std::unique_ptr<PrinterHandler> PrinterHandler::CreateForPrivetPrinters(
+ Profile* profile) {
+ return base::MakeUnique<PrivetPrinterHandler>(profile);
}
+#endif
diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h
index 58b215f6008..5ec697689c6 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h
@@ -11,16 +11,16 @@
#include "base/callback.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
+#include "chrome/common/features.h"
namespace base {
class DictionaryValue;
class ListValue;
-class RefCountedMemory;
+class RefCountedBytes;
+class Value;
}
-namespace content {
-class BrowserContext;
-}
+class Profile;
namespace gfx {
class Size;
@@ -37,13 +37,19 @@ class PrinterHandler {
using GetCapabilityCallback =
base::Callback<void(const base::DictionaryValue& capability)>;
using PrintCallback =
- base::Callback<void(bool success, const std::string& error)>;
+ base::Callback<void(bool success, const base::Value& error)>;
using GetPrinterInfoCallback =
base::Callback<void(const base::DictionaryValue& printer_info)>;
- // Creates an instance of an PrinterHandler for extension printers.
+ // Creates an instance of a PrinterHandler for extension printers.
static std::unique_ptr<PrinterHandler> CreateForExtensionPrinters(
- content::BrowserContext* browser_context);
+ Profile* profile);
+
+#if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
+ // Creates an instance of a PrinterHandler for privet printers.
+ static std::unique_ptr<PrinterHandler> CreateForPrivetPrinters(
+ Profile* profile);
+#endif
virtual ~PrinterHandler() {}
@@ -83,7 +89,7 @@ class PrinterHandler {
const base::string16& job_title,
const std::string& ticket_json,
const gfx::Size& page_size,
- const scoped_refptr<base::RefCountedMemory>& print_data,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
const PrintCallback& callback) = 0;
};
diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc
new file mode 100644
index 00000000000..cfbce68a14c
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc
@@ -0,0 +1,274 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/print_preview/privet_printer_handler.h"
+
+#include <memory>
+#include <string>
+
+#include "base/bind.h"
+#include "base/callback.h"
+#include "base/command_line.h"
+#include "base/memory/ref_counted.h"
+#include "base/memory/ref_counted_memory.h"
+#include "base/memory/weak_ptr.h"
+#include "base/strings/string16.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/timer/timer.h"
+#include "chrome/browser/printing/cloud_print/privet_constants.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/signin/signin_manager_factory.h"
+#include "chrome/common/chrome_switches.h"
+#include "components/signin/core/browser/signin_manager.h"
+#include "ui/gfx/geometry/size.h"
+
+namespace {
+// Timeout for searching for privet printers, in seconds.
+const int kSearchTimeoutSec = 5;
+
+void FillPrinterDescription(const std::string& name,
+ const cloud_print::DeviceDescription& description,
+ bool has_local_printing,
+ base::DictionaryValue* printer_value) {
+ base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
+
+ printer_value->SetString("serviceName", name);
+ printer_value->SetString("name", description.name);
+ printer_value->SetBoolean("hasLocalPrinting", has_local_printing);
+ printer_value->SetBoolean(
+ "isUnregistered",
+ description.id.empty() &&
+ command_line->HasSwitch(switches::kEnablePrintPreviewRegisterPromos));
+ printer_value->SetString("cloudID", description.id);
+}
+} // namespace
+
+PrivetPrinterHandler::PrivetPrinterHandler(Profile* profile)
+ : profile_(profile), weak_ptr_factory_(this) {}
+
+PrivetPrinterHandler::~PrivetPrinterHandler() {}
+
+void PrivetPrinterHandler::Reset() {
+ weak_ptr_factory_.InvalidateWeakPtrs();
+}
+
+void PrivetPrinterHandler::StartGetPrinters(
+ const PrinterHandler::GetPrintersCallback& callback) {
+ using local_discovery::ServiceDiscoverySharedClient;
+ scoped_refptr<ServiceDiscoverySharedClient> service_discovery =
+ ServiceDiscoverySharedClient::GetInstance();
+ get_printers_callback_ = callback;
+ StartLister(service_discovery);
+}
+
+void PrivetPrinterHandler::StartGetCapability(
+ const std::string& destination_id,
+ const PrinterHandler::GetCapabilityCallback& callback) {
+ if (!CreateHTTP(destination_id,
+ base::Bind(&PrivetPrinterHandler::CapabilitiesUpdateClient,
+ weak_ptr_factory_.GetWeakPtr(), callback))) {
+ callback.Run(base::DictionaryValue());
+ }
+}
+
+void PrivetPrinterHandler::StartPrint(
+ const std::string& destination_id,
+ const std::string& capability,
+ const base::string16& job_title,
+ const std::string& ticket_json,
+ const gfx::Size& page_size,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
+ const PrinterHandler::PrintCallback& callback) {
+ if (!CreateHTTP(
+ destination_id,
+ base::Bind(&PrivetPrinterHandler::PrintUpdateClient,
+ weak_ptr_factory_.GetWeakPtr(), callback, job_title,
+ print_data, ticket_json, capability, page_size))) {
+ callback.Run(false, base::Value(-1));
+ }
+}
+
+void PrivetPrinterHandler::StartGrantPrinterAccess(
+ const std::string& printer_id,
+ const PrinterHandler::GetPrinterInfoCallback& callback) {
+ NOTREACHED();
+}
+
+void PrivetPrinterHandler::LocalPrinterChanged(
+ const std::string& name,
+ bool has_local_printing,
+ const cloud_print::DeviceDescription& description) {
+ base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
+ if (has_local_printing ||
+ command_line->HasSwitch(switches::kEnablePrintPreviewRegisterPromos)) {
+ auto printer_info = base::MakeUnique<base::DictionaryValue>();
+ FillPrinterDescription(name, description, has_local_printing,
+ printer_info.get());
+ base::ListValue printers;
+ printers.Set(0, std::move(printer_info));
+ get_printers_callback_.Run(printers, false);
+ }
+}
+
+void PrivetPrinterHandler::LocalPrinterRemoved(const std::string& name) {}
+
+void PrivetPrinterHandler::LocalPrinterCacheFlushed() {}
+
+void PrivetPrinterHandler::OnPrivetPrintingDone(
+ const cloud_print::PrivetLocalPrintOperation* print_operation) {
+ DCHECK(print_callback_);
+ print_callback_.Run(true, base::Value());
+}
+
+void PrivetPrinterHandler::OnPrivetPrintingError(
+ const cloud_print::PrivetLocalPrintOperation* print_operation,
+ int http_code) {
+ DCHECK(print_callback_);
+ print_callback_.Run(false, base::Value(http_code));
+}
+
+void PrivetPrinterHandler::StartLister(
+ const scoped_refptr<local_discovery::ServiceDiscoverySharedClient>&
+ client) {
+ DCHECK(!service_discovery_client_.get() ||
+ service_discovery_client_.get() == client.get());
+ service_discovery_client_ = client;
+ printer_lister_ = base::MakeUnique<cloud_print::PrivetLocalPrinterLister>(
+ service_discovery_client_.get(), profile_->GetRequestContext(), this);
+ privet_lister_timer_ = base::MakeUnique<base::OneShotTimer>();
+ privet_lister_timer_->Start(FROM_HERE,
+ base::TimeDelta::FromSeconds(kSearchTimeoutSec),
+ this, &PrivetPrinterHandler::StopLister);
+ printer_lister_->Start();
+}
+
+void PrivetPrinterHandler::StopLister() {
+ privet_lister_timer_.reset();
+ if (printer_lister_)
+ printer_lister_->Stop();
+ get_printers_callback_.Run(base::ListValue(), true);
+}
+
+void PrivetPrinterHandler::CapabilitiesUpdateClient(
+ const PrinterHandler::GetCapabilityCallback& callback,
+ std::unique_ptr<cloud_print::PrivetHTTPClient> http_client) {
+ if (!UpdateClient(std::move(http_client))) {
+ callback.Run(base::DictionaryValue());
+ return;
+ }
+
+ privet_capabilities_operation_ =
+ privet_http_client_->CreateCapabilitiesOperation(
+ base::Bind(&PrivetPrinterHandler::OnGotCapabilities,
+ weak_ptr_factory_.GetWeakPtr(), callback));
+ privet_capabilities_operation_->Start();
+}
+
+void PrivetPrinterHandler::OnGotCapabilities(
+ const PrinterHandler::GetCapabilityCallback& callback,
+ const base::DictionaryValue* capabilities) {
+ if (!capabilities || capabilities->HasKey(cloud_print::kPrivetKeyError) ||
+ !printer_lister_) {
+ callback.Run(base::DictionaryValue());
+ return;
+ }
+
+ std::string name = privet_capabilities_operation_->GetHTTPClient()->GetName();
+ const cloud_print::DeviceDescription* description =
+ printer_lister_->GetDeviceDescription(name);
+
+ if (!description) {
+ callback.Run(base::DictionaryValue());
+ return;
+ }
+
+ std::unique_ptr<base::DictionaryValue> printer_info =
+ base::MakeUnique<base::DictionaryValue>();
+ FillPrinterDescription(name, *description, true, printer_info.get());
+ base::DictionaryValue printer_info_and_caps;
+ printer_info_and_caps.SetDictionary("printer", std::move(printer_info));
+ std::unique_ptr<base::DictionaryValue> capabilities_copy =
+ capabilities->CreateDeepCopy();
+ printer_info_and_caps.SetDictionary("capabilities",
+ std::move(capabilities_copy));
+ callback.Run(printer_info_and_caps);
+ privet_capabilities_operation_.reset();
+}
+
+void PrivetPrinterHandler::PrintUpdateClient(
+ const PrinterHandler::PrintCallback& callback,
+ const base::string16& job_title,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
+ const std::string& print_ticket,
+ const std::string& capabilities,
+ const gfx::Size& page_size,
+ std::unique_ptr<cloud_print::PrivetHTTPClient> http_client) {
+ if (!UpdateClient(std::move(http_client))) {
+ callback.Run(false, base::Value(-1));
+ return;
+ }
+ print_callback_ = callback;
+ StartPrint(job_title, print_data, print_ticket, capabilities, page_size);
+}
+
+bool PrivetPrinterHandler::UpdateClient(
+ std::unique_ptr<cloud_print::PrivetHTTPClient> http_client) {
+ if (!http_client) {
+ privet_http_resolution_.reset();
+ return false;
+ }
+
+ privet_local_print_operation_.reset();
+ privet_capabilities_operation_.reset();
+ privet_http_client_ =
+ cloud_print::PrivetV1HTTPClient::CreateDefault(std::move(http_client));
+
+ privet_http_resolution_.reset();
+
+ return true;
+}
+
+void PrivetPrinterHandler::StartPrint(
+ const base::string16& job_title,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
+ const std::string& print_ticket,
+ const std::string& capabilities,
+ const gfx::Size& page_size) {
+ privet_local_print_operation_ =
+ privet_http_client_->CreateLocalPrintOperation(this);
+
+ privet_local_print_operation_->SetTicket(print_ticket);
+ privet_local_print_operation_->SetCapabilities(capabilities);
+ privet_local_print_operation_->SetJobname(base::UTF16ToUTF8(job_title));
+ privet_local_print_operation_->SetPageSize(page_size);
+ privet_local_print_operation_->SetData(print_data);
+
+ SigninManagerBase* signin_manager =
+ SigninManagerFactory::GetForProfileIfExists(profile_);
+ if (signin_manager) {
+ privet_local_print_operation_->SetUsername(
+ signin_manager->GetAuthenticatedAccountInfo().email);
+ }
+
+ privet_local_print_operation_->Start();
+}
+
+bool PrivetPrinterHandler::CreateHTTP(
+ const std::string& name,
+ const cloud_print::PrivetHTTPAsynchronousFactory::ResultCallback&
+ callback) {
+ const cloud_print::DeviceDescription* device_description =
+ printer_lister_ ? printer_lister_->GetDeviceDescription(name) : nullptr;
+
+ if (!device_description)
+ return false;
+
+ privet_http_factory_ =
+ cloud_print::PrivetHTTPAsynchronousFactory::CreateInstance(
+ profile_->GetRequestContext());
+ privet_http_resolution_ = privet_http_factory_->CreatePrivetHTTP(name);
+ privet_http_resolution_->Start(device_description->address, callback);
+
+ return true;
+}
diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h
new file mode 100644
index 00000000000..c4bb903b85b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h
@@ -0,0 +1,121 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRIVET_PRINTER_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRIVET_PRINTER_HANDLER_H_
+
+#include <memory>
+#include <string>
+
+#include "base/macros.h"
+#include "base/memory/ref_counted.h"
+#include "base/memory/weak_ptr.h"
+#include "base/strings/string16.h"
+#include "chrome/browser/local_discovery/service_discovery_shared_client.h"
+#include "chrome/browser/printing/cloud_print/privet_local_printer_lister.h"
+#include "chrome/browser/ui/webui/print_preview/printer_handler.h"
+
+namespace base {
+class DictionaryValue;
+class OneShotTimer;
+class RefCountedBytes;
+} // namespace base
+
+namespace gfx {
+class Size;
+}
+
+// Implementation of PrinterHandler interface
+class PrivetPrinterHandler
+ : public PrinterHandler,
+ public cloud_print::PrivetLocalPrinterLister::Delegate,
+ public cloud_print::PrivetLocalPrintOperation::Delegate {
+ public:
+ explicit PrivetPrinterHandler(Profile* profile);
+
+ ~PrivetPrinterHandler() override;
+
+ // PrinterHandler implementation:
+ void Reset() override;
+ void StartGetPrinters(
+ const PrinterHandler::GetPrintersCallback& callback) override;
+ void StartGetCapability(
+ const std::string& destination_id,
+ const PrinterHandler::GetCapabilityCallback& calback) override;
+ // TODO(tbarzic): It might make sense to have the strings in a single struct.
+ void StartPrint(const std::string& destination_id,
+ const std::string& capability,
+ const base::string16& job_title,
+ const std::string& ticket_json,
+ const gfx::Size& page_size,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
+ const PrinterHandler::PrintCallback& callback) override;
+ void StartGrantPrinterAccess(
+ const std::string& printer_id,
+ const PrinterHandler::GetPrinterInfoCallback& callback) override;
+
+ // PrivetLocalPrinterLister::Delegate implementation.
+ void LocalPrinterChanged(
+ const std::string& name,
+ bool has_local_printing,
+ const cloud_print::DeviceDescription& description) override;
+ void LocalPrinterRemoved(const std::string& name) override;
+ void LocalPrinterCacheFlushed() override;
+
+ // PrivetLocalPrintOperation::Delegate implementation.
+ void OnPrivetPrintingDone(
+ const cloud_print::PrivetLocalPrintOperation* print_operation) override;
+ void OnPrivetPrintingError(
+ const cloud_print::PrivetLocalPrintOperation* print_operation,
+ int http_code) override;
+
+ private:
+ void StartLister(
+ const scoped_refptr<local_discovery::ServiceDiscoverySharedClient>&
+ client);
+ void StopLister();
+ void CapabilitiesUpdateClient(
+ const PrinterHandler::GetCapabilityCallback& callback,
+ std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
+ void OnGotCapabilities(const PrinterHandler::GetCapabilityCallback& callback,
+ const base::DictionaryValue* capabilities);
+ void PrintUpdateClient(
+ const PrinterHandler::PrintCallback& callback,
+ const base::string16& job_title,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
+ const std::string& print_ticket,
+ const std::string& capabilities,
+ const gfx::Size& page_size,
+ std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
+ bool UpdateClient(std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
+ void StartPrint(const base::string16& job_title,
+ const scoped_refptr<base::RefCountedBytes>& print_data,
+ const std::string& print_ticket,
+ const std::string& capabilities,
+ const gfx::Size& page_size);
+ bool CreateHTTP(
+ const std::string& name,
+ const cloud_print::PrivetHTTPAsynchronousFactory::ResultCallback&
+ callback);
+
+ Profile* profile_;
+ scoped_refptr<local_discovery::ServiceDiscoverySharedClient>
+ service_discovery_client_;
+ std::unique_ptr<cloud_print::PrivetLocalPrinterLister> printer_lister_;
+ std::unique_ptr<base::OneShotTimer> privet_lister_timer_;
+ std::unique_ptr<cloud_print::PrivetHTTPAsynchronousFactory>
+ privet_http_factory_;
+ std::unique_ptr<cloud_print::PrivetHTTPResolution> privet_http_resolution_;
+ std::unique_ptr<cloud_print::PrivetV1HTTPClient> privet_http_client_;
+ std::unique_ptr<cloud_print::PrivetJSONOperation>
+ privet_capabilities_operation_;
+ std::unique_ptr<cloud_print::PrivetLocalPrintOperation>
+ privet_local_print_operation_;
+ PrinterHandler::GetPrintersCallback get_printers_callback_;
+ PrinterHandler::PrintCallback print_callback_;
+ base::WeakPtrFactory<PrivetPrinterHandler> weak_ptr_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(PrivetPrinterHandler);
+};
+#endif // CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_PRIVET_PRINTER_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.cc b/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.cc
index b2507188aa0..222469eb911 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.cc
@@ -4,6 +4,7 @@
#include "chrome/browser/ui/webui/print_preview/sticky_settings.h"
+#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
@@ -22,14 +23,18 @@ StickySettings::StickySettings() {}
StickySettings::~StickySettings() {}
+const std::string* StickySettings::printer_app_state() const {
+ return printer_app_state_ ? &printer_app_state_.value() : nullptr;
+}
+
void StickySettings::StoreAppState(const std::string& data) {
- printer_app_state_.reset(new std::string(data));
+ printer_app_state_ = base::make_optional(data);
}
-void StickySettings::SaveInPrefs(PrefService* prefs) {
- std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
+void StickySettings::SaveInPrefs(PrefService* prefs) const {
+ auto value = base::MakeUnique<base::DictionaryValue>();
if (printer_app_state_)
- value->SetString(kSettingAppState, *printer_app_state_);
+ value->SetString(kSettingAppState, printer_app_state_.value());
prefs->Set(prefs::kPrintPreviewStickySettings, *value);
}
@@ -41,13 +46,10 @@ void StickySettings::RestoreFromPrefs(PrefService* prefs) {
StoreAppState(buffer);
}
+// static
void StickySettings::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterDictionaryPref(prefs::kPrintPreviewStickySettings);
}
-std::string* StickySettings::printer_app_state() {
- return printer_app_state_.get();
-}
-
} // namespace printing
diff --git a/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.h b/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.h
index ddc142bb29d..e2a10d5c173 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/sticky_settings.h
@@ -5,9 +5,9 @@
#ifndef CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_STICKY_SETTINGS_H_
#define CHROME_BROWSER_UI_WEBUI_PRINT_PREVIEW_STICKY_SETTINGS_H_
-#include <memory>
#include <string>
+#include "base/optional.h"
#include "printing/print_job_constants.h"
class PrefService;
@@ -26,17 +26,18 @@ class StickySettings {
StickySettings();
~StickySettings();
- std::string* printer_app_state();
+ const std::string* printer_app_state() const;
// Stores app state for the last used printer.
void StoreAppState(const std::string& app_state);
- void SaveInPrefs(PrefService* profile);
+ void SaveInPrefs(PrefService* profile) const;
void RestoreFromPrefs(PrefService* profile);
+
static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
private:
- std::unique_ptr<std::string> printer_app_state_;
+ base::Optional<std::string> printer_app_state_;
};
} // namespace printing
diff --git a/chromium/chrome/browser/ui/webui/profile_helper.cc b/chromium/chrome/browser/ui/webui/profile_helper.cc
index fb660613cde..33cf95ad713 100644
--- a/chromium/chrome/browser/ui/webui/profile_helper.cc
+++ b/chromium/chrome/browser/ui/webui/profile_helper.cc
@@ -74,7 +74,12 @@ void DeleteProfileCallback(std::unique_ptr<ScopedKeepAlive> keep_alive,
void OpenNewWindowForProfile(Profile* profile) {
if (profiles::IsProfileLocked(profile->GetPath())) {
if (signin_util::IsForceSigninEnabled()) {
- ShowUserManager(base::Bind(&ShowSigninDialog, profile->GetPath()));
+ // Show sign in dialog iff there is one locked profile.
+ if (g_browser_process->profile_manager()->GetNumberOfProfiles() == 1) {
+ ShowUserManager(base::Bind(&ShowSigninDialog, profile->GetPath()));
+ } else {
+ ShowUserManager(ProfileManager::CreateCallback());
+ }
} else {
ShowUserManager(
base::Bind(&ShowReauthDialog, GetProfileUserName(profile)));
diff --git a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc
index d0cecfb2392..9834fa8cbe4 100644
--- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc
+++ b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc
@@ -52,16 +52,19 @@ namespace {
const char kSetAsDefaultBrowserHistogram[] = "DefaultBrowser.InteractionResult";
-// The enum permits registering in UMA the three possible outcomes (do not
+// The enum permits registering in UMA the four possible outcomes (do not
// reorder these).
// ACCEPTED: user pressed Next and made Chrome default.
// DECLINED: user simply closed the dialog without making Chrome default.
-// REGRETTED: user pressed Next but then elected a different default browser.
+// REGRETTED: user pressed Next but then selected a different default browser.
+// ACCEPTED_OTHER_MODE: user selected a different side-by-side install of
+// Chrome.
enum MakeChromeDefaultResult {
MAKE_CHROME_DEFAULT_ACCEPTED = 0,
MAKE_CHROME_DEFAULT_DECLINED = 1,
MAKE_CHROME_DEFAULT_REGRETTED = 2,
// MAKE_CHROME_DEFAULT_ACCEPTED_IMMERSE = 3, // Deprecated.
+ MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE = 4,
MAKE_CHROME_DEFAULT_MAX
};
@@ -166,12 +169,25 @@ void SetAsDefaultBrowserHandler::OnDefaultBrowserWorkerFinished(
shell_integration::DefaultWebClientState state) {
// The callback is expected to be invoked once the procedure has completed.
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (state == shell_integration::NOT_DEFAULT) {
- // The operation concluded, but Chrome is still not the default. This
- // suggests the user has decided not to make Chrome the default.
- ConcludeInteraction(MAKE_CHROME_DEFAULT_REGRETTED);
- } else if (state == shell_integration::IS_DEFAULT) {
- ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED);
+ switch (state) {
+ case shell_integration::NOT_DEFAULT:
+ // The operation concluded, but Chrome is still not the default. This
+ // suggests the user has decided not to make Chrome the default.
+ ConcludeInteraction(MAKE_CHROME_DEFAULT_REGRETTED);
+ break;
+ case shell_integration::IS_DEFAULT:
+ ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED);
+ break;
+ case shell_integration::UNKNOWN_DEFAULT:
+ break;
+ case shell_integration::OTHER_MODE_IS_DEFAULT:
+ // Interestingly, the user picked a different install mode of this browser
+ // (e.g., stable Chrome rather than Chrome Beta).
+ ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE);
+ break;
+ case shell_integration::NUM_DEFAULT_STATES:
+ NOTREACHED();
+ break;
}
// Otherwise, keep the dialog open since the user probably didn't make a
@@ -298,8 +314,10 @@ void SetAsDefaultBrowserDialogImpl::OnDialogClosed(
// Suppress showing the default browser infobar if the user explicitly elected
// *not to* make Chrome default.
- if (dialog_interaction_result_ == MAKE_CHROME_DEFAULT_REGRETTED)
+ if (dialog_interaction_result_ == MAKE_CHROME_DEFAULT_REGRETTED ||
+ dialog_interaction_result_ == MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE) {
chrome::DefaultBrowserPromptDeclined(profile_);
+ }
// Carry on with a normal chrome session. For the purpose of surfacing this
// dialog the actual browser window had to remain hidden. Now it's time to
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc
index f4e3bd21af2..783593ba83d 100644
--- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc
@@ -8,7 +8,6 @@
#include <string>
-#include "ash/system/devicetype_utils.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
@@ -72,6 +71,7 @@
#include "chromeos/network/network_state_handler.h"
#include "chromeos/system/statistics_provider.h"
#include "components/user_manager/user_manager.h"
+#include "ui/chromeos/devicetype_utils.h"
#endif
using base::ListValue;
@@ -568,22 +568,22 @@ void AboutHandler::HandleRequestUpdateOverCellular(
const base::ListValue* args) {
CHECK_EQ(2U, args->GetSize());
- std::string target_version;
- std::string target_size_string;
- int64_t target_size;
+ std::string update_version;
+ std::string update_size_string;
+ int64_t update_size;
- CHECK(args->GetString(0, &target_version));
- CHECK(args->GetString(1, &target_size_string));
- CHECK(base::StringToInt64(target_size_string, &target_size));
+ CHECK(args->GetString(0, &update_version));
+ CHECK(args->GetString(1, &update_size_string));
+ CHECK(base::StringToInt64(update_size_string, &update_size));
- RequestUpdateOverCellular(target_version, target_size);
+ RequestUpdateOverCellular(update_version, update_size);
}
-void AboutHandler::RequestUpdateOverCellular(const std::string& target_version,
- int64_t target_size) {
- version_updater_->SetUpdateOverCellularTarget(
+void AboutHandler::RequestUpdateOverCellular(const std::string& update_version,
+ int64_t update_size) {
+ version_updater_->SetUpdateOverCellularOneTimePermission(
base::Bind(&AboutHandler::SetUpdateStatus, base::Unretained(this)),
- target_version, target_size);
+ update_version, update_size);
}
#endif // defined(OS_CHROMEOS)
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.h b/chromium/chrome/browser/ui/webui/settings/about_handler.h
index 3c6577519d1..f213735e091 100644
--- a/chromium/chrome/browser/ui/webui/settings/about_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/about_handler.h
@@ -107,12 +107,12 @@ class AboutHandler : public settings::SettingsPageUIHandler,
void HandleRequestUpdate(const base::ListValue* args);
// Checks for and applies update over cellular connection, triggered by JS.
- // Target version and size should be included in the list of arguments.
+ // Update version and size should be included in the list of arguments.
void HandleRequestUpdateOverCellular(const base::ListValue* args);
- // Checks for and applies update over cellular connection to the given target.
- void RequestUpdateOverCellular(const std::string& target_version,
- int64_t target_size);
+ // Checks for and applies update over cellular connection.
+ void RequestUpdateOverCellular(const std::string& update_version,
+ int64_t update_size);
#endif
diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc
index c863519b315..dae38e4333b 100644
--- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc
@@ -14,6 +14,7 @@
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
+#include "chromeos/login/login_state.h"
#endif
namespace settings {
@@ -43,6 +44,16 @@ void AppearanceHandler::RegisterMessages() {
"openWallpaperManager",
base::Bind(&AppearanceHandler::HandleOpenWallpaperManager,
base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "isWallpaperSettingVisible",
+ base::Bind(&AppearanceHandler::IsWallpaperSettingVisible,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "isWallpaperPolicyControlled",
+ base::Bind(&AppearanceHandler::IsWallpaperPolicyControlled,
+ base::Unretained(this)));
#endif
}
@@ -60,9 +71,51 @@ void AppearanceHandler::HandleUseSystemTheme(const base::ListValue* args) {
#endif
#if defined(OS_CHROMEOS)
+void AppearanceHandler::IsWallpaperSettingVisible(const base::ListValue* args) {
+ CHECK_EQ(args->GetSize(), 1U);
+ const base::Value* callback_id;
+ CHECK(args->Get(0, &callback_id));
+ AllowJavascript();
+
+ bool is_wallpaper_visible = false;
+ const chromeos::LoginState* login_state = chromeos::LoginState::Get();
+ const chromeos::LoginState::LoggedInUserType user_type =
+ login_state->GetLoggedInUserType();
+ const user_manager::User* user =
+ user_manager::UserManager::Get()->GetActiveUser();
+
+ // Only login, whitelist types and active users are allowed to change
+ // their wallpaper. Then show the wallpaper setting row for them.
+ if (login_state->IsUserLoggedIn() && user &&
+ (user_type == chromeos::LoginState::LOGGED_IN_USER_REGULAR ||
+ user_type == chromeos::LoginState::LOGGED_IN_USER_OWNER ||
+ user_type == chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT ||
+ user_type == chromeos::LoginState::LOGGED_IN_USER_SUPERVISED)) {
+ is_wallpaper_visible = true;
+ }
+
+ ResolveJavascriptCallback(*callback_id, base::Value(is_wallpaper_visible));
+}
+
+void AppearanceHandler::IsWallpaperPolicyControlled(
+ const base::ListValue* args) {
+ CHECK_EQ(args->GetSize(), 1U);
+ const base::Value* callback_id;
+ CHECK(args->Get(0, &callback_id));
+ AllowJavascript();
+
+ ResolveJavascriptCallback(
+ *callback_id,
+ base::Value(chromeos::WallpaperManager::Get()->IsPolicyControlled(
+ user_manager::UserManager::Get()->GetActiveUser()->GetAccountId())));
+}
+
void AppearanceHandler::HandleOpenWallpaperManager(
const base::ListValue* /*args*/) {
- chromeos::WallpaperManager::Get()->Open();
+ if (!chromeos::WallpaperManager::Get()->IsPolicyControlled(
+ user_manager::UserManager::Get()->GetActiveUser()->GetAccountId())) {
+ chromeos::WallpaperManager::Get()->Open();
+ }
}
#endif
diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h
index a00a9637dc7..d31af5aa186 100644
--- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h
@@ -41,6 +41,12 @@ class AppearanceHandler : public SettingsPageUIHandler {
#endif
#if defined(OS_CHROMEOS)
+ // Whether should show the wallpaper setting row.
+ void IsWallpaperSettingVisible(const base::ListValue* args);
+
+ // Whether the wallpaper is policy controlled.
+ void IsWallpaperPolicyControlled(const base::ListValue* args);
+
// Open the wallpaper manager app.
void HandleOpenWallpaperManager(const base::ListValue* args);
#endif
diff --git a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc
new file mode 100644
index 00000000000..d847d122e18
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc
@@ -0,0 +1,56 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/settings/change_password_handler.h"
+
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/safe_browsing/safe_browsing_service.h"
+#include "components/prefs/pref_service.h"
+#include "components/safe_browsing/password_protection/password_protection_service.h"
+#include "content/public/browser/page_navigator.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_ui.h"
+
+
+namespace settings {
+
+ChangePasswordHandler::ChangePasswordHandler(Profile* profile)
+ : profile_(profile), service_(nullptr) {
+ if (g_browser_process && g_browser_process->safe_browsing_service()) {
+ service_ = g_browser_process->safe_browsing_service()
+ ->GetPasswordProtectionService(profile_);
+ }
+}
+
+ChangePasswordHandler::~ChangePasswordHandler() {}
+
+void ChangePasswordHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "onChangePasswordPageShown",
+ base::Bind(&ChangePasswordHandler::HandleChangePasswordPageShown,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "changePassword", base::Bind(&ChangePasswordHandler::HandleChangePassword,
+ base::Unretained(this)));
+}
+
+void ChangePasswordHandler::HandleChangePasswordPageShown(
+ const base::ListValue* args) {
+ if (service_) {
+ service_->OnWarningShown(
+ web_ui()->GetWebContents(),
+ safe_browsing::PasswordProtectionService::CHROME_SETTINGS);
+ }
+}
+
+void ChangePasswordHandler::HandleChangePassword(const base::ListValue* args) {
+ if (service_) {
+ service_->OnWarningDone(
+ web_ui()->GetWebContents(),
+ safe_browsing::PasswordProtectionService::CHROME_SETTINGS,
+ safe_browsing::PasswordProtectionService::CHANGE_PASSWORD);
+ }
+}
+
+} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/change_password_handler.h b/chromium/chrome/browser/ui/webui/settings/change_password_handler.h
new file mode 100644
index 00000000000..9f1ef3bc92f
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.h
@@ -0,0 +1,50 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHANGE_PASSWORD_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHANGE_PASSWORD_HANDLER_H_
+
+#include <memory>
+#include <vector>
+
+#include "base/macros.h"
+#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
+#include "components/prefs/pref_change_registrar.h"
+
+class Profile;
+
+namespace safe_browsing {
+class PasswordProtectionService;
+}
+
+namespace settings {
+
+// Chrome "Change Password" settings page UI handler.
+class ChangePasswordHandler : public SettingsPageUIHandler {
+ public:
+ explicit ChangePasswordHandler(Profile* profile);
+ ~ChangePasswordHandler() override;
+
+ // SettingsPageUIHandler implementation.
+ void RegisterMessages() override;
+ void OnJavascriptAllowed() override {}
+ void OnJavascriptDisallowed() override {}
+
+ private:
+ void HandleChangePasswordPageShown(const base::ListValue* args);
+
+ void HandleChangePassword(const base::ListValue* args);
+
+ Profile* profile_;
+
+ PrefChangeRegistrar pref_registrar_;
+
+ safe_browsing::PasswordProtectionService* service_;
+
+ DISALLOW_COPY_AND_ASSIGN(ChangePasswordHandler);
+};
+
+} // namespace settings
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHANGE_PASSWORD_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc
index 25352bdd42e..85ba7ba1984 100644
--- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.cc
@@ -9,6 +9,8 @@
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
+#include "base/metrics/user_metrics.h"
+#include "base/metrics/user_metrics_action.h"
#include "base/synchronization/lock.h"
#include "base/values.h"
#include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h"
@@ -23,6 +25,15 @@ namespace settings {
namespace {
+// These numeric values must be kept in sync with the definition of
+// settings.ChromeCleanupDismissSource in
+// chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js.
+enum ChromeCleanerDismissSource {
+ kOther = 0,
+ kCleanupSuccessDoneButton = 1,
+ kCleanupFailureDoneButton = 2,
+};
+
// Returns a ListValue containing a copy of the file paths stored in |files|.
base::ListValue GetFilesAsListStorage(const std::set<base::FilePath>& files) {
base::ListValue value;
@@ -82,6 +93,15 @@ void ChromeCleanupHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"startCleanup", base::Bind(&ChromeCleanupHandler::HandleStartCleanup,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "notifyShowDetails",
+ base::Bind(&ChromeCleanupHandler::HandleNotifyShowDetails,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "notifyChromeCleanupLearnMoreClicked",
+ base::Bind(
+ &ChromeCleanupHandler::HandleNotifyChromeCleanupLearnMoreClicked,
+ base::Unretained(this)));
}
void ChromeCleanupHandler::OnJavascriptAllowed() {
@@ -128,7 +148,27 @@ void ChromeCleanupHandler::OnLogsEnabledChanged(bool logs_enabled) {
}
void ChromeCleanupHandler::HandleDismiss(const base::ListValue* args) {
- DCHECK_EQ(0U, args->GetSize());
+ CHECK_EQ(1U, args->GetSize());
+ int dismiss_source_int = -1;
+ CHECK(args->GetInteger(0, &dismiss_source_int));
+
+ ChromeCleanerDismissSource dismiss_source =
+ static_cast<ChromeCleanerDismissSource>(dismiss_source_int);
+
+ switch (dismiss_source) {
+ case kCleanupSuccessDoneButton:
+ base::RecordAction(base::UserMetricsAction(
+ "SoftwareReporter.CleanupWebui_CleanupSuccessDone"));
+ break;
+ case kCleanupFailureDoneButton:
+ base::RecordAction(base::UserMetricsAction(
+ "SoftwareReporter.CleanupWebui_CleanupFailureDone"));
+ break;
+ case kOther:
+ break;
+ default:
+ NOTREACHED();
+ }
controller_->RemoveObserver(this);
controller_->ResetIdleState();
@@ -146,6 +186,8 @@ void ChromeCleanupHandler::HandleRegisterChromeCleanerObserver(
base::FeatureList::IsEnabled(safe_browsing::kInBrowserCleanerUIFeature));
UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.CleanupCard", true);
+ base::RecordAction(
+ base::UserMetricsAction("SoftwareReporter.CleanupWebui_Shown"));
AllowJavascript();
// Send the current logs upload state.
@@ -155,6 +197,9 @@ void ChromeCleanupHandler::HandleRegisterChromeCleanerObserver(
void ChromeCleanupHandler::HandleRestartComputer(const base::ListValue* args) {
DCHECK_EQ(0U, args->GetSize());
+ base::RecordAction(
+ base::UserMetricsAction("SoftwareReporter.CleanupWebui_RestartComputer"));
+
CallJavascriptFunction("cr.webUIListenerCallback",
base::Value("chrome-cleanup-on-dismiss"));
@@ -167,6 +212,14 @@ void ChromeCleanupHandler::HandleSetLogsUploadPermission(
bool allow_logs_upload = false;
args->GetBoolean(0, &allow_logs_upload);
+ if (allow_logs_upload) {
+ base::RecordAction(base::UserMetricsAction(
+ "SoftwareReporter.CleanupWebui_LogsUploadEnabled"));
+ } else {
+ base::RecordAction(base::UserMetricsAction(
+ "SoftwareReporter.CleanupWebui_LogsUploadDisabled"));
+ }
+
controller_->SetLogsEnabled(allow_logs_upload);
}
@@ -180,6 +233,9 @@ void ChromeCleanupHandler::HandleStartCleanup(const base::ListValue* args) {
safe_browsing::RecordCleanupStartedHistogram(
safe_browsing::CLEANUP_STARTED_FROM_PROMPT_IN_SETTINGS);
+ base::RecordAction(
+ base::UserMetricsAction("SoftwareReporter.CleanupWebui_StartCleanup"));
+
controller_->ReplyWithUserResponse(
profile_,
allow_logs_upload
@@ -187,4 +243,27 @@ void ChromeCleanupHandler::HandleStartCleanup(const base::ListValue* args) {
: ChromeCleanerController::UserResponse::kAcceptedWithoutLogs);
}
+void ChromeCleanupHandler::HandleNotifyShowDetails(
+ const base::ListValue* args) {
+ CHECK_EQ(1U, args->GetSize());
+ bool details_section_visible = false;
+ args->GetBoolean(0, &details_section_visible);
+
+ if (details_section_visible) {
+ base::RecordAction(
+ base::UserMetricsAction("SoftwareReporter.CleanupWebui_ShowDetails"));
+ } else {
+ base::RecordAction(
+ base::UserMetricsAction("SoftwareReporter.CleanupWebui_HideDetails"));
+ }
+}
+
+void ChromeCleanupHandler::HandleNotifyChromeCleanupLearnMoreClicked(
+ const base::ListValue* args) {
+ CHECK_EQ(0U, args->GetSize());
+
+ base::RecordAction(
+ base::UserMetricsAction("SoftwareReporter.CleanupWebui_LearnMore"));
+}
+
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h
index 59f4493ceb6..f26f2fcf439 100644
--- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler.h
@@ -60,6 +60,14 @@ class ChromeCleanupHandler
// software from the user's computer.
void HandleStartCleanup(const base::ListValue* args);
+ // Callback for the "showDetails" message that notifies Chrome about whether
+ // the user expanded or closed the details section of the page.
+ void HandleNotifyShowDetails(const base::ListValue* args);
+
+ // Callback for the "chromeCleanupLearnMore" message that notifies Chrome that
+ // the "learn more" link was clicked.
+ void HandleNotifyChromeCleanupLearnMoreClicked(const base::ListValue* args);
+
// Raw pointer to a singleton. Must outlive this object.
safe_browsing::ChromeCleanerController* controller_;
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc
index fccd102c341..e8b08bb9da3 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.cc
@@ -8,6 +8,9 @@
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h" // kSettingsAppId
+#include "content/public/browser/web_contents.h"
+#include "ui/display/display.h"
+#include "ui/display/screen.h"
#include "ui/events/event_constants.h"
namespace chromeos {
@@ -99,7 +102,11 @@ void AndroidAppsHandler::ShowAndroidAppsSettings(const base::ListValue* args) {
// Settings in secondary profile cannot access ARC.
CHECK(arc::IsArcAllowedForProfile(profile_));
- arc::LaunchAndroidSettingsApp(profile_, flags);
+ const int64_t display_id =
+ display::Screen::GetScreen()
+ ->GetDisplayNearestView(web_ui()->GetWebContents()->GetNativeView())
+ .id();
+ arc::LaunchAndroidSettingsApp(profile_, flags, display_id);
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc
index 4c75079683d..37cabdcad79 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/change_picture_handler.cc
@@ -141,7 +141,8 @@ void ChangePictureHandler::SendDefaultImages() {
void ChangePictureHandler::HandleChooseFile(const base::ListValue* args) {
DCHECK(args && args->empty());
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
base::FilePath downloads_path;
if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_path)) {
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 a75305fab98..86a3de231ad 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
@@ -184,7 +184,9 @@ std::string PrinterAddress(const std::string& host, int port) {
return host;
}
-// Returns a JSON representation of |printer| as a CupsPrinterInfo.
+// Returns a JSON representation of |printer| as a CupsPrinterInfo. Note it's
+// possible that this function returns a nullptr if the printer url is not in
+// the right format.
std::unique_ptr<base::DictionaryValue> GetPrinterInfo(const Printer& printer) {
std::unique_ptr<base::DictionaryValue> printer_info =
CreateEmptyPrinterInfo();
@@ -308,7 +310,11 @@ void CupsPrintersHandler::HandleGetCupsPrintersList(
auto printers_list = base::MakeUnique<base::ListValue>();
for (const Printer& printer : printers) {
- printers_list->Append(GetPrinterInfo(printer));
+ // TODO(skau): Theoretically |printer_info| should not be a nullptr as we
+ // should not allow adding an invalid configured printer to PrinterManager.
+ auto printer_info = GetPrinterInfo(printer);
+ if (printer_info)
+ printers_list->Append(std::move(printer_info));
}
auto response = base::MakeUnique<base::DictionaryValue>();
@@ -495,6 +501,14 @@ void CupsPrintersHandler::HandleAddCupsPrinter(const base::ListValue* args) {
printer_uri += "/" + printer_queue;
}
+ // Validate uri before continuing.
+ PrinterUri uri;
+ if (!ParseUri(printer_uri, &uri)) {
+ LOG(ERROR) << "Failed to parse printer";
+ OnAddPrinterError();
+ return;
+ }
+
// Read PPD selection if it was used.
std::string ppd_manufacturer;
std::string ppd_model;
@@ -677,7 +691,8 @@ void CupsPrintersHandler::HandleSelectPPDFile(const base::ListValue* args) {
->DownloadPath();
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
gfx::NativeWindow owning_window =
chrome::FindBrowserWithWebContents(web_ui()->GetWebContents())
->window()
@@ -771,10 +786,14 @@ void CupsPrintersHandler::OnPrintersChanged(
std::unique_ptr<base::ListValue> printers_list =
base::MakeUnique<base::ListValue>();
for (const Printer& printer : automatic_printers_) {
- printers_list->Append(GetPrinterInfo(printer));
+ auto printer_info = GetPrinterInfo(printer);
+ if (printer_info)
+ printers_list->Append(std::move(printer_info));
}
for (const Printer& printer : discovered_printers_) {
- printers_list->Append(GetPrinterInfo(printer));
+ auto printer_info = GetPrinterInfo(printer);
+ if (printer_info)
+ printers_list->Append(std::move(printer_info));
}
FireWebUIListener("on-printer-discovered", *printers_list);
@@ -789,9 +808,11 @@ void CupsPrintersHandler::HandleAddDiscoveredPrinter(
CHECK(args->GetString(0, &printer_id));
std::unique_ptr<Printer> printer = printers_manager_->GetPrinter(printer_id);
- if (printer == nullptr) {
+ PrinterUri uri;
+ if (printer == nullptr || !ParseUri(printer->uri(), &uri)) {
// Printer disappeared, so we don't have information about it anymore and
- // can't really do much. Fail the add.
+ // can't really do much. Or the printer uri was not parsed successfully.
+ // Fail the add.
FireWebUIListener("on-add-cups-printer", base::Value(false),
base::Value(printer_id));
return;
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc
index 5ff31cac218..be631336538 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.cc
@@ -259,15 +259,16 @@ void PowerHandler::SendBatteryStatus() {
base::string16 status_text;
if (show_time) {
status_text = l10n_util::GetStringFUTF16(
- charging ? IDS_OPTIONS_BATTERY_STATUS_CHARGING
- : IDS_OPTIONS_BATTERY_STATUS,
+ charging ? IDS_SETTINGS_BATTERY_STATUS_CHARGING
+ : IDS_SETTINGS_BATTERY_STATUS,
base::IntToString16(percent), GetBatteryTimeText(time_left));
} else {
- status_text = l10n_util::GetStringFUTF16(IDS_OPTIONS_BATTERY_STATUS_SHORT,
+ status_text = l10n_util::GetStringFUTF16(IDS_SETTINGS_BATTERY_STATUS_SHORT,
base::IntToString16(percent));
}
base::DictionaryValue battery_dict;
+ battery_dict.SetBoolean("present", power_status_->IsBatteryPresent());
battery_dict.SetBoolean("charging", charging);
battery_dict.SetBoolean("calculating", calculating);
battery_dict.SetInteger("percent", percent);
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 b6ddf0a4ecf..14bbb70fefb 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
@@ -277,8 +277,8 @@ void StorageHandler::OnGetBrowsingDataSize(bool is_site_data, int64_t size) {
size_string = ui::FormatBytes(
browser_site_data_size_ + browser_cache_size_);
} else {
- size_string = l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_UNKNOWN);
+ size_string =
+ l10n_util::GetStringUTF16(IDS_SETTINGS_STORAGE_SIZE_UNKNOWN);
}
updating_browsing_data_size_ = false;
FireWebUIListener("storage-browsing-data-size-changed",
@@ -321,8 +321,8 @@ void StorageHandler::OnGetOtherUserSize(bool success, int64_t size) {
size_string = ui::FormatBytes(
std::accumulate(user_sizes_.begin(), user_sizes_.end(), 0LL));
} else {
- size_string = l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_UNKNOWN);
+ size_string =
+ l10n_util::GetStringUTF16(IDS_SETTINGS_STORAGE_SIZE_UNKNOWN);
}
updating_other_users_size_ = false;
FireWebUIListener("storage-other-users-size-changed",
@@ -363,8 +363,7 @@ void StorageHandler::OnGetAndroidSize(bool succeeded,
size->total_cache_bytes;
size_string = ui::FormatBytes(total_bytes);
} else {
- size_string = l10n_util::GetStringUTF16(
- IDS_OPTIONS_SETTINGS_STORAGE_SIZE_UNKNOWN);
+ size_string = l10n_util::GetStringUTF16(IDS_SETTINGS_STORAGE_SIZE_UNKNOWN);
}
updating_android_size_ = false;
FireWebUIListener("storage-android-size-changed", base::Value(size_string));
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
new file mode 100644
index 00000000000..69675d49bc5
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc
@@ -0,0 +1,303 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/settings/custom_home_pages_table_model.h"
+
+#include <stddef.h>
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/i18n/rtl.h"
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/history/history_service_factory.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/history/core/browser/history_service.h"
+#include "components/url_formatter/url_formatter.h"
+#include "content/public/browser/web_contents.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/base/models/table_model_observer.h"
+#include "ui/gfx/codec/png_codec.h"
+#include "url/gurl.h"
+
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/ui/settings_window_manager_chromeos.h"
+#endif
+
+struct CustomHomePagesTableModel::Entry {
+ Entry() : task_id(base::CancelableTaskTracker::kBadTaskId) {}
+
+ // URL of the page.
+ GURL url;
+
+ // Page title. If this is empty, we'll display the URL as the entry.
+ base::string16 title;
+
+ // If not |base::CancelableTaskTracker::kBadTaskId|, indicates we're loading
+ // the title for the page.
+ base::CancelableTaskTracker::TaskId task_id;
+};
+
+CustomHomePagesTableModel::CustomHomePagesTableModel(Profile* profile)
+ : profile_(profile),
+ observer_(NULL),
+ num_outstanding_title_lookups_(0) {
+}
+
+CustomHomePagesTableModel::~CustomHomePagesTableModel() {
+}
+
+void CustomHomePagesTableModel::SetURLs(const std::vector<GURL>& urls) {
+ entries_.resize(urls.size());
+ for (size_t i = 0; i < urls.size(); ++i) {
+ entries_[i].url = urls[i];
+ entries_[i].title.erase();
+ }
+ LoadAllTitles();
+}
+
+/**
+ * Move a number of existing entries to a new position, reordering the table.
+ *
+ * We determine the range of elements affected by the move, save the moved
+ * elements, compact the remaining ones, and re-insert moved elements.
+ * Expects |index_list| to be ordered ascending.
+ */
+void CustomHomePagesTableModel::MoveURLs(int insert_before,
+ const std::vector<int>& index_list) {
+ if (index_list.empty()) return;
+ DCHECK(insert_before >= 0 && insert_before <= RowCount());
+
+ // The range of elements that needs to be reshuffled is [ |first|, |last| ).
+ int first = std::min(insert_before, index_list.front());
+ int last = std::max(insert_before, index_list.back() + 1);
+
+ // Save the dragged elements. Also, adjust insertion point if it is before a
+ // dragged element.
+ std::vector<Entry> moved_entries;
+ for (size_t i = 0; i < index_list.size(); ++i) {
+ moved_entries.push_back(entries_[index_list[i]]);
+ if (index_list[i] == insert_before)
+ insert_before++;
+ }
+
+ // Compact the range between beginning and insertion point, moving downwards.
+ size_t skip_count = 0;
+ for (int i = first; i < insert_before; ++i) {
+ if (skip_count < index_list.size() && index_list[skip_count] == i)
+ skip_count++;
+ else
+ entries_[i - skip_count] = entries_[i];
+ }
+
+ // Moving items down created a gap. We start compacting up after it.
+ first = insert_before;
+ insert_before -= skip_count;
+
+ // Now compact up for elements after the insertion point.
+ skip_count = 0;
+ for (int i = last - 1; i >= first; --i) {
+ if (skip_count < index_list.size() &&
+ index_list[index_list.size() - skip_count - 1] == i) {
+ skip_count++;
+ } else {
+ entries_[i + skip_count] = entries_[i];
+ }
+ }
+
+ // Insert moved elements.
+ std::copy(moved_entries.begin(), moved_entries.end(),
+ entries_.begin() + insert_before);
+
+ // Possibly large change, so tell the view to just rebuild itself.
+ if (observer_)
+ observer_->OnModelChanged();
+}
+
+void CustomHomePagesTableModel::AddWithoutNotification(
+ int index, const GURL& url) {
+ DCHECK(index >= 0 && index <= RowCount());
+ entries_.insert(entries_.begin() + static_cast<size_t>(index), Entry());
+ entries_[index].url = url;
+}
+
+void CustomHomePagesTableModel::Add(int index, const GURL& url) {
+ AddWithoutNotification(index, url);
+ LoadTitle(&(entries_[index]));
+ if (observer_)
+ observer_->OnItemsAdded(index, 1);
+}
+
+void CustomHomePagesTableModel::RemoveWithoutNotification(int index) {
+ DCHECK(index >= 0 && index < RowCount());
+ Entry* entry = &(entries_[index]);
+ // Cancel any pending load requests now so we don't deref a bogus pointer when
+ // we get the loaded notification.
+ if (entry->task_id != base::CancelableTaskTracker::kBadTaskId) {
+ task_tracker_.TryCancel(entry->task_id);
+ entry->task_id = base::CancelableTaskTracker::kBadTaskId;
+ }
+ entries_.erase(entries_.begin() + static_cast<size_t>(index));
+}
+
+void CustomHomePagesTableModel::Remove(int index) {
+ RemoveWithoutNotification(index);
+ if (observer_)
+ observer_->OnItemsRemoved(index, 1);
+}
+
+void CustomHomePagesTableModel::SetToCurrentlyOpenPages(
+ const content::WebContents* ignore_contents) {
+ // Remove the current entries.
+ while (RowCount())
+ RemoveWithoutNotification(0);
+
+ // Add tabs from appropriate browser windows.
+ int add_index = 0;
+ for (auto* browser : *BrowserList::GetInstance()) {
+ if (!ShouldIncludeBrowser(browser))
+ continue;
+
+ for (int tab_index = 0;
+ tab_index < browser->tab_strip_model()->count();
+ ++tab_index) {
+ const content::WebContents* contents =
+ browser->tab_strip_model()->GetWebContentsAt(tab_index);
+ if (contents == ignore_contents)
+ continue;
+ const GURL url = contents->GetURL();
+ if (!url.is_empty() && !url.SchemeIs(content::kChromeDevToolsScheme))
+ AddWithoutNotification(add_index++, url);
+ }
+ }
+ LoadAllTitles();
+}
+
+std::vector<GURL> CustomHomePagesTableModel::GetURLs() {
+ std::vector<GURL> urls(entries_.size());
+ for (size_t i = 0; i < entries_.size(); ++i)
+ urls[i] = entries_[i].url;
+ return urls;
+}
+
+int CustomHomePagesTableModel::RowCount() {
+ return static_cast<int>(entries_.size());
+}
+
+base::string16 CustomHomePagesTableModel::GetText(int row, int column_id) {
+ DCHECK(column_id == 0);
+ DCHECK(row >= 0 && row < RowCount());
+ return entries_[row].title.empty() ? FormattedURL(row) : entries_[row].title;
+}
+
+base::string16 CustomHomePagesTableModel::GetTooltip(int row) {
+ return entries_[row].title.empty()
+ ? base::string16()
+ : l10n_util::GetStringFUTF16(IDS_SETTINGS_ON_STARTUP_PAGE_TOOLTIP,
+ entries_[row].title,
+ FormattedURL(row));
+}
+
+void CustomHomePagesTableModel::SetObserver(ui::TableModelObserver* observer) {
+ observer_ = observer;
+}
+
+bool CustomHomePagesTableModel::ShouldIncludeBrowser(Browser* browser) {
+ // Do not include incognito browsers.
+ if (browser->profile() != profile_)
+ return false;
+#if defined(OS_CHROMEOS)
+ // Do not include the Settings window.
+ if (chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(
+ browser)) {
+ return false;
+ }
+#endif
+ return true;
+}
+
+void CustomHomePagesTableModel::LoadTitle(Entry* entry) {
+ history::HistoryService* history_service =
+ HistoryServiceFactory::GetForProfile(profile_,
+ ServiceAccessType::EXPLICIT_ACCESS);
+ if (history_service) {
+ entry->task_id = history_service->QueryURL(
+ entry->url,
+ false,
+ base::Bind(&CustomHomePagesTableModel::OnGotTitle,
+ base::Unretained(this),
+ entry->url,
+ false),
+ &task_tracker_);
+ }
+}
+
+void CustomHomePagesTableModel::LoadAllTitles() {
+ history::HistoryService* history_service =
+ HistoryServiceFactory::GetForProfile(profile_,
+ ServiceAccessType::EXPLICIT_ACCESS);
+ // It's possible for multiple LoadAllTitles() queries to be inflight we want
+ // to make sure everything is resolved before updating the observer or we risk
+ // getting rendering glitches.
+ num_outstanding_title_lookups_ += entries_.size();
+ for (Entry& entry : entries_) {
+ if (history_service) {
+ entry.task_id = history_service->QueryURL(
+ entry.url,
+ false,
+ base::Bind(&CustomHomePagesTableModel::OnGotOneOfManyTitles,
+ base::Unretained(this),
+ entry.url),
+ &task_tracker_);
+ }
+ }
+ if (entries_.empty())
+ observer_->OnModelChanged();
+}
+
+void CustomHomePagesTableModel::OnGotOneOfManyTitles(const GURL& entry_url,
+ bool found_url,
+ const history::URLRow& row,
+ const history::VisitVector& visits) {
+ OnGotTitle(entry_url, false, found_url, row, visits);
+ DCHECK_GE(num_outstanding_title_lookups_, 1);
+ if (--num_outstanding_title_lookups_ == 0 && observer_)
+ observer_->OnModelChanged();
+}
+
+void CustomHomePagesTableModel::OnGotTitle(const GURL& entry_url,
+ bool observable,
+ bool found_url,
+ const history::URLRow& row,
+ const history::VisitVector& visits) {
+ Entry* entry = NULL;
+ size_t entry_index = 0;
+ for (size_t i = 0; i < entries_.size(); ++i) {
+ if (entries_[i].url == entry_url) {
+ entry = &entries_[i];
+ entry_index = i;
+ break;
+ }
+ }
+ if (!entry) {
+ // The URLs changed before we were called back.
+ return;
+ }
+ entry->task_id = base::CancelableTaskTracker::kBadTaskId;
+ if (found_url && !row.title().empty()) {
+ entry->title = row.title();
+ if (observer_ && observable)
+ observer_->OnItemsChanged(static_cast<int>(entry_index), 1);
+ }
+}
+
+base::string16 CustomHomePagesTableModel::FormattedURL(int row) const {
+ base::string16 url = url_formatter::FormatUrl(entries_[row].url);
+ url = base::i18n::GetDisplayStringInLTRDirectionality(url);
+ return url;
+}
diff --git a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h
new file mode 100644
index 00000000000..04760e43e7b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.h
@@ -0,0 +1,127 @@
+// 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_SETTINGS_CUSTOM_HOME_PAGES_TABLE_MODEL_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CUSTOM_HOME_PAGES_TABLE_MODEL_H_
+
+#include <string>
+#include <vector>
+
+#include "base/compiler_specific.h"
+#include "base/macros.h"
+#include "base/task/cancelable_task_tracker.h"
+#include "components/history/core/browser/history_types.h"
+#include "ui/base/models/table_model.h"
+
+class Browser;
+class GURL;
+class Profile;
+
+namespace content {
+class WebContents;
+}
+
+namespace history {
+class URLRow;
+}
+
+namespace ui {
+class TableModelObserver;
+}
+
+// CustomHomePagesTableModel is the model for the TableView showing the list
+// of pages the user wants opened on startup.
+
+class CustomHomePagesTableModel : public ui::TableModel {
+ public:
+ explicit CustomHomePagesTableModel(Profile* profile);
+ ~CustomHomePagesTableModel() override;
+
+ // Sets the set of urls that this model contains.
+ void SetURLs(const std::vector<GURL>& urls);
+
+ // Collect all entries indexed by |index_list|, and moves them to be right
+ // before the element addressed by |insert_before|. Used by Drag&Drop.
+ // Expects |index_list| to be ordered ascending.
+ void MoveURLs(int insert_before, const std::vector<int>& index_list);
+
+ // Adds an entry at the specified index.
+ void Add(int index, const GURL& url);
+
+ // Removes the entry at the specified index.
+ void Remove(int index);
+
+ // Clears any entries and fills the list with pages currently opened in the
+ // browser. |ignore_contents| is omitted from the open pages.
+ void SetToCurrentlyOpenPages(const content::WebContents* ignore_contents);
+
+ // Returns the set of urls this model contains.
+ std::vector<GURL> GetURLs();
+
+ // TableModel overrides:
+ int RowCount() override;
+ base::string16 GetText(int row, int column_id) override;
+ base::string16 GetTooltip(int row) override;
+ void SetObserver(ui::TableModelObserver* observer) override;
+
+ private:
+ // Each item in the model is represented as an Entry. Entry stores the URL
+ // and title of the page.
+ struct Entry;
+
+ // Returns false if pages from |browser| should not be considered.
+ bool ShouldIncludeBrowser(Browser* browser);
+
+ // Loads the title for the specified entry.
+ void LoadTitle(Entry* entry);
+
+ // Loads all the titles, notifies the observer of the change once all loads
+ // are complete.
+ void LoadAllTitles();
+
+ // Callback from history service. Updates the title of the Entry whose
+ // |url| matches |entry_url| and notifies the observer of the change if
+ // |observable| is true.
+ void OnGotTitle(const GURL& entry_url,
+ bool observable,
+ bool found_url,
+ const history::URLRow& row,
+ const history::VisitVector& visits);
+
+ // Like OnGotTitle, except that num_outstanding_title_lookups_ is decremented
+ // and if the count reaches zero the observer is notifed.
+ void OnGotOneOfManyTitles(const GURL& entry_url,
+ bool found_url,
+ const history::URLRow& row,
+ const history::VisitVector& visits);
+
+ // Adds an entry at the specified index, but doesn't load the title or tell
+ // the observer.
+ void AddWithoutNotification(int index, const GURL& url);
+
+ // Removes the entry at the specified index, but doesn't tell the observer.
+ void RemoveWithoutNotification(int index);
+
+ // Returns the URL for a particular row, formatted for display to the user.
+ base::string16 FormattedURL(int row) const;
+
+ // Set of entries we're showing.
+ std::vector<Entry> entries_;
+
+ // Profile used to load titles.
+ Profile* profile_;
+
+ ui::TableModelObserver* observer_;
+
+ // Used in loading titles.
+ base::CancelableTaskTracker task_tracker_;
+
+ // Used to keep track of when it's time to update the observer when loading
+ // multiple titles.
+ int num_outstanding_title_lookups_;
+
+ DISALLOW_COPY_AND_ASSIGN(CustomHomePagesTableModel);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CUSTOM_HOME_PAGES_TABLE_MODEL_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc b/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc
index e5acd37e95a..b5ab983a438 100644
--- a/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/downloads_handler.cc
@@ -83,7 +83,8 @@ void DownloadsHandler::HandleSelectDownloadLocation(
const base::ListValue* args) {
PrefService* pref_service = profile_->GetPrefs();
select_folder_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
ui::SelectFileDialog::FileTypeInfo info;
info.allowed_paths = ui::SelectFileDialog::FileTypeInfo::NATIVE_OR_DRIVE_PATH;
select_folder_dialog_->SelectFile(
diff --git a/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc b/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc
index 5439d599a88..9eba60e7cc4 100644
--- a/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/extension_control_handler.cc
@@ -11,7 +11,7 @@
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/web_ui.h"
#include "extensions/browser/extension_system.h"
-#include "extensions/common/extension.h"
+#include "extensions/common/disable_reason.h"
namespace settings {
@@ -32,7 +32,7 @@ void ExtensionControlHandler::HandleDisableExtension(
Profile::FromWebUI(web_ui()))->extension_service();
DCHECK(extension_service);
extension_service->DisableExtension(
- extension_id, extensions::Extension::DISABLE_USER_ACTION);
+ extension_id, extensions::disable_reason::DISABLE_USER_ACTION);
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
index 3dbd09b2a41..665e94308a7 100644
--- a/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -35,17 +35,17 @@
#if defined(OS_CHROMEOS)
#include "ash/strings/grit/ash_strings.h"
-#include "ash/system/devicetype_utils.h"
#include "ash/system/night_light/night_light_controller.h"
#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h"
#include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h"
#include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h"
-#include "chrome/browser/ui/webui/chromeos/ui_account_tweaks.h"
#include "chromeos/chromeos_switches.h"
#include "components/arc/arc_util.h"
#include "components/user_manager/user_manager.h"
+#include "ui/chromeos/devicetype_utils.h"
#include "ui/chromeos/events/keyboard_layout_util.h"
#include "ui/display/display_switches.h"
#else
@@ -56,12 +56,20 @@
#include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h"
#endif
+#if defined(USE_NSS_CERTS)
+#include "chrome/browser/ui/webui/certificate_manager_localized_strings_provider.h"
+#endif
+
+#if defined(SAFE_BROWSING_DB_LOCAL)
+#include "components/safe_browsing/password_protection/password_protection_service.h"
+#endif
+
namespace settings {
namespace {
// Note that settings.html contains a <script> tag which imports a script of
// the following name. These names must be kept in sync.
-const char kLocalizedStringsFile[] = "strings.js";
+constexpr char kLocalizedStringsFile[] = "strings.js";
struct LocalizedString {
const char* name;
@@ -155,48 +163,43 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
{"monoAudioLabel", IDS_SETTINGS_MONO_AUDIO_LABEL},
{"a11yExplanation", IDS_SETTINGS_ACCESSIBILITY_EXPLANATION},
{"caretHighlightLabel",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_CARET_HIGHLIGHT_DESCRIPTION},
+ IDS_SETTINGS_ACCESSIBILITY_CARET_HIGHLIGHT_DESCRIPTION},
{"cursorHighlightLabel",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_CURSOR_HIGHLIGHT_DESCRIPTION},
+ IDS_SETTINGS_ACCESSIBILITY_CURSOR_HIGHLIGHT_DESCRIPTION},
{"focusHighlightLabel",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_FOCUS_HIGHLIGHT_DESCRIPTION},
- {"selectToSpeakTitle",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_TITLE},
+ IDS_SETTINGS_ACCESSIBILITY_FOCUS_HIGHLIGHT_DESCRIPTION},
+ {"selectToSpeakTitle", IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_TITLE},
{"selectToSpeakDescription",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_DESCRIPTION},
+ IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_DESCRIPTION},
{"selectToSpeakOptionsLabel",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_OPTIONS_LABEL},
- {"switchAccessLabel",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_DESCRIPTION},
+ IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_OPTIONS_LABEL},
+ {"switchAccessLabel", IDS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_DESCRIPTION},
{"switchAccessOptionsLabel",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_OPTIONS_LABEL},
+ IDS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_OPTIONS_LABEL},
{"manageAccessibilityFeatures",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES},
- {"textToSpeechHeading",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_TEXT_TO_SPEECH_HEADING},
- {"displayHeading", IDS_OPTIONS_SETTINGS_ACCESSIBILITY_DISPLAY_HEADING},
- {"displaySettingsTitle",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_DISPLAY_SETTINGS_TITLE},
+ IDS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES},
+ {"textToSpeechHeading", IDS_SETTINGS_ACCESSIBILITY_TEXT_TO_SPEECH_HEADING},
+ {"displayHeading", IDS_SETTINGS_ACCESSIBILITY_DISPLAY_HEADING},
+ {"displaySettingsTitle", IDS_SETTINGS_ACCESSIBILITY_DISPLAY_SETTINGS_TITLE},
{"displaySettingsDescription",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_DISPLAY_SETTINGS_DESCRIPTION},
+ IDS_SETTINGS_ACCESSIBILITY_DISPLAY_SETTINGS_DESCRIPTION},
{"appearanceSettingsTitle",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_APPEARANCE_SETTINGS_TITLE},
+ IDS_SETTINGS_ACCESSIBILITY_APPEARANCE_SETTINGS_TITLE},
{"appearanceSettingsDescription",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_APPEARANCE_SETTINGS_DESCRIPTION},
- {"keyboardHeading", IDS_OPTIONS_SETTINGS_ACCESSIBILITY_KEYBOARD_HEADING},
+ IDS_SETTINGS_ACCESSIBILITY_APPEARANCE_SETTINGS_DESCRIPTION},
+ {"keyboardHeading", IDS_SETTINGS_ACCESSIBILITY_KEYBOARD_HEADING},
{"keyboardSettingsTitle",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_KEYBOARD_SETTINGS_TITLE},
+ IDS_SETTINGS_ACCESSIBILITY_KEYBOARD_SETTINGS_TITLE},
{"keyboardSettingsDescription",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_KEYBOARD_SETTINGS_DESCRIPTION},
+ IDS_SETTINGS_ACCESSIBILITY_KEYBOARD_SETTINGS_DESCRIPTION},
{"mouseAndTouchpadHeading",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_MOUSE_AND_TOUCHPAD_HEADING},
- {"mouseSettingsTitle",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_MOUSE_SETTINGS_TITLE},
+ IDS_SETTINGS_ACCESSIBILITY_MOUSE_AND_TOUCHPAD_HEADING},
+ {"mouseSettingsTitle", IDS_SETTINGS_ACCESSIBILITY_MOUSE_SETTINGS_TITLE},
{"mouseSettingsDescription",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_MOUSE_SETTINGS_DESCRIPTION},
- {"audioHeading", IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUDIO_HEADING},
+ IDS_SETTINGS_ACCESSIBILITY_MOUSE_SETTINGS_DESCRIPTION},
+ {"audioHeading", IDS_SETTINGS_ACCESSIBILITY_AUDIO_HEADING},
{"additionalFeaturesTitle",
- IDS_OPTIONS_SETTINGS_ACCESSIBILITY_ADDITIONAL_FEATURES_TITLE},
+ IDS_SETTINGS_ACCESSIBILITY_ADDITIONAL_FEATURES_TITLE},
#endif
};
AddLocalizedStringsBulk(html_source, localized_strings,
@@ -238,6 +241,7 @@ void AddAboutStrings(content::WebUIDataSource* html_source) {
{"aboutArcVersionLabel", IDS_SETTINGS_ABOUT_PAGE_ARC_VERSION},
{"aboutBuildDateLabel", IDS_VERSION_UI_BUILD_DATE},
{"aboutChannelBeta", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_BETA},
+ {"aboutChannelCanary", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_CANARY},
{"aboutChannelDev", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_DEV},
{"aboutChannelLabel", IDS_SETTINGS_ABOUT_PAGE_CHANNEL},
{"aboutChannelStable", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_STABLE},
@@ -288,20 +292,13 @@ void AddAboutStrings(content::WebUIDataSource* html_source) {
html_source->AddString(
"aboutUpgradeUpToDate",
#if defined(OS_CHROMEOS)
- ash::SubstituteChromeOSDeviceType(IDS_SETTINGS_UPGRADE_UP_TO_DATE));
+ ui::SubstituteChromeOSDeviceType(IDS_SETTINGS_UPGRADE_UP_TO_DATE));
#else
l10n_util::GetStringUTF16(IDS_SETTINGS_UPGRADE_UP_TO_DATE));
#endif
}
#if defined(OS_CHROMEOS)
-void AddAccountUITweaksStrings(content::WebUIDataSource* html_source,
- Profile* profile) {
- base::DictionaryValue localized_values;
- chromeos::AddAccountUITweaksLocalizedValues(&localized_values, profile);
- html_source->AddLocalizedStrings(localized_values);
-}
-
void AddAndroidAppStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"androidAppsPageTitle", arc::IsPlayStoreAvailable()
@@ -311,7 +308,6 @@ void AddAndroidAppStrings(content::WebUIDataSource* html_source) {
{"androidAppsEnable", IDS_SETTINGS_ANDROID_APPS_ENABLE},
{"androidAppsManageApps", IDS_SETTINGS_ANDROID_APPS_MANAGE_APPS},
{"androidAppsRemove", IDS_SETTINGS_ANDROID_APPS_REMOVE},
- {"androidAppsLearnMore", IDS_SETTINGS_ANDROID_APPS_LEARN_MORE},
{"androidAppsDisableDialogTitle",
IDS_SETTINGS_ANDROID_APPS_DISABLE_DIALOG_TITLE},
{"androidAppsDisableDialogMessage",
@@ -359,8 +355,7 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source,
{"showWindowDecorations", IDS_SHOW_WINDOW_DECORATIONS},
#endif
#if defined(OS_MACOSX)
- // TODO(dbeam): use an IDS_SETTINGS_* string instead.
- {"tabsToLinks", IDS_OPTIONS_TABS_TO_LINKS_PREF},
+ {"tabsToLinks", IDS_SETTINGS_TABS_TO_LINKS_PREF},
#endif
};
AddLocalizedStringsBulk(html_source, localized_strings,
@@ -370,15 +365,13 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source,
#if defined(OS_CHROMEOS)
void AddBluetoothStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
- {"bluetoothAccept", IDS_OPTIONS_SETTINGS_BLUETOOTH_ACCEPT_PASSKEY},
{"bluetoothConnected", IDS_SETTINGS_BLUETOOTH_CONNECTED},
{"bluetoothConnecting", IDS_SETTINGS_BLUETOOTH_CONNECTING},
{"bluetoothDeviceListPaired", IDS_SETTINGS_BLUETOOTH_DEVICE_LIST_PAIRED},
{"bluetoothDeviceListUnpaired",
IDS_SETTINGS_BLUETOOTH_DEVICE_LIST_UNPAIRED},
- {"bluetoothConnect", IDS_OPTIONS_SETTINGS_BLUETOOTH_CONNECT},
- {"bluetoothDisconnect", IDS_OPTIONS_SETTINGS_BLUETOOTH_DISCONNECT},
- {"bluetoothDismiss", IDS_OPTIONS_SETTINGS_BLUETOOTH_DISMISS_ERROR},
+ {"bluetoothConnect", IDS_SETTINGS_BLUETOOTH_CONNECT},
+ {"bluetoothDisconnect", IDS_SETTINGS_BLUETOOTH_DISCONNECT},
{"bluetoothToggleA11yLabel",
IDS_SETTINGS_BLUETOOTH_TOGGLE_ACCESSIBILITY_LABEL},
{"bluetoothExpandA11yLabel",
@@ -387,133 +380,38 @@ void AddBluetoothStrings(content::WebUIDataSource* html_source) {
{"bluetoothNoDevicesFound", IDS_SETTINGS_BLUETOOTH_NO_DEVICES_FOUND},
{"bluetoothNotConnected", IDS_SETTINGS_BLUETOOTH_NOT_CONNECTED},
{"bluetoothPageTitle", IDS_SETTINGS_BLUETOOTH},
- {"bluetoothPair", IDS_SETTINGS_BLUETOOTH_PAIR},
{"bluetoothPairDevicePageTitle",
IDS_SETTINGS_BLUETOOTH_PAIR_DEVICE_TITLE},
- {"bluetoothReject", IDS_OPTIONS_SETTINGS_BLUETOOTH_REJECT_PASSKEY},
{"bluetoothRemove", IDS_SETTINGS_BLUETOOTH_REMOVE},
- // Device connecting and pairing.
- {"bluetoothStartConnecting", IDS_SETTINGS_BLUETOOTH_START_CONNECTING},
- {"bluetoothEnterKey", IDS_OPTIONS_SETTINGS_BLUETOOTH_ENTER_KEY},
- // These ids are generated in JS using 'bluetooth_' + a value from
- // bluetoothPrivate.PairingEventType (see bluetooth_private.idl).
- // 'keysEntered', and 'requestAuthorization' have no associated message.
- {"bluetooth_requestPincode", IDS_SETTINGS_BLUETOOTH_REQUEST_PINCODE},
- {"bluetooth_displayPincode", IDS_SETTINGS_BLUETOOTH_DISPLAY_PINCODE},
- {"bluetooth_requestPasskey", IDS_SETTINGS_BLUETOOTH_REQUEST_PASSKEY},
- {"bluetooth_displayPasskey", IDS_SETTINGS_BLUETOOTH_DISPLAY_PASSKEY},
- {"bluetooth_confirmPasskey", IDS_SETTINGS_BLUETOOTH_CONFIRM_PASSKEY},
- // These ids are generated in JS using 'bluetooth_connect_' + a value from
- // bluetoothPrivate.ConnectResultType (see bluetooth_private.idl).
- {"bluetooth_connect_attributeLengthInvalid",
- IDS_SETTINGS_BLUETOOTH_CONNECT_ATTRIBUTE_LENGTH_INVALID},
- {"bluetooth_connect_authCanceled",
- IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_CANCELED},
- {"bluetooth_connect_authFailed",
- IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_FAILED},
- {"bluetooth_connect_authRejected",
- IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_REJECTED},
- {"bluetooth_connect_authTimeout",
- IDS_SETTINGS_BLUETOOTH_CONNECT_AUTH_TIMEOUT},
- {"bluetooth_connect_connectionCongested",
- IDS_SETTINGS_BLUETOOTH_CONNECT_CONNECTION_CONGESTED},
- {"bluetooth_connect_failed", IDS_SETTINGS_BLUETOOTH_CONNECT_FAILED},
- {"bluetooth_connect_inProgress",
- IDS_SETTINGS_BLUETOOTH_CONNECT_IN_PROGRESS},
- {"bluetooth_connect_insufficientEncryption",
- IDS_SETTINGS_BLUETOOTH_CONNECT_INSUFFICIENT_ENCRYPTION},
- {"bluetooth_connect_offsetInvalid",
- IDS_SETTINGS_BLUETOOTH_CONNECT_OFFSET_INVALID},
- {"bluetooth_connect_readNotPermitted",
- IDS_SETTINGS_BLUETOOTH_CONNECT_READ_NOT_PERMITTED},
- {"bluetooth_connect_requestNotSupported",
- IDS_SETTINGS_BLUETOOTH_CONNECT_REQUEST_NOT_SUPPORTED},
- {"bluetooth_connect_unsupportedDevice",
- IDS_SETTINGS_BLUETOOTH_CONNECT_UNSUPPORTED_DEVICE},
- {"bluetooth_connect_writeNotPermitted",
- IDS_SETTINGS_BLUETOOTH_CONNECT_WRITE_NOT_PERMITTED},
};
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
+ chromeos::bluetooth_dialog::AddLocalizedStrings(html_source);
}
#endif
-#if defined(USE_NSS_CERTS)
-void AddCertificateManagerStrings(content::WebUIDataSource* html_source) {
+void AddChangePasswordStrings(content::WebUIDataSource* html_source) {
+#if defined(SAFE_BROWSING_DB_LOCAL)
+ bool show_softer_warning =
+ safe_browsing::PasswordProtectionService::ShouldShowSofterWarning();
+
+ auto title_string_id = show_softer_warning
+ ? IDS_SETTINGS_CHANGE_PASSWORD_TITLE_SOFTER
+ : IDS_SETTINGS_CHANGE_PASSWORD_TITLE;
LocalizedString localized_strings[] = {
- {"certificateManagerPageTitle", IDS_SETTINGS_CERTIFICATE_MANAGER},
- {"certificateManagerExpandA11yLabel",
- IDS_SETTINGS_CERTIFICATE_MANAGER_EXPAND_ACCESSIBILITY_LABEL},
- {"certificateManagerNoCertificates",
- IDS_SETTINGS_CERTIFICATE_MANAGER_NO_CERTIFICATES},
- {"certificateManagerYourCertificates",
- IDS_SETTINGS_CERTIFICATE_MANAGER_YOUR_CERTIFICATES},
- {"certificateManagerYourCertificatesDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_YOUR_CERTIFICATES_DESCRIPTION},
- {"certificateManagerServers", IDS_SETTINGS_CERTIFICATE_MANAGER_SERVERS},
- {"certificateManagerServersDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_SERVERS_DESCRIPTION},
- {"certificateManagerAuthorities",
- IDS_SETTINGS_CERTIFICATE_MANAGER_AUTHORITIES},
- {"certificateManagerAuthoritiesDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_AUTHORITIES_DESCRIPTION},
- {"certificateManagerOthers", IDS_SETTINGS_CERTIFICATE_MANAGER_OTHERS},
- {"certificateManagerOthersDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_OTHERS_DESCRIPTION},
- {"certificateManagerView", IDS_SETTINGS_CERTIFICATE_MANAGER_VIEW},
- {"certificateManagerImport", IDS_SETTINGS_CERTIFICATE_MANAGER_IMPORT},
- {"certificateManagerImportAndBind",
- IDS_SETTINGS_CERTIFICATE_MANAGER_IMPORT_AND_BIND},
- {"certificateManagerExport", IDS_SETTINGS_CERTIFICATE_MANAGER_EXPORT},
- {"certificateManagerDelete", IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE},
- {"certificateManagerDone", IDS_SETTINGS_CERTIFICATE_MANAGER_DONE},
- {"certificateManagerUntrusted",
- IDS_SETTINGS_CERTIFICATE_MANAGER_UNTRUSTED},
- // CA trust edit dialog.
- {"certificateManagerCaTrustEditDialogTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_TITLE},
- {"certificateManagerCaTrustEditDialogDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_DESCRIPTION},
- {"certificateManagerCaTrustEditDialogExplanation",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_EXPLANATION},
- {"certificateManagerCaTrustEditDialogSsl",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_SSL},
- {"certificateManagerCaTrustEditDialogEmail",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_EMAIL},
- {"certificateManagerCaTrustEditDialogObjSign",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CA_TRUST_EDIT_DIALOG_OBJ_SIGN},
- // Certificate delete confirmation dialog.
- {"certificateManagerDeleteUserTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_USER_TITLE},
- {"certificateManagerDeleteUserDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_USER_DESCRIPTION},
- {"certificateManagerDeleteServerTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_SERVER_TITLE},
- {"certificateManagerDeleteServerDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_SERVER_DESCRIPTION},
- {"certificateManagerDeleteCaTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_CA_TITLE},
- {"certificateManagerDeleteCaDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_CA_DESCRIPTION},
- {"certificateManagerDeleteOtherTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_OTHER_TITLE},
- // Encrypt/decrypt password dialogs.
- {"certificateManagerEncryptPasswordTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_ENCRYPT_PASSWORD_TITLE},
- {"certificateManagerDecryptPasswordTitle",
- IDS_SETTINGS_CERTIFICATE_MANAGER_DECRYPT_PASSWORD_TITLE},
- {"certificateManagerEncryptPasswordDescription",
- IDS_SETTINGS_CERTIFICATE_MANAGER_ENCRYPT_PASSWORD_DESCRIPTION},
- {"certificateManagerPassword", IDS_SETTINGS_CERTIFICATE_MANAGER_PASSWORD},
- {"certificateManagerConfirmPassword",
- IDS_SETTINGS_CERTIFICATE_MANAGER_CONFIRM_PASSWORD},
- {"certificateImportErrorFormat",
- IDS_SETTINGS_CERTIFICATE_MANAGER_IMPORT_ERROR_FORMAT},
+ {"changePasswordPageTitle", title_string_id},
+ {"changePasswordPageDetails", IDS_SETTINGS_CHANGE_PASSWORD_DETAIL},
+ {"changePasswordPageButton", IDS_SETTINGS_CHANGE_PASSWORD_BUTTON},
};
+
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
-}
+
+ const std::string icon_id =
+ show_softer_warning ? "settings:security" : "cr:warning";
+ html_source->AddString("changePasswordPageIcon", icon_id);
#endif
+}
void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
@@ -603,6 +501,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) {
{"pointerFast", IDS_SETTINGS_POINTER_SPEED_FAST_LABEL},
{"mouseSpeed", IDS_SETTINGS_MOUSE_SPEED_LABEL},
{"mouseSwapButtons", IDS_SETTINGS_MOUSE_SWAP_BUTTONS_LABEL},
+ {"mouseReverseScroll", IDS_SETTINGS_MOUSE_REVERSE_SCROLL_LABEL},
};
AddLocalizedStringsBulk(html_source, pointers_strings,
arraysize(pointers_strings));
@@ -818,9 +717,9 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) {
.spec();
html_source->AddString("chromeCleanupLearnMoreUrl", cleanup_learn_more_url);
- base::string16 powered_by_html = l10n_util::GetStringFUTF16(
- IDS_CHROME_CLEANUP_WEBUI_FOOTER_POWERED_BY,
- L"<span id='powered-by-logo'></span><span>®</span>");
+ base::string16 powered_by_html =
+ l10n_util::GetStringFUTF16(IDS_CHROME_CLEANUP_WEBUI_FOOTER_POWERED_BY,
+ L"<span id='powered-by-logo'></span>");
html_source->AddString("chromeCleanupPoweredByHtml", powered_by_html);
}
#endif // defined(OS_WIN)
@@ -836,17 +735,16 @@ void AddResetStrings(content::WebUIDataSource* html_source) {
{"resetPageCommit", IDS_RESET_PROFILE_SETTINGS_COMMIT_BUTTON},
{"resetPageFeedback", IDS_SETTINGS_RESET_PROFILE_FEEDBACK},
#if defined(OS_CHROMEOS)
- {"powerwashTitle", IDS_OPTIONS_FACTORY_RESET},
- {"powerwashDialogTitle", IDS_OPTIONS_FACTORY_RESET_HEADING},
- {"powerwashDialogExplanation", IDS_OPTIONS_FACTORY_RESET_WARNING},
+ {"powerwashTitle", IDS_SETTINGS_FACTORY_RESET},
+ {"powerwashDialogTitle", IDS_SETTINGS_FACTORY_RESET_HEADING},
+ {"powerwashDialogExplanation", IDS_SETTINGS_FACTORY_RESET_WARNING},
{"powerwashDialogButton", IDS_SETTINGS_RESTART},
{"powerwashLearnMoreUrl", IDS_FACTORY_RESET_HELP_URL},
#endif
// Automatic reset banner (now a dialog).
{"resetAutomatedDialogTitle", IDS_SETTINGS_RESET_AUTOMATED_DIALOG_TITLE},
- {"resetProfileBannerButton",
- IDS_AUTOMATIC_SETTINGS_RESET_BANNER_RESET_BUTTON_TEXT},
- {"resetProfileBannerDescription", IDS_AUTOMATIC_SETTINGS_RESET_BANNER_TEXT},
+ {"resetProfileBannerButton", IDS_SETTINGS_RESET_BANNER_RESET_BUTTON_TEXT},
+ {"resetProfileBannerDescription", IDS_SETTINGS_RESET_BANNER_TEXT},
};
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
@@ -858,7 +756,7 @@ void AddResetStrings(content::WebUIDataSource* html_source) {
#if defined(OS_CHROMEOS)
html_source->AddString(
"powerwashDescription",
- l10n_util::GetStringFUTF16(IDS_OPTIONS_FACTORY_RESET_DESCRIPTION,
+ l10n_util::GetStringFUTF16(IDS_SETTINGS_FACTORY_RESET_DESCRIPTION,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
#endif
}
@@ -930,7 +828,7 @@ void AddEasyUnlockStrings(content::WebUIDataSource* html_source) {
arraysize(localized_strings));
base::string16 device_name =
- l10n_util::GetStringUTF16(ash::GetChromeOSDeviceTypeResourceId());
+ l10n_util::GetStringUTF16(ui::GetChromeOSDeviceTypeResourceId());
html_source->AddString(
"easyUnlockSetupIntro",
l10n_util::GetStringFUTF16(IDS_SETTINGS_EASY_UNLOCK_SETUP_INTRO,
@@ -969,6 +867,7 @@ void AddInternetStrings(content::WebUIDataSource* html_source) {
{"internetConfigTitle", IDS_SETTINGS_INTERNET_CONFIG},
{"internetDetailPageTitle", IDS_SETTINGS_INTERNET_DETAIL},
{"internetDeviceEnabling", IDS_SETTINGS_INTERNET_DEVICE_ENABLING},
+ {"internetDeviceInitializing", IDS_SETTINGS_INTERNET_DEVICE_INITIALIZING},
{"internetKnownNetworksPageTitle", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS},
{"internetMobileSearching", IDS_SETTINGS_INTERNET_MOBILE_SEARCH},
{"internetNoNetworks", IDS_SETTINGS_INTERNET_NO_NETWORKS},
@@ -1015,50 +914,16 @@ void AddInternetStrings(content::WebUIDataSource* html_source) {
{"networkPrefer", IDS_SETTINGS_INTERNET_NETWORK_PREFER},
{"networkPrimaryUserControlled",
IDS_SETTINGS_INTERNET_NETWORK_PRIMARY_USER_CONTROLLED},
- {"networkProxy", IDS_SETTINGS_INTERNET_NETWORK_PROXY_PROXY},
- {"networkProxyAddException",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_ADD_EXCEPTION},
- {"networkProxyAllowShared",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_ALLOW_SHARED},
- {"networkProxyAllowSharedWarningTitle",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_ALLOW_SHARED_WARNING_TITLE},
- {"networkProxyAllowSharedWarningMessage",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_ALLOW_SHARED_WARNING_MESSAGE},
- {"networkProxyAutoConfig",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_AUTO_CONFIG},
- {"networkProxyConnectionType",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_CONNECTION_TYPE},
- {"networkProxyEnforcedPolicy",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_ENFORCED_POLICY},
- {"networkProxyExceptionList",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_EXCEPTION_LIST},
- {"networkProxyFtp", IDS_SETTINGS_INTERNET_NETWORK_PROXY_FTP_PROXY},
- {"networkProxyHttp", IDS_SETTINGS_INTERNET_NETWORK_PROXY_HTTP_PROXY},
- {"networkProxyPort", IDS_SETTINGS_INTERNET_NETWORK_PROXY_PORT},
- {"networkProxyShttp", IDS_SETTINGS_INTERNET_NETWORK_PROXY_SHTTP_PROXY},
- {"networkProxySocks", IDS_SETTINGS_INTERNET_NETWORK_PROXY_SOCKS_HOST},
- {"networkProxyTypeDirect",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_DIRECT},
- {"networkProxyTypeManual",
- IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_MANUAL},
- {"networkProxyTypePac", IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_PAC},
- {"networkProxyTypeWpad", IDS_SETTINGS_INTERNET_NETWORK_PROXY_TYPE_WPAD},
- {"networkProxyUseSame", IDS_SETTINGS_INTERNET_NETWORK_PROXY_USE_SAME},
- {"networkSectionAccessPoint",
- IDS_SETTINGS_INTERNET_NETWORK_SECTION_ACCESS_POINT},
{"networkSectionAdvanced",
IDS_SETTINGS_INTERNET_NETWORK_SECTION_ADVANCED},
{"networkSectionAdvancedA11yLabel",
IDS_SETTINGS_INTERNET_NETWORK_SECTION_ADVANCED_ACCESSIBILITY_LABEL},
- {"networkSectionNameservers",
- IDS_SETTINGS_INTERNET_NETWORK_SECTION_NAMESERVERS},
{"networkSectionNetwork", IDS_SETTINGS_INTERNET_NETWORK_SECTION_NETWORK},
{"networkSectionNetworkExpandA11yLabel",
IDS_SETTINGS_INTERNET_NETWORK_SECTION_NETWORK_ACCESSIBILITY_LABEL},
{"networkSectionProxy", IDS_SETTINGS_INTERNET_NETWORK_SECTION_PROXY},
{"networkSectionProxyExpandA11yLabel",
IDS_SETTINGS_INTERNET_NETWORK_SECTION_PROXY_ACCESSIBILITY_LABEL},
- {"networkSectionWpad", IDS_SETTINGS_INTERNET_NETWORK_SECTION_WPAD},
{"networkShared", IDS_SETTINGS_INTERNET_NETWORK_SHARED},
{"networkSimCardLocked", IDS_SETTINGS_INTERNET_NETWORK_SIM_CARD_LOCKED},
{"networkSimCardMissing", IDS_SETTINGS_INTERNET_NETWORK_SIM_CARD_MISSING},
@@ -1220,9 +1085,6 @@ void AddChromeOSUserStrings(content::WebUIDataSource* html_source,
void AddOnStartupStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"onStartup", IDS_SETTINGS_ON_STARTUP},
- {"onStartupDescription", IDS_SETTINGS_ON_STARTUP_DESCRIPTION},
- {"onStartupManage", IDS_SETTINGS_ON_STARTUP_MANAGE},
- {"onStartupPages", IDS_SETTINGS_ON_STARTUP_PAGES},
{"onStartupOpenNewTab", IDS_SETTINGS_ON_STARTUP_OPEN_NEW_TAB},
{"onStartupContinue", IDS_SETTINGS_ON_STARTUP_CONTINUE},
{"onStartupOpenSpecific", IDS_SETTINGS_ON_STARTUP_OPEN_SPECIFIC},
@@ -1401,7 +1263,6 @@ void AddPeopleStrings(content::WebUIDataSource* html_source) {
{"chooseFile", IDS_SETTINGS_CHANGE_PICTURE_CHOOSE_FILE},
{"profilePhoto", IDS_SETTINGS_CHANGE_PICTURE_PROFILE_PHOTO},
{"oldPhoto", IDS_SETTINGS_CHANGE_PICTURE_OLD_PHOTO},
- {"profilePhotoLoading", IDS_SETTINGS_CHANGE_PICTURE_PROFILE_LOADING_PHOTO},
{"previewAltText", IDS_SETTINGS_CHANGE_PICTURE_PREVIEW_ALT},
{"authorCreditText", IDS_SETTINGS_CHANGE_PICTURE_AUTHOR_CREDIT_TEXT},
{"photoFlippedAccessibleText", IDS_SETTINGS_PHOTO_FLIP_ACCESSIBLE_TEXT},
@@ -1415,6 +1276,8 @@ void AddPeopleStrings(content::WebUIDataSource* html_source) {
{"showShortcutLabel", IDS_SETTINGS_PROFILE_SHORTCUT_TOGGLE_LABEL},
#endif // defined(OS_CHROMEOS)
{"syncOverview", IDS_SETTINGS_SYNC_OVERVIEW},
+ {"syncDisabledByAdministrator",
+ IDS_SETTINGS_SYNC_DISABLED_BY_ADMINISTRATOR},
{"syncSignin", IDS_SETTINGS_SYNC_SIGNIN},
{"syncDisconnect", IDS_SETTINGS_SYNC_DISCONNECT},
{"syncDisconnectTitle", IDS_SETTINGS_SYNC_DISCONNECT_TITLE},
@@ -1541,7 +1404,6 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) {
{"cupsPrintersLearnMoreLabel",
IDS_SETTINGS_PRINTING_CUPS_PRINTERS_LEARN_MORE_LABEL},
{"addCupsPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_ADD_PRINTER},
- {"cupsPrinterDetails", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_DETAILS},
{"editPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_EDIT},
{"removePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_REMOVE},
{"searchLabel", IDS_SETTINGS_PRINTING_CUPS_SEARCH_LABEL},
@@ -1649,6 +1511,9 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source,
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
+ html_source->AddBoolean("tabsInCbd",
+ base::FeatureList::IsEnabled(features::kTabsInCbd));
+
html_source->AddBoolean(
"importantSitesInCbd",
base::FeatureList::IsEnabled(features::kImportantSitesInCbd));
@@ -1691,10 +1556,17 @@ void AddSearchInSettingsStrings(content::WebUIDataSource* html_source) {
html_source->AddString("searchNoResultsHelp", help_text);
}
-void AddSearchStrings(content::WebUIDataSource* html_source) {
+void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) {
+#if defined(OS_CHROMEOS)
+ const bool is_user_primary =
+ chromeos::ProfileHelper::Get()->GetUserByProfile(profile) ==
+ user_manager::UserManager::Get()->GetPrimaryUser();
+#endif
+
LocalizedString localized_strings[] = {
#if defined(OS_CHROMEOS)
- {"searchPageTitle", chromeos::switches::IsVoiceInteractionEnabled()
+ {"searchPageTitle", !profile->IsSupervised() && is_user_primary &&
+ chromeos::switches::IsVoiceInteractionEnabled()
? IDS_SETTINGS_SEARCH_AND_ASSISTANT
: IDS_SETTINGS_SEARCH},
#else
@@ -1734,8 +1606,9 @@ void AddSearchStrings(content::WebUIDataSource* html_source) {
base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL));
html_source->AddString("searchExplanation", search_explanation_text);
#if defined(OS_CHROMEOS)
- html_source->AddBoolean("enableVoiceInteraction",
- chromeos::switches::IsVoiceInteractionEnabled());
+ html_source->AddBoolean(
+ "enableVoiceInteraction",
+ chromeos::switches::IsVoiceInteractionEnabled() && is_user_primary);
#endif
}
@@ -1752,6 +1625,7 @@ void AddSearchEnginesStrings(content::WebUIDataSource* html_source) {
{"searchEnginesNoOtherEngines",
IDS_SETTINGS_SEARCH_ENGINES_NO_OTHER_ENGINES},
{"searchEnginesExtension", IDS_SETTINGS_SEARCH_ENGINES_EXTENSION_ENGINES},
+ {"searchEnginesSearch", IDS_SETTINGS_SEARCH_ENGINES_SEARCH},
{"searchEnginesSearchEngine", IDS_SETTINGS_SEARCH_ENGINES_SEARCH_ENGINE},
{"searchEnginesKeyword", IDS_SETTINGS_SEARCH_ENGINES_KEYWORD},
{"searchEnginesQueryURL", IDS_SETTINGS_SEARCH_ENGINES_QUERY_URL},
@@ -1872,6 +1746,7 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
{"siteSettingsNotifications", IDS_SETTINGS_SITE_SETTINGS_NOTIFICATIONS},
{"siteSettingsImages", IDS_SETTINGS_SITE_SETTINGS_IMAGES},
{"siteSettingsJavascript", IDS_SETTINGS_SITE_SETTINGS_JAVASCRIPT},
+ {"siteSettingsSound", IDS_SETTINGS_SITE_SETTINGS_SOUND},
{"siteSettingsFlash", IDS_SETTINGS_SITE_SETTINGS_FLASH},
{"siteSettingsPdfDocuments", IDS_SETTINGS_SITE_SETTINGS_PDF_DOCUMENTS},
{"siteSettingsPdfDownloadPdfs",
@@ -1912,7 +1787,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_SITE_SETTINGS_ASK_BEFORE_SENDING},
{"siteSettingsAskBeforeSendingRecommended",
IDS_SETTINGS_SITE_SETTINGS_ASK_BEFORE_SENDING_RECOMMENDED},
- {"siteSettingsFlashAllow", IDS_SETTINGS_SITE_SETTINGS_FLASH_ALLOW},
{"siteSettingsFlashBlock", IDS_SETTINGS_SITE_SETTINGS_FLASH_BLOCK},
{"siteSettingsAllowRecentlyClosedSites",
IDS_SETTINGS_SITE_SETTINGS_ALLOW_RECENTLY_CLOSED_SITES},
@@ -1963,13 +1837,33 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_SITE_SETTINGS_BLOCK_DEFAULT_MENU},
{"siteSettingsActionAllow", IDS_SETTINGS_SITE_SETTINGS_ALLOW_MENU},
{"siteSettingsActionBlock", IDS_SETTINGS_SITE_SETTINGS_BLOCK_MENU},
+ {"siteSettingsActionAsk", IDS_SETTINGS_SITE_SETTINGS_ASK_MENU},
{"siteSettingsActionReset", IDS_SETTINGS_SITE_SETTINGS_RESET_MENU},
{"siteSettingsActionSessionOnly",
IDS_SETTINGS_SITE_SETTINGS_SESSION_ONLY_MENU},
{"siteSettingsUsage", IDS_SETTINGS_SITE_SETTINGS_USAGE},
+ {"siteSettingsUsageNone", IDS_SETTINGS_SITE_SETTINGS_USAGE_NONE},
{"siteSettingsPermissions", IDS_SETTINGS_SITE_SETTINGS_PERMISSIONS},
- {"siteSettingsClearAndReset", IDS_SETTINGS_SITE_SETTINGS_CLEAR_BUTTON},
+ {"siteSettingsSourceExtensionAllow",
+ IDS_PAGE_INFO_PERMISSION_ALLOWED_BY_EXTENSION},
+ {"siteSettingsSourceExtensionBlock",
+ IDS_PAGE_INFO_PERMISSION_BLOCKED_BY_EXTENSION},
+ {"siteSettingsSourceExtensionAsk",
+ IDS_PAGE_INFO_PERMISSION_ASK_BY_EXTENSION},
+ {"siteSettingsSourcePolicyAllow",
+ IDS_PAGE_INFO_PERMISSION_ALLOWED_BY_POLICY},
+ {"siteSettingsSourcePolicyBlock",
+ IDS_PAGE_INFO_PERMISSION_BLOCKED_BY_POLICY},
+ {"siteSettingsSourcePolicyAsk", IDS_PAGE_INFO_PERMISSION_ASK_BY_POLICY},
+ {"siteSettingsSourceEmbargo",
+ IDS_PAGE_INFO_PERMISSION_AUTOMATICALLY_BLOCKED},
+ {"siteSettingsSourceInsecureOrigin",
+ IDS_SETTINGS_SITE_SETTINGS_SOURCE_INSECURE_ORIGIN},
+ {"siteSettingsSourceKillSwitch",
+ IDS_SETTINGS_SITE_SETTINGS_SOURCE_KILL_SWITCH},
+ {"siteSettingsReset", IDS_SETTINGS_SITE_SETTINGS_RESET_BUTTON},
{"siteSettingsCookieHeader", IDS_SETTINGS_SITE_SETTINGS_COOKIE_HEADER},
+ {"siteSettingsCookieLink", IDS_SETTINGS_SITE_SETTINGS_COOKIE_LINK},
{"siteSettingsCookieRemove", IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE},
{"siteSettingsCookieRemoveAll",
IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL},
@@ -1986,11 +1880,11 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
{"siteSettingsCookieSearch", IDS_SETTINGS_SITE_SETTINGS_COOKIE_SEARCH},
{"siteSettingsCookieSubpage", IDS_SETTINGS_SITE_SETTINGS_COOKIE_SUBPAGE},
{"siteSettingsDelete", IDS_SETTINGS_SITE_SETTINGS_DELETE},
- {"siteSettingsSiteClearAll", IDS_SETTINGS_SITE_SETTINGS_SITE_CLEAR_ALL},
- {"siteSettingsSiteRemoveConfirmation",
- IDS_SETTINGS_SITE_SETTINGS_SITE_REMOVE_CONFIRMATION},
- {"siteSettingsSiteRemoveDialogTitle",
- IDS_SETTINGS_SITE_SETTINGS_SITE_REMOVE_DIALOG_TITLE},
+ {"siteSettingsSiteResetAll", IDS_SETTINGS_SITE_SETTINGS_SITE_RESET_ALL},
+ {"siteSettingsSiteResetConfirmation",
+ IDS_SETTINGS_SITE_SETTINGS_SITE_RESET_CONFIRMATION},
+ {"siteSettingsSiteResetDialogTitle",
+ IDS_SETTINGS_SITE_SETTINGS_SITE_RESET_DIALOG_TITLE},
{"thirdPartyCookie", IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE},
{"thirdPartyCookieSublabel",
IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE_SUBLABEL},
@@ -2004,7 +1898,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
{"incognitoSite", IDS_SETTINGS_SITE_SETTINGS_INCOGNITO},
{"incognitoSiteOnly", IDS_SETTINGS_SITE_SETTINGS_INCOGNITO_ONLY},
{"embeddedIncognitoSite", IDS_SETTINGS_SITE_SETTINGS_INCOGNITO_EMBEDDED},
- {"siteSettingsSiteDetails", IDS_SETTINGS_SITE_DETAILS},
{"noSitesAdded", IDS_SETTINGS_SITE_NO_SITES_ADDED},
{"siteSettingsAds", IDS_SETTINGS_SITE_SETTINGS_ADS},
{"siteSettingsAdsBlock", IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK},
@@ -2024,22 +1917,25 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
base::FeatureList::IsEnabled(
subresource_filter::kSafeBrowsingSubresourceFilterExperimentalUI));
+ html_source->AddBoolean(
+ "enableSoundContentSetting",
+ base::FeatureList::IsEnabled(features::kSoundContentSetting));
+
if (PluginUtils::ShouldPreferHtmlOverPlugins(
HostContentSettingsMapFactory::GetForProfile(profile))) {
LocalizedString flash_strings[] = {
- {"siteSettingsFlashAskBefore",
- IDS_SETTINGS_SITE_SETTINGS_FLASH_ASK_BEFORE_RUNNING},
- {"siteSettingsFlashAskBeforeSubtitle",
- IDS_SETTINGS_SITE_SETTINGS_FLASH_ASK_BEFORE_RUNNING_SUBTITLE},
+ {"siteSettingsFlashAskFirst", IDS_SETTINGS_SITE_SETTINGS_ASK_FIRST},
+ {"siteSettingsFlashAskFirstRecommended",
+ IDS_SETTINGS_SITE_SETTINGS_ASK_FIRST_RECOMMENDED},
};
AddLocalizedStringsBulk(html_source, flash_strings,
arraysize(flash_strings));
} else {
LocalizedString flash_strings[] = {
- {"siteSettingsFlashAskBefore",
+ {"siteSettingsFlashAskFirst",
IDS_SETTINGS_SITE_SETTINGS_FLASH_DETECT_IMPORTANT},
- {"siteSettingsFlashAskBeforeSubtitle",
- IDS_SETTINGS_SITE_SETTINGS_FLASH_DETECT_IMPORTANT_SUBTITLE},
+ {"siteSettingsFlashAskFirstRecommended",
+ IDS_SETTINGS_SITE_SETTINGS_FLASH_DETECT_IMPORTANT_RECOMMENDED},
};
AddLocalizedStringsBulk(html_source, flash_strings,
arraysize(flash_strings));
@@ -2130,109 +2026,6 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) {
}
#endif
-#if defined(OS_CHROMEOS)
-void AddOncStrings(content::WebUIDataSource* html_source) {
- LocalizedString onc_property_strings[] = {
- // Thes strings are generated by prepending 'Onc' to the ONC property
- // name. Any '.' in the property name is replaced with '-'. Properties
- // with translatable enumerated values have the value appended after '_'.
- {"OncCellular-APN-AccessPointName",
- IDS_ONC_CELLULAR_APN_ACCESS_POINT_NAME},
- {"OncCellular-APN-AccessPointName_none",
- IDS_ONC_CELLULAR_APN_ACCESS_POINT_NAME_NONE},
- {"OncCellular-APN-Password", IDS_ONC_CELLULAR_APN_PASSWORD},
- {"OncCellular-APN-Username", IDS_ONC_CELLULAR_APN_USERNAME},
- {"OncCellular-ActivationState", IDS_ONC_CELLULAR_ACTIVATION_STATE},
- {"OncCellular-ActivationState_Activated",
- IDS_ONC_CELLULAR_ACTIVATION_STATE_ACTIVATED},
- {"OncCellular-ActivationState_Activating",
- IDS_ONC_CELLULAR_ACTIVATION_STATE_ACTIVATING},
- {"OncCellular-ActivationState_NotActivated",
- IDS_ONC_CELLULAR_ACTIVATION_STATE_NOT_ACTIVATED},
- {"OncCellular-ActivationState_PartiallyActivated",
- IDS_ONC_CELLULAR_ACTIVATION_STATE_PARTIALLY_ACTIVATED},
- {"OncCellular-Carrier", IDS_ONC_CELLULAR_CARRIER},
- {"OncCellular-Family", IDS_ONC_CELLULAR_FAMILY},
- {"OncCellular-FirmwareRevision", IDS_ONC_CELLULAR_FIRMWARE_REVISION},
- {"OncCellular-HardwareRevision", IDS_ONC_CELLULAR_HARDWARE_REVISION},
- {"OncCellular-HomeProvider-Code", IDS_ONC_CELLULAR_HOME_PROVIDER_CODE},
- {"OncCellular-HomeProvider-Country",
- IDS_ONC_CELLULAR_HOME_PROVIDER_COUNTRY},
- {"OncCellular-HomeProvider-Name", IDS_ONC_CELLULAR_HOME_PROVIDER_NAME},
- {"OncCellular-Manufacturer", IDS_ONC_CELLULAR_MANUFACTURER},
- {"OncCellular-ModelID", IDS_ONC_CELLULAR_MODEL_ID},
- {"OncCellular-NetworkTechnology", IDS_ONC_CELLULAR_NETWORK_TECHNOLOGY},
- {"OncCellular-PRLVersion", IDS_ONC_CELLULAR_PRL_VERSION},
- {"OncCellular-RoamingState", IDS_ONC_CELLULAR_ROAMING_STATE},
- {"OncCellular-RoamingState_Home", IDS_ONC_CELLULAR_ROAMING_STATE_HOME},
- {"OncCellular-RoamingState_Roaming",
- IDS_ONC_CELLULAR_ROAMING_STATE_ROAMING},
- {"OncCellular-ServingOperator-Code",
- IDS_ONC_CELLULAR_SERVING_OPERATOR_CODE},
- {"OncCellular-ServingOperator-Name",
- IDS_ONC_CELLULAR_SERVING_OPERATOR_NAME},
- {"OncConnected", IDS_ONC_CONNECTED},
- {"OncConnecting", IDS_ONC_CONNECTING},
- {"OncEAP-AnonymousIdentity", IDS_ONC_EAP_ANONYMOUS_IDENTITY},
- {"OncEAP-Identity", IDS_ONC_EAP_IDENTITY},
- {"OncEAP-Inner", IDS_ONC_EAP_INNER},
- {"OncEAP-Inner_Automatic", IDS_ONC_EAP_INNER_AUTOMATIC},
- {"OncEAP-Inner_CHAP", IDS_ONC_EAP_INNER_CHAP},
- {"OncEAP-Inner_GTC", IDS_ONC_EAP_INNER_GTC},
- {"OncEAP-Inner_MD5", IDS_ONC_EAP_INNER_MD5},
- {"OncEAP-Inner_MSCHAP", IDS_ONC_EAP_INNER_MSCHAP},
- {"OncEAP-Inner_MSCHAPv2", IDS_ONC_EAP_INNER_MSCHAPV2},
- {"OncEAP-Inner_PAP", IDS_ONC_EAP_INNER_PAP},
- {"OncEAP-Outer", IDS_ONC_EAP_OUTER},
- {"OncEAP-Outer_LEAP", IDS_ONC_EAP_OUTER_LEAP},
- {"OncEAP-Outer_PEAP", IDS_ONC_EAP_OUTER_PEAP},
- {"OncEAP-Outer_EAP-TLS", IDS_ONC_EAP_OUTER_TLS},
- {"OncEAP-Outer_EAP-TTLS", IDS_ONC_EAP_OUTER_TTLS},
- {"OncEAP-Password", IDS_ONC_WIFI_PASSWORD},
- {"OncEAP-SubjectMatch", IDS_ONC_EAP_SUBJECT_MATCH},
- {"OncMacAddress", IDS_ONC_MAC_ADDRESS},
- {"OncNotConnected", IDS_ONC_NOT_CONNECTED},
- {"OncRestrictedConnectivity", IDS_ONC_RESTRICTED_CONNECTIVITY},
- {"OncTether-BatteryPercentage", IDS_ONC_TETHER_BATTERY_PERCENTAGE},
- {"OncTether-BatteryPercentage_Value",
- IDS_ONC_TETHER_BATTERY_PERCENTAGE_VALUE},
- {"OncTether-SignalStrength", IDS_ONC_TETHER_SIGNAL_STRENGTH},
- {"OncTether-SignalStrength_Weak", IDS_ONC_TETHER_SIGNAL_STRENGTH_WEAK},
- {"OncTether-SignalStrength_Okay", IDS_ONC_TETHER_SIGNAL_STRENGTH_OKAY},
- {"OncTether-SignalStrength_Good", IDS_ONC_TETHER_SIGNAL_STRENGTH_GOOD},
- {"OncTether-SignalStrength_Strong",
- IDS_ONC_TETHER_SIGNAL_STRENGTH_STRONG},
- {"OncTether-SignalStrength_VeryStrong",
- IDS_ONC_TETHER_SIGNAL_STRENGTH_VERY_STRONG},
- {"OncTether-Carrier", IDS_ONC_TETHER_CARRIER},
- {"OncTether-Carrier_Unknown", IDS_ONC_TETHER_CARRIER_UNKNOWN},
- {"OncVPN-Host", IDS_ONC_VPN_HOST},
- {"OncVPN-L2TP-Username", IDS_ONC_VPN_L2TP_USERNAME},
- {"OncVPN-OpenVPN-Username", IDS_ONC_VPN_OPEN_VPN_USERNAME},
- {"OncVPN-ThirdPartyVPN-ProviderName",
- IDS_ONC_VPN_THIRD_PARTY_VPN_PROVIDER_NAME},
- {"OncVPN-Type", IDS_ONC_VPN_TYPE},
- {"OncWiFi-Frequency", IDS_ONC_WIFI_FREQUENCY},
- {"OncWiFi-Passphrase", IDS_ONC_WIFI_PASSWORD},
- {"OncWiFi-SSID", IDS_ONC_WIFI_SSID},
- {"OncWiFi-Security", IDS_ONC_WIFI_SECURITY},
- {"OncWiFi-Security_None", IDS_ONC_WIFI_SECURITY_NONE},
- {"OncWiFi-Security_WEP-PSK", IDS_ONC_WIFI_SECURITY_WEP},
- {"OncWiFi-Security_WPA-EAP", IDS_ONC_WIFI_SECURITY_EAP},
- {"OncWiFi-Security_WPA-PSK", IDS_ONC_WIFI_SECURITY_PSK},
- {"OncWiFi-Security_WEP-8021X", IDS_ONC_WIFI_SECURITY_EAP},
- {"OncWiFi-SignalStrength", IDS_ONC_WIFI_SIGNAL_STRENGTH},
- {"OncWiMAX-EAP-Identity", IDS_ONC_WIMAX_EAP_IDENTITY},
- {"Oncipv4-Gateway", IDS_ONC_IPV4_GATEWAY},
- {"Oncipv4-IPAddress", IDS_ONC_IPV4_ADDRESS},
- {"Oncipv4-RoutingPrefix", IDS_ONC_IPV4_ROUTING_PREFIX},
- {"Oncipv6-IPAddress", IDS_ONC_IPV6_ADDRESS},
- };
- AddLocalizedStringsBulk(html_source, onc_property_strings,
- arraysize(onc_property_strings));
-}
-#endif // OS_CHROMEOS
-
} // namespace
void AddLocalizedStrings(content::WebUIDataSource* html_source,
@@ -2245,6 +2038,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source,
AddChromeCleanupStrings(html_source);
#endif // defined(OS_WIN)
+ AddChangePasswordStrings(html_source);
AddClearBrowsingDataStrings(html_source);
AddCommonStrings(html_source, profile);
AddDownloadsStrings(html_source);
@@ -2260,12 +2054,11 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source,
AddGoogleAssistantStrings(html_source);
#endif
AddSearchInSettingsStrings(html_source);
- AddSearchStrings(html_source);
+ AddSearchStrings(html_source, profile);
AddSiteSettingsStrings(html_source, profile);
AddWebContentStrings(html_source);
#if defined(OS_CHROMEOS)
- AddAccountUITweaksStrings(html_source, profile);
AddAndroidAppStrings(html_source);
AddBluetoothStrings(html_source);
AddChromeOSUserStrings(html_source, profile);
@@ -2274,7 +2067,6 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source,
AddEasyUnlockStrings(html_source);
AddInternetStrings(html_source);
AddMultideviceStrings(html_source);
- AddOncStrings(html_source);
AddUsersStrings(html_source);
#else
AddDefaultBrowserStrings(html_source);
@@ -2283,11 +2075,13 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source,
#endif
#if defined(USE_NSS_CERTS)
- AddCertificateManagerStrings(html_source);
+ certificate_manager::AddLocalizedStrings(html_source);
#endif
#if defined(OS_CHROMEOS)
chromeos::network_element::AddLocalizedStrings(html_source);
+ chromeos::network_element::AddOncLocalizedStrings(html_source);
+ chromeos::network_element::AddConfigLocalizedStrings(html_source);
#endif
policy_indicator::AddLocalizedStrings(html_source);
diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc
index d2a801f5a63..2da8861c3fd 100644
--- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc
+++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.cc
@@ -89,18 +89,17 @@
#endif // defined(OS_CHROMEOS)
#if defined(USE_NSS_CERTS)
-#include "chrome/browser/ui/webui/settings/certificates_handler.h"
+#include "chrome/browser/ui/webui/certificates_handler.h"
#elif defined(OS_WIN) || defined(OS_MACOSX)
#include "chrome/browser/ui/webui/settings/native_certificates_handler.h"
#endif // defined(USE_NSS_CERTS)
-namespace settings {
+#if defined(SAFE_BROWSING_DB_LOCAL)
+#include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
+#include "chrome/browser/ui/webui/settings/change_password_handler.h"
+#endif
-bool IsValidOrigin(const GURL& url) {
- const GURL origin = url.GetOrigin();
- return origin == GURL(chrome::kChromeUISettingsURL).GetOrigin() ||
- origin == GURL(chrome::kChromeUIMdSettingsURL).GetOrigin();
-}
+namespace settings {
// static
void MdSettingsUI::RegisterProfilePrefs(
@@ -112,7 +111,7 @@ void MdSettingsUI::RegisterProfilePrefs(
registry->RegisterBooleanPref(prefs::kImportDialogSearchEngine, true);
}
-MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url)
+MdSettingsUI::MdSettingsUI(content::WebUI* web_ui)
: content::WebUIController(web_ui),
WebContentsObserver(web_ui->GetWebContents()) {
#if BUILDFLAG(USE_VULCANIZE)
@@ -123,7 +122,8 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url)
AddSettingsPageUIHandler(base::MakeUnique<AppearanceHandler>(web_ui));
#if defined(USE_NSS_CERTS)
- AddSettingsPageUIHandler(base::MakeUnique<CertificatesHandler>(false));
+ AddSettingsPageUIHandler(
+ base::MakeUnique<certificate_manager::CertificatesHandler>());
#elif defined(OS_WIN) || defined(OS_MACOSX)
AddSettingsPageUIHandler(base::MakeUnique<NativeCertificatesHandler>());
#endif // defined(USE_NSS_CERTS)
@@ -186,13 +186,11 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url)
AddSettingsPageUIHandler(base::MakeUnique<SystemHandler>());
#endif
- // Host must be derived from the visible URL, since this might be serving
- // either chrome://settings or chrome://md-settings.
- CHECK(IsValidOrigin(url));
-
content::WebUIDataSource* html_source =
- content::WebUIDataSource::Create(url.host());
- html_source->AddString("hostname", url.host());
+ content::WebUIDataSource::Create(chrome::kChromeUISettingsHost);
+ // This is used by a <base> tag in c/b/r/settings/BUILD.gn. TODO(dbeam): Is
+ // this still needed now that there's only 1 host name?
+ html_source->AddString("hostname", chrome::kChromeUISettingsHost);
#if defined(OS_WIN)
if (base::FeatureList::IsEnabled(safe_browsing::kInBrowserCleanerUIFeature)) {
@@ -216,6 +214,13 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url)
}
#endif // defined(OS_WIN)
+#if defined(SAFE_BROWSING_DB_LOCAL)
+ AddSettingsPageUIHandler(base::MakeUnique<ChangePasswordHandler>(profile));
+ html_source->AddBoolean("changePasswordEnabled",
+ safe_browsing::ChromePasswordProtectionService::
+ ShouldShowChangePasswordSettingUI(profile));
+#endif
+
#if defined(OS_CHROMEOS)
chromeos::settings::EasyUnlockSettingsHandler* easy_unlock_handler =
chromeos::settings::EasyUnlockSettingsHandler::Create(html_source,
@@ -231,6 +236,9 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url)
html_source->AddBoolean(
"quickUnlockEnabled",
chromeos::quick_unlock::IsPinEnabled(profile->GetPrefs()));
+ html_source->AddBoolean(
+ "quickUnlockDisabledByPolicy",
+ chromeos::quick_unlock::IsPinDisabledByPolicy(profile->GetPrefs()));
html_source->AddBoolean("fingerprintUnlockEnabled",
chromeos::quick_unlock::IsFingerprintEnabled());
html_source->AddBoolean("hasInternalStylus",
@@ -302,9 +310,8 @@ MdSettingsUI::~MdSettingsUI() {
}
void MdSettingsUI::AddSettingsPageUIHandler(
- std::unique_ptr<SettingsPageUIHandler> handler) {
+ std::unique_ptr<content::WebUIMessageHandler> handler) {
DCHECK(handler);
- handlers_.insert(handler.get());
web_ui()->AddMessageHandler(std::move(handler));
}
diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.h b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.h
index 1ca22c6e5ed..2d3fd4e95ee 100644
--- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui.h
+++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui.h
@@ -17,7 +17,9 @@
#include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_state_change_observer_win.h"
#endif
-class GURL;
+namespace content {
+class WebUIMessageHandler;
+}
namespace user_prefs {
class PrefRegistrySyncable;
@@ -25,18 +27,13 @@ class PrefRegistrySyncable;
namespace settings {
-class SettingsPageUIHandler;
-
-// Exposed for testing.
-bool IsValidOrigin(const GURL& url);
-
-// The WebUI handler for chrome://md-settings.
+// The WebUI handler for chrome://settings.
class MdSettingsUI : public content::WebUIController,
public content::WebContentsObserver {
public:
static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
- MdSettingsUI(content::WebUI* web_ui, const GURL& url);
+ explicit MdSettingsUI(content::WebUI* web_ui);
~MdSettingsUI() override;
// content::WebContentsObserver:
@@ -47,10 +44,8 @@ class MdSettingsUI : public content::WebUIController,
void DocumentOnLoadCompletedInMainFrame() override;
private:
- void AddSettingsPageUIHandler(std::unique_ptr<SettingsPageUIHandler> handler);
-
- // Weak references; all |handlers_| are owned by |web_ui()|.
- std::unordered_set<SettingsPageUIHandler*> handlers_;
+ void AddSettingsPageUIHandler(
+ std::unique_ptr<content::WebUIMessageHandler> handler);
base::Time load_start_time_;
diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_ui_browsertest.cc
index 6d48adec4d9..da53ce1b369 100644
--- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/md_settings_ui_browsertest.cc
@@ -20,15 +20,15 @@ typedef InProcessBrowserTest MdSettingsUITest;
using ui_test_utils::NavigateToURL;
IN_PROC_BROWSER_TEST_F(MdSettingsUITest, ViewSourceDoesntCrash) {
- NavigateToURL(browser(), GURL(content::kViewSourceScheme + std::string(":") +
- chrome::kChromeUIMdSettingsURL +
- std::string("strings.js")));
+ NavigateToURL(browser(),
+ GURL(content::kViewSourceScheme + std::string(":") +
+ chrome::kChromeUISettingsURL + std::string("strings.js")));
}
// Catch lifetime issues in message handlers. There was previously a problem
// with PrefMember calling Init again after Destroy.
IN_PROC_BROWSER_TEST_F(MdSettingsUITest, ToggleJavaScript) {
- NavigateToURL(browser(), GURL(chrome::kChromeUIMdSettingsURL));
+ NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL));
const auto& handlers = *browser()
->tab_strip_model()
diff --git a/chromium/chrome/browser/ui/webui/settings/md_settings_ui_unittest.cc b/chromium/chrome/browser/ui/webui/settings/md_settings_ui_unittest.cc
deleted file mode 100644
index 01b50410761..00000000000
--- a/chromium/chrome/browser/ui/webui/settings/md_settings_ui_unittest.cc
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/settings/md_settings_ui.h"
-
-#include "chrome/common/url_constants.h"
-#include "content/public/common/url_constants.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "url/gurl.h"
-
-TEST(MdSettingsUITest, IsValidOrigin) {
- EXPECT_TRUE(settings::IsValidOrigin(GURL(chrome::kChromeUISettingsURL)));
- EXPECT_TRUE(settings::IsValidOrigin(GURL(chrome::kChromeUIMdSettingsURL)));
-
- EXPECT_FALSE(settings::IsValidOrigin(GURL("http://evil.com")));
- EXPECT_FALSE(settings::IsValidOrigin(GURL("https://google.com")));
- EXPECT_FALSE(settings::IsValidOrigin(GURL(chrome::kChromeUINewTabURL)));
- EXPECT_FALSE(settings::IsValidOrigin(GURL(chrome::kChromeUIHistoryURL)));
-}
diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc
index e6a1b37ef3d..1477fb8c97c 100644
--- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc
@@ -733,9 +733,6 @@ void PeopleHandler::OnStateChanged(syncer::SyncService* sync) {
std::unique_ptr<base::DictionaryValue>
PeopleHandler::GetSyncStatusDictionary() {
- // The items which are to be written into |sync_status| are also described in
- // chrome/browser/resources/options/browser_options.js in @typedef
- // for SyncStatus. Please update it whenever you add or remove any keys here.
std::unique_ptr<base::DictionaryValue> sync_status(new base::DictionaryValue);
if (profile_->IsGuestSession()) {
// Cannot display signin status when running in guest mode on chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc
index 9318aff4dd6..5b314f5a314 100644
--- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc
@@ -38,6 +38,7 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
+#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_web_ui.h"
@@ -506,8 +507,9 @@ TEST_F(PeopleHandlerTest, AcquireSyncBlockerWhenLoadingSyncSettingsSubpage) {
EXPECT_FALSE(handler_->sync_blocker_);
- content::WebContentsTester::For(web_contents())
- ->StartNavigation(chrome::GetSettingsUrl(chrome::kSyncSetupSubPage));
+ auto navigation = content::NavigationSimulator::CreateBrowserInitiated(
+ chrome::GetSettingsUrl(chrome::kSyncSetupSubPage), web_contents());
+ navigation->Start();
handler_->InitializeSyncBlocker();
EXPECT_TRUE(handler_->sync_blocker_);
diff --git a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc
index 701fdad9632..102f8690da7 100644
--- a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc
@@ -88,9 +88,6 @@ void ProtocolHandlersHandler::GetHandlersForProtocol(
const std::string& protocol,
base::DictionaryValue* handlers_value) {
ProtocolHandlerRegistry* registry = GetProtocolHandlerRegistry();
- // The items which are to be written into |handlers_value| are also described
- // in chrome/browser/resources/options/handler_options.js in @typedef
- // for Handlers. Please update them whenever you add or remove any keys here.
handlers_value->SetString("protocol", protocol);
handlers_value->SetInteger("default_handler",
registry->GetHandlerIndex(protocol));
diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc
index 7f30825234b..6ecd5cc170d 100644
--- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc
@@ -70,7 +70,7 @@ ResetRequestOriginFromString(const std::string& request_origin) {
const char ResetSettingsHandler::kCctResetSettingsHash[] = "cct";
ResetSettingsHandler::ResetSettingsHandler(Profile* profile)
- : profile_(profile), weak_ptr_factory_(this) {
+ : profile_(profile), callback_weak_ptr_factory_(this) {
google_brand::GetBrand(&brandcode_);
}
@@ -100,6 +100,10 @@ ResetSettingsHandler* ResetSettingsHandler::Create(
return new ResetSettingsHandler(profile);
}
+void ResetSettingsHandler::OnJavascriptDisallowed() {
+ callback_weak_ptr_factory_.InvalidateWeakPtrs();
+}
+
void ResetSettingsHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("performResetProfileSettings",
base::Bind(&ResetSettingsHandler::HandleResetProfileSettings,
@@ -182,10 +186,9 @@ void ResetSettingsHandler::HandleGetReportedSettings(
std::string callback_id;
CHECK(args->GetString(0, &callback_id));
- setting_snapshot_->RequestShortcuts(base::Bind(
- &ResetSettingsHandler::OnGetReportedSettingsDone,
- weak_ptr_factory_.GetWeakPtr(),
- callback_id));
+ setting_snapshot_->RequestShortcuts(
+ base::Bind(&ResetSettingsHandler::OnGetReportedSettingsDone,
+ callback_weak_ptr_factory_.GetWeakPtr(), callback_id));
}
void ResetSettingsHandler::OnGetReportedSettingsDone(std::string callback_id) {
@@ -249,8 +252,8 @@ void ResetSettingsHandler::ResetProfile(
GetResetter()->Reset(
ProfileResetter::ALL, std::move(default_settings),
base::Bind(&ResetSettingsHandler::OnResetProfileSettingsDone,
- weak_ptr_factory_.GetWeakPtr(), callback_id, send_settings,
- request_origin));
+ callback_weak_ptr_factory_.GetWeakPtr(), callback_id,
+ send_settings, request_origin));
base::RecordAction(base::UserMetricsAction("ResetProfile"));
UMA_HISTOGRAM_BOOLEAN("ProfileReset.SendFeedback", send_settings);
UMA_HISTOGRAM_ENUMERATION(
diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h
index bb4d9f2207c..1a9458c43b3 100644
--- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h
@@ -47,7 +47,7 @@ class ResetSettingsHandler : public SettingsPageUIHandler {
// WebUIMessageHandler implementation.
void RegisterMessages() override;
void OnJavascriptAllowed() override {}
- void OnJavascriptDisallowed() override {}
+ void OnJavascriptDisallowed() override;
protected:
explicit ResetSettingsHandler(Profile* profile);
@@ -110,7 +110,8 @@ class ResetSettingsHandler : public SettingsPageUIHandler {
// Contains Chrome brand code; empty for organic Chrome.
std::string brandcode_;
- base::WeakPtrFactory<ResetSettingsHandler> weak_ptr_factory_;
+ // Used to cancel callbacks when JavaScript becomes disallowed.
+ base::WeakPtrFactory<ResetSettingsHandler> callback_weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ResetSettingsHandler);
};
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 8ba91de6eac..598f32482fa 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
@@ -34,6 +34,7 @@
#include "ui/base/text/bytes_formatting.h"
using ImportantReason = ImportantSitesUtil::ImportantReason;
+using BrowsingDataType = browsing_data::BrowsingDataType;
namespace {
@@ -110,6 +111,10 @@ void ClearBrowsingDataHandler::OnJavascriptDisallowed() {
void ClearBrowsingDataHandler::HandleClearBrowsingData(
const base::ListValue* args) {
+ CHECK_EQ(4U, args->GetSize());
+ std::string webui_callback_id;
+ CHECK(args->GetString(0, &webui_callback_id));
+
PrefService* prefs = profile_->GetPrefs();
int site_data_mask = ChromeBrowsingDataRemoverDelegate::DATA_TYPE_SITE_DATA;
@@ -118,44 +123,66 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData(
site_data_mask &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA;
int remove_mask = 0;
- if (prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory))
- remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory))
- remove_mask |= content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS;
- }
-
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteCache))
- remove_mask |= content::BrowsingDataRemover::DATA_TYPE_CACHE;
-
int origin_mask = 0;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteCookies)) {
- remove_mask |= site_data_mask;
- origin_mask |= content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
+ std::vector<BrowsingDataType> data_type_vector;
+ const base::ListValue* data_type_list = nullptr;
+ CHECK(args->GetList(1, &data_type_list));
+ for (const auto& type : *data_type_list) {
+ std::string pref_name;
+ CHECK(type.GetAsString(&pref_name));
+ BrowsingDataType data_type =
+ browsing_data::GetDataTypeFromDeletionPreference(pref_name);
+ data_type_vector.push_back(data_type);
+
+ switch (data_type) {
+ case BrowsingDataType::HISTORY:
+ if (prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory))
+ remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY;
+ break;
+ case BrowsingDataType::DOWNLOADS:
+ if (prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory))
+ remove_mask |= content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS;
+ break;
+ case BrowsingDataType::CACHE:
+ remove_mask |= content::BrowsingDataRemover::DATA_TYPE_CACHE;
+ break;
+ case BrowsingDataType::COOKIES:
+ remove_mask |= site_data_mask;
+ origin_mask |=
+ content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
+ break;
+ case BrowsingDataType::PASSWORDS:
+ remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PASSWORDS;
+ break;
+ case BrowsingDataType::FORM_DATA:
+ remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA;
+ break;
+ case BrowsingDataType::MEDIA_LICENSES:
+ remove_mask |= content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES;
+ break;
+ case BrowsingDataType::HOSTED_APPS_DATA:
+ remove_mask |= site_data_mask;
+ origin_mask |= content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
+ break;
+ case BrowsingDataType::BOOKMARKS:
+ case BrowsingDataType::SITE_SETTINGS:
+ // Only implemented on Android.
+ NOTREACHED();
+ case BrowsingDataType::NUM_TYPES:
+ NOTREACHED();
+ }
}
- if (prefs->GetBoolean(browsing_data::prefs::kDeletePasswords))
- remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PASSWORDS;
-
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteFormData))
- remove_mask |= ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA;
-
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteMediaLicenses))
- remove_mask |= content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES;
-
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteHostedAppsData)) {
- remove_mask |= site_data_mask;
- origin_mask |= content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
- }
+ base::flat_set<BrowsingDataType> data_types(std::move(data_type_vector));
// Record the deletion of cookies and cache.
content::BrowsingDataRemover::CookieOrCacheDeletionChoice choice =
content::BrowsingDataRemover::NEITHER_COOKIES_NOR_CACHE;
- if (prefs->GetBoolean(browsing_data::prefs::kDeleteCookies)) {
- choice = prefs->GetBoolean(browsing_data::prefs::kDeleteCache)
+ if (data_types.find(BrowsingDataType::COOKIES) != data_types.end()) {
+ choice = data_types.find(BrowsingDataType::CACHE) != data_types.end()
? content::BrowsingDataRemover::BOTH_COOKIES_AND_CACHE
: content::BrowsingDataRemover::ONLY_COOKIES;
- } else if (prefs->GetBoolean(browsing_data::prefs::kDeleteCache)) {
+ } else if (data_types.find(BrowsingDataType::CACHE) != data_types.end()) {
choice = content::BrowsingDataRemover::ONLY_CACHE;
}
@@ -164,43 +191,38 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData(
content::BrowsingDataRemover::MAX_CHOICE_VALUE);
// Record the circumstances under which passwords are deleted.
- if (prefs->GetBoolean(browsing_data::prefs::kDeletePasswords)) {
- static const char* other_types[] = {
- browsing_data::prefs::kDeleteBrowsingHistory,
- browsing_data::prefs::kDeleteDownloadHistory,
- browsing_data::prefs::kDeleteCache,
- browsing_data::prefs::kDeleteCookies,
- browsing_data::prefs::kDeleteFormData,
- browsing_data::prefs::kDeleteHostedAppsData,
- browsing_data::prefs::kDeleteMediaLicenses,
+ if (data_types.find(BrowsingDataType::PASSWORDS) != data_types.end()) {
+ static const BrowsingDataType other_types[] = {
+ BrowsingDataType::HISTORY, BrowsingDataType::DOWNLOADS,
+ BrowsingDataType::CACHE, BrowsingDataType::COOKIES,
+ BrowsingDataType::FORM_DATA, BrowsingDataType::HOSTED_APPS_DATA,
+ BrowsingDataType::MEDIA_LICENSES,
};
static size_t num_other_types = arraysize(other_types);
- int checked_other_types = std::count_if(
- other_types, other_types + num_other_types,
- [prefs](const std::string& pref) { return prefs->GetBoolean(pref); });
+ int checked_other_types =
+ std::count_if(other_types, other_types + num_other_types,
+ [&data_types](BrowsingDataType type) {
+ return data_types.find(type) != data_types.end();
+ });
UMA_HISTOGRAM_SPARSE_SLOWLY(
"History.ClearBrowsingData.PasswordsDeletion.AdditionalDatatypesCount",
checked_other_types);
}
- int period_selected =
- prefs->GetInteger(browsing_data::prefs::kDeleteTimePeriod);
-
- std::string webui_callback_id;
- CHECK_EQ(2U, args->GetSize());
- CHECK(args->GetString(0, &webui_callback_id));
+ int period_selected;
+ CHECK(args->GetInteger(2, &period_selected));
const base::ListValue* important_sites = nullptr;
- CHECK(args->GetList(1, &important_sites));
+ CHECK(args->GetList(3, &important_sites));
std::unique_ptr<content::BrowsingDataFilterBuilder> filter_builder =
ProcessImportantSites(important_sites);
content::BrowsingDataRemover* remover =
content::BrowserContext::GetBrowsingDataRemover(profile_);
- base::OnceClosure callback =
- base::BindOnce(&ClearBrowsingDataHandler::OnClearingTaskFinished,
- weak_ptr_factory_.GetWeakPtr(), webui_callback_id);
+ base::OnceClosure callback = base::BindOnce(
+ &ClearBrowsingDataHandler::OnClearingTaskFinished,
+ weak_ptr_factory_.GetWeakPtr(), webui_callback_id, std::move(data_types));
browsing_data::TimePeriod time_period =
static_cast<browsing_data::TimePeriod>(period_selected);
@@ -250,7 +272,8 @@ ClearBrowsingDataHandler::ProcessImportantSites(
}
void ClearBrowsingDataHandler::OnClearingTaskFinished(
- const std::string& webui_callback_id) {
+ const std::string& webui_callback_id,
+ const base::flat_set<BrowsingDataType>& data_types) {
PrefService* prefs = profile_->GetPrefs();
int notice_shown_times = prefs->GetInteger(
browsing_data::prefs::kClearBrowsingDataHistoryNoticeShownTimes);
@@ -263,7 +286,7 @@ void ClearBrowsingDataHandler::OnClearingTaskFinished(
// 2. The notice has been shown less than |kMaxTimesHistoryNoticeShown|.
notice_shown_times < kMaxTimesHistoryNoticeShown &&
// 3. The selected data types contained browsing history.
- prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory);
+ data_types.find(BrowsingDataType::HISTORY) != data_types.end();
if (show_notice) {
// Increment the preference.
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h
index 07cce948091..7e833071531 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h
@@ -9,12 +9,14 @@
#include <string>
#include <vector>
+#include "base/containers/flat_set.h"
#include "base/macros.h"
#include "base/scoped_observer.h"
#include "chrome/browser/engagement/important_sites_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "components/browser_sync/profile_sync_service.h"
+#include "components/browsing_data/core/browsing_data_utils.h"
#include "components/browsing_data/core/counters/browsing_data_counter.h"
namespace base {
@@ -51,7 +53,9 @@ class ClearBrowsingDataHandler : public SettingsPageUIHandler,
// Called when a clearing task finished. |webui_callback_id| is provided
// by the WebUI action that initiated it.
- void OnClearingTaskFinished(const std::string& webui_callback_id);
+ void OnClearingTaskFinished(
+ const std::string& webui_callback_id,
+ const base::flat_set<browsing_data::BrowsingDataType>& data_types);
// Get important sites, called by Javascript.
void HandleGetImportantSites(const base::ListValue* value);
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc
index a0a37b8a34f..4a019494a6d 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_import_data_handler.cc
@@ -231,7 +231,8 @@ void ImportDataHandler::HandleChooseBookmarksFile(const base::ListValue* args) {
DCHECK(args && args->empty());
select_file_dialog_ = ui::SelectFileDialog::Create(
- this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
+ this,
+ std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.resize(1);
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.h
index 1fdafc531e6..56b2f419b25 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_startup_pages_handler.h
@@ -6,7 +6,7 @@
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_STARTUP_PAGES_HANDLER_H_
#include "base/macros.h"
-#include "chrome/browser/custom_home_pages_table_model.h"
+#include "chrome/browser/ui/webui/settings/custom_home_pages_table_model.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "components/prefs/pref_change_registrar.h"
#include "ui/base/models/table_model_observer.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 0ecdfb29705..ac50ebeb82d 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -17,22 +17,26 @@
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/content_settings/web_site_settings_uma_util.h"
+#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/permissions/chooser_context_base.h"
-#include "chrome/browser/permissions/permission_manager.h"
-#include "chrome/browser/permissions/permission_result.h"
+#include "chrome/browser/permissions/permission_decision_auto_blocker.h"
#include "chrome/browser/permissions/permission_uma_util.h"
#include "chrome/browser/permissions/permission_util.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/browser/ui/page_info/page_info_infobar_delegate.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/site_settings_helper.h"
#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
#include "chrome/grit/generated_resources.h"
-#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/crx_file/id_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/page_zoom.h"
#include "content/public/common/url_constants.h"
@@ -52,7 +56,7 @@ namespace settings {
namespace {
-const char kZoom[] = "zoom";
+constexpr char kZoom[] = "zoom";
// Return an appropriate API Permission ID for the given string name.
extensions::APIPermission::APIPermission::ID APIPermissionFromGroupName(
@@ -103,89 +107,6 @@ void AddExceptionsGrantedByHostedApps(content::BrowserContext* context,
}
}
-// Retrieves the corresponding string, according to the following precedence
-// order from highest to lowest priority:
-// 1. Kill-switch.
-// 2. Enterprise policy.
-// 3. Extensions.
-// 4. User-set per-origin setting.
-// 5. Embargo.
-// 6. User-set patterns.
-// 7. User-set global default for a ContentSettingsType.
-// 8. Chrome's built-in default.
-std::string ConvertContentSettingSourceToString(
- const content_settings::SettingInfo& info,
- PermissionStatusSource permission_status_source) {
- // TODO(patricialor): Do some plumbing for sources #1, #2, #3, and #5 through
- // to the Web UI. Currently there aren't strings to represent these sources.
- if (permission_status_source == PermissionStatusSource::KILL_SWITCH)
- return site_settings::kPreferencesSource; // Source #1.
-
- if (info.source == content_settings::SETTING_SOURCE_POLICY ||
- info.source == content_settings::SETTING_SOURCE_SUPERVISED) {
- return site_settings::kPolicyProviderId; // Source #2.
- }
-
- if (info.source == content_settings::SETTING_SOURCE_EXTENSION)
- return site_settings::kExtensionProviderId; // Source #3.
-
- DCHECK_NE(content_settings::SETTING_SOURCE_NONE, info.source);
- if (info.source == content_settings::SETTING_SOURCE_USER) {
- if (permission_status_source ==
- PermissionStatusSource::SAFE_BROWSING_BLACKLIST ||
- permission_status_source ==
- PermissionStatusSource::MULTIPLE_DISMISSALS ||
- permission_status_source == PermissionStatusSource::MULTIPLE_IGNORES) {
- return site_settings::kPreferencesSource; // Source #5.
- }
- if (info.primary_pattern == ContentSettingsPattern::Wildcard() &&
- info.secondary_pattern == ContentSettingsPattern::Wildcard()) {
- return "default"; // Source #7, #8.
- }
- // Source #4, #6. When #4 is the source, |permission_status_source|
- // won't be set to any of the source #5 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 site_settings::kPreferencesSource;
- }
-
- NOTREACHED();
- return site_settings::kPreferencesSource;
-}
-
-ContentSetting GetContentSettingForOrigin(const GURL& origin,
- ContentSettingsType content_type,
- Profile* profile,
- std::string* source_string) {
- // TODO(patricialor): In future, PermissionManager should know about all
- // content settings, not just the permissions, plus all the possible sources,
- // and the calls to HostContentSettingsMap should be removed.
- content_settings::SettingInfo info;
- HostContentSettingsMap* map =
- HostContentSettingsMapFactory::GetForProfile(profile);
- std::unique_ptr<base::Value> value = map->GetWebsiteSetting(
- origin, origin, content_type, std::string(), &info);
-
- // Retrieve the content setting.
- PermissionResult result(CONTENT_SETTING_DEFAULT,
- PermissionStatusSource::UNSPECIFIED);
- if (PermissionUtil::IsPermission(content_type)) {
- result = PermissionManager::Get(profile)->GetPermissionStatus(
- content_type, origin, origin);
- } else {
- DCHECK(value.get());
- DCHECK_EQ(base::Value::Type::INTEGER, value->GetType());
- result.content_setting =
- content_settings::ValueToContentSetting(value.get());
- }
-
- // Retrieve the source of the content setting.
- *source_string = ConvertContentSettingSourceToString(info, result.source);
-
- return result.content_setting;
-}
-
} // namespace
@@ -230,14 +151,21 @@ void SiteSettingsHandler::RegisterMessages() {
base::Bind(&SiteSettingsHandler::HandleGetOriginPermissions,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "resetCategoryPermissionForOrigin",
- base::Bind(&SiteSettingsHandler::HandleResetCategoryPermissionForOrigin,
+ "setOriginPermissions",
+ base::Bind(&SiteSettingsHandler::HandleSetOriginPermissions,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "resetCategoryPermissionForPattern",
+ base::Bind(&SiteSettingsHandler::HandleResetCategoryPermissionForPattern,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "setCategoryPermissionForOrigin",
- base::Bind(&SiteSettingsHandler::HandleSetCategoryPermissionForOrigin,
+ "setCategoryPermissionForPattern",
+ base::Bind(&SiteSettingsHandler::HandleSetCategoryPermissionForPattern,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
+ "isOriginValid", base::Bind(&SiteSettingsHandler::HandleIsOriginValid,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
"isPatternValid",
base::Bind(&SiteSettingsHandler::HandleIsPatternValid,
base::Unretained(this)));
@@ -560,10 +488,15 @@ void SiteSettingsHandler::HandleGetOriginPermissions(
types->GetString(i, &type);
ContentSettingsType content_type =
site_settings::ContentSettingsTypeFromGroupName(type);
-
- std::string source_string;
- ContentSetting content_setting = GetContentSettingForOrigin(
- origin_url, content_type, profile_, &source_string);
+ HostContentSettingsMap* map =
+ HostContentSettingsMapFactory::GetForProfile(profile_);
+ const auto* extension_registry =
+ extensions::ExtensionRegistry::Get(profile_);
+
+ std::string source_string, display_name;
+ ContentSetting content_setting = site_settings::GetContentSettingForOrigin(
+ profile_, map, origin_url, content_type, &source_string,
+ extension_registry, &display_name);
std::string content_setting_string =
content_settings::ContentSettingToString(content_setting);
@@ -572,7 +505,7 @@ void SiteSettingsHandler::HandleGetOriginPermissions(
raw_site_exception->SetBoolean(site_settings::kIncognito,
profile_->IsOffTheRecord());
raw_site_exception->SetString(site_settings::kOrigin, origin);
- raw_site_exception->SetString(site_settings::kDisplayName, origin);
+ raw_site_exception->SetString(site_settings::kDisplayName, display_name);
raw_site_exception->SetString(site_settings::kSetting,
content_setting_string);
raw_site_exception->SetString(site_settings::kSource, source_string);
@@ -582,7 +515,62 @@ void SiteSettingsHandler::HandleGetOriginPermissions(
ResolveJavascriptCallback(*callback_id, *exceptions);
}
-void SiteSettingsHandler::HandleResetCategoryPermissionForOrigin(
+void SiteSettingsHandler::HandleSetOriginPermissions(
+ const base::ListValue* args) {
+ CHECK_EQ(3U, args->GetSize());
+ std::string origin_string;
+ CHECK(args->GetString(0, &origin_string));
+ const base::ListValue* types;
+ CHECK(args->GetList(1, &types));
+ std::string value;
+ CHECK(args->GetString(2, &value));
+
+ const GURL origin(origin_string);
+ if (!origin.is_valid())
+ return;
+
+ ContentSetting setting;
+ CHECK(content_settings::ContentSettingFromString(value, &setting));
+ for (size_t i = 0; i < types->GetSize(); ++i) {
+ std::string type;
+ types->GetString(i, &type);
+
+ ContentSettingsType content_type =
+ site_settings::ContentSettingsTypeFromGroupName(type);
+ HostContentSettingsMap* map =
+ HostContentSettingsMapFactory::GetForProfile(profile_);
+
+ PermissionUtil::ScopedRevocationReporter scoped_revocation_reporter(
+ profile_, origin, origin, content_type,
+ PermissionSourceUI::SITE_SETTINGS);
+
+ // Clear any existing embargo status if the new setting isn't block.
+ if (setting != CONTENT_SETTING_BLOCK) {
+ PermissionDecisionAutoBlocker::GetForProfile(profile_)
+ ->RemoveEmbargoByUrl(origin, content_type);
+ }
+ map->SetContentSettingDefaultScope(origin, origin, content_type,
+ std::string(), setting);
+ WebSiteSettingsUmaUtil::LogPermissionChange(content_type, setting);
+ }
+
+ // Show an infobar reminding the user to reload tabs where their site
+ // permissions have been updated.
+ for (auto* it : *BrowserList::GetInstance()) {
+ TabStripModel* tab_strip = it->tab_strip_model();
+ for (int i = 0; i < tab_strip->count(); ++i) {
+ content::WebContents* web_contents = tab_strip->GetWebContentsAt(i);
+ GURL tab_url = web_contents->GetLastCommittedURL();
+ if (url::IsSameOriginWith(origin, tab_url)) {
+ InfoBarService* infobar_service =
+ InfoBarService::FromWebContents(web_contents);
+ PageInfoInfoBarDelegate::Create(infobar_service);
+ }
+ }
+ }
+}
+
+void SiteSettingsHandler::HandleResetCategoryPermissionForPattern(
const base::ListValue* args) {
CHECK_EQ(4U, args->GetSize());
std::string primary_pattern_string;
@@ -626,7 +614,7 @@ void SiteSettingsHandler::HandleResetCategoryPermissionForOrigin(
content_type, ContentSetting::CONTENT_SETTING_DEFAULT);
}
-void SiteSettingsHandler::HandleSetCategoryPermissionForOrigin(
+void SiteSettingsHandler::HandleSetCategoryPermissionForPattern(
const base::ListValue* args) {
CHECK_EQ(5U, args->GetSize());
std::string primary_pattern_string;
@@ -675,6 +663,18 @@ void SiteSettingsHandler::HandleSetCategoryPermissionForOrigin(
WebSiteSettingsUmaUtil::LogPermissionChange(content_type, setting);
}
+void SiteSettingsHandler::HandleIsOriginValid(const base::ListValue* args) {
+ AllowJavascript();
+ CHECK_EQ(2U, args->GetSize());
+ const base::Value* callback_id;
+ CHECK(args->Get(0, &callback_id));
+ std::string origin_string;
+ CHECK(args->GetString(1, &origin_string));
+
+ ResolveJavascriptCallback(*callback_id,
+ base::Value(GURL(origin_string).is_valid()));
+}
+
void SiteSettingsHandler::HandleIsPatternValid(
const base::ListValue* args) {
CHECK_EQ(2U, args->GetSize());
@@ -790,8 +790,9 @@ void SiteSettingsHandler::SendZoomLevels() {
int zoom_percent = static_cast<int>(
content::ZoomLevelToZoomFactor(zoom_level.zoom_level) * 100 + 0.5);
exception->SetString(kZoom, base::FormatPercent(zoom_percent));
- exception->SetString(
- site_settings::kSource, site_settings::kPreferencesSource);
+ exception->SetString(site_settings::kSource,
+ site_settings::SiteSettingSourceToString(
+ site_settings::SiteSettingSource::kPreference));
// Append the new entry to the list and map.
zoom_levels_exceptions.Append(std::move(exception));
}
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 e735dd71fe6..dfeac3099a9 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
@@ -59,13 +59,19 @@ class SiteSettingsHandler : public SettingsPageUIHandler,
private:
friend class SiteSettingsHandlerTest;
+ friend class SiteSettingsHandlerInfobarTest;
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, DefaultSettingSource);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExceptionHelpers);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExtensionDisplayName);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetDefault);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetOriginPermissions);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetForInvalidURLs);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Incognito);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Origins);
- FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExceptionHelpers);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Patterns);
- FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Incognito);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerInfobarTest,
+ SettingPermissionsTriggersInfobar);
// Asynchronously fetches the usage for a given origin. Replies back with
// OnGetUsageInfo above.
@@ -87,13 +93,18 @@ class SiteSettingsHandler : public SettingsPageUIHandler,
// Returns the list of site exceptions for a given content settings type.
void HandleGetExceptionList(const base::ListValue* args);
+ // Gets and sets a list of ContentSettingTypes for an origin.
+ // TODO(https://crbug.com/739241): Investigate replacing the
+ // '*CategoryPermissionForPattern' equivalents below with these methods.
+ void HandleGetOriginPermissions(const base::ListValue* args);
+ void HandleSetOriginPermissions(const base::ListValue* args);
+
// Handles setting and resetting an origin permission.
- void HandleResetCategoryPermissionForOrigin(const base::ListValue* args);
- void HandleSetCategoryPermissionForOrigin(const base::ListValue* args);
+ void HandleResetCategoryPermissionForPattern(const base::ListValue* args);
+ void HandleSetCategoryPermissionForPattern(const base::ListValue* args);
- // Retrieves the content settings for a given list of ContentSettingTypes for
- // an origin.
- void HandleGetOriginPermissions(const base::ListValue* args);
+ // Returns whether a given string is a valid origin.
+ void HandleIsOriginValid(const base::ListValue* args);
// Returns whether a given pattern is valid.
void HandleIsPatternValid(const base::ListValue* args);
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 2d843114943..ac904b3c9a1 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
@@ -5,21 +5,31 @@
#include "chrome/browser/ui/webui/settings/site_settings_handler.h"
#include <memory>
+#include <string>
#include "base/test/histogram_tester.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
+#include "chrome/browser/extensions/extension_service.h"
+#include "chrome/browser/extensions/test_extension_system.h"
+#include "chrome/browser/infobars/infobar_service.h"
+#include "chrome/browser/ui/browser_window.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/site_settings_helper.h"
+#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_profile.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_types.h"
#include "components/content_settings/core/common/pref_names.h"
+#include "components/infobars/core/infobar.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
+#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_web_ui.h"
+#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension_builder.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -30,9 +40,10 @@
namespace {
-const char kCallbackId[] = "test-callback-id";
-const char kSetting[] = "setting";
-const char kSource[] = "source";
+constexpr char kCallbackId[] = "test-callback-id";
+constexpr char kSetting[] = "setting";
+constexpr char kSource[] = "source";
+constexpr char kExtensionName[] = "Test Extension";
}
@@ -74,7 +85,10 @@ class ContentSettingSourceSetter {
class SiteSettingsHandlerTest : public testing::Test {
public:
- SiteSettingsHandlerTest() : handler_(&profile_) {
+ SiteSettingsHandlerTest()
+ : kNotifications(site_settings::ContentSettingsTypeToGroupName(
+ CONTENT_SETTINGS_TYPE_NOTIFICATIONS)),
+ handler_(&profile_) {
#if defined(OS_CHROMEOS)
mock_user_manager_ = new chromeos::MockUserManager;
user_manager_enabler_.reset(
@@ -92,8 +106,8 @@ class SiteSettingsHandlerTest : public testing::Test {
content::TestWebUI* web_ui() { return &web_ui_; }
SiteSettingsHandler* handler() { return &handler_; }
- void ValidateDefault(const std::string& expected_setting,
- const std::string& expected_source,
+ void ValidateDefault(const ContentSetting expected_setting,
+ const site_settings::SiteSettingSource expected_source,
size_t expected_total_calls) {
EXPECT_EQ(expected_total_calls, web_ui()->call_data().size());
@@ -112,19 +126,20 @@ class SiteSettingsHandlerTest : public testing::Test {
ASSERT_TRUE(data.arg3()->GetAsDictionary(&default_value));
std::string setting;
ASSERT_TRUE(default_value->GetString(kSetting, &setting));
- EXPECT_EQ(expected_setting, setting);
+ EXPECT_EQ(content_settings::ContentSettingToString(expected_setting),
+ setting);
std::string source;
if (default_value->GetString(kSource, &source))
- EXPECT_EQ(expected_source, source);
+ EXPECT_EQ(site_settings::SiteSettingSourceToString(expected_source),
+ source);
}
- void ValidateOrigin(
- const std::string& expected_origin,
- const std::string& expected_display_name,
- const std::string& expected_embedding,
- const std::string& expected_setting,
- const std::string& expected_source,
- size_t expected_total_calls) {
+ void ValidateOrigin(const std::string& expected_origin,
+ const std::string& expected_embedding,
+ const std::string& expected_display_name,
+ const ContentSetting expected_setting,
+ const site_settings::SiteSettingSource expected_source,
+ size_t expected_total_calls) {
EXPECT_EQ(expected_total_calls, web_ui()->call_data().size());
const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
@@ -152,9 +167,11 @@ class SiteSettingsHandlerTest : public testing::Test {
site_settings::kEmbeddingOrigin, &embedding_origin));
ASSERT_EQ(expected_embedding, embedding_origin);
ASSERT_TRUE(exception->GetString(site_settings::kSetting, &setting));
- ASSERT_EQ(expected_setting, setting);
+ ASSERT_EQ(content_settings::ContentSettingToString(expected_setting),
+ setting);
ASSERT_TRUE(exception->GetString(site_settings::kSource, &source));
- ASSERT_EQ(expected_source, source);
+ ASSERT_EQ(site_settings::SiteSettingSourceToString(expected_source),
+ source);
}
void ValidateNoOrigin(size_t expected_total_calls) {
@@ -256,6 +273,9 @@ class SiteSettingsHandlerTest : public testing::Test {
incognito_profile_ = nullptr;
}
+ // Content setting group name for |CONTENT_SETTINGS_TYPE_NOTIFICATIONS|.
+ const std::string kNotifications;
+
private:
content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_;
@@ -272,37 +292,41 @@ TEST_F(SiteSettingsHandlerTest, GetAndSetDefault) {
// Test the JS -> C++ -> JS callback path for getting and setting defaults.
base::ListValue get_args;
get_args.AppendString(kCallbackId);
- get_args.AppendString("notifications");
+ get_args.AppendString(kNotifications);
handler()->HandleGetDefaultValueForContentType(&get_args);
- ValidateDefault("ask", "default", 1U);
+ ValidateDefault(CONTENT_SETTING_ASK,
+ site_settings::SiteSettingSource::kDefault, 1U);
// Set the default to 'Blocked'.
base::ListValue set_args;
- set_args.AppendString("notifications");
- set_args.AppendString("block");
+ set_args.AppendString(kNotifications);
+ set_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK));
handler()->HandleSetDefaultValueForContentType(&set_args);
EXPECT_EQ(2U, web_ui()->call_data().size());
// Verify that the default has been set to 'Blocked'.
handler()->HandleGetDefaultValueForContentType(&get_args);
- ValidateDefault("block", "default", 3U);
+ ValidateDefault(CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSource::kDefault, 3U);
}
TEST_F(SiteSettingsHandlerTest, Origins) {
- // Test the JS -> C++ -> JS callback path for configuring origins, by setting
- // Google.com to blocked.
- const std::string google("http://www.google.com");
+ const std::string google("https://www.google.com:443");
const std::string kUmaBase("WebsiteSettings.Menu.PermissionChanged");
{
+ // Test the JS -> C++ -> JS callback path for configuring origins, by
+ // setting Google.com to blocked.
base::ListValue set_args;
set_args.AppendString(google); // Primary pattern.
set_args.AppendString(google); // Secondary pattern.
- set_args.AppendString("notifications");
- set_args.AppendString("block");
+ set_args.AppendString(kNotifications);
+ set_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK));
set_args.AppendBoolean(false); // Incognito.
base::HistogramTester histograms;
- handler()->HandleSetCategoryPermissionForOrigin(&set_args);
+ handler()->HandleSetCategoryPermissionForPattern(&set_args);
EXPECT_EQ(1U, web_ui()->call_data().size());
histograms.ExpectTotalCount(kUmaBase, 1);
histograms.ExpectTotalCount(kUmaBase + ".Allowed", 0);
@@ -310,37 +334,23 @@ TEST_F(SiteSettingsHandlerTest, Origins) {
histograms.ExpectTotalCount(kUmaBase + ".Reset", 0);
}
- // If the change was successful, it should show up in the response from
- // getExceptionList() as well as getOriginPermissions().
- // Check getOriginPermissions().
- base::ListValue get_origin_permissions_args;
- get_origin_permissions_args.AppendString(kCallbackId);
- get_origin_permissions_args.AppendString(google);
- {
- auto category_list = base::MakeUnique<base::ListValue>();
- category_list->AppendString("notifications");
- get_origin_permissions_args.Append(std::move(category_list));
- }
- handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- ValidateOrigin(google, google, google, "block", "preference", 2U);
-
- // Check getExceptionList().
base::ListValue get_exception_list_args;
get_exception_list_args.AppendString(kCallbackId);
- get_exception_list_args.AppendString("notifications");
+ get_exception_list_args.AppendString(kNotifications);
handler()->HandleGetExceptionList(&get_exception_list_args);
- ValidateOrigin(google, google, google, "block", "preference", 3U);
+ ValidateOrigin(google, google, google, CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSource::kPreference, 2U);
{
// Reset things back to how they were.
base::ListValue reset_args;
reset_args.AppendString(google);
reset_args.AppendString(google);
- reset_args.AppendString("notifications");
+ reset_args.AppendString(kNotifications);
reset_args.AppendBoolean(false); // Incognito.
base::HistogramTester histograms;
- handler()->HandleResetCategoryPermissionForOrigin(&reset_args);
- EXPECT_EQ(4U, web_ui()->call_data().size());
+ handler()->HandleResetCategoryPermissionForPattern(&reset_args);
+ EXPECT_EQ(3U, web_ui()->call_data().size());
histograms.ExpectTotalCount(kUmaBase, 1);
histograms.ExpectTotalCount(kUmaBase + ".Allowed", 0);
histograms.ExpectTotalCount(kUmaBase + ".Blocked", 0);
@@ -349,15 +359,12 @@ TEST_F(SiteSettingsHandlerTest, Origins) {
// Verify the reset was successful.
handler()->HandleGetExceptionList(&get_exception_list_args);
- ValidateNoOrigin(5U);
-
- handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- // "Ask" is the default value for Notifications.
- ValidateOrigin(google, google, google, "ask", "default", 6U);
+ ValidateNoOrigin(4U);
}
TEST_F(SiteSettingsHandlerTest, DefaultSettingSource) {
- const std::string google("https://www.google.com");
+ // Use a non-default port to verify the display name does not strip this off.
+ const std::string google("https://www.google.com:183");
ContentSettingSourceSetter source_setter(profile(),
CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
@@ -365,58 +372,153 @@ TEST_F(SiteSettingsHandlerTest, DefaultSettingSource) {
get_origin_permissions_args.AppendString(kCallbackId);
get_origin_permissions_args.AppendString(google);
auto category_list = base::MakeUnique<base::ListValue>();
- category_list->AppendString("notifications");
+ category_list->AppendString(kNotifications);
get_origin_permissions_args.Append(std::move(category_list));
// Test Chrome built-in defaults are marked as default.
handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- ValidateOrigin(google, google, google, "ask", "default", 1U);
+ ValidateOrigin(google, google, google, CONTENT_SETTING_ASK,
+ site_settings::SiteSettingSource::kDefault, 1U);
base::ListValue default_value_args;
- default_value_args.AppendString("notifications");
- default_value_args.AppendString("block");
+ default_value_args.AppendString(kNotifications);
+ default_value_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK));
handler()->HandleSetDefaultValueForContentType(&default_value_args);
// A user-set global default should also show up as default.
handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- ValidateOrigin(google, google, google, "block", "default", 3U);
+ ValidateOrigin(google, google, google, CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSource::kDefault, 3U);
base::ListValue set_notification_pattern_args;
set_notification_pattern_args.AppendString("[*.]google.com");
set_notification_pattern_args.AppendString("*");
- set_notification_pattern_args.AppendString("notifications");
- set_notification_pattern_args.AppendString("allow");
+ set_notification_pattern_args.AppendString(kNotifications);
+ set_notification_pattern_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_ALLOW));
set_notification_pattern_args.AppendBoolean(false);
- handler()->HandleSetCategoryPermissionForOrigin(
+ handler()->HandleSetCategoryPermissionForPattern(
&set_notification_pattern_args);
// A user-set pattern should not show up as default.
handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- ValidateOrigin(google, google, google, "allow", "preference", 5U);
+ ValidateOrigin(google, google, google, CONTENT_SETTING_ALLOW,
+ site_settings::SiteSettingSource::kPreference, 5U);
base::ListValue set_notification_origin_args;
set_notification_origin_args.AppendString(google);
set_notification_origin_args.AppendString(google);
- set_notification_origin_args.AppendString("notifications");
- set_notification_origin_args.AppendString("block");
+ set_notification_origin_args.AppendString(kNotifications);
+ set_notification_origin_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK));
set_notification_origin_args.AppendBoolean(false);
- handler()->HandleSetCategoryPermissionForOrigin(
+ handler()->HandleSetCategoryPermissionForPattern(
&set_notification_origin_args);
// A user-set per-origin permission should not show up as default.
handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- ValidateOrigin(google, google, google, "block", "preference", 7U);
+ ValidateOrigin(google, google, google, CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSource::kPreference, 7U);
// Enterprise-policy set defaults should not show up as default.
source_setter.SetPolicyDefault(CONTENT_SETTING_ALLOW);
handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
- ValidateOrigin(google, google, google, "allow", "policy", 8U);
+ ValidateOrigin(google, google, google, CONTENT_SETTING_ALLOW,
+ site_settings::SiteSettingSource::kPolicy, 8U);
+}
+
+TEST_F(SiteSettingsHandlerTest, GetAndSetOriginPermissions) {
+ const std::string origin_with_port("https://www.example.com:443");
+ // The display name won't show the port if it's default for that scheme.
+ const std::string origin("https://www.example.com");
+ base::ListValue get_args;
+ get_args.AppendString(kCallbackId);
+ get_args.AppendString(origin_with_port);
+ {
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ get_args.Append(std::move(category_list));
+ }
+ handler()->HandleGetOriginPermissions(&get_args);
+ ValidateOrigin(origin_with_port, origin_with_port, origin,
+ CONTENT_SETTING_ASK,
+ site_settings::SiteSettingSource::kDefault, 1U);
+
+ // Block notifications.
+ base::ListValue set_args;
+ set_args.AppendString(origin_with_port);
+ {
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ set_args.Append(std::move(category_list));
+ }
+ set_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK));
+ handler()->HandleSetOriginPermissions(&set_args);
+ EXPECT_EQ(2U, web_ui()->call_data().size());
+
+ // Reset things back to how they were.
+ base::ListValue reset_args;
+ reset_args.AppendString(origin_with_port);
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ reset_args.Append(std::move(category_list));
+ reset_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_DEFAULT));
+
+ handler()->HandleSetOriginPermissions(&reset_args);
+ EXPECT_EQ(3U, web_ui()->call_data().size());
+
+ // Verify the reset was successful.
+ handler()->HandleGetOriginPermissions(&get_args);
+ ValidateOrigin(origin_with_port, origin_with_port, origin,
+ CONTENT_SETTING_ASK,
+ site_settings::SiteSettingSource::kDefault, 4U);
+}
+
+TEST_F(SiteSettingsHandlerTest, GetAndSetForInvalidURLs) {
+ const std::string origin("arbitrary string");
+ EXPECT_FALSE(GURL(origin).is_valid());
+ base::ListValue get_args;
+ get_args.AppendString(kCallbackId);
+ get_args.AppendString(origin);
+ {
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ get_args.Append(std::move(category_list));
+ }
+ handler()->HandleGetOriginPermissions(&get_args);
+ // Verify that it'll return CONTENT_SETTING_BLOCK as |origin| is not a secure
+ // context, a requirement for notifications. Note that the display string
+ // will be blank since it's an invalid URL.
+ ValidateOrigin(origin, origin, "", CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSource::kInsecureOrigin, 1U);
+
+ // Make sure setting a permission on an invalid origin doesn't crash.
+ base::ListValue set_args;
+ set_args.AppendString(origin);
+ {
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ set_args.Append(std::move(category_list));
+ }
+ set_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_ALLOW));
+ handler()->HandleSetOriginPermissions(&set_args);
+
+ // Also make sure the content setting for |origin| wasn't actually changed.
+ handler()->HandleGetOriginPermissions(&get_args);
+ ValidateOrigin(origin, origin, "", CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSource::kInsecureOrigin, 2U);
}
TEST_F(SiteSettingsHandlerTest, ExceptionHelpers) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromString("[*.]google.com");
std::unique_ptr<base::DictionaryValue> exception =
- site_settings::GetExceptionForPage(pattern, pattern, pattern.ToString(),
- CONTENT_SETTING_BLOCK, "preference",
- false);
+ site_settings::GetExceptionForPage(
+ pattern, pattern, pattern.ToString(), CONTENT_SETTING_BLOCK,
+ site_settings::SiteSettingSourceToString(
+ site_settings::SiteSettingSource::kPreference),
+ false);
std::string primary_pattern, secondary_pattern, display_name, type;
bool incognito;
@@ -430,18 +532,18 @@ TEST_F(SiteSettingsHandlerTest, ExceptionHelpers) {
base::ListValue args;
args.AppendString(primary_pattern);
args.AppendString(secondary_pattern);
- args.AppendString("notifications"); // Chosen arbitrarily.
+ args.AppendString(kNotifications); // Chosen arbitrarily.
args.AppendString(type);
args.AppendBoolean(incognito);
// We don't need to check the results. This is just to make sure it doesn't
// crash on the input.
- handler()->HandleSetCategoryPermissionForOrigin(&args);
+ handler()->HandleSetCategoryPermissionForPattern(&args);
scoped_refptr<const extensions::Extension> extension;
extension = extensions::ExtensionBuilder()
.SetManifest(extensions::DictionaryBuilder()
- .Set("name", "Test extension")
+ .Set("name", kExtensionName)
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Build())
@@ -462,7 +564,36 @@ TEST_F(SiteSettingsHandlerTest, ExceptionHelpers) {
CHECK(dictionary->GetBoolean(site_settings::kIncognito, &incognito));
// Again, don't need to check the results.
- handler()->HandleSetCategoryPermissionForOrigin(&args);
+ handler()->HandleSetCategoryPermissionForPattern(&args);
+}
+
+TEST_F(SiteSettingsHandlerTest, ExtensionDisplayName) {
+ auto* extension_registry = extensions::ExtensionRegistry::Get(profile());
+ std::string test_extension_id = "test-extension-url";
+ std::string test_extension_url = "chrome-extension://" + test_extension_id;
+ scoped_refptr<const extensions::Extension> extension =
+ extensions::ExtensionBuilder()
+ .SetManifest(extensions::DictionaryBuilder()
+ .Set("name", kExtensionName)
+ .Set("version", "1.0.0")
+ .Set("manifest_version", 2)
+ .Build())
+ .SetID(test_extension_id)
+ .Build();
+ extension_registry->AddEnabled(extension);
+
+ base::ListValue get_origin_permissions_args;
+ get_origin_permissions_args.AppendString(kCallbackId);
+ get_origin_permissions_args.AppendString(test_extension_url);
+ {
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ get_origin_permissions_args.Append(std::move(category_list));
+ }
+ handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
+ ValidateOrigin(test_extension_url, test_extension_url, kExtensionName,
+ CONTENT_SETTING_ASK,
+ site_settings::SiteSettingSource::kDefault, 1U);
}
TEST_F(SiteSettingsHandlerTest, Patterns) {
@@ -525,4 +656,218 @@ TEST_F(SiteSettingsHandlerTest, ZoomLevels) {
EXPECT_EQ(default_level, level);
}
+class SiteSettingsHandlerInfobarTest : public BrowserWithTestWindowTest {
+ public:
+ SiteSettingsHandlerInfobarTest()
+ : kNotifications(site_settings::ContentSettingsTypeToGroupName(
+ CONTENT_SETTINGS_TYPE_NOTIFICATIONS)) {}
+
+ void SetUp() override {
+ BrowserWithTestWindowTest::SetUp();
+ handler_ = base::MakeUnique<SiteSettingsHandler>(profile());
+ handler()->set_web_ui(web_ui());
+ handler()->AllowJavascript();
+ web_ui()->ClearTrackedCalls();
+
+ window2_ = base::WrapUnique(CreateBrowserWindow());
+ browser2_ = base::WrapUnique(
+ CreateBrowser(profile(), browser()->type(), false, window2_.get()));
+
+ extensions::TestExtensionSystem* extension_system =
+ static_cast<extensions::TestExtensionSystem*>(
+ extensions::ExtensionSystem::Get(profile()));
+ extension_system->CreateExtensionService(
+ base::CommandLine::ForCurrentProcess(), base::FilePath(), false);
+ }
+
+ void TearDown() override {
+ // SiteSettingsHandler maintains a HostZoomMap::Subscription internally, so
+ // make sure that's cleared before BrowserContext / profile destruction.
+ handler()->DisallowJavascript();
+
+ // Also destroy |browser2_| before the profile. browser()'s destruction is
+ // handled in BrowserWithTestWindowTest::TearDown().
+ browser2()->tab_strip_model()->CloseAllTabs();
+ browser2_.reset();
+ BrowserWithTestWindowTest::TearDown();
+ }
+
+ InfoBarService* GetInfobarServiceForTab(Browser* browser,
+ int tab_index,
+ GURL* tab_url) {
+ content::WebContents* web_contents =
+ browser->tab_strip_model()->GetWebContentsAt(tab_index);
+ if (tab_url)
+ *tab_url = web_contents->GetLastCommittedURL();
+ return InfoBarService::FromWebContents(web_contents);
+ }
+
+ content::TestWebUI* web_ui() { return &web_ui_; }
+
+ SiteSettingsHandler* handler() { return handler_.get(); }
+
+ Browser* browser2() { return browser2_.get(); }
+
+ const std::string kNotifications;
+
+ private:
+ content::TestWebUI web_ui_;
+ std::unique_ptr<SiteSettingsHandler> handler_;
+ std::unique_ptr<BrowserWindow> window2_;
+ std::unique_ptr<Browser> browser2_;
+
+ DISALLOW_COPY_AND_ASSIGN(SiteSettingsHandlerInfobarTest);
+};
+
+TEST_F(SiteSettingsHandlerInfobarTest, SettingPermissionsTriggersInfobar) {
+ // Note all GURLs starting with 'origin' below belong to the same origin.
+ // _____ _______________ ________ ________ ___________
+ // Window 1: / foo \' origin_anchor \' chrome \' origin \' extension \
+ // ------------- -----------------------------------------------------
+ std::string origin_anchor_string =
+ "https://www.example.com/with/path/blah#heading";
+ const GURL foo("http://foo");
+ const GURL origin_anchor(origin_anchor_string);
+ const GURL chrome("chrome://about");
+ const GURL origin("https://www.example.com/");
+ const GURL extension(
+ "chrome-extension://fooooooooooooooooooooooooooooooo/bar.html");
+
+ // Make sure |extension|'s extension ID exists before navigating to it. This
+ // fixes a test timeout that occurs with --enable-browser-side-navigation on.
+ scoped_refptr<const extensions::Extension> test_extension =
+ extensions::ExtensionBuilder("Test")
+ .SetID("fooooooooooooooooooooooooooooooo")
+ .Build();
+ extensions::ExtensionSystem::Get(profile())
+ ->extension_service()
+ ->AddExtension(test_extension.get());
+
+ // __________ ______________ ___________________ _______
+ // Window 2: / insecure '/ origin_query \' example_subdomain \' about \
+ // ------------------------- --------------------------------
+ const GURL insecure("http://www.example.com/");
+ const GURL origin_query("https://www.example.com/?param=value");
+ const GURL example_subdomain("https://subdomain.example.com/");
+ const GURL about(url::kAboutBlankURL);
+
+ // Set up. Note AddTab() adds tab at index 0, so add them in reverse order.
+ AddTab(browser(), extension);
+ AddTab(browser(), origin);
+ AddTab(browser(), chrome);
+ AddTab(browser(), origin_anchor);
+ AddTab(browser(), foo);
+ for (int i = 0; i < browser()->tab_strip_model()->count(); ++i) {
+ EXPECT_EQ(0u,
+ GetInfobarServiceForTab(browser(), i, nullptr)->infobar_count());
+ }
+
+ AddTab(browser2(), about);
+ AddTab(browser2(), example_subdomain);
+ AddTab(browser2(), origin_query);
+ AddTab(browser2(), insecure);
+ for (int i = 0; i < browser2()->tab_strip_model()->count(); ++i) {
+ EXPECT_EQ(0u,
+ GetInfobarServiceForTab(browser2(), i, nullptr)->infobar_count());
+ }
+
+ // Block notifications.
+ base::ListValue set_args;
+ set_args.AppendString(origin_anchor_string);
+ {
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ set_args.Append(std::move(category_list));
+ }
+ set_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK));
+ handler()->HandleSetOriginPermissions(&set_args);
+
+ // Make sure all tabs belonging to the same origin as |origin_anchor| have an
+ // infobar shown.
+ GURL tab_url;
+ for (int i = 0; i < browser()->tab_strip_model()->count(); ++i) {
+ if (i == /*origin_anchor=*/1 || i == /*origin=*/3) {
+ EXPECT_EQ(
+ 1u, GetInfobarServiceForTab(browser(), i, &tab_url)->infobar_count());
+ EXPECT_TRUE(url::IsSameOriginWith(origin, tab_url));
+ } else {
+ EXPECT_EQ(
+ 0u, GetInfobarServiceForTab(browser(), i, &tab_url)->infobar_count());
+ EXPECT_FALSE(url::IsSameOriginWith(origin, tab_url));
+ }
+ }
+ for (int i = 0; i < browser2()->tab_strip_model()->count(); ++i) {
+ if (i == /*origin_query=*/1) {
+ EXPECT_EQ(
+ 1u,
+ GetInfobarServiceForTab(browser2(), i, &tab_url)->infobar_count());
+ EXPECT_TRUE(url::IsSameOriginWith(origin, tab_url));
+ } else {
+ EXPECT_EQ(
+ 0u,
+ GetInfobarServiceForTab(browser2(), i, &tab_url)->infobar_count());
+ EXPECT_FALSE(url::IsSameOriginWith(origin, tab_url));
+ }
+ }
+
+ // Navigate the |foo| tab to the same origin as |origin_anchor|, and the
+ // |origin_query| tab to a different origin.
+ const GURL origin_path("https://www.example.com/path/to/page.html");
+ content::NavigationController* foo_controller =
+ &browser()
+ ->tab_strip_model()
+ ->GetWebContentsAt(/*foo=*/0)
+ ->GetController();
+ NavigateAndCommit(foo_controller, origin_path);
+
+ const GURL example_without_www("https://example.com/");
+ content::NavigationController* origin_query_controller =
+ &browser2()
+ ->tab_strip_model()
+ ->GetWebContentsAt(/*origin_query=*/1)
+ ->GetController();
+ NavigateAndCommit(origin_query_controller, example_without_www);
+
+ // Reset all permissions.
+ base::ListValue reset_args;
+ reset_args.AppendString(origin_anchor_string);
+ auto category_list = base::MakeUnique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ reset_args.Append(std::move(category_list));
+ reset_args.AppendString(
+ content_settings::ContentSettingToString(CONTENT_SETTING_DEFAULT));
+ handler()->HandleSetOriginPermissions(&reset_args);
+
+ // Check the same tabs (plus the tab navigated to |origin_path|) still have
+ // infobars showing.
+ for (int i = 0; i < browser()->tab_strip_model()->count(); ++i) {
+ if (i == /*origin_path=*/0 || i == /*origin_anchor=*/1 ||
+ i == /*origin=*/3) {
+ EXPECT_EQ(
+ 1u, GetInfobarServiceForTab(browser(), i, &tab_url)->infobar_count());
+ EXPECT_TRUE(url::IsSameOriginWith(origin, tab_url));
+ } else {
+ EXPECT_EQ(
+ 0u, GetInfobarServiceForTab(browser(), i, &tab_url)->infobar_count());
+ EXPECT_FALSE(url::IsSameOriginWith(origin, tab_url));
+ }
+ }
+ // The infobar on the original |origin_query| tab (which has now been
+ // navigated to |example_without_www|) should disappear.
+ for (int i = 0; i < browser2()->tab_strip_model()->count(); ++i) {
+ EXPECT_EQ(
+ 0u, GetInfobarServiceForTab(browser2(), i, &tab_url)->infobar_count());
+ EXPECT_FALSE(url::IsSameOriginWith(origin, tab_url));
+ }
+
+ // Make sure it's the correct infobar that's being shown.
+ EXPECT_EQ(infobars::InfoBarDelegate::PAGE_INFO_INFOBAR_DELEGATE,
+ GetInfobarServiceForTab(browser(), /*origin_path=*/0, &tab_url)
+ ->infobar_at(0)
+ ->delegate()
+ ->GetIdentifier());
+ EXPECT_TRUE(url::IsSameOriginWith(origin, tab_url));
+}
+
} // namespace settings
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 71e633bf7b0..c5c69ded135 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc
@@ -277,7 +277,7 @@ void InlineLoginHandler::HandleNavigationButtonClicked(
Browser* browser = signin::GetDesktopBrowser(web_ui());
DCHECK(browser);
- browser->signin_view_controller()->delegate()->PerformNavigation();
+ browser->signin_view_controller()->PerformNavigation();
}
void InlineLoginHandler::HandleDialogClose(const base::ListValue* args) {
diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc
index 7e5ee30a873..fc181e2df5e 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
@@ -73,7 +73,7 @@
namespace {
-void LogHistogramValue(int action) {
+void LogHistogramValue(signin_metrics::AccessPointAction action) {
UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
signin_metrics::HISTOGRAM_MAX);
}
diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h
index 55b00d2f5be..8863b9c26b4 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h
@@ -10,9 +10,13 @@
#include "ui/web_dialogs/web_dialog_ui.h"
// Inline login WebUI in various signin flows for ChromeOS and Chrome desktop.
-// The authentication is carried out via the host gaia_auth extension. Upon
-// success, the profile of the webui should be populated with proper cookies.
-// Then this UI would fetch the oauth2 tokens using the cookies.
+// Upon success, the profile of the webui should be populated with proper
+// cookies. Then this UI would fetch the oauth2 tokens using the cookies.
+//
+// The authentication is carried out via the host gaia_auth extension because:
+// * The page is loaded in a isolated renderer, which is better for security.
+// * Gaia endpoints used during sign-in expect a clean cookie jar.
+// * It bypasses account consistency and reconciliation.
class InlineLoginUI : public ui::WebDialogUI {
public:
explicit InlineLoginUI(content::WebUI* web_ui);
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 06fe6ac739b..2a10ba64ba4 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
@@ -111,6 +111,35 @@ void RunLoopFor(base::TimeDelta duration) {
namespace login_ui_test_utils {
+class SigninViewControllerTestUtil {
+ public:
+ static bool TryDismissSyncConfirmationDialog(Browser* browser) {
+#if defined(OS_CHROMEOS)
+ NOTREACHED();
+ return false;
+#else
+ SigninViewController* signin_view_controller =
+ browser->signin_view_controller();
+ DCHECK_NE(signin_view_controller, nullptr);
+ if (!signin_view_controller->ShowsModalDialog())
+ return false;
+ content::WebContents* dialog_web_contents =
+ signin_view_controller->GetModalDialogWebContentsForTesting();
+ DCHECK_NE(dialog_web_contents, nullptr);
+ std::string message;
+ std::string js =
+ "if (document.getElementById('confirmButton') == null) {"
+ " window.domAutomationController.send('NotFound');"
+ "} else {"
+ " document.getElementById('confirmButton').click();"
+ " window.domAutomationController.send('Ok');"
+ "}";
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(dialog_web_contents, js,
+ &message));
+ return message == "Ok";
+#endif
+ }
+};
void WaitUntilUIReady(Browser* browser) {
std::string message;
@@ -252,38 +281,10 @@ bool SignInWithUI(Browser* browser,
signin_metrics::Reason::REASON_SIGNIN_PRIMARY_ACCOUNT);
}
-bool TryDismissSyncConfirmationDialog(Browser* browser) {
-#if defined(OS_CHROMEOS)
- NOTREACHED();
- return false;
-#else
- SigninViewController* signin_view_controller =
- browser->signin_view_controller();
- DCHECK_NE(signin_view_controller, nullptr);
- SigninViewControllerDelegate* delegate = signin_view_controller->delegate();
- if (delegate == nullptr)
- return false;
- content::WebContents* dialog_web_contents =
- delegate->web_contents_for_testing();
- DCHECK_NE(dialog_web_contents, nullptr);
- std::string message;
- std::string js =
- "if (document.getElementById('confirmButton') == null) {"
- " window.domAutomationController.send('NotFound');"
- "} else {"
- " document.getElementById('confirmButton').click();"
- " window.domAutomationController.send('Ok');"
- "}";
- EXPECT_TRUE(content::ExecuteScriptAndExtractString(dialog_web_contents, js,
- &message));
- return message == "Ok";
-#endif
-}
-
bool DismissSyncConfirmationDialog(Browser* browser, base::TimeDelta timeout) {
const base::Time expire_time = base::Time::Now() + timeout;
while (base::Time::Now() <= expire_time) {
- if (TryDismissSyncConfirmationDialog(browser))
+ if (SigninViewControllerTestUtil::TryDismissSyncConfirmationDialog(browser))
return true;
RunLoopFor(base::TimeDelta::FromMilliseconds(1000));
}
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc
index 48e1c14c118..897f0c5e44d 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc
@@ -53,11 +53,6 @@ void SigninDiceInternalsHandler::HandleEnableSync(const base::ListValue* args) {
// OneClickSigninSyncStarter is suicidal (it will kill itself once it finishes
// enabling sync).
OneClickSigninSyncStarter::Callback callback;
- new OneClickSigninSyncStarter(
- profile_, browser, gaia_id, email, "" /* password */,
- "" /* refresh_token */, OneClickSigninSyncStarter::CURRENT_PROFILE,
- OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST,
- web_ui()->GetWebContents(),
- OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN,
- GURL("") /* current_url */, GURL("") /* continue_url */, callback);
+ new OneClickSigninSyncStarter(profile_, browser, gaia_id, email,
+ web_ui()->GetWebContents(), callback);
}
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 3b9bd1e0a88..f66590d9f42 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
@@ -630,7 +630,7 @@ void UserManagerScreenHandler::RemoveUserDialogLoadStatsCallback(
base::DictionaryValue return_value;
for (const auto& item : result) {
auto stat = base::MakeUnique<base::DictionaryValue>();
- stat->SetIntegerWithoutPathExpansion("count", item.count);
+ stat->SetKey("count", base::Value(item.count));
return_value.SetWithoutPathExpansion(item.category, std::move(stat));
}
if (result.size() == profiles::kProfileStatisticsCategories.size()) {
@@ -700,7 +700,7 @@ void UserManagerScreenHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("accountPickerReady", kDoNothingCallback);
web_ui()->RegisterMessageCallback("loginUIStateChanged", kDoNothingCallback);
web_ui()->RegisterMessageCallback("hideCaptivePortal", kDoNothingCallback);
- web_ui()->RegisterMessageCallback("getTouchViewState", kDoNothingCallback);
+ web_ui()->RegisterMessageCallback("getTabletModeState", kDoNothingCallback);
// Unused callbacks from display_manager.js
web_ui()->RegisterMessageCallback("showAddUser", kDoNothingCallback);
web_ui()->RegisterMessageCallback("updateCurrentScreen", kDoNothingCallback);
@@ -848,6 +848,13 @@ void UserManagerScreenHandler::GetLocalizedValues(
localized_strings->SetString("browseAsGuestAllProfilesLockedError",
l10n_util::GetStringUTF16(
IDS_USER_MANAGER_GO_GUEST_PROFILES_LOCKED_ERROR));
+
+ base::string16 prompt_message;
+ if (signin_util::IsForceSigninEnabled()) {
+ prompt_message = l10n_util::GetStringUTF16(IDS_USER_MANAGER_PROMPT_MESSAGE);
+ }
+
+ localized_strings->SetString("userManagerPromptMessage", prompt_message);
}
void UserManagerScreenHandler::SendUserList() {
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 55ec6aaad04..2cfedd5969e 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
@@ -3,6 +3,7 @@
// found in the LICENSE file.
#include "base/command_line.h"
+#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
index 94bc931cd86..dc95d8685bb 100644
--- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
@@ -12,10 +12,12 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/about_signin_internals_factory.h"
#include "chrome/browser/signin/gaia_cookie_manager_service_factory.h"
+#include "chrome/browser/ui/webui/signin/signin_dice_internals_handler.h"
#include "chrome/common/url_constants.h"
#include "components/grit/components_resources.h"
#include "components/signin/core/browser/about_signin_internals.h"
#include "components/signin/core/browser/gaia_cookie_manager_service.h"
+#include "components/signin/core/common/profile_management_switches.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -43,6 +45,12 @@ SignInInternalsUI::SignInInternalsUI(content::WebUI* web_ui)
AboutSigninInternalsFactory::GetForProfile(profile);
if (about_signin_internals)
about_signin_internals->AddSigninObserver(this);
+#if BUILDFLAG(ENABLE_DICE_SUPPORT)
+ if (signin::IsAccountConsistencyDiceEnabled()) {
+ web_ui->AddMessageHandler(
+ base::MakeUnique<SigninDiceInternalsHandler>(profile));
+ }
+#endif
}
}
diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc
index 299d94c1cc3..01dc4037d05 100644
--- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc
+++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc
@@ -10,32 +10,26 @@
#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "chrome/browser/permissions/chooser_context_base.h"
+#include "chrome/browser/permissions/permission_manager.h"
+#include "chrome/browser/permissions/permission_result.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/usb/usb_chooser_context_factory.h"
#include "chrome/common/pref_names.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/prefs/pref_service.h"
#include "extensions/browser/extension_registry.h"
+#include "extensions/common/constants.h"
+#include "url/origin.h"
namespace site_settings {
-const char kAppName[] = "appName";
-const char kAppId[] = "appId";
-const char kSetting[] = "setting";
-const char kOrigin[] = "origin";
-const char kDisplayName[] = "displayName";
-const char kOriginForFavicon[] = "originForFavicon";
-const char kExtensionProviderId[] = "extension";
-const char kPolicyProviderId[] = "policy";
-const char kSource[] = "source";
-const char kIncognito[] = "incognito";
-const char kEmbeddingOrigin[] = "embeddingOrigin";
-const char kPreferencesSource[] = "preference";
-const char kObject[] = "object";
-const char kObjectName[] = "objectName";
-
-const char kGroupTypeUsb[] = "usb-devices";
+constexpr char kAppName[] = "appName";
+constexpr char kAppId[] = "appId";
+constexpr char kObject[] = "object";
+constexpr char kObjectName[] = "objectName";
ChooserContextBase* GetUsbChooserContext(Profile* profile) {
return reinterpret_cast<ChooserContextBase*>(
@@ -59,6 +53,7 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = {
{CONTENT_SETTINGS_TYPE_COOKIES, "cookies"},
{CONTENT_SETTINGS_TYPE_IMAGES, "images"},
{CONTENT_SETTINGS_TYPE_JAVASCRIPT, "javascript"},
+ {CONTENT_SETTINGS_TYPE_SOUND, "sound"},
{CONTENT_SETTINGS_TYPE_PLUGINS, "plugins"},
{CONTENT_SETTINGS_TYPE_POPUPS, "popups"},
{CONTENT_SETTINGS_TYPE_GEOLOCATION, "location"},
@@ -78,6 +73,78 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = {
{CONTENT_SETTINGS_TYPE_ADS, "ads"},
};
+struct SiteSettingSourceStringMapping {
+ SiteSettingSource source;
+ const char* source_str;
+};
+
+const SiteSettingSourceStringMapping kSiteSettingSourceStringMapping[] = {
+ {SiteSettingSource::kDefault, "default"},
+ {SiteSettingSource::kEmbargo, "embargo"},
+ {SiteSettingSource::kExtension, "extension"},
+ {SiteSettingSource::kInsecureOrigin, "insecure-origin"},
+ {SiteSettingSource::kKillSwitch, "kill-switch"},
+ {SiteSettingSource::kPolicy, "policy"},
+ {SiteSettingSource::kPreference, "preference"},
+};
+static_assert(arraysize(kSiteSettingSourceStringMapping) ==
+ static_cast<int>(SiteSettingSource::kNumSources),
+ "kSiteSettingSourceStringMapping should have "
+ "SiteSettingSource::kNumSources elements");
+
+// 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. User-set per-origin setting.
+// 6. Embargo.
+// 7. User-set patterns.
+// 8. User-set global default for a ContentSettingsType.
+// 9. Chrome's built-in default.
+SiteSettingSource CalculateSiteSettingSource(
+ const content_settings::SettingInfo& info,
+ PermissionStatusSource permission_status_source) {
+ if (permission_status_source == PermissionStatusSource::KILL_SWITCH)
+ return SiteSettingSource::kKillSwitch; // Source #1.
+
+ if (permission_status_source == PermissionStatusSource::INSECURE_ORIGIN)
+ return SiteSettingSource::kInsecureOrigin; // Source #2.
+
+ if (info.source == content_settings::SETTING_SOURCE_POLICY ||
+ info.source == content_settings::SETTING_SOURCE_SUPERVISED) {
+ return SiteSettingSource::kPolicy; // Source #3.
+ }
+
+ if (info.source == content_settings::SETTING_SOURCE_EXTENSION)
+ return SiteSettingSource::kExtension; // Source #4.
+
+ DCHECK_NE(content_settings::SETTING_SOURCE_NONE, info.source);
+ if (info.source == content_settings::SETTING_SOURCE_USER) {
+ if (permission_status_source ==
+ PermissionStatusSource::SAFE_BROWSING_BLACKLIST ||
+ permission_status_source ==
+ PermissionStatusSource::MULTIPLE_DISMISSALS ||
+ permission_status_source == PermissionStatusSource::MULTIPLE_IGNORES) {
+ return SiteSettingSource::kEmbargo; // Source #6.
+ }
+ if (info.primary_pattern == ContentSettingsPattern::Wildcard() &&
+ info.secondary_pattern == ContentSettingsPattern::Wildcard()) {
+ return SiteSettingSource::kDefault; // Source #8, #9.
+ }
+ // Source #5, #7. When #5 is the source, |permission_status_source| won't
+ // be set to any of the source #6 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;
+ }
+
+ NOTREACHED();
+ return SiteSettingSource::kPreference;
+}
+
} // namespace
bool HasRegisteredGroupName(ContentSettingsType type) {
@@ -108,6 +175,10 @@ std::string ContentSettingsTypeToGroupName(ContentSettingsType type) {
return std::string();
}
+std::string SiteSettingSourceToString(const SiteSettingSource source) {
+ return kSiteSettingSourceStringMapping[static_cast<int>(source)].source_str;
+}
+
// Add an "Allow"-entry to the list of |exceptions| for a |url_pattern| from
// the web extent of a hosted |app|.
void AddExceptionForHostedApp(const std::string& url_pattern,
@@ -118,12 +189,12 @@ void AddExceptionForHostedApp(const std::string& url_pattern,
content_settings::ContentSettingToString(CONTENT_SETTING_ALLOW);
DCHECK(!setting_string.empty());
- exception->SetString(site_settings::kSetting, setting_string);
- exception->SetString(site_settings::kOrigin, url_pattern);
- exception->SetString(site_settings::kDisplayName, url_pattern);
- exception->SetString(site_settings::kEmbeddingOrigin, url_pattern);
- exception->SetString(site_settings::kSource, "HostedApp");
- exception->SetBoolean(site_settings::kIncognito, false);
+ exception->SetString(kSetting, setting_string);
+ exception->SetString(kOrigin, url_pattern);
+ exception->SetString(kDisplayName, url_pattern);
+ exception->SetString(kEmbeddingOrigin, url_pattern);
+ exception->SetString(kSource, "HostedApp");
+ exception->SetBoolean(kIncognito, false);
exception->SetString(kAppName, app.name());
exception->SetString(kAppId, app.id());
exceptions->Append(std::move(exception));
@@ -156,12 +227,10 @@ std::unique_ptr<base::DictionaryValue> GetExceptionForPage(
return exception;
}
-std::string GetDisplayName(
- const ContentSettingsPattern& pattern,
+std::string GetDisplayNameForExtension(
+ const GURL& url,
const extensions::ExtensionRegistry* extension_registry) {
- if (extension_registry &&
- pattern.GetScheme() == ContentSettingsPattern::SCHEME_CHROMEEXTENSION) {
- GURL url(pattern.ToString());
+ if (extension_registry && url.SchemeIs(extensions::kExtensionScheme)) {
// For the extension scheme, the pattern must be a valid URL.
DCHECK(url.is_valid());
const extensions::Extension* extension =
@@ -170,6 +239,38 @@ std::string GetDisplayName(
if (extension)
return extension->name();
}
+ return std::string();
+}
+
+// Takes |url| and converts it into an individual origin string or retrieves
+// name of the extension it belongs to.
+std::string GetDisplayNameForGURL(
+ const GURL& url,
+ const extensions::ExtensionRegistry* extension_registry) {
+ const url::Origin origin(url);
+ if (origin.unique())
+ return url.spec();
+
+ std::string display_name =
+ GetDisplayNameForExtension(url, extension_registry);
+ if (!display_name.empty())
+ return display_name;
+
+ // Note that using Serialize() here will chop off default port numbers and
+ // percent encode the origin.
+ return origin.Serialize();
+}
+
+// If the given |pattern| represents an individual origin or extension, retrieve
+// a string to display it as such. If not, return the pattern as a string.
+std::string GetDisplayNameForPattern(
+ const ContentSettingsPattern& pattern,
+ const extensions::ExtensionRegistry* extension_registry) {
+ const GURL url(pattern.ToString());
+ const std::string extension_display_name =
+ GetDisplayNameForExtension(url, extension_registry);
+ if (!extension_display_name.empty())
+ return extension_display_name;
return pattern.ToString();
}
@@ -190,7 +291,8 @@ void GetExceptionsFromHostContentSettingsMap(
// Don't add default settings.
if (i->primary_pattern == ContentSettingsPattern::Wildcard() &&
i->secondary_pattern == ContentSettingsPattern::Wildcard() &&
- i->source != kPreferencesSource) {
+ i->source !=
+ SiteSettingSourceToString(SiteSettingSource::kPreference)) {
continue;
}
@@ -222,7 +324,7 @@ void GetExceptionsFromHostContentSettingsMap(
const ContentSettingsPattern& primary_pattern = i->first.first;
const OnePatternSettings& one_settings = i->second;
const std::string display_name =
- GetDisplayName(primary_pattern, extension_registry);
+ GetDisplayNameForPattern(primary_pattern, extension_registry);
// The "parent" entry either has an identical primary and secondary pattern,
// or has a wildcard secondary. The two cases are indistinguishable in the
@@ -264,7 +366,8 @@ void GetExceptionsFromHostContentSettingsMap(
if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC ||
type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
auto& policy_exceptions = all_provider_exceptions
- [HostContentSettingsMap::GetProviderTypeFromSource(kPolicyProviderId)];
+ [HostContentSettingsMap::GetProviderTypeFromSource(
+ SiteSettingSourceToString(SiteSettingSource::kPolicy))];
DCHECK(policy_exceptions.empty());
GetPolicyAllowedUrls(type, &policy_exceptions, extension_registry, web_ui,
incognito);
@@ -285,9 +388,44 @@ void GetContentCategorySetting(
map->GetDefaultContentSetting(content_type, &provider));
DCHECK(!setting.empty());
- object->SetString(site_settings::kSetting, setting);
- if (provider != "default")
- object->SetString(site_settings::kSource, provider);
+ object->SetString(kSetting, setting);
+ if (provider != SiteSettingSourceToString(SiteSettingSource::kDefault))
+ object->SetString(kSource, provider);
+}
+
+ContentSetting GetContentSettingForOrigin(
+ Profile* profile,
+ const HostContentSettingsMap* map,
+ const GURL& origin,
+ ContentSettingsType content_type,
+ std::string* source_string,
+ const extensions::ExtensionRegistry* extension_registry,
+ std::string* display_name) {
+ // TODO(patricialor): In future, PermissionManager should know about all
+ // content settings, not just the permissions, plus all the possible sources,
+ // and the calls to HostContentSettingsMap should be removed.
+ content_settings::SettingInfo info;
+ std::unique_ptr<base::Value> value = map->GetWebsiteSetting(
+ origin, origin, content_type, std::string(), &info);
+
+ // Retrieve the content setting.
+ PermissionResult result(CONTENT_SETTING_DEFAULT,
+ PermissionStatusSource::UNSPECIFIED);
+ if (PermissionUtil::IsPermission(content_type)) {
+ result = PermissionManager::Get(profile)->GetPermissionStatus(
+ content_type, origin, origin);
+ } else {
+ DCHECK(value.get());
+ DCHECK_EQ(base::Value::Type::INTEGER, value->GetType());
+ result.content_setting =
+ content_settings::ValueToContentSetting(value.get());
+ }
+
+ // Retrieve the source of the content setting.
+ *source_string = SiteSettingSourceToString(
+ CalculateSiteSettingSource(info, result.source));
+ *display_name = GetDisplayNameForGURL(origin, extension_registry);
+ return result.content_setting;
}
void GetPolicyAllowedUrls(
@@ -326,10 +464,11 @@ void GetPolicyAllowedUrls(
patterns.begin(), patterns.end(), std::greater<ContentSettingsPattern>());
for (const ContentSettingsPattern& pattern : patterns) {
- std::string display_name = GetDisplayName(pattern, extension_registry);
+ std::string display_name =
+ GetDisplayNameForPattern(pattern, extension_registry);
exceptions->push_back(GetExceptionForPage(
pattern, ContentSettingsPattern(), display_name, CONTENT_SETTING_ALLOW,
- kPolicyProviderId, incognito));
+ SiteSettingSourceToString(SiteSettingSource::kPolicy), incognito));
}
}
@@ -356,12 +495,11 @@ std::unique_ptr<base::DictionaryValue> GetChooserExceptionForPage(
content_settings::ContentSettingToString(CONTENT_SETTING_DEFAULT);
DCHECK(!setting_string.empty());
- exception->SetString(site_settings::kSetting, setting_string);
- exception->SetString(site_settings::kOrigin, requesting_origin.spec());
- exception->SetString(site_settings::kDisplayName, requesting_origin.spec());
- exception->SetString(
- site_settings::kEmbeddingOrigin, embedding_origin.spec());
- exception->SetString(site_settings::kSource, provider_name);
+ exception->SetString(kSetting, setting_string);
+ exception->SetString(kOrigin, requesting_origin.spec());
+ exception->SetString(kDisplayName, requesting_origin.spec());
+ exception->SetString(kEmbeddingOrigin, embedding_origin.spec());
+ exception->SetString(kSource, provider_name);
exception->SetBoolean(kIncognito, incognito);
if (object) {
exception->SetString(kObjectName, name);
diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.h b/chromium/chrome/browser/ui/webui/site_settings_helper.h
index d9662f6e67c..f5ef7f82b50 100644
--- a/chromium/chrome/browser/ui/webui/site_settings_helper.h
+++ b/chromium/chrome/browser/ui/webui/site_settings_helper.h
@@ -41,30 +41,39 @@ typedef std::map<std::pair<ContentSettingsPattern, std::string>,
OnePatternSettings>
AllPatternsSettings;
-extern const char kSetting[];
-extern const char kOrigin[];
-extern const char kDisplayName[];
-extern const char kOriginForFavicon[];
-extern const char kExtensionProviderId[];
-extern const char kPolicyProviderId[];
-extern const char kSource[];
-extern const char kIncognito[];
-extern const char kEmbeddingOrigin[];
-extern const char kPreferencesSource[];
+constexpr char kDisplayName[] = "displayName";
+constexpr char kEmbeddingOrigin[] = "embeddingOrigin";
+constexpr char kIncognito[] = "incognito";
+constexpr char kOrigin[] = "origin";
+constexpr char kOriginForFavicon[] = "originForFavicon";
+constexpr char kSetting[] = "setting";
+constexpr char kSource[] = "source";
// Group types.
-extern const char kGroupTypeUsb[];
+constexpr char kGroupTypeUsb[] = "usb-devices";
+
+enum class SiteSettingSource {
+ kDefault,
+ kEmbargo,
+ kExtension,
+ kInsecureOrigin,
+ kKillSwitch,
+ kPolicy,
+ kPreference,
+ kNumSources,
+};
// Returns whether a group name has been registered for the given type.
bool HasRegisteredGroupName(ContentSettingsType type);
-// Gets a content settings type from the group name identifier.
+// Converts a ContentSettingsType to/from its group name identifier.
ContentSettingsType ContentSettingsTypeFromGroupName(const std::string& name);
-
-// Gets a string identifier for the group name.
std::string ContentSettingsTypeToGroupName(ContentSettingsType type);
-// Helper function to construct a dictonary for an exception.
+// Converts a SiteSettingSource to its string identifier.
+std::string SiteSettingSourceToString(const SiteSettingSource source);
+
+// Helper function to construct a dictionary for an exception.
std::unique_ptr<base::DictionaryValue> GetExceptionForPage(
const ContentSettingsPattern& pattern,
const ContentSettingsPattern& secondary_pattern,
@@ -73,7 +82,7 @@ std::unique_ptr<base::DictionaryValue> GetExceptionForPage(
const std::string& provider_name,
bool incognito);
-// Helper function to construct a dictonary for a hosted app exception.
+// Helper function to construct a dictionary for a hosted app exception.
void AddExceptionForHostedApp(const std::string& url_pattern,
const extensions::Extension& app, base::ListValue* exceptions);
@@ -97,6 +106,19 @@ void GetContentCategorySetting(
ContentSettingsType content_type,
base::DictionaryValue* object);
+// Retrieves the current setting for a given origin, category pair, the source
+// of that setting, and its display name, which will be different if it's an
+// extension. Note this is similar to GetContentCategorySetting() above but this
+// goes through the PermissionManager (preferred, see https://crbug.com/739241).
+ContentSetting GetContentSettingForOrigin(
+ Profile* profile,
+ const HostContentSettingsMap* map,
+ const GURL& origin,
+ ContentSettingsType content_type,
+ std::string* source_string,
+ const extensions::ExtensionRegistry* extension_registry,
+ std::string* display_name);
+
// Returns exceptions constructed from the policy-set allowed URLs
// for the content settings |type| mic or camera.
void GetPolicyAllowedUrls(
diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc b/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc
index a241f35e3e4..cb9a40f99e9 100644
--- a/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc
@@ -2,21 +2,24 @@
// 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/site_settings_helper.h"
+
#include "base/memory/ptr_util.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
-#include "chrome/browser/ui/webui/site_settings_helper.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
+#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/content_settings/core/test/content_settings_mock_provider.h"
#include "components/content_settings/core/test/content_settings_test_utils.h"
#include "content/public/test/test_browser_thread_bundle.h"
+#include "extensions/browser/extension_registry.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace site_settings {
namespace {
-const ContentSettingsType kContentType = CONTENT_SETTINGS_TYPE_GEOLOCATION;
+constexpr ContentSettingsType kContentType = CONTENT_SETTINGS_TYPE_GEOLOCATION;
}
class SiteSettingsHelperTest : public testing::Test {
@@ -24,18 +27,20 @@ class SiteSettingsHelperTest : public testing::Test {
void VerifySetting(const base::ListValue& exceptions,
int index,
const std::string& pattern,
- const std::string& setting) {
+ const std::string& pattern_display_name,
+ const ContentSetting setting) {
const base::DictionaryValue* dict;
exceptions.GetDictionary(index, &dict);
std::string actual_pattern;
dict->GetString("origin", &actual_pattern);
EXPECT_EQ(pattern, actual_pattern);
std::string actual_display_name;
- dict->GetString("displayName", &actual_display_name);
- EXPECT_EQ(pattern, actual_display_name);
+ dict->GetString(kDisplayName, &actual_display_name);
+ EXPECT_EQ(pattern_display_name, actual_display_name);
std::string actual_setting;
- dict->GetString("setting", &actual_setting);
- EXPECT_EQ(setting, actual_setting);
+ dict->GetString(kSetting, &actual_setting);
+ EXPECT_EQ(content_settings::ContentSettingToString(setting),
+ actual_setting);
}
void AddSetting(HostContentSettingsMap* map,
@@ -58,7 +63,7 @@ TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) {
base::ListValue exceptions;
// Check that the initial state of the map is empty.
- site_settings::GetExceptionsFromHostContentSettingsMap(
+ GetExceptionsFromHostContentSettingsMap(
map, kContentType, /*extension_registry=*/nullptr, /*web_ui=*/nullptr,
/*incognito=*/false, /*filter=*/nullptr, &exceptions);
EXPECT_EQ(0u, exceptions.GetSize());
@@ -66,9 +71,10 @@ TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) {
map->SetDefaultContentSetting(kContentType, CONTENT_SETTING_ALLOW);
// Add a policy exception.
+ std::string star_google_com = "http://[*.]google.com";
auto policy_provider = base::MakeUnique<content_settings::MockProvider>();
policy_provider->SetWebsiteSetting(
- ContentSettingsPattern::FromString("http://[*.]google.com"),
+ ContentSettingsPattern::FromString(star_google_com),
ContentSettingsPattern::Wildcard(), kContentType, "",
new base::Value(CONTENT_SETTING_BLOCK));
policy_provider->set_read_only(true);
@@ -76,14 +82,17 @@ TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) {
map, std::move(policy_provider), HostContentSettingsMap::POLICY_PROVIDER);
// Add user preferences.
- AddSetting(map, "http://*", CONTENT_SETTING_BLOCK);
- AddSetting(map, "http://maps.google.com", CONTENT_SETTING_BLOCK);
- AddSetting(map, "http://[*.]google.com", CONTENT_SETTING_ALLOW);
+ std::string http_star = "http://*";
+ std::string maps_google_com = "http://maps.google.com";
+ AddSetting(map, http_star, CONTENT_SETTING_BLOCK);
+ AddSetting(map, maps_google_com, CONTENT_SETTING_BLOCK);
+ AddSetting(map, star_google_com, CONTENT_SETTING_ALLOW);
// Add an extension exception.
+ std::string drive_google_com = "http://drive.google.com";
auto extension_provider = base::MakeUnique<content_settings::MockProvider>();
extension_provider->SetWebsiteSetting(
- ContentSettingsPattern::FromString("http://drive.google.com"),
+ ContentSettingsPattern::FromString(drive_google_com),
ContentSettingsPattern::Wildcard(), kContentType, "",
new base::Value(CONTENT_SETTING_ASK));
extension_provider->set_read_only(true);
@@ -92,7 +101,7 @@ TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) {
HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER);
exceptions.Clear();
- site_settings::GetExceptionsFromHostContentSettingsMap(
+ GetExceptionsFromHostContentSettingsMap(
map, kContentType, /*extension_registry=*/nullptr, /*web_ui=*/nullptr,
/*incognito=*/false, /*filter=*/nullptr, &exceptions);
@@ -103,13 +112,102 @@ TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) {
// The default content setting should not be returned.
int i = 0;
// From policy provider:
- VerifySetting(exceptions, i++, "http://[*.]google.com", "block");
+ VerifySetting(exceptions, i++, star_google_com, star_google_com,
+ CONTENT_SETTING_BLOCK);
// From extension provider:
- VerifySetting(exceptions, i++, "http://drive.google.com", "ask");
+ VerifySetting(exceptions, i++, drive_google_com, drive_google_com,
+ CONTENT_SETTING_ASK);
// From user preferences:
- VerifySetting(exceptions, i++, "http://maps.google.com", "block");
- VerifySetting(exceptions, i++, "http://[*.]google.com", "allow");
- VerifySetting(exceptions, i++, "http://*", "block");
+ VerifySetting(exceptions, i++, maps_google_com, maps_google_com,
+ CONTENT_SETTING_BLOCK);
+ VerifySetting(exceptions, i++, star_google_com, star_google_com,
+ CONTENT_SETTING_ALLOW);
+ VerifySetting(exceptions, i++, http_star, "http://*", CONTENT_SETTING_BLOCK);
+}
+
+// Tests the following content setting sources: Chrome default, user-set global
+// default, user-set pattern, user-set origin setting, extension, and policy.
+TEST_F(SiteSettingsHelperTest, ContentSettingSource) {
+ TestingProfile profile;
+ HostContentSettingsMap* map =
+ HostContentSettingsMapFactory::GetForProfile(&profile);
+
+ GURL origin("https://www.example.com/");
+ auto* extension_registry = extensions::ExtensionRegistry::Get(&profile);
+ std::string source;
+ std::string display_name;
+ ContentSetting content_setting;
+
+ // Built in Chrome default.
+ content_setting =
+ GetContentSettingForOrigin(&profile, map, origin, kContentType, &source,
+ extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kDefault), source);
+ EXPECT_EQ(CONTENT_SETTING_ASK, content_setting);
+
+ // User-set global default.
+ map->SetDefaultContentSetting(kContentType, CONTENT_SETTING_ALLOW);
+ content_setting =
+ GetContentSettingForOrigin(&profile, map, origin, kContentType, &source,
+ extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kDefault), source);
+ EXPECT_EQ(CONTENT_SETTING_ALLOW, content_setting);
+
+ // User-set pattern.
+ AddSetting(map, "https://*", CONTENT_SETTING_BLOCK);
+ content_setting =
+ GetContentSettingForOrigin(&profile, map, origin, kContentType, &source,
+ extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kPreference), source);
+ EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting);
+
+ // User-set origin setting.
+ map->SetContentSettingDefaultScope(origin, origin, kContentType,
+ std::string(), CONTENT_SETTING_ALLOW);
+ content_setting =
+ GetContentSettingForOrigin(&profile, map, origin, kContentType, &source,
+ extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kPreference), source);
+ EXPECT_EQ(CONTENT_SETTING_ALLOW, content_setting);
+
+ // Extension.
+ auto extension_provider = base::MakeUnique<content_settings::MockProvider>();
+ extension_provider->SetWebsiteSetting(ContentSettingsPattern::FromURL(origin),
+ ContentSettingsPattern::FromURL(origin),
+ kContentType, "",
+ new base::Value(CONTENT_SETTING_BLOCK));
+ extension_provider->set_read_only(true);
+ content_settings::TestUtils::OverrideProvider(
+ map, std::move(extension_provider),
+ HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER);
+ content_setting =
+ GetContentSettingForOrigin(&profile, map, origin, kContentType, &source,
+ extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kExtension), source);
+ EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting);
+
+ // Enterprise policy.
+ auto policy_provider = base::MakeUnique<content_settings::MockProvider>();
+ policy_provider->SetWebsiteSetting(ContentSettingsPattern::FromURL(origin),
+ ContentSettingsPattern::FromURL(origin),
+ kContentType, "",
+ new base::Value(CONTENT_SETTING_ALLOW));
+ policy_provider->set_read_only(true);
+ content_settings::TestUtils::OverrideProvider(
+ map, std::move(policy_provider), HostContentSettingsMap::POLICY_PROVIDER);
+ content_setting =
+ GetContentSettingForOrigin(&profile, map, origin, kContentType, &source,
+ extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kPolicy), source);
+ EXPECT_EQ(CONTENT_SETTING_ALLOW, content_setting);
+
+ // Insecure origins.
+ content_setting = GetContentSettingForOrigin(
+ &profile, map, GURL("http://www.insecure_http_site.com/"), kContentType,
+ &source, extension_registry, &display_name);
+ EXPECT_EQ(SiteSettingSourceToString(SiteSettingSource::kInsecureOrigin),
+ source);
+ EXPECT_EQ(CONTENT_SETTING_BLOCK, content_setting);
}
} // namespace site_settings
diff --git a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc
index 96cd84ae0dc..bf378f24bb7 100644
--- a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.cc
@@ -14,6 +14,7 @@
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/time_formatting.h"
+#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
@@ -23,29 +24,36 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/android/chrome_feature_list.h"
+#include "chrome/browser/android/ntp/android_content_suggestions_notifier.h"
#include "chrome/browser/ntp_snippets/content_suggestions_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
+#include "chrome/common/pref_names.h"
#include "components/ntp_snippets/category.h"
#include "components/ntp_snippets/category_info.h"
#include "components/ntp_snippets/category_rankers/category_ranker.h"
+#include "components/ntp_snippets/contextual/contextual_content_suggestions_service.h"
#include "components/ntp_snippets/features.h"
#include "components/ntp_snippets/pref_names.h"
#include "components/ntp_snippets/remote/remote_suggestions_fetcher.h"
#include "components/ntp_snippets/remote/remote_suggestions_provider.h"
+#include "components/ntp_snippets/remote/remote_suggestions_provider_impl.h"
#include "components/ntp_snippets/switches.h"
#include "components/offline_pages/core/offline_page_feature.h"
#include "components/prefs/pref_service.h"
#include "components/variations/variations_associated_data.h"
#include "content/public/browser/web_ui.h"
+#include "url/gurl.h"
-using ntp_snippets::ContentSuggestion;
using ntp_snippets::Category;
using ntp_snippets::CategoryInfo;
using ntp_snippets::CategoryStatus;
+using ntp_snippets::ContentSuggestion;
using ntp_snippets::KnownCategories;
+using ntp_snippets::RemoteSuggestion;
using ntp_snippets::RemoteSuggestionsProvider;
using ntp_snippets::UserClassifier;
@@ -149,14 +157,27 @@ std::set<variations::VariationID> SnippetsExperiments() {
return result;
}
+std::string TimeToJSONTimeString(const base::Time time) {
+ base::Time::Exploded exploded;
+ time.UTCExplode(&exploded);
+ return base::StringPrintf(
+ "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", exploded.year, exploded.month,
+ exploded.day_of_month, exploded.hour, exploded.minute, exploded.second,
+ exploded.millisecond);
+}
+
} // namespace
SnippetsInternalsMessageHandler::SnippetsInternalsMessageHandler(
ntp_snippets::ContentSuggestionsService* content_suggestions_service,
+ ntp_snippets::ContextualContentSuggestionsService*
+ contextual_content_suggestions_service,
PrefService* pref_service)
: content_suggestions_service_observer_(this),
dom_loaded_(false),
content_suggestions_service_(content_suggestions_service),
+ contextual_content_suggestions_service_(
+ contextual_content_suggestions_service),
remote_suggestions_provider_(
content_suggestions_service_
->remote_suggestions_provider_for_debugging()),
@@ -173,7 +194,7 @@ void SnippetsInternalsMessageHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"clearClassification",
- base::Bind(&SnippetsInternalsMessageHandler::ClearClassification,
+ base::Bind(&SnippetsInternalsMessageHandler::HandleClearClassification,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
@@ -187,9 +208,27 @@ void SnippetsInternalsMessageHandler::RegisterMessages() {
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "fetchRemoteSuggestionsInTheBackground",
+ "fetchRemoteSuggestionsInTheBackgroundIn2Seconds",
base::Bind(&SnippetsInternalsMessageHandler::
- FetchRemoteSuggestionsInTheBackground,
+ HandleFetchRemoteSuggestionsInTheBackgroundIn2Seconds,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "fetchContextualSuggestions",
+ base::Bind(
+ &SnippetsInternalsMessageHandler::HandleFetchContextualSuggestions,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "resetNotificationsState",
+ base::Bind(
+ &SnippetsInternalsMessageHandler::HandleResetNotificationsState,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "pushDummySuggestionIn10Seconds",
+ base::Bind(&SnippetsInternalsMessageHandler::
+ HandlePushDummySuggestionIn10Seconds,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
@@ -333,7 +372,7 @@ void SnippetsInternalsMessageHandler::HandleToggleDismissedSuggestions(
}
}
-void SnippetsInternalsMessageHandler::ClearClassification(
+void SnippetsInternalsMessageHandler::HandleClearClassification(
const base::ListValue* args) {
DCHECK_EQ(0u, args->GetSize());
content_suggestions_service_->user_classifier()
@@ -341,11 +380,63 @@ void SnippetsInternalsMessageHandler::ClearClassification(
SendClassification();
}
-void SnippetsInternalsMessageHandler::FetchRemoteSuggestionsInTheBackground(
- const base::ListValue* args) {
+void SnippetsInternalsMessageHandler::
+ HandleFetchRemoteSuggestionsInTheBackgroundIn2Seconds(
+ const base::ListValue* args) {
DCHECK_EQ(0u, args->GetSize());
- remote_suggestions_provider_->RefetchInTheBackground(
- RemoteSuggestionsProvider::FetchStatusCallback());
+ suggestion_push_timer_.Start(
+ FROM_HERE, base::TimeDelta::FromSeconds(2),
+ base::Bind(&SnippetsInternalsMessageHandler::
+ FetchRemoteSuggestionsInTheBackground,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void SnippetsInternalsMessageHandler::HandleFetchContextualSuggestions(
+ const base::ListValue* args) {
+ DCHECK_EQ(1u, args->GetSize());
+ std::string url_str;
+ args->GetString(0, &url_str);
+ contextual_content_suggestions_service_->FetchContextualSuggestions(
+ GURL(url_str),
+ base::BindOnce(
+ &SnippetsInternalsMessageHandler::OnContextualSuggestionsFetched,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void SnippetsInternalsMessageHandler::HandleResetNotificationsState(
+ const base::ListValue* args) {
+ pref_service_->SetInteger(
+ prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
+ pref_service_->SetInteger(prefs::kContentSuggestionsNotificationsSentCount,
+ 0);
+ pref_service_->SetInteger(prefs::kContentSuggestionsNotificationsSentDay, 0);
+ AndroidContentSuggestionsNotifier().HideAllNotifications(
+ ContentSuggestionsNotificationAction::CONTENT_SUGGESTIONS_HIDE_FRONTMOST);
+}
+
+void SnippetsInternalsMessageHandler::OnContextualSuggestionsFetched(
+ ntp_snippets::Status status,
+ const GURL& url,
+ std::vector<ntp_snippets::ContentSuggestion> suggestions) {
+ // Ids start in a range distinct from those created by SendContentSuggestions.
+ int id = 10000;
+ auto suggestions_list = base::MakeUnique<base::ListValue>();
+ for (const ContentSuggestion& suggestion : suggestions) {
+ suggestions_list->Append(PrepareSuggestion(suggestion, id++));
+ }
+ base::DictionaryValue result;
+ result.Set("list", std::move(suggestions_list));
+ web_ui()->CallJavascriptFunctionUnsafe(
+ "chrome.SnippetsInternals.receiveContextualSuggestions", result,
+ base::Value(static_cast<int>(status.code)));
+}
+
+void SnippetsInternalsMessageHandler::HandlePushDummySuggestionIn10Seconds(
+ const base::ListValue* args) {
+ suggestion_push_timer_.Start(
+ FROM_HERE, base::TimeDelta::FromSeconds(10),
+ base::Bind(&SnippetsInternalsMessageHandler::PushDummySuggestion,
+ weak_ptr_factory_.GetWeakPtr()));
}
void SnippetsInternalsMessageHandler::SendAllContent() {
@@ -508,6 +599,53 @@ void SnippetsInternalsMessageHandler::SendString(const std::string& name,
"chrome.SnippetsInternals.receiveProperty", string_name, string_value);
}
+void SnippetsInternalsMessageHandler::FetchRemoteSuggestionsInTheBackground() {
+ remote_suggestions_provider_->RefetchInTheBackground(
+ RemoteSuggestionsProvider::FetchStatusCallback());
+}
+
+void SnippetsInternalsMessageHandler::PushDummySuggestion() {
+ std::string json = R"(
+ {"categories" : [{
+ "id": 1,
+ "localizedTitle": "section title",
+ "suggestions" : [{
+ "ids" : ["http://url.com"],
+ "title" : "Pushed Dummy Title %s",
+ "snippet" : "Pushed Dummy Snippet",
+ "fullPageUrl" : "http://url.com",
+ "creationTime" : "%s",
+ "expirationTime" : "%s",
+ "attribution" : "Pushed Dummy Publisher",
+ "imageUrl" : "https://www.google.com/favicon.ico",
+ "notificationInfo": {
+ "shouldNotify": true,
+ "deadline": "2100-01-01T00:00:01.000Z"
+ }
+ }]
+ }]}
+ )";
+
+ const base::Time now = base::Time::Now();
+ json = base::StringPrintf(
+ json.c_str(), base::UTF16ToUTF8(base::TimeFormatTimeOfDay(now)).c_str(),
+ TimeToJSONTimeString(now).c_str(),
+ TimeToJSONTimeString(now + base::TimeDelta::FromMinutes(60)).c_str());
+
+ gcm::IncomingMessage message;
+ message.data["payload"] = json;
+
+ RemoteSuggestionsProvider* provider =
+ content_suggestions_service_->remote_suggestions_provider_for_debugging();
+ DCHECK(provider);
+ ntp_snippets::BreakingNewsListener* listener =
+ static_cast<ntp_snippets::RemoteSuggestionsProviderImpl*>(provider)
+ ->breaking_news_listener_for_debugging();
+ DCHECK(listener);
+ static_cast<ntp_snippets::BreakingNewsGCMAppHandler*>(listener)->OnMessage(
+ "com.google.breakingnews.gcm", message);
+}
+
void SnippetsInternalsMessageHandler::OnDismissedSuggestionsLoaded(
Category category,
std::vector<ContentSuggestion> dismissed_suggestions) {
diff --git a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h
index 965e2d42f90..c86459a4463 100644
--- a/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/snippets_internals_message_handler.h
@@ -12,10 +12,13 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observer.h"
+#include "base/timer/timer.h"
#include "components/ntp_snippets/category.h"
#include "components/ntp_snippets/category_status.h"
+#include "components/ntp_snippets/content_suggestion.h"
#include "components/ntp_snippets/content_suggestions_service.h"
#include "components/ntp_snippets/remote/remote_suggestions_provider.h"
+#include "components/ntp_snippets/status.h"
#include "content/public/browser/web_ui_message_handler.h"
namespace base {
@@ -24,6 +27,7 @@ class ListValue;
namespace ntp_snippets {
class ContentSuggestionsService;
+class ContextualContentSuggestionsService;
} // namespace ntp_snippets
class PrefService;
@@ -35,6 +39,8 @@ class SnippetsInternalsMessageHandler
public:
SnippetsInternalsMessageHandler(
ntp_snippets::ContentSuggestionsService* content_suggestions_service,
+ ntp_snippets::ContextualContentSuggestionsService*
+ contextual_content_suggestions_service,
PrefService* pref_service);
~SnippetsInternalsMessageHandler() override;
@@ -59,8 +65,16 @@ class SnippetsInternalsMessageHandler
void HandleClearCachedSuggestions(const base::ListValue* args);
void HandleClearDismissedSuggestions(const base::ListValue* args);
void HandleToggleDismissedSuggestions(const base::ListValue* args);
- void ClearClassification(const base::ListValue* args);
- void FetchRemoteSuggestionsInTheBackground(const base::ListValue* args);
+ void HandleClearClassification(const base::ListValue* args);
+ void HandleFetchRemoteSuggestionsInTheBackgroundIn2Seconds(
+ const base::ListValue* args);
+ void HandleFetchContextualSuggestions(const base::ListValue* args);
+ void HandleResetNotificationsState(const base::ListValue* args);
+ void OnContextualSuggestionsFetched(
+ ntp_snippets::Status status_code,
+ const GURL& url,
+ std::vector<ntp_snippets::ContentSuggestion> suggestions);
+ void HandlePushDummySuggestionIn10Seconds(const base::ListValue* args);
void SendAllContent();
void SendClassification();
@@ -70,6 +84,9 @@ class SnippetsInternalsMessageHandler
void SendBoolean(const std::string& name, bool value);
void SendString(const std::string& name, const std::string& value);
+ void FetchRemoteSuggestionsInTheBackground();
+ void PushDummySuggestion();
+
void OnDismissedSuggestionsLoaded(
ntp_snippets::Category category,
std::vector<ntp_snippets::ContentSuggestion> dismissed_suggestions);
@@ -82,6 +99,8 @@ class SnippetsInternalsMessageHandler
bool dom_loaded_;
ntp_snippets::ContentSuggestionsService* content_suggestions_service_;
+ ntp_snippets::ContextualContentSuggestionsService*
+ contextual_content_suggestions_service_;
ntp_snippets::RemoteSuggestionsProvider* remote_suggestions_provider_;
PrefService* pref_service_;
@@ -94,6 +113,9 @@ class SnippetsInternalsMessageHandler
ntp_snippets::Category::CompareByID>
dismissed_suggestions_;
+ base::OneShotTimer suggestion_push_timer_;
+ base::OneShotTimer suggestions_fetch_timer_;
+
base::WeakPtrFactory<SnippetsInternalsMessageHandler> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(SnippetsInternalsMessageHandler);
diff --git a/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc b/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc
index a8f475d61ff..35e79554383 100644
--- a/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/snippets_internals_ui.cc
@@ -5,7 +5,9 @@
#include "chrome/browser/ui/webui/snippets_internals_ui.h"
#include "base/memory/ptr_util.h"
+#include "build/build_config.h"
#include "chrome/browser/ntp_snippets/content_suggestions_service_factory.h"
+#include "chrome/browser/ntp_snippets/contextual_content_suggestions_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/snippets_internals_message_handler.h"
#include "chrome/common/url_constants.h"
@@ -13,12 +15,24 @@
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#if defined(OS_ANDROID)
+#include "chrome/browser/android/chrome_feature_list.h"
+#endif
+
namespace {
content::WebUIDataSource* CreateSnippetsInternalsHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUISnippetsInternalsHost);
+#if defined(OS_ANDROID)
+ source->AddBoolean("contextualSuggestionsEnabled",
+ base::FeatureList::IsEnabled(
+ chrome::android::kContextualSuggestionsCarousel));
+#else
+ source->AddBoolean("contextualSuggestionsEnabled", false);
+#endif
+ source->SetJsonPath("strings.js");
source->AddResourcePath("snippets_internals.js", IDR_SNIPPETS_INTERNALS_JS);
source->AddResourcePath("snippets_internals.css", IDR_SNIPPETS_INTERNALS_CSS);
source->SetDefaultResource(IDR_SNIPPETS_INTERNALS_HTML);
@@ -35,6 +49,8 @@ SnippetsInternalsUI::SnippetsInternalsUI(content::WebUI* web_ui)
web_ui->AddMessageHandler(base::MakeUnique<SnippetsInternalsMessageHandler>(
ContentSuggestionsServiceFactory::GetInstance()->GetForProfile(profile),
+ ContextualContentSuggestionsServiceFactory::GetInstance()->GetForProfile(
+ profile),
profile->GetPrefs()));
}
diff --git a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc
index 97763c58b0e..a2879cb150c 100644
--- a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc
@@ -42,6 +42,8 @@ content::WebUIDataSource* CreateSyncInternalsHTMLSource() {
IDR_SYNC_DRIVER_SYNC_INTERNALS_SEARCH_JS);
source->AddResourcePath(syncer::sync_ui_util::kUserEventsJS,
IDR_SYNC_DRIVER_SYNC_INTERNALS_USER_EVENTS_JS);
+ source->AddResourcePath(syncer::sync_ui_util::kTrafficLogJS,
+ IDR_SYNC_DRIVER_SYNC_INTERNALS_TRAFFIC_LOG_JS);
source->SetDefaultResource(IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_HTML);
return source;
}
diff --git a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc
index d2f80d1f756..2cdebf6de72 100644
--- a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc
+++ b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc
@@ -210,7 +210,7 @@ void TranslateInternalsHandler::SendPrefsToJs() {
for (const char* key : keys) {
const PrefService::Preference* pref = prefs->FindPreference(key);
if (pref)
- dict.Set(key, base::MakeUnique<base::Value>(*pref->GetValue()));
+ dict.SetKey(key, pref->GetValue()->Clone());
}
SendMessageToJs("prefsUpdated", dict);
diff --git a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn
index 1774bc05f83..4d0059e3ae2 100644
--- a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn
@@ -13,7 +13,4 @@ mojom("mojo_bindings") {
"//url/mojo:url_mojom_gurl",
"//url/mojo:url_mojom_origin",
]
-
- # TODO(crbug.com/714018): Convert the implementation to use OnceCallback.
- use_once_callback = false
}
diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc
index 4b711599245..b62096267ee 100644
--- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc
@@ -23,7 +23,7 @@ class TestUsbDevice : public device::UsbDevice {
const GURL& landing_page);
// device::UsbDevice overrides:
- void Open(const OpenCallback& callback) override;
+ void Open(OpenCallback callback) override;
private:
~TestUsbDevice() override;
@@ -47,8 +47,8 @@ TestUsbDevice::TestUsbDevice(const std::string& name,
webusb_landing_page_ = landing_page;
}
-void TestUsbDevice::Open(const OpenCallback& callback) {
- callback.Run(nullptr);
+void TestUsbDevice::Open(OpenCallback callback) {
+ std::move(callback).Run(nullptr);
}
TestUsbDevice::~TestUsbDevice() {}
@@ -65,34 +65,33 @@ void UsbInternalsPageHandler::AddDeviceForTesting(
const std::string& name,
const std::string& serial_number,
const std::string& landing_page,
- const AddDeviceForTestingCallback& callback) {
+ AddDeviceForTestingCallback callback) {
device::UsbService* service = device::DeviceClient::Get()->GetUsbService();
if (service) {
GURL landing_page_url(landing_page);
if (!landing_page_url.is_valid()) {
- callback.Run(false, "Landing page URL is invalid.");
+ std::move(callback).Run(false, "Landing page URL is invalid.");
return;
}
service->AddDeviceForTesting(
new TestUsbDevice(name, serial_number, landing_page_url));
- callback.Run(true, "Added.");
+ std::move(callback).Run(true, "Added.");
} else {
- callback.Run(false, "USB service unavailable.");
+ std::move(callback).Run(false, "USB service unavailable.");
}
}
void UsbInternalsPageHandler::RemoveDeviceForTesting(
const std::string& guid,
- const RemoveDeviceForTestingCallback& callback) {
+ RemoveDeviceForTestingCallback callback) {
device::UsbService* service = device::DeviceClient::Get()->GetUsbService();
if (service)
service->RemoveDeviceForTesting(guid);
- callback.Run();
+ std::move(callback).Run();
}
-void UsbInternalsPageHandler::GetTestDevices(
- const GetTestDevicesCallback& callback) {
+void UsbInternalsPageHandler::GetTestDevices(GetTestDevicesCallback callback) {
std::vector<scoped_refptr<device::UsbDevice>> devices;
device::UsbService* service = device::DeviceClient::Get()->GetUsbService();
if (service)
@@ -107,5 +106,5 @@ void UsbInternalsPageHandler::GetTestDevices(
device_info->landing_page = device->webusb_landing_page();
result.push_back(std::move(device_info));
}
- callback.Run(std::move(result));
+ std::move(callback).Run(std::move(result));
}
diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h
index 6ae1c8aaf16..e3952f99cf1 100644
--- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h
+++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.h
@@ -18,15 +18,13 @@ class UsbInternalsPageHandler : public mojom::UsbInternalsPageHandler,
~UsbInternalsPageHandler() override;
// mojom::UsbInternalsPageHandler overrides:
- void AddDeviceForTesting(
- const std::string& name,
- const std::string& serial_number,
- const std::string& landing_page,
- const AddDeviceForTestingCallback& callback) override;
- void RemoveDeviceForTesting(
- const std::string& guid,
- const RemoveDeviceForTestingCallback& callback) override;
- void GetTestDevices(const GetTestDevicesCallback& callback) override;
+ void AddDeviceForTesting(const std::string& name,
+ const std::string& serial_number,
+ const std::string& landing_page,
+ AddDeviceForTestingCallback callback) override;
+ void RemoveDeviceForTesting(const std::string& guid,
+ RemoveDeviceForTestingCallback callback) override;
+ void GetTestDevices(GetTestDevicesCallback callback) override;
private:
mojo::Binding<mojom::UsbInternalsPageHandler> binding_;
diff --git a/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc b/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc
index 0c700a9afab..35561e43ab7 100644
--- a/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc
+++ b/chromium/chrome/browser/ui/webui/web_ui_test_handler.cc
@@ -7,9 +7,11 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop/message_loop.h"
+#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/render_messages.h"
+#include "chrome/common/web_ui_tester.mojom.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_types.h"
@@ -17,6 +19,7 @@
#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/common/associated_interface_provider.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -33,8 +36,10 @@ WebUITestHandler::WebUITestHandler()
void WebUITestHandler::PreloadJavaScript(const base::string16& js_text,
RenderViewHost* preload_host) {
DCHECK(preload_host);
- preload_host->Send(new ChromeViewMsg_WebUIJavaScript(
- preload_host->GetRoutingID(), js_text));
+ chrome::mojom::WebUITesterAssociatedPtr web_ui_tester;
+ preload_host->GetMainFrame()->GetRemoteAssociatedInterfaces()->GetInterface(
+ &web_ui_tester);
+ web_ui_tester->ExecuteWebUIJavaScript(js_text);
}
void WebUITestHandler::RunJavaScript(const base::string16& js_text) {
@@ -62,7 +67,7 @@ void WebUITestHandler::HandleTestResult(const base::ListValue* test_result) {
// Quit the message loop if |is_waiting_| so waiting process can get result or
// error. To ensure this gets done, do this before ASSERT* calls.
if (is_waiting_)
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
SCOPED_TRACE("WebUITestHandler::HandleTestResult");
@@ -82,7 +87,7 @@ void WebUITestHandler::JavaScriptComplete(const base::Value* result) {
// Quit the message loop if |is_waiting_| so waiting process can get result or
// error. To ensure this gets done, do this before ASSERT* calls.
if (is_waiting_)
- base::MessageLoopForUI::current()->QuitWhenIdle();
+ base::RunLoop::QuitCurrentWhenIdleDeprecated();
SCOPED_TRACE("WebUITestHandler::JavaScriptComplete");
diff --git a/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc b/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc
index 636e059a741..9b7dc79a29d 100644
--- a/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/webui_webview_browsertest.cc
@@ -158,14 +158,26 @@ IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, ExecuteScriptCodeFromFile) {
base::Value(GetTestUrl("empty.html").spec())));
}
-IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, AddContentScript) {
+// TODO(crbug.com/751907) Flaky on CrOS trybots.
+#if defined(OS_CHROMEOS)
+#define MAYBE_AddContentScript DISABLED_AddContentScript
+#else
+#define MAYBE_AddContentScript AddContentScript
+#endif
+IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, MAYBE_AddContentScript) {
ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL());
ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest(
"testAddContentScript", base::Value(GetTestUrl("empty.html").spec())));
}
-IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, AddMultiContentScripts) {
+// TODO(crbug.com/751907) Flaky on CrOS trybots.
+#if defined(OS_CHROMEOS)
+#define MAYBE_AddMultiContentScripts DISABLED_AddMultiContentScripts
+#else
+#define MAYBE_AddMultiContentScripts AddMultiContentScripts
+#endif
+IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, MAYBE_AddMultiContentScripts) {
ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL());
ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest(
@@ -173,9 +185,17 @@ IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, AddMultiContentScripts) {
base::Value(GetTestUrl("empty.html").spec())));
}
+// TODO(crbug.com/751907) Flaky on CrOS trybots.
+#if defined(OS_CHROMEOS)
+#define MAYBE_AddContentScriptWithSameNameShouldOverwriteTheExistingOne \
+ DISABLED_AddContentScriptWithSameNameShouldOverwriteTheExistingOne
+#else
+#define MAYBE_AddContentScriptWithSameNameShouldOverwriteTheExistingOne \
+ AddContentScriptWithSameNameShouldOverwriteTheExistingOne
+#endif
IN_PROC_BROWSER_TEST_F(
WebUIWebViewBrowserTest,
- AddContentScriptWithSameNameShouldOverwriteTheExistingOne) {
+ MAYBE_AddContentScriptWithSameNameShouldOverwriteTheExistingOne) {
ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL());
ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest(
@@ -193,7 +213,14 @@ IN_PROC_BROWSER_TEST_F(
base::Value(GetTestUrl("empty.html").spec())));
}
-IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, AddAndRemoveContentScripts) {
+// TODO(crbug.com/751907) Flaky on CrOS trybots.
+#if defined(OS_CHROMEOS)
+#define MAYBE_AddAndRemoveContentScripts DISABLED_AddAndRemoveContentScripts
+#else
+#define MAYBE_AddAndRemoveContentScripts AddAndRemoveContentScripts
+#endif
+IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest,
+ MAYBE_AddAndRemoveContentScripts) {
ui_test_utils::NavigateToURL(browser(), GetWebViewEnabledWebUIURL());
ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest(
@@ -247,9 +274,12 @@ IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, AddContentScriptWithCode) {
}
#if defined(OS_CHROMEOS)
+// TODO(crbug.com/662673) Flaky on CrOS trybots.
+#define MAYBE_AddContentScriptIncognito DISABLED_AddContentScriptIncognito
// Right now we only have incognito WebUI on CrOS, but this should
// theoretically work for all platforms.
-IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest, AddContentScriptIncognito) {
+IN_PROC_BROWSER_TEST_F(WebUIWebViewBrowserTest,
+ MAYBE_AddContentScriptIncognito) {
Browser* incognito_browser =
OpenURLOffTheRecord(browser()->profile(), GetWebViewEnabledWebUIURL());
diff --git a/chromium/chrome/browser/ui/webui/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome_handler.cc
index 82b10df1e90..db6e1a8245f 100644
--- a/chromium/chrome/browser/ui/webui/welcome_handler.cc
+++ b/chromium/chrome/browser/ui/webui/welcome_handler.cc
@@ -67,7 +67,7 @@ void WelcomeHandler::HandleUserDecline(const base::ListValue* args) {
// attempted to sign in.
result_ = (result_ == WelcomeResult::ATTEMPTED)
? WelcomeResult::ATTEMPTED_DECLINED
- : result_ = WelcomeResult::DECLINED;
+ : WelcomeResult::DECLINED;
GoToNewTabPage();
}
@@ -84,6 +84,7 @@ void WelcomeHandler::RegisterMessages() {
void WelcomeHandler::GoToNewTabPage() {
chrome::NavigateParams params(GetBrowser(), GURL(chrome::kChromeUINewTabURL),
ui::PageTransition::PAGE_TRANSITION_LINK);
+ params.source_contents = web_ui()->GetWebContents();
chrome::Navigate(&params);
}
diff --git a/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc b/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc
index eab42d6f7f9..bb74e7d667f 100644
--- a/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc
+++ b/chromium/chrome/browser/ui/webui/welcome_win10_handler.cc
@@ -22,10 +22,13 @@ namespace {
void RecordDefaultBrowserResult(
const std::string& histogram_suffix,
shell_integration::DefaultWebClientState default_browser_state) {
+ // Consider the page successful if this or any other side-by-side install of
+ // Chrome was chosen as the user's default browser.
base::UmaHistogramBoolean(
base::StringPrintf("Welcome.Win10.DefaultPromptResult_%s",
histogram_suffix.c_str()),
- default_browser_state == shell_integration::IS_DEFAULT);
+ (default_browser_state == shell_integration::IS_DEFAULT ||
+ default_browser_state == shell_integration::OTHER_MODE_IS_DEFAULT));
}
void RecordPinnedResult(const std::string& histogram_suffix,
diff --git a/chromium/chrome/browser/vr/BUILD.gn b/chromium/chrome/browser/vr/BUILD.gn
index 88bd84ce403..11480b87a22 100644
--- a/chromium/chrome/browser/vr/BUILD.gn
+++ b/chromium/chrome/browser/vr/BUILD.gn
@@ -18,12 +18,18 @@ static_library("vr_common") {
"animation_player.h",
"color_scheme.cc",
"color_scheme.h",
+ "databinding/binding.h",
+ "databinding/binding_base.cc",
+ "databinding/binding_base.h",
"elements/button.cc",
"elements/button.h",
"elements/button_texture.cc",
"elements/button_texture.h",
"elements/close_button_texture.cc",
"elements/close_button_texture.h",
+ "elements/content_element.cc",
+ "elements/content_element.h",
+ "elements/draw_phase.h",
"elements/exclusive_screen_toast.cc",
"elements/exclusive_screen_toast.h",
"elements/exclusive_screen_toast_texture.cc",
@@ -36,6 +42,8 @@ static_library("vr_common") {
"elements/exit_prompt_texture.h",
"elements/exit_warning_texture.cc",
"elements/exit_warning_texture.h",
+ "elements/grid.cc",
+ "elements/grid.h",
"elements/insecure_content_permanent_texture.cc",
"elements/insecure_content_permanent_texture.h",
"elements/insecure_content_transient_texture.cc",
@@ -46,15 +54,13 @@ static_library("vr_common") {
"elements/loading_indicator.h",
"elements/loading_indicator_texture.cc",
"elements/loading_indicator_texture.h",
+ "elements/rect.cc",
+ "elements/rect.h",
"elements/render_text_wrapper.cc",
"elements/render_text_wrapper.h",
"elements/screen_dimmer.cc",
"elements/screen_dimmer.h",
"elements/simple_textured_element.h",
- "elements/splash_screen_icon.cc",
- "elements/splash_screen_icon.h",
- "elements/splash_screen_icon_texture.cc",
- "elements/splash_screen_icon_texture.h",
"elements/system_indicator.cc",
"elements/system_indicator.h",
"elements/system_indicator_texture.cc",
@@ -65,11 +71,9 @@ static_library("vr_common") {
"elements/textured_element.h",
"elements/transience_manager.cc",
"elements/transience_manager.h",
- "elements/transient_url_bar.cc",
- "elements/transient_url_bar.h",
"elements/ui_element.cc",
"elements/ui_element.h",
- "elements/ui_element_debug_id.h",
+ "elements/ui_element_name.h",
"elements/ui_element_transform_operations.cc",
"elements/ui_element_transform_operations.h",
"elements/ui_texture.cc",
@@ -78,6 +82,12 @@ static_library("vr_common") {
"elements/url_bar.h",
"elements/url_bar_texture.cc",
"elements/url_bar_texture.h",
+ "elements/viewport_aware_root.cc",
+ "elements/viewport_aware_root.h",
+ "elements/webvr_url_toast.cc",
+ "elements/webvr_url_toast.h",
+ "elements/webvr_url_toast_texture.cc",
+ "elements/webvr_url_toast_texture.h",
"exit_vr_prompt_choice.h",
"font_fallback.cc",
"font_fallback.h",
@@ -87,6 +97,7 @@ static_library("vr_common") {
"gltf_asset.h",
"gltf_parser.cc",
"gltf_parser.h",
+ "target_property.h",
"toolbar_helper.cc",
"toolbar_helper.h",
"toolbar_state.cc",
@@ -136,19 +147,24 @@ static_library("vr_common") {
test("vr_common_unittests") {
sources = [
"animation_player_unittest.cc",
+ "databinding/binding_unittest.cc",
"elements/close_button_texture_unittest.cc",
"elements/exit_prompt_unittest.cc",
"elements/linear_layout_unittest.cc",
"elements/transience_manager_unittest.cc",
"elements/ui_element_unittest.cc",
"elements/url_bar_texture_unittest.cc",
+ "elements/viewport_aware_root_unittest.cc",
"fps_meter_unittest.cc",
"gltf_parser_unittest.cc",
"run_all_unittests.cc",
"test/animation_utils.cc",
"test/animation_utils.h",
+ "test/constants.h",
"test/mock_browser_interface.cc",
"test/mock_browser_interface.h",
+ "test/mock_content_input_delegate.cc",
+ "test/mock_content_input_delegate.h",
"test/paths.cc",
"test/paths.h",
"test/ui_scene_manager_test.cc",
@@ -156,6 +172,7 @@ test("vr_common_unittests") {
"ui_input_manager_unittest.cc",
"ui_scene_manager_unittest.cc",
"ui_scene_unittest.cc",
+ "vr_gl_util_unittest.cc",
]
deps = [