diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-01-20 13:40:20 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-01-22 12:41:23 +0000 |
commit | 7961cea6d1041e3e454dae6a1da660b453efd238 (patch) | |
tree | c0eeb4a9ff9ba32986289c1653d9608e53ccb444 /chromium/chrome/browser | |
parent | b7034d0803538058e5c9d904ef03cf5eab34f6ef (diff) | |
download | qtwebengine-chromium-7961cea6d1041e3e454dae6a1da660b453efd238.tar.gz |
BASELINE: Update Chromium to 78.0.3904.130
Change-Id: If185e0c0061b3437531c97c9c8c78f239352a68b
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/chrome/browser')
1183 files changed, 23680 insertions, 18191 deletions
diff --git a/chromium/chrome/browser/BUILD.gn b/chromium/chrome/browser/BUILD.gn index c00a09a5ec2..d730660c086 100644 --- a/chromium/chrome/browser/BUILD.gn +++ b/chromium/chrome/browser/BUILD.gn @@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//base/allocator/allocator.gni") import("//build/config/chrome_build.gni") import("//build/config/crypto.gni") import("//build/config/features.gni") @@ -34,6 +35,7 @@ import("//ui/base/ui_features.gni") # produces a conflict for the "grit" template so we have to only include one. if (is_android) { import("//build/config/android/rules.gni") + import("//chrome/android/features/dev_ui/dev_ui_module.gni") } else { import("//tools/grit/grit_rule.gni") } @@ -123,6 +125,8 @@ jumbo_split_static_library("browser") { "autofill/address_normalizer_factory.h", "autofill/autocomplete_history_manager_factory.cc", "autofill/autocomplete_history_manager_factory.h", + "autofill/autofill_gstatic_reader.cc", + "autofill/autofill_gstatic_reader.h", "autofill/autofill_profile_validator_factory.cc", "autofill/autofill_profile_validator_factory.h", "autofill/personal_data_manager_factory.cc", @@ -265,6 +269,8 @@ jumbo_split_static_library("browser") { "chrome_browser_application_mac.mm", "chrome_browser_field_trials.cc", "chrome_browser_field_trials.h", + "chrome_browser_interface_binders.cc", + "chrome_browser_interface_binders.h", "chrome_browser_main.cc", "chrome_browser_main.h", "chrome_browser_main_android.cc", @@ -284,8 +290,6 @@ jumbo_split_static_library("browser") { "chrome_quota_permission_context.h", "chrome_resource_bundle_helper.cc", "chrome_resource_bundle_helper.h", - "chrome_service.cc", - "chrome_service.h", "client_hints/client_hints.cc", "client_hints/client_hints.h", "client_hints/client_hints_factory.cc", @@ -301,6 +305,8 @@ jumbo_split_static_library("browser") { "command_updater_delegate.h", "command_updater_impl.cc", "command_updater_impl.h", + "complex_tasks/endpoint_fetcher/endpoint_fetcher.cc", + "complex_tasks/endpoint_fetcher/endpoint_fetcher.h", "complex_tasks/task_tab_helper.cc", "complex_tasks/task_tab_helper.h", "component_updater/chrome_component_updater_configurator.cc", @@ -329,6 +335,8 @@ jumbo_split_static_library("browser") { "component_updater/recovery_improved_component_installer.h", "component_updater/safety_tips_component_installer.cc", "component_updater/safety_tips_component_installer.h", + "component_updater/ssl_error_assistant_component_installer.cc", + "component_updater/ssl_error_assistant_component_installer.h", "component_updater/sth_set_component_remover.cc", "component_updater/sth_set_component_remover.h", "component_updater/subresource_filter_component_installer.cc", @@ -337,6 +345,8 @@ jumbo_split_static_library("browser") { "component_updater/sw_reporter_installer_win.h", "consent_auditor/consent_auditor_factory.cc", "consent_auditor/consent_auditor_factory.h", + "content_index/content_index_metrics.cc", + "content_index/content_index_metrics.h", "content_index/content_index_provider_factory.cc", "content_index/content_index_provider_factory.h", "content_index/content_index_provider_impl.cc", @@ -365,14 +375,14 @@ jumbo_split_static_library("browser") { "custom_handlers/protocol_handler_registry.h", "custom_handlers/protocol_handler_registry_factory.cc", "custom_handlers/protocol_handler_registry_factory.h", - "data_reduction_proxy/data_reduction_proxy_chrome_io_data.cc", - "data_reduction_proxy/data_reduction_proxy_chrome_io_data.h", "data_reduction_proxy/data_reduction_proxy_chrome_settings.cc", "data_reduction_proxy/data_reduction_proxy_chrome_settings.h", "data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.cc", "data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h", "data_reduction_proxy/data_reduction_proxy_tab_helper.cc", "data_reduction_proxy/data_reduction_proxy_tab_helper.h", + "data_saver/data_saver_top_host_provider.cc", + "data_saver/data_saver_top_host_provider.h", "data_use_measurement/chrome_data_use_measurement.cc", "data_use_measurement/chrome_data_use_measurement.h", "defaults.cc", @@ -482,6 +492,7 @@ jumbo_split_static_library("browser") { "engagement/site_engagement_service.h", "engagement/site_engagement_service_factory.cc", "engagement/site_engagement_service_factory.h", + "expired_flags_list.h", "external_protocol/external_protocol_handler.cc", "external_protocol/external_protocol_handler.h", "external_protocol/external_protocol_observer.cc", @@ -503,6 +514,8 @@ jumbo_split_static_library("browser") { "file_select_helper_contacts_android.cc", "file_select_helper_contacts_android.h", "file_select_helper_mac.mm", + "file_util_service.cc", + "file_util_service.h", "flag_descriptions.cc", "flag_descriptions.h", "font_pref_change_notifier.cc", @@ -527,8 +540,6 @@ jumbo_split_static_library("browser") { "geolocation/geolocation_permission_context_extensions.h", "global_keyboard_shortcuts_mac.h", "global_keyboard_shortcuts_mac.mm", - "google/chrome_google_url_tracker_client.cc", - "google/chrome_google_url_tracker_client.h", "google/did_run_updater_win.cc", "google/did_run_updater_win.h", "google/google_brand.cc", @@ -537,13 +548,19 @@ jumbo_split_static_library("browser") { "google/google_search_domain_mixing_metrics_emitter.h", "google/google_search_domain_mixing_metrics_emitter_factory.cc", "google/google_search_domain_mixing_metrics_emitter_factory.h", - "google/google_url_tracker_factory.cc", - "google/google_url_tracker_factory.h", "gpu/gpu_mode_manager.cc", "gpu/gpu_mode_manager.h", "hang_monitor/hang_crash_dump.h", "hang_monitor/hang_crash_dump_mac.cc", "hang_monitor/hang_crash_dump_win.cc", + "heavy_ad_intervention/heavy_ad_blocklist.cc", + "heavy_ad_intervention/heavy_ad_blocklist.h", + "heavy_ad_intervention/heavy_ad_helper.cc", + "heavy_ad_intervention/heavy_ad_helper.h", + "heavy_ad_intervention/heavy_ad_service.cc", + "heavy_ad_intervention/heavy_ad_service.h", + "heavy_ad_intervention/heavy_ad_service_factory.cc", + "heavy_ad_intervention/heavy_ad_service_factory.h", "history/chrome_history_backend_client.cc", "history/chrome_history_backend_client.h", "history/chrome_history_client.cc", @@ -620,8 +637,6 @@ jumbo_split_static_library("browser") { "lifetime/application_lifetime_mac.mm", "lifetime/browser_shutdown.cc", "lifetime/browser_shutdown.h", - "lookalikes/lookalike_url_allowlist.cc", - "lookalikes/lookalike_url_allowlist.h", "lookalikes/lookalike_url_controller_client.cc", "lookalikes/lookalike_url_controller_client.h", "lookalikes/lookalike_url_interstitial_page.cc", @@ -630,7 +645,15 @@ jumbo_split_static_library("browser") { "lookalikes/lookalike_url_navigation_throttle.h", "lookalikes/lookalike_url_service.cc", "lookalikes/lookalike_url_service.h", + "lookalikes/lookalike_url_tab_storage.cc", + "lookalikes/lookalike_url_tab_storage.h", + "lookalikes/safety_tips/reputation_service.cc", + "lookalikes/safety_tips/reputation_service.h", + "lookalikes/safety_tips/reputation_web_contents_observer.cc", + "lookalikes/safety_tips/reputation_web_contents_observer.h", "lookalikes/safety_tips/safety_tip_ui.h", + "lookalikes/safety_tips/safety_tip_ui_helper.cc", + "lookalikes/safety_tips/safety_tip_ui_helper.h", "lookalikes/safety_tips/safety_tips_config.cc", "lookalikes/safety_tips/safety_tips_config.h", "mac/bluetooth_utility.h", @@ -726,12 +749,14 @@ jumbo_split_static_library("browser") { "media/webrtc/webrtc_event_log_manager_remote.h", "media/webrtc/webrtc_event_log_uploader.cc", "media/webrtc/webrtc_event_log_uploader.h", + "media/webrtc/webrtc_log_buffer.cc", + "media/webrtc/webrtc_log_buffer.h", "media/webrtc/webrtc_log_uploader.cc", "media/webrtc/webrtc_log_uploader.h", "media/webrtc/webrtc_log_util.cc", "media/webrtc/webrtc_log_util.h", - "media/webrtc/webrtc_logging_handler_host.cc", - "media/webrtc/webrtc_logging_handler_host.h", + "media/webrtc/webrtc_logging_controller.cc", + "media/webrtc/webrtc_logging_controller.h", "media/webrtc/webrtc_rtp_dump_handler.cc", "media/webrtc/webrtc_rtp_dump_handler.h", "media/webrtc/webrtc_rtp_dump_writer.cc", @@ -834,6 +859,8 @@ jumbo_split_static_library("browser") { "net/dns_probe_service.h", "net/dns_probe_service_factory.cc", "net/dns_probe_service_factory.h", + "net/dns_util.cc", + "net/dns_util.h", "net/file_downloader.cc", "net/file_downloader.h", "net/net_error_diagnostics_dialog.h", @@ -856,6 +883,8 @@ jumbo_split_static_library("browser") { "net/proxy_service_factory.h", "net/referrer.cc", "net/referrer.h", + "net/secure_dns_policy_handler.cc", + "net/secure_dns_policy_handler.h", "net/service_providers_win.cc", "net/service_providers_win.h", "net/system_network_context_manager.cc", @@ -919,6 +948,16 @@ jumbo_split_static_library("browser") { "offline_items_collection/offline_content_aggregator_factory.cc", "offline_items_collection/offline_content_aggregator_factory.h", "omnibox/common/omnibox_features.h", + "optimization_guide/optimization_guide_hints_manager.cc", + "optimization_guide/optimization_guide_hints_manager.h", + "optimization_guide/optimization_guide_keyed_service.cc", + "optimization_guide/optimization_guide_keyed_service.h", + "optimization_guide/optimization_guide_keyed_service_factory.cc", + "optimization_guide/optimization_guide_keyed_service_factory.h", + "optimization_guide/optimization_guide_navigation_data.cc", + "optimization_guide/optimization_guide_navigation_data.h", + "optimization_guide/optimization_guide_web_contents_observer.cc", + "optimization_guide/optimization_guide_web_contents_observer.h", "page_load_metrics/metrics_navigation_throttle.cc", "page_load_metrics/metrics_navigation_throttle.h", "page_load_metrics/metrics_web_contents_observer.cc", @@ -1016,10 +1055,10 @@ jumbo_split_static_library("browser") { "page_load_metrics/protocol_util.h", "page_load_metrics/resource_tracker.cc", "page_load_metrics/resource_tracker.h", + "password_manager/account_storage/account_password_store_factory.cc", + "password_manager/account_storage/account_password_store_factory.h", "password_manager/chrome_password_manager_client.cc", "password_manager/chrome_password_manager_client.h", - "password_manager/password_manager_util_linux.cc", - "password_manager/password_manager_util_linux.h", "password_manager/password_manager_util_mac.h", "password_manager/password_manager_util_mac.mm", "password_manager/password_manager_util_win.cc", @@ -1036,11 +1075,17 @@ jumbo_split_static_library("browser") { "performance_manager/chrome_browser_main_extra_parts_performance_manager.h", "performance_manager/chrome_content_browser_client_performance_manager_part.cc", "performance_manager/chrome_content_browser_client_performance_manager_part.h", + "performance_manager/decorators/freeze_origin_trial_policy_aggregator.cc", + "performance_manager/decorators/freeze_origin_trial_policy_aggregator.h", "performance_manager/decorators/frozen_frame_aggregator.cc", "performance_manager/decorators/frozen_frame_aggregator.h", "performance_manager/decorators/page_almost_idle_decorator.cc", "performance_manager/decorators/page_almost_idle_decorator.h", + "performance_manager/decorators/process_metrics_decorator.cc", + "performance_manager/decorators/process_metrics_decorator.h", "performance_manager/frame_priority/frame_priority.cc", + "performance_manager/frame_priority/max_vote_aggregator.cc", + "performance_manager/frame_priority/override_vote_aggregator.cc", "performance_manager/graph/frame_node.cc", "performance_manager/graph/frame_node_impl.cc", "performance_manager/graph/frame_node_impl.h", @@ -1060,6 +1105,14 @@ jumbo_split_static_library("browser") { "performance_manager/graph/page_node.cc", "performance_manager/graph/page_node_impl.cc", "performance_manager/graph/page_node_impl.h", + "performance_manager/graph/policies/policy_features.cc", + "performance_manager/graph/policies/policy_features.h", + "performance_manager/graph/policies/working_set_trimmer_policy.cc", + "performance_manager/graph/policies/working_set_trimmer_policy.h", + "performance_manager/graph/policies/working_set_trimmer_policy_chromeos.cc", + "performance_manager/graph/policies/working_set_trimmer_policy_chromeos.h", + "performance_manager/graph/policies/working_set_trimmer_policy_win.cc", + "performance_manager/graph/policies/working_set_trimmer_policy_win.h", "performance_manager/graph/process_node.cc", "performance_manager/graph/process_node_impl.cc", "performance_manager/graph/process_node_impl.h", @@ -1067,6 +1120,9 @@ jumbo_split_static_library("browser") { "performance_manager/graph/system_node.cc", "performance_manager/graph/system_node_impl.cc", "performance_manager/graph/system_node_impl.h", + "performance_manager/graph/worker_node.cc", + "performance_manager/graph/worker_node_impl.cc", + "performance_manager/graph/worker_node_impl.h", "performance_manager/mechanisms/working_set_trimmer.cc", "performance_manager/mechanisms/working_set_trimmer.h", "performance_manager/mechanisms/working_set_trimmer_chromeos.cc", @@ -1074,14 +1130,10 @@ jumbo_split_static_library("browser") { "performance_manager/mechanisms/working_set_trimmer_win.cc", "performance_manager/mechanisms/working_set_trimmer_win.h", "performance_manager/observers/background_metrics_reporter.h", - "performance_manager/observers/graph_observer.cc", - "performance_manager/observers/graph_observer.h", "performance_manager/observers/isolation_context_metrics.cc", "performance_manager/observers/isolation_context_metrics.h", "performance_manager/observers/metrics_collector.cc", "performance_manager/observers/metrics_collector.h", - "performance_manager/observers/working_set_trimmer_observer_win.cc", - "performance_manager/observers/working_set_trimmer_observer_win.h", "performance_manager/performance_manager.cc", "performance_manager/performance_manager.h", "performance_manager/performance_manager_clock.cc", @@ -1116,6 +1168,8 @@ jumbo_split_static_library("browser") { "performance_manager/persistence/site_data/site_data_writer.h", "performance_manager/persistence/site_data/tab_visibility.h", "performance_manager/public/frame_priority/frame_priority.h", + "performance_manager/public/frame_priority/max_vote_aggregator.h", + "performance_manager/public/frame_priority/override_vote_aggregator.h", "performance_manager/public/graph/frame_node.h", "performance_manager/public/graph/graph.h", "performance_manager/public/graph/graph_operations.h", @@ -1124,7 +1178,10 @@ jumbo_split_static_library("browser") { "performance_manager/public/graph/page_node.h", "performance_manager/public/graph/process_node.h", "performance_manager/public/graph/system_node.h", + "performance_manager/public/graph/worker_node.h", + "performance_manager/public/render_process_host_proxy.h", "performance_manager/public/web_contents_proxy.h", + "performance_manager/render_process_host_proxy.cc", "performance_manager/render_process_user_data.cc", "performance_manager/render_process_user_data.h", "performance_manager/web_contents_proxy.cc", @@ -1148,6 +1205,8 @@ jumbo_split_static_library("browser") { "permissions/permission_context_base.h", "permissions/permission_decision_auto_blocker.cc", "permissions/permission_decision_auto_blocker.h", + "permissions/permission_features.cc", + "permissions/permission_features.h", "permissions/permission_manager.cc", "permissions/permission_manager.h", "permissions/permission_manager_factory.cc", @@ -1348,8 +1407,6 @@ jumbo_split_static_library("browser") { "previews/previews_service.h", "previews/previews_service_factory.cc", "previews/previews_service_factory.h", - "previews/previews_top_host_provider.cc", - "previews/previews_top_host_provider.h", "previews/previews_ui_tab_helper.cc", "previews/previews_ui_tab_helper.h", "previews/resource_loading_hints/resource_loading_hints_web_contents_observer.cc", @@ -1415,6 +1472,7 @@ jumbo_split_static_library("browser") { "profiles/profile_key.h", "profiles/profile_manager.cc", "profiles/profile_manager.h", + "profiles/profile_manager_observer.h", "profiles/profile_metrics.cc", "profiles/profile_metrics.h", "profiles/profile_shortcut_manager_win.cc", @@ -1452,8 +1510,6 @@ jumbo_split_static_library("browser") { "renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm", "renderer_preferences_util.cc", "renderer_preferences_util.h", - "resource_coordinator/discard_before_unload_helper.cc", - "resource_coordinator/discard_before_unload_helper.h", "resource_coordinator/resource_coordinator_parts.cc", "resource_coordinator/resource_coordinator_parts.h", "resource_coordinator/session_restore_policy.cc", @@ -1470,8 +1526,6 @@ jumbo_split_static_library("browser") { "resource_coordinator/utils.h", "resources_util.cc", "resources_util.h", - "scoped_visibility_tracker.cc", - "scoped_visibility_tracker.h", "search/instant_io_context.cc", "search/instant_io_context.h", "search/ntp_icon_source.cc", @@ -1536,10 +1590,13 @@ jumbo_split_static_library("browser") { "sharing/features.h", "sharing/ping_message_handler.cc", "sharing/ping_message_handler.h", + "sharing/shared_clipboard/feature_flags.cc", + "sharing/shared_clipboard/feature_flags.h", + "sharing/shared_clipboard/shared_clipboard_message_handler.cc", + "sharing/shared_clipboard/shared_clipboard_message_handler.h", "sharing/sharing_constants.cc", "sharing/sharing_constants.h", - "sharing/sharing_device_info.cc", - "sharing/sharing_device_info.h", + "sharing/sharing_device_capability.h", "sharing/sharing_device_registration.cc", "sharing/sharing_device_registration.h", "sharing/sharing_device_registration_result.h", @@ -1550,10 +1607,13 @@ jumbo_split_static_library("browser") { "sharing/sharing_message_handler.h", "sharing/sharing_metrics.cc", "sharing/sharing_metrics.h", + "sharing/sharing_send_message_result.h", "sharing/sharing_service.cc", "sharing/sharing_service.h", "sharing/sharing_service_factory.cc", "sharing/sharing_service_factory.h", + "sharing/sharing_service_proxy_android.cc", + "sharing/sharing_service_proxy_android.h", "sharing/sharing_sync_preference.cc", "sharing/sharing_sync_preference.h", "sharing/vapid_key_manager.cc", @@ -1590,8 +1650,6 @@ jumbo_split_static_library("browser") { "signin/chrome_signin_url_loader_throttle.cc", "signin/chrome_signin_url_loader_throttle.h", "signin/header_modification_delegate.h", - "signin/header_modification_delegate_on_io_thread_impl.cc", - "signin/header_modification_delegate_on_io_thread_impl.h", "signin/header_modification_delegate_on_ui_thread_impl.cc", "signin/header_modification_delegate_on_ui_thread_impl.h", "signin/identity_manager_factory.cc", @@ -1625,8 +1683,6 @@ jumbo_split_static_library("browser") { "speech/speech_recognizer_delegate.h", "speech/tts_controller_delegate_impl.cc", "speech/tts_controller_delegate_impl.h", - "speech/tts_message_filter.cc", - "speech/tts_message_filter.h", "ssl/bad_clock_blocking_page.cc", "ssl/bad_clock_blocking_page.h", "ssl/captive_portal_blocking_page.cc", @@ -1766,6 +1822,8 @@ jumbo_split_static_library("browser") { "translate/translate_service.h", "undo/bookmark_undo_service_factory.cc", "undo/bookmark_undo_service_factory.h", + "unexpire_flags.cc", + "unexpire_flags.h", "unified_consent/unified_consent_service_factory.cc", "unified_consent/unified_consent_service_factory.h", "update_client/chrome_update_query_params_delegate.cc", @@ -1795,18 +1853,6 @@ jumbo_split_static_library("browser") { "wake_lock/wake_lock_permission_context.h", "web_data_service_factory.cc", "web_data_service_factory.h", - "webauthn/authenticator_list_observer.h", - "webauthn/authenticator_reference.cc", - "webauthn/authenticator_reference.h", - "webauthn/authenticator_request_dialog_model.cc", - "webauthn/authenticator_request_dialog_model.h", - "webauthn/authenticator_request_scheduler.cc", - "webauthn/authenticator_request_scheduler.h", - "webauthn/authenticator_transport.h", - "webauthn/chrome_authenticator_request_delegate.cc", - "webauthn/chrome_authenticator_request_delegate.h", - "webauthn/observable_authenticator_list.cc", - "webauthn/observable_authenticator_list.h", "win/app_icon.cc", "win/app_icon.h", "win/automation_controller.cc", @@ -1869,10 +1915,12 @@ jumbo_split_static_library("browser") { public_deps = [ "//base", "//chrome/common", + "//chrome/services/file_util/public/mojom", "//components/account_id", "//components/autofill/core/browser", "//components/nacl/common:buildflags", "//components/payments/core", + "//components/safe_browsing:buildflags", "//components/sync", "//components/sync_device_info", "//content/public/browser", @@ -1882,6 +1930,7 @@ jumbo_split_static_library("browser") { deps = [ ":active_use_util", ":availability_protos", + ":expired_flags_list", ":ntp_background_proto", ":resource_prefetch_predictor_proto", "//base:i18n", @@ -1973,7 +2022,6 @@ jumbo_split_static_library("browser") { "//components/language/core/browser", "//components/language/core/common", "//components/leveldb_proto", - "//components/leveldb_proto/content:factory", "//components/metrics:call_stack_profile_collector", "//components/metrics:component_metrics", "//components/metrics:demographic_metrics_provider", @@ -1982,7 +2030,6 @@ jumbo_split_static_library("browser") { "//components/metrics:ui", "//components/metrics_services_manager", "//components/mirroring/browser", - "//components/mirroring/mojom:constants", "//components/mirroring/mojom:host", "//components/mirroring/mojom:service", "//components/mirroring/service:mirroring_service", @@ -2028,9 +2075,10 @@ jumbo_split_static_library("browser") { "//components/security_state/core", "//components/send_tab_to_self", "//components/services/heap_profiling", - "//components/services/patch/public/mojom", + "//components/services/patch/content", "//components/services/quarantine", "//components/services/quarantine/public/mojom", + "//components/services/unzip/content", "//components/services/unzip/public/mojom", "//components/sessions", "//components/signin/core/browser", @@ -2046,7 +2094,6 @@ jumbo_split_static_library("browser") { "//components/subresource_filter/content/browser", "//components/subresource_filter/core/browser", "//components/suggestions", - "//components/supervised_user_error_page", "//components/sync", "//components/sync_bookmarks", "//components/sync_preferences", @@ -2064,8 +2111,8 @@ jumbo_split_static_library("browser") { "//components/update_client:common_impl", "//components/upload_list", "//components/url_formatter", - "//components/url_formatter/top_domains:top500_domains", - "//components/url_formatter/top_domains:top500_domains_header", + "//components/url_formatter/spoof_checks/top_domains:top500_domains", + "//components/url_formatter/spoof_checks/top_domains:top500_domains_header", "//components/url_matcher", "//components/user_prefs", "//components/variations", @@ -2085,8 +2132,6 @@ jumbo_split_static_library("browser") { "//content/public/browser", "//content/public/browser", "//content/public/common", - "//content/public/common:buildflags", - "//content/public/common:feature_h264_with_openh264_ffmpeg", "//content/public/common:service_names", "//crypto", "//crypto:platform", @@ -2104,8 +2149,8 @@ jumbo_split_static_library("browser") { "//media/midi", "//media/mojo:buildflags", "//media/mojo/common", - "//media/mojo/interfaces:mirror_service_remoting", - "//media/mojo/interfaces:remoting", + "//media/mojo/mojom:mirror_service_remoting", + "//media/mojo/mojom:remoting", "//media/mojo/services", "//media/webrtc", "//mojo/core/embedder", @@ -2136,6 +2181,7 @@ jumbo_split_static_library("browser") { "//services/preferences/tracked", "//services/proxy_resolver/public/mojom", "//services/resource_coordinator/public/cpp:resource_coordinator_cpp", + "//services/resource_coordinator/public/cpp/memory_instrumentation:browser", "//services/service_manager/public/cpp", "//services/shape_detection/public/mojom", "//services/strings", @@ -2200,14 +2246,14 @@ jumbo_split_static_library("browser") { "android/android_theme_resources.h", "android/app_hooks.cc", "android/app_hooks.h", + "android/autofill_assistant/assistant_collect_user_data_delegate.cc", + "android/autofill_assistant/assistant_collect_user_data_delegate.h", "android/autofill_assistant/assistant_form_delegate.cc", "android/autofill_assistant/assistant_form_delegate.h", "android/autofill_assistant/assistant_header_delegate.cc", "android/autofill_assistant/assistant_header_delegate.h", "android/autofill_assistant/assistant_overlay_delegate.cc", "android/autofill_assistant/assistant_overlay_delegate.h", - "android/autofill_assistant/assistant_payment_request_delegate.cc", - "android/autofill_assistant/assistant_payment_request_delegate.h", "android/autofill_assistant/client_android.cc", "android/autofill_assistant/client_android.h", "android/autofill_assistant/ui_controller_android.cc", @@ -2216,6 +2262,8 @@ jumbo_split_static_library("browser") { "android/background_sync_launcher_android.h", "android/background_tab_manager.cc", "android/background_tab_manager.h", + "android/background_task_scheduler/chrome_background_task_factory.cc", + "android/background_task_scheduler/chrome_background_task_factory.h", "android/bookmarks/bookmark_bridge.cc", "android/bookmarks/bookmark_bridge.h", "android/bookmarks/partner_bookmarks_reader.cc", @@ -2334,6 +2382,8 @@ jumbo_split_static_library("browser") { "android/devtools_manager_delegate_android.h", "android/devtools_server.cc", "android/devtools_server.h", + "android/dfm_resource_bundle_helper.cc", + "android/dfm_resource_bundle_helper.h", "android/digital_asset_links/digital_asset_links_handler.cc", "android/digital_asset_links/digital_asset_links_handler.h", "android/document/document_web_contents_delegate.cc", @@ -2361,6 +2411,7 @@ jumbo_split_static_library("browser") { "android/download/download_media_parser.h", "android/download/download_media_parser_bridge.cc", "android/download/download_media_parser_bridge.h", + "android/download/download_open_source.h", "android/download/download_startup_utils.cc", "android/download/download_startup_utils.h", "android/download/download_utils.cc", @@ -2490,10 +2541,13 @@ jumbo_split_static_library("browser") { "android/location_settings_impl.h", "android/logo_bridge.cc", "android/logo_bridge.h", + "android/media/media_capture_devices_dispatcher_android.cc", "android/metrics/android_profile_session_durations_service.cc", "android/metrics/android_profile_session_durations_service.h", "android/metrics/android_profile_session_durations_service_factory.cc", "android/metrics/android_profile_session_durations_service_factory.h", + "android/metrics/background_task_memory_metrics_emitter.cc", + "android/metrics/background_task_memory_metrics_emitter.h", "android/metrics/launch_metrics.cc", "android/metrics/uma_session_stats.cc", "android/metrics/uma_session_stats.h", @@ -2531,8 +2585,13 @@ jumbo_split_static_library("browser") { "android/oom_intervention/oom_intervention_tab_helper.h", "android/partner_browser_customizations.cc", "android/partner_browser_customizations.h", + "android/password_change_delegate.h", + "android/password_editing_bridge.cc", + "android/password_editing_bridge.h", "android/password_ui_view_android.cc", "android/password_ui_view_android.h", + "android/password_update_delegate.cc", + "android/password_update_delegate.h", "android/payments/service_worker_payment_app_bridge.cc", "android/photo_picker_sandbox_bridge.cc", "android/policy/policy_auditor.cc", @@ -2595,13 +2654,10 @@ jumbo_split_static_library("browser") { "android/shortcut_helper.h", "android/shortcut_info.cc", "android/shortcut_info.h", - "android/signin/chrome_signin_manager_delegate.cc", - "android/signin/chrome_signin_manager_delegate.h", "android/signin/signin_investigator_android.cc", "android/signin/signin_investigator_android.h", "android/signin/signin_manager_android.cc", "android/signin/signin_manager_android.h", - "android/signin/signin_manager_delegate.h", "android/signin/signin_promo_util_android.cc", "android/signin/signin_promo_util_android.h", "android/signin/signin_utils.cc", @@ -2667,8 +2723,8 @@ jumbo_split_static_library("browser") { "android/webapps/add_to_homescreen_data_fetcher.h", "android/webapps/add_to_homescreen_manager.cc", "android/webapps/add_to_homescreen_manager.h", - "android/webapps/single_tab_mode_tab_helper.cc", - "android/webapps/single_tab_mode_tab_helper.h", + "android/webapps/webapk_ukm_recorder.cc", + "android/webapps/webapk_ukm_recorder.h", "android/webapps/webapp_registry.cc", "android/webapps/webapp_registry.h", "android/widget/thumbnail_generator.cc", @@ -2723,6 +2779,10 @@ jumbo_split_static_library("browser") { "invalidation/invalidation_service_factory_android.h", "lifetime/application_lifetime_android.cc", "lifetime/application_lifetime_android.h", + "lookalikes/safety_tips/safety_tip_infobar.cc", + "lookalikes/safety_tips/safety_tip_infobar.h", + "lookalikes/safety_tips/safety_tip_infobar_delegate.cc", + "lookalikes/safety_tips/safety_tip_infobar_delegate.h", "media/android/cdm/media_drm_license_manager.cc", "media/android/cdm/media_drm_license_manager.h", "media/android/cdm/media_drm_origin_id_manager.cc", @@ -2765,6 +2825,8 @@ jumbo_split_static_library("browser") { "password_manager/auto_signin_first_run_dialog_android.h", "password_manager/credential_android.cc", "password_manager/credential_android.h", + "password_manager/credential_leak_controller_android.cc", + "password_manager/credential_leak_controller_android.h", "password_manager/generated_password_saved_infobar_delegate_android.cc", "password_manager/generated_password_saved_infobar_delegate_android.h", "password_manager/password_accessory_controller.h", @@ -2795,6 +2857,10 @@ jumbo_split_static_library("browser") { "permissions/permission_dialog_delegate.h", "permissions/permission_prompt_android.cc", "permissions/permission_prompt_android.h", + "permissions/permission_request_notification_android.cc", + "permissions/permission_request_notification_android.h", + "permissions/permission_request_notification_handler.cc", + "permissions/permission_request_notification_handler.h", "permissions/permission_update_infobar_delegate_android.cc", "permissions/permission_update_infobar_delegate_android.h", "platform_util_android.cc", @@ -2812,6 +2878,8 @@ jumbo_split_static_library("browser") { "search/contextual_search_policy_handler_android.h", "search_engines/template_url_service_factory_android.cc", "search_engines/template_url_service_factory_android.h", + "sharing/shared_clipboard/shared_clipboard_message_handler_android.cc", + "sharing/shared_clipboard/shared_clipboard_message_handler_android.h", "signin/identity_services_provider_android.cc", "signin/signin_manager_android_factory.cc", "signin/signin_manager_android_factory.h", @@ -2827,6 +2895,7 @@ jumbo_split_static_library("browser") { "translate/android/translate_bridge.cc", ] public_deps += [ + "//chrome/android/features/dev_ui:buildflags", "//components/image_fetcher/core", "//components/ntp_snippets", ] @@ -2854,13 +2923,13 @@ jumbo_split_static_library("browser") { "//components/send_tab_to_self", "//components/signin/internal/identity_manager", # see android/signin/DEPS "//media/mojo/clients", - "//media/mojo/interfaces:constants", + "//media/mojo/mojom:constants", "//rlz:rlz_utils", "//sandbox", "//sandbox:sandbox_buildflags", "//services/proxy_resolver:lib", + "//third_party/android_ndk:cpu_features", "//third_party/android_opengl/etc1", - "//third_party/android_sdk:cpu_features", "//third_party/crashpad/crashpad/client:client", "//third_party/libaddressinput:util", "//third_party/libphonenumber", @@ -2876,6 +2945,21 @@ jumbo_split_static_library("browser") { "supervised_user/child_accounts/child_account_service_android.cc", "supervised_user/child_accounts/child_account_service_android.h", ] + deps += [ "//chrome/browser/supervised_user/supervised_user_error_page" ] + } + + if (dfmify_dev_ui) { + sources += [ + "android/dev_ui/dev_ui_module_provider.cc", + "android/dev_ui/dev_ui_module_provider.h", + "android/dev_ui/dev_ui_url_handler.cc", + "android/dev_ui/dev_ui_url_handler.h", + "ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc", + "ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h", + "ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc", + "ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h", + ] + deps += [ "//chrome/android/modules/dev_ui/provider:jni_headers" ] } } else { # !is_android sources += [ @@ -2918,6 +3002,7 @@ jumbo_split_static_library("browser") { "background/background_contents_service_observer.h", "badging/badge_manager.cc", "badging/badge_manager.h", + "badging/badge_manager_delegate.cc", "badging/badge_manager_delegate.h", "badging/badge_manager_factory.cc", "badging/badge_manager_factory.h", @@ -3010,11 +3095,6 @@ jumbo_split_static_library("browser") { "first_run/first_run_internal_linux.cc", "first_run/first_run_internal_mac.mm", "first_run/first_run_internal_win.cc", - "first_run/upgrade_util.h", - "first_run/upgrade_util_mac.h", - "first_run/upgrade_util_mac.mm", - "first_run/upgrade_util_win.cc", - "first_run/upgrade_util_win.h", "font_family_cache.cc", "font_family_cache.h", "hid/chrome_hid_delegate.cc", @@ -3154,8 +3234,6 @@ jumbo_split_static_library("browser") { "metrics/first_web_contents_profiler.cc", "metrics/first_web_contents_profiler.h", "metrics/incognito_observer_desktop.cc", - "metrics/tab_reactivation_tracker.cc", - "metrics/tab_reactivation_tracker.h", "metrics/tab_stats_data_store.cc", "metrics/tab_stats_data_store.h", "metrics/tab_stats_tracker.cc", @@ -3163,8 +3241,6 @@ jumbo_split_static_library("browser") { "metrics/tab_stats_tracker_delegate.h", "metrics/tab_stats_tracker_delegate_win.cc", "metrics/tab_stats_tracker_win.cc", - "metrics/tab_usage_recorder.cc", - "metrics/tab_usage_recorder.h", "notifications/notification_system_observer.cc", "notifications/notification_system_observer.h", "notifications/profile_notification.cc", @@ -3290,8 +3366,8 @@ jumbo_split_static_library("browser") { "search/background/ntp_background_service_factory.cc", "search/background/ntp_background_service_factory.h", "search/background/ntp_background_service_observer.h", - "search/background/onboarding_ntp_backgrounds.cc", - "search/background/onboarding_ntp_backgrounds.h", + "search/background/ntp_backgrounds.cc", + "search/background/ntp_backgrounds.h", "search/chrome_colors/chrome_colors_factory.cc", "search/chrome_colors/chrome_colors_factory.h", "search/chrome_colors/chrome_colors_service.cc", @@ -3349,16 +3425,25 @@ jumbo_split_static_library("browser") { "serial/serial_chooser_context.h", "serial/serial_chooser_context_factory.cc", "serial/serial_chooser_context_factory.h", - "sharing/click_to_call/click_to_call_constants.h", "sharing/click_to_call/click_to_call_context_menu_observer.cc", "sharing/click_to_call/click_to_call_context_menu_observer.h", - "sharing/click_to_call/click_to_call_dialog.h", - "sharing/click_to_call/click_to_call_sharing_dialog_controller.cc", - "sharing/click_to_call/click_to_call_sharing_dialog_controller.h", + "sharing/click_to_call/click_to_call_ui_controller.cc", + "sharing/click_to_call/click_to_call_ui_controller.h", "sharing/click_to_call/click_to_call_utils.cc", "sharing/click_to_call/click_to_call_utils.h", - "sharing/sharing_dialog_controller.cc", - "sharing/sharing_dialog_controller.h", + "sharing/shared_clipboard/shared_clipboard_context_menu_observer.cc", + "sharing/shared_clipboard/shared_clipboard_context_menu_observer.h", + "sharing/shared_clipboard/shared_clipboard_message_handler_desktop.cc", + "sharing/shared_clipboard/shared_clipboard_message_handler_desktop.h", + "sharing/shared_clipboard/shared_clipboard_ui_controller.cc", + "sharing/shared_clipboard/shared_clipboard_ui_controller.h", + "sharing/shared_clipboard/shared_clipboard_utils.cc", + "sharing/shared_clipboard/shared_clipboard_utils.h", + "sharing/sharing_dialog.h", + "sharing/sharing_notification_handler.cc", + "sharing/sharing_notification_handler.h", + "sharing/sharing_ui_controller.cc", + "sharing/sharing_ui_controller.h", "signin/signin_promo.cc", "signin/signin_promo.h", "signin/signin_ui_util.cc", @@ -3471,9 +3556,22 @@ jumbo_split_static_library("browser") { "usb/web_usb_detector.h", "web_launch/web_launch_files_helper.cc", "web_launch/web_launch_files_helper.h", + "webauthn/authenticator_list_observer.h", + "webauthn/authenticator_reference.cc", + "webauthn/authenticator_reference.h", + "webauthn/authenticator_request_dialog_model.cc", + "webauthn/authenticator_request_dialog_model.h", + "webauthn/authenticator_request_scheduler.cc", + "webauthn/authenticator_request_scheduler.h", + "webauthn/authenticator_transport.h", + "webauthn/chrome_authenticator_request_delegate.cc", + "webauthn/chrome_authenticator_request_delegate.h", + "webauthn/observable_authenticator_list.cc", + "webauthn/observable_authenticator_list.h", ] deps += [ ":theme_properties", + "//base/util/memory_pressure", "//chrome/app/vector_icons", "//chrome/browser/policy:path_parser", "//chrome/browser/profile_resetter:profile_reset_report_proto", @@ -3492,6 +3590,7 @@ jumbo_split_static_library("browser") { "//components/image_fetcher/core", "//components/keep_alive_registry", "//components/ntp_snippets", + "//components/services/app_service/public/cpp:app_file_handling", "//components/vector_icons", "//components/web_modal", "//components/zoom", @@ -3516,6 +3615,8 @@ jumbo_split_static_library("browser") { "apps/app_service/arc_apps.h", "apps/app_service/arc_apps_factory.cc", "apps/app_service/arc_apps_factory.h", + "apps/app_service/arc_icon_once_loader.cc", + "apps/app_service/arc_icon_once_loader.h", "apps/app_service/built_in_chromeos_apps.cc", "apps/app_service/built_in_chromeos_apps.h", "apps/app_service/crostini_apps.cc", @@ -3566,6 +3667,8 @@ jumbo_split_static_library("browser") { "metrics/perf/heap_collector.h", "metrics/perf/metric_collector.cc", "metrics/perf/metric_collector.h", + "metrics/perf/metric_provider.cc", + "metrics/perf/metric_provider.h", "metrics/perf/perf_events_collector.cc", "metrics/perf/perf_events_collector.h", "metrics/perf/perf_output.cc", @@ -3599,6 +3702,8 @@ jumbo_split_static_library("browser") { "sync/sync_error_notifier_ash.h", "sync/sync_error_notifier_factory_ash.cc", "sync/sync_error_notifier_factory_ash.h", + "sync/wifi_configuration_sync_service_factory.cc", + "sync/wifi_configuration_sync_service_factory.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", @@ -3618,18 +3723,16 @@ jumbo_split_static_library("browser") { "//chrome/services/cups_proxy", "//chrome/services/cups_proxy/public/mojom", "//chromeos/components/account_manager", + "//chromeos/components/sync_wifi", "//chromeos/services/assistant/public:feature_flags", "//chromeos/services/assistant/public/cpp:prefs", "//chromeos/services/cellular_setup", - "//chromeos/services/device_sync", "//chromeos/services/device_sync/public/mojom", - "//chromeos/services/ime/public/mojom", "//chromeos/services/multidevice_setup", "//chromeos/services/multidevice_setup/public/cpp:first_run_field_trial", "//chromeos/services/multidevice_setup/public/mojom", "//chromeos/services/network_config", "//chromeos/services/network_config/public/mojom", - "//chromeos/services/secure_channel", "//chromeos/services/secure_channel/public/mojom", "//chromeos/strings", "//components/services/font:lib", @@ -3675,9 +3778,10 @@ jumbo_split_static_library("browser") { "browser_switcher/browser_switcher_policy_migrator.h", "browser_switcher/browser_switcher_service_win.cc", "browser_switcher/browser_switcher_service_win.h", + "downgrade/downgrade_manager.cc", + "downgrade/downgrade_manager.h", "downgrade/user_data_downgrade.cc", "downgrade/user_data_downgrade.h", - "first_run/upgrade_util.cc", "notifications/win/notification_image_retainer.cc", "notifications/win/notification_image_retainer.h", "notifications/win/notification_template_builder.cc", @@ -3696,11 +3800,9 @@ jumbo_split_static_library("browser") { ] deps += [ ":chrome_process_finder", - "//chrome:file_pre_reader", "//chrome/browser/safe_browsing/chrome_cleaner", "//chrome/browser/safe_browsing/chrome_cleaner:public", "//chrome/browser/win/conflicts:module_info", - "//chrome/chrome_elf:blacklist", "//chrome/chrome_elf:constants", "//chrome/chrome_elf:dll_hash", "//chrome/chrome_watcher:client", @@ -3741,6 +3843,10 @@ jumbo_split_static_library("browser") { ] } + if (is_multi_dll_chrome) { + defines += [ "CHROME_MULTIPLE_DLL_BROWSER" ] + } + if (is_chrome_branded) { deps += [ "//chrome/browser/win/conflicts:module_list_proto", @@ -3835,18 +3941,28 @@ jumbo_split_static_library("browser") { deps += [ "//ui/gfx/x" ] } deps += [ "//services/service_manager/zygote" ] + + if (use_allocator == "tcmalloc") { + deps += [ "//chrome/common/performance_manager/mojom" ] + + sources += [ + "performance_manager/graph/policies/dynamic_tcmalloc_policy_linux.cc", + "performance_manager/graph/policies/dynamic_tcmalloc_policy_linux.h", + ] + } } if (is_desktop_linux) { # Desktop linux, doesn't count ChromeOS. sources += [ - "first_run/upgrade_util.cc", "first_run/upgrade_util_linux.cc", "first_run/upgrade_util_linux.h", "icon_loader_auralinux.cc", "platform_util_linux.cc", "shell_integration_linux.cc", "shell_integration_linux.h", + "themes/theme_service_aura_linux.cc", + "themes/theme_service_aura_linux.h", ] if (use_dbus) { @@ -3864,14 +3980,6 @@ jumbo_split_static_library("browser") { sources += [ "fullscreen_aurax11.cc", "media/webrtc/window_icon_util_x11.cc", - - # ThemeServiceAuraX11 does not depend on X11, although its - # instantiation/inclusion in theme_service_factory.cc is conditioned - # by USE_X11. - # TODO(tonikitoo): Check if non-x11 could benefit from it. If so, - # rename and use it. - "themes/theme_service_aurax11.cc", - "themes/theme_service_aurax11.h", ] } @@ -3956,6 +4064,12 @@ jumbo_split_static_library("browser") { if (!is_android && !is_chromeos) { sources += [ + "first_run/upgrade_util.cc", + "first_run/upgrade_util.h", + "first_run/upgrade_util_mac.h", + "first_run/upgrade_util_mac.mm", + "first_run/upgrade_util_win.cc", + "first_run/upgrade_util_win.h", "lifetime/switch_utils.cc", "lifetime/switch_utils.h", "metrics/upgrade_metrics_provider.cc", @@ -4043,6 +4157,10 @@ jumbo_split_static_library("browser") { "payments/payment_request_display_manager_factory.h", "payments/payment_request_factory.cc", "payments/payment_request_factory.h", + "sync/sync_clipboard_service.cc", + "sync/sync_clipboard_service.h", + "sync/sync_clipboard_service_factory.cc", + "sync/sync_clipboard_service_factory.h", ] deps += [ "//components/payments/content" ] } @@ -4147,6 +4265,7 @@ jumbo_split_static_library("browser") { ] deps += [ "//components/printing/browser", + "//components/services/pdf_compositor/public/cpp", "//components/services/pdf_compositor/public/mojom", "//printing", ] @@ -4188,6 +4307,8 @@ jumbo_split_static_library("browser") { "printing/print_preview_message_handler.h", "printing/print_view_manager.cc", "printing/print_view_manager.h", + "printing/printing_service.cc", + "printing/printing_service.h", "printing/pwg_raster_converter.cc", "printing/pwg_raster_converter.h", ] @@ -4229,8 +4350,6 @@ jumbo_split_static_library("browser") { "captive_portal/captive_portal_tab_helper.h", "captive_portal/captive_portal_tab_reloader.cc", "captive_portal/captive_portal_tab_reloader.h", - "component_updater/ssl_error_assistant_component_installer.cc", - "component_updater/ssl_error_assistant_component_installer.h", "ssl/captive_portal_metrics_recorder.cc", "ssl/captive_portal_metrics_recorder.h", ] @@ -4462,7 +4581,6 @@ jumbo_split_static_library("browser") { # TODO(loyso): Erase these. crbug.com/877898. "//chrome/browser/web_applications:web_applications_on_extensions", - "//chrome/browser/web_applications/bookmark_apps", "//chrome/browser/web_applications/components", "//chrome/browser/web_applications/extensions", ] @@ -4471,7 +4589,6 @@ jumbo_split_static_library("browser") { "//chrome/browser/sync_file_system/drive_backend:sync_file_system_drive_proto", "//chrome/browser/web_applications", "//chrome/browser/web_applications:web_applications_on_extensions", - "//chrome/browser/web_applications/bookmark_apps", "//chrome/browser/web_applications/components", "//chrome/browser/web_applications/extensions", "//chrome/common/extensions/api", @@ -4516,7 +4633,7 @@ jumbo_split_static_library("browser") { "media/output_protection_impl.cc", "media/output_protection_impl.h", ] - deps += [ "//media/mojo/interfaces" ] + deps += [ "//media/mojo/mojom" ] if (enable_widevine) { if (enable_widevine_cdm_component) { @@ -4549,7 +4666,7 @@ jumbo_split_static_library("browser") { if (mojo_media_host == "browser") { deps += [ - "//media/mojo/interfaces:constants", + "//media/mojo/mojom:constants", "//media/mojo/services", ] } @@ -4807,7 +4924,7 @@ jumbo_split_static_library("browser") { ] public_deps += [ - "//components/google/core/browser", + "//components/google/core/common", "//components/rlz", "//rlz:rlz_lib", ] @@ -4897,17 +5014,6 @@ jumbo_split_static_library("browser") { ] } - if (enable_simple_browser_service_in_process) { - deps += [ - "//services/content/simple_browser", - "//services/content/simple_browser/public/mojom", - ] - } - - if (enable_simple_browser_service_out_of_process) { - deps += [ "//services/content/simple_browser/public/mojom" ] - } - if (enable_spellcheck) { sources += [ "spellchecker/spell_check_host_chrome_impl.cc", @@ -5315,6 +5421,27 @@ if (is_chrome_branded) { } } +action("expired_flags_list_gen") { + script = "//tools/flags/generate_expired_list.py" + sources = [ + "flag-metadata.json", + ] + outputs = [ + "$root_gen_dir/chrome/browser/expired_flags_list.cc", + ] + args = rebase_path(sources, root_build_dir) + + rebase_path(outputs, root_build_dir) +} + +source_set("expired_flags_list") { + deps = [ + ":expired_flags_list_gen", + ] + sources = [ + "$root_gen_dir/chrome/browser/expired_flags_list.cc", + ] +} + # Use a static library here because many test binaries depend on this but don't # require many files from it. This makes linking more efficient. static_library("test_support") { @@ -5360,6 +5487,8 @@ static_library("test_support") { "history/history_test_utils.h", "installable/fake_installable_manager.cc", "installable/fake_installable_manager.h", + "lookalikes/safety_tips/safety_tip_test_utils.cc", + "lookalikes/safety_tips/safety_tip_test_utils.h", "media/webrtc/fake_desktop_media_list.cc", "media/webrtc/fake_desktop_media_list.h", "media/webrtc/fake_desktop_media_picker_factory.cc", @@ -5390,6 +5519,8 @@ static_library("test_support") { "search_engines/template_url_service_test_util.h", "signin/chrome_signin_client_test_util.cc", "signin/chrome_signin_client_test_util.h", + "signin/e2e_tests/test_accounts_util.cc", + "signin/e2e_tests/test_accounts_util.h", "signin/identity_test_environment_profile_adaptor.cc", "signin/identity_test_environment_profile_adaptor.h", "signin/scoped_account_consistency.cc", @@ -5398,6 +5529,8 @@ static_library("test_support") { "ssl/ssl_client_auth_requestor_mock.h", "subresource_filter/test_ruleset_publisher.cc", "subresource_filter/test_ruleset_publisher.h", + "translate/translate_test_utils.cc", + "translate/translate_test_utils.h", ] configs += [ "//build/config:precompiled_headers" ] @@ -5420,6 +5553,7 @@ static_library("test_support") { "//components/prefs:test_support", "//components/safe_browsing:csd_proto", "//components/search_engines:test_support", + "//components/services/unzip/content", "//components/sessions:test_support", "//components/signin/public/identity_manager:test_support", "//components/subresource_filter/core/browser:test_support", @@ -5581,6 +5715,7 @@ static_library("test_support") { ] deps += [ "//components/drive:test_support", + "//components/services/unzip:in_process", "//components/storage_monitor:test_support", "//extensions:test_support", "//google_apis:test_support", @@ -5623,10 +5758,10 @@ static_library("test_support") { if (has_spellcheck_panel) { sources += [ - "spellchecker/test/spellcheck_content_browser_client.cc", - "spellchecker/test/spellcheck_content_browser_client.h", "spellchecker/test/spellcheck_mock_panel_host.cc", "spellchecker/test/spellcheck_mock_panel_host.h", + "spellchecker/test/spellcheck_panel_browsertest_helper.cc", + "spellchecker/test/spellcheck_panel_browsertest_helper.h", ] } } @@ -5667,3 +5802,21 @@ if (!is_android) { ] } } + +if (is_android) { + java_cpp_enum("sharing_device_capability_generated_enum") { + sources = [ + "sharing/sharing_device_capability.h", + ] + } + java_cpp_enum("sharing_send_message_result_generated_enum") { + sources = [ + "sharing/sharing_send_message_result.h", + ] + } + java_cpp_enum("sharing_dialog_type_generated_enum") { + sources = [ + "sharing/sharing_metrics.h", + ] + } +} diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api.cc b/chromium/chrome/browser/accessibility/accessibility_extension_api.cc index 55e9b36fc5f..d35dd345c61 100644 --- a/chromium/chrome/browser/accessibility/accessibility_extension_api.cc +++ b/chromium/chrome/browser/accessibility/accessibility_extension_api.cc @@ -20,7 +20,6 @@ #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/common/extensions/api/accessibility_private.h" #include "chrome/common/extensions/extension_constants.h" @@ -45,7 +44,7 @@ #include "ash/public/cpp/accessibility_focus_ring_info.h" #include "ash/public/cpp/event_rewriter_controller.h" #include "ash/public/cpp/window_tree_host_lookup.h" -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/mojom/constants.mojom.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/chromeos/arc/accessibility/arc_accessibility_helper_bridge.h" #include "ui/aura/window_tree_host.h" @@ -92,8 +91,6 @@ AccessibilityPrivateOpenSettingsSubpageFunction::Run() { if (chrome::IsOSSettingsSubPage(params->subpage)) { chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( profile, params->subpage); - } else { - chrome::ShowSettingsSubPageForProfile(profile, params->subpage); } #else // This function should only be available on ChromeOS. @@ -240,18 +237,6 @@ AccessibilityPrivateDarkenScreenFunction::Run() { #if defined(OS_CHROMEOS) ExtensionFunction::ResponseAction -AccessibilityPrivateSetSwitchAccessKeysFunction::Run() { - std::unique_ptr<accessibility_private::SetSwitchAccessKeys::Params> params = - accessibility_private::SetSwitchAccessKeys::Params::Create(*args_); - EXTENSION_FUNCTION_VALIDATE(params); - - ash::AccessibilityController::Get()->SetSwitchAccessKeysToCapture( - params->key_codes); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction AccessibilityPrivateSetNativeChromeVoxArcSupportForCurrentAppFunction::Run() { std::unique_ptr< accessibility_private::SetNativeChromeVoxArcSupportForCurrentApp::Params> diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api.h b/chromium/chrome/browser/accessibility/accessibility_extension_api.h index 0d21dd303dc..4f195349f66 100644 --- a/chromium/chrome/browser/accessibility/accessibility_extension_api.h +++ b/chromium/chrome/browser/accessibility/accessibility_extension_api.h @@ -14,7 +14,7 @@ // API function that enables or disables web content accessibility support. class AccessibilityPrivateSetNativeAccessibilityEnabledFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSetNativeAccessibilityEnabledFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION( @@ -23,8 +23,7 @@ class AccessibilityPrivateSetNativeAccessibilityEnabledFunction }; // API function that sets the location of the accessibility focus ring. -class AccessibilityPrivateSetFocusRingsFunction - : public UIThreadExtensionFunction { +class AccessibilityPrivateSetFocusRingsFunction : public ExtensionFunction { ~AccessibilityPrivateSetFocusRingsFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setFocusRings", @@ -32,8 +31,7 @@ class AccessibilityPrivateSetFocusRingsFunction }; // API function that sets the location of the accessibility highlights. -class AccessibilityPrivateSetHighlightsFunction - : public UIThreadExtensionFunction { +class AccessibilityPrivateSetHighlightsFunction : public ExtensionFunction { ~AccessibilityPrivateSetHighlightsFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setHighlights", @@ -42,7 +40,7 @@ class AccessibilityPrivateSetHighlightsFunction // API function that sets keyboard capture mode. class AccessibilityPrivateSetKeyboardListenerFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSetKeyboardListenerFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setKeyboardListener", @@ -50,8 +48,7 @@ class AccessibilityPrivateSetKeyboardListenerFunction }; // API function that darkens or undarkens the screen. -class AccessibilityPrivateDarkenScreenFunction - : public UIThreadExtensionFunction { +class AccessibilityPrivateDarkenScreenFunction : public ExtensionFunction { ~AccessibilityPrivateDarkenScreenFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.darkenScreen", @@ -60,7 +57,7 @@ class AccessibilityPrivateDarkenScreenFunction // Opens a specified subpage in Chrome settings. class AccessibilityPrivateOpenSettingsSubpageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateOpenSettingsSubpageFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.openSettingsSubpage", @@ -68,18 +65,9 @@ class AccessibilityPrivateOpenSettingsSubpageFunction }; #if defined(OS_CHROMEOS) -// API function that sets the keys to be captured by Switch Access. -class AccessibilityPrivateSetSwitchAccessKeysFunction - : public UIThreadExtensionFunction { - ~AccessibilityPrivateSetSwitchAccessKeysFunction() override {} - ResponseAction Run() override; - DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setSwitchAccessKeys", - ACCESSIBILITY_PRIVATE_SETSWITCHACCESSKEYS) -}; - // API function that sets native ChromeVox ARC support. class AccessibilityPrivateSetNativeChromeVoxArcSupportForCurrentAppFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSetNativeChromeVoxArcSupportForCurrentAppFunction() override {} ResponseAction Run() override; @@ -90,7 +78,7 @@ class AccessibilityPrivateSetNativeChromeVoxArcSupportForCurrentAppFunction // API function that injects key events. class AccessibilityPrivateSendSyntheticKeyEventFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSendSyntheticKeyEventFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.sendSyntheticKeyEvent", @@ -99,7 +87,7 @@ class AccessibilityPrivateSendSyntheticKeyEventFunction // API function that enables or disables mouse events in ChromeVox. class AccessibilityPrivateEnableChromeVoxMouseEventsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateEnableChromeVoxMouseEventsFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.enableChromeVoxMouseEvents", @@ -108,7 +96,7 @@ class AccessibilityPrivateEnableChromeVoxMouseEventsFunction // API function that injects mouse events. class AccessibilityPrivateSendSyntheticMouseEventFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSendSyntheticMouseEventFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.sendSyntheticMouseEvent", @@ -117,7 +105,7 @@ class AccessibilityPrivateSendSyntheticMouseEventFunction // API function that is called when the Select-to-Speak extension state changes. class AccessibilityPrivateOnSelectToSpeakStateChangedFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateOnSelectToSpeakStateChangedFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.onSelectToSpeakStateChanged", @@ -127,7 +115,7 @@ class AccessibilityPrivateOnSelectToSpeakStateChangedFunction // API function that is called when the Autoclick extension finds scrollable // bounds. class AccessibilityPrivateOnScrollableBoundsForPointFoundFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateOnScrollableBoundsForPointFoundFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION( @@ -137,8 +125,7 @@ class AccessibilityPrivateOnScrollableBoundsForPointFoundFunction // API function that is called when a user toggles Dictation from another // acessibility feature. -class AccessibilityPrivateToggleDictationFunction - : public UIThreadExtensionFunction { +class AccessibilityPrivateToggleDictationFunction : public ExtensionFunction { ~AccessibilityPrivateToggleDictationFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.toggleDictation", @@ -147,7 +134,7 @@ class AccessibilityPrivateToggleDictationFunction // API function that is called to show or hide the Switch Access menu. class AccessibilityPrivateSetSwitchAccessMenuStateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSetSwitchAccessMenuStateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setSwitchAccessMenuState", @@ -157,7 +144,7 @@ class AccessibilityPrivateSetSwitchAccessMenuStateFunction // API function that requests that key events be forwarded to the Switch // Access extension. class AccessibilityPrivateForwardKeyEventsToSwitchAccessFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateForwardKeyEventsToSwitchAccessFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION( @@ -167,7 +154,7 @@ class AccessibilityPrivateForwardKeyEventsToSwitchAccessFunction // API function that is called to get the device's battery status as a string. class AccessibilityPrivateGetBatteryDescriptionFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: AccessibilityPrivateGetBatteryDescriptionFunction(); ResponseAction Run() override; @@ -180,7 +167,7 @@ class AccessibilityPrivateGetBatteryDescriptionFunction // API function that opens or closes the virtual keyboard. class AccessibilityPrivateSetVirtualKeyboardVisibleFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~AccessibilityPrivateSetVirtualKeyboardVisibleFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setVirtualKeyboardVisible", diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc b/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc index 68771079c80..e5d387f926c 100644 --- a/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc +++ b/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc @@ -5,6 +5,7 @@ #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/system_web_app_manager.h" @@ -51,7 +52,7 @@ IN_PROC_BROWSER_TEST_F(AccessibilityPrivateApiTest, OpenSettingsSubpage) { WaitForLoadStop(web_contents); - EXPECT_EQ(GURL("chrome://settings/manageAccessibility/tts"), + EXPECT_EQ(GURL(chrome::GetOSSettingsUrl("manageAccessibility/tts")), web_contents->GetLastCommittedURL()); } @@ -71,15 +72,9 @@ IN_PROC_BROWSER_TEST_F(AccessibilityPrivateApiTest, chrome::SettingsWindowManager* settings_manager = chrome::SettingsWindowManager::GetInstance(); + // Invalid subpage should not open settings window. Browser* settings_browser = settings_manager->FindBrowserForProfile(profile); - EXPECT_NE(nullptr, settings_browser); - - content::WebContents* web_contents = - settings_browser->tab_strip_model()->GetWebContentsAt(0); - - WaitForLoadStop(web_contents); - - EXPECT_EQ(GURL("chrome://settings"), web_contents->GetLastCommittedURL()); + EXPECT_EQ(nullptr, settings_browser); } } // namespace extensions diff --git a/chromium/chrome/browser/accessibility/accessibility_ui.cc b/chromium/chrome/browser/accessibility/accessibility_ui.cc index 739b7d8f3d3..efa616a3309 100644 --- a/chromium/chrome/browser/accessibility/accessibility_ui.cc +++ b/chromium/chrome/browser/accessibility/accessibility_ui.cc @@ -256,7 +256,7 @@ AccessibilityUI::AccessibilityUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUIAccessibilityHost); // Add required resources. - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("accessibility.css", IDR_ACCESSIBILITY_CSS); html_source->AddResourcePath("accessibility.js", IDR_ACCESSIBILITY_JS); html_source->SetDefaultResource(IDR_ACCESSIBILITY_HTML); diff --git a/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc b/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc index aef787a1068..acbbe5111fc 100644 --- a/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc +++ b/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc @@ -26,8 +26,9 @@ void CaptionSettingsDialogCallback() { namespace captions { void CaptionSettingsDialog::ShowCaptionSettingsDialog() { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(CaptionSettingsDialogCallback)); } diff --git a/chromium/chrome/browser/android/vr/BUILD.gn b/chromium/chrome/browser/android/vr/BUILD.gn index 3deba2912d9..03fba1b35e0 100644 --- a/chromium/chrome/browser/android/vr/BUILD.gn +++ b/chromium/chrome/browser/android/vr/BUILD.gn @@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/android/rules.gni") +import("//chrome/android/modules/buildflags.gni") import("//chrome/common/features.gni") import("//device/vr/buildflags/buildflags.gni") import("//testing/test.gni") @@ -179,27 +180,23 @@ source_set("ui_module_factory") { ] } -# Similar to the ui_default_factory but also tries to open a dummy lib for the -# purpose of exercising the library loading mechanism. -source_set("ui_module_dummy_factory") { - sources = [ - "ui_module_dummy_factory.cc", - "ui_module_dummy_factory.h", - ] - deps = [ - ":ui_factory", - "//chrome/browser/vr:vr_base", - "//chrome/browser/vr:vr_ui", - ] -} - -# A dummy lib used to test the library loading mechanism. -loadable_module("vr_ui_dummy_lib") { - sources = [ - "ui_dummy.cc", - "ui_dummy.h", - ] - no_default_deps = true +# A top-level module factory target to be included by Chrome's main library +# target. Ideally, this would be pulled in by vr_android. However, vr_android +# is a dep of both Chrome and VR unit tests, and unit tests always require the +# non-module version of the factory. As such, vr_android doesn't know which +# factory it needs to use. The fact that vr_android has an implicity circular +# dependency on chrome/browser precludes the use of an intermediate target (eg. +# vr_android_with_factory). +group("module_factory") { + if (use_native_modules && modularize_vr_native) { + deps = [ + ":ui_module_factory", + ] + } else { + deps = [ + ":ui_default_factory", + ] + } } android_library("ar_java") { diff --git a/chromium/chrome/browser/apps/app_shim/BUILD.gn b/chromium/chrome/browser/apps/app_shim/BUILD.gn index bcc8043ddf0..ee6922e2f67 100644 --- a/chromium/chrome/browser/apps/app_shim/BUILD.gn +++ b/chromium/chrome/browser/apps/app_shim/BUILD.gn @@ -6,16 +6,14 @@ # communicating with app_shim processes on Mac. source_set("app_shim") { sources = [ - "app_shim_handler_mac.cc", - "app_shim_handler_mac.h", "app_shim_host_bootstrap_mac.cc", "app_shim_host_bootstrap_mac.h", "app_shim_host_mac.cc", "app_shim_host_mac.h", - "app_shim_host_manager_mac.h", - "app_shim_host_manager_mac.mm", - "apps_page_shim_handler.h", - "apps_page_shim_handler.mm", + "app_shim_listener.h", + "app_shim_listener.mm", + "app_shim_termination_manager.cc", + "app_shim_termination_manager.h", "extension_app_shim_handler_mac.cc", "extension_app_shim_handler_mac.h", "mach_bootstrap_acceptor.cc", diff --git a/chromium/chrome/browser/browser_resources.grd b/chromium/chrome/browser/browser_resources.grd index c0cef303f4a..87c529bf393 100644 --- a/chromium/chrome/browser/browser_resources.grd +++ b/chromium/chrome/browser/browser_resources.grd @@ -137,28 +137,6 @@ <include name="IDR_ACCESSIBILITY_CSS" file="resources\accessibility\accessibility.css" compress="gzip" type="BINDATA" /> <include name="IDR_ACCESSIBILITY_JS" file="resources\accessibility\accessibility.js" flattenhtml="true" compress="gzip" type="BINDATA" /> <include name="IDR_AD_NETWORK_HASHES" file="resources\ad_networks.dat" type="BINDATA" /> - <include name="IDR_BLUETOOTH_ADAPTER_MOJO_JS" file="${root_gen_dir}\device\bluetooth\public\mojom\adapter.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_DEVICE_MOJO_JS" file="${root_gen_dir}\device\bluetooth\public\mojom\device.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_UUID_MOJO_JS" file="${root_gen_dir}\device\bluetooth\public\mojom\uuid.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_CSS" file="resources\bluetooth_internals\bluetooth_internals.css" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_BROKER_JS" file="resources\bluetooth_internals\adapter_broker.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_PAGE_JS" file="resources\bluetooth_internals\adapter_page.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_CHARACTERISTIC_LIST_JS" file="resources\bluetooth_internals\characteristic_list.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_DESCRIPTOR_LIST_JS" file="resources\bluetooth_internals\descriptor_list.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_BROKER_JS" file="resources\bluetooth_internals\device_broker.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_COLLECTION_JS" file="resources\bluetooth_internals\device_collection.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_DETAILS_PAGE_JS" file="resources\bluetooth_internals\device_details_page.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_TABLE_JS" file="resources\bluetooth_internals\device_table.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_DEVICES_PAGE_JS" file="resources\bluetooth_internals\devices_page.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_EXPANDABLE_LIST_JS" file="resources\bluetooth_internals\expandable_list.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_HTML" file="resources\bluetooth_internals\bluetooth_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_JS" file="resources\bluetooth_internals\bluetooth_internals.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\bluetooth_internals\bluetooth_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_OBJECT_FIELDSET_JS" file="resources\bluetooth_internals\object_fieldset.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_SERVICE_LIST_JS" file="resources\bluetooth_internals\service_list.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_SIDEBAR_JS" file="resources\bluetooth_internals\sidebar.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_SNACKBAR_JS" file="resources\bluetooth_internals\snackbar.js" type="BINDATA" compress="gzip" /> - <include name="IDR_BLUETOOTH_INTERNALS_VALUE_CONTROL_JS" file="resources\bluetooth_internals\value_control.js" type="BINDATA" compress="gzip" /> <if expr="is_posix and not is_macosx"> <include name="IDR_CERTIFICATE_VIEWER_HTML" file="resources\certificate_viewer.html" type="BINDATA" /> <include name="IDR_CERTIFICATE_VIEWER_JS" file="resources\certificate_viewer.js" type="BINDATA" /> @@ -209,10 +187,16 @@ <include name="IDR_SNIPPETS_INTERNALS_CSS" file="resources\snippets_internals\snippets_internals.css" compress="gzip" type="BINDATA" /> <include name="IDR_SNIPPETS_INTERNALS_JS" file="resources\snippets_internals\snippets_internals.js" compress="gzip" type="BINDATA" /> <include name="IDR_SNIPPETS_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\snippets_internals\snippets_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> + <part file="resources/dev_ui_loader/dev_ui_loader.grdp" /> </if> - <include name="IDR_SUPERVISED_USER_INTERNALS_HTML" file="resources\supervised_user_internals\supervised_user_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" /> - <include name="IDR_SUPERVISED_USER_INTERNALS_CSS" file="resources\supervised_user_internals\supervised_user_internals.css" compress="gzip" type="BINDATA" /> - <include name="IDR_SUPERVISED_USER_INTERNALS_JS" file="resources\supervised_user_internals\supervised_user_internals.js" compress="gzip" type="BINDATA" /> + + <if expr="enable_supervised_users"> + <include name="IDR_SUPERVISED_USER_INTERNALS_HTML" file="resources\supervised_user_internals\supervised_user_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" /> + <include name="IDR_SUPERVISED_USER_INTERNALS_CSS" file="resources\supervised_user_internals\supervised_user_internals.css" compress="gzip" type="BINDATA" /> + <include name="IDR_SUPERVISED_USER_INTERNALS_JS" file="resources\supervised_user_internals\supervised_user_internals.js" compress="gzip" type="BINDATA" /> + <part file="resources/supervised_user_error_page_resources.grdp" /> + </if> + <if expr="enable_hangout_services_extension"> <!-- Hangout Services extension, included in Google Chrome builds only. --> <include name="IDR_HANGOUT_SERVICES_MANIFEST" file="resources\hangout_services\manifest.json" type="BINDATA" /> @@ -220,68 +204,17 @@ <!-- App Management. --> <if expr="not is_android"> - <include name="IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\interfaces\bitmap.mojom-lite.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\interfaces\image_info.mojom-lite.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS" file="${root_gen_dir}\ui\gfx\image\mojo\image.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\mojom\bitmap.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\mojom\image_info.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS" file="${root_gen_dir}\ui\gfx\image\mojom\image.mojom-lite.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\app_management\app_management.mojom-lite.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS" file="${root_gen_dir}\chrome\services\app_service\public\mojom\types.mojom-lite.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_ACTIONS_HTML" file="resources\app_management\actions.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_ACTIONS_JS" file="resources\app_management\actions.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_API_LISTENER_HTML" file="resources\app_management\api_listener.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_API_LISTENER_JS" file="resources\app_management\api_listener.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_APP_HTML" file="resources\app_management\app.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_APP_ITEM_HTML" file="resources\app_management\app_item.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_APP_ITEM_JS" file="resources\app_management\app_item.js" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_APP_JS" file="resources\app_management\app.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_HTML" file="resources\app_management\arc_permission_view.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_JS" file="resources\app_management\arc_permission_view.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML" file="resources\app_management\browser_proxy.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_JS" file="resources\app_management\browser_proxy.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_HTML" file="resources\app_management\chrome_app_permission_view.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS" file="resources\app_management\chrome_app_permission_view.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_CONSTANTS_HTML" file="resources\app_management\constants.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_CONSTANTS_JS" file="resources\app_management\constants.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_DOM_SWITCH_HTML" file="resources\app_management\dom_switch.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_DOM_SWITCH_JS" file="resources\app_management\dom_switch.js" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_HTML" file="resources\app_management\expandable_app_list.html" type="BINDATA"/> <include name="IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_JS" file="resources\app_management\expandable_app_list.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS" file="resources\app_management\fake_page_handler.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_ICONS_HTML" file="resources\app_management\icons.html" type="BINDATA" /> <include name="IDR_APP_MANAGEMENT_INDEX_HTML" file="resources\app_management\index.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_MAIN_VIEW_HTML" file="resources\app_management\main_view.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_MAIN_VIEW_JS" file="resources\app_management\main_view.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_METADATA_VIEW_HTML" file="resources\app_management\metadata_view.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_METADATA_VIEW_JS" file="resources\app_management\metadata_view.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_HTML" file="resources\app_management\notifications_view.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_JS" file="resources\app_management\notifications_view.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PERMISSION_ITEM_HTML" file="resources\app_management\permission_item.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PERMISSION_ITEM_JS" file="resources\app_management\permission_item.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_HTML" file="resources\app_management\permission_toggle.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_JS" file="resources\app_management\permission_toggle.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML" file="resources\app_management\permission_view_header.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS" file="resources\app_management\permission_view_header.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML" file="resources\app_management\pin_to_shelf_item.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS" file="resources\app_management\pin_to_shelf_item.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML" file="resources\app_management\pwa_permission_view.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_JS" file="resources\app_management\pwa_permission_view.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_REDUCERS_HTML" file="resources\app_management\reducers.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_REDUCERS_JS" file="resources\app_management\reducers.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_ROUTER_HTML" file="resources\app_management\router.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_ROUTER_JS" file="resources\app_management\router.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_SEARCH_VIEW_HTML" file="resources\app_management\search_view.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_SEARCH_VIEW_JS" file="resources\app_management\search_view.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_SHARED_STYLE_HTML" file="resources\app_management\shared_style.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_SHARED_VARS_HTML" file="resources\app_management\shared_vars.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_STORE_CLIENT_HTML" file="resources\app_management\store_client.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_STORE_CLIENT_JS" file="resources\app_management\store_client.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_STORE_HTML" file="resources\app_management\store.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_STORE_JS" file="resources\app_management\store.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML" file="resources\app_management\toggle_row.html" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_TOGGLE_ROW_JS" file="resources\app_management\toggle_row.js" type="BINDATA"/> - <include name="IDR_APP_MANAGEMENT_TYPES_JS" file="resources\app_management\types.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_UTIL_HTML" file="resources\app_management\util.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_UTIL_JS" file="resources\app_management\util.js" type="BINDATA" /> </if> <if expr="not is_android"> @@ -334,8 +267,8 @@ </if> <include name="IDR_IDENTITY_API_SCOPE_APPROVAL_MANIFEST" file="resources\identity_scope_approval_dialog\manifest.json" type="BINDATA" /> - <include name="IDR_INLINE_LOGIN_HTML" file="resources\inline_login\inline_login.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - <include name="IDR_INLINE_LOGIN_CSS" file="resources\inline_login\inline_login.css" flattenhtml="true" type="BINDATA" /> + <include name="IDR_INLINE_LOGIN_HTML" file="resources\inline_login\inline_login.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" preprocess="true" /> + <include name="IDR_INLINE_LOGIN_CSS" file="resources\inline_login\inline_login.css" flattenhtml="true" type="BINDATA" preprocess="true" /> <include name="IDR_INLINE_LOGIN_JS" file="resources\inline_login\inline_login.js" flattenhtml="true" type="BINDATA" /> <include name="IDR_GAIA_AUTH_AUTHENTICATOR_JS" file="resources\gaia_auth_host\authenticator.js" flattenhtml="true" type="BINDATA" /> <include name="IDR_INSPECT_CSS" file="resources\inspect\inspect.css" flattenhtml="true" type="BINDATA" /> @@ -427,6 +360,7 @@ <include name="IDR_USB_INTERNALS_HTML" file="resources\usb_internals\usb_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" /> <include name="IDR_USB_INTERNALS_JS" file="resources\usb_internals\usb_internals.js" type="BINDATA" compress="gzip" /> <include name="IDR_USB_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\usb_internals\usb_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> + <include name="IDR_WEB_FOOTER_EXPERIMENT_HTML" file="resources\web_footer_experiment\index.html" type="BINDATA" /> <include name="IDR_WEBRTC_LOGS_HTML" file="resources\media\webrtc_logs.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_WEBRTC_LOGS_JS" file="resources\media\webrtc_logs.js" type="BINDATA" /> <include name="IDR_WEBSTORE_MANIFEST" file="resources\webstore_app\manifest.json" type="BINDATA" /> @@ -509,10 +443,6 @@ <include name="IDR_QUICKOFFICE_MANIFEST" file="resources\chromeos\quickoffice\manifest.json" type="BINDATA" /> <include name="IDR_PRODUCT_CHROMEOS_SYNC_CONSENT_SCREEN_ICONS" file="internal\resources\chromeos-sync-consent-icons.html" type="BINDATA" /> </if> - <if expr="is_win"> - <include name="IDR_SET_AS_DEFAULT_BROWSER_JS" file="resources\set_as_default_browser.js" flattenhtml="true" type="BINDATA" /> - <include name="IDR_SET_AS_DEFAULT_BROWSER_HTML" file="resources\set_as_default_browser.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - </if> <if expr="not is_android and not chromeos"> <include name="IDR_CONTROL_BAR_HTML" file="resources\user_manager\control_bar.html" type="BINDATA" /> <include name="IDR_CONTROL_BAR_JS" file="resources\user_manager\control_bar.js" type="BINDATA" /> @@ -623,9 +553,7 @@ </if> <if expr="chromeos or is_win or is_macosx"> <include name="IDR_CAST_HTML" file="resources\cast\cast.html" type="BINDATA" /> - <include name="IDR_CAST_CSS" file="resources\cast\cast.css" type="BINDATA" /> <include name="IDR_CAST_JS" file="resources\cast\cast.js" type="BINDATA" /> - <include name="IDR_CAST_FAVICON" file="resources\cast\cast_favicon.ico" type="BINDATA" /> </if> <if expr="not is_android"> <include name="IDR_IME_WINDOW_CLOSE" file="resources\input_ime\ime_window_close.png" type="BINDATA" /> @@ -677,10 +605,12 @@ </if> <if expr="not is_android"> <include name="IDR_TAB_RANKER_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="resource_coordinator\tab_ranker\example_preprocessor_config.pb" type="BINDATA" /> + <include name="IDR_TAB_RANKER_PAIRWISE_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="resource_coordinator\tab_ranker\pairwise_preprocessor_config.pb" type="BINDATA" /> </if> <if expr="chromeos"> <include name="IDR_SMART_DIM_20181115_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="chromeos\power\ml\smart_dim\20181115_example_preprocessor_config.pb" type="BINDATA" /> <include name="IDR_SMART_DIM_20190221_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="chromeos\power\ml\smart_dim\20190221_example_preprocessor_config.pb" type="BINDATA" /> + <include name="IDR_TOP_CAT_20190722_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="ui\app_list\search\search_result_ranker\20190722_example_preprocessor_config.pb" type="BINDATA" /> </if> <if expr="chromeos"> <include name="IDR_ARC_GRAPHICS_TRACING_HTML" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing.html" compress="gzip" type="BINDATA"/> diff --git a/chromium/chrome/browser/browser_switcher/bho/BUILD.gn b/chromium/chrome/browser/browser_switcher/bho/BUILD.gn index f81f61e2282..05568aea2cd 100644 --- a/chromium/chrome/browser/browser_switcher/bho/BUILD.gn +++ b/chromium/chrome/browser/browser_switcher/bho/BUILD.gn @@ -4,10 +4,17 @@ import("//build/config/compiler/compiler.gni") import("//build/toolchain/win/midl.gni") +import("//testing/test.gni") assert(is_win) assert(target_cpu == "x86" || target_cpu == "x64") +declare_args() { + # If true, compile a BHO that doesn't depend on the CRT to significantly + # minimize binary size. + use_mini_bho = false +} + shared_library("browser_switcher_bho") { if (current_cpu == "x64") { # Name the 32-bit and 64-bit output differently, since they'll be copied to @@ -25,27 +32,58 @@ shared_library("browser_switcher_bho") { "_WINDLL", ] - # TODO(nicolaso): Reduce binary size as much as possible. - # - # TODO(nicolaso): Use ie_bho.def and ie_bho.rc. - # + if (use_mini_bho) { + configs += [ "//build/config/win:sdk_link" ] + + no_default_deps = true + + libs = [ + # For buffer overflow checks with the /GS flag. + "bufferoverflowU.lib", + ] + ldflags = [ + "/NODEFAULTLIB", + "/ENTRY:DllMain", + ] + } + # TODO(nicolaso): avoid code duplication, by using BrowserSwitcherSitelist and # AlternativeBrowserDriver classes from chrome/browser_switcher/. + if (use_mini_bho) { + sources = [ + "mini_bho.cc", + "mini_bho.def", + "mini_bho_util.cc", + "mini_bho_util.h", + ] + } else { + sources = [ + "//base/win/atl.h", + "bho.cc", + "bho.h", + "browser_switcher_core.cc", + "browser_switcher_core.h", + "ie_bho.cc", + "ie_bho.def", + "logging.cc", + "logging.h", + "resource.h", + ] + } + deps = [ + ":ie_bho_idl", + ] +} + +test("browser_switcher_bho_unittests") { sources = [ - "//base/win/atl.h", - "bho.cc", - "bho.h", - "browser_switcher_core.cc", - "browser_switcher_core.h", - "ie_bho.cc", - "ie_bho.def", - "ie_bho.h", - "logging.cc", - "logging.h", - "resource.h", + "mini_bho_util.cc", + "mini_bho_util.h", + "mini_bho_util_unittest.cc", ] deps = [ - ":ie_bho_idl", + "//base", + "//testing/gtest", ] } diff --git a/chromium/chrome/browser/chrome_notification_types.h b/chromium/chrome/browser/chrome_notification_types.h index e2df7f6556d..fa06a890677 100644 --- a/chromium/chrome/browser/chrome_notification_types.h +++ b/chromium/chrome/browser/chrome_notification_types.h @@ -57,12 +57,6 @@ enum NotificationType { // the source is Source<WebContents>. NOTIFICATION_TAB_LANGUAGE_DETERMINED, - // Sent when a page has been translated. The source is the tab for that page - // (Source<WebContents>) and the details are the language the page was - // originally in and the language it was translated to - // (std::pair<std::string, std::string>). - NOTIFICATION_PAGE_TRANSLATED, - // The user has changed the browser theme. The source is a // Source<ThemeService>. There are no details. NOTIFICATION_BROWSER_THEME_CHANGED, @@ -94,25 +88,6 @@ enum NotificationType { // handler. Use APP_TERMINATING for such needs. NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST, - // Tabs -------------------------------------------------------------------- - - // Sent when a tab is added to a WebContentsDelegate. The source is the - // WebContentsDelegate and the details is the added WebContents. - NOTIFICATION_TAB_ADDED, - - // This notification is sent after a tab has been appended to the tab_strip. - // The source is a Source<WebContents> of the tab being added. There - // are no details. - NOTIFICATION_TAB_PARENTED, - - // This message is sent before a tab has been closed. The source is a - // Source<NavigationController> with a pointer to the controller for the - // closed tab. No details are expected. - // - // See also content::NOTIFICATION_WEB_CONTENTS_DESTROYED, which is sent when - // the WebContents containing the NavigationController is destroyed. - NOTIFICATION_TAB_CLOSING, - // Authentication ---------------------------------------------------------- // This is sent when a login prompt is shown. The source is the @@ -144,29 +119,18 @@ enum NotificationType { // The details are none and the source is the new profile. NOTIFICATION_PROFILE_CREATED, + // Use ProfileManagerObserver::OnProfileAdded instead of this notification. // Sent after a Profile has been added to ProfileManager. // The details are none and the source is the new profile. NOTIFICATION_PROFILE_ADDED, // Use KeyedServiceShutdownNotifier instead this notification type (you did // read the comment at the top of the file, didn't you?). - // Sent early in the process of destroying a Profile, at the time a user - // initiates the deletion of a profile versus the much later time when the - // profile object is actually destroyed (use NOTIFICATION_PROFILE_DESTROYED). - // The details are none and the source is a Profile*. - NOTIFICATION_PROFILE_DESTRUCTION_STARTED, - - // Use KeyedServiceShutdownNotifier instead this notification type (you did - // read the comment at the top of the file, didn't you?). // Sent before a Profile is destroyed. This notification is sent both for // normal and OTR profiles. // The details are none and the source is a Profile*. NOTIFICATION_PROFILE_DESTROYED, - // Sent after the URLRequestContextGetter for a Profile has been initialized. - // The details are none and the source is a Profile*. - NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED, - // Printing ---------------------------------------------------------------- // Notification from PrintJob that an event occurred. It can be that a page @@ -181,22 +145,10 @@ enum NotificationType { // Misc -------------------------------------------------------------------- #if defined(OS_CHROMEOS) - // Sent when a chromium os user logs in. - // The details are a chromeos::User object. - NOTIFICATION_LOGIN_USER_CHANGED, - // Sent immediately after the logged-in user's profile is ready. // The details are a Profile object. NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, - // Sent when the chromium session of a particular user is started. - // If this is a new user on the machine this will not be sent until a profile - // picture has been selected, unlike NOTIFICATION_LOGIN_USER_CHANGED which is - // sent immediately after the user has logged in. This will be sent again if - // the browser crashes and restarts. - // The details are a chromeos::User object. - NOTIFICATION_SESSION_STARTED, - // Sent when a network error message is displayed on the WebUI login screen. // First paint event of this fires NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE. NOTIFICATION_LOGIN_NETWORK_ERROR_SHOWN, @@ -237,9 +189,6 @@ enum NotificationType { // Sent when kiosk app list is loaded in UI. NOTIFICATION_KIOSK_APPS_LOADED, - // Sent when the user list has changed. - NOTIFICATION_USER_LIST_CHANGED, - // Sent when the screen lock state has changed. The source is // ScreenLocker and the details is a bool specifing that the // screen is locked. When details is a false, the source object diff --git a/chromium/chrome/browser/chromeos/BUILD.gn b/chromium/chrome/browser/chromeos/BUILD.gn index c6e19a53f41..01b806ae0db 100644 --- a/chromium/chrome/browser/chromeos/BUILD.gn +++ b/chromium/chrome/browser/chromeos/BUILD.gn @@ -34,6 +34,7 @@ source_set("chromeos") { "//chromeos/dbus:seneschal_proto", "//chromeos/dbus:vm_applications_apps_proto", "//chromeos/dbus/power:power_manager_proto", + "//chromeos/services/assistant/public/mojom", "//chromeos/strings", "//components/policy/proto", "//components/signin/core/browser", @@ -127,7 +128,10 @@ source_set("chromeos") { "//chromeos/services/assistant/public/cpp:prefs", "//chromeos/services/cros_healthd/public/cpp", "//chromeos/services/cros_healthd/public/mojom", + "//chromeos/services/device_sync", "//chromeos/services/device_sync/public/cpp", + "//chromeos/services/ime:constants", + "//chromeos/services/ime/public/cpp:buildflags", "//chromeos/services/ime/public/mojom", "//chromeos/services/machine_learning/public/cpp", "//chromeos/services/machine_learning/public/mojom", @@ -137,14 +141,15 @@ source_set("chromeos") { "//chromeos/services/multidevice_setup/public/cpp:auth_token_validator", "//chromeos/services/multidevice_setup/public/cpp:oobe_completion_tracker", "//chromeos/services/multidevice_setup/public/cpp:prefs", + "//chromeos/services/secure_channel", "//chromeos/services/secure_channel/public/cpp/client", "//chromeos/settings", "//chromeos/system", "//chromeos/timezone", "//chromeos/tpm", "//components/arc", - "//components/arc/common:struct_traits", "//components/arc/media_session", + "//components/arc/mojom:mojom_traits", "//components/browser_sync", "//components/captive_portal", "//components/component_updater:crl_set_remover", @@ -162,6 +167,8 @@ source_set("chromeos") { "//components/flags_ui", "//components/gcm_driver", "//components/google/core/common", + "//components/guest_os", + "//components/guest_os:prefs", "//components/guest_view/browser", "//components/image_fetcher/core", "//components/invalidation/impl", @@ -182,6 +189,7 @@ source_set("chromeos") { "//components/policy/core/common", "//components/policy/core/common:common_constants", "//components/pref_registry", + "//components/printing/common:mojo_interfaces", "//components/proxy_config", "//components/quirks", "//components/rappor", @@ -224,7 +232,7 @@ source_set("chromeos") { "//gpu/ipc/host", "//gpu/ipc/service", "//media", - "//media/mojo/interfaces", + "//media/mojo/mojom", "//mojo/public/cpp/platform", "//mojo/public/cpp/system", "//net", @@ -472,14 +480,16 @@ source_set("chromeos") { "arc/bluetooth/arc_bluetooth_task_queue.h", "arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.cc", "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/enterprise/arc_cert_store_bridge.cc", - "arc/enterprise/arc_cert_store_bridge.h", "arc/enterprise/arc_enterprise_reporting_service.cc", "arc/enterprise/arc_enterprise_reporting_service.h", + "arc/enterprise/cert_store/arc_cert_installer.cc", + "arc/enterprise/cert_store/arc_cert_installer.h", + "arc/enterprise/cert_store/arc_cert_installer_utils.cc", + "arc/enterprise/cert_store/arc_cert_installer_utils.h", + "arc/enterprise/cert_store/arc_cert_store_bridge.cc", + "arc/enterprise/cert_store/arc_cert_store_bridge.h", "arc/extensions/arc_support_message_host.cc", "arc/extensions/arc_support_message_host.h", "arc/file_system_watcher/arc_file_system_watcher_service.cc", @@ -539,12 +549,24 @@ source_set("chromeos") { "arc/input_method_manager/arc_input_method_manager_service.h", "arc/input_method_manager/input_connection_impl.cc", "arc/input_method_manager/input_connection_impl.h", + "arc/instance_throttle/arc_active_window_throttle_observer.cc", + "arc/instance_throttle/arc_active_window_throttle_observer.h", + "arc/instance_throttle/arc_boot_phase_throttle_observer.cc", + "arc/instance_throttle/arc_boot_phase_throttle_observer.h", + "arc/instance_throttle/arc_instance_throttle.cc", + "arc/instance_throttle/arc_instance_throttle.h", + "arc/instance_throttle/arc_throttle_observer.cc", + "arc/instance_throttle/arc_throttle_observer.h", + "arc/instance_throttle/window_throttle_observer_base.cc", + "arc/instance_throttle/window_throttle_observer_base.h", "arc/intent_helper/arc_external_protocol_dialog.cc", "arc/intent_helper/arc_external_protocol_dialog.h", "arc/intent_helper/arc_intent_picker_app_fetcher.cc", "arc/intent_helper/arc_intent_picker_app_fetcher.h", "arc/intent_helper/arc_settings_service.cc", "arc/intent_helper/arc_settings_service.h", + "arc/intent_helper/custom_tab_session_impl.cc", + "arc/intent_helper/custom_tab_session_impl.h", "arc/intent_helper/open_with_menu.cc", "arc/intent_helper/open_with_menu.h", "arc/intent_helper/start_smart_selection_action_menu.cc", @@ -584,6 +606,10 @@ source_set("chromeos") { "arc/print/arc_print_service.h", "arc/print_spooler/arc_print_spooler_bridge.cc", "arc/print_spooler/arc_print_spooler_bridge.h", + "arc/print_spooler/arc_print_spooler_util.cc", + "arc/print_spooler/arc_print_spooler_util.h", + "arc/print_spooler/print_session_impl.cc", + "arc/print_spooler/print_session_impl.h", "arc/process/arc_process.cc", "arc/process/arc_process.h", "arc/process/arc_process_service.cc", @@ -679,6 +705,9 @@ source_set("chromeos") { "certificate_provider/certificate_requests.h", "certificate_provider/pin_dialog_manager.cc", "certificate_provider/pin_dialog_manager.h", + "certificate_provider/security_token_pin_dialog_host.h", + "certificate_provider/security_token_pin_dialog_host_popup_impl.cc", + "certificate_provider/security_token_pin_dialog_host_popup_impl.h", "certificate_provider/sign_requests.cc", "certificate_provider/sign_requests.h", "certificate_provider/thread_safe_certificate_map.cc", @@ -715,12 +744,21 @@ source_set("chromeos") { "chrome_browser_main_chromeos.h", "chrome_content_browser_client_chromeos_part.cc", "chrome_content_browser_client_chromeos_part.h", - "chrome_service_name.cc", - "chrome_service_name.h", + "crostini/ansible/ansible_management_service.cc", + "crostini/ansible/ansible_management_service.h", + "crostini/ansible/ansible_management_util.cc", + "crostini/ansible/ansible_management_util.h", + "crostini/ansible/pending_software_changes.cc", + "crostini/ansible/pending_software_changes.h", + "crostini/ansible/software_config.cc", + "crostini/ansible/software_config.h", "crostini/crostini_export_import.cc", "crostini/crostini_export_import.h", "crostini/crostini_export_import_notification.cc", "crostini/crostini_export_import_notification.h", + "crostini/crostini_installer.cc", + "crostini/crostini_installer.h", + "crostini/crostini_installer_ui_delegate.h", "crostini/crostini_manager.cc", "crostini/crostini_manager.h", "crostini/crostini_manager_factory.cc", @@ -747,12 +785,16 @@ source_set("chromeos") { "crostini/crostini_simple_types.h", "crostini/crostini_terminal.cc", "crostini/crostini_terminal.h", + "crostini/crostini_unsupported_action_notifier.cc", + "crostini/crostini_unsupported_action_notifier.h", "crostini/crostini_util.cc", "crostini/crostini_util.h", "crostini/crosvm_metrics.cc", "crostini/crosvm_metrics.h", "crostini/crosvm_process_list.cc", "crostini/crosvm_process_list.h", + "crostini/fake_crostini_installer_ui_delegate.cc", + "crostini/fake_crostini_installer_ui_delegate.h", "cryptauth/client_app_metadata_provider_service.cc", "cryptauth/client_app_metadata_provider_service.h", "cryptauth/client_app_metadata_provider_service_factory.cc", @@ -914,6 +956,8 @@ source_set("chromeos") { "file_manager/volume_manager_factory.cc", "file_manager/volume_manager_factory.h", "file_manager/volume_manager_observer.h", + "file_manager/web_file_tasks.cc", + "file_manager/web_file_tasks.h", "file_system_provider/abort_callback.h", "file_system_provider/extension_provider.cc", "file_system_provider/extension_provider.h", @@ -1238,6 +1282,10 @@ source_set("chromeos") { "login/login_auth_recorder.h", "login/login_client_cert_usage_observer.cc", "login/login_client_cert_usage_observer.h", + "login/login_screen_extensions_lifetime_manager.cc", + "login/login_screen_extensions_lifetime_manager.h", + "login/login_screen_extensions_storage_cleaner.cc", + "login/login_screen_extensions_storage_cleaner.h", "login/login_wizard.h", "login/mojo_system_info_dispatcher.cc", "login/mojo_system_info_dispatcher.h", @@ -1346,6 +1394,8 @@ source_set("chromeos") { "login/screens/welcome_screen.h", "login/screens/wrong_hwid_screen.cc", "login/screens/wrong_hwid_screen.h", + "login/security_token_pin_dialog_host_ash_impl.cc", + "login/security_token_pin_dialog_host_ash_impl.h", "login/session/chrome_session_manager.cc", "login/session/chrome_session_manager.h", "login/session/user_session_manager.cc", @@ -1409,8 +1459,12 @@ source_set("chromeos") { "login/ui/login_display_webui.h", "login/ui/login_feedback.cc", "login/ui/login_feedback.h", + "login/ui/login_screen_extension_ui/login_screen_extension_ui_create_options.cc", + "login/ui/login_screen_extension_ui/login_screen_extension_ui_create_options.h", "login/ui/login_screen_extension_ui/login_screen_extension_ui_dialog_delegate.cc", "login/ui/login_screen_extension_ui/login_screen_extension_ui_dialog_delegate.h", + "login/ui/login_screen_extension_ui/login_screen_extension_ui_web_dialog_view.cc", + "login/ui/login_screen_extension_ui/login_screen_extension_ui_web_dialog_view.h", "login/ui/login_screen_extension_ui/login_screen_extension_ui_window.cc", "login/ui/login_screen_extension_ui/login_screen_extension_ui_window.h", "login/ui/login_web_dialog.cc", @@ -1461,6 +1515,8 @@ source_set("chromeos") { "login/users/user_manager_interface.h", "login/version_info_updater.cc", "login/version_info_updater.h", + "login/version_updater/version_updater.cc", + "login/version_updater/version_updater.h", "login/wizard_controller.cc", "login/wizard_controller.h", "mobile/mobile_activator.cc", @@ -1479,6 +1535,8 @@ source_set("chromeos") { "net/client_cert_store_chromeos.h", "net/delay_network_call.cc", "net/delay_network_call.h", + "net/dhcp_wpad_url_client.cc", + "net/dhcp_wpad_url_client.h", "net/network_portal_detector_impl.cc", "net/network_portal_detector_impl.h", "net/network_portal_detector_test_impl.cc", @@ -1520,6 +1578,8 @@ source_set("chromeos") { "platform_keys/platform_keys_service.h", "platform_keys/platform_keys_service_factory.cc", "platform_keys/platform_keys_service_factory.h", + "plugin_vm/plugin_vm_engagement_metrics_service.cc", + "plugin_vm/plugin_vm_engagement_metrics_service.h", "plugin_vm/plugin_vm_files.cc", "plugin_vm/plugin_vm_files.h", "plugin_vm/plugin_vm_image_download_client.cc", @@ -1617,8 +1677,6 @@ source_set("chromeos") { "policy/device_policy_decoder_chromeos.cc", "policy/device_policy_decoder_chromeos.h", "policy/device_policy_remover.h", - "policy/device_scheduled_update_checker.cc", - "policy/device_scheduled_update_checker.h", "policy/device_wifi_allowed_handler.cc", "policy/device_wifi_allowed_handler.h", "policy/display_resolution_handler.cc", @@ -1673,8 +1731,6 @@ source_set("chromeos") { "policy/off_hours/off_hours_policy_applier.h", "policy/off_hours/off_hours_proto_parser.cc", "policy/off_hours/off_hours_proto_parser.h", - "policy/os_and_policies_update_checker.cc", - "policy/os_and_policies_update_checker.h", "policy/policy_cert_service.cc", "policy/policy_cert_service.h", "policy/policy_cert_service_factory.cc", @@ -1693,6 +1749,8 @@ source_set("chromeos") { "policy/remote_commands/device_command_reboot_job.h", "policy/remote_commands/device_command_refresh_machine_certificate_job.cc", "policy/remote_commands/device_command_refresh_machine_certificate_job.h", + "policy/remote_commands/device_command_remote_powerwash_job.cc", + "policy/remote_commands/device_command_remote_powerwash_job.h", "policy/remote_commands/device_command_screenshot_job.cc", "policy/remote_commands/device_command_screenshot_job.h", "policy/remote_commands/device_command_set_volume_job.cc", @@ -1711,6 +1769,14 @@ source_set("chromeos") { "policy/remote_commands/user_commands_factory_chromeos.h", "policy/rsu/lookup_key_uploader.cc", "policy/rsu/lookup_key_uploader.h", + "policy/scheduled_update_checker/device_scheduled_update_checker.cc", + "policy/scheduled_update_checker/device_scheduled_update_checker.h", + "policy/scheduled_update_checker/os_and_policies_update_checker.cc", + "policy/scheduled_update_checker/os_and_policies_update_checker.h", + "policy/scheduled_update_checker/scoped_wake_lock.cc", + "policy/scheduled_update_checker/scoped_wake_lock.h", + "policy/scheduled_update_checker/task_executor_with_retries.cc", + "policy/scheduled_update_checker/task_executor_with_retries.h", "policy/secondary_google_account_signin_policy_handler.cc", "policy/secondary_google_account_signin_policy_handler.h", "policy/server_backed_device_state.cc", @@ -1737,8 +1803,6 @@ source_set("chromeos") { "policy/status_uploader.h", "policy/system_log_uploader.cc", "policy/system_log_uploader.h", - "policy/task_executor_with_retries.cc", - "policy/task_executor_with_retries.h", "policy/tpm_auto_update_mode_policy_handler.cc", "policy/tpm_auto_update_mode_policy_handler.h", "policy/upload_job.h", @@ -1817,11 +1881,10 @@ source_set("chromeos") { "power/ml/adaptive_screen_brightness_ukm_logger.h", "power/ml/adaptive_screen_brightness_ukm_logger_impl.cc", "power/ml/adaptive_screen_brightness_ukm_logger_impl.h", + "power/ml/boot_clock.cc", "power/ml/boot_clock.h", "power/ml/idle_event_notifier.cc", "power/ml/idle_event_notifier.h", - "power/ml/real_boot_clock.cc", - "power/ml/real_boot_clock.h", "power/ml/recent_events_counter.cc", "power/ml/recent_events_counter.h", "power/ml/user_activity_controller.cc", @@ -1959,6 +2022,8 @@ source_set("chromeos") { "settings/stats_reporting_controller.h", "settings/stub_cros_settings_provider.cc", "settings/stub_cros_settings_provider.h", + "settings/supervised_user_cros_settings_provider.cc", + "settings/supervised_user_cros_settings_provider.h", "settings/token_encryptor.cc", "settings/token_encryptor.h", "smb_client/discovery/host_locator.h", @@ -2139,10 +2204,16 @@ source_set("chromeos") { "extensions/input_method_api.h", "extensions/login_screen/login/login_api.cc", "extensions/login_screen/login/login_api.h", + "extensions/login_screen/login_screen_storage/login_screen_storage_api.cc", + "extensions/login_screen/login_screen_storage/login_screen_storage_api.h", "extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler.cc", "extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler.h", "extensions/login_screen/login_screen_ui/login_screen_ui_api.cc", "extensions/login_screen/login_screen_ui/login_screen_ui_api.h", + "extensions/login_screen/login_state/login_state_api.cc", + "extensions/login_screen/login_state/login_state_api.h", + "extensions/login_screen/login_state/session_state_changed_event_dispatcher.cc", + "extensions/login_screen/login_state/session_state_changed_event_dispatcher.h", "extensions/media_player_api.cc", "extensions/media_player_api.h", "extensions/quick_unlock_private/quick_unlock_private_api.cc", @@ -2268,6 +2339,8 @@ static_library("test_support") { "login/test/test_condition_waiter.h", "login/test/test_predicate_waiter.cc", "login/test/test_predicate_waiter.h", + "login/version_updater/mock_version_updater_delegate.cc", + "login/version_updater/mock_version_updater_delegate.h", "printing/printing_stubs.cc", "printing/printing_stubs.h", "scoped_set_running_on_chromeos_for_testing.cc", @@ -2338,6 +2411,8 @@ source_set("unit_tests") { "arc/bluetooth/arc_bluetooth_bridge_unittest.cc", "arc/bluetooth/arc_bluetooth_task_queue_unittest.cc", "arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc", + "arc/enterprise/cert_store/arc_cert_installer_unittest.cc", + "arc/enterprise/cert_store/arc_cert_installer_utils_unittest.cc", "arc/extensions/arc_support_message_host_unittest.cc", "arc/file_system_watcher/arc_file_system_watcher_service_unittest.cc", "arc/fileapi/arc_content_file_system_async_file_util_unittest.cc", @@ -2356,6 +2431,10 @@ source_set("unit_tests") { "arc/input_method_manager/input_connection_impl_unittest.cc", "arc/input_method_manager/test_input_method_manager_bridge.cc", "arc/input_method_manager/test_input_method_manager_bridge.h", + "arc/instance_throttle/arc_active_window_throttle_observer_unittest.cc", + "arc/instance_throttle/arc_boot_phase_throttle_observer_unittest.cc", + "arc/instance_throttle/arc_instance_throttle_unittest.cc", + "arc/instance_throttle/arc_throttle_observer_unittest.cc", "arc/intent_helper/arc_external_protocol_dialog_unittest.cc", "arc/intent_helper/arc_intent_picker_app_fetcher_unittest.cc", "arc/intent_helper/arc_settings_service_unittest.cc", @@ -2399,13 +2478,18 @@ source_set("unit_tests") { "child_accounts/usage_time_limit_processor_unittest.cc", "child_accounts/usage_time_state_notifier_unittest.cc", "chrome_content_browser_client_chromeos_part_unittest.cc", + "crostini/ansible/ansible_management_service_unittest.cc", + "crostini/ansible/pending_software_changes_unittest.cc", + "crostini/ansible/software_config_unittest.cc", "crostini/crostini_export_import_unittest.cc", + "crostini/crostini_installer_unittest.cc", "crostini/crostini_manager_unittest.cc", "crostini/crostini_mime_types_service_unittest.cc", "crostini/crostini_package_notification_unittest.cc", "crostini/crostini_package_service_unittest.cc", "crostini/crostini_registry_service_unittest.cc", "crostini/crostini_reporting_util_unittest.cc", + "crostini/crostini_unsupported_action_notifier_unittest.cc", "crostini/crosvm_metrics_unittest.cc", "crostini/crosvm_process_list_unittest.cc", "cryptauth/client_app_metadata_provider_service_unittest.cc", @@ -2433,6 +2517,8 @@ source_set("unit_tests") { "extensions/install_limiter_unittest.cc", "extensions/login_screen/login/login_api_unittest.cc", "extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler_unittest.cc", + "extensions/login_screen/login_state/login_state_api_unittest.cc", + "extensions/login_screen/login_state/session_state_changed_event_dispatcher_unittest.cc", "extensions/permissions_updater_delegate_chromeos_unittest.cc", "extensions/public_session_permission_helper_unittest.cc", "extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc", @@ -2447,6 +2533,7 @@ source_set("unit_tests") { "file_manager/path_util_unittest.cc", "file_manager/url_util_unittest.cc", "file_manager/volume_manager_unittest.cc", + "file_manager/web_file_tasks_unittest.cc", "file_system_provider/fake_extension_provider.cc", "file_system_provider/fake_extension_provider.h", "file_system_provider/fake_provided_file_system.cc", @@ -2501,11 +2588,11 @@ source_set("unit_tests") { "guest_os/guest_os_share_path_unittest.cc", "hats/hats_finch_helper_unittest.cc", "hats/hats_notification_controller_unittest.cc", - "input_method/browser_state_monitor_unittest.cc", "input_method/input_method_configuration_unittest.cc", "input_method/input_method_engine_unittest.cc", "input_method/input_method_manager_impl_unittest.cc", "input_method/input_method_persistence_unittest.cc", + "kerberos/kerberos_credentials_manager_test.cc", "kerberos/kerberos_ticket_expiry_notification_test.cc", "locale_change_guard_unittest.cc", "lock_screen_apps/app_manager_impl_unittest.cc", @@ -2543,9 +2630,11 @@ source_set("unit_tests") { "login/signin_partition_manager_unittest.cc", "login/supervised/supervised_user_authentication_unittest.cc", "login/ui/login_screen_extension_ui/login_screen_extension_ui_dialog_delegate_unittest.cc", + "login/ui/login_screen_extension_ui/login_screen_extension_ui_web_dialog_view_unittest.cc", "login/users/affiliation_unittest.cc", "login/users/multi_profile_user_controller_unittest.cc", "login/users/user_manager_unittest.cc", + "login/version_updater/version_updater_unittest.cc", "mobile/mobile_activator_unittest.cc", "net/client_cert_store_chromeos_unittest.cc", "net/network_portal_detector_impl_unittest.cc", @@ -2588,7 +2677,6 @@ source_set("unit_tests") { "policy/device_cloud_policy_store_chromeos_unittest.cc", "policy/device_local_account_policy_service_unittest.cc", "policy/device_policy_decoder_chromeos_unittest.cc", - "policy/device_scheduled_update_checker_unittest.cc", "policy/dm_token_storage_unittest.cc", "policy/extension_cache_unittest.cc", "policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc", @@ -2602,12 +2690,14 @@ source_set("unit_tests") { "policy/off_hours/off_hours_policy_applier_unittest.cc", "policy/off_hours/off_hours_proto_parser_unittest.cc", "policy/pre_signin_policy_fetcher_unittest.cc", + "policy/remote_commands/device_command_remote_powerwash_job_unittest.cc", "policy/remote_commands/device_command_screenshot_job_unittest.cc", "policy/remote_commands/device_command_set_volume_job_unittest.cc", "policy/remote_commands/device_command_start_crd_session_unittest.cc", "policy/remote_commands/device_command_wipe_users_job_unittest.cc", "policy/remote_commands/user_command_arc_job_unittest.cc", "policy/rsu/lookup_key_uploader_unittest.cc", + "policy/scheduled_update_checker/device_scheduled_update_checker_unittest.cc", "policy/secondary_google_account_signin_policy_handler_unittest.cc", "policy/server_backed_state_keys_broker_unittest.cc", "policy/single_app_install_event_log_unittest.cc", @@ -2631,10 +2721,8 @@ source_set("unit_tests") { "power/extension_event_observer_unittest.cc", "power/ml/adaptive_screen_brightness_manager_unittest.cc", "power/ml/adaptive_screen_brightness_ukm_logger_impl_unittest.cc", - "power/ml/fake_boot_clock.cc", - "power/ml/fake_boot_clock.h", + "power/ml/boot_clock_unittest.cc", "power/ml/idle_event_notifier_unittest.cc", - "power/ml/real_boot_clock_unittest.cc", "power/ml/recent_events_counter_unittest.cc", "power/ml/smart_dim/model_unittest.cc", "power/ml/user_activity_manager_unittest.cc", @@ -2715,7 +2803,6 @@ source_set("unit_tests") { "../../common/extensions/api/file_browser_handlers/file_browser_handler_manifest_unittest.cc", "../../common/extensions/api/file_system_provider/file_system_provider_handler_unittest.cc", "../ui/views/frame/immersive_mode_controller_ash_unittest.cc", - "../ui/views/intent_picker_bubble_view_unittest.cc", "../ui/views/select_file_dialog_extension_unittest.cc", "../ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc", "../ui/webui/chromeos/login/l10n_util_test_util.cc", @@ -2992,3 +3079,14 @@ fuzzer_test("smb_url_fuzzer") { seed_corpus = "smb_client/fuzzer_data/smb_url_corpus" } + +fuzzer_test("zeroconf_printer_detector_fuzzer") { + sources = [ + "printing/zeroconf_printer_detector_fuzzer.cc", + ] + deps = [ + "//base/test:test_support", + "//chrome/browser", + "//chrome/browser/chromeos", + ] +} diff --git a/chromium/chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni b/chromium/chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni deleted file mode 100644 index 3a411a9f384..00000000000 --- a/chromium/chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni +++ /dev/null @@ -1,4 +0,0 @@ -declare_args() { - # Whether Kiosk Next should be enabled. - enable_kiosk_next = is_chromeos -} diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc index 34273edb807..f1551c68a9c 100644 --- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc +++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc @@ -15,7 +15,6 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/stl_util.h" -#include "base/task/post_task.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/common/custom_handlers/protocol_handler.h" @@ -23,10 +22,7 @@ #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/child_process_security_policy.h" -#include "net/base/network_delegate.h" -#include "net/url_request/url_request_redirect_job.h" using content::BrowserThread; using content::ChildProcessSecurityPolicy; @@ -75,64 +71,6 @@ GURL TranslateUrl( } // namespace -// IOThreadDelegate ------------------------------------------------------------ - -ProtocolHandlerRegistry::IOThreadDelegate::IOThreadDelegate(bool) - : enabled_(true) {} -ProtocolHandlerRegistry::IOThreadDelegate::~IOThreadDelegate() {} - -bool ProtocolHandlerRegistry::IOThreadDelegate::IsHandledProtocol( - const std::string& scheme) const { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - return enabled_ && !LookupHandler(default_handlers_, scheme).IsEmpty(); -} - -void ProtocolHandlerRegistry::IOThreadDelegate::ClearDefault( - const std::string& scheme) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - default_handlers_.erase(scheme); -} - -void ProtocolHandlerRegistry::IOThreadDelegate::SetDefault( - const ProtocolHandler& handler) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - ClearDefault(handler.protocol()); - default_handlers_.insert(std::make_pair(handler.protocol(), handler)); -} - -GURL ProtocolHandlerRegistry::IOThreadDelegate::Translate( - const GURL& url) const { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - return TranslateUrl(default_handlers_, url); -} - -// Create a new job for the supplied |URLRequest| if a default handler -// is registered and the associated handler is able to interpret -// the url from |request|. -net::URLRequestJob* ProtocolHandlerRegistry::IOThreadDelegate::MaybeCreateJob( - net::URLRequest* request, net::NetworkDelegate* network_delegate) const { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - GURL translated_url(Translate(request->url())); - if (translated_url.is_empty()) - return nullptr; - - return new net::URLRequestRedirectJob( - request, network_delegate, translated_url, - net::URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, - "Protocol Handler Registry"); -} - -void ProtocolHandlerRegistry::IOThreadDelegate::Enable() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - enabled_ = true; -} - -void ProtocolHandlerRegistry::IOThreadDelegate::Disable() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - enabled_ = false; -} - // Delegate -------------------------------------------------------------------- ProtocolHandlerRegistry::Delegate::~Delegate() {} @@ -187,8 +125,7 @@ ProtocolHandlerRegistry::ProtocolHandlerRegistry( delegate_(delegate), enabled_(true), is_loading_(false), - is_loaded_(false), - io_thread_delegate_(new IOThreadDelegate(enabled_)) {} + is_loaded_(false) {} bool ProtocolHandlerRegistry::SilentlyHandleRegisterHandlerRequest( const ProtocolHandler& handler) { @@ -207,7 +144,8 @@ bool ProtocolHandlerRegistry::SilentlyHandleRegisterHandlerRequest( void ProtocolHandlerRegistry::OnAcceptRegisterProtocolHandler( const ProtocolHandler& handler) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - RegisterProtocolHandler(handler, USER); + if (!RegisterProtocolHandler(handler, USER)) + return; SetDefault(handler); Save(); NotifyChanged(); @@ -267,9 +205,6 @@ void ProtocolHandlerRegistry::ClearDefault(const std::string& scheme) { DCHECK_CURRENTLY_ON(BrowserThread::UI); default_handlers_.erase(scheme); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&IOThreadDelegate::ClearDefault, - io_thread_delegate_, scheme)); Save(); NotifyChanged(); } @@ -529,11 +464,6 @@ void ProtocolHandlerRegistry::RemoveHandler( // NOTE We pass a copy because SetDefault() modifies handlers. SetDefault(ProtocolHandler(handlers[0])); } else { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&IOThreadDelegate::ClearDefault, io_thread_delegate_, - q->second.protocol())); - default_handlers_.erase(q); } } @@ -570,10 +500,6 @@ void ProtocolHandlerRegistry::Enable() { return; } enabled_ = true; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&IOThreadDelegate::Enable, io_thread_delegate_)); - ProtocolHandlerMap::const_iterator p; for (p = default_handlers_.begin(); p != default_handlers_.end(); ++p) { delegate_->RegisterExternalHandler(p->first); @@ -588,9 +514,6 @@ void ProtocolHandlerRegistry::Disable() { return; } enabled_ = false; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&IOThreadDelegate::Disable, io_thread_delegate_)); ProtocolHandlerMap::const_iterator p; for (p = default_handlers_.begin(); p != default_handlers_.end(); ++p) { @@ -678,9 +601,6 @@ void ProtocolHandlerRegistry::SetDefault(const ProtocolHandler& handler) { default_handlers_.erase(handler.protocol()); default_handlers_.insert(std::make_pair(handler.protocol(), handler)); PromoteHandler(handler); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&IOThreadDelegate::SetDefault, - io_thread_delegate_, handler)); } void ProtocolHandlerRegistry::InsertHandler(const ProtocolHandler& handler) { @@ -728,23 +648,29 @@ void ProtocolHandlerRegistry::NotifyChanged() { observer.OnProtocolHandlerRegistryChanged(); } -void ProtocolHandlerRegistry::RegisterProtocolHandler( +bool ProtocolHandlerRegistry::RegisterProtocolHandler( const ProtocolHandler& handler, const HandlerSource source) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(CanSchemeBeOverridden(handler.protocol())); DCHECK(!handler.IsEmpty()); + + // Ignore invalid handlers. + if (!handler.IsValid()) + return false; + ProtocolHandlerMultiMap& map = (source == POLICY) ? policy_protocol_handlers_ : user_protocol_handlers_; ProtocolHandlerList& list = map[handler.protocol()]; if (!HandlerExists(handler, list)) list.push_back(handler); if (IsRegistered(handler)) { - return; + return true; } if (enabled_ && !delegate_->IsExternalHandlerRegistered(handler.protocol())) delegate_->RegisterExternalHandler(handler.protocol()); InsertHandler(handler); + return true; } std::vector<const base::DictionaryValue*> @@ -780,7 +706,8 @@ void ProtocolHandlerRegistry::RegisterProtocolHandlersFromPref( p != registered_handlers.end(); ++p) { ProtocolHandler handler = ProtocolHandler::CreateProtocolHandler(*p); - RegisterProtocolHandler(handler, source); + if (!RegisterProtocolHandler(handler, source)) + continue; bool is_default = false; if ((*p)->GetBoolean("default", &is_default) && is_default) { SetDefault(handler); diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h index 443488f8546..614b1b09e68 100644 --- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h +++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h @@ -20,9 +20,6 @@ #include "chrome/common/custom_handlers/protocol_handler.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/browser_thread.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_job.h" -#include "net/url_request/url_request_job_factory.h" namespace user_prefs { class PrefRegistrySyncable; @@ -65,59 +62,6 @@ class ProtocolHandlerRegistry : public KeyedService { virtual void OnProtocolHandlerRegistryChanged() = 0; }; - // IOThreadDelegate is an IO thread specific object. Access to the class - // should all be done via the IO thread. The registry living on the UI thread - // makes a best effort to update the IO object after local updates are - // completed. - class IOThreadDelegate : public base::RefCountedThreadSafe<IOThreadDelegate> { - public: - // Creates a new instance. If |enabled| is true the registry is considered - // enabled on the IO thread. - explicit IOThreadDelegate(bool enabled); - - // Returns true if the protocol has a default protocol handler. - // Should be called only from the IO thread. - bool IsHandledProtocol(const std::string& scheme) const; - - // Clears the default for the provided protocol. - // Should be called only from the IO thread. - void ClearDefault(const std::string& scheme); - - // Makes this ProtocolHandler the default handler for its protocol. - // Should be called only from the IO thread. - void SetDefault(const ProtocolHandler& handler); - - // Returns a translated URL if |url| is handled by a protocol handler, - // otherwise it returns an empty URL. - GURL Translate(const GURL& url) const; - - // Creates a URL request job for the given request if there is a matching - // protocol handler, returns NULL otherwise. - net::URLRequestJob* MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const; - - // Indicate that the registry has been enabled in the IO thread's - // copy of the data. - void Enable(); - - // Indicate that the registry has been disabled in the IO thread's copy of - // the data. - void Disable(); - - private: - friend class base::RefCountedThreadSafe<IOThreadDelegate>; - virtual ~IOThreadDelegate(); - - // Copy of protocol handlers use only on the IO thread. - ProtocolHandlerRegistry::ProtocolHandlerMap default_handlers_; - - // Is the registry enabled on the IO thread. - bool enabled_; - - DISALLOW_COPY_AND_ASSIGN(IOThreadDelegate); - }; - // Creates a new instance. Assumes ownership of |delegate|. ProtocolHandlerRegistry(content::BrowserContext* context, Delegate* delegate); ~ProtocolHandlerRegistry() override; @@ -245,10 +189,6 @@ class ProtocolHandlerRegistry : public KeyedService { bool enabled() const { return enabled_; } - scoped_refptr<IOThreadDelegate> io_thread_delegate() { - return io_thread_delegate_; - } - // Add a predefined protocol handler. This has to be called before the first // load command was issued, otherwise the command will be ignored. void AddPredefinedHandler(const ProtocolHandler& handler); @@ -302,7 +242,7 @@ class ProtocolHandlerRegistry : public KeyedService { void NotifyChanged(); // Registers a new protocol handler. - void RegisterProtocolHandler(const ProtocolHandler& handler, + bool RegisterProtocolHandler(const ProtocolHandler& handler, const HandlerSource source); // Registers protocol handlers from the preference. @@ -396,10 +336,6 @@ class ProtocolHandlerRegistry : public KeyedService { // AddPredefinedHandler will be rejected. bool is_loaded_; - // Copy of registry data for use on the IO thread. Changes to the registry - // are posted to the IO thread where updates are applied to this object. - scoped_refptr<IOThreadDelegate> io_thread_delegate_; - base::ObserverList<Observer> observers_; // Makes it possible to invalidate the callback for the diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc b/chromium/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc index 3725feacba9..647b1054cb4 100644 --- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc +++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc @@ -10,14 +10,18 @@ #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" +#include "chrome/browser/extensions/extension_browsertest.h" +#include "chrome/browser/permissions/permission_request_manager.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/permission_bubble/mock_permission_prompt_factory.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" +#include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/blink/public/web/web_context_menu_data.h" @@ -48,8 +52,7 @@ class RegisterProtocolHandlerBrowserTest : public InProcessBrowserTest { return menu; } - void AddProtocolHandler(const std::string& protocol, - const GURL& url) { + void AddProtocolHandler(const std::string& protocol, const GURL& url) { ProtocolHandler handler = ProtocolHandler::CreateProtocolHandler(protocol, url); ProtocolHandlerRegistry* registry = @@ -116,19 +119,47 @@ IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerBrowserTest, IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerBrowserTest, CustomHandler) { ASSERT_TRUE(embedded_test_server()->Start()); - GURL handler_url = embedded_test_server()->GetURL("/custom_handler_foo.html"); - AddProtocolHandler("foo", handler_url); + GURL handler_url = embedded_test_server()->GetURL("/custom_handler.html"); + AddProtocolHandler("news", handler_url); - ui_test_utils::NavigateToURL(browser(), GURL("foo:test")); + ui_test_utils::NavigateToURL(browser(), GURL("news:test")); ASSERT_EQ(handler_url, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); // Also check redirects. GURL redirect_url = - embedded_test_server()->GetURL("/server-redirect?foo:test"); + embedded_test_server()->GetURL("/server-redirect?news:test"); ui_test_utils::NavigateToURL(browser(), redirect_url); ASSERT_EQ(handler_url, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } + +using RegisterProtocolHandlerExtensionBrowserTest = + extensions::ExtensionBrowserTest; + +IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerExtensionBrowserTest, Basic) { + PermissionRequestManager* manager = PermissionRequestManager::FromWebContents( + browser()->tab_strip_model()->GetActiveWebContents()); + auto prompt_factory = std::make_unique<MockPermissionPromptFactory>(manager); + prompt_factory->set_response_type(PermissionRequestManager::ACCEPT_ALL); + + const extensions::Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("protocol_handler")); + ASSERT_NE(nullptr, extension); + + std::string handler_url = + "chrome-extension://" + extension->id() + "/test.html"; + + // Register the handler. + ui_test_utils::NavigateToURL(browser(), GURL(handler_url)); + ASSERT_TRUE(content::ExecuteScript( + browser()->tab_strip_model()->GetActiveWebContents(), + "navigator.registerProtocolHandler('geo', 'test.html?%s', 'test');")); + + // Test the handler. + ui_test_utils::NavigateToURL(browser(), GURL("geo:test")); + ASSERT_EQ(GURL(handler_url + "?geo%3Atest"), + browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); +} diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc b/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc index f6fe7772a8e..5a4de3ea15a 100644 --- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc +++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc @@ -23,7 +23,7 @@ #include "components/pref_registry/pref_registry_syncable.h" #include "components/sync_preferences/pref_service_syncable.h" #include "content/public/browser/browser_task_traits.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_renderer_host.h" #include "net/base/request_priority.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" @@ -197,7 +197,7 @@ class QueryProtocolHandlerOnChange : public ProtocolHandlerRegistry::Observer { class ProtocolHandlerRegistryTest : public testing::Test { protected: ProtocolHandlerRegistryTest() - : test_protocol_handler_(CreateProtocolHandler("test", "test")) {} + : test_protocol_handler_(CreateProtocolHandler("news", "news")) {} FakeDelegate* delegate() const { return delegate_; } ProtocolHandlerRegistry* registry() { return registry_.get(); } @@ -268,13 +268,13 @@ class ProtocolHandlerRegistryTest : public testing::Test { CHECK(profile_->GetPrefs()); SetUpRegistry(true); test_protocol_handler_ = - CreateProtocolHandler("test", GURL("http://test.com/%s")); + CreateProtocolHandler("news", GURL("http://test.com/%s")); } void TearDown() override { TeadDownRegistry(); } private: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<TestingProfile> profile_; FakeDelegate* delegate_; // Registry assumes ownership of delegate_. @@ -283,34 +283,34 @@ class ProtocolHandlerRegistryTest : public testing::Test { }; TEST_F(ProtocolHandlerRegistryTest, AcceptProtocolHandlerHandlesProtocol) { - ASSERT_FALSE(registry()->IsHandledProtocol("test")); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); registry()->OnAcceptRegisterProtocolHandler(test_protocol_handler()); - ASSERT_TRUE(registry()->IsHandledProtocol("test")); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); } TEST_F(ProtocolHandlerRegistryTest, DeniedProtocolIsntHandledUntilAccepted) { registry()->OnDenyRegisterProtocolHandler(test_protocol_handler()); - ASSERT_FALSE(registry()->IsHandledProtocol("test")); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); registry()->OnAcceptRegisterProtocolHandler(test_protocol_handler()); - ASSERT_TRUE(registry()->IsHandledProtocol("test")); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); } TEST_F(ProtocolHandlerRegistryTest, ClearDefaultMakesProtocolNotHandled) { registry()->OnAcceptRegisterProtocolHandler(test_protocol_handler()); - registry()->ClearDefault("test"); - ASSERT_FALSE(registry()->IsHandledProtocol("test")); - ASSERT_TRUE(registry()->GetHandlerFor("test").IsEmpty()); + registry()->ClearDefault("news"); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); + ASSERT_TRUE(registry()->GetHandlerFor("news").IsEmpty()); } TEST_F(ProtocolHandlerRegistryTest, DisableDeregistersProtocolHandlers) { - ASSERT_FALSE(delegate()->IsExternalHandlerRegistered("test")); + ASSERT_FALSE(delegate()->IsExternalHandlerRegistered("news")); registry()->OnAcceptRegisterProtocolHandler(test_protocol_handler()); - ASSERT_TRUE(delegate()->IsExternalHandlerRegistered("test")); + ASSERT_TRUE(delegate()->IsExternalHandlerRegistered("news")); registry()->Disable(); - ASSERT_FALSE(delegate()->IsExternalHandlerRegistered("test")); + ASSERT_FALSE(delegate()->IsExternalHandlerRegistered("news")); registry()->Enable(); - ASSERT_TRUE(delegate()->IsExternalHandlerRegistered("test")); + ASSERT_TRUE(delegate()->IsExternalHandlerRegistered("news")); } TEST_F(ProtocolHandlerRegistryTest, IgnoreProtocolHandler) { @@ -322,8 +322,8 @@ TEST_F(ProtocolHandlerRegistryTest, IgnoreProtocolHandler) { } TEST_F(ProtocolHandlerRegistryTest, IgnoreEquivalentProtocolHandler) { - ProtocolHandler ph1 = CreateProtocolHandler("test", GURL("http://test/%s")); - ProtocolHandler ph2 = CreateProtocolHandler("test", GURL("http://test/%s")); + ProtocolHandler ph1 = CreateProtocolHandler("news", GURL("http://test/%s")); + ProtocolHandler ph2 = CreateProtocolHandler("news", GURL("http://test/%s")); registry()->OnIgnoreRegisterProtocolHandler(ph1); ASSERT_TRUE(registry()->IsIgnored(ph1)); @@ -340,21 +340,21 @@ TEST_F(ProtocolHandlerRegistryTest, SaveAndLoad) { registry()->OnAcceptRegisterProtocolHandler(test_protocol_handler()); registry()->OnIgnoreRegisterProtocolHandler(stuff_protocol_handler); - ASSERT_TRUE(registry()->IsHandledProtocol("test")); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); ASSERT_TRUE(registry()->IsIgnored(stuff_protocol_handler)); delegate()->Reset(); RecreateRegistry(true); - ASSERT_TRUE(registry()->IsHandledProtocol("test")); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); ASSERT_TRUE(registry()->IsIgnored(stuff_protocol_handler)); } TEST_F(ProtocolHandlerRegistryTest, Encode) { base::Time now = base::Time::Now(); - ProtocolHandler handler("test", GURL("http://example.com"), now); + ProtocolHandler handler("news", GURL("http://example.com"), now); auto value = handler.Encode(); ProtocolHandler recreated = ProtocolHandler::CreateProtocolHandler(value.get()); - EXPECT_EQ("test", recreated.protocol()); + EXPECT_EQ("news", recreated.protocol()); EXPECT_EQ(GURL("http://example.com"), recreated.url()); EXPECT_EQ(now, recreated.last_modified()); } @@ -363,9 +363,10 @@ TEST_F(ProtocolHandlerRegistryTest, GetHandlersBetween) { base::Time now = base::Time::Now(); base::Time one_hour_ago = now - base::TimeDelta::FromHours(1); base::Time two_hours_ago = now - base::TimeDelta::FromHours(2); - ProtocolHandler handler1("test1", GURL("http://example.com"), two_hours_ago); - ProtocolHandler handler2("test2", GURL("http://example.com"), one_hour_ago); - ProtocolHandler handler3("test3", GURL("http://example.com"), now); + ProtocolHandler handler1("bitcoin", GURL("http://example.com"), + two_hours_ago); + ProtocolHandler handler2("geo", GURL("http://example.com"), one_hour_ago); + ProtocolHandler handler3("im", GURL("http://example.com"), now); registry()->OnAcceptRegisterProtocolHandler(handler1); registry()->OnAcceptRegisterProtocolHandler(handler2); registry()->OnAcceptRegisterProtocolHandler(handler3); @@ -385,12 +386,12 @@ TEST_F(ProtocolHandlerRegistryTest, ClearHandlersBetween) { base::Time one_hour_ago = now - base::TimeDelta::FromHours(1); base::Time two_hours_ago = now - base::TimeDelta::FromHours(2); GURL url("http://example.com"); - ProtocolHandler handler1("test1", url, two_hours_ago); - ProtocolHandler handler2("test2", url, one_hour_ago); - ProtocolHandler handler3("test3", url, now); - ProtocolHandler ignored1("ignored1", url, two_hours_ago); - ProtocolHandler ignored2("ignored2", url, one_hour_ago); - ProtocolHandler ignored3("ignored3", url, now); + ProtocolHandler handler1("bitcoin", url, two_hours_ago); + ProtocolHandler handler2("geo", url, one_hour_ago); + ProtocolHandler handler3("im", url, now); + ProtocolHandler ignored1("irc", url, two_hours_ago); + ProtocolHandler ignored2("ircs", url, one_hour_ago); + ProtocolHandler ignored3("magnet", url, now); registry()->OnAcceptRegisterProtocolHandler(handler1); registry()->OnAcceptRegisterProtocolHandler(handler2); registry()->OnAcceptRegisterProtocolHandler(handler3); @@ -398,27 +399,27 @@ TEST_F(ProtocolHandlerRegistryTest, ClearHandlersBetween) { registry()->OnIgnoreRegisterProtocolHandler(ignored2); registry()->OnIgnoreRegisterProtocolHandler(ignored3); - EXPECT_TRUE(registry()->IsHandledProtocol("test1")); - EXPECT_TRUE(registry()->IsHandledProtocol("test2")); - EXPECT_TRUE(registry()->IsHandledProtocol("test3")); + EXPECT_TRUE(registry()->IsHandledProtocol("bitcoin")); + EXPECT_TRUE(registry()->IsHandledProtocol("geo")); + EXPECT_TRUE(registry()->IsHandledProtocol("im")); EXPECT_TRUE(registry()->IsIgnored(ignored1)); EXPECT_TRUE(registry()->IsIgnored(ignored2)); EXPECT_TRUE(registry()->IsIgnored(ignored3)); // Delete handler2 and ignored2. registry()->ClearUserDefinedHandlers(one_hour_ago, now); - EXPECT_TRUE(registry()->IsHandledProtocol("test1")); - EXPECT_FALSE(registry()->IsHandledProtocol("test2")); - EXPECT_TRUE(registry()->IsHandledProtocol("test3")); + EXPECT_TRUE(registry()->IsHandledProtocol("bitcoin")); + EXPECT_FALSE(registry()->IsHandledProtocol("geo")); + EXPECT_TRUE(registry()->IsHandledProtocol("im")); EXPECT_TRUE(registry()->IsIgnored(ignored1)); EXPECT_FALSE(registry()->IsIgnored(ignored2)); EXPECT_TRUE(registry()->IsIgnored(ignored3)); // Delete all. registry()->ClearUserDefinedHandlers(base::Time(), base::Time::Max()); - EXPECT_FALSE(registry()->IsHandledProtocol("test1")); - EXPECT_FALSE(registry()->IsHandledProtocol("test2")); - EXPECT_FALSE(registry()->IsHandledProtocol("test3")); + EXPECT_FALSE(registry()->IsHandledProtocol("bitcoin")); + EXPECT_FALSE(registry()->IsHandledProtocol("geo")); + EXPECT_FALSE(registry()->IsHandledProtocol("im")); EXPECT_FALSE(registry()->IsIgnored(ignored1)); EXPECT_FALSE(registry()->IsIgnored(ignored2)); EXPECT_FALSE(registry()->IsIgnored(ignored3)); @@ -433,15 +434,15 @@ TEST_F(ProtocolHandlerRegistryTest, TestEnabledDisabled) { TEST_F(ProtocolHandlerRegistryTest, DisallowRegisteringExternallyHandledProtocols) { - delegate()->RegisterExternalHandler("test"); - ASSERT_FALSE(registry()->CanSchemeBeOverridden("test")); + delegate()->RegisterExternalHandler("news"); + ASSERT_FALSE(registry()->CanSchemeBeOverridden("news")); } TEST_F(ProtocolHandlerRegistryTest, RemovingHandlerMeansItCanBeAddedAgain) { registry()->OnAcceptRegisterProtocolHandler(test_protocol_handler()); - ASSERT_TRUE(registry()->CanSchemeBeOverridden("test")); + ASSERT_TRUE(registry()->CanSchemeBeOverridden("news")); registry()->RemoveHandler(test_protocol_handler()); - ASSERT_TRUE(registry()->CanSchemeBeOverridden("test")); + ASSERT_TRUE(registry()->CanSchemeBeOverridden("news")); } TEST_F(ProtocolHandlerRegistryTest, TestStartsAsDefault) { @@ -450,31 +451,31 @@ TEST_F(ProtocolHandlerRegistryTest, TestStartsAsDefault) { } TEST_F(ProtocolHandlerRegistryTest, TestClearDefault) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); registry()->OnAcceptRegisterProtocolHandler(ph1); - registry()->ClearDefault("test"); + registry()->ClearDefault("news"); ASSERT_FALSE(registry()->IsDefault(ph1)); ASSERT_FALSE(registry()->IsDefault(ph2)); } TEST_F(ProtocolHandlerRegistryTest, TestGetHandlerFor) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); registry()->OnAcceptRegisterProtocolHandler(ph2); - ASSERT_EQ(ph2, registry()->GetHandlerFor("test")); - ASSERT_TRUE(registry()->IsHandledProtocol("test")); + ASSERT_EQ(ph2, registry()->GetHandlerFor("news")); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); } TEST_F(ProtocolHandlerRegistryTest, TestMostRecentHandlerIsDefault) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); ASSERT_FALSE(registry()->IsDefault(ph1)); @@ -482,8 +483,8 @@ TEST_F(ProtocolHandlerRegistryTest, TestMostRecentHandlerIsDefault) { } TEST_F(ProtocolHandlerRegistryTest, TestOnAcceptRegisterProtocolHandler) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); @@ -497,8 +498,8 @@ TEST_F(ProtocolHandlerRegistryTest, TestOnAcceptRegisterProtocolHandler) { } TEST_F(ProtocolHandlerRegistryTest, TestDefaultSaveLoad) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); registry()->OnDenyRegisterProtocolHandler(ph1); registry()->OnDenyRegisterProtocolHandler(ph2); @@ -517,13 +518,13 @@ TEST_F(ProtocolHandlerRegistryTest, TestDefaultSaveLoad) { } TEST_F(ProtocolHandlerRegistryTest, TestRemoveHandler) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->RemoveHandler(ph1); ASSERT_FALSE(registry()->IsRegistered(ph1)); - ASSERT_FALSE(registry()->IsHandledProtocol("test")); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); registry()->OnIgnoreRegisterProtocolHandler(ph1); ASSERT_FALSE(registry()->IsRegistered(ph1)); @@ -535,8 +536,8 @@ TEST_F(ProtocolHandlerRegistryTest, TestRemoveHandler) { } TEST_F(ProtocolHandlerRegistryTest, TestIsRegistered) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); @@ -544,8 +545,8 @@ TEST_F(ProtocolHandlerRegistryTest, TestIsRegistered) { } TEST_F(ProtocolHandlerRegistryTest, TestIsEquivalentRegistered) { - ProtocolHandler ph1 = CreateProtocolHandler("test", GURL("http://test/%s")); - ProtocolHandler ph2 = CreateProtocolHandler("test", GURL("http://test/%s")); + ProtocolHandler ph1 = CreateProtocolHandler("news", GURL("http://test/%s")); + ProtocolHandler ph2 = CreateProtocolHandler("news", GURL("http://test/%s")); registry()->OnAcceptRegisterProtocolHandler(ph1); ASSERT_TRUE(registry()->IsRegistered(ph1)); @@ -553,8 +554,8 @@ TEST_F(ProtocolHandlerRegistryTest, TestIsEquivalentRegistered) { } TEST_F(ProtocolHandlerRegistryTest, TestSilentlyRegisterHandler) { - ProtocolHandler ph1 = CreateProtocolHandler("test", GURL("http://test/1/%s")); - ProtocolHandler ph2 = CreateProtocolHandler("test", GURL("http://test/2/%s")); + ProtocolHandler ph1 = CreateProtocolHandler("news", GURL("http://test/1/%s")); + ProtocolHandler ph2 = CreateProtocolHandler("news", GURL("http://test/2/%s")); ProtocolHandler ph3 = CreateProtocolHandler("ignore", GURL("http://test/%s")); ProtocolHandler ph4 = CreateProtocolHandler("ignore", GURL("http://test/%s")); @@ -581,9 +582,9 @@ TEST_F(ProtocolHandlerRegistryTest, TestSilentlyRegisterHandler) { } TEST_F(ProtocolHandlerRegistryTest, TestRemoveHandlerRemovesDefault) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); - ProtocolHandler ph3 = CreateProtocolHandler("test", "test3"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); + ProtocolHandler ph3 = CreateProtocolHandler("news", "test3"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); @@ -595,15 +596,15 @@ TEST_F(ProtocolHandlerRegistryTest, TestRemoveHandlerRemovesDefault) { } TEST_F(ProtocolHandlerRegistryTest, TestGetHandlersFor) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); - ProtocolHandler ph2 = CreateProtocolHandler("test", "test2"); - ProtocolHandler ph3 = CreateProtocolHandler("test", "test3"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph2 = CreateProtocolHandler("news", "test2"); + ProtocolHandler ph3 = CreateProtocolHandler("news", "test3"); registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->OnAcceptRegisterProtocolHandler(ph2); registry()->OnAcceptRegisterProtocolHandler(ph3); ProtocolHandlerRegistry::ProtocolHandlerList handlers = - registry()->GetHandlersFor("test"); + registry()->GetHandlersFor("news"); ASSERT_EQ(static_cast<size_t>(3), handlers.size()); ASSERT_EQ(ph3, handlers[0]); @@ -616,7 +617,7 @@ TEST_F(ProtocolHandlerRegistryTest, TestGetRegisteredProtocols) { registry()->GetRegisteredProtocols(&protocols); ASSERT_EQ(static_cast<size_t>(0), protocols.size()); - registry()->GetHandlersFor("test"); + registry()->GetHandlersFor("news"); protocols.clear(); registry()->GetRegisteredProtocols(&protocols); @@ -624,12 +625,12 @@ TEST_F(ProtocolHandlerRegistryTest, TestGetRegisteredProtocols) { } TEST_F(ProtocolHandlerRegistryTest, TestIsHandledProtocol) { - registry()->GetHandlersFor("test"); - ASSERT_FALSE(registry()->IsHandledProtocol("test")); + registry()->GetHandlersFor("news"); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); } TEST_F(ProtocolHandlerRegistryTest, TestObserver) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); ProtocolHandlerChangeListener counter(registry()); registry()->OnAcceptRegisterProtocolHandler(ph1); @@ -651,43 +652,43 @@ TEST_F(ProtocolHandlerRegistryTest, TestObserver) { TEST_F(ProtocolHandlerRegistryTest, TestReentrantObserver) { QueryProtocolHandlerOnChange queryer(registry()); - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); registry()->OnAcceptRegisterProtocolHandler(ph1); ASSERT_TRUE(queryer.called()); } TEST_F(ProtocolHandlerRegistryTest, TestProtocolsWithNoDefaultAreHandled) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); registry()->OnAcceptRegisterProtocolHandler(ph1); - registry()->ClearDefault("test"); + registry()->ClearDefault("news"); std::vector<std::string> handled_protocols; registry()->GetRegisteredProtocols(&handled_protocols); ASSERT_EQ(static_cast<size_t>(1), handled_protocols.size()); - ASSERT_EQ("test", handled_protocols[0]); + ASSERT_EQ("news", handled_protocols[0]); } TEST_F(ProtocolHandlerRegistryTest, TestDisablePreventsHandling) { - ProtocolHandler ph1 = CreateProtocolHandler("test", "test1"); + ProtocolHandler ph1 = CreateProtocolHandler("news", "test1"); registry()->OnAcceptRegisterProtocolHandler(ph1); - ASSERT_TRUE(registry()->IsHandledProtocol("test")); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); registry()->Disable(); - ASSERT_FALSE(registry()->IsHandledProtocol("test")); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); } TEST_F(ProtocolHandlerRegistryTest, TestOSRegistration) { - ProtocolHandler ph_do1 = CreateProtocolHandler("do", "test1"); - ProtocolHandler ph_do2 = CreateProtocolHandler("do", "test2"); - ProtocolHandler ph_dont = CreateProtocolHandler("dont", "test"); + ProtocolHandler ph_do1 = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph_do2 = CreateProtocolHandler("news", "test2"); + ProtocolHandler ph_dont = CreateProtocolHandler("im", "test3"); - ASSERT_FALSE(delegate()->IsFakeRegisteredWithOS("do")); - ASSERT_FALSE(delegate()->IsFakeRegisteredWithOS("dont")); + ASSERT_FALSE(delegate()->IsFakeRegisteredWithOS("news")); + ASSERT_FALSE(delegate()->IsFakeRegisteredWithOS("im")); registry()->OnAcceptRegisterProtocolHandler(ph_do1); registry()->OnDenyRegisterProtocolHandler(ph_dont); base::RunLoop().RunUntilIdle(); - ASSERT_TRUE(delegate()->IsFakeRegisteredWithOS("do")); - ASSERT_FALSE(delegate()->IsFakeRegisteredWithOS("dont")); + ASSERT_TRUE(delegate()->IsFakeRegisteredWithOS("news")); + ASSERT_FALSE(delegate()->IsFakeRegisteredWithOS("im")); // This should not register with the OS, if it does the delegate // will assert for us. We don't need to wait for the message loop @@ -704,11 +705,11 @@ TEST_F(ProtocolHandlerRegistryTest, TestOSRegistration) { #endif TEST_F(ProtocolHandlerRegistryTest, MAYBE_TestOSRegistrationFailure) { - ProtocolHandler ph_do = CreateProtocolHandler("do", "test1"); - ProtocolHandler ph_dont = CreateProtocolHandler("dont", "test"); + ProtocolHandler ph_do = CreateProtocolHandler("news", "test1"); + ProtocolHandler ph_dont = CreateProtocolHandler("im", "test2"); - ASSERT_FALSE(registry()->IsHandledProtocol("do")); - ASSERT_FALSE(registry()->IsHandledProtocol("dont")); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); + ASSERT_FALSE(registry()->IsHandledProtocol("im")); registry()->OnAcceptRegisterProtocolHandler(ph_do); base::RunLoop().RunUntilIdle(); @@ -717,10 +718,10 @@ TEST_F(ProtocolHandlerRegistryTest, MAYBE_TestOSRegistrationFailure) { registry()->OnAcceptRegisterProtocolHandler(ph_dont); base::RunLoop().RunUntilIdle(); - ASSERT_TRUE(registry()->IsHandledProtocol("do")); - ASSERT_EQ(static_cast<size_t>(1), registry()->GetHandlersFor("do").size()); - ASSERT_FALSE(registry()->IsHandledProtocol("dont")); - ASSERT_EQ(static_cast<size_t>(1), registry()->GetHandlersFor("dont").size()); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); + ASSERT_EQ(static_cast<size_t>(1), registry()->GetHandlersFor("news").size()); + ASSERT_FALSE(registry()->IsHandledProtocol("im")); + ASSERT_EQ(static_cast<size_t>(1), registry()->GetHandlersFor("im").size()); } TEST_F(ProtocolHandlerRegistryTest, TestRemovingDefaultFallsBackToOldDefault) { @@ -822,17 +823,17 @@ TEST_F(ProtocolHandlerRegistryTest, TestIsSameOrigin) { TEST_F(ProtocolHandlerRegistryTest, TestInstallDefaultHandler) { RecreateRegistry(false); registry()->AddPredefinedHandler( - CreateProtocolHandler("test", GURL("http://test.com/%s"))); + CreateProtocolHandler("news", GURL("http://test.com/%s"))); registry()->InitProtocolSettings(); std::vector<std::string> protocols; registry()->GetRegisteredProtocols(&protocols); ASSERT_EQ(static_cast<size_t>(1), protocols.size()); - EXPECT_TRUE(registry()->IsHandledProtocol("test")); + EXPECT_TRUE(registry()->IsHandledProtocol("news")); auto handlers = registry()->GetUserDefinedHandlers(base::Time(), base::Time::Max()); EXPECT_TRUE(handlers.empty()); registry()->ClearUserDefinedHandlers(base::Time(), base::Time::Max()); - EXPECT_TRUE(registry()->IsHandledProtocol("test")); + EXPECT_TRUE(registry()->IsHandledProtocol("news")); } #define URL_p1u1 "http://p1u1.com/%s" @@ -847,16 +848,16 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapRegister) { base::ListValue handlers_registered_by_policy; handlers_registered_by_pref.Append( - GetProtocolHandlerValueWithDefault("p1", URL_p1u2, true)); + GetProtocolHandlerValueWithDefault("news", URL_p1u2, true)); handlers_registered_by_pref.Append( - GetProtocolHandlerValueWithDefault("p1", URL_p1u1, true)); + GetProtocolHandlerValueWithDefault("news", URL_p1u1, true)); handlers_registered_by_pref.Append( - GetProtocolHandlerValueWithDefault("p1", URL_p1u2, false)); + GetProtocolHandlerValueWithDefault("news", URL_p1u2, false)); handlers_registered_by_policy.Append( - GetProtocolHandlerValueWithDefault("p1", URL_p1u1, false)); + GetProtocolHandlerValueWithDefault("news", URL_p1u1, false)); handlers_registered_by_policy.Append( - GetProtocolHandlerValueWithDefault("p3", URL_p3u1, true)); + GetProtocolHandlerValueWithDefault("mailto", URL_p3u1, true)); profile()->GetPrefs()->Set(prefs::kRegisteredProtocolHandlers, handlers_registered_by_pref); @@ -865,14 +866,14 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapRegister) { registry()->InitProtocolSettings(); // Duplicate p1u2 eliminated in memory but not yet saved in pref - ProtocolHandler p1u1 = CreateProtocolHandler("p1", GURL(URL_p1u1)); - ProtocolHandler p1u2 = CreateProtocolHandler("p1", GURL(URL_p1u2)); + ProtocolHandler p1u1 = CreateProtocolHandler("news", GURL(URL_p1u1)); + ProtocolHandler p1u2 = CreateProtocolHandler("news", GURL(URL_p1u2)); ASSERT_EQ(InPrefHandlerCount(), 3); ASSERT_EQ(InMemoryHandlerCount(), 3); ASSERT_TRUE(registry()->IsDefault(p1u1)); ASSERT_FALSE(registry()->IsDefault(p1u2)); - ProtocolHandler p2u1 = CreateProtocolHandler("p2", GURL(URL_p2u1)); + ProtocolHandler p2u1 = CreateProtocolHandler("im", GURL(URL_p2u1)); registry()->OnDenyRegisterProtocolHandler(p2u1); // Duplicate p1u2 saved in pref and a new handler added to pref and memory @@ -887,7 +888,7 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapRegister) { ASSERT_EQ(InMemoryHandlerCount(), 4); ASSERT_TRUE(registry()->IsDefault(p1u1)); - ProtocolHandler p3u1 = CreateProtocolHandler("p3", GURL(URL_p3u1)); + ProtocolHandler p3u1 = CreateProtocolHandler("mailto", GURL(URL_p3u1)); registry()->RemoveHandler(p3u1); // p3u1 not removed from memory due to policy and it was never in pref. @@ -902,7 +903,7 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapRegister) { ASSERT_EQ(InMemoryHandlerCount(), 3); ASSERT_TRUE(registry()->IsDefault(p1u1)); - ProtocolHandler p1u3 = CreateProtocolHandler("p1", GURL(URL_p1u3)); + ProtocolHandler p1u3 = CreateProtocolHandler("news", GURL(URL_p1u3)); registry()->OnAcceptRegisterProtocolHandler(p1u3); // p1u3 added to pref and memory. @@ -926,14 +927,14 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapIgnore) { base::ListValue handlers_ignored_by_pref; base::ListValue handlers_ignored_by_policy; - handlers_ignored_by_pref.Append(GetProtocolHandlerValue("p1", URL_p1u1)); - handlers_ignored_by_pref.Append(GetProtocolHandlerValue("p1", URL_p1u2)); - handlers_ignored_by_pref.Append(GetProtocolHandlerValue("p1", URL_p1u2)); - handlers_ignored_by_pref.Append(GetProtocolHandlerValue("p3", URL_p3u1)); + handlers_ignored_by_pref.Append(GetProtocolHandlerValue("news", URL_p1u1)); + handlers_ignored_by_pref.Append(GetProtocolHandlerValue("news", URL_p1u2)); + handlers_ignored_by_pref.Append(GetProtocolHandlerValue("news", URL_p1u2)); + handlers_ignored_by_pref.Append(GetProtocolHandlerValue("mailto", URL_p3u1)); - handlers_ignored_by_policy.Append(GetProtocolHandlerValue("p1", URL_p1u2)); - handlers_ignored_by_policy.Append(GetProtocolHandlerValue("p1", URL_p1u3)); - handlers_ignored_by_policy.Append(GetProtocolHandlerValue("p2", URL_p2u1)); + handlers_ignored_by_policy.Append(GetProtocolHandlerValue("news", URL_p1u2)); + handlers_ignored_by_policy.Append(GetProtocolHandlerValue("news", URL_p1u3)); + handlers_ignored_by_policy.Append(GetProtocolHandlerValue("im", URL_p2u1)); profile()->GetPrefs()->Set(prefs::kIgnoredProtocolHandlers, handlers_ignored_by_pref); @@ -945,21 +946,21 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapIgnore) { ASSERT_EQ(InPrefIgnoredHandlerCount(), 4); ASSERT_EQ(InMemoryIgnoredHandlerCount(), 5); - ProtocolHandler p2u2 = CreateProtocolHandler("p2", GURL(URL_p2u2)); + ProtocolHandler p2u2 = CreateProtocolHandler("im", GURL(URL_p2u2)); registry()->OnIgnoreRegisterProtocolHandler(p2u2); // Duplicate p1u2 eliminated in pref, p2u2 added to pref and memory. ASSERT_EQ(InPrefIgnoredHandlerCount(), 4); ASSERT_EQ(InMemoryIgnoredHandlerCount(), 6); - ProtocolHandler p2u1 = CreateProtocolHandler("p2", GURL(URL_p2u1)); + ProtocolHandler p2u1 = CreateProtocolHandler("im", GURL(URL_p2u1)); registry()->RemoveIgnoredHandler(p2u1); // p2u1 installed by policy so cant be removed. ASSERT_EQ(InPrefIgnoredHandlerCount(), 4); ASSERT_EQ(InMemoryIgnoredHandlerCount(), 6); - ProtocolHandler p1u2 = CreateProtocolHandler("p1", GURL(URL_p1u2)); + ProtocolHandler p1u2 = CreateProtocolHandler("news", GURL(URL_p1u2)); registry()->RemoveIgnoredHandler(p1u2); // p1u2 installed by policy and pref so it is removed from pref and not from @@ -967,7 +968,7 @@ TEST_F(ProtocolHandlerRegistryTest, TestPrefPolicyOverlapIgnore) { ASSERT_EQ(InPrefIgnoredHandlerCount(), 3); ASSERT_EQ(InMemoryIgnoredHandlerCount(), 6); - ProtocolHandler p1u1 = CreateProtocolHandler("p1", GURL(URL_p1u1)); + ProtocolHandler p1u1 = CreateProtocolHandler("news", GURL(URL_p1u1)); registry()->RemoveIgnoredHandler(p1u1); // p1u1 installed by pref so it is removed from pref and memory. @@ -1060,7 +1061,7 @@ TEST_F(ProtocolHandlerRegistryTest, TestURIPercentEncoding) { TEST_F(ProtocolHandlerRegistryTest, TestMultiplePlaceholders) { ProtocolHandler ph = - CreateProtocolHandler("test", GURL("http://example.com/%s/url=%s")); + CreateProtocolHandler("news", GURL("http://example.com/%s/url=%s")); registry()->OnAcceptRegisterProtocolHandler(ph); GURL translated_url = ph.TranslateUrl(GURL("test:duplicated_placeholders")); @@ -1070,3 +1071,42 @@ TEST_F(ProtocolHandlerRegistryTest, TestMultiplePlaceholders) { ASSERT_EQ(translated_url, GURL("http://example.com/test%3Aduplicated_placeholders/url=%s")); } + +TEST_F(ProtocolHandlerRegistryTest, InvalidHandlers) { + // Invalid protocol. + registry()->OnAcceptRegisterProtocolHandler( + CreateProtocolHandler("foo", GURL("https://www.google.com/handler%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("foo")); + registry()->OnAcceptRegisterProtocolHandler( + CreateProtocolHandler("web", GURL("https://www.google.com/handler%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("web")); + registry()->OnAcceptRegisterProtocolHandler( + CreateProtocolHandler("web+", GURL("https://www.google.com/handler%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("web+")); + registry()->OnAcceptRegisterProtocolHandler( + CreateProtocolHandler("https", GURL("https://www.google.com/handler%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("https")); + + // Invalid handler URL. + // data: URL. + registry()->OnAcceptRegisterProtocolHandler(CreateProtocolHandler( + "news", + GURL("data:text/html,<html><body><b>hello world</b></body></html>%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); + // ftp:// URL. + registry()->OnAcceptRegisterProtocolHandler( + CreateProtocolHandler("news", GURL("ftp://www.google.com/handler%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); + // blob:// URL + registry()->OnAcceptRegisterProtocolHandler(CreateProtocolHandler( + "news", GURL("blob:https://www.google.com/" + "f2d8c47d-17d0-4bf5-8f0a-76e42cbed3bf/%s"))); + ASSERT_FALSE(registry()->IsHandledProtocol("news")); +} + +TEST_F(ProtocolHandlerRegistryTest, ExtensionHandler) { + registry()->OnAcceptRegisterProtocolHandler(CreateProtocolHandler( + "news", + GURL("chrome-extension://abcdefghijklmnopqrstuvwxyzabcdef/test.html"))); + ASSERT_TRUE(registry()->IsHandledProtocol("news")); +} diff --git a/chromium/chrome/browser/devtools/BUILD.gn b/chromium/chrome/browser/devtools/BUILD.gn index 3ea4479e121..36b76413f8e 100644 --- a/chromium/chrome/browser/devtools/BUILD.gn +++ b/chromium/chrome/browser/devtools/BUILD.gn @@ -100,7 +100,7 @@ static_library("devtools") { "//base", "//content/public/browser", "//net", - "//services/viz/privileged/interfaces/compositing", + "//services/viz/privileged/mojom/compositing", "//third_party/blink/public:buildflags", "//ui/events:dom_keycode_converter", ] diff --git a/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc b/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc index 758309f7793..1a9f5bbf099 100644 --- a/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc +++ b/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc @@ -625,7 +625,7 @@ void MockAndroidConnection::SendHTTPResponse(const std::string& body) { void StartMockAdbServer(FlushMode flush_mode) { base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&StartMockAdbServerOnIOThread, flush_mode), run_loop.QuitClosure()); @@ -634,8 +634,8 @@ void StartMockAdbServer(FlushMode flush_mode) { void StopMockAdbServer() { base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&StopMockAdbServerOnIOThread), - run_loop.QuitClosure()); + base::PostTaskAndReply(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&StopMockAdbServerOnIOThread), + run_loop.QuitClosure()); run_loop.Run(); } diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.cc b/chromium/chrome/browser/devtools/device/android_device_manager.cc index ce20fba0441..a59205407f5 100644 --- a/chromium/chrome/browser/devtools/device/android_device_manager.cc +++ b/chromium/chrome/browser/devtools/device/android_device_manager.cc @@ -12,7 +12,7 @@ #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" +#include "base/message_loop/message_pump_type.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -381,8 +381,8 @@ class DevicesRequest : public base::RefCountedThreadSafe<DevicesRequest> { void OnCountDevices(const base::Callback<void(int)>& callback, int device_count) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, device_count)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, device_count)); } } // namespace @@ -516,7 +516,7 @@ AndroidDeviceManager::HandlerThread::HandlerThread() { instance_ = this; thread_ = new base::Thread(kDevToolsAdbBridgeThreadName); base::Thread::Options options; - options.message_loop_type = base::MessageLoop::TYPE_IO; + options.message_pump_type = base::MessagePumpType::IO; if (!thread_->StartWithOptions(options)) { delete thread_; thread_ = nullptr; @@ -540,10 +540,10 @@ AndroidDeviceManager::HandlerThread::~HandlerThread() { if (!thread_) return; // Shut down thread on a thread other than UI so it can join a thread. - base::PostTaskWithTraits( - FROM_HERE, - {base::WithBaseSyncPrimitives(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(&HandlerThread::StopThread, thread_)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::WithBaseSyncPrimitives(), + base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&HandlerThread::StopThread, thread_)); } // static @@ -574,7 +574,7 @@ void AndroidDeviceManager::CountDevices( } void AndroidDeviceManager::set_usb_device_manager_for_test( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager) { + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager) { DCHECK_CURRENTLY_ON(BrowserThread::UI); handler_thread_->message_loop()->PostTask( FROM_HERE, diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.h b/chromium/chrome/browser/devtools/device/android_device_manager.h index b97c7e6f47b..942ac4b78c5 100644 --- a/chromium/chrome/browser/devtools/device/android_device_manager.h +++ b/chromium/chrome/browser/devtools/device/android_device_manager.h @@ -18,6 +18,7 @@ #include "base/single_thread_task_runner.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/mojom/usb_manager.mojom.h" #include "ui/gfx/geometry/size.h" @@ -204,7 +205,7 @@ class AndroidDeviceManager { void CountDevices(const base::Callback<void(int)>& callback); void set_usb_device_manager_for_test( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager); + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager); static std::string GetBrowserName(const std::string& socket, const std::string& package); diff --git a/chromium/chrome/browser/devtools/device/cast_device_provider.cc b/chromium/chrome/browser/devtools/device/cast_device_provider.cc index e0a6bed0609..8cae795aa7e 100644 --- a/chromium/chrome/browser/devtools/device/cast_device_provider.cc +++ b/chromium/chrome/browser/devtools/device/cast_device_provider.cc @@ -156,10 +156,9 @@ void CastDeviceProvider::QueryDevices(const SerialsCallback& callback) { if (!lister_delegate_) { lister_delegate_.reset(new DeviceListerDelegate( weak_factory_.GetWeakPtr(), base::ThreadTaskRunnerHandle::Get())); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&DeviceListerDelegate::StartDiscovery, - lister_delegate_->AsWeakPtr())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&DeviceListerDelegate::StartDiscovery, + lister_delegate_->AsWeakPtr())); } std::set<net::HostPortPair> targets; for (const auto& device_entry : device_info_map_) diff --git a/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc b/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc index 2aeaad3f5cd..ec895142198 100644 --- a/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc +++ b/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc @@ -400,6 +400,6 @@ void DevToolsAndroidBridge::set_tcp_provider_callback_for_test( } void DevToolsAndroidBridge::set_usb_device_manager_for_test( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager) { + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager) { device_manager_->set_usb_device_manager_for_test(std::move(fake_usb_manager)); } diff --git a/chromium/chrome/browser/devtools/device/devtools_android_bridge.h b/chromium/chrome/browser/devtools/device/devtools_android_bridge.h index 6dede6d0b6f..b2d2e497be9 100644 --- a/chromium/chrome/browser/devtools/device/devtools_android_bridge.h +++ b/chromium/chrome/browser/devtools/device/devtools_android_bridge.h @@ -23,6 +23,7 @@ #include "components/prefs/pref_change_registrar.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/devtools_agent_host.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "ui/gfx/geometry/size.h" namespace base { @@ -136,7 +137,7 @@ class DevToolsAndroidBridge : public KeyedService { base::Callback<void(scoped_refptr<TCPDeviceProvider>)>; void set_tcp_provider_callback_for_test(TCPProviderCallback callback); void set_usb_device_manager_for_test( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager); + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager); void Shutdown() override; diff --git a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc index 101cddf50a6..b623a1475a4 100644 --- a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc +++ b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc @@ -46,9 +46,8 @@ const char kPageReloadCommand[] = "{'method': 'Page.reload', id: 1}"; const char kWebViewSocketPrefix[] = "webview_devtools_remote"; static void ScheduleTaskDefault(const base::Closure& task) { - base::PostDelayedTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, task, - base::TimeDelta::FromMilliseconds(kPollingIntervalMs)); + base::PostDelayedTask(FROM_HERE, {BrowserThread::UI}, task, + base::TimeDelta::FromMilliseconds(kPollingIntervalMs)); } // ProtocolCommand ------------------------------------------------------------ diff --git a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc index be43c35de89..99fe24c6d13 100644 --- a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc +++ b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc @@ -231,9 +231,9 @@ class SocketTunnel { adb_thread_runner_(base::ThreadTaskRunnerHandle::Get()) { ResolveHostCallback resolve_host_callback = base::BindOnce( &SocketTunnel::OnResolveHostComplete, base::Unretained(this)); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ResolveHost, profile, host, port, - std::move(resolve_host_callback))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ResolveHost, profile, host, port, + std::move(resolve_host_callback))); } void OnResolveHostComplete(net::AddressList resolved_addresses) { diff --git a/chromium/chrome/browser/devtools/device/tcp_device_provider.cc b/chromium/chrome/browser/devtools/device/tcp_device_provider.cc index 48a1ca318db..49f340aae90 100644 --- a/chromium/chrome/browser/devtools/device/tcp_device_provider.cc +++ b/chromium/chrome/browser/devtools/device/tcp_device_provider.cc @@ -157,10 +157,9 @@ TCPDeviceProvider::~TCPDeviceProvider() { } void TCPDeviceProvider::InitializeHostResolver() { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&TCPDeviceProvider::InitializeHostResolverOnUI, this, - mojo::MakeRequest(&host_resolver_))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&TCPDeviceProvider::InitializeHostResolverOnUI, + this, mojo::MakeRequest(&host_resolver_))); host_resolver_.set_connection_error_handler(base::BindOnce( &TCPDeviceProvider::InitializeHostResolver, base::Unretained(this))); } 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 8da28afc32a..e487f57418c 100644 --- a/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc +++ b/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc @@ -27,6 +27,9 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_utils.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "services/device/public/cpp/test/fake_usb_device.h" #include "services/device/public/cpp/test/fake_usb_device_info.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" @@ -204,20 +207,22 @@ class MockLocalSocket : public MockAndroidConnection::Delegate { class FakeAndroidUsbDevice : public FakeUsbDevice { public: - static void Create(scoped_refptr<FakeUsbDeviceInfo> device_info, - device::mojom::UsbDeviceRequest request, - device::mojom::UsbDeviceClientPtr client) { + static void Create( + scoped_refptr<FakeUsbDeviceInfo> device_info, + mojo::PendingReceiver<device::mojom::UsbDevice> receiver, + mojo::PendingRemote<device::mojom::UsbDeviceClient> client) { auto* device_object = new FakeAndroidUsbDevice(device_info, std::move(client)); - device_object->binding_ = mojo::MakeStrongBinding( - base::WrapUnique(device_object), std::move(request)); + device_object->receiver_ = mojo::MakeSelfOwnedReceiver( + base::WrapUnique(device_object), std::move(receiver)); } ~FakeAndroidUsbDevice() override = default; protected: - FakeAndroidUsbDevice(scoped_refptr<FakeUsbDeviceInfo> device, - device::mojom::UsbDeviceClientPtr client) + FakeAndroidUsbDevice( + scoped_refptr<FakeUsbDeviceInfo> device, + mojo::PendingRemote<device::mojom::UsbDeviceClient> client) : FakeUsbDevice(device, std::move(client)) { broken_traits_ = static_cast<FakeAndroidUsbDeviceInfo*>(device.get())->broken_traits(); @@ -420,11 +425,13 @@ class FakeAndroidUsbManager : public FakeUsbDeviceManager { FakeAndroidUsbManager() = default; ~FakeAndroidUsbManager() override = default; - void GetDevice(const std::string& guid, - device::mojom::UsbDeviceRequest device_request, - device::mojom::UsbDeviceClientPtr device_client) override { + void GetDevice( + const std::string& guid, + mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver, + mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client) + override { DCHECK(base::Contains(devices(), guid)); - FakeAndroidUsbDevice::Create(devices()[guid], std::move(device_request), + FakeAndroidUsbDevice::Create(devices()[guid], std::move(device_receiver), std::move(device_client)); } }; @@ -510,15 +517,15 @@ class AndroidUsbDiscoveryTest : public InProcessBrowserTest { // Set a fake USB device manager for AndroidUsbDevice. usb_manager_ = CreateFakeUsbManager(); DCHECK(usb_manager_); - device::mojom::UsbDeviceManagerPtrInfo manager_ptr_info; - usb_manager_->AddBinding(mojo::MakeRequest(&manager_ptr_info)); - adb_bridge_->set_usb_device_manager_for_test(std::move(manager_ptr_info)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> manager; + usb_manager_->AddReceiver(manager.InitWithNewPipeAndPassReceiver()); + adb_bridge_->set_usb_device_manager_for_test(std::move(manager)); } void ScheduleDeviceCountRequest(const base::Closure& request) { DCHECK_CURRENTLY_ON(BrowserThread::UI); scheduler_invoked_++; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, request); + base::PostTask(FROM_HERE, {BrowserThread::UI}, request); } virtual std::unique_ptr<FakeUsbDeviceManager> CreateFakeUsbManager() { diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc b/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc index 66b9c619609..1229c477a88 100644 --- a/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc +++ b/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc @@ -98,58 +98,59 @@ void OnProbeFinished(const AndroidUsbDevicesCallback& callback, } void OnDeviceClosed(const std::string& guid, - device::mojom::UsbDevicePtr device_ptr) { + mojo::Remote<device::mojom::UsbDevice> device) { base::Erase(g_open_devices.Get(), guid); } void OnDeviceClosedWithBarrier(const std::string& guid, - device::mojom::UsbDevicePtr device_ptr, + mojo::Remote<device::mojom::UsbDevice> device, const base::RepeatingClosure& barrier) { base::Erase(g_open_devices.Get(), guid); barrier.Run(); } -void CreateDeviceOnInterfaceClaimed(AndroidUsbDevices* devices, - crypto::RSAPrivateKey* rsa_key, - AndroidDeviceInfo android_device_info, - device::mojom::UsbDevicePtr device_ptr, - const base::RepeatingClosure& barrier, - bool success) { +void CreateDeviceOnInterfaceClaimed( + AndroidUsbDevices* devices, + crypto::RSAPrivateKey* rsa_key, + AndroidDeviceInfo android_device_info, + mojo::Remote<device::mojom::UsbDevice> device, + const base::RepeatingClosure& barrier, + bool success) { if (success) { - devices->push_back(new AndroidUsbDevice(rsa_key, android_device_info, - std::move(device_ptr))); + devices->push_back( + new AndroidUsbDevice(rsa_key, android_device_info, std::move(device))); barrier.Run(); } else { - auto* device = device_ptr.get(); - device->Close(base::BindOnce(&OnDeviceClosedWithBarrier, - android_device_info.guid, - std::move(device_ptr), barrier)); + auto* device_raw = device.get(); + device_raw->Close(base::BindOnce(&OnDeviceClosedWithBarrier, + android_device_info.guid, + std::move(device), barrier)); } } -void OnInterfaceReleased(device::mojom::UsbDevicePtr device_ptr, +void OnInterfaceReleased(mojo::Remote<device::mojom::UsbDevice> device, const std::string& guid, bool release_successful) { - auto* device = device_ptr.get(); - device->Close(base::BindOnce(&OnDeviceClosed, guid, std::move(device_ptr))); + auto* device_raw = device.get(); + device_raw->Close(base::BindOnce(&OnDeviceClosed, guid, std::move(device))); } void OnDeviceOpened(AndroidUsbDevices* devices, crypto::RSAPrivateKey* rsa_key, AndroidDeviceInfo android_device_info, - device::mojom::UsbDevicePtr device_ptr, + mojo::Remote<device::mojom::UsbDevice> device, const base::RepeatingClosure& barrier, device::mojom::UsbOpenDeviceError error) { // For UsbOpenDeviceError::OK and UsbOpenDeviceError::ALREADY_OPEN we all try // to claim the interface because the device may be opened by other modules or // extensions for different interface. if (error != device::mojom::UsbOpenDeviceError::ACCESS_DENIED) { - DCHECK(device_ptr); - auto* device = device_ptr.get(); - device->ClaimInterface( + DCHECK(device); + auto* device_raw = device.get(); + device_raw->ClaimInterface( android_device_info.interface_id, base::BindOnce(&CreateDeviceOnInterfaceClaimed, devices, rsa_key, - android_device_info, std::move(device_ptr), barrier)); + android_device_info, std::move(device), barrier)); } else { base::Erase(g_open_devices.Get(), android_device_info.guid); barrier.Run(); @@ -174,12 +175,12 @@ void OpenAndroidDevices(crypto::RSAPrivateKey* rsa_key, } g_open_devices.Get().push_back(device_info.guid); - device::mojom::UsbDevicePtr device_ptr; + mojo::Remote<device::mojom::UsbDevice> device; UsbDeviceManagerHelper::GetInstance()->GetDevice( - device_info.guid, mojo::MakeRequest(&device_ptr)); - auto* device = device_ptr.get(); - device->Open(base::BindOnce(&OnDeviceOpened, devices, rsa_key, device_info, - std::move(device_ptr), barrier)); + device_info.guid, device.BindNewPipeAndPassReceiver()); + auto* device_raw = device.get(); + device_raw->Open(base::BindOnce(&OnDeviceOpened, devices, rsa_key, + device_info, std::move(device), barrier)); } } @@ -200,17 +201,18 @@ void AndroidUsbDevice::Enumerate(crypto::RSAPrivateKey* rsa_key, base::BindOnce(&OpenAndroidDevices, rsa_key, callback)); } -AndroidUsbDevice::AndroidUsbDevice(crypto::RSAPrivateKey* rsa_key, - const AndroidDeviceInfo& android_device_info, - device::mojom::UsbDevicePtr device_ptr) +AndroidUsbDevice::AndroidUsbDevice( + crypto::RSAPrivateKey* rsa_key, + const AndroidDeviceInfo& android_device_info, + mojo::Remote<device::mojom::UsbDevice> device) : rsa_key_(rsa_key->Copy()), - device_ptr_(std::move(device_ptr)), + device_(std::move(device)), android_device_info_(android_device_info), is_connected_(false), signature_sent_(false), last_socket_id_(256) { - DCHECK(device_ptr_); - device_ptr_.set_connection_error_handler( + DCHECK(device_); + device_.set_disconnect_handler( base::BindOnce(&AndroidUsbDevice::Terminate, weak_factory_.GetWeakPtr())); } @@ -224,8 +226,8 @@ void AndroidUsbDevice::InitOnCallerThread() { } net::StreamSocket* AndroidUsbDevice::CreateSocket(const std::string& command) { - if (!device_ptr_) - return NULL; + if (!device_) + return nullptr; uint32_t socket_id = ++last_socket_id_; sockets_[socket_id] = new AndroidUsbSocket( @@ -298,17 +300,17 @@ void AndroidUsbDevice::Queue(std::unique_ptr<AdbMessage> message) { void AndroidUsbDevice::ProcessOutgoing() { DCHECK(task_runner_->BelongsToCurrentThread()); - if (outgoing_queue_.empty() || !device_ptr_) + if (outgoing_queue_.empty() || !device_) return; BulkMessage message = outgoing_queue_.front(); outgoing_queue_.pop(); DumpMessage(true, message->front(), message->size()); - device_ptr_->GenericTransferOut( - android_device_info_.outbound_address, message->data(), kUsbTimeout, - base::Bind(&AndroidUsbDevice::OutgoingMessageSent, - weak_factory_.GetWeakPtr())); + device_->GenericTransferOut(android_device_info_.outbound_address, + message->data(), kUsbTimeout, + base::Bind(&AndroidUsbDevice::OutgoingMessageSent, + weak_factory_.GetWeakPtr())); } void AndroidUsbDevice::OutgoingMessageSent(UsbTransferStatus status) { @@ -321,10 +323,10 @@ void AndroidUsbDevice::OutgoingMessageSent(UsbTransferStatus status) { void AndroidUsbDevice::ReadHeader() { DCHECK(task_runner_->BelongsToCurrentThread()); - if (!device_ptr_) + if (!device_) return; - device_ptr_->GenericTransferIn( + device_->GenericTransferIn( android_device_info_.inbound_address, kHeaderSize, kUsbTimeout, base::Bind(&AndroidUsbDevice::ParseHeader, weak_factory_.GetWeakPtr())); } @@ -372,11 +374,11 @@ void AndroidUsbDevice::ReadBody(std::unique_ptr<AdbMessage> message, uint32_t data_check) { DCHECK(task_runner_->BelongsToCurrentThread()); - if (!device_ptr_.get()) { + if (!device_.get()) { return; } - device_ptr_->GenericTransferIn( + device_->GenericTransferIn( android_device_info_.inbound_address, data_length, kUsbTimeout, base::Bind(&AndroidUsbDevice::ParseBody, weak_factory_.GetWeakPtr(), base::Passed(&message), data_length, data_check)); @@ -479,16 +481,16 @@ void AndroidUsbDevice::Terminate() { // For connection error, remove the guid from recored opening/opened list. // For transfer errors, we'll do this after releasing the interface. - if (!device_ptr_) { + if (!device_) { base::Erase(g_open_devices.Get(), android_device_info_.guid); return; } // For Transfer error case. - // Make sure we zero-out |device_ptr_| so that closing connections did not + // Make sure we zero-out |device_| so that closing connections did not // open new socket connections. - device::mojom::UsbDevicePtr device_ptr = std::move(device_ptr_); - device_ptr_.reset(); + mojo::Remote<device::mojom::UsbDevice> device = std::move(device_); + device_.reset(); // Iterate over copy. AndroidUsbSockets sockets(sockets_); @@ -497,10 +499,10 @@ void AndroidUsbDevice::Terminate() { } DCHECK(sockets_.empty()); - auto* device = device_ptr.get(); - device->ReleaseInterface( + auto* device_raw = device.get(); + device_raw->ReleaseInterface( android_device_info_.interface_id, - base::BindOnce(&OnInterfaceReleased, std::move(device_ptr), + base::BindOnce(&OnInterfaceReleased, std::move(device), android_device_info_.guid)); } diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_device.h b/chromium/chrome/browser/devtools/device/usb/android_usb_device.h index cad570fe003..3a66cdba358 100644 --- a/chromium/chrome/browser/devtools/device/usb/android_usb_device.h +++ b/chromium/chrome/browser/devtools/device/usb/android_usb_device.h @@ -18,6 +18,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/devtools/device/usb/usb_device_manager_helper.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/usb_device.mojom.h" namespace base { @@ -80,7 +81,7 @@ class AndroidUsbDevice : public base::RefCountedThreadSafe<AndroidUsbDevice> { AndroidUsbDevice(crypto::RSAPrivateKey* rsa_key, const AndroidDeviceInfo& android_device_info, - device::mojom::UsbDevicePtr device_ptr); + mojo::Remote<device::mojom::UsbDevice> device); void InitOnCallerThread(); @@ -133,7 +134,7 @@ class AndroidUsbDevice : public base::RefCountedThreadSafe<AndroidUsbDevice> { std::unique_ptr<crypto::RSAPrivateKey> rsa_key_; // Device info - device::mojom::UsbDevicePtr device_ptr_; + mojo::Remote<device::mojom::UsbDevice> device_; AndroidDeviceInfo android_device_info_; bool is_connected_; diff --git a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc index 78884250899..b45c11ae051 100644 --- a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc +++ b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc @@ -15,6 +15,8 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/system_connector.h" #include "mojo/public/cpp/bindings/callback_helpers.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/mojom/constants.mojom.h" #include "services/device/public/mojom/usb_enumeration_options.mojom.h" #include "services/service_manager/public/cpp/connector.h" @@ -104,11 +106,11 @@ void CountAndroidDevices(base::OnceCallback<void(int)> callback, } void BindDeviceServiceOnUIThread( - device::mojom::UsbDeviceManagerRequest request) { + mojo::PendingReceiver<device::mojom::UsbDeviceManager> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Bind to the DeviceService for USB device manager. - content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, - std::move(request)); + content::GetSystemConnector()->Connect(device::mojom::kServiceName, + std::move(receiver)); } } // namespace @@ -147,7 +149,7 @@ void UsbDeviceManagerHelper::CountDevices( // static void UsbDeviceManagerHelper::SetUsbManagerForTesting( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager) { + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager) { GetInstance()->SetUsbManagerForTestingInternal(std::move(fake_usb_manager)); } @@ -171,12 +173,12 @@ void UsbDeviceManagerHelper::GetAndroidDevices( void UsbDeviceManagerHelper::GetDevice( const std::string& guid, - device::mojom::UsbDeviceRequest device_request) { + mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver) { EnsureUsbDeviceManagerConnection(); DCHECK(device_manager_); - device_manager_->GetDevice(guid, std::move(device_request), - /*device_client=*/nullptr); + device_manager_->GetDevice(guid, std::move(device_receiver), + /*device_client=*/mojo::NullRemote()); } void UsbDeviceManagerHelper::EnsureUsbDeviceManagerConnection() { @@ -186,23 +188,21 @@ void UsbDeviceManagerHelper::EnsureUsbDeviceManagerConnection() { return; // Just for testing. - if (testing_device_manager_info_) { - device_manager_.Bind(std::move(testing_device_manager_info_)); - device_manager_.set_connection_error_handler( + if (testing_device_manager_) { + device_manager_.Bind(std::move(testing_device_manager_)); + device_manager_.set_disconnect_handler( base::BindOnce(&UsbDeviceManagerHelper::OnDeviceManagerConnectionError, weak_factory_.GetWeakPtr())); return; } - device::mojom::UsbDeviceManagerRequest request = - mojo::MakeRequest(&device_manager_); - device_manager_.set_connection_error_handler( + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&BindDeviceServiceOnUIThread, + device_manager_.BindNewPipeAndPassReceiver())); + + device_manager_.set_disconnect_handler( base::BindOnce(&UsbDeviceManagerHelper::OnDeviceManagerConnectionError, weak_factory_.GetWeakPtr())); - - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&BindDeviceServiceOnUIThread, std::move(request))); } void UsbDeviceManagerHelper::CountDevicesInternal( @@ -219,10 +219,10 @@ void UsbDeviceManagerHelper::CountDevicesInternal( } void UsbDeviceManagerHelper::SetUsbManagerForTestingInternal( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager) { + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(fake_usb_manager); - testing_device_manager_info_ = std::move(fake_usb_manager); + testing_device_manager_ = std::move(fake_usb_manager); } void UsbDeviceManagerHelper::OnDeviceManagerConnectionError() { diff --git a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h index 5d7c7d48d2c..fbeeab96e65 100644 --- a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h +++ b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h @@ -9,6 +9,9 @@ #include <vector> #include "base/threading/thread_checker.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/usb_device.mojom.h" #include "services/device/public/mojom/usb_manager.mojom.h" @@ -49,7 +52,7 @@ class UsbDeviceManagerHelper { static UsbDeviceManagerHelper* GetInstance(); static void CountDevices(base::OnceCallback<void(int)> callback); static void SetUsbManagerForTesting( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager); + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager); // Please do not create UsbDeviceManagerHelper instance from this constructor // directly, use static method GetInstance() instead. @@ -58,19 +61,20 @@ class UsbDeviceManagerHelper { void GetAndroidDevices(AndroidDeviceInfoListCallback callback); - void GetDevice(const std::string& guid, - device::mojom::UsbDeviceRequest device_request); + void GetDevice( + const std::string& guid, + mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver); private: void CountDevicesInternal(base::OnceCallback<void(int)> callback); void SetUsbManagerForTestingInternal( - device::mojom::UsbDeviceManagerPtrInfo fake_usb_manager); + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_usb_manager); void EnsureUsbDeviceManagerConnection(); void OnDeviceManagerConnectionError(); - device::mojom::UsbDeviceManagerPtr device_manager_; + mojo::Remote<device::mojom::UsbDeviceManager> device_manager_; // Just for test. - device::mojom::UsbDeviceManagerPtrInfo testing_device_manager_info_; + mojo::PendingRemote<device::mojom::UsbDeviceManager> testing_device_manager_; THREAD_CHECKER(thread_checker_); diff --git a/chromium/chrome/browser/devtools/devtools_file_helper.cc b/chromium/chrome/browser/devtools/devtools_file_helper.cc index 546d65f0860..15cedcc5ed4 100644 --- a/chromium/chrome/browser/devtools/devtools_file_helper.cc +++ b/chromium/chrome/browser/devtools/devtools_file_helper.cc @@ -77,15 +77,17 @@ class SelectFileDialog : public ui::SelectFileDialog::Listener, void Show(ui::SelectFileDialog::Type type, const base::FilePath& default_path) { AddRef(); // Balanced in the three listener outcomes. + base::FilePath::StringType ext; + ui::SelectFileDialog::FileTypeInfo file_type_info; + if (type == ui::SelectFileDialog::SELECT_SAVEAS_FILE && + default_path.Extension().length() > 0) { + ext = default_path.Extension().substr(1); + file_type_info.extensions.resize(1); + file_type_info.extensions[0].push_back(ext); + } select_file_dialog_->SelectFile( - type, - base::string16(), - default_path, - NULL, - 0, - base::FilePath::StringType(), - platform_util::GetTopLevel(web_contents_->GetNativeView()), - NULL); + type, base::string16(), default_path, &file_type_info, 0, ext, + platform_util::GetTopLevel(web_contents_->GetNativeView()), nullptr); } // ui::SelectFileDialog::Listener implementation. @@ -217,8 +219,8 @@ DevToolsFileHelper::DevToolsFileHelper(WebContents* web_contents, : web_contents_(web_contents), profile_(profile), delegate_(delegate), - file_task_runner_( - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})) { + file_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})) { pref_change_registrar_.Init(profile_->GetPrefs()); } diff --git a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc index 96079b9f876..9e97b8e3d52 100644 --- a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc +++ b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc @@ -322,9 +322,8 @@ void DevToolsFileSystemIndexer::FileSystemIndexingJob::CollectFilesToIndex() { } if (file_path.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - BindOnce(total_work_callback_, file_path_times_.size())); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + BindOnce(total_work_callback_, file_path_times_.size())); indexing_it_ = file_path_times_.begin(); IndexFiles(); return; @@ -360,7 +359,7 @@ void DevToolsFileSystemIndexer::FileSystemIndexingJob::IndexFiles() { return; if (indexing_it_ == file_path_times_.end()) { g_trigram_index.Get().NormalizeVectors(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, done_callback_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, done_callback_); return; } FilePath file_path = indexing_it_->first; @@ -452,8 +451,8 @@ void DevToolsFileSystemIndexer::FileSystemIndexingJob::ReportWorked() { ++files_indexed_; if (should_send_worked_nitification) { last_worked_notification_time_ = current_time; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - BindOnce(worked_callback_, files_indexed_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + BindOnce(worked_callback_, files_indexed_)); files_indexed_ = 0; } } @@ -516,6 +515,6 @@ void DevToolsFileSystemIndexer::SearchInPathOnImplSequence( if (path.IsParent(*it)) result.push_back(it->AsUTF8Unsafe()); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - BindOnce(callback, std::move(result))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + BindOnce(callback, std::move(result))); } 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 c3be1b672be..f2403b4d5f3 100644 --- a/chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc +++ b/chromium/chrome/browser/devtools/devtools_file_system_indexer_unittest.cc @@ -11,7 +11,7 @@ #include "base/run_loop.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/common/chrome_paths.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" class DevToolsFileSystemIndexerTest : public testing::Test { @@ -36,7 +36,7 @@ class DevToolsFileSystemIndexerTest : public testing::Test { indexing_done_ = false; } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; scoped_refptr<DevToolsFileSystemIndexer> indexer_; std::set<std::string> search_results_; bool indexing_done_; diff --git a/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc b/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc index c43ee562be6..e49a2e533c8 100644 --- a/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc +++ b/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc @@ -8,7 +8,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "base/test/test_timeouts.h" #include "base/threading/sequenced_task_runner_handle.h" #include "chrome/browser/devtools/devtools_file_watcher.h" @@ -34,7 +34,7 @@ class DevToolsFileWatcherTest : public testing::Test { base::ScopedTempDir temp_dir_; base::FilePath base_path_; - base::test::ScopedTaskEnvironment task_environment_; + base::test::TaskEnvironment task_environment_; bool done_flag_ = false; std::set<std::string> expected_changed_paths_; diff --git a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc index 250a9ade9f3..ad76170f21e 100644 --- a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc +++ b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc @@ -39,10 +39,12 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/policy/chrome_browser_policy_connector.h" #include "chrome/browser/policy/developer_tools_policy_handler.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" +#include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" @@ -59,6 +61,9 @@ #include "components/autofill/core/browser/autofill_manager.h" #include "components/autofill/core/browser/autofill_manager_test_delegate.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/policy/core/common/mock_configuration_policy_provider.h" +#include "components/policy/core/common/policy_map.h" +#include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -621,7 +626,7 @@ class WorkerDevToolsSanityTest : public InProcessBrowserTest { if (host->GetType() == DevToolsAgentHost::kTypeSharedWorker && host->GetURL().path().rfind(path_) != std::string::npos) { *out_host_ = host; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, quit_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, quit_); delete this; } } @@ -757,8 +762,13 @@ IN_PROC_BROWSER_TEST_F(DevToolsBeforeUnloadTest, // Tests that BeforeUnload event gets called on devtools that are opened // on another devtools. -IN_PROC_BROWSER_TEST_F(DevToolsBeforeUnloadTest, - TestDevToolsOnDevTools) { +#if defined(OS_CHROMEOS) || defined(OS_LINUX) +// TODO(https://crbug.com/1000654): Re-enable this test. +#define MAYBE_TestDevToolsOnDevTools DISABLED_TestDevToolsOnDevTools +#else +#define MAYBE_TestDevToolsOnDevTools TestDevToolsOnDevTools +#endif +IN_PROC_BROWSER_TEST_F(DevToolsBeforeUnloadTest, MAYBE_TestDevToolsOnDevTools) { ASSERT_TRUE(spawned_test_server()->Start()); LoadTestPage(kDebuggerTestPage); @@ -786,22 +796,21 @@ IN_PROC_BROWSER_TEST_F(DevToolsBeforeUnloadTest, DevToolsWindowTesting::Get(windows[2])->main_web_contents()); // Try to close second devtools. { - content::WindowedNotificationObserver cancel_browser( - chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED, - content::NotificationService::AllSources()); chrome::CloseWindow(DevToolsWindowTesting::Get(windows[1])->browser()); CancelModalDialog(); - cancel_browser.Wait(); + base::RunLoop().RunUntilIdle(); + // The second devtools hasn't closed. + EXPECT_EQ(windows[1], + DevToolsWindow::GetInstanceForInspectedWebContents( + DevToolsWindowTesting::Get(windows[0])->main_web_contents())); } // Try to close browser window. { - content::WindowedNotificationObserver cancel_browser( - chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED, - content::NotificationService::AllSources()); chrome::CloseWindow(browser()); AcceptModalDialog(); CancelModalDialog(); - cancel_browser.Wait(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(browser(), BrowserList::GetInstance()->get(0)); } // Try to exit application. { @@ -1354,8 +1363,10 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DevtoolsInDevTools) { // Some web features, when used from an extension, are subject to browser-side // security policy enforcement. Make sure they work properly from inside a // devtools extension. +// ToDo(993982): The test is flaky (timeout, crash, and fail) on several builds: +// Debug, Windows, Mac, MSan, and ASan. IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest, - DevToolsExtensionSecurityPolicyGrants) { + DISABLED_DevToolsExtensionSecurityPolicyGrants) { ASSERT_TRUE(embedded_test_server()->Start()); auto dir = std::make_unique<extensions::TestExtensionDir>(); @@ -1593,7 +1604,13 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestConsoleOnNavigateBack) { RunTest("testConsoleOnNavigateBack", kNavigateBackTestPage); } -IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDeviceEmulation) { +#if defined(OS_LINUX) +// Flaking on linux runs, see crbug.com/990692. +#define MAYBE_TestDeviceEmulation DISABLED_TestDeviceEmulation +#else +#define MAYBE_TestDeviceEmulation TestDeviceEmulation +#endif +IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestDeviceEmulation) { RunTest("testDeviceMetricsOverrides", "about:blank"); } @@ -1917,7 +1934,8 @@ class RemoteDebuggingTest : public extensions::ExtensionApiTest { #if defined(OS_CHROMEOS) #define MAYBE_RemoteDebugger DISABLED_RemoteDebugger #else -#define MAYBE_RemoteDebugger RemoteDebugger +// TODO(crbug.com/997911): Flaky on all platforms. +#define MAYBE_RemoteDebugger DISABLED_RemoteDebugger #endif IN_PROC_BROWSER_TEST_F(RemoteDebuggingTest, MAYBE_RemoteDebugger) { ASSERT_TRUE(RunExtensionTest("target_list")) << message_; @@ -2118,10 +2136,9 @@ class StaticURLDataSource : public content::URLDataSource { // content::URLDataSource: std::string GetSource() override { return source_; } - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const GotDataCallback& callback) override { + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const GotDataCallback& callback) override { std::string data(content_); callback.Run(base::RefCountedString::TakeString(&data)); } @@ -2347,6 +2364,43 @@ IN_PROC_BROWSER_TEST_F(InProcessBrowserTest, BrowserCloseWithBeforeUnload) { ui_test_utils::WaitForBrowserToClose(browser()); } +class DevToolsPolicyTest : public InProcessBrowserTest { + protected: + DevToolsPolicyTest() { + EXPECT_CALL(provider_, IsInitializationComplete(testing::_)) + .WillRepeatedly(testing::Return(true)); + } + + void SetUpInProcessBrowserTestFixture() override { + policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); + } + policy::MockConfigurationPolicyProvider provider_; +}; + +IN_PROC_BROWSER_TEST_F(DevToolsPolicyTest, OpenBlackListedDevTools) { + base::ListValue blacklist; + blacklist.AppendString("chrome-devtools://*"); + policy::PolicyMap policies; + policies.Set(policy::key::kURLBlacklist, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, + blacklist.CreateDeepCopy(), nullptr); + provider_.UpdateChromePolicy(policies); + + WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); + scoped_refptr<content::DevToolsAgentHost> agent( + content::DevToolsAgentHost::GetOrCreateFor(wc)); + DevToolsWindow::OpenDevToolsWindow(wc); + DevToolsWindow* window = DevToolsWindow::FindDevToolsWindow(agent.get()); + if (window) { + base::RunLoop run_loop; + DevToolsWindowTesting::Get(window)->SetCloseCallback( + run_loop.QuitClosure()); + run_loop.Run(); + } + window = DevToolsWindow::FindDevToolsWindow(agent.get()); + ASSERT_EQ(nullptr, window); +} + // Flaky on Mus. See https://crbug.com/819285. IN_PROC_BROWSER_TEST_F(SitePerProcessDevToolsSanityTest, DISABLED_InputDispatchEventsToOOPIF) { @@ -2368,7 +2422,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDevToolsSanityTest, content::WaitForLoadStop(tab); for (auto* frame : GetInspectedTab()->GetAllFrames()) { - content::WaitForHitTestDataOrChildSurfaceReady(frame); + content::WaitForHitTestData(frame); } DevToolsWindow* window = DevToolsWindowTesting::OpenDevToolsWindowSync(GetInspectedTab(), false); diff --git a/chromium/chrome/browser/devtools/devtools_window.cc b/chromium/chrome/browser/devtools/devtools_window.cc index 3dbd95ca379..14bc702c89f 100644 --- a/chromium/chrome/browser/devtools/devtools_window.cc +++ b/chromium/chrome/browser/devtools/devtools_window.cc @@ -424,6 +424,13 @@ DevToolsWindow::~DevToolsWindow() { close_callback_.Run(); close_callback_ = base::Closure(); } + // Defer deletion of the main web contents, since we could get here + // via RenderFrameHostImpl method that expects WebContents to live + // for some time. See http://crbug.com/997299 for details. + if (owned_main_web_contents_) { + base::SequencedTaskRunnerHandle::Get()->DeleteSoon( + FROM_HERE, std::move(owned_main_web_contents_)); + } } // static @@ -600,7 +607,7 @@ void DevToolsWindow::ToggleDevToolsWindow( Browser* browser, const DevToolsToggleAction& action) { if (action.type() == DevToolsToggleAction::kToggle && - browser->is_devtools()) { + browser->is_type_devtools()) { browser->tab_strip_model()->CloseAllTabs(); return; } @@ -888,7 +895,7 @@ bool DevToolsWindow::NeedsToInterceptBeforeUnload( // static bool DevToolsWindow::HasFiredBeforeUnloadEventForDevToolsBrowser( Browser* browser) { - DCHECK(browser->is_devtools()); + DCHECK(browser->is_type_devtools()); // When FastUnloadController is used, devtools frontend will be detached // from the browser window at this point which means we've already fired // beforeunload. @@ -1006,9 +1013,9 @@ DevToolsWindow* DevToolsWindow::Create( // Check for a place to dock. Browser* browser = nullptr; int tab; - if (!FindInspectedBrowserAndTabIndex(inspected_web_contents, - &browser, &tab) || - browser->is_type_popup()) { + if (!FindInspectedBrowserAndTabIndex(inspected_web_contents, &browser, + &tab) || + !browser->is_type_normal()) { can_dock = false; } } diff --git a/chromium/chrome/browser/devtools/inspector_protocol_config.json b/chromium/chrome/browser/devtools/inspector_protocol_config.json index ae2a2d80704..53897298398 100644 --- a/chromium/chrome/browser/devtools/inspector_protocol_config.json +++ b/chromium/chrome/browser/devtools/inspector_protocol_config.json @@ -14,7 +14,7 @@ }, { "domain": "Browser", - "include": [ "getWindowForTarget", "getWindowBounds", "setWindowBounds", "close", "grantPermissions", "resetPermissions", "setDockTile" ], + "include": [ "getWindowForTarget", "getWindowBounds", "setWindowBounds", "close", "setDockTile" ], "include_events": [] }, { diff --git a/chromium/chrome/browser/devtools/protocol/browser_handler.cc b/chromium/chrome/browser/devtools/protocol/browser_handler.cc index 2bc97efa18c..371df65890b 100644 --- a/chromium/chrome/browser/devtools/protocol/browser_handler.cc +++ b/chromium/chrome/browser/devtools/protocol/browser_handler.cc @@ -13,8 +13,6 @@ #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h" #include "chrome/browser/devtools/devtools_dock_tile.h" #include "chrome/browser/lifetime/application_lifetime.h" -#include "chrome/browser/permissions/permission_manager.h" -#include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" @@ -25,7 +23,6 @@ #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_png_rep.h" -using PermissionOverrides = std::set<content::PermissionType>; using protocol::Maybe; using protocol::Response; @@ -63,53 +60,6 @@ std::unique_ptr<protocol::Browser::Bounds> GetBrowserWindowBounds( .Build(); } -Response FromProtocolPermissionType( - const protocol::Browser::PermissionType& type, - content::PermissionType* out_type) { - if (type == protocol::Browser::PermissionTypeEnum::Notifications) { - *out_type = content::PermissionType::NOTIFICATIONS; - } else if (type == protocol::Browser::PermissionTypeEnum::Geolocation) { - *out_type = content::PermissionType::GEOLOCATION; - } else if (type == - protocol::Browser::PermissionTypeEnum::ProtectedMediaIdentifier) { - *out_type = content::PermissionType::PROTECTED_MEDIA_IDENTIFIER; - } else if (type == protocol::Browser::PermissionTypeEnum::Midi) { - *out_type = content::PermissionType::MIDI; - } else if (type == protocol::Browser::PermissionTypeEnum::MidiSysex) { - *out_type = content::PermissionType::MIDI_SYSEX; - } else if (type == protocol::Browser::PermissionTypeEnum::DurableStorage) { - *out_type = content::PermissionType::DURABLE_STORAGE; - } else if (type == protocol::Browser::PermissionTypeEnum::AudioCapture) { - *out_type = content::PermissionType::AUDIO_CAPTURE; - } else if (type == protocol::Browser::PermissionTypeEnum::VideoCapture) { - *out_type = content::PermissionType::VIDEO_CAPTURE; - } else if (type == protocol::Browser::PermissionTypeEnum::BackgroundSync) { - *out_type = content::PermissionType::BACKGROUND_SYNC; - } else if (type == protocol::Browser::PermissionTypeEnum::Flash) { - *out_type = content::PermissionType::FLASH; - } else if (type == protocol::Browser::PermissionTypeEnum::Sensors) { - *out_type = content::PermissionType::SENSORS; - } else if (type == - protocol::Browser::PermissionTypeEnum::AccessibilityEvents) { - *out_type = content::PermissionType::ACCESSIBILITY_EVENTS; - } else if (type == protocol::Browser::PermissionTypeEnum::ClipboardRead) { - *out_type = content::PermissionType::CLIPBOARD_READ; - } else if (type == protocol::Browser::PermissionTypeEnum::ClipboardWrite) { - *out_type = content::PermissionType::CLIPBOARD_WRITE; - } else if (type == protocol::Browser::PermissionTypeEnum::PaymentHandler) { - *out_type = content::PermissionType::PAYMENT_HANDLER; - } else if (type == protocol::Browser::PermissionTypeEnum::BackgroundFetch) { - *out_type = content::PermissionType::BACKGROUND_FETCH; - } else if (type == protocol::Browser::PermissionTypeEnum::WakeLockScreen) { - *out_type = content::PermissionType::WAKE_LOCK_SCREEN; - } else if (type == protocol::Browser::PermissionTypeEnum::WakeLockSystem) { - *out_type = content::PermissionType::WAKE_LOCK_SYSTEM; - } else { - return Response::InvalidParams("Unknown permission type: " + type); - } - return Response::OK(); -} - } // namespace BrowserHandler::BrowserHandler(protocol::UberDispatcher* dispatcher, @@ -161,9 +111,8 @@ Response BrowserHandler::GetWindowBounds( } Response BrowserHandler::Close() { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce([]() { chrome::ExitIgnoreUnloadHandlers(); })); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce([]() { chrome::ExitIgnoreUnloadHandlers(); })); return Response::OK(); } @@ -229,62 +178,6 @@ Response BrowserHandler::SetWindowBounds( return Response::OK(); } -Response BrowserHandler::Disable() { - for (auto& browser_context_id : contexts_with_overridden_permissions_) { - Profile* profile = nullptr; - Maybe<std::string> context_id = - browser_context_id.empty() ? Maybe<std::string>() - : Maybe<std::string>(browser_context_id); - FindProfile(context_id, &profile); - if (profile) { - PermissionManager* permission_manager = PermissionManager::Get(profile); - permission_manager->ResetPermissionOverridesForDevTools(); - } - } - contexts_with_overridden_permissions_.clear(); - return Response::OK(); -} - -Response BrowserHandler::GrantPermissions( - const std::string& origin, - std::unique_ptr<protocol::Array<protocol::Browser::PermissionType>> - permissions, - Maybe<std::string> browser_context_id) { - Profile* profile = nullptr; - Response response = FindProfile(browser_context_id, &profile); - if (!response.isSuccess()) - return response; - - PermissionOverrides overrides; - for (const std::string& permission : *permissions) { - content::PermissionType type; - Response type_response = FromProtocolPermissionType(permission, &type); - if (!type_response.isSuccess()) - return type_response; - overrides.insert(type); - } - - PermissionManager* permission_manager = PermissionManager::Get(profile); - GURL url = GURL(origin).GetOrigin(); - permission_manager->SetPermissionOverridesForDevTools(url, - std::move(overrides)); - contexts_with_overridden_permissions_.insert( - browser_context_id.fromMaybe("")); - return Response::FallThrough(); -} - -Response BrowserHandler::ResetPermissions( - Maybe<std::string> browser_context_id) { - Profile* profile = nullptr; - Response response = FindProfile(browser_context_id, &profile); - if (!response.isSuccess()) - return response; - PermissionManager* permission_manager = PermissionManager::Get(profile); - permission_manager->ResetPermissionOverridesForDevTools(); - contexts_with_overridden_permissions_.erase(browser_context_id.fromMaybe("")); - return Response::FallThrough(); -} - protocol::Response BrowserHandler::SetDockTile( protocol::Maybe<std::string> label, protocol::Maybe<protocol::Binary> image) { @@ -295,26 +188,3 @@ protocol::Response BrowserHandler::SetDockTile( !reps.empty() ? gfx::Image(reps) : gfx::Image()); return Response::OK(); } - -Response BrowserHandler::FindProfile( - const Maybe<std::string>& browser_context_id, - Profile** profile) { - auto* delegate = ChromeDevToolsManagerDelegate::GetInstance(); - if (!browser_context_id.isJust()) { - *profile = - Profile::FromBrowserContext(delegate->GetDefaultBrowserContext()); - if (*profile == nullptr) - return Response::Error("Browser context management is not supported."); - return Response::OK(); - } - - std::string context_id = browser_context_id.fromJust(); - for (auto* context : delegate->GetBrowserContexts()) { - if (context->UniqueId() == context_id) { - *profile = Profile::FromBrowserContext(context); - return Response::OK(); - } - } - return Response::InvalidParams("Failed to find browser context for id " + - context_id); -} diff --git a/chromium/chrome/browser/devtools/protocol/browser_handler.h b/chromium/chrome/browser/devtools/protocol/browser_handler.h index 17869033b42..80a30553c06 100644 --- a/chromium/chrome/browser/devtools/protocol/browser_handler.h +++ b/chromium/chrome/browser/devtools/protocol/browser_handler.h @@ -8,8 +8,6 @@ #include "base/containers/flat_set.h" #include "chrome/browser/devtools/protocol/browser.h" -class Profile; - class BrowserHandler : public protocol::Browser::Backend { public: BrowserHandler(protocol::UberDispatcher* dispatcher, @@ -28,23 +26,11 @@ class BrowserHandler : public protocol::Browser::Backend { protocol::Response SetWindowBounds( int window_id, std::unique_ptr<protocol::Browser::Bounds> out_bounds) override; - protocol::Response Disable() override; - protocol::Response GrantPermissions( - const std::string& origin, - std::unique_ptr<protocol::Array<protocol::Browser::PermissionType>> - permissions, - protocol::Maybe<std::string> browser_context_id) override; - protocol::Response ResetPermissions( - protocol::Maybe<std::string> browser_context_id) override; protocol::Response SetDockTile( protocol::Maybe<std::string> label, protocol::Maybe<protocol::Binary> image) override; private: - protocol::Response FindProfile( - const protocol::Maybe<std::string>& browser_context_id, - Profile** profile); - base::flat_set<std::string> contexts_with_overridden_permissions_; std::string target_id_; diff --git a/chromium/chrome/browser/devtools/protocol/cast_handler.cc b/chromium/chrome/browser/devtools/protocol/cast_handler.cc index a437d4b68ef..bccebb6efd1 100644 --- a/chromium/chrome/browser/devtools/protocol/cast_handler.cc +++ b/chromium/chrome/browser/devtools/protocol/cast_handler.cc @@ -13,7 +13,7 @@ #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/media_router/media_router_ui_helper.h" #include "chrome/common/media_router/media_source.h" -#include "chrome/common/media_router/mojo/media_router.mojom.h" +#include "chrome/common/media_router/mojom/media_router.mojom.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn index e26b2ba3fb5..000374bc06a 100644 --- a/chromium/chrome/browser/extensions/BUILD.gn +++ b/chromium/chrome/browser/extensions/BUILD.gn @@ -422,10 +422,6 @@ jumbo_static_library("extensions") { "blacklist_factory.h", "blacklist_state_fetcher.cc", "blacklist_state_fetcher.h", - "bookmark_app_extension_util.cc", - "bookmark_app_extension_util.h", - "bookmark_app_helper.cc", - "bookmark_app_helper.h", "browser_context_keyed_service_factories.cc", "browser_context_keyed_service_factories.h", "browser_extension_window_controller.cc", @@ -447,8 +443,6 @@ jumbo_static_library("extensions") { "chrome_content_browser_client_extensions_part.h", "chrome_content_verifier_delegate.cc", "chrome_content_verifier_delegate.h", - "chrome_extension_api_frame_id_map_helper.cc", - "chrome_extension_api_frame_id_map_helper.h", "chrome_extension_browser_constants.cc", "chrome_extension_browser_constants.h", "chrome_extension_chooser_dialog.h", @@ -764,6 +758,7 @@ jumbo_static_library("extensions") { "//chrome/common", "//chrome/common/extensions/api", "//components/safe_browsing:csd_proto", + "//components/safe_browsing:webprotect_proto", "//components/safe_browsing/db:util", "//components/signin/core/browser", "//content/public/browser", @@ -830,11 +825,14 @@ jumbo_static_library("extensions") { "//components/proxy_config", "//components/rappor", "//components/resources", + "//components/safe_browsing:buildflags", "//components/safe_browsing:csd_proto", "//components/safe_browsing:features", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:database_manager", "//components/search_engines", + "//components/services/patch/content", + "//components/services/unzip/content", "//components/services/unzip/public/cpp", "//components/sessions", "//components/signin/public/identity_manager", @@ -997,7 +995,7 @@ jumbo_static_library("extensions") { "//components/drive", "//components/user_manager", "//media/capture:capture_lib", - "//media/capture/video/chromeos/mojo:cros_camera", + "//media/capture/video/chromeos/mojom:cros_camera", "//remoting/base", "//remoting/host", "//remoting/host/it2me:chrome_os_host", @@ -1100,7 +1098,6 @@ jumbo_static_library("extensions") { if (is_win) { deps += [ - "//chrome/services/wifi_util_win/public/mojom", "//third_party/iaccessible2", "//third_party/isimpledom", ] diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h index d900d64d169..afee1976650 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h @@ -82,8 +82,7 @@ class ActivityLogPrivateGetExtensionActivitiesFunction }; // The implementation of activityLogPrivate.deleteActivities -class ActivityLogPrivateDeleteActivitiesFunction - : public UIThreadExtensionFunction { +class ActivityLogPrivateDeleteActivitiesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteActivities", ACTIVITYLOGPRIVATE_DELETEACTIVITIES) @@ -97,7 +96,7 @@ class ActivityLogPrivateDeleteActivitiesFunction // The implementation of activityLogPrivate.deleteActivitiesByExtension class ActivityLogPrivateDeleteActivitiesByExtensionFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteActivitiesByExtension", ACTIVITYLOGPRIVATE_DELETEACTIVITIESBYEXTENSION) @@ -110,8 +109,7 @@ class ActivityLogPrivateDeleteActivitiesByExtensionFunction }; // The implementation of activityLogPrivate.deleteDatabase -class ActivityLogPrivateDeleteDatabaseFunction - : public UIThreadExtensionFunction { +class ActivityLogPrivateDeleteDatabaseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteDatabase", ACTIVITYLOGPRIVATE_DELETEDATABASE) @@ -124,7 +122,7 @@ class ActivityLogPrivateDeleteDatabaseFunction }; // The implementation of activityLogPrivate.deleteUrls -class ActivityLogPrivateDeleteUrlsFunction : public UIThreadExtensionFunction { +class ActivityLogPrivateDeleteUrlsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteUrls", ACTIVITYLOGPRIVATE_DELETEURLS) diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc index 7636ce0380c..69f3e85c660 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc @@ -57,8 +57,8 @@ class ActivityLogApiTest : public ExtensionApiTest { base::CommandLine saved_cmdline_; }; -#if defined(OS_WIN) -// TODO(pmarch): fix flakiness on win debug - http://crbug.com/299393 +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) +// TODO(crbug.com/299393): Flaky on Mac, Windows and Linux. #define MAYBE_TriggerEvent DISABLED_TriggerEvent #else #define MAYBE_TriggerEvent TriggerEvent diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h index 20a4924315b..5b42cd41d7a 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h @@ -13,7 +13,7 @@ namespace extensions { -class AutofillPrivateSaveAddressFunction : public UIThreadExtensionFunction { +class AutofillPrivateSaveAddressFunction : public ExtensionFunction { public: AutofillPrivateSaveAddressFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.saveAddress", @@ -31,7 +31,7 @@ class AutofillPrivateSaveAddressFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateSaveAddressFunction); }; -class AutofillPrivateGetCountryListFunction : public UIThreadExtensionFunction { +class AutofillPrivateGetCountryListFunction : public ExtensionFunction { public: AutofillPrivateGetCountryListFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.getCountryList", @@ -49,8 +49,7 @@ class AutofillPrivateGetCountryListFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetCountryListFunction); }; -class AutofillPrivateGetAddressComponentsFunction : - public UIThreadExtensionFunction { +class AutofillPrivateGetAddressComponentsFunction : public ExtensionFunction { public: AutofillPrivateGetAddressComponentsFunction() {} DECLARE_EXTENSION_FUNCTION("autofillPrivate.getAddressComponents", @@ -66,7 +65,7 @@ class AutofillPrivateGetAddressComponentsFunction : DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetAddressComponentsFunction); }; -class AutofillPrivateGetAddressListFunction : public UIThreadExtensionFunction { +class AutofillPrivateGetAddressListFunction : public ExtensionFunction { public: AutofillPrivateGetAddressListFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.getAddressList", @@ -84,7 +83,7 @@ class AutofillPrivateGetAddressListFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetAddressListFunction); }; -class AutofillPrivateSaveCreditCardFunction : public UIThreadExtensionFunction { +class AutofillPrivateSaveCreditCardFunction : public ExtensionFunction { public: AutofillPrivateSaveCreditCardFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.saveCreditCard", @@ -102,7 +101,7 @@ class AutofillPrivateSaveCreditCardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateSaveCreditCardFunction); }; -class AutofillPrivateRemoveEntryFunction : public UIThreadExtensionFunction { +class AutofillPrivateRemoveEntryFunction : public ExtensionFunction { public: AutofillPrivateRemoveEntryFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.removeEntry", @@ -120,8 +119,7 @@ class AutofillPrivateRemoveEntryFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateRemoveEntryFunction); }; -class AutofillPrivateValidatePhoneNumbersFunction : - public UIThreadExtensionFunction { +class AutofillPrivateValidatePhoneNumbersFunction : public ExtensionFunction { public: AutofillPrivateValidatePhoneNumbersFunction() {} DECLARE_EXTENSION_FUNCTION("autofillPrivate.validatePhoneNumbers", @@ -137,7 +135,7 @@ class AutofillPrivateValidatePhoneNumbersFunction : DISALLOW_COPY_AND_ASSIGN(AutofillPrivateValidatePhoneNumbersFunction); }; -class AutofillPrivateMaskCreditCardFunction : public UIThreadExtensionFunction { +class AutofillPrivateMaskCreditCardFunction : public ExtensionFunction { public: AutofillPrivateMaskCreditCardFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.maskCreditCard", @@ -155,8 +153,7 @@ class AutofillPrivateMaskCreditCardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateMaskCreditCardFunction); }; -class AutofillPrivateGetCreditCardListFunction - : public UIThreadExtensionFunction { +class AutofillPrivateGetCreditCardListFunction : public ExtensionFunction { public: AutofillPrivateGetCreditCardListFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.getCreditCardList", @@ -174,8 +171,7 @@ class AutofillPrivateGetCreditCardListFunction DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetCreditCardListFunction); }; -class AutofillPrivateMigrateCreditCardsFunction - : public UIThreadExtensionFunction { +class AutofillPrivateMigrateCreditCardsFunction : public ExtensionFunction { public: AutofillPrivateMigrateCreditCardsFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.migrateCreditCards", @@ -194,7 +190,7 @@ class AutofillPrivateMigrateCreditCardsFunction }; class AutofillPrivateLogServerCardLinkClickedFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: AutofillPrivateLogServerCardLinkClickedFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.logServerCardLinkClicked", diff --git a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc index b33da9fe462..f2333134976 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc @@ -56,11 +56,8 @@ bool ChromeAutomationInternalApiDelegate::GetTabById( content::WebContents** contents, std::string* error_msg) { *error_msg = tabs_constants::kTabNotFoundError; - return ExtensionTabUtil::GetTabById( - tab_id, browser_context, include_incognito, - nullptr, /* browser out param */ - nullptr, /* tab strip out param */ - contents, nullptr /* tab_index out param */); + return ExtensionTabUtil::GetTabById(tab_id, browser_context, + include_incognito, contents); } int ChromeAutomationInternalApiDelegate::GetTabId( @@ -69,7 +66,7 @@ int ChromeAutomationInternalApiDelegate::GetTabId( } content::WebContents* ChromeAutomationInternalApiDelegate::GetActiveWebContents( - UIThreadExtensionFunction* function) { + ExtensionFunction* function) { return ChromeExtensionFunctionDetails(function) .GetCurrentBrowser() ->tab_strip_model() diff --git a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h index 474b575dc6e..f2bdc737969 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h +++ b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h @@ -26,7 +26,7 @@ class ChromeAutomationInternalApiDelegate std::string* error_msg) override; int GetTabId(content::WebContents* contents) override; content::WebContents* GetActiveWebContents( - UIThreadExtensionFunction* function) override; + ExtensionFunction* function) override; void EnableDesktop() override; ui::AXTreeID GetAXTreeID() override; void SetEventBundleSink(ui::AXEventBundleSink* sink) override; 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 95240d00bc2..2da1d159732 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 @@ -321,6 +321,7 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ServiceEvents) { ExtensionTestMessageListener listener(true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth_low_energy/service_events"))); + EXPECT_TRUE(listener.WaitUntilSatisfied()); // These will create the identifier mappings. event_router()->GattServiceAdded( @@ -341,7 +342,6 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ServiceEvents) { event_router()->GattServiceRemoved( mock_adapter_, device0_.get(), service0_.get()); - EXPECT_TRUE(listener.WaitUntilSatisfied()); ASSERT_EQ("ready", listener.message()) << listener.message(); listener.Reply("go"); @@ -366,12 +366,13 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedService) { .Times(1) .WillOnce(Return(service0_.get())); + ExtensionTestMessageListener get_service_success_listener(false); + event_router()->GattServiceAdded( mock_adapter_, device0_.get(), service0_.get()); event_router()->GattDiscoveryCompleteForService(mock_adapter_, service0_.get()); - ExtensionTestMessageListener get_service_success_listener(false); EXPECT_TRUE(get_service_success_listener.WaitUntilSatisfied()); ASSERT_EQ("getServiceSuccess", get_service_success_listener.message()) << get_service_success_listener.message(); @@ -382,10 +383,11 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedService) { EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(0); EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)).Times(0); + ExtensionTestMessageListener get_service_fail_listener(true); + event_router()->GattServiceRemoved( mock_adapter_, device0_.get(), service0_.get()); - ExtensionTestMessageListener get_service_fail_listener(true); EXPECT_TRUE(get_service_fail_listener.WaitUntilSatisfied()); ASSERT_EQ("getServiceFail", get_service_fail_listener.message()) << get_service_fail_listener.message(); @@ -931,6 +933,7 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, DescriptorValueChanged) { ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( "bluetooth_low_energy/descriptor_value_changed"))); + EXPECT_TRUE(listener.WaitUntilSatisfied()); // Cause events to be sent to the extension. std::vector<uint8_t> value; @@ -939,7 +942,6 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, DescriptorValueChanged) { event_router()->GattDescriptorValueChanged( mock_adapter_, desc1_.get(), value); - EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/OWNERS b/chromium/chrome/browser/extensions/api/bookmark_manager_private/OWNERS new file mode 100644 index 00000000000..745d78d4c26 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/OWNERS @@ -0,0 +1,2 @@ +calamity@chromium.org +johntlee@chromium.org diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc index 81209a9ac4b..5f90d3df246 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc @@ -19,7 +19,7 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/managed/managed_bookmark_service.h" #include "components/bookmarks/test/bookmark_test_helpers.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" using bookmarks::BookmarkModel; @@ -65,7 +65,7 @@ class ExtensionBookmarksTest : public testing::Test { folder_, 0, base::ASCIIToUTF16("CNet"), GURL("http://cnet.com")); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; bookmarks::ManagedBookmarkService* managed_; BookmarkModel* model_; diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index 3ee926982f7..12113c4f5d4 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc @@ -794,9 +794,9 @@ bool BookmarksExportFunction::RunOnReady() { // extensions use user gesture for export, so use USER_VISIBLE priority. // GetDefaultFilepathForBookmarkExport() might have to touch filesystem // (stat or access, for example), so this requires IO. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&GetDefaultFilepathForBookmarkExport), base::BindOnce(&BookmarksIOFunction::ShowSelectFileDialog, this, 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 d222c335e76..09b44ef1f9a 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 @@ -134,10 +134,9 @@ void BrailleControllerImpl::WriteDots(const std::vector<uint8_t>& cells, void BrailleControllerImpl::AddObserver(BrailleObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BrailleControllerImpl::StartConnecting, - base::Unretained(this)))) { + if (!base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BrailleControllerImpl::StartConnecting, + base::Unretained(this)))) { NOTREACHED(); } observers_.AddObserver(observer); @@ -174,8 +173,9 @@ void BrailleControllerImpl::StartConnecting() { } if (!sequenced_task_runner_) { - sequenced_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + sequenced_task_runner_ = + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); } // Only try to connect after we've started to watch the @@ -213,7 +213,7 @@ void BrailleControllerImpl::OnSocketDirChangedOnTaskThread( LOG(ERROR) << "Error watching brlapi directory: " << path.value(); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&BrailleControllerImpl::OnSocketDirChangedOnIOThread, base::Unretained(this))); @@ -272,11 +272,10 @@ void BrailleControllerImpl::ScheduleTryToConnect() { } VLOG(1) << "Scheduling connection retry to brlapi"; connect_scheduled_ = true; - base::PostDelayedTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BrailleControllerImpl::TryToConnect, - base::Unretained(this)), - kConnectionDelay); + base::PostDelayedTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BrailleControllerImpl::TryToConnect, + base::Unretained(this)), + kConnectionDelay); } void BrailleControllerImpl::Disconnect() { @@ -318,7 +317,7 @@ void BrailleControllerImpl::DispatchKeys() { void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrailleControllerImpl::DispatchKeyEvent, base::Unretained(this), base::Passed(&event))); @@ -332,7 +331,7 @@ void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) { void BrailleControllerImpl::DispatchOnDisplayStateChanged( std::unique_ptr<DisplayState> new_state) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - if (!base::PostTaskWithTraits( + if (!base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &BrailleControllerImpl::DispatchOnDisplayStateChanged, diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h index d6a88e094d4..2684e50134e 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h +++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h @@ -107,7 +107,7 @@ class BrailleDisplayPrivateWriteDotsFunction : public AsyncApiFunction { }; class BrailleDisplayPrivateUpdateBluetoothBrailleDisplayAddressFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~BrailleDisplayPrivateUpdateBluetoothBrailleDisplayAddressFunction() override {} ResponseAction Run() override; diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc index e9efd7d7ba0..037d634141f 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc @@ -68,10 +68,9 @@ class MockBrlapiConnection : public BrlapiConnection { data_->connected = true; on_data_ready_ = on_data_ready; if (!data_->pending_keys.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&MockBrlapiConnection::NotifyDataReady, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&MockBrlapiConnection::NotifyDataReady, + base::Unretained(this))); } return CONNECT_SUCCESS; } @@ -80,7 +79,7 @@ class MockBrlapiConnection : public BrlapiConnection { data_->connected = false; if (data_->reappear_on_disconnect) { data_->display_columns *= 2; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &BrailleControllerImpl::PokeSocketDirForTesting, @@ -129,10 +128,9 @@ class MockBrlapiConnection : public BrlapiConnection { void NotifyDataReady() { on_data_ready_.Run(); if (!data_->pending_keys.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&MockBrlapiConnection::NotifyDataReady, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&MockBrlapiConnection::NotifyDataReady, + base::Unretained(this))); } } 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 cd22764d64c..e73cd3f3032 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 @@ -351,13 +351,13 @@ bool BrowsingDataRemoverFunction::RunAsync() { ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA) { // If we're being asked to remove plugin data, check whether it's actually // supported. - PostTaskWithTraits( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, - base::TaskPriority::USER_VISIBLE}, - base::BindOnce( - &BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported, - this, PluginPrefs::GetForProfile(GetProfile()))); + PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::TaskPriority::USER_VISIBLE}, + base::BindOnce( + &BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported, + this, PluginPrefs::GetForProfile(GetProfile()))); } else { StartRemoving(); } @@ -377,7 +377,7 @@ void BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported( if (!PluginDataRemoverHelper::IsSupported(plugin_prefs.get())) removal_mask_ &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrowsingDataRemoverFunction::StartRemoving, this)); } 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 d5a9a0c05a9..2a588cf744e 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 @@ -61,7 +61,7 @@ extern const char kInvalidOriginError[]; } // namespace extension_browsing_data_api_constants -class BrowsingDataSettingsFunction : public UIThreadExtensionFunction { +class BrowsingDataSettingsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("browsingData.settings", BROWSINGDATA_SETTINGS) diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc index e72b5ae5c9b..b2e4c22d486 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc @@ -64,8 +64,7 @@ bool SetGaiaCookieForProfile(Profile* profile) { callback = base::BindLambdaForTesting( [&success, &loop_quit](net::CanonicalCookie::CookieInclusionStatus s) { - success = - (s == net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + success = s.IsInclude(); std::move(loop_quit).Run(); }); network::mojom::CookieManager* cookie_manager = @@ -76,8 +75,9 @@ bool SetGaiaCookieForProfile(Profile* profile) { cookie_manager->SetCanonicalCookie( cookie, google_url.scheme(), options, mojo::WrapCallbackWithDefaultInvokeIfNotRun( - std::move(callback), - net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_UNKNOWN_ERROR)); + std::move(callback), net::CanonicalCookie::CookieInclusionStatus( + net::CanonicalCookie::CookieInclusionStatus:: + EXCLUDE_UNKNOWN_ERROR))); loop.Run(); return success; } diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc index 19e460c0dbc..c10602fe117 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc @@ -55,7 +55,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase { browser_window_ = std::make_unique<TestBrowserWindow>(); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_ = std::make_unique<Browser>(params); 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 a94ea2115e3..3aef65b5906 100644 --- a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc +++ b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc @@ -434,18 +434,14 @@ IN_PROC_BROWSER_TEST_P(CastStreamingApiTestWithPixelOutput, // removed after launch. Note: CastStreamingApiTestWithPixelOutput.EndToEnd is // the only integration test exercising audio service loopback streams, so it's // a very important test to have. -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -// Platforms launched on. +#if defined(OS_WIN) || defined(OS_MACOSX) || \ + (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +// Platforms where the out of process audio service is supported. INSTANTIATE_TEST_SUITE_P(, CastStreamingApiTestWithPixelOutput, ::testing::Values(true)); -#elif defined(OS_MACOSX) || defined(OS_WIN) -// Supported platforms but not launched on. -INSTANTIATE_TEST_SUITE_P(, - CastStreamingApiTestWithPixelOutput, - ::testing::Bool()); #else -// Platforms where the out of process audio service isn't supported +// Platforms where the out of process audio service is not supported. INSTANTIATE_TEST_SUITE_P(, CastStreamingApiTestWithPixelOutput, ::testing::Values(false)); diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc index 42b5813d2a5..533bdee1e87 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc @@ -15,8 +15,10 @@ #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" #include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h" +#include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h" #include "chrome/common/extensions/api/certificate_provider.h" #include "chrome/common/extensions/api/certificate_provider_internal.h" +#include "chromeos/constants/security_token_pin_types.h" #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_private_key.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" @@ -24,28 +26,28 @@ namespace api_cp = extensions::api::certificate_provider; namespace api_cpi = extensions::api::certificate_provider_internal; +using PinCodeType = chromeos::SecurityTokenPinCodeType; +using PinErrorLabel = chromeos::SecurityTokenPinErrorLabel; namespace { -chromeos::RequestPinView::RequestPinErrorType GetErrorTypeForView( - api_cp::PinRequestErrorType error_type) { +PinErrorLabel GetErrorLabelForDialog(api_cp::PinRequestErrorType error_type) { switch (error_type) { case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PIN: - return chromeos::RequestPinView::RequestPinErrorType::INVALID_PIN; + return PinErrorLabel::kInvalidPin; case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PUK: - return chromeos::RequestPinView::RequestPinErrorType::INVALID_PUK; + return PinErrorLabel::kInvalidPuk; case api_cp::PinRequestErrorType:: PIN_REQUEST_ERROR_TYPE_MAX_ATTEMPTS_EXCEEDED: - return chromeos::RequestPinView::RequestPinErrorType:: - MAX_ATTEMPTS_EXCEEDED; + return PinErrorLabel::kMaxAttemptsExceeded; case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_UNKNOWN_ERROR: - return chromeos::RequestPinView::RequestPinErrorType::UNKNOWN_ERROR; + return PinErrorLabel::kUnknown; case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_NONE: - return chromeos::RequestPinView::RequestPinErrorType::NONE; + return PinErrorLabel::kNone; } NOTREACHED(); - return chromeos::RequestPinView::RequestPinErrorType::NONE; + return PinErrorLabel::kNone; } } // namespace @@ -216,11 +218,11 @@ CertificateProviderStopPinRequestFunction::Run() { // Extension provided an error, which means it intends to notify the user with // the error and not allow any more input. - chromeos::RequestPinView::RequestPinErrorType error_type = - GetErrorTypeForView(params->details.error_type); + const PinErrorLabel error_label = + GetErrorLabelForDialog(params->details.error_type); const chromeos::PinDialogManager::StopPinRequestResult stop_request_result = service->pin_dialog_manager()->StopPinRequestWithError( - extension()->id(), error_type, + extension()->id(), error_label, base::BindOnce( &CertificateProviderStopPinRequestFunction::OnPinRequestStopped, this)); @@ -238,13 +240,7 @@ CertificateProviderStopPinRequestFunction::Run() { } void CertificateProviderStopPinRequestFunction::OnPinRequestStopped() { - chromeos::CertificateProviderService* const service = - chromeos::CertificateProviderServiceFactory::GetForBrowserContext( - browser_context()); - DCHECK(service); - Respond(NoArguments()); - service->pin_dialog_manager()->OnPinDialogClosed(); } CertificateProviderRequestPinFunction:: @@ -274,19 +270,19 @@ ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() { api_cp::RequestPin::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - api_cp::PinRequestType pin_request_type = + const api_cp::PinRequestType pin_request_type = params->details.request_type == api_cp::PinRequestType::PIN_REQUEST_TYPE_NONE ? api_cp::PinRequestType::PIN_REQUEST_TYPE_PIN : params->details.request_type; - chromeos::RequestPinView::RequestPinErrorType error_type = - GetErrorTypeForView(params->details.error_type); + const PinErrorLabel error_label = + GetErrorLabelForDialog(params->details.error_type); - chromeos::RequestPinView::RequestPinCodeType code_type = + const PinCodeType code_type = (pin_request_type == api_cp::PinRequestType::PIN_REQUEST_TYPE_PIN) - ? chromeos::RequestPinView::RequestPinCodeType::PIN - : chromeos::RequestPinView::RequestPinCodeType::PUK; + ? PinCodeType::kPin + : PinCodeType::kPuk; chromeos::CertificateProviderService* const service = chromeos::CertificateProviderServiceFactory::GetForBrowserContext( @@ -303,7 +299,8 @@ ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() { const chromeos::PinDialogManager::RequestPinResult result = service->pin_dialog_manager()->RequestPin( extension()->id(), extension()->name(), - params->details.sign_request_id, code_type, error_type, attempts_left, + params->details.sign_request_id, code_type, error_label, + attempts_left, base::BindOnce( &CertificateProviderRequestPinFunction::OnInputReceived, this)); switch (result) { diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h index 67b8ee0eabb..b61e947336d 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h @@ -28,9 +28,9 @@ struct CertificateInfo; } class CertificateProviderInternalReportCertificatesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderInternalReportCertificatesFunction() override; ResponseAction Run() override; @@ -43,9 +43,9 @@ class CertificateProviderInternalReportCertificatesFunction }; class CertificateProviderInternalReportSignatureFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderInternalReportSignatureFunction() override; ResponseAction Run() override; @@ -53,9 +53,9 @@ class CertificateProviderInternalReportSignatureFunction CERTIFICATEPROVIDERINTERNAL_REPORTSIGNATURE) }; -class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction { +class CertificateProviderRequestPinFunction : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderRequestPinFunction() override; ResponseAction Run() override; bool ShouldSkipQuotaLimiting() const override; @@ -68,10 +68,9 @@ class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction { CERTIFICATEPROVIDER_REQUESTPIN) }; -class CertificateProviderStopPinRequestFunction - : public UIThreadExtensionFunction { +class CertificateProviderStopPinRequestFunction : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderStopPinRequestFunction() override; ResponseAction Run() override; diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc index 2a266152d46..1611eb4a730 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc @@ -173,7 +173,7 @@ class CertificateProviderRequestPinTest : public CertificateProviderApiTest { void AddFakeSignRequest() { cert_provider_service_->pin_dialog_manager()->AddSignRequestId( - extension_->id(), kFakeSignRequestId); + extension_->id(), kFakeSignRequestId, {}); } void NavigateTo(const std::string& test_page_file_name) { @@ -183,11 +183,13 @@ class CertificateProviderRequestPinTest : public CertificateProviderApiTest { chromeos::RequestPinView* GetActivePinDialogView() { return cert_provider_service_->pin_dialog_manager() + ->default_dialog_host_for_testing() ->active_view_for_testing(); } views::Widget* GetActivePinDialogWindow() { return cert_provider_service_->pin_dialog_manager() + ->default_dialog_host_for_testing() ->active_window_for_testing(); } 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 b8070abbf3d..4772d8e3c12 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc @@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/files/file_path.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "build/build_config.h" @@ -16,6 +17,7 @@ #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/extension_action/extension_action_api.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" @@ -25,7 +27,10 @@ #include "chrome/browser/extensions/api/storage/managed_value_store_cache.h" #include "chrome/browser/extensions/api/storage/sync_value_store_cache.h" #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h" +#include "chrome/browser/extensions/extension_action.h" +#include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_action_runner.h" +#include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/system_display/display_info_provider.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.h" @@ -103,7 +108,7 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers( extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents); - if (performance_manager::PerformanceManager::GetInstance()) { + if (performance_manager::PerformanceManager::IsAvailable()) { performance_manager::PerformanceManagerTabHelper::CreateForWebContents( web_contents); } @@ -213,6 +218,57 @@ void ChromeExtensionsAPIClient::NotifyWebRequestWithheld( runner->OnWebRequestBlocked(extension); } +void ChromeExtensionsAPIClient::UpdateActionCount( + content::BrowserContext* context, + const ExtensionId& extension_id, + int tab_id, + int action_count, + bool clear_badge_text) { + const Extension* extension = + ExtensionRegistry::Get(context)->enabled_extensions().GetByID( + extension_id); + DCHECK(extension); + + ExtensionAction* action = + ExtensionActionManager::Get(context)->GetExtensionAction(*extension); + DCHECK(action); + + action->SetDNRActionCount(tab_id, action_count); + + // The badge text should be cleared if |action| contains explicitly set badge + // text for the |tab_id| when the preference is then toggled on. In this case, + // the matched action count should take precedence over the badge text. + if (clear_badge_text) + action->ClearBadgeText(tab_id); + + content::WebContents* tab_contents = nullptr; + if (ExtensionTabUtil::GetTabById( + tab_id, context, true /* include_incognito */, &tab_contents) && + tab_contents) { + ExtensionActionAPI::Get(context)->NotifyChange(action, tab_contents, + context); + } +} + +void ChromeExtensionsAPIClient::ClearActionCount( + content::BrowserContext* context, + const Extension& extension) { + ExtensionAction* action = + ExtensionActionManager::Get(context)->GetExtensionAction(extension); + DCHECK(action); + + action->ClearDNRActionCountForAllTabs(); + + std::vector<content::WebContents*> contents_to_notify = + ExtensionTabUtil::GetAllActiveWebContentsForContext( + context, true /* include_incognito */); + + for (auto* active_contents : contents_to_notify) { + ExtensionActionAPI::Get(context)->NotifyChange(action, active_contents, + context); + } +} + AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate() const { return new ChromeAppViewGuestDelegate(); @@ -241,9 +297,9 @@ WebViewGuestDelegate* ChromeExtensionsAPIClient::CreateWebViewGuestDelegate( return new ChromeWebViewGuestDelegate(web_view_guest); } -WebViewPermissionHelperDelegate* ChromeExtensionsAPIClient:: - CreateWebViewPermissionHelperDelegate( - WebViewPermissionHelper* web_view_permission_helper) const { +WebViewPermissionHelperDelegate* +ChromeExtensionsAPIClient::CreateWebViewPermissionHelperDelegate( + WebViewPermissionHelper* web_view_permission_helper) const { return new ChromeWebViewPermissionHelperDelegate(web_view_permission_helper); } @@ -251,12 +307,10 @@ scoped_refptr<ContentRulesRegistry> ChromeExtensionsAPIClient::CreateContentRulesRegistry( content::BrowserContext* browser_context, RulesCacheDelegate* cache_delegate) const { - return scoped_refptr<ContentRulesRegistry>( - new ChromeContentRulesRegistry( - browser_context, - cache_delegate, - base::Bind(&CreateDefaultContentPredicateEvaluators, - base::Unretained(browser_context)))); + return base::MakeRefCounted<ChromeContentRulesRegistry>( + browser_context, cache_delegate, + base::Bind(&CreateDefaultContentPredicateEvaluators, + base::Unretained(browser_context))); } std::unique_ptr<DevicePermissionsPrompt> 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 a4837bf2e18..f5ff000a8c4 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h @@ -39,6 +39,13 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient { void NotifyWebRequestWithheld(int render_process_id, int render_frame_id, const ExtensionId& extension_id) override; + void UpdateActionCount(content::BrowserContext* context, + const ExtensionId& extension_id, + int tab_id, + int action_count, + bool clear_badge_text) override; + void ClearActionCount(content::BrowserContext* context, + const Extension& extension) override; AppViewGuestDelegate* CreateAppViewGuestDelegate() const override; ExtensionOptionsGuestDelegate* CreateExtensionOptionsGuestDelegate( ExtensionOptionsGuest* guest) const override; diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc index 73d0c21d940..7948a83f6dc 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc @@ -6,7 +6,7 @@ #include "base/macros.h" #include "chrome/common/webui_url_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/web_request_info.h" #include "google_apis/gaia/gaia_urls.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,7 +19,7 @@ class ChromeExtensionsAPIClientTest : public testing::Test { ChromeExtensionsAPIClientTest() = default; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClientTest); }; diff --git a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h index eb7494ec660..35900ac4fd7 100644 --- a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h +++ b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h @@ -48,8 +48,7 @@ class CloudPrintTestsDelegate { virtual std::vector<std::string> GetPrinters() = 0; }; -class CloudPrintPrivateSetupConnectorFunction - : public UIThreadExtensionFunction { +class CloudPrintPrivateSetupConnectorFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.setupConnector", CLOUDPRINTPRIVATE_SETUPCONNECTOR) @@ -63,7 +62,7 @@ class CloudPrintPrivateSetupConnectorFunction ResponseAction Run() override; }; -class CloudPrintPrivateGetHostNameFunction : public UIThreadExtensionFunction { +class CloudPrintPrivateGetHostNameFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.getHostName", CLOUDPRINTPRIVATE_GETHOSTNAME) @@ -77,7 +76,7 @@ class CloudPrintPrivateGetHostNameFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class CloudPrintPrivateGetPrintersFunction : public UIThreadExtensionFunction { +class CloudPrintPrivateGetPrintersFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.getPrinters", CLOUDPRINTPRIVATE_GETPRINTERS) @@ -94,7 +93,7 @@ class CloudPrintPrivateGetPrintersFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class CloudPrintPrivateGetClientIdFunction : public UIThreadExtensionFunction { +class CloudPrintPrivateGetClientIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.getClientId", CLOUDPRINTPRIVATE_GETCLIENTID) diff --git a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h index 4ab0dd1457e..56841a47bb3 100644 --- a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h +++ b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h @@ -9,7 +9,7 @@ namespace extensions { -class CommandLinePrivateHasSwitchFunction : public UIThreadExtensionFunction { +class CommandLinePrivateHasSwitchFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("commandLinePrivate.hasSwitch", COMMANDLINEPRIVATE_HASSWITCH) protected: diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.cc b/chromium/chrome/browser/extensions/api/commands/command_service.cc index 8e055684c41..6f1e04fcaf5 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service.cc @@ -143,12 +143,12 @@ bool CommandService::RemovesBookmarkShortcut(const Extension* extension) { } // static -bool CommandService::RemovesBookmarkOpenPagesShortcut( +bool CommandService::RemovesBookmarkAllTabsShortcut( const Extension* extension) { - return UIOverrides::RemovesBookmarkOpenPagesShortcut(extension) && - (extension->permissions_data()->HasAPIPermission( - APIPermission::kBookmarkManagerPrivate) || - FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()); + return UIOverrides::RemovesBookmarkAllTabsShortcut(extension) && + (extension->permissions_data()->HasAPIPermission( + APIPermission::kBookmarkManagerPrivate) || + FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()); } bool CommandService::GetBrowserActionCommand(const std::string& extension_id, @@ -426,7 +426,7 @@ bool CommandService::RequestsBookmarkShortcutOverride( return RemovesBookmarkShortcut(extension) && GetSuggestedExtensionCommand( extension->id(), - chrome::GetPrimaryChromeAcceleratorForBookmarkPage(), nullptr); + chrome::GetPrimaryChromeAcceleratorForBookmarkTab(), nullptr); } void CommandService::AddObserver(Observer* observer) { @@ -579,7 +579,7 @@ bool CommandService::CanAutoAssign(const Command &command, // Not a global command, check if Chrome shortcut and whether // we can override it. if (command.accelerator() == - chrome::GetPrimaryChromeAcceleratorForBookmarkPage() && + chrome::GetPrimaryChromeAcceleratorForBookmarkTab() && CommandService::RemovesBookmarkShortcut(extension)) { // If this check fails it either means we have an API to override a // key that isn't a ChromeAccelerator (and the API can therefore be diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.h b/chromium/chrome/browser/extensions/api/commands/command_service.h index 22d82e817a1..6f3e1e89a9c 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.h +++ b/chromium/chrome/browser/extensions/api/commands/command_service.h @@ -99,8 +99,8 @@ class CommandService : public BrowserContextKeyedAPI, static bool RemovesBookmarkShortcut(const Extension* extension); // Returns true if |extension| is permitted to and does remove the bookmark - // open pages shortcut key. - static bool RemovesBookmarkOpenPagesShortcut(const Extension* extension); + // all tabs shortcut key. + static bool RemovesBookmarkAllTabsShortcut(const Extension* extension); // Gets the command (if any) for the browser action of an extension given // its |extension_id|. The function consults the master list to see if diff --git a/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc b/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc index c9ecdae11e3..a6a2e01b0ac 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc @@ -10,11 +10,11 @@ #include "build/build_config.h" #include "chrome/browser/extensions/api/commands/command_service.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/common/pref_names.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" +#include "extensions/browser/extension_registry.h" #include "extensions/common/manifest_constants.h" namespace { @@ -64,15 +64,14 @@ IN_PROC_BROWSER_TEST_F(CommandServiceTest, RemoveShortcutSurvivesUpdate) { scoped_temp_dir.GetPath().AppendASCII("v2.crx"), pem_path, base::FilePath()); - ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> - extension_service(); + ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); CommandService* command_service = CommandService::Get(browser()->profile()); const char kId[] = "pgoakhfeplldmjheffidklpoklkppipp"; // Install v1 of the extension. ASSERT_TRUE(InstallExtension(path_v1, 1)); - EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); + EXPECT_TRUE(registry->GetExtensionById(kId, ExtensionRegistry::ENABLED)); // Verify it has a command of Alt+Shift+F. ui::Accelerator accelerator = command_service->FindCommandByName( @@ -93,7 +92,7 @@ IN_PROC_BROWSER_TEST_F(CommandServiceTest, RemoveShortcutSurvivesUpdate) { // Update to version 2. EXPECT_TRUE(UpdateExtension(kId, path_v2, 0)); - EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); + EXPECT_TRUE(registry->GetExtensionById(kId, ExtensionRegistry::ENABLED)); // Verify it is still set to nothing. accelerator = command_service->FindCommandByName( diff --git a/chromium/chrome/browser/extensions/api/commands/commands.h b/chromium/chrome/browser/extensions/api/commands/commands.h index 16b940fb965..433bdd19756 100644 --- a/chromium/chrome/browser/extensions/api/commands/commands.h +++ b/chromium/chrome/browser/extensions/api/commands/commands.h @@ -7,7 +7,7 @@ #include "extensions/browser/extension_function.h" -class GetAllCommandsFunction : public UIThreadExtensionFunction { +class GetAllCommandsFunction : public ExtensionFunction { ~GetAllCommandsFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("commands.getAll", COMMANDS_GETALL) 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 f2458751626..0f87e20fe15 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 @@ -347,7 +347,7 @@ void ContentSettingsContentSettingGetResourceIdentifiersFunction::OnGotPlugins( list->Append(std::move(dict)); } SetResult(std::move(list)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ContentSettingsContentSettingGetResourceIdentifiersFunction:: diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h index fa0fb0c3e11..be5d3208e9c 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h @@ -14,8 +14,7 @@ struct WebPluginInfo; namespace extensions { -class ContentSettingsContentSettingClearFunction - : public UIThreadExtensionFunction { +class ContentSettingsContentSettingClearFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.clear", CONTENTSETTINGS_CLEAR) @@ -26,8 +25,7 @@ class ContentSettingsContentSettingClearFunction ResponseAction Run() override; }; -class ContentSettingsContentSettingGetFunction - : public UIThreadExtensionFunction { +class ContentSettingsContentSettingGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.get", CONTENTSETTINGS_GET) @@ -38,8 +36,7 @@ class ContentSettingsContentSettingGetFunction ResponseAction Run() override; }; -class ContentSettingsContentSettingSetFunction - : public UIThreadExtensionFunction { +class ContentSettingsContentSettingSetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.set", CONTENTSETTINGS_SET) diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc index 66c59d56e6e..47757999355 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/content_settings/content_settings_service.h" #include "base/lazy_instance.h" +#include "base/memory/scoped_refptr.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_prefs_scope.h" #include "extensions/browser/pref_names.h" @@ -12,7 +13,7 @@ namespace extensions { ContentSettingsService::ContentSettingsService(content::BrowserContext* context) - : content_settings_store_(new ContentSettingsStore()), + : content_settings_store_(base::MakeRefCounted<ContentSettingsStore>()), scoped_observer_(this) {} ContentSettingsService::~ContentSettingsService() {} diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h index 78e00b7415c..4dc9f20151a 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h @@ -9,7 +9,7 @@ namespace extensions { -class ContextMenusCreateFunction : public UIThreadExtensionFunction { +class ContextMenusCreateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.create", CONTEXTMENUS_CREATE) @@ -20,7 +20,7 @@ class ContextMenusCreateFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ContextMenusUpdateFunction : public UIThreadExtensionFunction { +class ContextMenusUpdateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.update", CONTEXTMENUS_UPDATE) @@ -31,7 +31,7 @@ class ContextMenusUpdateFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ContextMenusRemoveFunction : public UIThreadExtensionFunction { +class ContextMenusRemoveFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.remove", CONTEXTMENUS_REMOVE) @@ -42,7 +42,7 @@ class ContextMenusRemoveFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ContextMenusRemoveAllFunction : public UIThreadExtensionFunction { +class ContextMenusRemoveAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.removeAll", CONTEXTMENUS_REMOVEALL) diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc index 9a1e1967385..aca854a958e 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -182,14 +182,14 @@ void CookiesEventRouter::MaybeStartListening() { ? original_profile->GetOffTheRecordProfile() : nullptr; - if (!binding_) - BindToCookieManager(&binding_, original_profile); - if (!otr_binding_.is_bound() && otr_profile) - BindToCookieManager(&otr_binding_, otr_profile); + if (!receiver_.is_bound()) + BindToCookieManager(&receiver_, original_profile); + if (!otr_receiver_.is_bound() && otr_profile) + BindToCookieManager(&otr_receiver_, otr_profile); } void CookiesEventRouter::BindToCookieManager( - mojo::Binding<network::mojom::CookieChangeListener>* binding, + mojo::Receiver<network::mojom::CookieChangeListener>* receiver, Profile* profile) { network::mojom::CookieManager* cookie_manager = content::BrowserContext::GetDefaultStoragePartition(profile) @@ -197,19 +197,17 @@ void CookiesEventRouter::BindToCookieManager( if (!cookie_manager) return; - network::mojom::CookieChangeListenerPtr listener_ptr; - binding->Bind(mojo::MakeRequest(&listener_ptr)); - binding->set_connection_error_handler(base::BindOnce( - &CookiesEventRouter::OnConnectionError, base::Unretained(this), binding)); - - cookie_manager->AddGlobalChangeListener(std::move(listener_ptr)); + cookie_manager->AddGlobalChangeListener(receiver->BindNewPipeAndPassRemote()); + receiver->set_disconnect_handler( + base::BindOnce(&CookiesEventRouter::OnConnectionError, + base::Unretained(this), receiver)); } void CookiesEventRouter::OnConnectionError( - mojo::Binding<network::mojom::CookieChangeListener>* binding) { + mojo::Receiver<network::mojom::CookieChangeListener>* receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - binding->Close(); + receiver->reset(); MaybeStartListening(); } @@ -251,25 +249,26 @@ ExtensionFunction::ResponseAction CookiesGetFunction::Run() { if (!parsed_args_->details.store_id.get()) parsed_args_->details.store_id.reset(new std::string(store_id)); + DCHECK(!url_.is_empty() && url_.is_valid()); cookies_helpers::GetCookieListFromManager( cookie_manager, url_, - base::BindOnce(&CookiesGetFunction::GetCookieCallback, this)); + base::BindOnce(&CookiesGetFunction::GetCookieListCallback, this)); // Will finish asynchronously. return RespondLater(); } -void CookiesGetFunction::GetCookieCallback( - const net::CookieList& cookie_list, +void CookiesGetFunction::GetCookieListCallback( + const net::CookieStatusList& cookie_status_list, const net::CookieStatusList& excluded_cookies) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - for (const net::CanonicalCookie& cookie : cookie_list) { + for (const net::CookieWithStatus& cookie_with_status : cookie_status_list) { // Return the first matching cookie. Relies on the fact that the // CookieManager interface returns them in canonical order (longest path, // then earliest creation time). - if (cookie.Name() == parsed_args_->details.name) { + if (cookie_with_status.cookie.Name() == parsed_args_->details.name) { api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie( - cookie, *parsed_args_->details.store_id); + cookie_with_status.cookie, *parsed_args_->details.store_id); Respond(ArgumentList(api::cookies::Get::Results::Create(api_cookie))); return; } @@ -308,22 +307,46 @@ ExtensionFunction::ResponseAction CookiesGetAllFunction::Run() { parsed_args_->details.store_id.reset(new std::string(store_id)); DCHECK(url_.is_empty() || url_.is_valid()); - cookies_helpers::GetCookieListFromManager( - cookie_manager, url_, - base::BindOnce(&CookiesGetAllFunction::GetAllCookiesCallback, this)); + if (url_.is_empty()) { + cookies_helpers::GetAllCookiesFromManager( + cookie_manager, + base::BindOnce(&CookiesGetAllFunction::GetAllCookiesCallback, this)); + } else { + cookies_helpers::GetCookieListFromManager( + cookie_manager, url_, + base::BindOnce(&CookiesGetAllFunction::GetCookieListCallback, this)); + } return RespondLater(); } void CookiesGetAllFunction::GetAllCookiesCallback( - const net::CookieList& cookie_list, + const net::CookieList& cookie_list) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + ResponseValue response; + if (extension()) { + std::vector<api::cookies::Cookie> match_vector; + cookies_helpers::AppendMatchingCookiesFromCookieListToVector( + cookie_list, &parsed_args_->details, extension(), &match_vector); + + response = + ArgumentList(api::cookies::GetAll::Results::Create(match_vector)); + } else { + // TODO(devlin): When can |extension()| be null for this function? + response = NoArguments(); + } + Respond(std::move(response)); +} + +void CookiesGetAllFunction::GetCookieListCallback( + const net::CookieStatusList& cookie_status_list, const net::CookieStatusList& excluded_cookies) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ResponseValue response; if (extension()) { std::vector<api::cookies::Cookie> match_vector; - cookies_helpers::AppendMatchingCookiesToVector( - cookie_list, url_, &parsed_args_->details, extension(), &match_vector); + cookies_helpers::AppendMatchingCookiesFromCookieStatusListToVector( + cookie_status_list, &parsed_args_->details, extension(), &match_vector); response = ArgumentList(api::cookies::GetAll::Results::Create(match_vector)); @@ -417,7 +440,7 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() { // is generated. success_ = false; state_ = SET_COMPLETED; - GetCookieListCallback(net::CookieList(), net::CookieStatusList()); + GetCookieListCallback(net::CookieStatusList(), net::CookieStatusList()); return AlreadyResponded(); } @@ -428,6 +451,7 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() { options.set_include_httponly(); options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); + DCHECK(!url_.is_empty() && url_.is_valid()); cookie_manager->SetCanonicalCookie( *cc, url_.scheme(), options, base::BindOnce(&CookiesSetFunction::SetCanonicalCookieCallback, this)); @@ -444,12 +468,11 @@ void CookiesSetFunction::SetCanonicalCookieCallback( DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(NO_RESPONSE, state_); state_ = SET_COMPLETED; - success_ = (set_cookie_result == - net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + success_ = set_cookie_result.IsInclude(); } void CookiesSetFunction::GetCookieListCallback( - const net::CookieList& cookie_list, + const net::CookieStatusList& cookie_list, const net::CookieStatusList& excluded_cookies) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(SET_COMPLETED, state_); @@ -465,16 +488,16 @@ void CookiesSetFunction::GetCookieListCallback( } ResponseValue value; - for (const net::CanonicalCookie& cookie : cookie_list) { + for (const net::CookieWithStatus& cookie_with_status : cookie_list) { // Return the first matching cookie. Relies on the fact that the // CookieMonster returns them in canonical order (longest path, then // earliest creation time). std::string name = parsed_args_->details.name.get() ? *parsed_args_->details.name : std::string(); - if (cookie.Name() == name) { + if (cookie_with_status.cookie.Name() == name) { api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie( - cookie, *parsed_args_->details.store_id); + cookie_with_status.cookie, *parsed_args_->details.store_id); value = ArgumentList(api::cookies::Set::Results::Create(api_cookie)); break; } diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h index fbd37d66f00..ac95fc35736 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h @@ -19,7 +19,8 @@ #include "chrome/common/extensions/api/cookies.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "net/cookies/canonical_cookie.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "url/gurl.h" @@ -60,10 +61,10 @@ class CookiesEventRouter : public BrowserListObserver { void MaybeStartListening(); void BindToCookieManager( - mojo::Binding<network::mojom::CookieChangeListener>* binding, + mojo::Receiver<network::mojom::CookieChangeListener>* receiver, Profile* profile); void OnConnectionError( - mojo::Binding<network::mojom::CookieChangeListener>* binding); + mojo::Receiver<network::mojom::CookieChangeListener>* receiver); void OnCookieChange(bool otr, const net::CanonicalCookie& canonical_cookie, network::mojom::CookieChangeCause cause); @@ -81,17 +82,17 @@ class CookiesEventRouter : public BrowserListObserver { // profiles, we need a pair of bindings, as well as a pair of // CookieChangeListener instances. CookieChangeListener listener_{this, false}; - mojo::Binding<network::mojom::CookieChangeListener> binding_{&listener_}; + mojo::Receiver<network::mojom::CookieChangeListener> receiver_{&listener_}; CookieChangeListener otr_listener_{this, true}; - mojo::Binding<network::mojom::CookieChangeListener> otr_binding_{ + mojo::Receiver<network::mojom::CookieChangeListener> otr_receiver_{ &otr_listener_}; DISALLOW_COPY_AND_ASSIGN(CookiesEventRouter); }; // Implements the cookies.get() extension function. -class CookiesGetFunction : public UIThreadExtensionFunction { +class CookiesGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.get", COOKIES_GET) @@ -104,16 +105,16 @@ class CookiesGetFunction : public UIThreadExtensionFunction { ResponseAction Run() override; private: - void GetCookieCallback(const net::CookieList& cookie_list, - const net::CookieStatusList& excluded_cookies); + void GetCookieListCallback(const net::CookieStatusList& cookie_status_list, + const net::CookieStatusList& excluded_cookies); GURL url_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::Get::Params> parsed_args_; }; // Implements the cookies.getAll() extension function. -class CookiesGetAllFunction : public UIThreadExtensionFunction { +class CookiesGetAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.getAll", COOKIES_GETALL) @@ -126,16 +127,19 @@ class CookiesGetAllFunction : public UIThreadExtensionFunction { ResponseAction Run() override; private: - void GetAllCookiesCallback(const net::CookieList& cookie_list, + // For the two different callback signatures for getting cookies for a URL vs + // getting all cookies. They do the same thing. + void GetAllCookiesCallback(const net::CookieList& cookie_list); + void GetCookieListCallback(const net::CookieStatusList& cookie_status_list, const net::CookieStatusList& excluded_cookies); GURL url_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::GetAll::Params> parsed_args_; }; // Implements the cookies.set() extension function. -class CookiesSetFunction : public UIThreadExtensionFunction { +class CookiesSetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.set", COOKIES_SET) @@ -148,18 +152,18 @@ class CookiesSetFunction : public UIThreadExtensionFunction { private: void SetCanonicalCookieCallback( net::CanonicalCookie::CookieInclusionStatus set_cookie_result); - void GetCookieListCallback(const net::CookieList& cookie_list, + void GetCookieListCallback(const net::CookieStatusList& cookie_list, const net::CookieStatusList& excluded_cookies); enum { NO_RESPONSE, SET_COMPLETED, GET_COMPLETED } state_; GURL url_; bool success_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::Set::Params> parsed_args_; }; // Implements the cookies.remove() extension function. -class CookiesRemoveFunction : public UIThreadExtensionFunction { +class CookiesRemoveFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.remove", COOKIES_REMOVE) @@ -175,12 +179,12 @@ class CookiesRemoveFunction : public UIThreadExtensionFunction { void RemoveCookieCallback(uint32_t /* num_deleted */); GURL url_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::Remove::Params> parsed_args_; }; // Implements the cookies.getAllCookieStores() extension function. -class CookiesGetAllCookieStoresFunction : public UIThreadExtensionFunction { +class CookiesGetAllCookieStoresFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.getAllCookieStores", COOKIES_GETALLCOOKIESTORES) diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc index 2c663be2948..f4dfc24b93c 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc @@ -38,6 +38,28 @@ namespace GetAll = extensions::api::cookies::GetAll; namespace extensions { +namespace { + +void AppendCookieToVectorIfMatchAndHasHostPermission( + const net::CanonicalCookie cookie, + const GetAll::Params::Details* details, + const Extension* extension, + std::vector<Cookie>* match_vector) { + // Ignore any cookie whose domain doesn't match the extension's + // host permissions. + GURL cookie_domain_url = cookies_helpers::GetURLFromCanonicalCookie(cookie); + if (!extension->permissions_data()->HasHostPermission(cookie_domain_url)) + return; + // Filter the cookie using the match filter. + cookies_helpers::MatchFilter filter(details); + if (filter.MatchesCookie(cookie)) { + match_vector->push_back( + cookies_helpers::CreateCookie(cookie, *details->store_id)); + } +} + +} // namespace + namespace cookies_helpers { static const char kOriginalProfileStoreId[] = "0"; @@ -81,6 +103,7 @@ Cookie CreateCookie(const net::CanonicalCookie& canonical_cookie, cookie.secure = canonical_cookie.IsSecure(); cookie.http_only = canonical_cookie.IsHttpOnly(); + DCHECK(net::IsValidSameSiteValue(canonical_cookie.SameSite())); switch (canonical_cookie.SameSite()) { case net::CookieSameSite::NO_RESTRICTION: cookie.same_site = api::cookies::SAME_SITE_STATUS_NO_RESTRICTION; @@ -95,6 +118,8 @@ Cookie CreateCookie(const net::CanonicalCookie& canonical_cookie, case net::CookieSameSite::UNSPECIFIED: cookie.same_site = api::cookies::SAME_SITE_STATUS_UNSPECIFIED; break; + default: + NOTREACHED(); } cookie.session = !canonical_cookie.IsPersistent(); @@ -129,22 +154,14 @@ void GetCookieListFromManager( network::mojom::CookieManager* manager, const GURL& url, network::mojom::CookieManager::GetCookieListCallback callback) { - if (url.is_empty()) { - // GetAllCookies has a different callback signature than GetCookieList, but - // can be treated as the same, just returning no excluded cookies. - // |AddCookieStatusList| takes a |GetCookieListCallback| and returns a - // callback that calls the input callback with an empty excluded list. - manager->GetAllCookies( - net::cookie_util::AddCookieStatusList(std::move(callback))); - } else { - net::CookieOptions options; - options.set_include_httponly(); - options.set_same_site_cookie_context( - net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - options.set_do_not_update_access_time(); - - manager->GetCookieList(url, options, std::move(callback)); - } + manager->GetCookieList(url, net::CookieOptions::MakeAllInclusive(), + std::move(callback)); +} + +void GetAllCookiesFromManager( + network::mojom::CookieManager* manager, + network::mojom::CookieManager::GetAllCookiesCallback callback) { + manager->GetAllCookies(std::move(callback)); } GURL GetURLFromCanonicalCookie(const net::CanonicalCookie& cookie) { @@ -158,21 +175,27 @@ GURL GetURLFromCanonicalCookie(const net::CanonicalCookie& cookie) { return GURL(scheme + url::kStandardSchemeSeparator + host + "/"); } -void AppendMatchingCookiesToVector(const net::CookieList& all_cookies, - const GURL& url, - const GetAll::Params::Details* details, - const Extension* extension, - std::vector<Cookie>* match_vector) { +void AppendMatchingCookiesFromCookieListToVector( + const net::CookieList& all_cookies, + const GetAll::Params::Details* details, + const Extension* extension, + std::vector<Cookie>* match_vector) { for (const net::CanonicalCookie& cookie : all_cookies) { - // Ignore any cookie whose domain doesn't match the extension's - // host permissions. - GURL cookie_domain_url = GetURLFromCanonicalCookie(cookie); - if (!extension->permissions_data()->HasHostPermission(cookie_domain_url)) - continue; - // Filter the cookie using the match filter. - cookies_helpers::MatchFilter filter(details); - if (filter.MatchesCookie(cookie)) - match_vector->push_back(CreateCookie(cookie, *details->store_id)); + AppendCookieToVectorIfMatchAndHasHostPermission(cookie, details, extension, + match_vector); + } +} + +void AppendMatchingCookiesFromCookieStatusListToVector( + const net::CookieStatusList& all_cookies_with_statuses, + const GetAll::Params::Details* details, + const Extension* extension, + std::vector<Cookie>* match_vector) { + for (const net::CookieWithStatus& cookie_with_status : + all_cookies_with_statuses) { + const net::CanonicalCookie& cookie = cookie_with_status.cookie; + AppendCookieToVectorIfMatchAndHasHostPermission(cookie, details, extension, + match_vector); } } diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h index 0b21eb056db..298b16e49a7 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h @@ -58,12 +58,17 @@ api::cookies::CookieStore CreateCookieStore( std::unique_ptr<base::ListValue> tab_ids); // Dispatch a request to the CookieManager for cookies associated with -// |url|, or all cookies if |url.is_empty()|. +// |url|. void GetCookieListFromManager( network::mojom::CookieManager* manager, const GURL& url, network::mojom::CookieManager::GetCookieListCallback callback); +// Dispatch a request to the CookieManager for all cookies. +void GetAllCookiesFromManager( + network::mojom::CookieManager* manager, + network::mojom::CookieManager::GetAllCookiesCallback callback); + // Constructs a URL from a cookie's information for use in checking // a cookie against the extension's host permissions. The Secure // property of the cookie defines the URL scheme, and the cookie's @@ -74,9 +79,15 @@ GURL GetURLFromCanonicalCookie( // Looks through all cookies in the given cookie store, and appends to the // match vector all the cookies that both match the given URL and cookie details // and are allowed by extension host permissions. -void AppendMatchingCookiesToVector( +void AppendMatchingCookiesFromCookieListToVector( const net::CookieList& all_cookies, - const GURL& url, + const api::cookies::GetAll::Params::Details* details, + const Extension* extension, + std::vector<api::cookies::Cookie>* match_vector); + +// Same as above except takes a CookieStatusList (and ignores the statuses). +void AppendMatchingCookiesFromCookieStatusListToVector( + const net::CookieStatusList& all_cookies_with_statuses, const api::cookies::GetAll::Params::Details* details, const Extension* extension, std::vector<api::cookies::Cookie>* match_vector); diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc index fbfc9935aa7..56e587afe38 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc @@ -10,13 +10,14 @@ #include <memory> #include <utility> +#include "base/optional.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/browser/extensions/api/cookies/cookies_api_constants.h" #include "chrome/browser/extensions/api/cookies/cookies_helpers.h" #include "chrome/common/extensions/api/cookies.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_constants.h" #include "testing/gtest/include/gtest/gtest.h" @@ -43,7 +44,7 @@ struct DomainMatchCase { class ExtensionCookiesTest : public testing::Test { private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(ExtensionCookiesTest, StoreIdProfileConversion) { @@ -186,9 +187,9 @@ TEST_F(ExtensionCookiesTest, DomainMatching) { TEST_F(ExtensionCookiesTest, DecodeUTF8WithErrorHandling) { std::unique_ptr<net::CanonicalCookie> canonical_cookie( - net::CanonicalCookie::Create(GURL("http://test.com"), - "=011Q255bNX_1!yd\203e+;path=/path\203", - base::Time::Now(), net::CookieOptions())); + net::CanonicalCookie::Create( + GURL("http://test.com"), "=011Q255bNX_1!yd\203e+;path=/path\203", + base::Time::Now(), base::nullopt /* server_time */)); ASSERT_NE(nullptr, canonical_cookie.get()); Cookie cookie = cookies_helpers::CreateCookie(*canonical_cookie, "some cookie store"); diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc index 40acfb6057a..da020fe3416 100644 --- a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc @@ -216,9 +216,7 @@ CryptotokenPrivateCanAppIdGetAttestationFunction::Run() { content::WebContents* web_contents = nullptr; if (!ExtensionTabUtil::GetTabById(params->options.tab_id, browser_context(), true /* include incognito windows */, - nullptr /* out_browser */, - nullptr /* out_tab_strip */, &web_contents, - nullptr /* out_tab_index */)) { + &web_contents)) { return RespondNow(Error("cannot find specified tab")); } diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h index 7c92493260b..9ac938c8b12 100644 --- a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h @@ -27,18 +27,18 @@ void CryptotokenRegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry); class CryptotokenPrivateCanOriginAssertAppIdFunction - : public UIThreadExtensionFunction { - public: - CryptotokenPrivateCanOriginAssertAppIdFunction(); - DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canOriginAssertAppId", - CRYPTOTOKENPRIVATE_CANORIGINASSERTAPPID) - protected: - ~CryptotokenPrivateCanOriginAssertAppIdFunction() override {} - ResponseAction Run() override; + : public ExtensionFunction { + public: + CryptotokenPrivateCanOriginAssertAppIdFunction(); + DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canOriginAssertAppId", + CRYPTOTOKENPRIVATE_CANORIGINASSERTAPPID) + protected: + ~CryptotokenPrivateCanOriginAssertAppIdFunction() override {} + ResponseAction Run() override; }; class CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction(); DECLARE_EXTENSION_FUNCTION( @@ -51,7 +51,7 @@ class CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction }; class CryptotokenPrivateCanAppIdGetAttestationFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: CryptotokenPrivateCanAppIdGetAttestationFunction(); DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canAppIdGetAttestation", diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc index 0500f7e9888..4ed224a3259 100644 --- a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc @@ -31,7 +31,7 @@ namespace { using namespace api::cryptotoken_private; -bool GetSingleBooleanResult(UIThreadExtensionFunction* function, bool* result) { +bool GetSingleBooleanResult(ExtensionFunction* function, bool* result) { const base::ListValue* result_list = function->GetResultList(); if (!result_list) { ADD_FAILURE() << "Function has no result list."; diff --git a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc index b7903610641..b8d2c3b4444 100644 --- a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc +++ b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc @@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/memory/scoped_refptr.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h" #include "chrome/browser/profiles/profile.h" @@ -82,7 +83,7 @@ DashboardPrivateShowPermissionPromptForDelegatedInstallFunction::Run() { .get(); } - scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper( + auto helper = base::MakeRefCounted<WebstoreInstallHelper>( this, params_->details.id, params_->details.manifest, icon_url); // The helper will call us back via OnWebstoreParseSuccess or diff --git a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h index 66697ef6964..93a75ad77b5 100644 --- a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h +++ b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h @@ -23,7 +23,7 @@ namespace extensions { class Extension; class DashboardPrivateShowPermissionPromptForDelegatedInstallFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public WebstoreInstallHelper::Delegate { public: DECLARE_EXTENSION_FUNCTION( diff --git a/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h b/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h index 8af53d7e2bd..07306919e59 100644 --- a/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h +++ b/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h @@ -15,8 +15,7 @@ class DataUsageBucket; namespace extensions { -class DataReductionProxyClearDataSavingsFunction - : public UIThreadExtensionFunction { +class DataReductionProxyClearDataSavingsFunction : public ExtensionFunction { private: ~DataReductionProxyClearDataSavingsFunction() override {} @@ -26,8 +25,7 @@ class DataReductionProxyClearDataSavingsFunction ResponseAction Run() override; }; -class DataReductionProxyGetDataUsageFunction - : public UIThreadExtensionFunction { +class DataReductionProxyGetDataUsageFunction : public ExtensionFunction { private: ~DataReductionProxyGetDataUsageFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc index e5cd5ab180e..6c79f07702a 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc @@ -421,10 +421,10 @@ void DebuggerFunction::FormatErrorMessage(const std::string& format) { bool DebuggerFunction::InitAgentHost() { if (debuggee_.tab_id) { - WebContents* web_contents = NULL; + WebContents* web_contents = nullptr; bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id, GetProfile(), include_incognito_information(), - NULL, NULL, &web_contents, NULL); + &web_contents); if (result && web_contents) { // TODO(rdevlin.cronin) This should definitely be GetLastCommittedURL(). GURL url = web_contents->GetVisibleURL(); @@ -668,7 +668,7 @@ DebuggerGetTargetsFunction::~DebuggerGetTargetsFunction() { bool DebuggerGetTargetsFunction::RunAsync() { content::DevToolsAgentHost::List list = DevToolsAgentHost::GetOrCreateAll(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DebuggerGetTargetsFunction::SendTargetList, this, list)); return true; diff --git a/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc b/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc index 29f627d834f..ae31311197c 100644 --- a/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc @@ -15,8 +15,8 @@ #include "components/version_info/channel.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_task_traits.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "extensions/browser/api/declarative/test_rules_registry.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" #include "extensions/common/api/declarative/declarative_constants.h" @@ -63,7 +63,7 @@ class RulesRegistryServiceTest : public testing::Test { } protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) { @@ -85,22 +85,22 @@ TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) { EXPECT_TRUE(registry_service.GetRulesRegistry(key, "io").get()); EXPECT_FALSE(registry_service.GetRulesRegistry(key, "foo").get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "ui"), "ui_task")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "io"), "io_task")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "ui"), 1)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "io"), 1)); @@ -121,12 +121,12 @@ TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) { .Build(); registry_service.SimulateExtensionUninstalled(extension.get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "ui"), 0)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "io"), 0)); diff --git a/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc b/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc index fd55b3da387..6d91223e12d 100644 --- a/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc @@ -17,7 +17,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/declarative/rules_cache_delegate.h" #include "extensions/browser/api/declarative/rules_registry_service.h" diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h index 3cad3939ab9..058b888d5a0 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h @@ -11,8 +11,8 @@ #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_view_host.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/browser_test_utils.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_renderer_host.h" #include "testing/gtest/include/gtest/gtest.h" @@ -45,7 +45,7 @@ class DeclarativeContentConditionTrackerTest : public testing::Test { const void* GeneratePredicateGroupID(); private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; // Enables MockRenderProcessHosts. content::RenderViewHostTestEnabler render_view_host_test_enabler_; diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc index d9b1b058ecd..e704227958c 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc @@ -29,17 +29,22 @@ #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "build/build_config.h" +#include "chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h" +#include "chrome/browser/extensions/extension_action.h" +#include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_action_runner.h" #include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/load_error_reporter.h" #include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/net/profile_network_context_service.h" #include "chrome/browser/net/profile_network_context_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" +#include "chrome/common/extensions/api/extension_action/action_info.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" @@ -490,6 +495,18 @@ class DeclarativeNetRequestBrowserTest ASSERT_EQ("success", ExecuteScriptInBackgroundPage(extension_id, script)); } + void SetActionsAsBadgeText(const ExtensionId& extension_id, bool pref) { + const char* pref_string = pref ? "true" : "false"; + static constexpr char kSetActionCountAsBadgeTextScript[] = R"( + chrome.declarativeNetRequest.setActionCountAsBadgeText(%s); + window.domAutomationController.send("done"); + )"; + + ExecuteScriptInBackgroundPage( + extension_id, + base::StringPrintf(kSetActionCountAsBadgeTextScript, pref_string)); + } + std::set<GURL> GetAndResetRequestsToServer() { base::AutoLock lock(requests_to_server_lock_); std::set<GURL> results = requests_to_server_; @@ -942,7 +959,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowRedirect) { rule.condition->url_filter = rule_data.url_filter; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rule.action->type = rule_data.action_type; - rule.action->redirect_url = rule_data.redirect_url; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; rules.push_back(rule); } @@ -1155,7 +1173,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Add |kNumExtensions| each redirecting example.com to a different redirect // url. for (size_t i = 1; i <= kNumExtensions; ++i) { - rule.action->redirect_url = redirect_url_for_extension_number(i); + rule.action->redirect.emplace(); + rule.action->redirect->url = redirect_url_for_extension_number(i); ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {rule}, std::to_string(i), {URLPattern::kAllUrlsPattern})); @@ -1198,7 +1217,6 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { {"def.com", 4, "block", base::nullopt}, {"def.com", 5, "redirect", get_url_for_host("xyz.com")}, {"ghi*", 6, "redirect", get_url_for_host("ghijk.com")}, - {"ijk*", 7, "redirect", "/manifest.json"}, }; // Load the extension. @@ -1210,7 +1228,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { rule.priority = kMinValidPriority; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rule.action->type = rule_data.action_type; - rule.action->redirect_url = rule_data.redirect_url; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; rules.push_back(rule); } ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( @@ -1236,13 +1255,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { // Though ghijk.com still matches the redirect rule for |ghi*|, it will // not redirect to itself. {"ghi.com", true, GURL(get_url_for_host("ghijk.com")), 2}, - // ijklm.com -> chrome-extension://<extension_id>/manifest.json. - // Since this redirects to a manifest.json, don't expect the frame with - // script to load. - {"ijklm.com", false, - GURL("chrome-extension://" + last_loaded_extension_id() + - "/manifest.json"), - 2}}; + }; for (const auto& test_case : test_cases) { std::string url = get_url_for_host(test_case.hostname); @@ -1299,7 +1312,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RedirectPriority) { rule.id = id++; rule.priority = j; rule.action->type = std::string("redirect"); - rule.action->redirect_url = redirect_url_for_priority(j); + rule.action->redirect.emplace(); + rule.action->redirect->url = redirect_url_for_priority(j); rule.condition->url_filter = pattern; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rules.push_back(rule); @@ -1372,7 +1386,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, UpgradeRules) { rule.priority = rule_data.priority; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rule.action->type = rule_data.action_type; - rule.action->redirect_url = rule_data.redirect_url; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; rules.push_back(rule); } @@ -1688,8 +1703,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, set_has_background_script(true); LoadExtensionWithRules({}); - const Extension* dnr_extension = extension_service()->GetExtensionById( - last_loaded_extension_id(), false /*include_disabled*/); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); ASSERT_TRUE(dnr_extension); EXPECT_EQ("Test extension", dnr_extension->name()); @@ -2046,8 +2061,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, const GURL unblocked_url = embedded_test_server()->GetURL( "yahoo.com", "/pages_with_script/index.html"); - const Extension* extension = extension_service()->GetExtensionById( - extension_id, false /*include_disabled*/); + const Extension* extension = extension_registry()->GetExtensionById( + extension_id, ExtensionRegistry::ENABLED); RulesetSource static_source = RulesetSource::CreateStatic(*extension); RulesetSource dynamic_source = RulesetSource::CreateDynamic(profile(), *extension); @@ -2281,15 +2296,16 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, rule.condition->resource_types = std::vector<std::string>({"script"}); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = + rule.action->redirect.emplace(); + rule.action->redirect->url = embedded_test_server()->GetURL("b.com", "/subresources/script.js").spec(); std::vector<std::string> host_permissions = {"*://a.com/", "*://b.com/*"}; ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {rule}, "extension" /* directory */, host_permissions)); - const Extension* extension = extension_service()->GetExtensionById( - last_loaded_extension_id(), false /*include_disabled*/); + const Extension* extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); auto verify_script_redirected = [this, extension]( @@ -2414,8 +2430,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {rule}, "test_extension", {URLPattern::kAllUrlsPattern})); - const Extension* extension = extension_service()->GetExtensionById( - last_loaded_extension_id(), false /*include_disabled*/); + const Extension* extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_TRUE(extension->permissions_data()->HasEffectiveAccessToAllHosts()); @@ -2477,7 +2493,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, DynamicRules) { std::vector<std::string>({"main_frame"}); redirect_rule.priority = kMinValidPriority; redirect_rule.action->type = std::string("redirect"); - redirect_rule.action->redirect_url = dynamic_redirect_url.spec(); + redirect_rule.action->redirect.emplace(); + redirect_rule.action->redirect->url = dynamic_redirect_url.spec(); redirect_rule.id = kMinValidID + 1; ASSERT_NO_FATAL_FAILURE(AddDynamicRules(last_loaded_extension_id(), @@ -2571,6 +2588,464 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, test_referrer_blocked(false); } +// Tests rules using the Redirect dictionary. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, Redirect) { + TestRule rule1 = CreateGenericRule(); + rule1.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule1.id = kMinValidID; + rule1.condition->url_filter = std::string("ex"); + rule1.action->type = std::string("redirect"); + rule1.priority = kMinValidPriority; + rule1.action->redirect.emplace(); + rule1.action->redirect->url = + embedded_test_server() + ->GetURL("google.com", "/pages_with_script/index.html") + .spec(); + + TestRule rule2 = CreateGenericRule(); + rule2.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule2.id = kMinValidID + 1; + rule2.condition->url_filter = std::string("example.com"); + rule2.action->type = std::string("redirect"); + rule2.priority = kMinValidPriority + 1; + rule2.action->redirect.emplace(); + rule2.action->redirect->extension_path = "/manifest.json?query#fragment"; + + TestRule rule3 = CreateGenericRule(); + rule3.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule3.id = kMinValidID + 2; + rule3.condition->url_filter = std::string("||example.com"); + rule3.action->type = std::string("redirect"); + rule3.priority = kMinValidPriority + 2; + rule3.action->redirect.emplace(); + rule3.action->redirect->transform.emplace(); + auto& transform = rule3.action->redirect->transform; + transform->host = "new.host.com"; + transform->path = "/pages_with_script/page.html"; + transform->query = "?new_query"; + transform->fragment = "#new_fragment"; + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {rule1, rule2, rule3}, "test_extension", {URLPattern::kAllUrlsPattern})); + + struct { + GURL url; + GURL expected_url; + } cases[] = {{embedded_test_server()->GetURL("example.com", + "/pages_with_script/index.html"), + // Because of higher priority, the transform rule is chosen. + embedded_test_server()->GetURL( + "new.host.com", + "/pages_with_script/page.html?new_query#new_fragment")}, + // Because of higher priority, the extensionPath rule is chosen. + {embedded_test_server()->GetURL( + "xyz.com", "/pages_with_script/index.html?example.com"), + GURL("chrome-extension://" + last_loaded_extension_id() + + "/manifest.json?query#fragment")}, + {embedded_test_server()->GetURL("ex.com", + "/pages_with_script/index.html"), + embedded_test_server()->GetURL( + "google.com", "/pages_with_script/index.html")}}; + + for (const auto& test_case : cases) { + SCOPED_TRACE("Testing " + test_case.url.spec()); + ui_test_utils::NavigateToURL(browser(), test_case.url); + EXPECT_EQ(test_case.expected_url, web_contents()->GetLastCommittedURL()); + } +} + +// Test that the badge text for an extension will update to reflect the number +// of actions taken on requests matching the extension's ruleset. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionsMatchedCountAsBadgeText) { + auto get_url_for_host = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, + "/pages_with_script/index.html"); + }; + + // This page simulates a user clicking on a link, so that the next page it + // navigates to has a Referrer header. + auto get_url_with_referrer = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, "/simulate_click.html"); + }; + + // Navigates frame with name |frame_name| to |url|. + auto navigate_frame = [this](const std::string& frame_name, const GURL& url) { + content::TestNavigationObserver navigation_observer( + web_contents(), 1 /*number_of_navigations*/); + + // Before navigation, We set the referrer policy of the iframe to + // 'no-referrer' to prevent a referer header from being added for the iframe + // navigation. + ASSERT_TRUE(content::ExecuteScript( + GetMainFrame(), + base::StringPrintf(R"( + document.getElementsByName('%s')[0].referrerPolicy = 'no-referrer'; + document.getElementsByName('%s')[0].src = '%s';)", + frame_name.c_str(), frame_name.c_str(), + url.spec().c_str()))); + navigation_observer.Wait(); + }; + + const std::string kFrameName1 = "frame1"; + const GURL page_url = embedded_test_server()->GetURL( + "norulesmatched.com", "/page_with_two_frames.html"); + + struct { + std::string url_filter; + int id; + int priority; + std::string action_type; + base::Optional<std::string> redirect_url; + base::Optional<std::vector<std::string>> remove_headers_list; + } rules_data[] = { + {"abc.com", 1, 1, "block", base::nullopt, base::nullopt}, + {"def.com", 2, 1, "redirect", "http://zzz.com", base::nullopt}, + {"jkl.com", 3, 1, "removeHeaders", base::nullopt, + std::vector<std::string>({"referer"})}, + {"abcd.com", 4, 1, "block", base::nullopt, base::nullopt}, + {"abcd", 5, 1, "allow", base::nullopt, base::nullopt}, + }; + + // Load the extension. + std::vector<TestRule> rules; + for (const auto& rule_data : rules_data) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = rule_data.url_filter; + rule.id = rule_data.id; + rule.priority = rule_data.priority; + rule.condition->resource_types = + std::vector<std::string>({"main_frame", "sub_frame"}); + rule.action->type = rule_data.action_type; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; + rule.action->remove_headers_list = rule_data.remove_headers_list; + rules.push_back(rule); + } + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId& extension_id = last_loaded_extension_id(); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + + ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText(extension_id, + true); + + ExtensionAction* action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + struct { + std::string frame_hostname; + std::string expected_badge_text; + bool has_referrer_header; + } test_cases[] = { + // zzz.com does not match any rules, but we should still display 0 as the + // badge text as the preference is on. + {"zzz.com", "0", false}, + // abc.com is blocked by a matching rule and should increment the badge + // text. + {"abc.com", "1", false}, + // def.com is redirected by a matching rule and should increment the badge + // text. + {"def.com", "2", false}, + // jkl.com matches with a removeHeaders rule, but has no headers. + // Therefore no action is taken and the badge text stays the same. + {"jkl.com", "2", false}, + // jkl.com matches with a removeHeaders rule and has a referrer header. + // Therefore the badge text should be incremented. + {"jkl.com", "3", true}, + // abcd.com matches both a block rule and an allow rule. Since the allow + // rule overrides the block rule, no action is taken and the badge text + // stays the same, + {"abcd.com", "3", false}, + }; + + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + // Verify that the badge text is 0 when navigation finishes. + int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ("0", action->GetDisplayBadgeText(first_tab_id)); + + for (const auto& test_case : test_cases) { + GURL url = test_case.has_referrer_header + ? get_url_with_referrer(test_case.frame_hostname) + : get_url_for_host(test_case.frame_hostname); + SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); + + navigate_frame(kFrameName1, url); + EXPECT_EQ(test_case.expected_badge_text, + action->GetDisplayBadgeText(first_tab_id)); + } + + std::string first_tab_badge_text = action->GetDisplayBadgeText(first_tab_id); + + const GURL second_tab_url = get_url_for_host("nomatch.com"); + ui_test_utils::NavigateToURLWithDisposition( + browser(), second_tab_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + + ASSERT_EQ(2, browser()->tab_strip_model()->count()); + ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(1)); + + int second_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ("0", action->GetDisplayBadgeText(second_tab_id)); + + // Verify that the badge text for the first tab is unaffected. + EXPECT_EQ(first_tab_badge_text, action->GetDisplayBadgeText(first_tab_id)); +} + +// Test that the extension cannot retrieve the number of actions matched +// from the badge text by calling chrome.browserAction.getBadgeText. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + GetBadgeTextForActionsMatched) { + auto query_badge_text_from_ext = [this](const ExtensionId& extension_id, + int tab_id) { + static constexpr char kBadgeTextQueryScript[] = R"( + chrome.browserAction.getBadgeText({tabId: %d}, badgeText => { + window.domAutomationController.send(badgeText); + }); + )"; + + return ExecuteScriptInBackgroundPage( + extension_id, base::StringPrintf(kBadgeTextQueryScript, tab_id)); + }; + + // Load the extension with a background script so scripts can be run from its + // generated background page. + set_has_background_script(true); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {}, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId& extension_id = last_loaded_extension_id(); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + + ExtensionAction* action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + const std::string default_badge_text = "asdf"; + action->SetBadgeText(ExtensionAction::kDefaultTabId, default_badge_text); + + const GURL page_url = embedded_test_server()->GetURL( + "norulesmatched.com", "/pages_with_script/index.html"); + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + // The preference is initially turned off. Both the visible badge text and the + // badge text queried by the extension using getBadgeText() should return the + // default badge text. + int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(first_tab_id)); + + std::string queried_badge_text = + query_badge_text_from_ext(extension_id, first_tab_id); + EXPECT_EQ(default_badge_text, queried_badge_text); + + SetActionsAsBadgeText(extension_id, true); + // Since the preference is on for the current tab, attempting to query the + // badge text from the extension should return the placeholder text instead of + // the matched action count. + queried_badge_text = query_badge_text_from_ext(extension_id, first_tab_id); + EXPECT_EQ(declarative_net_request::kActionCountPlaceholderBadgeText, + queried_badge_text); + + // The displayed badge text should show "0" as no actions have been matched. + EXPECT_EQ("0", action->GetDisplayBadgeText(first_tab_id)); + + SetActionsAsBadgeText(extension_id, false); + // Switching the preference off should cause the extension queried badge text + // to be the explicitly set badge text for this tab if it exists. In this + // case, the queried badge text should be the default badge text. + queried_badge_text = query_badge_text_from_ext(extension_id, first_tab_id); + EXPECT_EQ(default_badge_text, queried_badge_text); + + // The displayed badge text should be the default badge text now that the + // preference is off. + EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(first_tab_id)); + + // Verify that turning off the preference deletes the DNR action count within + // the extension action. + EXPECT_FALSE(action->HasDNRActionCount(first_tab_id)); +} + +// Test that enabling the setActionCountAsBadgeText preference will update +// all browsers sharing the same browser context. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionCountPreferenceMultipleWindows) { + // Load the extension with a background script so scripts can be run from its + // generated background page. + set_has_background_script(true); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {}, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId& extension_id = last_loaded_extension_id(); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + + ExtensionAction* extension_action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + const GURL page_url = embedded_test_server()->GetURL( + "norulesmatched.com", "/pages_with_script/index.html"); + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + int first_browser_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ("", extension_action->GetDisplayBadgeText(first_browser_tab_id)); + + // Now create a new browser with the same profile as |browser()| and navigate + // to |page_url|. + Browser* second_browser = CreateBrowser(profile()); + ui_test_utils::NavigateToURL(second_browser, page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame(second_browser))); + content::WebContents* second_browser_contents = + second_browser->tab_strip_model()->GetActiveWebContents(); + + int second_browser_tab_id = + ExtensionTabUtil::GetTabId(second_browser_contents); + EXPECT_EQ("", extension_action->GetDisplayBadgeText(second_browser_tab_id)); + + // Set up an observer to listen for ExtensionAction updates for the active web + // contents of both browser windows. + TestExtensionActionAPIObserver test_api_observer( + profile(), extension_id, {web_contents(), second_browser_contents}); + + SetActionsAsBadgeText(extension_id, true); + + // Wait until ExtensionActionAPI::NotifyChange is called, then perform a + // sanity check on the browser action's badge text. + test_api_observer.Wait(); + + EXPECT_EQ("0", extension_action->GetDisplayBadgeText(first_browser_tab_id)); + + // The badge text for the second browser window should also update to the + // matched action count because the second browser shares the same browser + // context as the first. + EXPECT_EQ("0", extension_action->GetDisplayBadgeText(second_browser_tab_id)); +} + +// Test that the action matched badge text for an extension is visible in an +// incognito context if the extension is incognito enabled. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionsMatchedCountAsBadgeTextIncognito) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = "abc.com"; + rule.id = kMinValidID; + rule.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule.action->type = "block"; + + std::vector<TestRule> rules({rule}); + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {rules}, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId extension_id = last_loaded_extension_id(); + util::SetIsIncognitoEnabled(extension_id, profile(), true /*enabled*/); + + ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText(extension_id, + true); + + Browser* incognito_browser = CreateIncognitoBrowser(); + ui_test_utils::NavigateToURL(incognito_browser, GURL("http://abc.com")); + + content::WebContents* incognito_contents = + incognito_browser->tab_strip_model()->GetActiveWebContents(); + + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + ExtensionAction* incognito_action = + ExtensionActionManager::Get(incognito_contents->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + // TODO(crbug.com/992251): This should be a "1" after the main-frame + // navigation case is fixed. + EXPECT_EQ("0", incognito_action->GetDisplayBadgeText( + ExtensionTabUtil::GetTabId(incognito_contents))); +} + +// Test that the actions matched badge text for an extension will be reset +// when a main-frame navigation finishes. +// TODO(crbug.com/992251): Edit this test to add more main-frame cases. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionsMatchedCountAsBadgeTextMainFrame) { + auto get_url_for_host = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, + "/pages_with_script/index.html"); + }; + + struct { + std::string url_filter; + int id; + int priority; + std::string action_type; + std::vector<std::string> resource_types; + base::Optional<std::string> redirect_url; + } rules_data[] = { + {"abc.com", 1, 1, "block", std::vector<std::string>({"script"}), + base::nullopt}, + {"def.com", 2, 1, "redirect", std::vector<std::string>({"main_frame"}), + get_url_for_host("abc.com").spec()}, + }; + + // Load the extension. + std::vector<TestRule> rules; + for (const auto& rule_data : rules_data) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = rule_data.url_filter; + rule.id = rule_data.id; + rule.priority = rule_data.priority; + rule.condition->resource_types = rule_data.resource_types; + rule.action->type = rule_data.action_type; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; + rules.push_back(rule); + } + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules, "test_extension", {URLPattern::kAllUrlsPattern})); + + const Extension* dnr_extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); + + ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText( + last_loaded_extension_id(), true); + + ExtensionAction* action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + struct { + std::string frame_hostname; + std::string expected_badge_text; + } test_cases[] = { + // The script on get_url_for_host("abc.com") matches with a rule and + // should increment the badge text. + {"abc.com", "1"}, + // No rules match, so the badge text should be 0 once navigation finishes. + {"nomatch.com", "0"}, + // The request to def.com will redirect to get_url_for_host("abc.com") and + // the script on abc.com should match with a rule. + {"def.com", "1"}, + }; + + int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + for (const auto& test_case : test_cases) { + GURL url = get_url_for_host(test_case.frame_hostname); + SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); + + ui_test_utils::NavigateToURL(browser(), url); + EXPECT_EQ(test_case.expected_badge_text, + action->GetDisplayBadgeText(first_tab_id)); + } +} + // Test fixture to verify that host permissions for the request url and the // request initiator are properly checked when redirecting requests. Loads an // example.com url with four sub-frames named frame_[1..4] from hosts @@ -2595,7 +3070,8 @@ class DeclarativeNetRequestHostPermissionsBrowserTest rule.condition->url_filter = std::string("not_a_valid_child_frame.html"); rule.condition->resource_types = std::vector<std::string>({"sub_frame"}); rule.action->type = std::string("redirect"); - rule.action->redirect_url = + rule.action->redirect.emplace(); + rule.action->redirect->url = embedded_test_server()->GetURL("foo.com", "/child_frame.html").spec(); ASSERT_NO_FATAL_FAILURE( diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc index eb626a6c874..7d3391696c1 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc @@ -191,7 +191,8 @@ TEST_P(RuleIndexingTest, DuplicateResourceTypes) { TEST_P(RuleIndexingTest, EmptyRedirectRulePriority) { TestRule rule = CreateGenericRule(); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("https://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("https://google.com"); AddRule(rule); LoadAndExpectError( ParseInfo(ParseResult::ERROR_EMPTY_REDIRECT_RULE_PRIORITY, *rule.id) @@ -208,7 +209,7 @@ TEST_P(RuleIndexingTest, EmptyRedirectRuleUrl) { rule.priority = kMinValidPriority; AddRule(rule); - LoadAndExpectError(ParseInfo(ParseResult::ERROR_EMPTY_REDIRECT_URL, *rule.id) + LoadAndExpectError(ParseInfo(ParseResult::ERROR_INVALID_REDIRECT, *rule.id) .GetErrorDescription()); } @@ -223,7 +224,8 @@ TEST_P(RuleIndexingTest, InvalidRuleID) { TEST_P(RuleIndexingTest, InvalidRedirectRulePriority) { TestRule rule = CreateGenericRule(); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("https://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("https://google.com"); rule.priority = kMinValidPriority - 1; AddRule(rule); LoadAndExpectError( @@ -271,7 +273,8 @@ TEST_P(RuleIndexingTest, EmptyURLFilter) { TEST_P(RuleIndexingTest, InvalidRedirectURL) { TestRule rule = CreateGenericRule(); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("google"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("google"); rule.priority = kMinValidPriority; AddRule(rule); LoadAndExpectError( diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc index d2648003e57..808d1b52973 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc @@ -307,7 +307,8 @@ TEST_P(RulesetManagerTest, Redirect) { rule.condition->url_filter = std::string("example.com"); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://google.com"); std::unique_ptr<CompositeMatcher> matcher; ASSERT_NO_FATAL_FAILURE( CreateMatcherForRules({rule}, "test_extension", &matcher, @@ -373,7 +374,8 @@ TEST_P(RulesetManagerTest, ExtensionScheme) { rule.condition->url_filter = std::string("*"); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://google.com"); ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules( {rule}, "test extension_2", &matcher, std::vector<std::string>({URLPattern::kAllUrlsPattern}), @@ -460,7 +462,7 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { int frame_id; int parent_frame_id; std::string last_committed_main_frame_url; - base::Optional<std::string> pending_main_frame_url; + base::Optional<GURL> pending_main_frame_url; }; struct TestCase { std::string url; @@ -511,7 +513,7 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { "http://example.com", kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - kAllowedPageURL, "http://example.com/xyz"}), + kAllowedPageURL, GURL("http://example.com/xyz")}), true}, // Here we'll determine |kAllowedPageURL| to be the main @@ -520,7 +522,7 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { "http://google.com", kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - kAllowedPageURL, "http://yahoo.com/xyz"}), + kAllowedPageURL, GURL("http://yahoo.com/xyz")}), false}, // In these cases both |pending_main_frame_url| and @@ -530,19 +532,20 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { "http://google.com", kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - "http://google.com/abc", kAllowedPageURL}), + "http://google.com/abc", GURL(kAllowedPageURL)}), false}, {"http://example.com/script.js", content::ResourceType::kScript, base::nullopt, kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - kAllowedPageURL, "http://google.com/abc"}), + kAllowedPageURL, GURL("http://google.com/abc")}), false}, {"http://example.com/script.js", content::ResourceType::kScript, base::nullopt, kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - "http://yahoo.com/abc", "http://yahoo.com/allow123"}), + "http://yahoo.com/abc", + GURL("http://yahoo.com/allow123")}), true}, }; @@ -564,10 +567,8 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { const FrameDataParams& frame_params = *test_case.frame_data_params; params.frame_data = ExtensionApiFrameIdMap::FrameData( frame_params.frame_id, frame_params.parent_frame_id, kDummyTabId, - kDummyWindowId, GURL(frame_params.last_committed_main_frame_url)); - if (frame_params.pending_main_frame_url) - params.frame_data->pending_main_frame_url = - GURL(*frame_params.pending_main_frame_url); + kDummyWindowId, GURL(frame_params.last_committed_main_frame_url), + frame_params.pending_main_frame_url); } Action expected_action = test_case.expect_blocked_with_allowed_pages @@ -590,7 +591,8 @@ TEST_P(RulesetManagerTest, HostPermissionForInitiator) { rule.priority = kMinValidPriority; rule.condition->url_filter = std::string("example.com"); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("https://foo.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("https://foo.com"); std::vector<std::string> host_permissions = {"*://yahoo.com/*", "*://example.com/*"}; ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules( diff --git a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc index fe07b62a6cf..9cf163ca4d9 100644 --- a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc @@ -19,7 +19,7 @@ #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_test_util.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/declarative_webrequest/request_stage.h" #include "extensions/browser/api/declarative_webrequest/webrequest_condition.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" 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 5ac5e3a80c3..897c6601bb7 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 @@ -19,7 +19,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/url_matcher/url_matcher_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/declarative/rules_registry_service.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" #include "extensions/browser/api/web_request/permission_helper.h" @@ -223,7 +223,7 @@ class WebRequestRulesRegistryTest : public testing::Test { } protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; // Two extensions with host permissions for all URLs and the DWR permission. // Installation times will be so that |extension_| is older than diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc index 13b8da3d41e..9b97e1bbd96 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc @@ -83,7 +83,7 @@ bool DesktopCaptureChooseDesktopMediaFunction::RunAsync() { } if (!ExtensionTabUtil::GetTabById(*(params->target_tab->id), GetProfile(), - true, NULL, NULL, &web_contents, NULL)) { + true, &web_contents)) { error_ = kDesktopCaptureApiInvalidTabIdError; return false; } diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h index 595a331a6a2..798348f9e7a 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h @@ -67,7 +67,7 @@ class DesktopCaptureChooseDesktopMediaFunctionBase }; class DesktopCaptureCancelChooseDesktopMediaFunctionBase - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DesktopCaptureCancelChooseDesktopMediaFunctionBase(); 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 a923c4d2d71..6cd0dd1f2f8 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 @@ -14,6 +14,7 @@ #include "base/files/file_util.h" #include "base/guid.h" #include "base/lazy_instance.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" @@ -176,8 +177,9 @@ void GetManifestError(const std::string& error, // This will read the manifest and call AddFailure with the read manifest // contents. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFileToString, extension_path.Append(kManifestFilename)), base::BindOnce(std::move(callback), extension_path, error, line)); @@ -1472,9 +1474,10 @@ bool DeveloperPrivateLoadDirectoryFunction::LoadByFileSystemAPI( project_base_path_ = project_path; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce( &DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent, this, project_base_path_)); @@ -1498,7 +1501,7 @@ void DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent( pending_copy_operations_count_ = 1; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI, @@ -1563,7 +1566,7 @@ void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPICb( pending_copy_operations_count_--; if (!pending_copy_operations_count_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::SendResponse, this, success_)); @@ -1583,9 +1586,10 @@ void DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback( return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::CopyFile, this, src_path, target_path)); } @@ -1605,7 +1609,7 @@ void DeveloperPrivateLoadDirectoryFunction::CopyFile( pending_copy_operations_count_--; if (!pending_copy_operations_count_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::Load, this)); } @@ -1710,8 +1714,9 @@ DeveloperPrivateRequestFileSourceFunction::Run() { if (properties.path_suffix == kManifestFile && !properties.manifest_key) return RespondNow(Error(kManifestKeyIsRequiredError)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&ReadFileToString, extension->path().Append(path_suffix)), base::Bind(&DeveloperPrivateRequestFileSourceFunction::Finish, this)); @@ -1817,7 +1822,7 @@ DeveloperPrivateOpenDevToolsFunction::Run() { // ... but some pages (popups and apps) don't have tabs, and some (background // pages) don't have an associated browser. For these, the inspector opens in // a new window, and our work is done. - if (!browser || !browser->is_type_tabbed()) + if (!browser || !browser->is_type_normal()) return RespondNow(NoArguments()); TabStripModel* tab_strip = browser->tab_strip_model(); @@ -1886,11 +1891,10 @@ DeveloperPrivateRepairExtensionFunction::Run() { if (!web_contents) return RespondNow(Error(kCouldNotFindWebContentsError)); - scoped_refptr<WebstoreReinstaller> reinstaller(new WebstoreReinstaller( + auto reinstaller = base::MakeRefCounted<WebstoreReinstaller>( web_contents, params->extension_id, base::BindOnce( - &DeveloperPrivateRepairExtensionFunction::OnReinstallComplete, - this))); + &DeveloperPrivateRepairExtensionFunction::OnReinstallComplete, this)); reinstaller->BeginReinstall(); return RespondLater(); 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 4113d204780..639cf9e4777 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 @@ -294,7 +294,7 @@ void BrowserContextKeyedAPIFactory< namespace api { -class DeveloperPrivateAPIFunction : public UIThreadExtensionFunction { +class DeveloperPrivateAPIFunction : public ExtensionFunction { protected: ~DeveloperPrivateAPIFunction() override; @@ -488,7 +488,7 @@ class DeveloperPrivateShowPermissionsDialogFunction DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateShowPermissionsDialogFunction); }; -class DeveloperPrivateChooseEntryFunction : public UIThreadExtensionFunction, +class DeveloperPrivateChooseEntryFunction : public ExtensionFunction, public EntryPickerClient { protected: ~DeveloperPrivateChooseEntryFunction() override; @@ -498,7 +498,6 @@ class DeveloperPrivateChooseEntryFunction : public UIThreadExtensionFunction, int file_type_index); }; - class DeveloperPrivateLoadUnpackedFunction : public DeveloperPrivateChooseEntryFunction { public: @@ -611,8 +610,7 @@ class DeveloperPrivatePackDirectoryFunction std::string key_path_str_; }; -class DeveloperPrivateIsProfileManagedFunction - : public UIThreadExtensionFunction { +class DeveloperPrivateIsProfileManagedFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("developerPrivate.isProfileManaged", DEVELOPERPRIVATE_ISPROFILEMANAGED) 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 b3d60b9ec88..7dc5b23f894 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 @@ -31,7 +31,6 @@ #include "chrome/test/base/testing_profile.h" #include "components/crx_file/id_util.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" -#include "components/services/unzip/unzip_service.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/browser/notification_service.h" #include "content/public/test/web_contents_tester.h" @@ -127,7 +126,7 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall { // A wrapper around extension_function_test_utils::RunFunction that runs with // the associated browser, no flags, and can take stack-allocated arguments. - bool RunFunction(const scoped_refptr<UIThreadExtensionFunction>& function, + bool RunFunction(const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args); // Loads an unpacked extension that is backed by a real directory, allowing @@ -185,7 +184,7 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall { }; bool DeveloperPrivateApiUnitTest::RunFunction( - const scoped_refptr<UIThreadExtensionFunction>& function, + const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args) { return extension_function_test_utils::RunFunction( function.get(), args.CreateDeepCopy(), browser(), api_test_utils::NONE); @@ -235,7 +234,7 @@ void DeveloperPrivateApiUnitTest::TestExtensionPrefSetting( const base::Callback<bool()>& has_pref, const std::string& key, const std::string& extension_id) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateUpdateExtensionConfigurationFunction()); EXPECT_FALSE(has_pref.Run()) << key; @@ -280,7 +279,7 @@ testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction( const base::ListValue& args, api::developer_private::PackStatus expected_status, int expected_flags) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivatePackDirectoryFunction()); if (!RunFunction(function, args)) return testing::AssertionFailure() << "Could not run function."; @@ -309,7 +308,7 @@ testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction( void DeveloperPrivateApiUnitTest::UpdateProfileConfigurationDevMode( bool dev_mode) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateUpdateProfileConfigurationFunction()); std::unique_ptr<base::ListValue> args = ListBuilder() @@ -320,7 +319,7 @@ void DeveloperPrivateApiUnitTest::UpdateProfileConfigurationDevMode( void DeveloperPrivateApiUnitTest::GetProfileConfiguration( std::unique_ptr<api::developer_private::ProfileInfo>* profile_info) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetProfileConfigurationFunction()); base::ListValue args; EXPECT_TRUE(RunFunction(function, args)) << function->GetError(); @@ -338,7 +337,7 @@ void DeveloperPrivateApiUnitTest::RunUpdateHostAccess( base::StringPiece new_access) { SCOPED_TRACE(new_access); ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - scoped_refptr<UIThreadExtensionFunction> function = base::MakeRefCounted< + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted< api::DeveloperPrivateUpdateExtensionConfigurationFunction>(); std::string args = base::StringPrintf(R"([{"extensionId": "%s", "hostAccess": "%s"}])", @@ -360,7 +359,7 @@ void DeveloperPrivateApiUnitTest::SetUp() { browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); @@ -406,14 +405,14 @@ TEST_F(DeveloperPrivateApiUnitTest, TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateReload) { const Extension* extension = LoadUnpackedExtension(); std::string extension_id = extension->id(); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateReloadFunction()); base::ListValue reload_args; reload_args.AppendString(extension_id); TestExtensionRegistryObserver registry_observer(registry()); EXPECT_TRUE(RunFunction(function, reload_args)); - const Extension* unloaded_extension = + scoped_refptr<const Extension> unloaded_extension = registry_observer.WaitForExtensionUnloaded(); EXPECT_EQ(extension, unloaded_extension); const Extension* reloaded_extension = @@ -487,7 +486,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateChoosePath) { base::ListValue choose_args; choose_args.AppendString("FOLDER"); choose_args.AppendString("LOAD"); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateChoosePathFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); EXPECT_TRUE(RunFunction(function, choose_args)) << function->GetError(); @@ -528,7 +527,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpacked) { // Try loading a good extension (it should succeed, and the extension should // be added). - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); ExtensionIdSet current_ids = registry()->enabled_extensions().GetIDs(); @@ -578,7 +577,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) { base::FilePath path = dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -605,7 +604,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) { base::FilePath path = dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -637,7 +636,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) { base::FilePath path = dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -670,7 +669,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { { // Trying to load the extension should result in a load error with the // retry id populated. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -690,7 +689,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { // same retry id. This is somewhat an implementation detail, but is // important to ensure we don't allocate crazy numbers of ids if the user // just retries continuously. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -719,7 +718,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { base::FilePath second_path = second_dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&second_path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -750,7 +749,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { { // Try reloading the extension by supplying the retry id. It should succeed. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); TestExtensionRegistryObserver observer(registry()); @@ -767,7 +766,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { { // Try supplying an invalid retry id. It should fail with an error. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = api_test_utils::RunFunctionAndReturnError( @@ -996,7 +995,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateRequestFileSource) { properties.message = kErrorMessage; properties.manifest_key.reset(new std::string("name")); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateRequestFileSourceFunction()); base::ListValue file_source_args; file_source_args.Append(properties.ToValue()); @@ -1022,7 +1021,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateGetExtensionsInfo) { // ExtensionInfoGenerator's unittest), but rather just to make sure we can // serialize/deserialize the result - which implicity tests that everything // has a sane value. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetExtensionsInfoFunction()); EXPECT_TRUE(RunFunction(function, base::ListValue())) << function->GetError(); const base::ListValue* results = function->GetResultList(); @@ -1081,7 +1080,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDeleteExtensionErrors) { .Set("type", type_string) .Build()) .Build(); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new api::DeveloperPrivateDeleteExtensionErrorsFunction(); EXPECT_TRUE(RunFunction(function, *args)) << function->GetError(); // Two errors should remain. @@ -1124,7 +1123,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RepairNotBrokenExtension) { // Attempt to repair the good extension, expect failure. std::unique_ptr<base::ListValue> args = ListBuilder().Append(extension->id()).Build(); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new api::DeveloperPrivateRepairExtensionFunction(); EXPECT_FALSE(RunFunction(function, *args)); EXPECT_EQ("Cannot repair a healthy extension.", function->GetError()); @@ -1155,7 +1154,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RepairPolicyExtension) { // Attempt to repair the good extension, expect failure. std::unique_ptr<base::ListValue> args = ListBuilder().Append(extension_id).Build(); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new api::DeveloperPrivateRepairExtensionFunction(); EXPECT_FALSE(RunFunction(function, *args)); EXPECT_EQ("Cannot repair a healthy extension.", function->GetError()); @@ -1220,7 +1219,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedFailsWithoutDevMode) { PrefService* prefs = profile()->GetPrefs(); prefs->SetBoolean(prefs::kExtensionsUIDeveloperMode, false); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = extension_function_test_utils::RunFunctionAndReturnError( @@ -1253,7 +1252,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedFailsWithBlacklistingPolicy) { EXPECT_FALSE(info->can_load_unpacked); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = extension_function_test_utils::RunFunctionAndReturnError( @@ -1296,7 +1295,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileNoDraggedPath) { std::unique_ptr<content::WebContents> web_contents( content::WebContentsTester::CreateTestWebContents(profile(), nullptr)); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1322,7 +1321,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileCrx) { DeveloperPrivateAPI::Get(profile())->SetDraggedPath(web_contents.get(), crx_path); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1345,7 +1344,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileUserScript) { DeveloperPrivateAPI::Get(profile())->SetDraggedPath(web_contents.get(), script_path); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1369,7 +1368,7 @@ TEST_F(DeveloperPrivateApiUnitTest, GrantHostPermission) { bool should_succeed, const char* expected_error) { SCOPED_TRACE(host); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateAddHostPermissionFunction>(); std::string args = base::StringPrintf(R"(["%s", "%s"])", @@ -1426,7 +1425,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RemoveHostPermission) { bool should_succeed, const char* expected_error) { SCOPED_TRACE(host); - scoped_refptr<UIThreadExtensionFunction> function = base::MakeRefCounted< + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted< api::DeveloperPrivateRemoveHostPermissionFunction>(); std::string args = base::StringPrintf(R"(["%s", "%s"])", extension->id().c_str(), host.data()); @@ -1580,7 +1579,7 @@ TEST_F(DeveloperPrivateApiUnitTest, *extension_prefs->GetRuntimeGrantedPermissions(extension->id())); { - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateAddHostPermissionFunction>(); std::string args = base::StringPrintf( R"(["%s", "%s"])", extension->id().c_str(), "*://chromium.org/*"); @@ -1611,7 +1610,7 @@ TEST_F(DeveloperPrivateApiUnitTest, *extension_prefs->GetRuntimeGrantedPermissions(extension->id())); { - scoped_refptr<UIThreadExtensionFunction> function = base::MakeRefCounted< + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted< api::DeveloperPrivateRemoveHostPermissionFunction>(); std::string args = base::StringPrintf( R"(["%s", "%s"])", extension->id().c_str(), "*://chromium.org/*"); @@ -1731,7 +1730,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileZip) { DeveloperPrivateAPI::Get(profile())->SetDraggedPath(web_contents.get(), zip_path); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1766,7 +1765,7 @@ TEST_F(DeveloperPrivateApiSupervisedUserUnitTest, ASSERT_TRUE(profile()->IsSupervised()); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = extension_function_test_utils::RunFunctionAndReturnError( diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc index 570844d39d4..f4cb2836829 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc @@ -43,7 +43,7 @@ IN_PROC_BROWSER_TEST_F(DeveloperPrivateApiTest, InspectAppWindowView) { const Extension* app = LoadAndLaunchApp(dir); // Get the info about the app, including the inspectable views. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetExtensionInfoFunction()); std::unique_ptr<base::Value> result( extension_function_test_utils::RunFunctionAndReturnSingleResult( @@ -97,7 +97,7 @@ IN_PROC_BROWSER_TEST_F(DeveloperPrivateApiTest, InspectEmbeddedOptionsPage) { WaitForExtensionNotIdle(extension->id()); // Get the info about the extension, including the inspectable views. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetExtensionInfoFunction()); std::unique_ptr<base::Value> result( extension_function_test_utils::RunFunctionAndReturnSingleResult( 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 f886ffd58e4..afb404e5637 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc @@ -37,13 +37,13 @@ EntryPicker::EntryPicker(EntryPickerClient* client, : client_(client) { if (g_skip_picker_for_test) { if (g_path_to_be_picked_for_test) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EntryPicker::FileSelected, base::Unretained(this), *g_path_to_be_picked_for_test, 1, static_cast<void*>(nullptr))); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EntryPicker::FileSelectionCanceled, base::Unretained(this), static_cast<void*>(nullptr))); 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 d51463b16ef..095b9e97d3f 100644 --- a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc @@ -17,6 +17,7 @@ #include "extensions/browser/api/usb/usb_device_manager.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/extension.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/hid/fake_hid_manager.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "services/device/public/mojom/hid.mojom.h" @@ -53,10 +54,10 @@ class DevicePermissionsManagerTest : public testing::Test { "}")); // Set fake device manager for extensions::UsbDeviceManager. - device::mojom::UsbDeviceManagerPtr usb_manager_ptr; - fake_usb_manager_.AddBinding(mojo::MakeRequest(&usb_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager; + fake_usb_manager_.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver()); UsbDeviceManager::Get(env_->profile()) - ->SetDeviceManagerForTesting(std::move(usb_manager_ptr)); + ->SetDeviceManagerForTesting(std::move(usb_manager)); base::RunLoop().RunUntilIdle(); device0_ = fake_usb_manager_.CreateAndAddDevice(0, 0, "Test Manufacturer", diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc index 689928221a8..7ba05fc5f7a 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc @@ -929,13 +929,14 @@ const char ExtensionDownloadsEventRouterData::kKey[] = bool OnDeterminingFilenameWillDispatchCallback( bool* any_determiners, ExtensionDownloadsEventRouterData* data, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { *any_determiners = true; base::Time installed = - ExtensionPrefs::Get(context)->GetInstallTime(extension->id()); + ExtensionPrefs::Get(browser_context)->GetInstallTime(extension->id()); data->AddPendingDeterminer(extension->id(), installed); return true; } diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h index 105cbe800e6..1f39ba01ffd 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h @@ -107,7 +107,7 @@ class DownloadsDownloadFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsDownloadFunction); }; -class DownloadsSearchFunction : public UIThreadExtensionFunction { +class DownloadsSearchFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.search", DOWNLOADS_SEARCH) DownloadsSearchFunction(); @@ -120,7 +120,7 @@ class DownloadsSearchFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsSearchFunction); }; -class DownloadsPauseFunction : public UIThreadExtensionFunction { +class DownloadsPauseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.pause", DOWNLOADS_PAUSE) DownloadsPauseFunction(); @@ -133,7 +133,7 @@ class DownloadsPauseFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsPauseFunction); }; -class DownloadsResumeFunction : public UIThreadExtensionFunction { +class DownloadsResumeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.resume", DOWNLOADS_RESUME) DownloadsResumeFunction(); @@ -146,7 +146,7 @@ class DownloadsResumeFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsResumeFunction); }; -class DownloadsCancelFunction : public UIThreadExtensionFunction { +class DownloadsCancelFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.cancel", DOWNLOADS_CANCEL) DownloadsCancelFunction(); @@ -159,7 +159,7 @@ class DownloadsCancelFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsCancelFunction); }; -class DownloadsEraseFunction : public UIThreadExtensionFunction { +class DownloadsEraseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.erase", DOWNLOADS_ERASE) DownloadsEraseFunction(); @@ -211,7 +211,7 @@ class DownloadsAcceptDangerFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsAcceptDangerFunction); }; -class DownloadsShowFunction : public UIThreadExtensionFunction { +class DownloadsShowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.show", DOWNLOADS_SHOW) DownloadsShowFunction(); @@ -224,7 +224,7 @@ class DownloadsShowFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsShowFunction); }; -class DownloadsShowDefaultFolderFunction : public UIThreadExtensionFunction { +class DownloadsShowDefaultFolderFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION( "downloads.showDefaultFolder", DOWNLOADS_SHOWDEFAULTFOLDER) @@ -238,7 +238,7 @@ class DownloadsShowDefaultFolderFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsShowDefaultFolderFunction); }; -class DownloadsOpenFunction : public UIThreadExtensionFunction { +class DownloadsOpenFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.open", DOWNLOADS_OPEN) DownloadsOpenFunction(); @@ -261,7 +261,7 @@ class DownloadsOpenFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsOpenFunction); }; -class DownloadsSetShelfEnabledFunction : public UIThreadExtensionFunction { +class DownloadsSetShelfEnabledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.setShelfEnabled", DOWNLOADS_SETSHELFENABLED) 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 039b3d9d3d8..0e2a4d31138 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc @@ -111,7 +111,7 @@ void OnOpenPromptCreated(download::DownloadItem* item, DownloadOpenPrompt* prompt) { EXPECT_FALSE(item->GetOpened()); // Posts a task to accept the DownloadOpenPrompt. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DownloadOpenPrompt::AcceptConfirmationDialogForTesting, base::Unretained(prompt))); @@ -599,9 +599,8 @@ class DownloadExtensionTest : public ExtensionApiTest { GetCurrentManager(), download_count); } - bool RunFunction(UIThreadExtensionFunction* function, - const std::string& args) { - scoped_refptr<UIThreadExtensionFunction> delete_function(function); + bool RunFunction(ExtensionFunction* function, const std::string& args) { + scoped_refptr<ExtensionFunction> delete_function(function); SetUpExtensionFunction(function); bool result = extension_function_test_utils::RunFunction( function, args, current_browser(), GetFlags()); @@ -622,7 +621,7 @@ class DownloadExtensionTest : public ExtensionApiTest { // on-record profile to match real-life behavior. base::Value* RunFunctionAndReturnResult( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, const std::string& args) { SetUpExtensionFunction(function.get()); return extension_function_test_utils::RunFunctionAndReturnSingleResult( @@ -630,17 +629,16 @@ class DownloadExtensionTest : public ExtensionApiTest { } std::string RunFunctionAndReturnError( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, const std::string& args) { SetUpExtensionFunction(function.get()); return extension_function_test_utils::RunFunctionAndReturnError( function.get(), args, current_browser(), GetFlags()); } - bool RunFunctionAndReturnString( - scoped_refptr<UIThreadExtensionFunction> function, - const std::string& args, - std::string* result_string) { + bool RunFunctionAndReturnString(scoped_refptr<ExtensionFunction> function, + const std::string& args, + std::string* result_string) { SetUpExtensionFunction(function.get()); std::unique_ptr<base::Value> result( RunFunctionAndReturnResult(function, args)); @@ -661,7 +659,7 @@ class DownloadExtensionTest : public ExtensionApiTest { const Extension* extension() { return extension_; } private: - void SetUpExtensionFunction(UIThreadExtensionFunction* function) { + void SetUpExtensionFunction(ExtensionFunction* function) { if (extension_) { const GURL url = current_browser_ == incognito_browser_ && !IncognitoInfo::IsSplitMode(extension_) @@ -708,10 +706,9 @@ class MockIconExtractorImpl : public DownloadFileIconExtractor { if (expected_path_ == path && expected_icon_size_ == icon_size) { callback_ = callback; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&MockIconExtractorImpl::RunCallback, - base::Unretained(this))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&MockIconExtractorImpl::RunCallback, + base::Unretained(this))); return true; } else { return false; @@ -793,7 +790,7 @@ class HTML5FileWriter { // Invoke the fileapi to copy it into the sandboxed filesystem. bool result = false; base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&CreateFileForTestingOnIOThread, base::Unretained(context), path, temp_file, @@ -810,7 +807,7 @@ class HTML5FileWriter { base::File::Error error) { DCHECK_CURRENTLY_ON(BrowserThread::IO); *result = error == base::File::FILE_OK; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, quit_closure); + base::PostTask(FROM_HERE, {BrowserThread::UI}, quit_closure); } static void CreateFileForTestingOnIOThread( @@ -1044,7 +1041,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_EQ(id, element); } -scoped_refptr<UIThreadExtensionFunction> MockedGetFileIconFunction( +scoped_refptr<ExtensionFunction> MockedGetFileIconFunction( const base::FilePath& expected_path, IconLoader::IconSize icon_size, const std::string& response) { @@ -2324,14 +2321,14 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, " \"paused\": false," " \"url\": \"%s\"}]", download_url.c_str()))); - ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, - base::StringPrintf( - "[{\"id\": %d," - " \"filename\": {" - " \"previous\": \"\"," - " \"current\": \"%s\"}}]", - result_id, - GetFilename("file.txt").c_str()))); + // File will be renamed to file.html due to its mime type. + ASSERT_TRUE( + WaitFor(downloads::OnChanged::kEventName, + base::StringPrintf("[{\"id\": %d," + " \"filename\": {" + " \"previous\": \"\"," + " \"current\": \"%s\"}}]", + result_id, GetFilename("file.html").c_str()))); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, base::StringPrintf( "[{\"id\": %d," @@ -3003,6 +3000,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_FALSE(determine_result.get()); // No return value. } +// Tests that overriding a safe file extension to a dangerous extension will not +// trigger the dangerous prompt and will not change the extension. IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, DownloadExtensionTest_OnDeterminingFilename_DangerousOverride) { @@ -3042,7 +3041,7 @@ IN_PROC_BROWSER_TEST_F( ASSERT_TRUE(item->GetTargetFilePath().empty()); ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); - // Respond to the onDeterminingFilename. + // Respond to the onDeterminingFilename with a dangerous extension. std::string error; ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename( current_browser()->profile(), false, GetExtensionId(), result_id, @@ -3051,12 +3050,68 @@ IN_PROC_BROWSER_TEST_F( EXPECT_EQ("", error); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, - base::StringPrintf( - "[{\"id\": %d," - " \"danger\": {" - " \"previous\":\"safe\"," - " \"current\":\"file\"}}]", - result_id))); + base::StringPrintf("[{\"id\": %d," + " \"state\": {" + " \"previous\": \"in_progress\"," + " \"current\": \"complete\"}}]", + result_id))); + EXPECT_EQ(downloads_directory().AppendASCII("overridden.txt"), + item->GetTargetFilePath()); +} + +// Tests that overriding a dangerous file extension to a safe extension will +// trigger the dangerous prompt and will not change the extension. +IN_PROC_BROWSER_TEST_F( + DownloadExtensionTest, + DownloadExtensionTest_OnDeterminingFilename_SafeOverride) { + GoOnTheRecord(); + LoadExtension("downloads_split"); + AddFilenameDeterminer(); + + std::string download_url = "data:application/x-shockwave-flash,"; + // Start downloading a file. + std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( + new DownloadsDownloadFunction(), + base::StringPrintf("[{\"url\": \"%s\"}]", download_url.c_str()))); + ASSERT_TRUE(result.get()); + int result_id = -1; + ASSERT_TRUE(result->GetAsInteger(&result_id)); + DownloadItem* item = GetCurrentManager()->GetDownload(result_id); + ASSERT_TRUE(item); + ScopedCancellingItem canceller(item); + ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); + + ASSERT_TRUE(WaitFor( + downloads::OnCreated::kEventName, + base::StringPrintf("[{\"danger\": \"safe\"," + " \"incognito\": false," + " \"id\": %d," + " \"mime\": \"application/x-shockwave-flash\"," + " \"paused\": false," + " \"url\": \"%s\"}]", + result_id, download_url.c_str()))); + ASSERT_TRUE(WaitFor(downloads::OnDeterminingFilename::kEventName, + base::StringPrintf("[{\"id\": %d," + " \"filename\":\"download.swf\"}]", + result_id))); + ASSERT_TRUE(item->GetTargetFilePath().empty()); + ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); + + // Respond to the onDeterminingFilename with a safe extension. + std::string error; + ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename( + current_browser()->profile(), false, GetExtensionId(), result_id, + base::FilePath(FILE_PATH_LITERAL("overridden.txt")), + downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY, &error)); + EXPECT_EQ("", error); + + // Dangerous download prompt will be shown. + ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, + base::StringPrintf("[{\"id\": %d, " + " \"danger\": {" + " \"previous\": \"safe\"," + " \"current\": \"file\"}}]", + result_id))); item->ValidateDangerousDownload(); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, @@ -3066,6 +3121,7 @@ IN_PROC_BROWSER_TEST_F( " \"previous\":\"file\"," " \"current\":\"accepted\"}}]", result_id))); + ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, base::StringPrintf( "[{\"id\": %d," @@ -4159,7 +4215,7 @@ IN_PROC_BROWSER_TEST_F( // This test is very flaky on Win XP and Aura. http://crbug.com/248438 // Also flaky on Linux. http://crbug.com/700382 -// Also flaky on Mac ASAN with PlzNavigate. +// Also flaky on Mac ASAN. // Test download interruption while extensions determining filename. Should not // re-dispatch onDeterminingFilename. IN_PROC_BROWSER_TEST_F( @@ -4337,7 +4393,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, LoadExtension("downloads_split"); std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsDownloadFunction(), - "[{\"url\": \"data:,\", \"filename\": \"dangerous.swf\"}]")); + "[{\"url\": \"data:application/x-shockwave-flash,\", \"filename\": " + "\"dangerous.swf\"}]")); ASSERT_TRUE(result.get()); int result_id = -1; ASSERT_TRUE(result->GetAsInteger(&result_id)); diff --git a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h index 639906d4bbe..490c94eed33 100644 --- a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h +++ b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h @@ -10,8 +10,7 @@ namespace extensions { -class DownloadsInternalDetermineFilenameFunction - : public UIThreadExtensionFunction { +class DownloadsInternalDetermineFilenameFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloadsInternal.determineFilename", DOWNLOADSINTERNAL_DETERMINEFILENAME) diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc index 35679e37510..87b1c700975 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc @@ -19,8 +19,13 @@ namespace extensions { namespace { -// Checks for the current browser context if the user is affiliated. +// Checks for the current browser context if the user is affiliated or belongs +// to the sign-in profile. bool IsPermittedToGetDeviceAttributes(content::BrowserContext* context) { + if (chromeos::ProfileHelper::IsSigninProfile( + Profile::FromBrowserContext(context))) { + return true; + } const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile( Profile::FromBrowserContext(context)); diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h index 0f879217328..5c6a57cf641 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h @@ -10,7 +10,7 @@ namespace extensions { class EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction(); @@ -25,7 +25,7 @@ class EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction }; class EnterpriseDeviceAttributesGetDeviceSerialNumberFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDeviceSerialNumberFunction(); @@ -41,7 +41,7 @@ class EnterpriseDeviceAttributesGetDeviceSerialNumberFunction }; class EnterpriseDeviceAttributesGetDeviceAssetIdFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDeviceAssetIdFunction(); @@ -56,7 +56,7 @@ class EnterpriseDeviceAttributesGetDeviceAssetIdFunction }; class EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction(); diff --git a/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h b/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h index 1600ac52056..0d691184809 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h @@ -12,7 +12,7 @@ namespace extensions { class EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction(); diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc index 1d0643aaf8b..2932c7037d5 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc @@ -281,12 +281,12 @@ EnterprisePlatformKeysChallengeMachineKeyFunction::Run() { this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeMachineKey::Run, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, StringFromVector(params->challenge), - params->register_key ? *params->register_key : false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = + base::Bind(&EPKPChallengeMachineKey::Run, base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), callback, + StringFromVector(params->challenge), + params->register_key ? *params->register_key : false); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } @@ -322,11 +322,11 @@ EnterprisePlatformKeysChallengeUserKeyFunction::Run() { &EnterprisePlatformKeysChallengeUserKeyFunction::OnChallengedKey, this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeUserKey::Run, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, StringFromVector(params->challenge), params->register_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = + base::Bind(&EPKPChallengeUserKey::Run, base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), callback, + StringFromVector(params->challenge), params->register_key); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h index 6900eb2f582..9ec384a2ef3 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h @@ -21,7 +21,7 @@ typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; namespace extensions { class EnterprisePlatformKeysInternalGenerateKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysInternalGenerateKeyFunction() override; ResponseAction Run() override; @@ -35,8 +35,7 @@ class EnterprisePlatformKeysInternalGenerateKeyFunction ENTERPRISE_PLATFORMKEYSINTERNAL_GENERATEKEY) }; -class EnterprisePlatformKeysGetCertificatesFunction - : public UIThreadExtensionFunction { +class EnterprisePlatformKeysGetCertificatesFunction : public ExtensionFunction { private: ~EnterprisePlatformKeysGetCertificatesFunction() override; ResponseAction Run() override; @@ -51,7 +50,7 @@ class EnterprisePlatformKeysGetCertificatesFunction }; class EnterprisePlatformKeysImportCertificateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysImportCertificateFunction() override; ResponseAction Run() override; @@ -65,7 +64,7 @@ class EnterprisePlatformKeysImportCertificateFunction }; class EnterprisePlatformKeysRemoveCertificateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysRemoveCertificateFunction() override; ResponseAction Run() override; @@ -79,7 +78,7 @@ class EnterprisePlatformKeysRemoveCertificateFunction }; class EnterprisePlatformKeysInternalGetTokensFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysInternalGetTokensFunction() override; ResponseAction Run() override; @@ -94,7 +93,7 @@ class EnterprisePlatformKeysInternalGetTokensFunction }; class EnterprisePlatformKeysChallengeMachineKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysChallengeMachineKeyFunction(); explicit EnterprisePlatformKeysChallengeMachineKeyFunction( @@ -117,7 +116,7 @@ class EnterprisePlatformKeysChallengeMachineKeyFunction }; class EnterprisePlatformKeysChallengeUserKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysChallengeUserKeyFunction(); explicit EnterprisePlatformKeysChallengeUserKeyFunction( 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 5fa0fffc205..bffca7db092 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 @@ -85,6 +85,7 @@ void SignChallengeCallbackTrue( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, true, "response")); @@ -98,6 +99,7 @@ void SignChallengeCallbackFalse( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false, "")); @@ -108,6 +110,7 @@ void GetCertificateCallbackTrue( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -121,6 +124,7 @@ void GetCertificateCallbackFalse( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -141,9 +145,9 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { ON_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillByDefault(Invoke(RegisterKeyCallbackTrue)); ON_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillByDefault(Invoke(SignChallengeCallbackTrue)); - ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillByDefault(Invoke(GetCertificateCallbackTrue)); stub_install_attributes_.SetCloudManaged("google.com", "device_id"); @@ -181,7 +185,7 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { // Like extension_function_test_utils::RunFunctionAndReturnError but with an // explicit ListValue. - std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, + std::string RunFunctionAndReturnError(ExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { utils::RunFunction(function, std::move(args), browser, @@ -193,7 +197,7 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { // Like extension_function_test_utils::RunFunctionAndReturnSingleResult but // with an explicit ListValue. base::Value* RunFunctionAndReturnSingleResult( - UIThreadExtensionFunction* function, + ExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { scoped_refptr<ExtensionFunction> function_owner(function); @@ -297,7 +301,7 @@ TEST_F(EPKChallengeMachineKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKChallengeMachineKeyTest, GetCertificateFailed) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackFalse)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -306,7 +310,7 @@ TEST_F(EPKChallengeMachineKeyTest, GetCertificateFailed) { TEST_F(EPKChallengeMachineKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -327,7 +331,8 @@ TEST_F(EPKChallengeMachineKeyTest, KeyExists) { std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) + .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); @@ -354,14 +359,14 @@ TEST_F(EPKChallengeMachineKeyTest, Success) { EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. - EXPECT_CALL( - mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), - "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) + EXPECT_CALL(mock_async_method_caller_, + TpmAttestationSignEnterpriseChallenge( + chromeos::attestation::KEY_DEVICE, + cryptohome::Identification(), "attest-ent-machine", + "google.com", "device_id", _, "challenge", _, _)) .Times(1); std::unique_ptr<base::Value> value( @@ -373,24 +378,26 @@ TEST_F(EPKChallengeMachineKeyTest, Success) { } TEST_F(EPKChallengeMachineKeyTest, KeyRegisteredSuccess) { + std::string key_name_for_spkac = "attest-ent-machine-" + extension_->id(); // GetCertificate must be called exactly once. EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); // TpmAttestationRegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(chromeos::attestation::KEY_DEVICE, _ /* Unused by the API. */, - "attest-ent-machine", _)) + key_name_for_spkac, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL( mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), - "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) + "attest-ent-machine", "google.com", "device_id", _, "challenge", + key_name_for_spkac, _)) .Times(1); std::unique_ptr<base::Value> value(RunFunctionAndReturnSingleResult( @@ -488,7 +495,7 @@ TEST_F(EPKChallengeUserKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKChallengeUserKeyTest, GetCertificateFailed) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackFalse)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -497,7 +504,7 @@ TEST_F(EPKChallengeUserKeyTest, GetCertificateFailed) { TEST_F(EPKChallengeUserKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -518,7 +525,8 @@ TEST_F(EPKChallengeUserKeyTest, KeyExists) { AccountId::FromUserEmail(kUserEmail)), "attest-ent-user", std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) + .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); @@ -545,7 +553,7 @@ TEST_F(EPKChallengeUserKeyTest, Success) { EXPECT_CALL( mock_attestation_flow_, GetCertificate(chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); const cryptohome::Identification cryptohome_id( AccountId::FromUserEmail(kUserEmail)); @@ -554,7 +562,7 @@ TEST_F(EPKChallengeUserKeyTest, Success) { mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_USER, cryptohome_id, "attest-ent-user", - kUserEmail, "device_id", _, "challenge", _)) + kUserEmail, "device_id", _, "challenge", _, _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index 92e1bc05574..c68aaa5367b 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc @@ -43,6 +43,12 @@ #include "google_apis/gaia/gaia_auth_util.h" #include "third_party/cros_system_api/dbus/service_constants.h" +namespace { +// Prefix for naming machine keys used for SignedPublicKeyAndChallenge when +// challenging the EMK with register=true. +const char kEnterpriseMachineKeyForSpkacPrefix[] = "attest-ent-machine-"; +} // namespace + namespace extensions { namespace api_epkp = api::enterprise_platform_keys_private; @@ -68,12 +74,14 @@ EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext( const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback) : key_type(key_type), account_id(account_id), key_name(key_name), certificate_profile(certificate_profile), require_user_consent(require_user_consent), + key_name_for_spkac(key_name_for_spkac), callback(callback) {} EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext( @@ -199,13 +207,11 @@ void EPKPChallengeKeyBase::PrepareKey( const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback) { - const PrepareKeyContext context = PrepareKeyContext(key_type, - account_id, - key_name, - certificate_profile, - require_user_consent, - callback); + const PrepareKeyContext context = + PrepareKeyContext(key_type, account_id, key_name, certificate_profile, + require_user_consent, key_name_for_spkac, callback); cryptohome_client_->TpmAttestationIsPrepared( base::BindOnce(&EPKPChallengeKeyBase::IsAttestationPreparedCallback, base::Unretained(this), context)); @@ -224,6 +230,18 @@ void EPKPChallengeKeyBase::IsAttestationPreparedCallback( base::Unretained(this), context)); return; } + + if (!context.key_name_for_spkac.empty()) { + // Generate a new key and have it signed by PCA. + attestation_flow_->GetCertificate( + context.certificate_profile, context.account_id, + std::string(), // Not used. + true, // Force a new key to be generated. + context.key_name_for_spkac, + base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback, + base::Unretained(this), context.callback)); + return; + } // Attestation is available, see if the key we need already exists. cryptohome_client_->TpmAttestationDoesKeyExist( context.key_type, @@ -295,6 +313,7 @@ void EPKPChallengeKeyBase::AskForUserConsentCallback( context.certificate_profile, context.account_id, std::string(), // Not used. true, // Force a new key to be generated. + std::string(), // Leave key name empty to generate a default name. base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback, base::Unretained(this), context.callback)); } @@ -337,11 +356,10 @@ EPKPChallengeMachineKey::EPKPChallengeMachineKey( EPKPChallengeMachineKey::~EPKPChallengeMachineKey() { } -void EPKPChallengeMachineKey::Run( - scoped_refptr<UIThreadExtensionFunction> caller, - const ChallengeKeyCallback& callback, - const std::string& challenge, - bool register_key) { +void EPKPChallengeMachineKey::Run(scoped_refptr<ExtensionFunction> caller, + const ChallengeKeyCallback& callback, + const std::string& challenge, + bool register_key) { callback_ = callback; profile_ = ChromeExtensionFunctionDetails(caller.get()).GetProfile(); extension_ = scoped_refptr<const Extension>(caller->extension()); @@ -372,7 +390,7 @@ void EPKPChallengeMachineKey::Run( } void EPKPChallengeMachineKey::DecodeAndRun( - scoped_refptr<UIThreadExtensionFunction> caller, + scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key) { @@ -393,18 +411,31 @@ void EPKPChallengeMachineKey::GetDeviceAttestationEnabledCallback( return; } + // The EMK cannot be registered as that would relinquish it and the DMServer + // relies on it to remain stable. If register_key = true, generate a new + // machine key to side-load into the system-wide token. This key will be + // used for SignedPublicKeyAndChallenge but the challenge response will still + // be singed using the stable EMK. + std::string key_name_for_spkac; + if (register_key) { + key_name_for_spkac = kEnterpriseMachineKeyForSpkacPrefix + extension_->id(); + } PrepareKey(chromeos::attestation::KEY_DEVICE, EmptyAccountId(), // Not used. chromeos::attestation::kEnterpriseMachineKey, chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, false, // user consent is not required. + key_name_for_spkac, base::Bind(&EPKPChallengeMachineKey::PrepareKeyCallback, - base::Unretained(this), challenge, register_key)); + base::Unretained(this), challenge, register_key, + key_name_for_spkac)); } -void EPKPChallengeMachineKey::PrepareKeyCallback(const std::string& challenge, - bool register_key, - PrepareKeyResult result) { +void EPKPChallengeMachineKey::PrepareKeyCallback( + const std::string& challenge, + bool register_key, + const std::string& key_name_for_spkac, + PrepareKeyResult result) { if (result != PREPARE_KEY_OK) { callback_.Run(false, base::StringPrintf(kGetCertificateFailedError, result)); @@ -419,7 +450,7 @@ void EPKPChallengeMachineKey::PrepareKeyCallback(const std::string& challenge, GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, - challenge, + challenge, key_name_for_spkac, base::Bind(&EPKPChallengeMachineKey::SignChallengeCallback, base::Unretained(this), register_key)); } @@ -433,10 +464,12 @@ void EPKPChallengeMachineKey::SignChallengeCallback( return; } if (register_key) { + std::string key_name_for_spkac = + kEnterpriseMachineKeyForSpkacPrefix + extension_->id(); async_caller_->TpmAttestationRegisterKey( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), // Not used. - chromeos::attestation::kEnterpriseMachineKey, + key_name_for_spkac, base::Bind(&EPKPChallengeMachineKey::RegisterKeyCallback, base::Unretained(this), response)); } else { @@ -489,7 +522,7 @@ void EPKPChallengeUserKey::RegisterProfilePrefs( registry->RegisterListPref(prefs::kAttestationExtensionWhitelist); } -void EPKPChallengeUserKey::Run(scoped_refptr<UIThreadExtensionFunction> caller, +void EPKPChallengeUserKey::Run(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& challenge, bool register_key) { @@ -535,11 +568,10 @@ void EPKPChallengeUserKey::Run(scoped_refptr<UIThreadExtensionFunction> caller, } } -void EPKPChallengeUserKey::DecodeAndRun( - scoped_refptr<UIThreadExtensionFunction> caller, - const ChallengeKeyCallback& callback, - const std::string& encoded_challenge, - bool register_key) { +void EPKPChallengeUserKey::DecodeAndRun(scoped_refptr<ExtensionFunction> caller, + const ChallengeKeyCallback& callback, + const std::string& encoded_challenge, + bool register_key) { std::string challenge; if (!base::Base64Decode(encoded_challenge, &challenge)) { callback.Run(false, kChallengeBadBase64Error); @@ -561,7 +593,7 @@ void EPKPChallengeUserKey::GetDeviceAttestationEnabledCallback( PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(), chromeos::attestation::kEnterpriseUserKey, chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, - require_user_consent, + require_user_consent, std::string() /* key_name_for_spkac */, base::Bind(&EPKPChallengeUserKey::PrepareKeyCallback, base::Unretained(this), challenge, register_key)); } @@ -582,7 +614,7 @@ void EPKPChallengeUserKey::PrepareKeyCallback(const std::string& challenge, chromeos::attestation::kEnterpriseUserKey, GetUserEmail(), GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, - challenge, + challenge, std::string() /* key_name_for_spkac */, base::Bind(&EPKPChallengeUserKey::SignChallengeCallback, base::Unretained(this), register_key)); } @@ -645,11 +677,11 @@ EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::Run() { this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeMachineKey::DecodeAndRun, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, params->challenge, false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = base::Bind(&EPKPChallengeMachineKey::DecodeAndRun, + base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), + callback, params->challenge, false); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } @@ -688,11 +720,11 @@ EnterprisePlatformKeysPrivateChallengeUserKeyFunction::Run() { this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeUserKey::DecodeAndRun, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, params->challenge, params->register_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = + base::Bind(&EPKPChallengeUserKey::DecodeAndRun, base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), callback, + params->challenge, params->register_key); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h index 66cb475b59f..e8e9fa09d43 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h @@ -100,16 +100,18 @@ class EPKPChallengeKeyBase { // Returns the enterprise virtual device ID. std::string GetDeviceId() const; - // Prepares the key for signing. It will first check if the key exists. If - // the key does not exist, it will call AttestationFlow::GetCertificate() to - // get a new one. If require_user_consent is true, it will explicitly ask for - // user consent before calling GetCertificate(). + // Prepares the key for signing. It will first check if a new key should be + // generated, i.e. |key_name_for_spkac| is not empty or the key doesn't + // exist and, if necessary, call AttestationFlow::GetCertificate() to get a + // new one. If require_user_consent is true, it will explicitly ask for user + // consent before calling GetCertificate(). void PrepareKey( chromeos::attestation::AttestationKeyType key_type, const AccountId& account_id, const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback); chromeos::CryptohomeClient* cryptohome_client_; @@ -130,6 +132,7 @@ class EPKPChallengeKeyBase { chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback); PrepareKeyContext(const PrepareKeyContext& other); ~PrepareKeyContext(); @@ -139,6 +142,7 @@ class EPKPChallengeKeyBase { const std::string key_name; chromeos::attestation::AttestationCertificateProfile certificate_profile; bool require_user_consent; + std::string key_name_for_spkac; const base::Callback<void(PrepareKeyResult)> callback; }; @@ -176,13 +180,13 @@ class EPKPChallengeMachineKey : public EPKPChallengeKeyBase { // Asynchronously run the flow to challenge a machine key in the |caller| // context. - void Run(scoped_refptr<UIThreadExtensionFunction> caller, + void Run(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key); // Like |Run| but expects a Base64 |encoded_challenge|. - void DecodeAndRun(scoped_refptr<UIThreadExtensionFunction> caller, + void DecodeAndRun(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key); @@ -195,6 +199,7 @@ class EPKPChallengeMachineKey : public EPKPChallengeKeyBase { bool enabled); void PrepareKeyCallback(const std::string& challenge, bool register_key, + const std::string& key_name_for_spkac, PrepareKeyResult result); void SignChallengeCallback(bool register_key, bool success, @@ -223,13 +228,13 @@ class EPKPChallengeUserKey : public EPKPChallengeKeyBase { // Asynchronously run the flow to challenge a user key in the |caller| // context. - void Run(scoped_refptr<UIThreadExtensionFunction> caller, + void Run(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& challenge, bool register_key); // Like |Run| but expects a Base64 |encoded_challenge|. - void DecodeAndRun(scoped_refptr<UIThreadExtensionFunction> caller, + void DecodeAndRun(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key); @@ -255,7 +260,7 @@ class EPKPChallengeUserKey : public EPKPChallengeKeyBase { }; class EnterprisePlatformKeysPrivateChallengeMachineKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysPrivateChallengeMachineKeyFunction(); explicit EnterprisePlatformKeysPrivateChallengeMachineKeyFunction( @@ -279,7 +284,7 @@ class EnterprisePlatformKeysPrivateChallengeMachineKeyFunction }; class EnterprisePlatformKeysPrivateChallengeUserKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysPrivateChallengeUserKeyFunction(); explicit EnterprisePlatformKeysPrivateChallengeUserKeyFunction( 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 3dc0c29bc66..6230610cb4a 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 @@ -88,6 +88,7 @@ void SignChallengeCallbackTrue( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, true, "response")); @@ -101,6 +102,7 @@ void SignChallengeCallbackFalse( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false, "")); @@ -111,6 +113,7 @@ void GetCertificateCallbackTrue( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -124,6 +127,7 @@ void GetCertificateCallbackUnspecifiedFailure( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -138,6 +142,7 @@ void GetCertificateCallbackBadRequestFailure( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -164,9 +169,9 @@ class EPKPChallengeKeyTestBase : public BrowserWithTestWindowTest { ON_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillByDefault(Invoke(RegisterKeyCallbackTrue)); ON_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillByDefault(Invoke(SignChallengeCallbackTrue)); - ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillByDefault(Invoke(GetCertificateCallbackTrue)); stub_install_attributes_.SetCloudManaged("google.com", "device_id"); @@ -301,7 +306,7 @@ TEST_F(EPKPChallengeMachineKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKPChallengeMachineKeyTest, GetCertificateFailed) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackUnspecifiedFailure)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -310,7 +315,7 @@ TEST_F(EPKPChallengeMachineKeyTest, GetCertificateFailed) { TEST_F(EPKPChallengeMachineKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -321,7 +326,7 @@ TEST_F(EPKPChallengeMachineKeyTest, KeyExists) { cryptohome_client_.SetTpmAttestationDeviceCertificate("attest-ent-machine", std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), @@ -366,14 +371,14 @@ TEST_P(EPKPChallengeMachineKeyAllProfilesTest, Success) { EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. - EXPECT_CALL( - mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), - "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) + EXPECT_CALL(mock_async_method_caller_, + TpmAttestationSignEnterpriseChallenge( + chromeos::attestation::KEY_DEVICE, + cryptohome::Identification(), "attest-ent-machine", + "google.com", "device_id", _, "challenge", _, _)) .Times(1); std::unique_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( @@ -464,7 +469,7 @@ TEST_F(EPKPChallengeUserKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithUnspecifiedFailure) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackUnspecifiedFailure)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -472,7 +477,7 @@ TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithUnspecifiedFailure) { } TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithBadRequestFailure) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackBadRequestFailure)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -481,7 +486,7 @@ TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithBadRequestFailure) { TEST_F(EPKPChallengeUserKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -502,7 +507,7 @@ TEST_F(EPKPChallengeUserKeyTest, KeyExists) { AccountId::FromUserEmail(kUserEmail)), "attest-ent-user", std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), @@ -527,10 +532,10 @@ TEST_F(EPKPChallengeUserKeyTest, PersonalDevice) { TEST_F(EPKPChallengeUserKeyTest, Success) { // GetCertificate must be called exactly once. - EXPECT_CALL(mock_attestation_flow_, - GetCertificate( - chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, - _, _, _, _)) + EXPECT_CALL( + mock_attestation_flow_, + GetCertificate(chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, + _, _, _, _, _)) .Times(1); const AccountId account_id = AccountId::FromUserEmail(kUserEmail); // SignEnterpriseChallenge must be called exactly once. @@ -539,7 +544,7 @@ TEST_F(EPKPChallengeUserKeyTest, Success) { chromeos::attestation::KEY_USER, cryptohome::Identification(account_id), "attest-ent-user", cryptohome::Identification(account_id).id(), "device_id", _, - "challenge", _)) + "challenge", _, _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc index 85b835c492a..5284f7e8586 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc @@ -113,8 +113,10 @@ void AppendAdditionalBrowserInformation(em::ChromeDesktopReportRequest* request, // the future. request->mutable_browser_report() ->mutable_chrome_user_profile_reports(0) - ->set_policy_data( - policy::GetAllPolicyValuesAsJSON(profile, true, false, false)); + ->set_policy_data(policy::DictionaryPolicyConversions() + .WithBrowserContext(profile) + .EnablePrettyPrint(false) + .ToJSON()); int64_t timestamp = GetMachineLevelUserCloudPolicyFetchTimestamp(); if (timestamp > 0) { diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc index 9be986f7cfa..cfa80831e07 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc @@ -15,7 +15,7 @@ #include "components/policy/core/common/cloud/cloud_policy_util.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace em = enterprise_management; @@ -24,7 +24,7 @@ namespace extensions { class ChromeDesktopReportRequestGeneratorTest : public ::testing::Test { protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h index c6ebd8fa877..ec772107862 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h @@ -27,7 +27,7 @@ extern const char kDeviceIdNotFound[]; } // namespace enterprise_reporting class EnterpriseReportingPrivateUploadChromeDesktopReportFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION( "enterprise.reportingPrivate.uploadChromeDesktopReport", @@ -65,8 +65,7 @@ class EnterpriseReportingPrivateUploadChromeDesktopReportFunction EnterpriseReportingPrivateUploadChromeDesktopReportFunction); }; -class EnterpriseReportingPrivateGetDeviceIdFunction - : public UIThreadExtensionFunction { +class EnterpriseReportingPrivateGetDeviceIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("enterprise.reportingPrivate.getDeviceId", ENTERPRISEREPORTINGPRIVATE_GETDEVICEID) diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc index bca47a1b158..344b3238590 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc @@ -34,7 +34,7 @@ class EnterpriseReportingPrivateUploadChromeDesktopReportTest public: EnterpriseReportingPrivateUploadChromeDesktopReportTest() {} - UIThreadExtensionFunction* CreateChromeDesktopReportingFunction( + ExtensionFunction* CreateChromeDesktopReportingFunction( const std::string& dm_token) { EnterpriseReportingPrivateUploadChromeDesktopReportFunction* function = EnterpriseReportingPrivateUploadChromeDesktopReportFunction:: @@ -85,7 +85,7 @@ TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, } TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadFailed) { - UIThreadExtensionFunction* function = + ExtensionFunction* function = CreateChromeDesktopReportingFunction(kFakeDMToken); EXPECT_CALL(*client_, SetupRegistration(kFakeDMToken, kFakeClientId, _)) .Times(1); @@ -99,7 +99,7 @@ TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadFailed) { TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadSucceeded) { - UIThreadExtensionFunction* function = + ExtensionFunction* function = CreateChromeDesktopReportingFunction(kFakeDMToken); EXPECT_CALL(*client_, SetupRegistration(kFakeDMToken, kFakeClientId, _)) .Times(1); 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 5af703b6ed9..e8a2d2d10f7 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 @@ -15,6 +15,8 @@ #include "build/build_config.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" +#include "chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h" +#include "chrome/browser/extensions/api/extension_action/test_icon_image_observer.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_action_icon_factory.h" #include "chrome/browser/extensions/extension_action_manager.h" @@ -209,7 +211,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, Basic) { // Test that we received the changes. ExtensionAction* action = GetBrowserAction(*extension); ASSERT_EQ("Modified", action->GetTitle(ExtensionAction::kDefaultTabId)); - ASSERT_EQ("badge", action->GetBadgeText(ExtensionAction::kDefaultTabId)); + ASSERT_EQ("badge", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); ASSERT_EQ(SkColorSetARGB(255, 255, 255, 255), action->GetBadgeBackgroundColor(ExtensionAction::kDefaultTabId)); @@ -701,7 +704,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, DISABLED_CloseBackgroundPage) { extensions::ProcessManager::Get(browser()->profile()); ASSERT_TRUE(manager->GetBackgroundHostForExtension(extension->id())); ExtensionAction* action = GetBrowserAction(*extension); - ASSERT_EQ("", action->GetBadgeText(ExtensionAction::kDefaultTabId)); + ASSERT_EQ("", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); content::WindowedNotificationObserver host_destroyed_observer( extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, @@ -715,7 +719,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, DISABLED_CloseBackgroundPage) { // and the badge text has been set. host_destroyed_observer.Wait(); ASSERT_FALSE(manager->GetBackgroundHostForExtension(extension->id())); - ASSERT_EQ("X", action->GetBadgeText(ExtensionAction::kDefaultTabId)); + ASSERT_EQ("X", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); } IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BadgeBackgroundColor) { @@ -878,14 +883,28 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionPopupWithIframe) { IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionWithRectangularIcon) { ExtensionTestMessageListener ready_listener("ready", true); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("browser_action").AppendASCII("rect_icon"))); + + const Extension* extension = LoadExtension( + test_data_dir_.AppendASCII("browser_action").AppendASCII("rect_icon")); + ASSERT_TRUE(extension); EXPECT_TRUE(ready_listener.WaitUntilSatisfied()); + + // Wait for the default icon to load before accessing the underlying + // gfx::Image. + TestIconImageObserver::WaitForExtensionActionIcon(extension, profile()); + gfx::Image first_icon = GetBrowserActionsBar()->GetIcon(0); + ASSERT_FALSE(first_icon.IsEmpty()); + + TestExtensionActionAPIObserver observer(profile(), extension->id()); ResultCatcher catcher; ready_listener.Reply(std::string()); EXPECT_TRUE(catcher.GetNextResult()); + // Wait for extension action to be updated. + observer.Wait(); + gfx::Image next_icon = GetBrowserActionsBar()->GetIcon(0); + ASSERT_FALSE(next_icon.IsEmpty()); EXPECT_FALSE(gfx::test::AreImagesEqual(first_icon, next_icon)); } diff --git a/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc b/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc index 2c4893d0dc1..5027f9ac3e0 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc @@ -94,7 +94,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, BrowserActionDefaultPersistence) { // If the extension hasn't already set the badge text, then we should wait for // it to do so. - if (extension_action->GetBadgeText(0) != "Hello") { + if (extension_action->GetExplicitlySetBadgeText(0) != "Hello") { ExtensionTestMessageListener listener("Badge Text Set", false /* won't send custom reply */); ASSERT_TRUE(listener.WaitUntilSatisfied()); 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 7ad5b39767f..8fd11ee84dd 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 @@ -10,7 +10,6 @@ #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -29,7 +28,6 @@ #include "content/public/browser/notification_types.h" #include "content/public/common/page_zoom.h" #include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_system.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension.h" #include "extensions/common/extension_set.h" @@ -341,9 +339,10 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, return; OpenPopupViaAPI(false); - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); - ASSERT_FALSE(service->GetExtensionById(last_loaded_extension_id(), false) + ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ASSERT_FALSE(registry + ->GetExtensionById(last_loaded_extension_id(), + ExtensionRegistry::ENABLED) ->permissions_data() ->HasAPIPermissionForTab( SessionTabHelper::IdForTab( diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc index ef0c3b6b928..28bdacc39e9 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc @@ -31,6 +31,7 @@ #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h" #include "chrome/common/extensions/api/extension_action/action_info.h" #include "content/public/browser/notification_service.h" +#include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" @@ -48,9 +49,6 @@ namespace extensions { namespace { -// Whether the browser action is visible in the toolbar. -const char kBrowserActionVisible[] = "browser_action_visible"; - // Errors. const char kNoExtensionActionError[] = "This extension has no action specified."; @@ -113,29 +111,6 @@ void ExtensionActionAPI::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } -bool ExtensionActionAPI::GetBrowserActionVisibility( - const std::string& extension_id) { - bool visible = false; - ExtensionPrefs* prefs = GetExtensionPrefs(); - if (!prefs || !prefs->ReadPrefAsBoolean(extension_id, - kBrowserActionVisible, - &visible)) { - return true; - } - return visible; -} - -void ExtensionActionAPI::SetBrowserActionVisibility( - const std::string& extension_id, - bool visible) { - if (GetBrowserActionVisibility(extension_id) == visible) - return; - - GetExtensionPrefs()->UpdateExtensionPref( - extension_id, kBrowserActionVisible, - std::make_unique<base::Value>(visible)); -} - bool ExtensionActionAPI::ShowExtensionActionPopup( const Extension* extension, Browser* browser, @@ -191,8 +166,16 @@ void ExtensionActionAPI::DispatchExtensionActionClicked( if (event_name) { std::unique_ptr<base::ListValue> args(new base::ListValue()); + // The action APIs (browserAction, pageAction, action) are only available + // to blessed extension contexts. As such, we deterministically know that + // the right context type here is blessed. + constexpr Feature::Context context_type = + Feature::BLESSED_EXTENSION_CONTEXT; + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, context_type, + web_contents); args->Append(ExtensionTabUtil::CreateTabObject( - web_contents, ExtensionTabUtil::kScrubTab, extension) + web_contents, scrub_tab_behavior, extension) ->ToValue()); DispatchEventToExtension(web_contents->GetBrowserContext(), @@ -283,8 +266,7 @@ ExtensionFunction::ResponseAction ExtensionActionFunction::Run() { // Find the WebContents that contains this tab id if one is required. if (tab_id_ != ExtensionAction::kDefaultTabId) { ExtensionTabUtil::GetTabById(tab_id_, browser_context(), - include_incognito_information(), nullptr, - nullptr, &contents_, nullptr); + include_incognito_information(), &contents_); if (!contents_) return RespondNow(Error(kNoTabError, base::NumberToString(tab_id_))); } else { @@ -494,8 +476,19 @@ ExtensionActionGetPopupFunction::RunExtensionAction() { ExtensionFunction::ResponseAction ExtensionActionGetBadgeTextFunction::RunExtensionAction() { - return RespondNow(OneArgument( - std::make_unique<base::Value>(extension_action_->GetBadgeText(tab_id_)))); + // Return a placeholder value if the extension has called + // setActionCountAsBadgeText(true) and the badge count shown for this tab is + // the number of actions matched. + std::string badge_text = + extension_action_->UseDNRActionCountAsBadgeText(tab_id_) + ? declarative_net_request::kActionCountPlaceholderBadgeText + : extension_action_->GetExplicitlySetBadgeText(tab_id_); + + // TODO(crbug.com/990224): Document this behavior once + // chrome.declarativeNetRequest.setActionCountAsBadgeText is promoted to beta + // from trunk. + return RespondNow( + OneArgument(std::make_unique<base::Value>(std::move(badge_text)))); } ExtensionFunction::ResponseAction diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h index f4d9ea2b9dd..6ae7ffbe33a 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h @@ -67,10 +67,6 @@ class ExtensionActionAPI : public BrowserContextKeyedAPI { void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); - bool GetBrowserActionVisibility(const std::string& extension_id); - void SetBrowserActionVisibility(const std::string& extension_id, - bool visible); - // Opens the popup for the given |extension| in the given |browser|'s window. // If |grant_active_tab_permissions| is true, this grants the extension // activeTab (so this should only be done if this is through a direct user @@ -130,7 +126,7 @@ class ExtensionActionAPI : public BrowserContextKeyedAPI { // tabIds while browserAction's are optional, they have different internal // browser notification requirements, and not all functions are defined for all // APIs). -class ExtensionActionFunction : public UIThreadExtensionFunction { +class ExtensionActionFunction : public ExtensionFunction { public: static bool ParseCSSColorString(const std::string& color_string, SkColor* result); @@ -446,7 +442,7 @@ class BrowserActionDisableFunction : public ExtensionActionHideFunction { ~BrowserActionDisableFunction() override {} }; -class BrowserActionOpenPopupFunction : public UIThreadExtensionFunction, +class BrowserActionOpenPopupFunction : public ExtensionFunction, public content::NotificationObserver { public: DECLARE_EXTENSION_FUNCTION("browserAction.openPopup", diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc index c90241d63ad..760b0b8d622 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc @@ -13,6 +13,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h" +#include "chrome/browser/extensions/api/extension_action/test_icon_image_observer.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -266,39 +267,6 @@ class MultiActionAPITest return action_manager->GetExtensionAction(extension); } - // Waits for the given |icon| to finish it's first load. - // TODO(devlin): It's unfortunate we need this here. Ideally, either this - // would be less convoluted, or would even be taken care of by the extension - // loading methods. - void WaitForIconLoaded(IconImage* icon) { - class IconImageWaiter : public IconImage::Observer { - public: - IconImageWaiter() : observer_(this) {} - ~IconImageWaiter() override = default; - - void Wait(IconImage* icon) { - if (!icon->did_complete_initial_load()) { - observer_.Add(icon); - run_loop_.Run(); - } - } - - private: - // IconImage::Observer: - void OnExtensionIconImageChanged(IconImage* icon) override { - DCHECK(icon->did_complete_initial_load()); - run_loop_.Quit(); - } - - base::RunLoop run_loop_; - ScopedObserver<IconImage, IconImage::Observer> observer_; - - DISALLOW_COPY_AND_ASSIGN(IconImageWaiter); - }; - - IconImageWaiter().Wait(icon); - } - private: std::unique_ptr<ScopedCurrentChannel> current_channel_; @@ -641,7 +609,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) { ASSERT_TRUE(action->default_icon()); // Wait for the default icon to finish loading; otherwise it may be empty // when we check it. - WaitForIconLoaded(action->default_icon_image()); + TestIconImageObserver::WaitForIcon(action->default_icon_image()); int tab_id = GetActiveTabId(); EXPECT_TRUE(ActionHasDefaultState(*action, tab_id)); @@ -889,7 +857,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, GettersAndSetters) { ValuePair custom_badge_text2{"custom badge2", "'custom badge2'"}; auto get_badge_text = [](ExtensionAction* action, int tab_id) { - return action->GetBadgeText(tab_id); + return action->GetExplicitlySetBadgeText(tab_id); }; ActionTestHelper badge_text_helper(kApiName, "setBadgeText", "getBadgeText", diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc deleted file mode 100644 index 9eb67c61f19..00000000000 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc +++ /dev/null @@ -1,66 +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 <string> - -#include "base/logging.h" -#include "base/macros.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" -#include "chrome/browser/extensions/api/extension_action/extension_action_api.h" -#include "chrome/browser/extensions/extension_prefs_unittest.h" -#include "chrome/test/base/testing_profile.h" -#include "extensions/common/extension.h" - -namespace extensions { - -// Tests force hiding browser actions. -class ExtensionPrefsHidingBrowserActions : public ExtensionPrefsTest { - public: - ExtensionPrefsHidingBrowserActions() {} - ~ExtensionPrefsHidingBrowserActions() override {} - - void Initialize() override { - profile_.reset(new TestingProfile()); - - // Install 5 extensions. - for (int i = 0; i < 5; i++) { - std::string name = "test" + base::NumberToString(i); - extensions_.push_back(prefs_.AddExtension(name)); - } - - ExtensionActionAPI* action_api = ExtensionActionAPI::Get(profile_.get()); - action_api->set_prefs_for_testing(prefs()); - for (const scoped_refptr<const Extension>& extension : extensions_) - EXPECT_TRUE(action_api->GetBrowserActionVisibility(extension->id())); - - action_api->SetBrowserActionVisibility(extensions_[0]->id(), false); - action_api->SetBrowserActionVisibility(extensions_[1]->id(), true); - } - - void Verify() override { - ExtensionActionAPI* action_api = ExtensionActionAPI::Get(profile_.get()); - action_api->set_prefs_for_testing(prefs()); - // Make sure the one we hid is hidden. - EXPECT_FALSE(action_api->GetBrowserActionVisibility(extensions_[0]->id())); - - // Make sure the other id's are not hidden. - ExtensionList::const_iterator iter = extensions_.begin() + 1; - for (; iter != extensions_.end(); ++iter) { - SCOPED_TRACE(base::StringPrintf("Loop %d ", - static_cast<int>(iter - extensions_.begin()))); - EXPECT_TRUE(action_api->GetBrowserActionVisibility((*iter)->id())); - } - } - - private: - std::unique_ptr<TestingProfile> profile_; - ExtensionList extensions_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionPrefsHidingBrowserActions); -}; - -TEST_F(ExtensionPrefsHidingBrowserActions, ForceHide) {} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc index 2083a406aa9..054f6a38116 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc @@ -13,6 +13,14 @@ TestExtensionActionAPIObserver::TestExtensionActionAPIObserver( scoped_observer_.Add(ExtensionActionAPI::Get(context)); } +TestExtensionActionAPIObserver::TestExtensionActionAPIObserver( + content::BrowserContext* context, + const ExtensionId& extension_id, + const std::set<content::WebContents*>& contents_to_observe) + : TestExtensionActionAPIObserver(context, extension_id) { + contents_to_observe_ = contents_to_observe; +} + TestExtensionActionAPIObserver::~TestExtensionActionAPIObserver() = default; void TestExtensionActionAPIObserver::Wait() { @@ -25,7 +33,10 @@ void TestExtensionActionAPIObserver::OnExtensionActionUpdated( content::BrowserContext* browser_context) { if (extension_action->extension_id() == extension_id_) { last_web_contents_ = web_contents; - run_loop_.QuitWhenIdle(); + contents_to_observe_.erase(web_contents); + + if (contents_to_observe_.empty()) + run_loop_.QuitWhenIdle(); } } diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h index 11b35f5b279..981da2f2b36 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h +++ b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h @@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_EXTENSION_ACTION_API_OBSERVER_H_ #define CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_EXTENSION_ACTION_API_OBSERVER_H_ +#include <set> + #include "base/macros.h" #include "base/run_loop.h" #include "base/scoped_observer.h" @@ -23,9 +25,15 @@ class TestExtensionActionAPIObserver : public ExtensionActionAPI::Observer { public: TestExtensionActionAPIObserver(content::BrowserContext* context, const ExtensionId& extension_id); + TestExtensionActionAPIObserver( + content::BrowserContext* context, + const ExtensionId& extension_id, + const std::set<content::WebContents*>& contents_to_observe); ~TestExtensionActionAPIObserver() override; - // Waits till the extension action is updated. + // Waits until the extension action is updated and the update is seen for all + // web contents in |contents_to_observe_| if |contents_to_observe_| is not + // empty. void Wait(); // Returns the web contents for which the extension action was updated. Must @@ -47,6 +55,9 @@ class TestExtensionActionAPIObserver : public ExtensionActionAPI::Observer { ScopedObserver<ExtensionActionAPI, ExtensionActionAPI::Observer> scoped_observer_; + // An optional set of web contents to observe for extension action updates. + std::set<content::WebContents*> contents_to_observe_; + DISALLOW_COPY_AND_ASSIGN(TestExtensionActionAPIObserver); }; diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.cc b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.cc new file mode 100644 index 00000000000..5544ebace55 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.cc @@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/api/extension_action/test_icon_image_observer.h" + +#include "chrome/browser/extensions/extension_action.h" +#include "chrome/browser/extensions/extension_action_manager.h" + +namespace extensions { + +TestIconImageObserver::TestIconImageObserver() : observer_(this) {} +TestIconImageObserver::~TestIconImageObserver() = default; + +void TestIconImageObserver::Wait(IconImage* icon) { + if (!icon->did_complete_initial_load()) { + observer_.Add(icon); + run_loop_.Run(); + } +} + +void TestIconImageObserver::OnExtensionIconImageChanged(IconImage* icon) { + DCHECK(icon->did_complete_initial_load()); + run_loop_.Quit(); +} + +void TestIconImageObserver::WaitForIcon(IconImage* icon) { + TestIconImageObserver().Wait(icon); +} +void TestIconImageObserver::WaitForExtensionActionIcon( + const Extension* extension, + content::BrowserContext* context) { + DCHECK(extension); + auto* action_manager = ExtensionActionManager::Get(context); + ExtensionAction* action = action_manager->GetExtensionAction(*extension); + + DCHECK(action); + DCHECK(action->default_icon_image()); + WaitForIcon(action->default_icon_image()); +} + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h new file mode 100644 index 00000000000..b8881d8a8a6 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h @@ -0,0 +1,41 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_ICON_IMAGE_OBSERVER_H_ +#define CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_ICON_IMAGE_OBSERVER_H_ + +#include "base/macros.h" +#include "base/run_loop.h" +#include "base/scoped_observer.h" +#include "extensions/browser/extension_icon_image.h" + +namespace extensions { + +class Extension; + +// This class helps to observe action icons. As default action icons load +// asynchronously we need to wait for it to finish before using them. +class TestIconImageObserver : public IconImage::Observer { + public: + TestIconImageObserver(); + ~TestIconImageObserver() override; + + void Wait(IconImage* icon); + + static void WaitForIcon(IconImage* icon); + static void WaitForExtensionActionIcon(const Extension* extension, + content::BrowserContext* context); + + private: + // IconImage::Observer: + void OnExtensionIconImageChanged(IconImage* icon) override; + + base::RunLoop run_loop_; + ScopedObserver<IconImage, IconImage::Observer> observer_; + + DISALLOW_COPY_AND_ASSIGN(TestIconImageObserver); +}; +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_ICON_IMAGE_OBSERVER_H_ diff --git a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc index b440c80df8a..c5c066eb388 100644 --- a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc +++ b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc @@ -106,7 +106,7 @@ bool GetVolumeListForExtension( // Callback called when consent is granted or denied. void OnConsentReceived( content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, + scoped_refptr<ExtensionFunction> requester, const FileSystemDelegate::FileSystemCallback& success_callback, const FileSystemDelegate::ErrorCallback& error_callback, const std::string& extension_id, @@ -252,7 +252,7 @@ base::FilePath ChromeFileSystemDelegate::GetDefaultDirectory() { } bool ChromeFileSystemDelegate::ShowSelectFileDialog( - scoped_refptr<UIThreadExtensionFunction> extension_function, + scoped_refptr<ExtensionFunction> extension_function, ui::SelectFileDialog::Type type, const base::FilePath& default_path, const ui::SelectFileDialog::FileTypeInfo* file_types, @@ -282,7 +282,7 @@ bool ChromeFileSystemDelegate::ShowSelectFileDialog( return false; } - // The file picker will hold a reference to the UIThreadExtensionFunction + // The file picker will hold a reference to the ExtensionFunction // instance, preventing its destruction (and subsequent sending of the // function response) until the user has selected a file or cancelled the // picker. At that point, the picker will delete itself, which will also free @@ -330,7 +330,7 @@ ChromeFileSystemDelegate::GetGrantVolumesMode( void ChromeFileSystemDelegate::RequestFileSystem( content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, + scoped_refptr<ExtensionFunction> requester, const Extension& extension, std::string volume_id, bool writable, diff --git a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h index 9dd8784bceb..a1276399fa3 100644 --- a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h +++ b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h @@ -32,7 +32,7 @@ class ChromeFileSystemDelegate : public FileSystemDelegate { // FileSystemDelegate: base::FilePath GetDefaultDirectory() override; bool ShowSelectFileDialog( - scoped_refptr<UIThreadExtensionFunction> extension_function, + scoped_refptr<ExtensionFunction> extension_function, ui::SelectFileDialog::Type type, const base::FilePath& default_path, const ui::SelectFileDialog::FileTypeInfo* file_types, @@ -50,7 +50,7 @@ class ChromeFileSystemDelegate : public FileSystemDelegate { content::RenderFrameHost* render_frame_host, const Extension& extension) override; void RequestFileSystem(content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, + scoped_refptr<ExtensionFunction> requester, const Extension& extension, std::string volume_id, bool writable, 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 2ed1d872059..33c14d9d9f5 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 @@ -19,7 +19,7 @@ #include "components/prefs/testing_pref_service.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/file_system/file_system_delegate.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" @@ -137,7 +137,7 @@ class FileSystemApiConsentProviderTest : public testing::Test { chromeos::FakeChromeUserManager* user_manager_; // Owned by the scope enabler. std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_enabler_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; std::unique_ptr<Volume> download_volume_; }; diff --git a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h index 880218aba60..6b206d44778 100644 --- a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h +++ b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h @@ -101,7 +101,7 @@ class FontSettingsAPI : public BrowserContextKeyedAPI { }; // fontSettings.clearFont API function. -class FontSettingsClearFontFunction : public UIThreadExtensionFunction { +class FontSettingsClearFontFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.clearFont", FONTSETTINGS_CLEARFONT) @@ -115,7 +115,7 @@ class FontSettingsClearFontFunction : public UIThreadExtensionFunction { }; // fontSettings.getFont API function. -class FontSettingsGetFontFunction : public UIThreadExtensionFunction { +class FontSettingsGetFontFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.getFont", FONTSETTINGS_GETFONT) @@ -127,7 +127,7 @@ class FontSettingsGetFontFunction : public UIThreadExtensionFunction { }; // fontSettings.setFont API function. -class FontSettingsSetFontFunction : public UIThreadExtensionFunction { +class FontSettingsSetFontFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.setFont", FONTSETTINGS_SETFONT) @@ -156,7 +156,7 @@ class FontSettingsGetFontListFunction : public ChromeAsyncExtensionFunction { }; // Base class for extension API functions that clear a browser font pref. -class ClearFontPrefExtensionFunction : public UIThreadExtensionFunction { +class ClearFontPrefExtensionFunction : public ExtensionFunction { protected: ~ClearFontPrefExtensionFunction() override {} @@ -169,7 +169,7 @@ class ClearFontPrefExtensionFunction : public UIThreadExtensionFunction { }; // Base class for extension API functions that get a browser font pref. -class GetFontPrefExtensionFunction : public UIThreadExtensionFunction { +class GetFontPrefExtensionFunction : public ExtensionFunction { protected: ~GetFontPrefExtensionFunction() override {} @@ -186,7 +186,7 @@ class GetFontPrefExtensionFunction : public UIThreadExtensionFunction { }; // Base class for extension API functions that set a browser font pref. -class SetFontPrefExtensionFunction : public UIThreadExtensionFunction { +class SetFontPrefExtensionFunction : public ExtensionFunction { protected: ~SetFontPrefExtensionFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_api.h b/chromium/chrome/browser/extensions/api/gcm/gcm_api.h index 40bbd1b1147..8e538f667a5 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_api.h +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_api.h @@ -17,7 +17,7 @@ class Profile; namespace extensions { -class GcmApiFunction : public UIThreadExtensionFunction { +class GcmApiFunction : public ExtensionFunction { public: GcmApiFunction() {} @@ -42,7 +42,7 @@ class GcmRegisterFunction : public GcmApiFunction { protected: ~GcmRegisterFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: @@ -59,7 +59,7 @@ class GcmUnregisterFunction : public GcmApiFunction { protected: ~GcmUnregisterFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: @@ -75,7 +75,7 @@ class GcmSendFunction : public GcmApiFunction { protected: ~GcmSendFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: diff --git a/chromium/chrome/browser/extensions/api/history/history_api.h b/chromium/chrome/browser/extensions/api/history/history_api.h index 9a0433dbf79..5349fca6a52 100644 --- a/chromium/chrome/browser/extensions/api/history/history_api.h +++ b/chromium/chrome/browser/extensions/api/history/history_api.h @@ -93,7 +93,7 @@ template <> void BrowserContextKeyedAPIFactory<HistoryAPI>::DeclareFactoryDependencies(); // Base class for history function APIs. -class HistoryFunction : public UIThreadExtensionFunction { +class HistoryFunction : public ExtensionFunction { protected: ~HistoryFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/i18n/i18n_api.h b/chromium/chrome/browser/extensions/api/i18n/i18n_api.h index 5576a36339f..88ed7094431 100644 --- a/chromium/chrome/browser/extensions/api/i18n/i18n_api.h +++ b/chromium/chrome/browser/extensions/api/i18n/i18n_api.h @@ -9,7 +9,7 @@ namespace extensions { -class I18nGetAcceptLanguagesFunction : public UIThreadExtensionFunction { +class I18nGetAcceptLanguagesFunction : public ExtensionFunction { ~I18nGetAcceptLanguagesFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("i18n.getAcceptLanguages", I18N_GETACCEPTLANGUAGES) diff --git a/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc b/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc index bd781fbb1e6..1ef3f5eba80 100644 --- a/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc +++ b/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc @@ -7,7 +7,7 @@ #include <vector> #include "base/run_loop.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -94,7 +94,7 @@ class IdentityGaiaWebAuthFlowTest : public testing::Test { protected: testing::StrictMock<MockGaiaWebAuthFlowDelegate> delegate_; GoogleServiceAuthError::State ubertoken_error_state_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(IdentityGaiaWebAuthFlowTest, OAuthError) { diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc b/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc index a4d5166c2eb..64262f3b2bf 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc @@ -9,7 +9,7 @@ #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/test/base/testing_profile.h" #include "components/signin/public/base/signin_buildflags.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -17,7 +17,7 @@ namespace extensions { #if BUILDFLAG(ENABLE_DICE_SUPPORT) // Tests that all accounts in extensions is only enabled when Dice is enabled. TEST(IdentityApiTest, DiceAllAccountsExtensions) { - content::TestBrowserThreadBundle test_thread_bundle; + content::BrowserTaskEnvironment task_environment; base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(kExtensionsAllAccountsFeature); @@ -43,7 +43,7 @@ TEST(IdentityApiTest, DiceAllAccountsExtensions) { #endif TEST(IdentityApiTest, AllAccountsExtensionDisabled) { - content::TestBrowserThreadBundle test_thread_bundle; + content::BrowserTaskEnvironment task_environment; #if BUILDFLAG(ENABLE_DICE_SUPPORT) base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(kExtensionsAllAccountsFeature); diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc index 99e6d3972a3..ef79b4e60e5 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc @@ -89,7 +89,7 @@ static const char kExtensionId[] = "ext_id"; // after the call happens. class AsyncFunctionRunner { public: - void RunFunctionAsync(UIThreadExtensionFunction* function, + void RunFunctionAsync(ExtensionFunction* function, const std::string& args, content::BrowserContext* browser_context) { response_delegate_.reset(new api_test_utils::SendResponseHelper(function)); @@ -109,14 +109,14 @@ class AsyncFunctionRunner { function->RunWithValidation()->Execute(); } - std::string WaitForError(UIThreadExtensionFunction* function) { + std::string WaitForError(ExtensionFunction* function) { RunMessageLoopUntilResponse(); CHECK(function->response_type()); EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type()); return function->GetError(); } - base::Value* WaitForSingleResult(UIThreadExtensionFunction* function) { + base::Value* WaitForSingleResult(ExtensionFunction* function) { RunMessageLoopUntilResponse(); EXPECT_TRUE(function->GetError().empty()) << "Unexpected error: " << function->GetError(); @@ -140,18 +140,17 @@ class AsyncFunctionRunner { class AsyncExtensionBrowserTest : public ExtensionBrowserTest { protected: // Provide wrappers of AsynchronousFunctionRunner for convenience. - void RunFunctionAsync(UIThreadExtensionFunction* function, - const std::string& args) { + void RunFunctionAsync(ExtensionFunction* function, const std::string& args) { async_function_runner_ = std::make_unique<AsyncFunctionRunner>(); async_function_runner_->RunFunctionAsync(function, args, browser()->profile()); } - std::string WaitForError(UIThreadExtensionFunction* function) { + std::string WaitForError(ExtensionFunction* function) { return async_function_runner_->WaitForError(function); } - base::Value* WaitForSingleResult(UIThreadExtensionFunction* function) { + base::Value* WaitForSingleResult(ExtensionFunction* function) { return async_function_runner_->WaitForSingleResult(function); } 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 a123670090e..1b8c765ef1d 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 @@ -10,7 +10,7 @@ namespace extensions { -class IdentityGetAccountsFunction : public UIThreadExtensionFunction { +class IdentityGetAccountsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.getAccounts", IDENTITY_GETACCOUNTS) @@ -19,7 +19,7 @@ class IdentityGetAccountsFunction : public UIThreadExtensionFunction { private: ~IdentityGetAccountsFunction() override; - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ExtensionFunction::ResponseAction Run() override; }; 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 2efd2f74eb6..1de99c202c3 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 @@ -145,14 +145,14 @@ bool IdentityGetAuthTokenFunction::RunAsync() { if (gaia_id.empty() || IsPrimaryAccountOnly()) { // Try the primary account. // TODO(https://crbug.com/932400): collapse the asynchronicity - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount, weak_ptr_factory_.GetWeakPtr(), gaia_id)); } else { // Get the AccountInfo for the account that the extension wishes to use. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&IdentityGetAuthTokenFunction::FetchExtensionAccountInfo, weak_ptr_factory_.GetWeakPtr(), gaia_id)); @@ -199,7 +199,8 @@ void IdentityGetAuthTokenFunction::FetchExtensionAccountInfo( const std::string& gaia_id) { OnReceivedExtensionAccountInfo(base::OptionalOrNullptr( IdentityManagerFactory::GetForProfile(GetProfile()) - ->FindAccountInfoForAccountWithRefreshTokenByGaiaId(gaia_id))); + ->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId( + gaia_id))); } void IdentityGetAuthTokenFunction::OnReceivedExtensionAccountInfo( @@ -261,7 +262,7 @@ void IdentityGetAuthTokenFunction::OnAccountsInCookieUpdated( email_for_default_web_account_ = account.email; OnReceivedExtensionAccountInfo(base::OptionalOrNullptr( IdentityManagerFactory::GetForProfile(GetProfile()) - ->FindAccountInfoForAccountWithRefreshTokenByGaiaId( + ->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId( account.gaia_id))); } else { OnReceivedExtensionAccountInfo(nullptr); @@ -800,7 +801,7 @@ void IdentityGetAuthTokenFunction::StartGaiaRequest( void IdentityGetAuthTokenFunction::ShowExtensionLoginPrompt() { base::Optional<AccountInfo> account = IdentityManagerFactory::GetForProfile(GetProfile()) - ->FindAccountInfoForAccountWithRefreshTokenByAccountId( + ->FindExtendedAccountInfoForAccountWithRefreshTokenByAccountId( token_key_.account_id); std::string email_hint = account ? account->email : email_for_default_web_account_; diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h index 0eb440bebac..1b3b46143d4 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h @@ -129,8 +129,8 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction, // instance, or empty if this was not in the parameters. void GetAuthTokenForPrimaryAccount(const std::string& extension_gaia_id); - // Wrapper to FindAccountInfoForAccountWithRefreshTokenByGaiaId() to avoid a - // synchronous call to IdentityManager in RunAsync(). + // Wrapper to FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId() to + // avoid a synchronous call to IdentityManager in RunAsync(). void FetchExtensionAccountInfo(const std::string& gaia_id); // Called when the AccountInfo that this instance should use is available. diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h index f68ecc9b21c..84edc0d3488 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h @@ -10,7 +10,7 @@ namespace extensions { -class IdentityGetProfileUserInfoFunction : public UIThreadExtensionFunction { +class IdentityGetProfileUserInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.getProfileUserInfo", IDENTITY_GETPROFILEUSERINFO) @@ -20,7 +20,7 @@ class IdentityGetProfileUserInfoFunction : public UIThreadExtensionFunction { private: ~IdentityGetProfileUserInfoFunction() override; - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ExtensionFunction::ResponseAction Run() override; }; diff --git a/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h b/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h index 710c2eeff43..e99b46414ab 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h @@ -10,7 +10,7 @@ namespace extensions { -class IdentityRemoveCachedAuthTokenFunction : public UIThreadExtensionFunction { +class IdentityRemoveCachedAuthTokenFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.removeCachedAuthToken", EXPERIMENTAL_IDENTITY_REMOVECACHEDAUTHTOKEN) diff --git a/chromium/chrome/browser/extensions/api/idltest/idltest_api.h b/chromium/chrome/browser/extensions/api/idltest/idltest_api.h index 48b5e9d7d6c..5219e3e07fd 100644 --- a/chromium/chrome/browser/extensions/api/idltest/idltest_api.h +++ b/chromium/chrome/browser/extensions/api/idltest/idltest_api.h @@ -7,7 +7,7 @@ #include "extensions/browser/extension_function.h" -class IdltestSendArrayBufferFunction : public UIThreadExtensionFunction { +class IdltestSendArrayBufferFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.sendArrayBuffer", IDLTEST_SENDARRAYBUFFER) @@ -16,7 +16,7 @@ class IdltestSendArrayBufferFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class IdltestSendArrayBufferViewFunction : public UIThreadExtensionFunction { +class IdltestSendArrayBufferViewFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.sendArrayBufferView", IDLTEST_SENDARRAYBUFFERVIEW) @@ -26,7 +26,7 @@ class IdltestSendArrayBufferViewFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class IdltestGetArrayBufferFunction : public UIThreadExtensionFunction { +class IdltestGetArrayBufferFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.getArrayBuffer", IDLTEST_GETARRAYBUFFER) 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 6b229b022da..8560050c09a 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 @@ -9,7 +9,6 @@ #include "chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "content/public/browser/browser_thread.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -21,12 +20,10 @@ const int kPartitionTableSize = 2 * 4096; DestroyPartitionsOperation::DestroyPartitionsOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& storage_unit_id, const base::FilePath& download_folder) : Operation(manager, - std::move(connector), extension_id, storage_unit_id, download_folder) {} diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h index 3373953c3e6..c1fc6448ceb 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h @@ -19,7 +19,6 @@ class DestroyPartitionsOperation : public Operation { public: DestroyPartitionsOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& storage_unit_id, const base::FilePath& download_folder); 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 1a49548244c..35ca237f4ef 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 @@ -9,7 +9,6 @@ #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -42,8 +41,7 @@ TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) { scoped_refptr<DestroyPartitionsOperation> operation( new DestroyPartitionsOperation( - manager.AsWeakPtr(), - /*connector=*/nullptr, kDummyExtensionId, + manager.AsWeakPtr(), kDummyExtensionId, test_utils_.GetDevicePath().AsUTF8Unsafe(), base::FilePath(FILE_PATH_LITERAL("/var/tmp")))); 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 03aff051004..657ecfd62f8 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 @@ -8,23 +8,26 @@ #include "base/files/file_path.h" #include "base/location.h" #include "base/optional.h" +#include "build/build_config.h" #include "chrome/grit/generated_resources.h" -#include "chrome/services/removable_storage_writer/public/mojom/constants.mojom.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "services/service_manager/public/cpp/connector.h" +#include "content/public/browser/sandbox_type.h" +#include "content/public/browser/service_process_host.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace image_writer { namespace { + ImageWriterUtilityClient::ImageWriterUtilityClientFactory* g_factory_for_testing = nullptr; -void DeleteInterfacePtr(chrome::mojom::RemovableStorageWriterPtr writer_ptr) { - // Just let the parameters go out of scope so they are deleted. +void DeleteRemote(mojo::Remote<chrome::mojom::RemovableStorageWriter> writer) { + // Just let the parameter go out of scope so it's deleted. } + } // namespace class ImageWriterUtilityClient::RemovableStorageWriterClientImpl @@ -32,10 +35,11 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl public: RemovableStorageWriterClientImpl( ImageWriterUtilityClient* owner, - chrome::mojom::RemovableStorageWriterClientPtr* interface_ptr) - : binding_(this, mojo::MakeRequest(interface_ptr)), + mojo::PendingReceiver<chrome::mojom::RemovableStorageWriterClient> + receiver) + : receiver_(this, std::move(receiver)), image_writer_utility_client_(owner) { - binding_.set_connection_error_handler( + receiver_.set_disconnect_handler( base::BindOnce(&ImageWriterUtilityClient::OnConnectionError, image_writer_utility_client_)); } @@ -55,7 +59,8 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl } } - mojo::Binding<chrome::mojom::RemovableStorageWriterClient> binding_; + mojo::Receiver<chrome::mojom::RemovableStorageWriterClient> receiver_; + // |image_writer_utility_client_| owns |this|. ImageWriterUtilityClient* const image_writer_utility_client_; @@ -63,29 +68,23 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl }; ImageWriterUtilityClient::ImageWriterUtilityClient( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector) - : task_runner_(task_runner), connector_(std::move(connector)) {} + const scoped_refptr<base::SequencedTaskRunner>& task_runner) + : task_runner_(task_runner) {} ImageWriterUtilityClient::~ImageWriterUtilityClient() { // We could be running on a different TaskRunner (typically, the UI thread). // Post to be safe. - task_runner_->DeleteSoon(FROM_HERE, std::move(connector_)); - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&DeleteInterfacePtr, - std::move(removable_storage_writer_))); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&DeleteRemote, std::move(removable_storage_writer_))); } // static scoped_refptr<ImageWriterUtilityClient> ImageWriterUtilityClient::Create( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector) { - // connector_ can be null in unit-tests. - DCHECK(!connector || !connector->IsBound()); + const scoped_refptr<base::SequencedTaskRunner>& task_runner) { if (g_factory_for_testing) return g_factory_for_testing->Run(); - return base::WrapRefCounted( - new ImageWriterUtilityClient(task_runner, std::move(connector))); + return base::WrapRefCounted(new ImageWriterUtilityClient(task_runner)); } // static @@ -108,11 +107,12 @@ void ImageWriterUtilityClient::Write(const ProgressCallback& progress_callback, BindServiceIfNeeded(); - chrome::mojom::RemovableStorageWriterClientPtr client; + mojo::PendingRemote<chrome::mojom::RemovableStorageWriterClient> + remote_client; removable_storage_writer_client_ = - std::make_unique<RemovableStorageWriterClientImpl>(this, &client); - - removable_storage_writer_->Write(source, target, std::move(client)); + std::make_unique<RemovableStorageWriterClientImpl>( + this, remote_client.InitWithNewPipeAndPassReceiver()); + removable_storage_writer_->Write(source, target, std::move(remote_client)); } void ImageWriterUtilityClient::Verify(const ProgressCallback& progress_callback, @@ -129,11 +129,12 @@ void ImageWriterUtilityClient::Verify(const ProgressCallback& progress_callback, BindServiceIfNeeded(); - chrome::mojom::RemovableStorageWriterClientPtr client; + mojo::PendingRemote<chrome::mojom::RemovableStorageWriterClient> + remote_client; removable_storage_writer_client_ = - std::make_unique<RemovableStorageWriterClientImpl>(this, &client); - - removable_storage_writer_->Verify(source, target, std::move(client)); + std::make_unique<RemovableStorageWriterClientImpl>( + this, remote_client.InitWithNewPipeAndPassReceiver()); + removable_storage_writer_->Verify(source, target, std::move(remote_client)); } void ImageWriterUtilityClient::Cancel(const CancelCallback& cancel_callback) { @@ -157,9 +158,19 @@ void ImageWriterUtilityClient::BindServiceIfNeeded() { if (removable_storage_writer_) return; - connector_->BindInterface(chrome::mojom::kRemovableStorageWriterServiceName, - mojo::MakeRequest(&removable_storage_writer_)); - removable_storage_writer_.set_connection_error_handler( +#if defined(OS_WIN) + constexpr auto kSandboxType = + service_manager::SANDBOX_TYPE_NO_SANDBOX_AND_ELEVATED_PRIVILEGES; +#else + constexpr auto kSandboxType = service_manager::SANDBOX_TYPE_NO_SANDBOX; +#endif + content::ServiceProcessHost::Launch( + removable_storage_writer_.BindNewPipeAndPassReceiver(), + content::ServiceProcessHost::Options() + .WithDisplayName(IDS_UTILITY_PROCESS_IMAGE_WRITER_NAME) + .WithSandboxType(kSandboxType) + .Pass()); + removable_storage_writer_.set_disconnect_handler( base::BindOnce(&ImageWriterUtilityClient::OnConnectionError, this)); } 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 6ac29f5ab5e..63c45483721 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 @@ -16,10 +16,7 @@ #include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" #include "chrome/services/removable_storage_writer/public/mojom/removable_storage_writer.mojom.h" - -namespace service_manager { -class Connector; -} +#include "mojo/public/cpp/bindings/remote.h" namespace extensions { namespace image_writer { @@ -36,10 +33,8 @@ class ImageWriterUtilityClient using ImageWriterUtilityClientFactory = base::Callback<scoped_refptr<ImageWriterUtilityClient>()>; - // |connector| should be a fresh connector not yet bound to any thread. static scoped_refptr<ImageWriterUtilityClient> Create( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector); + const scoped_refptr<base::SequencedTaskRunner>& task_runner); static void SetFactoryForTesting(ImageWriterUtilityClientFactory* factory); @@ -79,9 +74,8 @@ class ImageWriterUtilityClient friend class base::RefCountedThreadSafe<ImageWriterUtilityClient>; friend class ImageWriterUtilityClientTest; - ImageWriterUtilityClient( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector); + explicit ImageWriterUtilityClient( + const scoped_refptr<base::SequencedTaskRunner>& task_runner); virtual ~ImageWriterUtilityClient(); private: @@ -102,9 +96,7 @@ class ImageWriterUtilityClient scoped_refptr<base::SequencedTaskRunner> task_runner_; - std::unique_ptr<service_manager::Connector> connector_; - - chrome::mojom::RemovableStorageWriterPtr removable_storage_writer_; + mojo::Remote<chrome::mojom::RemovableStorageWriter> removable_storage_writer_; std::unique_ptr<RemovableStorageWriterClientImpl> removable_storage_writer_client_; 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 7447bbcab5c..797239e9342 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc @@ -19,8 +19,6 @@ #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/system_connector.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -43,8 +41,8 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_)); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ImageWriterUtilityClientTest::FillFile, image_, pattern), run_loop.QuitClosure()); @@ -56,8 +54,8 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { device_ = image_.ReplaceExtension(FILE_PATH_LITERAL("out")); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ImageWriterUtilityClientTest::FillFile, device_, pattern), run_loop.QuitClosure()); @@ -102,16 +100,13 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { const std::string& error() const { return error_; } private: - void SetUpOnMainThread() override { - connector_ = content::GetSystemConnector()->Clone(); - } - void StartWriteTest() { DCHECK(IsRunningInCorrectSequence()); - if (!image_writer_utility_client_) + if (!image_writer_utility_client_) { image_writer_utility_client_ = - new ImageWriterUtilityClient(GetTaskRunner(), std::move(connector_)); + new ImageWriterUtilityClient(GetTaskRunner()); + } success_ = false; progress_ = 0; @@ -156,9 +151,10 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { void StartVerifyTest() { DCHECK(IsRunningInCorrectSequence()); - if (!image_writer_utility_client_) + if (!image_writer_utility_client_) { image_writer_utility_client_ = - new ImageWriterUtilityClient(GetTaskRunner(), std::move(connector_)); + new ImageWriterUtilityClient(GetTaskRunner()); + } success_ = false; progress_ = 0; @@ -203,8 +199,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { success_ = cancel_; quit_called_ = true; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_); } void Shutdown() { @@ -213,8 +208,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { image_writer_utility_client_->Shutdown(); quit_called_ = true; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_); } static void FillFile(const base::FilePath& path, char pattern) { @@ -224,8 +218,8 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { base::SequencedTaskRunner* CreateTaskRunner() { DCHECK(!task_runner_.get()); - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - Operation::blocking_task_traits()); + task_runner_ = + base::CreateSequencedTaskRunner(Operation::blocking_task_traits()); return task_runner_.get(); } @@ -255,7 +249,6 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { bool cancel_ = false; std::string error_; scoped_refptr<base::SequencedTaskRunner> task_runner_; - std::unique_ptr<service_manager::Connector> connector_; DISALLOW_COPY_AND_ASSIGN(ImageWriterUtilityClientTest); }; 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 a3cd8085f6e..330d582ae81 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc @@ -15,7 +15,6 @@ #include "chrome/browser/extensions/api/image_writer_private/unzip_helper.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -29,7 +28,6 @@ const int kMD5BufferSize = 1024; } // namespace Operation::Operation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& device_path, const base::FilePath& download_folder) @@ -41,18 +39,13 @@ Operation::Operation(base::WeakPtr<OperationManager> manager, device_path_(device_path), #endif temp_dir_(std::make_unique<base::ScopedTempDir>()), - connector_(std::move(connector)), stage_(image_writer_api::STAGE_UNKNOWN), progress_(0), download_folder_(download_folder), - task_runner_( - base::CreateSequencedTaskRunnerWithTraits(blocking_task_traits())) { + task_runner_(base::CreateSequencedTaskRunner(blocking_task_traits())) { } Operation::~Operation() { - // The connector_ is bound to the |task_runner_| and must be deleted there. - task_runner_->DeleteSoon(FROM_HERE, std::move(connector_)); - // base::ScopedTempDir must be destroyed on a thread that allows blocking IO // because it will try delete the directory if a call to Delete() hasn't been // made or was unsuccessful. @@ -134,7 +127,7 @@ void Operation::Finish() { CleanUp(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationManager::OnComplete, manager_, extension_id_)); } @@ -142,7 +135,7 @@ void Operation::Finish() { void Operation::Error(const std::string& error_message) { DCHECK(IsRunningInCorrectSequence()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationManager::OnError, manager_, extension_id_, stage_, progress_, error_message)); @@ -163,10 +156,9 @@ void Operation::SetProgress(int progress) { progress_ = progress; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OperationManager::OnProgress, manager_, extension_id_, - stage_, progress_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationManager::OnProgress, manager_, + extension_id_, stage_, progress_)); } void Operation::SetStage(image_writer_api::Stage stage) { @@ -178,10 +170,9 @@ void Operation::SetStage(image_writer_api::Stage stage) { stage_ = stage; progress_ = 0; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OperationManager::OnProgress, manager_, extension_id_, - stage_, progress_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationManager::OnProgress, manager_, + extension_id_, stage_, progress_)); } bool Operation::IsCancelled() { @@ -205,9 +196,7 @@ void Operation::CompleteAndContinue(const base::Closure& continuation) { void Operation::StartUtilityClient() { DCHECK(IsRunningInCorrectSequence()); if (!image_writer_client_.get()) { - // connector_ can be null in tests. - image_writer_client_ = ImageWriterUtilityClient::Create( - task_runner_, connector_ ? connector_->Clone() : nullptr); + image_writer_client_ = ImageWriterUtilityClient::Create(task_runner_); AddCleanUpFunction(base::BindOnce(&Operation::StopUtilityClient, this)); } } 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 cfc95222395..7444da741d7 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h @@ -32,10 +32,6 @@ namespace base { class FilePath; } // namespace base -namespace service_manager { -class Connector; -} - namespace extensions { namespace image_writer { @@ -67,7 +63,6 @@ class Operation : public base::RefCountedThreadSafe<Operation> { base::OnceCallback<void(bool, const std::string&)>; Operation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& device_path, const base::FilePath& download_folder); @@ -219,9 +214,6 @@ class Operation : public base::RefCountedThreadSafe<Operation> { // Runs all cleanup functions. void CleanUp(); - // Connector to the service manager. Used and deleted on |task_runner_|. - std::unique_ptr<service_manager::Connector> connector_; - // |stage_| and |progress_| are owned by the FILE thread, use |SetStage| and // |SetProgress| to update. Progress should be in the interval [0,100] image_writer_api::Stage stage_; @@ -237,6 +229,7 @@ class Operation : public base::RefCountedThreadSafe<Operation> { static constexpr base::TaskTraits blocking_task_traits() { return { + base::ThreadPool(), // Requires I/O. base::MayBlock(), // Apps (e.g. Chromebook Recovery Utility) present UI feedback based on 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 60ea32e7ca0..9144e4d6cfd 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 @@ -26,8 +26,8 @@ namespace { void ClearImageBurner() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ClearImageBurner)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ClearImageBurner)); return; } @@ -45,7 +45,7 @@ void Operation::Write(const base::Closure& continuation) { // Note this has to be run on the FILE thread to avoid concurrent access. AddCleanUpFunction(base::Bind(&ClearImageBurner)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&Operation::UnmountVolumes, this, continuation)); } 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 3f5d95f8bc8..f0dbae03359 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 @@ -7,6 +7,7 @@ #include <utility> #include "base/lazy_instance.h" +#include "base/memory/scoped_refptr.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h" @@ -20,12 +21,10 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" -#include "content/public/browser/system_connector.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" -#include "services/service_manager/public/cpp/connector.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/file_manager/path_util.h" @@ -87,10 +86,10 @@ void OperationManager::StartWriteFromUrl( ->GetURLLoaderFactoryForBrowserProcess() ->Clone(mojo::MakeRequest(&url_loader_factory_info)); - scoped_refptr<Operation> operation(new WriteFromUrlOperation( - weak_factory_.GetWeakPtr(), CreateConnector(), extension_id, + auto operation = base::MakeRefCounted<WriteFromUrlOperation>( + weak_factory_.GetWeakPtr(), extension_id, std::move(url_loader_factory_info), url, hash, device_path, - GetAssociatedDownloadFolder())); + GetAssociatedDownloadFolder()); operations_[extension_id] = operation; operation->PostTask(base::BindOnce(&Operation::Start, operation)); @@ -114,9 +113,9 @@ void OperationManager::StartWriteFromFile( return; } - scoped_refptr<Operation> operation(new WriteFromFileOperation( - weak_factory_.GetWeakPtr(), CreateConnector(), extension_id, path, - device_path, GetAssociatedDownloadFolder())); + auto operation = base::MakeRefCounted<WriteFromFileOperation>( + weak_factory_.GetWeakPtr(), extension_id, path, device_path, + GetAssociatedDownloadFolder()); operations_[extension_id] = operation; operation->PostTask(base::BindOnce(&Operation::Start, operation)); std::move(callback).Run(true, ""); @@ -147,9 +146,9 @@ void OperationManager::DestroyPartitions( return; } - scoped_refptr<Operation> operation(new DestroyPartitionsOperation( - weak_factory_.GetWeakPtr(), CreateConnector(), extension_id, device_path, - GetAssociatedDownloadFolder())); + auto operation = base::MakeRefCounted<DestroyPartitionsOperation>( + weak_factory_.GetWeakPtr(), extension_id, device_path, + GetAssociatedDownloadFolder()); operations_[extension_id] = operation; operation->PostTask(base::BindOnce(&Operation::Start, operation)); std::move(callback).Run(true, ""); @@ -243,11 +242,6 @@ void OperationManager::OnExtensionUnloaded( DeleteOperation(extension->id()); } -std::unique_ptr<service_manager::Connector> -OperationManager::CreateConnector() { - return content::GetSystemConnector()->Clone(); -} - void OperationManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h index e9c88e3ac22..ae2a04f5658 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h @@ -86,10 +86,6 @@ class OperationManager : public BrowserContextKeyedAPI, static BrowserContextKeyedAPIFactory<OperationManager>* GetFactoryInstance(); static OperationManager* Get(content::BrowserContext* context); - protected: - // Overridden in test. - virtual std::unique_ptr<service_manager::Connector> CreateConnector(); - private: static const char* service_name() { return "OperationManager"; 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 b27b88e9ab0..2ae9ff7edfd 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 @@ -13,24 +13,12 @@ #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" #include "extensions/browser/test_event_router.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { namespace { -class TestOperationManager : public OperationManager { - public: - explicit TestOperationManager(content::BrowserContext* context) - : OperationManager(context) {} - - private: - std::unique_ptr<service_manager::Connector> CreateConnector() override { - return nullptr; - } -}; - class ImageWriterOperationManagerTest : public ImageWriterUnitTestBase { public: void StartCallback(bool success, const std::string& error) { @@ -68,7 +56,7 @@ class ImageWriterOperationManagerTest : public ImageWriterUnitTestBase { }; TEST_F(ImageWriterOperationManagerTest, WriteFromFile) { - TestOperationManager manager(&test_profile_); + OperationManager manager(&test_profile_); manager.StartWriteFromFile( kDummyExtensionId, test_utils_.GetImagePath(), @@ -93,7 +81,7 @@ TEST_F(ImageWriterOperationManagerTest, WriteFromFile) { } TEST_F(ImageWriterOperationManagerTest, DestroyPartitions) { - TestOperationManager manager(&test_profile_); + OperationManager manager(&test_profile_); manager.DestroyPartitions( kDummyExtensionId, test_utils_.GetDevicePath().AsUTF8Unsafe(), 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 4cb18028036..5e90ec2533f 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 @@ -15,8 +15,7 @@ #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "services/service_manager/public/cpp/connector.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/zlib/google/zip.h" @@ -53,11 +52,7 @@ class OperationForTest : public Operation { const ExtensionId& extension_id, const std::string& device_path, const base::FilePath& download_path) - : Operation(manager_, - /*connector=*/nullptr, - extension_id, - device_path, - download_path) {} + : Operation(manager_, extension_id, device_path, download_path) {} void StartImpl() override {} @@ -121,7 +116,7 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase { // Cancel() will ensure we Shutdown() FakeImageWriterClient. operation_->Cancel(); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ImageWriterUnitTestBase::TearDown(); } 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 39dee11b2cd..ec433f683f3 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 @@ -28,9 +28,9 @@ void RemovableStorageProvider::GetAllDevices(DeviceListReadyCallback callback) { return; } // We need to do some file i/o to get the device block size - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&RemovableStorageProvider::PopulateDeviceList), std::move(callback)); 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 5dd00878cfd..e333dd5b7ac 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 @@ -5,6 +5,7 @@ #define CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_REMOVABLE_STORAGE_PROVIDER_H_ #include "base/callback.h" +#include "base/memory/scoped_refptr.h" #include "chrome/common/extensions/api/image_writer_private.h" #include "chrome/common/ref_counted_util.h" 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 525557ccce8..780f0c7ecc0 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 @@ -4,6 +4,7 @@ #include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h" +#include "base/memory/scoped_refptr.h" #include "chromeos/disks/disk.h" #include "chromeos/disks/disk_mount_manager.h" @@ -24,7 +25,7 @@ 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()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); for (DiskMountManager::DiskMap::const_iterator iter = disks.begin(); iter != disks.end(); 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 91fd7c8ec41..431c9e43557 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 @@ -8,7 +8,7 @@ #include "base/run_loop.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" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -104,7 +104,7 @@ class RemovableStorageProviderChromeOsUnitTest : public testing::Test { EXPECT_EQ(capacity, device->capacity); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; MockDiskMountManager* disk_mount_manager_mock_; scoped_refptr<StorageDeviceList> devices_; }; @@ -125,7 +125,7 @@ TEST_F(RemovableStorageProviderChromeOsUnitTest, GetAllDevices) { base::Bind(&RemovableStorageProviderChromeOsUnitTest::DevicesCallback, base::Unretained(this))); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_EQ(2U, devices_->data.size()); @@ -146,7 +146,7 @@ TEST_F(RemovableStorageProviderChromeOsUnitTest, EmptyProductAndModel) { base::Bind(&RemovableStorageProviderChromeOsUnitTest::DevicesCallback, base::Unretained(this))); - thread_bundle_.RunUntilIdle(); + 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 fa04548454b..fa2976bbf96 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 @@ -5,6 +5,7 @@ #include <stdint.h> #include "base/files/file_util.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h" #include "content/public/browser/browser_thread.h" @@ -57,7 +58,7 @@ RemovableStorageProvider::PopulateDeviceList() { return nullptr; } - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); /* Create a list of the devices in the 'block' subsystem. */ device::ScopedUdevEnumeratePtr enumerate( device::udev_enumerate_new(udev.get())); 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 4cc10223c1a..d6e49e851fe 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 @@ -14,6 +14,7 @@ #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/mac/scoped_ioobject.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/sys_string_conversions.h" #include "base/threading/scoped_blocking_call.h" #include "chrome/common/extensions/image_writer/image_writer_util_mac.h" @@ -42,7 +43,7 @@ RemovableStorageProvider::PopulateDeviceList() { } base::mac::ScopedIOObject<io_object_t> disk_obj; - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); while (disk_obj.reset(IOIteratorNext(disk_iterator)), disk_obj) { std::string bsd_name; uint64_t size_in_bytes; 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 cd04a90314d..e069f5f485a 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc @@ -15,6 +15,7 @@ #include <memory> +#include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -197,7 +198,7 @@ RemovableStorageProvider::PopulateDeviceList() { SP_DEVICE_INTERFACE_DATA interface_data; interface_data.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); while (SetupDiEnumDeviceInterfaces( interface_enumerator, NULL, // Device Info data. 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 6a745455bab..c7ca25348d9 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 @@ -14,7 +14,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" -#include "services/service_manager/public/cpp/connector.h" #if defined(OS_CHROMEOS) #include "chromeos/dbus/dbus_thread_manager.h" @@ -92,11 +91,10 @@ SimulateProgressInfo::SimulateProgressInfo(const SimulateProgressInfo&) = default; FakeImageWriterClient::FakeImageWriterClient() - : ImageWriterUtilityClient( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}), - /*connector=*/nullptr) {} + : ImageWriterUtilityClient(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {} FakeImageWriterClient::~FakeImageWriterClient() {} void FakeImageWriterClient::SimulateProgressAndCompletion( @@ -316,7 +314,7 @@ bool ImageWriterTestUtils::FillFile(const base::FilePath& file, } ImageWriterUnitTestBase::ImageWriterUnitTestBase() - : thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD) {} + : task_environment_(content::BrowserTaskEnvironment::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 ab9f77a6752..f2e1b3c5246 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 @@ -12,11 +12,11 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/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" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -204,7 +204,7 @@ class ImageWriterUnitTestBase : public testing::Test { ImageWriterTestUtils test_utils_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; } // namespace image_writer 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 index f80ddf9dd2e..4ae7b054f1b 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc @@ -34,8 +34,8 @@ 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}); + base::CreateSingleThreadTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); task_runner->PostTask(FROM_HERE, base::BindOnce(&UnzipHelper::UnzipImpl, this, image_path, temp_dir_path)); } 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 26b06b178cf..dfb46fe602a 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 @@ -8,7 +8,6 @@ #include "base/files/file_util.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "content/public/browser/browser_thread.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -17,16 +16,11 @@ using content::BrowserThread; WriteFromFileOperation::WriteFromFileOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const base::FilePath& user_file_path, const std::string& device_path, const base::FilePath& download_folder) - : Operation(manager, - std::move(connector), - extension_id, - device_path, - download_folder) { + : Operation(manager, extension_id, device_path, download_folder) { image_path_ = user_file_path; } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h index 5e6951e2ff6..ef82e25f881 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h @@ -7,10 +7,6 @@ #include "chrome/browser/extensions/api/image_writer_private/operation.h" -namespace service_manager { -class Connector; -} - namespace extensions { namespace image_writer { @@ -18,7 +14,6 @@ namespace image_writer { class WriteFromFileOperation : public Operation { public: WriteFromFileOperation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const base::FilePath& user_file_path, const std::string& storage_unit_id, 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 11af9bbe4f6..cc3d4473c73 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 @@ -9,7 +9,6 @@ #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -42,8 +41,7 @@ class ImageWriterFromFileTest : public ImageWriterUnitTestBase { TEST_F(ImageWriterFromFileTest, InvalidFile) { scoped_refptr<WriteFromFileOperation> op = new WriteFromFileOperation( - manager_.AsWeakPtr(), - /*connector=*/nullptr, kDummyExtensionId, test_utils_.GetImagePath(), + manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetImagePath(), test_utils_.GetDevicePath().AsUTF8Unsafe(), base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); @@ -70,8 +68,7 @@ TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) { #endif scoped_refptr<WriteFromFileOperation> op = new WriteFromFileOperation( - manager_.AsWeakPtr(), - /*connector=*/nullptr, kDummyExtensionId, test_utils_.GetImagePath(), + manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetImagePath(), test_utils_.GetDevicePath().AsUTF8Unsafe(), base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); EXPECT_CALL(manager_, 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 7c4669b4d8c..fdebd683504 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 @@ -12,7 +12,6 @@ #include "net/url_request/url_fetcher.h" #include "services/network/public/cpp/resource_response.h" #include "services/network/public/cpp/simple_url_loader.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -21,18 +20,13 @@ using content::BrowserThread; WriteFromUrlOperation::WriteFromUrlOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, network::mojom::URLLoaderFactoryPtrInfo factory_info, GURL url, const std::string& hash, const std::string& device_path, const base::FilePath& download_folder) - : Operation(manager, - std::move(connector), - extension_id, - device_path, - download_folder), + : Operation(manager, extension_id, device_path, download_folder), url_loader_factory_ptr_info_(std::move(factory_info)), url_(url), hash_(hash), 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 757fc07ffb9..617f609515a 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 @@ -25,7 +25,6 @@ class OperationManager; class WriteFromUrlOperation : public Operation { public: WriteFromUrlOperation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, network::mojom::URLLoaderFactoryPtrInfo factory_info, GURL url, 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 bcb23055c50..fd04e401865 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 @@ -14,7 +14,6 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/url_loader_interceptor.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -44,7 +43,6 @@ class WriteFromUrlOperationForTest : public WriteFromUrlOperation { const std::string& hash, const std::string& storage_unit_id) : WriteFromUrlOperation(manager, - /*connector=*/nullptr, extension_id, std::move(factory_info), url, @@ -243,7 +241,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) { // soon. operation->VerifyDownload(base::Bind( [](base::OnceClosure quit_closure) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, std::move(quit_closure)); diff --git a/chromium/chrome/browser/extensions/api/input_ime/OWNERS b/chromium/chrome/browser/extensions/api/input_ime/OWNERS index bed537d50a2..d4bff68b766 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/OWNERS +++ b/chromium/chrome/browser/extensions/api/input_ime/OWNERS @@ -1,5 +1,6 @@ # primary reviewer shuchen@chromium.org +keithlee@chromium.org # backup reviewer googleo@chromium.org 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 de28c1441a6..9bfb7c8e07c 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 @@ -95,10 +95,10 @@ void ImeObserver::OnKeyEvent( extensions::InputImeEventRouter* event_router = extensions::GetInputImeEventRouter(profile_); - if (!event_router || !event_router->GetActiveEngine(extension_id_)) + if (!event_router || !event_router->GetEngineIfActive(extension_id_)) return; const std::string request_id = - event_router->GetActiveEngine(extension_id_) + event_router->GetEngineIfActive(extension_id_) ->AddRequest(component_id, std::move(key_data)); input_ime::KeyboardEvent key_data_value; @@ -312,7 +312,7 @@ ExtensionFunction::ResponseAction InputImeKeyEventHandledFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (engine) { engine->KeyEventHandled(extension_id(), params->request_id, params->response); @@ -324,7 +324,7 @@ ExtensionFunction::ResponseAction InputImeSetCompositionFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (engine) { std::unique_ptr<SetComposition::Params> parent_params( SetComposition::Params::Create(*args_)); @@ -372,7 +372,7 @@ ExtensionFunction::ResponseAction InputImeCommitTextFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (engine) { std::unique_ptr<CommitText::Params> parent_params( CommitText::Params::Create(*args_)); @@ -392,7 +392,7 @@ ExtensionFunction::ResponseAction InputImeSendKeyEventsFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (!engine) return RespondNow(Error(kInputImeApiErrorEngineNotAvailable)); diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h index 78e9fce74fd..c3fc3b3344e 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h @@ -128,7 +128,7 @@ class InputImeEventRouterFactory { DISALLOW_COPY_AND_ASSIGN(InputImeEventRouterFactory); }; -class InputImeKeyEventHandledFunction : public UIThreadExtensionFunction { +class InputImeKeyEventHandledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.keyEventHandled", INPUT_IME_KEYEVENTHANDLED) @@ -136,11 +136,11 @@ class InputImeKeyEventHandledFunction : public UIThreadExtensionFunction { protected: ~InputImeKeyEventHandledFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class InputImeSetCompositionFunction : public UIThreadExtensionFunction { +class InputImeSetCompositionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setComposition", INPUT_IME_SETCOMPOSITION) @@ -148,29 +148,29 @@ class InputImeSetCompositionFunction : public UIThreadExtensionFunction { protected: ~InputImeSetCompositionFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class InputImeCommitTextFunction : public UIThreadExtensionFunction { +class InputImeCommitTextFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.commitText", INPUT_IME_COMMITTEXT) protected: ~InputImeCommitTextFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class InputImeSendKeyEventsFunction : public UIThreadExtensionFunction { +class InputImeSendKeyEventsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.sendKeyEvents", INPUT_IME_SENDKEYEVENTS) protected: ~InputImeSendKeyEventsFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc index b3d868bd61e..697de915f2f 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 @@ -16,12 +16,12 @@ #include "chrome/browser/chromeos/login/lock/screen_locker.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h" #include "chrome/common/extensions/api/input_ime.h" #include "chrome/common/extensions/api/input_method_private.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/process_manager.h" #include "extensions/common/manifest_handlers/background_info.h" #include "ui/base/ime/chromeos/component_extension_ime_manager.h" #include "ui/base/ime/chromeos/extension_ime_util.h" @@ -271,12 +271,12 @@ class ImeObserverChromeOS : public ui::ImeObserver { // 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) { + extensions::ExtensionRegistry* extension_registry = + extensions::ExtensionRegistry::Get(profile_); + if (extension_registry) { const extensions::Extension* extension = - extension_system->extension_service()->GetExtensionById( - extension_id_, false /* include_disabled */); + extension_registry->GetExtensionById( + extension_id_, extensions::ExtensionRegistry::ENABLED); if (!extension) return; extensions::ProcessManager* process_manager = @@ -370,12 +370,12 @@ class ImeObserverChromeOS : public ui::ImeObserver { namespace extensions { -InputMethodEngine* GetActiveEngine(Profile* profile, - const std::string& extension_id) { +InputMethodEngine* GetEngineIfActive(Profile* profile, + const std::string& extension_id) { InputImeEventRouter* event_router = GetInputImeEventRouter(profile); InputMethodEngine* engine = event_router ? static_cast<InputMethodEngine*>( - event_router->GetActiveEngine(extension_id)) + event_router->GetEngineIfActive(extension_id)) : nullptr; return engine; } @@ -468,7 +468,7 @@ InputMethodEngine* InputImeEventRouter::GetEngine( return (it != engine_map_.end()) ? it->second : nullptr; } -InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( +InputMethodEngineBase* InputImeEventRouter::GetEngineIfActive( const std::string& extension_id) { std::map<std::string, InputMethodEngine*>::iterator it = engine_map_.find(extension_id); @@ -477,7 +477,7 @@ InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( } ExtensionFunction::ResponseAction InputImeClearCompositionFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { return RespondNow(OneArgument(std::make_unique<base::Value>(false))); @@ -498,7 +498,7 @@ ExtensionFunction::ResponseAction InputImeClearCompositionFunction::Run() { } ExtensionFunction::ResponseAction InputImeHideInputViewFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) return RespondNow(NoArguments()); @@ -579,7 +579,7 @@ InputImeSetCandidateWindowPropertiesFunction::Run() { } ExtensionFunction::ResponseAction InputImeSetCandidatesFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { return RespondNow(OneArgument(std::make_unique<base::Value>(true))); @@ -616,7 +616,7 @@ ExtensionFunction::ResponseAction InputImeSetCandidatesFunction::Run() { } ExtensionFunction::ResponseAction InputImeSetCursorPositionFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { return RespondNow(OneArgument(std::make_unique<base::Value>(false))); @@ -713,7 +713,7 @@ InputMethodPrivateNotifyImeMenuItemActivatedFunction::Run() { std::string active_extension_id = chromeos::extension_ime_util::GetExtensionIDFromInputMethodID( current_input_method.id()); - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), active_extension_id); if (!engine) return RespondNow(Error(kInputImeApiChromeOSErrorEngineNotAvailable)); @@ -728,7 +728,7 @@ InputMethodPrivateNotifyImeMenuItemActivatedFunction::Run() { ExtensionFunction::ResponseAction InputMethodPrivateGetCompositionBoundsFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) return RespondNow(Error(kInputImeApiChromeOSErrorEngineNotAvailable)); @@ -760,7 +760,7 @@ void InputImeAPI::OnExtensionLoaded(content::BrowserContext* browser_context, // can receive the onActivate event to recover itself upon the // unexpected unload. InputMethodEngineBase* engine = - event_router->GetActiveEngine(extension->id()); + event_router->GetEngineIfActive(extension->id()); // When extension is unloaded unexpectedly and reloaded, OS doesn't pass // details.browser_context value in OnListenerAdded callback. So we need // to reactivate engine here. @@ -817,8 +817,8 @@ void InputImeAPI::OnListenerAdded(const EventListenerInfo& details) { if (!details.browser_context) return; InputMethodEngine* engine = - GetActiveEngine(Profile::FromBrowserContext(details.browser_context), - details.extension_id); + GetEngineIfActive(Profile::FromBrowserContext(details.browser_context), + details.extension_id); // Notifies the IME extension for IME ready with onActivate/onFocus events. if (engine) engine->Enable(engine->GetActiveComponentId()); diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h index a20921c57d2..c07e7259450 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h @@ -21,7 +21,7 @@ class InputMethodEngine; namespace extensions { -class InputImeClearCompositionFunction : public UIThreadExtensionFunction { +class InputImeClearCompositionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.clearComposition", INPUT_IME_CLEARCOMPOSITION) @@ -33,8 +33,7 @@ class InputImeClearCompositionFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeSetCandidateWindowPropertiesFunction - : public UIThreadExtensionFunction { +class InputImeSetCandidateWindowPropertiesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCandidateWindowProperties", INPUT_IME_SETCANDIDATEWINDOWPROPERTIES) @@ -46,7 +45,7 @@ class InputImeSetCandidateWindowPropertiesFunction ResponseAction Run() override; }; -class InputImeSetCandidatesFunction : public UIThreadExtensionFunction { +class InputImeSetCandidatesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCandidates", INPUT_IME_SETCANDIDATES) @@ -57,7 +56,7 @@ class InputImeSetCandidatesFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeSetCursorPositionFunction : public UIThreadExtensionFunction { +class InputImeSetCursorPositionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCursorPosition", INPUT_IME_SETCURSORPOSITION) @@ -69,7 +68,7 @@ class InputImeSetCursorPositionFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeSetMenuItemsFunction : public UIThreadExtensionFunction { +class InputImeSetMenuItemsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setMenuItems", INPUT_IME_SETMENUITEMS) @@ -80,7 +79,7 @@ class InputImeSetMenuItemsFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeUpdateMenuItemsFunction : public UIThreadExtensionFunction { +class InputImeUpdateMenuItemsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.updateMenuItems", INPUT_IME_UPDATEMENUITEMS) @@ -92,7 +91,7 @@ class InputImeUpdateMenuItemsFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeDeleteSurroundingTextFunction : public UIThreadExtensionFunction { +class InputImeDeleteSurroundingTextFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.deleteSurroundingText", INPUT_IME_DELETESURROUNDINGTEXT) @@ -103,7 +102,7 @@ class InputImeDeleteSurroundingTextFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeHideInputViewFunction : public UIThreadExtensionFunction { +class InputImeHideInputViewFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.hideInputView", INPUT_IME_HIDEINPUTVIEW) @@ -111,19 +110,19 @@ class InputImeHideInputViewFunction : public UIThreadExtensionFunction { protected: ~InputImeHideInputViewFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; class InputMethodPrivateNotifyImeMenuItemActivatedFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: InputMethodPrivateNotifyImeMenuItemActivatedFunction() {} protected: ~InputMethodPrivateNotifyImeMenuItemActivatedFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -134,7 +133,7 @@ class InputMethodPrivateNotifyImeMenuItemActivatedFunction }; class InputMethodPrivateGetCompositionBoundsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("inputMethodPrivate.getCompositionBounds", INPUTMETHODPRIVATE_GETCOMPOSITIONBOUNDS) @@ -157,7 +156,7 @@ class InputImeEventRouter : public InputImeEventRouterBase { void UnregisterAllImes(const std::string& extension_id); chromeos::InputMethodEngine* GetEngine(const std::string& extension_id); - input_method::InputMethodEngineBase* GetActiveEngine( + input_method::InputMethodEngineBase* GetEngineIfActive( const std::string& extension_id) override; std::string GetUnloadedExtensionId() const { diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc index 112b9cc3f87..95a52f9e403 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc @@ -122,13 +122,13 @@ class ImeObserverNonChromeOS : public ui::ImeObserver { namespace extensions { -InputMethodEngine* GetActiveEngine(content::BrowserContext* browser_context, - const std::string& extension_id) { +InputMethodEngine* GetEngineIfActive(content::BrowserContext* browser_context, + const std::string& extension_id) { Profile* profile = Profile::FromBrowserContext(browser_context); InputImeEventRouter* event_router = GetInputImeEventRouter(profile); InputMethodEngine* engine = event_router ? static_cast<InputMethodEngine*>( - event_router->GetActiveEngine(extension_id)) + event_router->GetEngineIfActive(extension_id)) : nullptr; return engine; } @@ -174,7 +174,7 @@ InputImeEventRouter::~InputImeEventRouter() { DeleteInputMethodEngine(active_engine_->GetExtensionId()); } -InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( +InputMethodEngineBase* InputImeEventRouter::GetEngineIfActive( const std::string& extension_id) { return (ui::IMEBridge::Get()->GetCurrentEngineHandler() && active_engine_ && @@ -324,7 +324,7 @@ void InputImeActivateFunction::OnPermissionBubbleFinished( ExtensionFunction::ResponseAction InputImeDeactivateFunction::Run() { InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); ui::IMEBridge::Get()->SetCurrentEngineHandler(nullptr); if (engine) engine->CloseImeWindows(); @@ -352,7 +352,7 @@ ExtensionFunction::ResponseAction InputImeCreateWindowFunction::Run() { } InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); @@ -375,7 +375,7 @@ ExtensionFunction::ResponseAction InputImeCreateWindowFunction::Run() { ExtensionFunction::ResponseAction InputImeShowWindowFunction::Run() { InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); @@ -388,7 +388,7 @@ ExtensionFunction::ResponseAction InputImeShowWindowFunction::Run() { ExtensionFunction::ResponseAction InputImeHideWindowFunction::Run() { InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h index da76c4637c6..68e06c59d6a 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h @@ -34,7 +34,7 @@ class InputImeEventRouter : public InputImeEventRouterBase { ~InputImeEventRouter() override; // Gets the input method engine if the extension is active. - input_method::InputMethodEngineBase* GetActiveEngine( + input_method::InputMethodEngineBase* GetEngineIfActive( const std::string& extension_id) override; // Actives the extension with new input method engine, and deletes the @@ -55,7 +55,7 @@ class InputImeEventRouter : public InputImeEventRouterBase { DISALLOW_COPY_AND_ASSIGN(InputImeEventRouter); }; -class InputImeCreateWindowFunction : public UIThreadExtensionFunction { +class InputImeCreateWindowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.createWindow", INPUT_IME_CREATEWINDOW) @@ -66,7 +66,7 @@ class InputImeCreateWindowFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class InputImeShowWindowFunction : public UIThreadExtensionFunction { +class InputImeShowWindowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.showWindow", INPUT_IME_SHOWWINDOW) @@ -77,7 +77,7 @@ class InputImeShowWindowFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class InputImeHideWindowFunction : public UIThreadExtensionFunction { +class InputImeHideWindowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.hideWindow", INPUT_IME_HIDEWINDOW) @@ -88,7 +88,7 @@ class InputImeHideWindowFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class InputImeActivateFunction : public UIThreadExtensionFunction { +class InputImeActivateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.activate", INPUT_IME_ACTIVATE) @@ -99,7 +99,7 @@ class InputImeActivateFunction : public UIThreadExtensionFunction { protected: ~InputImeActivateFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -109,14 +109,14 @@ class InputImeActivateFunction : public UIThreadExtensionFunction { void OnPermissionBubbleFinished(ImeWarningBubblePermissionStatus status); }; -class InputImeDeactivateFunction : public UIThreadExtensionFunction { +class InputImeDeactivateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.deactivate", INPUT_IME_DEACTIVATE) protected: ~InputImeDeactivateFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h index 132a6a679bc..6e575c382b7 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h @@ -22,7 +22,7 @@ class InputImeEventRouterBase { virtual ~InputImeEventRouterBase(); // Gets the input method engine if the extension is active. - virtual input_method::InputMethodEngineBase* GetActiveEngine( + virtual input_method::InputMethodEngineBase* GetEngineIfActive( const std::string& extension_id) = 0; Profile* GetProfile() const { return profile_; } diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc index 1f6eb29db33..15ab8552a61 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc @@ -132,7 +132,7 @@ ExtensionFunction::ResponseAction InstanceIDGetTokenFunction::DoWork() { GetInstanceID()->GetToken( params->get_token_params.authorized_entity, params->get_token_params.scope, options, - /*is_lazy=*/false, + /*flags=*/{}, base::Bind(&InstanceIDGetTokenFunction::GetTokenCompleted, this)); return RespondLater(); diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h index ffd49612b85..33a0bb0dba5 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h @@ -11,7 +11,7 @@ namespace extensions { -class InstanceIDApiFunction : public UIThreadExtensionFunction { +class InstanceIDApiFunction : public ExtensionFunction { public: InstanceIDApiFunction(); diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc index 125a7777f72..3e82ec740d5 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc @@ -35,7 +35,9 @@ #include "components/language/core/browser/pref_names.h" #include "components/language/core/common/language_util.h" #include "components/language/core/common/locale_util.h" +#include "components/spellcheck/browser/spellcheck_platform.h" #include "components/spellcheck/common/spellcheck_common.h" +#include "components/spellcheck/common/spellcheck_features.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_prefs.h" #include "third_party/icu/source/i18n/unicode/coll.h" @@ -292,6 +294,7 @@ LanguageSettingsPrivateEnableLanguageFunction::Run() { } translate_prefs->AddToLanguageList(language_code, /*force_blocked=*/false); + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -325,6 +328,7 @@ LanguageSettingsPrivateDisableLanguageFunction::Run() { } translate_prefs->RemoveFromLanguageList(language_code); + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -354,6 +358,7 @@ LanguageSettingsPrivateSetEnableTranslationForLanguageFunction::Run() { } else { translate_prefs->BlockLanguage(language_code); } + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -406,6 +411,7 @@ LanguageSettingsPrivateMoveLanguageFunction::Run() { const int offset = 1; translate_prefs->RearrangeLanguage(language_code, where, offset, supported_language_codes); + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -495,6 +501,12 @@ LanguageSettingsPrivateAddSpellcheckWordFunction::Run() { SpellcheckServiceFactory::GetForContext(browser_context()); bool success = service->GetCustomDictionary()->AddWord(params->word); +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) + if (spellcheck::UseBrowserSpellChecker()) { + spellcheck_platform::AddWord(base::UTF8ToUTF16(params->word)); + } +#endif + return RespondNow(OneArgument(std::make_unique<base::Value>(success))); } @@ -514,6 +526,12 @@ LanguageSettingsPrivateRemoveSpellcheckWordFunction::Run() { SpellcheckServiceFactory::GetForContext(browser_context()); bool success = service->GetCustomDictionary()->RemoveWord(params->word); +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) + if (spellcheck::UseBrowserSpellChecker()) { + spellcheck_platform::RemoveWord(base::UTF8ToUTF16(params->word)); + } +#endif + return RespondNow(OneArgument(std::make_unique<base::Value>(success))); } diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h index 951f544fa7e..2e745eb503b 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h @@ -14,7 +14,7 @@ namespace extensions { // Implements the languageSettingsPrivate.getLanguageList method. class LanguageSettingsPrivateGetLanguageListFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetLanguageListFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getLanguageList", @@ -33,8 +33,7 @@ class LanguageSettingsPrivateGetLanguageListFunction }; // Implements the languageSettingsPrivate.enableLanguage method. -class LanguageSettingsPrivateEnableLanguageFunction - : public UIThreadExtensionFunction { +class LanguageSettingsPrivateEnableLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateEnableLanguageFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.enableLanguage", @@ -54,7 +53,7 @@ class LanguageSettingsPrivateEnableLanguageFunction // Implements the languageSettingsPrivate.disableLanguage method. class LanguageSettingsPrivateDisableLanguageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateDisableLanguageFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.disableLanguage", @@ -75,7 +74,7 @@ class LanguageSettingsPrivateDisableLanguageFunction // Implements the languageSettingsPrivate.setEnableTranslationForLanguage // method. class LanguageSettingsPrivateSetEnableTranslationForLanguageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateSetEnableTranslationForLanguageFunction(); DECLARE_EXTENSION_FUNCTION( @@ -95,8 +94,7 @@ class LanguageSettingsPrivateSetEnableTranslationForLanguageFunction }; // Implements the languageSettingsPrivate.moveLanguage method. -class LanguageSettingsPrivateMoveLanguageFunction - : public UIThreadExtensionFunction { +class LanguageSettingsPrivateMoveLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateMoveLanguageFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.moveLanguage", @@ -116,7 +114,7 @@ class LanguageSettingsPrivateMoveLanguageFunction // Implements the languageSettingsPrivate.getSpellcheckDictionaryStatuses // method. class LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction(); DECLARE_EXTENSION_FUNCTION( @@ -136,7 +134,7 @@ class LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction // Implements the languageSettingsPrivate.getSpellcheckWords method. class LanguageSettingsPrivateGetSpellcheckWordsFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public SpellcheckCustomDictionary::Observer { public: LanguageSettingsPrivateGetSpellcheckWordsFunction(); @@ -163,7 +161,7 @@ class LanguageSettingsPrivateGetSpellcheckWordsFunction // Implements the languageSettingsPrivate.addSpellcheckWord method. class LanguageSettingsPrivateAddSpellcheckWordFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateAddSpellcheckWordFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.addSpellcheckWord", @@ -181,7 +179,7 @@ class LanguageSettingsPrivateAddSpellcheckWordFunction // Implements the languageSettingsPrivate.removeSpellcheckWord method. class LanguageSettingsPrivateRemoveSpellcheckWordFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateRemoveSpellcheckWordFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.removeSpellcheckWord", @@ -199,7 +197,7 @@ class LanguageSettingsPrivateRemoveSpellcheckWordFunction // Implements the languageSettingsPrivate.getTranslateTargetLanguage method. class LanguageSettingsPrivateGetTranslateTargetLanguageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetTranslateTargetLanguageFunction(); DECLARE_EXTENSION_FUNCTION( @@ -221,7 +219,7 @@ class LanguageSettingsPrivateGetTranslateTargetLanguageFunction // Implements the languageSettingsPrivate.getInputMethodLists method. class LanguageSettingsPrivateGetInputMethodListsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetInputMethodListsFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getInputMethodLists", @@ -238,8 +236,7 @@ class LanguageSettingsPrivateGetInputMethodListsFunction }; // Implements the languageSettingsPrivate.addInputMethod method. -class LanguageSettingsPrivateAddInputMethodFunction - : public UIThreadExtensionFunction { +class LanguageSettingsPrivateAddInputMethodFunction : public ExtensionFunction { public: LanguageSettingsPrivateAddInputMethodFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.addInputMethod", @@ -259,7 +256,7 @@ class LanguageSettingsPrivateAddInputMethodFunction // Implements the languageSettingsPrivate.removeInputMethod method. class LanguageSettingsPrivateRemoveInputMethodFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateRemoveInputMethodFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.removeInputMethod", @@ -279,7 +276,7 @@ class LanguageSettingsPrivateRemoveInputMethodFunction // Implements the languageSettingsPrivate.retryDownloadDictionary method. class LanguageSettingsPrivateRetryDownloadDictionaryFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateRetryDownloadDictionaryFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.retryDownloadDictionary", 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 eb9da3ee60f..9dd95841737 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 @@ -9,8 +9,11 @@ #include "base/bind.h" #include "base/macros.h" +#include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" +#include "chrome/browser/apps/app_service/app_launch_params.h" +#include "chrome/browser/apps/launch_service/launch_service.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/launch_util.h" @@ -24,14 +27,13 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/web_applications/web_app_dialog_utils.h" #include "chrome/browser/ui/webui/extensions/extension_icon_source.h" #include "chrome/browser/web_applications/components/app_registrar.h" #include "chrome/browser/web_applications/components/install_manager.h" #include "chrome/browser/web_applications/components/web_app_constants.h" +#include "chrome/browser/web_applications/components/web_app_install_utils.h" #include "chrome/browser/web_applications/components/web_app_provider_base.h" #include "chrome/browser/web_applications/components/web_app_utils.h" #include "chrome/common/extensions/extension_metrics.h" @@ -51,16 +53,59 @@ #include "services/data_decoder/public/cpp/safe_json_parser.h" #if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/login/demo_mode/demo_session.h" -#endif +#include "chrome/browser/ui/app_list/arc/arc_app_utils.h" +#include "components/arc/arc_service_manager.h" +#include "components/arc/arc_util.h" +#include "components/arc/mojom/intent_helper.mojom.h" +#include "components/arc/session/arc_bridge_service.h" +#endif // OS_CHROMEOS namespace { +#if defined(OS_CHROMEOS) +const char kPlayIntentPrefix[] = + "https://play.google.com/store/apps/details?id="; +const char kChromeWebStoreReferrer[] = "&referrer=chrome_web_store"; +#endif // OS_CHROMEOS + +using InstallAndroidAppCallback = + extensions::ManagementAPIDelegate::InstallAndroidAppCallback; +using AndroidAppInstallStatusCallback = + extensions::ManagementAPIDelegate::AndroidAppInstallStatusCallback; using InstallWebAppCallback = extensions::ManagementAPIDelegate::InstallWebAppCallback; using InstallWebAppResult = extensions::ManagementAPIDelegate::InstallWebAppResult; +#if defined(OS_CHROMEOS) +void OnDidCheckForIntentToPlayStore(const std::string& intent, + InstallAndroidAppCallback callback, + bool installable) { + if (!installable) { + std::move(callback).Run(false); + return; + } + + auto* arc_service_manager = arc::ArcServiceManager::Get(); + if (!arc_service_manager) { + std::move(callback).Run(false); + return; + } + + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_service_manager->arc_bridge_service()->intent_helper(), HandleUrl); + if (!instance) { + std::move(callback).Run(false); + return; + } + + instance->HandleUrl(intent, arc::kPlayStorePackage); + std::move(callback).Run(true); +} +#endif // OS_CHROMEOS + class ManagementSetEnabledFunctionInstallPromptDelegate : public extensions::InstallPromptDelegate { public: @@ -160,7 +205,8 @@ void OnGenerateAppForLinkCompleted( extensions::ManagementGenerateAppForLinkFunction* function, const web_app::AppId& app_id, web_app::InstallResultCode code) { - const bool install_success = code == web_app::InstallResultCode::kSuccess; + const bool install_success = + code == web_app::InstallResultCode::kSuccessNewInstall; function->FinishCreateWebApp(app_id, install_success); } @@ -178,6 +224,7 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->title = base::UTF8ToUTF16(title); web_app_info->app_url = launch_url; + web_app_info->open_as_window = false; if (!image_result.image.IsEmpty()) { WebApplicationInfo::IconInfo icon; @@ -192,7 +239,7 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { DCHECK(provider); provider->install_manager().InstallWebAppFromInfo( - std::move(web_app_info), /*no_network_install=*/false, + std::move(web_app_info), web_app::ForInstallableSite::kNo, WebappInstallSource::MANAGEMENT_API, base::BindOnce(OnGenerateAppForLinkCompleted, base::RetainedRef(function))); @@ -212,7 +259,7 @@ void OnWebAppInstallCompleted(InstallWebAppCallback callback, // TODO(loyso): Update this when more of the web_app::InstallResultCodes are // actually set. switch (code) { - case web_app::InstallResultCode::kSuccess: + case web_app::InstallResultCode::kSuccessNewInstall: result = InstallWebAppResult::kSuccess; break; default: @@ -257,10 +304,11 @@ void ChromeManagementAPIDelegate::LaunchAppFunctionDelegate( // returned. extensions::LaunchContainer launch_container = GetLaunchContainer(extensions::ExtensionPrefs::Get(context), extension); - OpenApplication(AppLaunchParams( - Profile::FromBrowserContext(context), extension->id(), launch_container, - WindowOpenDisposition::NEW_FOREGROUND_TAB, - extensions::AppLaunchSource::kSourceManagementApi)); + Profile* profile = Profile::FromBrowserContext(context); + apps::LaunchService::Get(profile)->OpenApplication( + AppLaunchParams(profile, extension->id(), launch_container, + WindowOpenDisposition::NEW_FOREGROUND_TAB, + apps::mojom::AppLaunchSource::kSourceManagementApi)); #if defined(OS_CHROMEOS) chromeos::DemoSession::RecordAppLaunchSourceIfInDemoMode( @@ -369,7 +417,7 @@ bool ChromeManagementAPIDelegate::IsWebAppInstalled( auto* provider = web_app::WebAppProviderBase::GetProviderBase( Profile::FromBrowserContext(context)); DCHECK(provider); - return provider->registrar().IsInstalled(web_app_url); + return provider->registrar().IsLocallyInstalled(web_app_url); } bool ChromeManagementAPIDelegate::CanContextInstallWebApps( @@ -391,6 +439,66 @@ void ChromeManagementAPIDelegate::InstallReplacementWebApp( std::move(callback))); } +bool ChromeManagementAPIDelegate::CanContextInstallAndroidApps( + content::BrowserContext* context) const { +#if defined(OS_CHROMEOS) + return arc::IsArcAllowedForProfile(Profile::FromBrowserContext(context)); +#else + return false; +#endif // defined(OS_CHROMEOS) +} + +void ChromeManagementAPIDelegate::CheckAndroidAppInstallStatus( + const std::string& package_name, + AndroidAppInstallStatusCallback callback) const { +#if defined(OS_CHROMEOS) + auto* arc_service_manager = arc::ArcServiceManager::Get(); + if (!arc_service_manager) { + std::move(callback).Run(false); + return; + } + + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_service_manager->arc_bridge_service()->app(), IsInstallable); + if (!instance) { + std::move(callback).Run(false); + return; + } + + instance->IsInstallable(package_name, std::move(callback)); +#else + std::move(callback).Run(false); +#endif // OS_CHROMEOS +} + +void ChromeManagementAPIDelegate::InstallReplacementAndroidApp( + const std::string& package_name, + InstallAndroidAppCallback callback) const { +#if defined(OS_CHROMEOS) + std::string intent = + base::StrCat({kPlayIntentPrefix, package_name, kChromeWebStoreReferrer}); + + auto* arc_service_manager = arc::ArcServiceManager::Get(); + if (!arc_service_manager) { + std::move(callback).Run(false); + return; + } + + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_service_manager->arc_bridge_service()->app(), IsInstallable); + if (!instance) { + std::move(callback).Run(false); + return; + } + + instance->IsInstallable( + package_name, base::BindOnce(&OnDidCheckForIntentToPlayStore, intent, + std::move(callback))); +#else + std::move(callback).Run(false); +#endif // defined(OS_CHROMEOS) +} + void ChromeManagementAPIDelegate::EnableExtension( content::BrowserContext* context, const std::string& extension_id) const { 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 8088380e0bb..83587591a41 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 @@ -54,6 +54,15 @@ class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate { content::BrowserContext* context, const GURL& web_app_url, ManagementAPIDelegate::InstallWebAppCallback callback) const override; + bool CanContextInstallAndroidApps( + content::BrowserContext* context) const override; + void CheckAndroidAppInstallStatus( + const std::string& package_name, + ManagementAPIDelegate::AndroidAppInstallStatusCallback callback) + const override; + void InstallReplacementAndroidApp( + const std::string& package_name, + ManagementAPIDelegate::InstallAndroidAppCallback callback) const override; void EnableExtension(content::BrowserContext* context, const std::string& extension_id) const override; void DisableExtension( 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 16f29ac9da4..93f3c8d8979 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,7 @@ #include "extensions/browser/extension_dialog_auto_confirm.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension_builder.h" #include "extensions/test/extension_test_message_listener.h" @@ -243,17 +243,17 @@ class ExtensionManagementApiEscalationTest : scoped_temp_dir_.GetPath().AppendASCII("permissions2.crx"), pem_path, base::FilePath()); - ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> - extension_service(); - // Install low-permission version of the extension. ASSERT_TRUE(InstallExtension(path_v1, 1)); - EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); + EXPECT_TRUE(extension_registry()->GetExtensionById( + kId, ExtensionRegistry::ENABLED)); // Update to a high-permission version - it should get disabled. EXPECT_FALSE(UpdateExtension(kId, path_v2, -1)); - EXPECT_TRUE(service->GetExtensionById(kId, false) == NULL); - EXPECT_TRUE(service->GetExtensionById(kId, true) != NULL); + EXPECT_FALSE(extension_registry()->GetExtensionById( + kId, ExtensionRegistry::ENABLED)); + EXPECT_TRUE(extension_registry()->GetExtensionById( + kId, ExtensionRegistry::COMPATIBILITY)); EXPECT_TRUE(ExtensionPrefs::Get(browser()->profile()) ->DidExtensionEscalatePermissions(kId)); } @@ -344,14 +344,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, // Register the target extension with extension service. scoped_refptr<const Extension> target_extension = ExtensionBuilder("TargetExtension").SetID(kId).Build(); - ExtensionService* const service = - ExtensionSystem::Get(browser()->profile())->extension_service(); - service->AddExtension(target_extension.get()); + extension_service()->AddExtension(target_extension.get()); SetEnabled(false, true, std::string(), source_extension); SetEnabled(true, true, std::string(), source_extension); - const Extension* extension = ExtensionSystem::Get(browser()->profile()) - ->extension_service() - ->GetExtensionById(kId, false); + const Extension* extension = + extension_registry()->GetExtensionById(kId, ExtensionRegistry::ENABLED); EXPECT_TRUE(extension); } } diff --git a/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc index af20dd95ad9..febd21f6435 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc @@ -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 "chrome/browser/extensions/browsertest_util.h" #include "chrome/browser/extensions/extension_action_runner.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/test/base/ui_test_utils.h" @@ -14,26 +15,7 @@ namespace extensions { -namespace { -enum class ContextType { - kEventPage, - kServiceWorker, -}; - -// Returns the newly added WebContents. -// TODO(lazyboy): We have at least 3 versions of this AddTab within -// //extensions, put this in a central place and use that instead. -content::WebContents* AddTab(Browser* browser, const GURL& url) { - int starting_tab_count = browser->tab_strip_model()->count(); - ui_test_utils::NavigateToURLWithDisposition( - browser, url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); - int tab_count = browser->tab_strip_model()->count(); - EXPECT_EQ(starting_tab_count + 1, tab_count); - return browser->tab_strip_model()->GetActiveWebContents(); -} - -} // namespace +using ContextType = ExtensionBrowserTest::ContextType; // Tests management API from a non-persistent extension (event page or // Service Worker). @@ -82,10 +64,7 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, UninstallSelf) { extensions::ExtensionRegistry::Get(browser()->profile())); base::FilePath path = test_dir.Pack(); - // NOTE: Do not use a scoped_refptr<Extension> as the |extension| might get - // uninstalled right away. - const Extension* extension = LoadExtension(path); - + scoped_refptr<const Extension> extension = LoadExtension(path); EXPECT_EQ(extension, observer.WaitForExtensionUninstalled()); } @@ -124,7 +103,8 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, // Click on browser action to start the test, |extension_a| will uninstall // |extension_b|. { - content::WebContents* web_contents = AddTab(browser(), GURL("about:blank")); + content::WebContents* web_contents = + browsertest_util::AddTab(browser(), GURL("about:blank")); ASSERT_TRUE(web_contents); ExtensionActionRunner::GetForWebContents( browser()->tab_strip_model()->GetActiveWebContents()) 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 9b7ea704b0e..5f753cc87b3 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc @@ -62,7 +62,7 @@ class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { // A wrapper around extension_function_test_utils::RunFunction that runs with // the associated browser, no flags, and can take stack-allocated arguments. - bool RunFunction(const scoped_refptr<UIThreadExtensionFunction>& function, + bool RunFunction(const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args); Browser* browser() { return browser_.get(); } @@ -80,7 +80,7 @@ class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { }; bool ManagementApiUnitTest::RunFunction( - const scoped_refptr<UIThreadExtensionFunction>& function, + const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args) { return extension_function_test_utils::RunFunction( function.get(), base::WrapUnique(args.DeepCopy()), browser(), @@ -98,7 +98,7 @@ void ManagementApiUnitTest::SetUp() { browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); } @@ -271,7 +271,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstall) { ScopedTestDialogAutoConfirm::ACCEPT); // Uninstall requires a user gesture, so this should fail. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); EXPECT_FALSE(RunFunction(function, uninstall_args)); EXPECT_EQ(std::string(constants::kGestureNeededForUninstallError), @@ -295,7 +295,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstall) { ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; service()->AddExtension(extension.get()); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new ManagementUninstallFunction(); EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id)); EXPECT_FALSE(RunFunction(function, uninstall_args)); @@ -347,7 +347,7 @@ TEST_F(ManagementApiUnitTest, ManagementWebStoreUninstall) { ScopedTestDialogAutoConfirm::CANCEL); ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); function->set_extension(triggering_extension); EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id)); @@ -360,7 +360,7 @@ TEST_F(ManagementApiUnitTest, ManagementWebStoreUninstall) { } { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); function->set_extension(triggering_extension); @@ -397,7 +397,7 @@ TEST_F(ManagementApiUnitTest, ManagementProgrammaticUninstall) { base::ListValue uninstall_args; uninstall_args.AppendString(extension->id()); { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); function->set_extension(triggering_extension); @@ -435,8 +435,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstallBlacklisted) { ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT); ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - scoped_refptr<UIThreadExtensionFunction> function( - new ManagementUninstallFunction()); + scoped_refptr<ExtensionFunction> function(new ManagementUninstallFunction()); base::ListValue uninstall_args; uninstall_args.AppendString(id); EXPECT_TRUE(RunFunction(function, uninstall_args)) << function->GetError(); @@ -452,7 +451,7 @@ TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlacklisted) { service()->BlacklistExtensionForTest(id); EXPECT_NE(nullptr, registry()->GetInstalledExtension(id)); - scoped_refptr<UIThreadExtensionFunction> function; + scoped_refptr<ExtensionFunction> function; // Test enabling it. { @@ -486,7 +485,7 @@ TEST_F(ManagementApiUnitTest, ExtensionInfo_MayEnable) { const std::string args = base::StringPrintf("[\"%s\"]", extension->id().c_str()); - scoped_refptr<UIThreadExtensionFunction> function; + scoped_refptr<ExtensionFunction> function; // Initially the extension should show as enabled. EXPECT_TRUE(registry()->enabled_extensions().Contains(extension->id())); diff --git a/chromium/chrome/browser/extensions/api/management/management_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_apitest.cc index b9b4b8e09b0..bbc3cb9f617 100644 --- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc @@ -22,6 +22,7 @@ #include "chrome/common/extensions/extension_constants.h" #include "extensions/browser/api/management/management_api.h" #include "extensions/browser/extension_dialog_auto_confirm.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/test_management_policy.h" #include "extensions/common/manifest.h" @@ -281,10 +282,10 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, InstallableWebApp) { auto* provider = web_app::WebAppProviderBase::GetProviderBase(browser()->profile()); - EXPECT_FALSE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_FALSE(provider->registrar().IsLocallyInstalled(good_web_app_url)); RunTest(kManifest, kGoodWebAppURL, kBackground, true /* from_webstore */); - EXPECT_TRUE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_TRUE(provider->registrar().IsLocallyInstalled(good_web_app_url)); chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false); } @@ -318,10 +319,10 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, auto* provider = web_app::WebAppProviderBase::GetProviderBase(browser()->profile()); - EXPECT_FALSE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_FALSE(provider->registrar().IsLocallyInstalled(good_web_app_url)); RunTest(kAppManifest, kGoodWebAppURL, kBackground, true /* from_webstore */); - EXPECT_TRUE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_TRUE(provider->registrar().IsLocallyInstalled(good_web_app_url)); chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false); } @@ -337,11 +338,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LoadExtensions(); extensions::ScopedTestDialogAutoConfirm auto_confirm( extensions::ScopedTestDialogAutoConfirm::ACCEPT); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - EXPECT_TRUE(service->GetExtensionById(extension_ids_["enabled_extension"], - false)); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); + EXPECT_TRUE( + registry->GetExtensionById(extension_ids_["enabled_extension"], + extensions::ExtensionRegistry::ENABLED)); // Ensure that all actions are allowed. extensions::ExtensionSystem::Get( @@ -350,8 +351,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ASSERT_TRUE(RunExtensionSubtest("management/management_policy", "allowed.html")); // The last thing the test does is uninstall the "enabled_extension". - EXPECT_FALSE(service->GetExtensionById(extension_ids_["enabled_extension"], - true)); + EXPECT_FALSE( + registry->GetExtensionById(extension_ids_["enabled_extension"], + extensions::ExtensionRegistry::COMPATIBILITY)); } // Fails often on Windows dbg bots. http://crbug.com/177163 @@ -364,11 +366,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_ManagementPolicyProhibited) { LoadExtensions(); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - EXPECT_TRUE(service->GetExtensionById(extension_ids_["enabled_extension"], - false)); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); + EXPECT_TRUE( + registry->GetExtensionById(extension_ids_["enabled_extension"], + extensions::ExtensionRegistry::ENABLED)); // Prohibit status changes. extensions::ManagementPolicy* policy = extensions::ExtensionSystem::Get( @@ -382,10 +384,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - // Load an extension that calls launchApp() on any app that gets // installed. ExtensionTestMessageListener launcher_loaded("launcher loaded", false); @@ -401,16 +399,18 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { // Find the app's browser. Check that it is a popup. ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); Browser* app_browser = FindOtherBrowser(browser()); - ASSERT_TRUE(app_browser->is_type_popup()); - ASSERT_TRUE(app_browser->is_app()); + ASSERT_TRUE(app_browser->is_type_app()); // Close the app panel. CloseBrowserSynchronously(app_browser); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); // Unload the extension. UninstallExtension(app_id); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); - ASSERT_FALSE(service->GetExtensionById(app_id, true)); + ASSERT_FALSE(registry->GetExtensionById( + app_id, extensions::ExtensionRegistry::COMPATIBILITY)); // Set a pref indicating that the user wants to launch in a regular tab. // This should be ignored, because panel apps always load in a popup. @@ -429,8 +429,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { // prefs, so we should still see the launch in a popup. ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); app_browser = FindOtherBrowser(browser()); - ASSERT_TRUE(app_browser->is_type_popup()); - ASSERT_TRUE(app_browser->is_app()); + ASSERT_TRUE(app_browser->is_type_app()); } // Disabled: crbug.com/230165, crbug.com/915339, crbug.com/979399 @@ -442,10 +441,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { #endif IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - // Load an extension that calls launchApp() on any app that gets // installed. ExtensionTestMessageListener launcher_loaded("launcher loaded", false); @@ -467,10 +462,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) { ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); ASSERT_EQ(2, browser()->tab_strip_model()->count()); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); // Unload the extension. UninstallExtension(app_id); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); - ASSERT_FALSE(service->GetExtensionById(app_id, true)); + ASSERT_FALSE(registry->GetExtensionById( + app_id, extensions::ExtensionRegistry::COMPATIBILITY)); // Set a pref indicating that the user wants to launch in a window. extensions::SetLaunchType(browser()->profile(), app_id, @@ -487,7 +485,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) { // a new browser. ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); Browser* app_browser = FindOtherBrowser(browser()); - ASSERT_TRUE(app_browser->is_app()); + ASSERT_TRUE(app_browser->is_type_app()); } // Flaky on MacOS: crbug.com/915339 diff --git a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc index b05f8f0c8cd..91b2e2ceb0a 100644 --- a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc @@ -33,6 +33,7 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/extension_host.h" +#include "extensions/browser/extension_host_observer.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" @@ -40,16 +41,18 @@ #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/browser/updater/extension_downloader.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_background_page_first_load_observer.h" #include "net/url_request/test_url_request_interceptor.h" #include "testing/gmock/include/gmock/gmock.h" using content::BrowserThread; using extensions::Extension; using extensions::ExtensionRegistry; +using extensions::ExtensionService; using extensions::Manifest; using policy::PolicyMap; -using testing::Return; using testing::_; +using testing::Return; namespace { @@ -58,6 +61,50 @@ std::string BuildForceInstallPolicyValue(const char* extension_id, return base::StringPrintf("%s;%s", extension_id, update_url); } +// Observes destruction of an extension's ExtensionHost if it is currently +// there. +class ExtensionHostDestructionObserver + : public extensions::ExtensionHostObserver { + public: + ExtensionHostDestructionObserver(Profile* profile, + const extensions::ExtensionId& extension_id) + : profile_(profile), + extension_id_(extension_id), + host_(extensions::ProcessManager::Get(profile) + ->GetBackgroundHostForExtension(extension_id_)), + extension_host_observer_(this) { + DCHECK(host_); + extension_host_observer_.Add(host_); + } + + void WaitForDestructionThenWaitForFirstLoad() { + run_loop_.Run(); + + extensions::TestBackgroundPageFirstLoadObserver first_load_observer( + profile_, extension_id_); + first_load_observer.Wait(); + } + + // ExtensionHostObserver: + void OnExtensionHostDestroyed( + const extensions::ExtensionHost* host) override { + if (host == host_) { + extension_host_observer_.Remove(host_); + run_loop_.Quit(); + } + } + + private: + Profile* const profile_ = nullptr; + const extensions::ExtensionId extension_id_; + extensions::ExtensionHost* const host_ = nullptr; + base::RunLoop run_loop_; + ScopedObserver<extensions::ExtensionHost, extensions::ExtensionHostObserver> + extension_host_observer_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionHostDestructionObserver); +}; + } // namespace class ExtensionManagementTest : public extensions::ExtensionBrowserTest { @@ -114,15 +161,8 @@ class ExtensionManagementTest : public extensions::ExtensionBrowserTest { extensions::ScopedInstallVerifierBypassForTest install_verifier_bypass_; }; -#if defined(OS_LINUX) || defined(OS_WIN) -// Times out sometimes on Linux and Win XP. http://crbug.com/89727 -#define MAYBE_InstallSameVersion DISABLED_InstallSameVersion -#else -#define MAYBE_InstallSameVersion InstallSameVersion -#endif - // Tests that installing the same version overwrites. -IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallSameVersion) { +IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { base::ScopedAllowBlockingForTesting allow_blocking; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); @@ -142,10 +182,22 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallSameVersion) { ASSERT_TRUE(extension); base::FilePath old_path = extension->path(); - // Install an extension with the same version. The previous install should be - // overwritten. - extension = InstallExtension(second_path, 0); - ASSERT_TRUE(extension); + const extensions::ExtensionId extension_id = extension->id(); + { + ExtensionHostDestructionObserver host_destruction_observer(profile(), + extension_id); + + // Install an extension with the same version. The previous install should + // be overwritten. + extension = InstallExtension(second_path, 0); + ASSERT_TRUE(extension); + + // Wait for the old ExtensionHost destruction first before waiting for the + // new one to load. + // Note that this is needed to ensure that |IsExtensionAtVersion| below can + // successfully execute JS, otherwise this test becomes flaky. + host_destruction_observer.WaitForDestructionThenWaitForFirstLoad(); + } base::FilePath new_path = extension->path(); EXPECT_FALSE(IsExtensionAtVersion(extension, "1.0")); @@ -207,12 +259,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallRequiresConfirm) { // Installing the extension without an auto confirming UI should result in // it being disabled, since good.crx has permissions that require approval. - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); std::string id = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; ASSERT_FALSE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 0)); - ASSERT_TRUE(service->GetExtensionById(id, true)); + ASSERT_TRUE(extension_registry()->GetExtensionById( + id, ExtensionRegistry::COMPATIBILITY)); UninstallExtension(id); // And the install should succeed when the permissions are accepted. @@ -373,10 +423,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ExtensionService* service = extension_service(); + ExtensionRegistry* registry = extension_registry(); const size_t size_before = registry->enabled_extensions().size(); ASSERT_TRUE(registry->disabled_extensions().is_empty()); const Extension* extension = InstallExtension(v1_path, 1); @@ -397,8 +445,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { install_observer.WaitForExtensionWillBeInstalled(); EXPECT_TRUE(listener2.WaitUntilSatisfied()); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", false); + extension = registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); ASSERT_TRUE(notification_listener.started()); @@ -422,8 +470,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { // Make sure the extension state is the same as before. ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", false); + extension = registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); } @@ -474,10 +522,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ExtensionService* service = extension_service(); + ExtensionRegistry* registry = extension_registry(); const size_t enabled_size_before = registry->enabled_extensions().size(); const size_t disabled_size_before = registry->disabled_extensions().size(); const Extension* extension = InstallExtension(v1_path, 1); @@ -500,11 +546,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, install_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(disabled_size_before + 1, registry->disabled_extensions().size()); ASSERT_EQ(enabled_size_before, registry->enabled_extensions().size()); - extension = service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", true); + extension = registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::COMPATIBILITY); ASSERT_TRUE(extension); - ASSERT_FALSE(service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", false)); + ASSERT_FALSE(registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::ENABLED)); ASSERT_EQ("2.0", extension->VersionString()); // The extension should have not made the callback because it is disabled. @@ -520,9 +566,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); + ExtensionService* service = extension_service(); const char kExtensionId[] = "ogjcoiohnmldgjemafoockdghcjciccf"; base::ScopedAllowBlockingForTesting allow_blocking; @@ -550,7 +594,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { return false; })); - ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ExtensionRegistry* registry = extension_registry(); const size_t size_before = registry->enabled_extensions().size(); ASSERT_TRUE(registry->disabled_extensions().is_empty()); @@ -576,7 +620,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { service->updater()->CheckNow(extensions::ExtensionUpdater::CheckParams()); install_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - const Extension* extension = service->GetExtensionById(kExtensionId, false); + const Extension* extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); @@ -629,9 +674,6 @@ const char kForceInstallNotEmptyHelp[] = // See http://crbug.com/57378 for flakiness details. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); const char kExtensionId[] = "ogjcoiohnmldgjemafoockdghcjciccf"; base::ScopedAllowBlockingForTesting allow_blocking; @@ -683,7 +725,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { // Check if the extension got installed. ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - const Extension* extension = service->GetExtensionById(kExtensionId, false); + const Extension* extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); EXPECT_EQ(Manifest::EXTERNAL_POLICY_DOWNLOAD, extension->location()); @@ -708,7 +751,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { policies.Erase(policy::key::kExtensionInstallForcelist); UpdateProviderPolicy(policies); EXPECT_EQ(size_before + 1, registry->enabled_extensions().size()); - EXPECT_FALSE(service->GetExtensionById(kExtensionId, true)); + EXPECT_FALSE(registry->GetExtensionById(kExtensionId, + ExtensionRegistry::COMPATIBILITY)); } // See http://crbug.com/103371 and http://crbug.com/120640. @@ -763,7 +807,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, // User install of the extension. ASSERT_TRUE(InstallExtension(v2_path, 1)); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - const Extension* extension = service->GetExtensionById(kExtensionId, false); + const Extension* extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::INTERNAL, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); @@ -782,7 +827,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, install_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, false); + extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::EXTERNAL_POLICY_DOWNLOAD, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); @@ -794,13 +840,15 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, policies.Erase(policy::key::kExtensionInstallForcelist); UpdateProviderPolicy(policies); ASSERT_EQ(size_before, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, true); + extension = registry->GetExtensionById(kExtensionId, + ExtensionRegistry::COMPATIBILITY); EXPECT_FALSE(extension); // User install again, but have it disabled too before setting the policy. ASSERT_TRUE(InstallExtension(v2_path, 1)); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, false); + extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::INTERNAL, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); @@ -808,7 +856,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableExtension(kExtensionId); EXPECT_EQ(1u, registry->disabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, true); + extension = registry->GetExtensionById(kExtensionId, + ExtensionRegistry::COMPATIBILITY); EXPECT_TRUE(extension); EXPECT_FALSE(service->IsExtensionEnabled(kExtensionId)); @@ -824,7 +873,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, extension_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, false); + extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::EXTERNAL_POLICY_DOWNLOAD, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api.h b/chromium/chrome/browser/extensions/api/mdns/mdns_api.h index 19464a2ef76..dbfe3b46e41 100644 --- a/chromium/chrome/browser/extensions/api/mdns/mdns_api.h +++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api.h @@ -118,7 +118,7 @@ class MDnsAPI : public BrowserContextKeyedAPI, DISALLOW_COPY_AND_ASSIGN(MDnsAPI); }; -class MdnsForceDiscoveryFunction : public UIThreadExtensionFunction { +class MdnsForceDiscoveryFunction : public ExtensionFunction { public: MdnsForceDiscoveryFunction(); @@ -126,7 +126,7 @@ class MdnsForceDiscoveryFunction : public UIThreadExtensionFunction { ~MdnsForceDiscoveryFunction() override; private: - // UIThreadExtensionFunction override. + // ExtensionFunction override. ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("mdns.forceDiscovery", MDNS_FORCEDISCOVERY) diff --git a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc index 633d8ff73d2..69ddd3fbc6a 100644 --- a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc @@ -13,12 +13,9 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/chromeos/delegate_to_browser_gpu_service_accelerator_factory.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/browser/system_connector.h" +#include "content/public/browser/video_capture_service.h" #include "mojo/public/cpp/bindings/strong_binding.h" -#include "services/service_manager/public/cpp/connector.h" -#include "services/video_capture/public/mojom/constants.mojom.h" #include "services/video_capture/public/mojom/device_factory.mojom.h" -#include "services/video_capture/public/mojom/device_factory_provider.mojom.h" namespace extensions { @@ -42,12 +39,40 @@ std::string GetComponentNameForComponentType( return ""; } +api::media_perception_private::ComponentInstallationError +GetComponentInstallationErrorForCrOSComponentManagerError( + const component_updater::CrOSComponentManager::Error error) { + switch (error) { + case component_updater::CrOSComponentManager::Error::ERROR_MAX: + case component_updater::CrOSComponentManager::Error::NONE: + return api::media_perception_private::COMPONENT_INSTALLATION_ERROR_NONE; + case component_updater::CrOSComponentManager::Error::UNKNOWN_COMPONENT: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_UNKNOWN_COMPONENT; + case component_updater::CrOSComponentManager::Error::INSTALL_FAILURE: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_INSTALL_FAILURE; + case component_updater::CrOSComponentManager::Error::MOUNT_FAILURE: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_MOUNT_FAILURE; + case component_updater::CrOSComponentManager::Error:: + COMPATIBILITY_CHECK_FAILED: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_COMPATIBILITY_CHECK_FAILED; + case component_updater::CrOSComponentManager::Error::NOT_FOUND: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_NOT_FOUND; + } + NOTREACHED() << "Reached component error type not in switch."; + return api::media_perception_private::COMPONENT_INSTALLATION_ERROR_NONE; +} + void OnLoadComponent( MediaPerceptionAPIDelegate::LoadCrOSComponentCallback load_callback, component_updater::CrOSComponentManager::Error error, const base::FilePath& mount_point) { std::move(load_callback) - .Run(error == component_updater::CrOSComponentManager::Error::NONE, + .Run(GetComponentInstallationErrorForCrOSComponentManagerError(error), mount_point); } @@ -68,22 +93,18 @@ void MediaPerceptionAPIDelegateChromeOS::LoadCrOSComponent( base::BindOnce(OnLoadComponent, std::move(load_callback))); } -void MediaPerceptionAPIDelegateChromeOS:: - BindDeviceFactoryProviderToVideoCaptureService( - video_capture::mojom::DeviceFactoryProviderPtr* provider) { +void MediaPerceptionAPIDelegateChromeOS::BindVideoSourceProvider( + mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // In unit test environments, there may not be any connector. - service_manager::Connector* connector = content::GetSystemConnector(); - if (!connector) - return; - connector->BindInterface(video_capture::mojom::kServiceName, provider); - video_capture::mojom::AcceleratorFactoryPtr accelerator_factory; mojo::MakeStrongBinding( std::make_unique< content::DelegateToBrowserGpuServiceAcceleratorFactory>(), mojo::MakeRequest(&accelerator_factory)); - (*provider)->InjectGpuDependencies(std::move(accelerator_factory)); + + auto& service = content::GetVideoCaptureService(); + service.InjectGpuDependencies(std::move(accelerator_factory)); + service.ConnectToVideoSourceProvider(std::move(receiver)); } void MediaPerceptionAPIDelegateChromeOS::SetMediaPerceptionRequestHandler( diff --git a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h index 1d765110283..45abc51201e 100644 --- a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h +++ b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h @@ -20,8 +20,9 @@ class MediaPerceptionAPIDelegateChromeOS void LoadCrOSComponent( const api::media_perception_private::ComponentType& type, LoadCrOSComponentCallback load_callback) override; - void BindDeviceFactoryProviderToVideoCaptureService( - video_capture::mojom::DeviceFactoryProviderPtr* provider) override; + void BindVideoSourceProvider( + mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver) + override; void SetMediaPerceptionRequestHandler( MediaPerceptionRequestHandler handler) override; void ForwardMediaPerceptionRequest( diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc index b19df51e216..ff4cc1c31a6 100644 --- a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc +++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc @@ -98,8 +98,7 @@ content::WebContents* ChromeMessagingDelegate::GetWebContentsByTabId( int tab_id) { content::WebContents* contents = nullptr; if (!ExtensionTabUtil::GetTabById(tab_id, browser_context, - /*incognito_enabled=*/true, nullptr, - nullptr, &contents, nullptr)) { + /*incognito_enabled=*/true, &contents)) { return nullptr; } return contents; diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc index 1ba3053c6d1..e0305176d49 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc @@ -95,10 +95,8 @@ struct BuiltInHost { std::unique_ptr<NativeMessageHost> CreateIt2MeHost() { return remoting::CreateIt2MeNativeMessagingHostForChromeOS( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}), g_browser_process->policy_service()); } @@ -127,7 +125,9 @@ static const BuiltInHost kBuiltInHost[] = { {arc::ArcSupportMessageHost::kHostName, arc::ArcSupportMessageHost::kHostOrigin, 1, &arc::ArcSupportMessageHost::Create}, - {chromeos::kWilcoDtcSupportdUiMessageHost, nullptr, 0, + {chromeos::kWilcoDtcSupportdUiMessageHost, + chromeos::kWilcoDtcSupportdHostOrigins, + chromeos::kWilcoDtcSupportdHostOriginsSize, &chromeos::CreateExtensionOwnedWilcoDtcSupportdMessageHost}, }; diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc index b6e5a3e5595..4efb28cd942 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc @@ -71,8 +71,8 @@ NativeMessageProcessHost::NativeMessageProcessHost( write_pending_(false) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_ = base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}); + task_runner_ = + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}); } NativeMessageProcessHost::~NativeMessageProcessHost() { @@ -83,8 +83,9 @@ NativeMessageProcessHost::~NativeMessageProcessHost() { // TODO(https://crbug.com/806451): On OSX EnsureProcessTerminated() may // block, so we have to post a task on the blocking pool. #if defined(OS_MACOSX) - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&base::EnsureProcessTerminated, Passed(&process_))); #else base::EnsureProcessTerminated(std::move(process_)); @@ -106,7 +107,8 @@ std::unique_ptr<NativeMessageHost> NativeMessageHost::Create( allow_user_level, native_view, GetProfilePathIfEnabled(Profile::FromBrowserContext(browser_context), source_extension_id, native_host_name), - /* require_native_initiated_connections = */ false)); + /* require_native_initiated_connections = */ false, + /* connect_id = */ "")); } // static @@ -162,8 +164,8 @@ void NativeMessageProcessHost::OnHostProcessLaunched( read_file_ = read_file.GetPlatformFile(); #endif - scoped_refptr<base::TaskRunner> task_runner(base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + scoped_refptr<base::TaskRunner> task_runner(base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); read_stream_.reset(new net::FileStream(std::move(read_file), task_runner)); diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc index ddab3fb0276..afb9c77adc7 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc @@ -40,7 +40,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "extensions/common/features/feature_channel.h" #include "testing/gtest/include/gtest/gtest.h" @@ -115,7 +115,7 @@ class NativeMessagingTest : public ::testing::Test, protected: NativeMessagingTest() : current_channel_(version_info::Channel::DEV), - thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP), channel_closed_(false) {} void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } @@ -177,7 +177,7 @@ class NativeMessagingTest : public ::testing::Test, ScopedCurrentChannel current_channel_; std::unique_ptr<NativeMessageHost> native_message_host_; std::unique_ptr<base::RunLoop> run_loop_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; std::string last_message_; @@ -315,6 +315,10 @@ TEST_F(NativeMessagingTest, EchoConnect) { const base::Value* args = nullptr; ASSERT_TRUE(last_message_parsed_->Get("args", &args)); EXPECT_TRUE(args->is_none()); + + const base::Value* connect_id_value = nullptr; + ASSERT_TRUE(last_message_parsed_->Get("connect_id", &connect_id_value)); + EXPECT_TRUE(connect_id_value->is_none()); } // Test send message with a real client. The args passed when launching the @@ -425,6 +429,10 @@ TEST_F(NativeMessagingTest, ReconnectArgsIfNativeConnectionDisallowed) { const base::Value* args_value = nullptr; ASSERT_TRUE(last_message_parsed_->Get("args", &args_value)); EXPECT_TRUE(args_value->is_none()); + + const base::Value* connect_id_value = nullptr; + ASSERT_TRUE(last_message_parsed_->Get("connect_id", &connect_id_value)); + EXPECT_TRUE(connect_id_value->is_none()); } TEST_F(NativeMessagingTest, UserLevel) { diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc index e8cc9ae6148..33042b32456 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc @@ -92,6 +92,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_NativeMessagingLaunch) { switches::kNativeMessagingConnectHost, ScopedTestNativeMessagingHost:: kSupportsNativeInitiatedConnectionsHostName); + command_line.AppendSwitchASCII(switches::kNativeMessagingConnectId, + "test-connect-id"); StartupBrowserCreator::ProcessCommandLineAlreadyRunning(command_line, {}, profile()->GetPath()); diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc index eabfae9941d..d0ccab75d99 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc @@ -7,6 +7,7 @@ #include <memory> #include <utility> +#include "base/strings/string_util.h" #include "chrome/browser/extensions/api/messaging/native_message_port.h" #include "chrome/browser/extensions/api/messaging/native_message_process_host.h" #include "chrome/browser/extensions/api/messaging/native_process_launcher.h" @@ -94,9 +95,21 @@ ScopedAllowNativeAppConnectionForTest:: g_allow_native_app_connection_for_test = nullptr; } +bool IsValidConnectionId(const base::StringPiece connection_id) { + return connection_id.size() <= 20 && + base::ContainsOnlyChars( + connection_id, + "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"); +} + void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, const std::string& host_id, + const std::string& connection_id, Profile* profile) { + if (!IsValidConnectionId(connection_id)) { + // TODO(crbug.com/967262): Report errors to the native messaging host. + return; + } if (!ExtensionSupportsConnectionFromNativeApp(extension_id, host_id, profile, /* log_errors = */ true)) { // TODO(crbug.com/967262): Report errors to the native messaging host. @@ -112,7 +125,7 @@ void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, NativeProcessLauncher::CreateDefault( /* allow_user_level = */ true, /* native_view = */ nullptr, profile->GetPath(), - /* require_native_initiated_connections = */ true)); + /* require_native_initiated_connections = */ true, connection_id)); auto native_message_port = std::make_unique<extensions::NativeMessagePort>( message_service->GetChannelDelegate(), port_id, std::move(native_message_host)); diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h index d730422c455..2bb104678ee 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h @@ -24,6 +24,7 @@ bool ExtensionSupportsConnectionFromNativeApp(const std::string& extension_id, // |host_id|. void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, const std::string& host_id, + const std::string& connection_id, Profile* profile); class ScopedAllowNativeAppConnectionForTest { diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc index 48ab25ef66f..63134b0e411 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/event_router.h" #include "extensions/browser/event_router_factory.h" #include "extensions/browser/extension_prefs.h" @@ -115,7 +115,7 @@ class ExtensionSupportsConnectionFromNativeAppTest : public ::testing::Test { } ScopedCurrentChannel channel_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; bool has_listener_result_ = true; TestingProfile profile_; std::string extension_id_; 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 fc731d68f81..edfdcbf0bc5 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc @@ -19,6 +19,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/path_service.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" @@ -47,7 +48,8 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { NativeProcessLauncherImpl(bool allow_user_level_hosts, intptr_t native_window, const base::FilePath& profile_directory, - bool require_native_initiated_connections); + bool require_native_initiated_connections, + const std::string& connect_id); ~NativeProcessLauncherImpl() override; void Launch(const GURL& origin, @@ -60,7 +62,8 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { Core(bool allow_user_level_hosts, intptr_t native_window, const base::FilePath& profile_directory, - bool require_native_initiated_connections); + bool require_native_initiated_connections, + const std::string& connect_id); void Launch(const GURL& origin, const std::string& native_host_name, const LaunchedCallback& callback); @@ -91,6 +94,8 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { const base::FilePath profile_directory_; const bool require_native_initiated_connections_; + + const std::string connect_id_; #if defined(OS_WIN) // Handle of the native window corresponding to the extension. intptr_t window_handle_; @@ -107,12 +112,14 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { NativeProcessLauncherImpl::Core::Core(bool allow_user_level_hosts, intptr_t window_handle, const base::FilePath& profile_directory, - bool require_native_initiated_connections) + bool require_native_initiated_connections, + const std::string& connect_id) : detached_(false), allow_user_level_hosts_(allow_user_level_hosts), profile_directory_(profile_directory), require_native_initiated_connections_( - require_native_initiated_connections) + require_native_initiated_connections), + connect_id_(connect_id) #if defined(OS_WIN) , window_handle_(window_handle) @@ -132,10 +139,11 @@ void NativeProcessLauncherImpl::Core::Launch( const GURL& origin, const std::string& native_host_name, const LaunchedCallback& callback) { - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&Core::DoLaunchOnThreadPool, this, - origin, native_host_name, callback)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&Core::DoLaunchOnThreadPool, this, origin, + native_host_name, callback)); } void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool( @@ -259,6 +267,11 @@ void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool( base::Base64Encode(encoded_reconnect_command, &encoded_reconnect_command); command_line.AppendArg( base::StrCat({"--reconnect-command=", encoded_reconnect_command})); + + if (!connect_id_.empty()) { + command_line.AppendArg(base::StrCat( + {"--", switches::kNativeMessagingConnectId, "=", connect_id_})); + } } base::Process process; @@ -290,7 +303,7 @@ void NativeProcessLauncherImpl::Core::CallCallbackOnIOThread( void NativeProcessLauncherImpl::Core::PostErrorResult( const LaunchedCallback& callback, LaunchResult error) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, this, callback, error, base::Process(), base::File(), @@ -302,7 +315,7 @@ void NativeProcessLauncherImpl::Core::PostResult( base::Process process, base::File read_file, base::File write_file) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, this, callback, RESULT_SUCCESS, std::move(process), @@ -313,11 +326,13 @@ NativeProcessLauncherImpl::NativeProcessLauncherImpl( bool allow_user_level_hosts, intptr_t window_handle, const base::FilePath& profile_directory, - bool require_native_initiated_connections) - : core_(new Core(allow_user_level_hosts, - window_handle, - profile_directory, - require_native_initiated_connections)) {} + bool require_native_initiated_connections, + const std::string& connect_id) + : core_(base::MakeRefCounted<Core>(allow_user_level_hosts, + window_handle, + profile_directory, + require_native_initiated_connections, + connect_id)) {} NativeProcessLauncherImpl::~NativeProcessLauncherImpl() { core_->Detach(); @@ -336,7 +351,8 @@ std::unique_ptr<NativeProcessLauncher> NativeProcessLauncher::CreateDefault( bool allow_user_level_hosts, gfx::NativeView native_view, const base::FilePath& profile_directory, - bool require_native_initiated_connections) { + bool require_native_initiated_connections, + const std::string& connect_id) { intptr_t window_handle = 0; #if defined(OS_WIN) window_handle = reinterpret_cast<intptr_t>( @@ -344,7 +360,7 @@ std::unique_ptr<NativeProcessLauncher> NativeProcessLauncher::CreateDefault( #endif return std::make_unique<NativeProcessLauncherImpl>( allow_user_level_hosts, window_handle, profile_directory, - require_native_initiated_connections); + require_native_initiated_connections, connect_id); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h index 51102bc3247..9ee0a8f3d62 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h @@ -51,7 +51,8 @@ class NativeProcessLauncher { bool allow_user_level_hosts, gfx::NativeView native_view, const base::FilePath& profile_directory, - bool require_native_initiated_connections); + bool require_native_initiated_connections, + const std::string& connect_id); NativeProcessLauncher() {} virtual ~NativeProcessLauncher() {} 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 c0843625742..e458a0501f0 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 @@ -84,6 +84,12 @@ bool NativeProcessLauncher::LaunchNativeProcess( options.allow_new_privs = true; #endif +#if defined(OS_MACOSX) + // This is executing a third-party binary, so do not associate any system + // private data requests with Chrome. + options.disclaim_responsibility = true; +#endif + base::Process local_process = base::LaunchProcess(command_line, options); if (!local_process.IsValid()) { LOG(ERROR) << "Error launching process"; diff --git a/chromium/chrome/browser/extensions/api/module/module.h b/chromium/chrome/browser/extensions/api/module/module.h index de81de0d8a8..cbdde206799 100644 --- a/chromium/chrome/browser/extensions/api/module/module.h +++ b/chromium/chrome/browser/extensions/api/module/module.h @@ -16,7 +16,7 @@ std::string GetUpdateURLData(const ExtensionPrefs* prefs, const std::string& extension_id); } // namespace extension -class ExtensionSetUpdateUrlDataFunction : public UIThreadExtensionFunction { +class ExtensionSetUpdateUrlDataFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.setUpdateUrlData", EXTENSION_SETUPDATEURLDATA) @@ -28,8 +28,7 @@ class ExtensionSetUpdateUrlDataFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ExtensionIsAllowedIncognitoAccessFunction - : public UIThreadExtensionFunction { +class ExtensionIsAllowedIncognitoAccessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.isAllowedIncognitoAccess", EXTENSION_ISALLOWEDINCOGNITOACCESS) @@ -41,8 +40,7 @@ class ExtensionIsAllowedIncognitoAccessFunction ResponseAction Run() override; }; -class ExtensionIsAllowedFileSchemeAccessFunction - : public UIThreadExtensionFunction { +class ExtensionIsAllowedFileSchemeAccessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.isAllowedFileSchemeAccess", EXTENSION_ISALLOWEDFILESCHEMEACCESS) diff --git a/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc b/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc index 27060f8ca72..db66f4b2e6b 100644 --- a/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc +++ b/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc @@ -133,8 +133,9 @@ void ChromeNetworkingCastPrivateDelegate::VerifyDestination( std::unique_ptr<Credentials> credentials, const VerifiedCallback& success_callback, const FailureCallback& failure_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&RunDecodeAndVerifyCredentials, base::Passed(&credentials)), base::Bind(&VerifyDestinationCompleted, success_callback, failure_callback)); @@ -145,8 +146,9 @@ void ChromeNetworkingCastPrivateDelegate::VerifyAndEncryptData( std::unique_ptr<Credentials> credentials, const DataCallback& success_callback, const FailureCallback& failure_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&RunVerifyAndEncryptData, data, base::Passed(&credentials)), base::Bind(&VerifyAndEncryptDataCompleted, success_callback, failure_callback)); diff --git a/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h b/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h index 4f12d14f07a..daf23fbaef8 100644 --- a/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h +++ b/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h @@ -18,7 +18,7 @@ class DictionaryValue; namespace extensions { class NetworkingCastPrivateVerifyDestinationFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateVerifyDestinationFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.verifyDestination", @@ -38,7 +38,7 @@ class NetworkingCastPrivateVerifyDestinationFunction }; class NetworkingCastPrivateVerifyAndEncryptDataFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateVerifyAndEncryptDataFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.verifyAndEncryptData", @@ -58,7 +58,7 @@ class NetworkingCastPrivateVerifyAndEncryptDataFunction }; class NetworkingCastPrivateSetWifiTDLSEnabledStateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateSetWifiTDLSEnabledStateFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.setWifiTDLSEnabledState", @@ -82,7 +82,7 @@ class NetworkingCastPrivateSetWifiTDLSEnabledStateFunction }; class NetworkingCastPrivateGetWifiTDLSStatusFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateGetWifiTDLSStatusFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.getWifiTDLSStatus", 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 d8121216c4c..bedfe826489 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 @@ -363,9 +363,6 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { // Sends a notification about the added profile. profile_test_->AddProfile(kUser1ProfilePath, userhash_); - // Enable technologies. - manager_test_->AddTechnology("wimax", true); - // Add IPConfigs base::DictionaryValue ipconfig; ipconfig.SetKey(shill::kAddressProperty, base::Value("0.0.0.0")); @@ -442,15 +439,6 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { kWifi2ServicePath, shill::kTetheringProperty, base::Value(shill::kTetheringNotDetectedState)); - AddService("stub_wimax", "wimax", shill::kTypeWimax, shill::kStateOnline); - service_test_->SetServiceProperty( - "stub_wimax", shill::kSignalStrengthProperty, base::Value(40)); - service_test_->SetServiceProperty("stub_wimax", shill::kProfileProperty, - base::Value(kUser1ProfilePath)); - service_test_->SetServiceProperty("stub_wimax", shill::kConnectableProperty, - base::Value(true)); - profile_test_->AddService(kUser1ProfilePath, "stub_wimax"); - base::ListValue frequencies2; frequencies2.AppendInteger(2400); frequencies2.AppendInteger(5000); @@ -573,8 +561,6 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetDeviceStates) { manager_test_->RemoveTechnology("cellular"); manager_test_->AddTechnology("cellular", false /* disabled */); manager_test_->SetTechnologyInitializing("cellular", true); - manager_test_->RemoveTechnology("wimax"); - manager_test_->AddTechnology("wimax", false /* disabled */); EXPECT_TRUE(RunNetworkingSubtest("getDeviceStates")) << message_; } diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc index 459f5333e41..5ccf99f3f54 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -59,7 +59,7 @@ class ExtensionNotificationHandlerTest : public testing::Test { ExtensionNotificationHandlerTest() {} private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(ExtensionNotificationHandlerTest, CloseHandler) { diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc index 4826ad17a57..427be63bed1 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc @@ -10,6 +10,8 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "chrome/browser/apps/app_service/app_launch_params.h" +#include "chrome/browser/apps/launch_service/launch_service.h" #include "chrome/browser/apps/platform_apps/app_browsertest_util.h" #include "chrome/browser/extensions/api/notifications/extension_notification_display_helper.h" #include "chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h" @@ -22,8 +24,6 @@ #include "chrome/browser/notifications/notifier_state_tracker.h" #include "chrome/browser/notifications/notifier_state_tracker_factory.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" #include "chrome/common/chrome_features.h" #include "chrome/test/base/interactive_test_utils.h" #include "content/public/browser/notification_service.h" @@ -205,11 +205,12 @@ class NotificationsApiTest : public extensions::ExtensionApiTest { } void LaunchPlatformApp(const Extension* extension) { - OpenApplication( - AppLaunchParams(browser()->profile(), extension->id(), - extensions::LaunchContainer::kLaunchContainerNone, - WindowOpenDisposition::NEW_WINDOW, - extensions::AppLaunchSource::kSourceTest)); + apps::LaunchService::Get(browser()->profile()) + ->OpenApplication( + AppLaunchParams(browser()->profile(), extension->id(), + apps::mojom::LaunchContainer::kLaunchContainerNone, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::AppLaunchSource::kSourceTest)); } std::unique_ptr<NotificationDisplayServiceTester> display_service_tester_; diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h index 27c7981cfc1..435ea6456f9 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h @@ -74,7 +74,7 @@ class ExtensionOmniboxEventRouter { DISALLOW_COPY_AND_ASSIGN(ExtensionOmniboxEventRouter); }; -class OmniboxSendSuggestionsFunction : public UIThreadExtensionFunction { +class OmniboxSendSuggestionsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("omnibox.sendSuggestions", OMNIBOX_SENDSUGGESTIONS) @@ -147,7 +147,7 @@ class OmniboxAPI : public BrowserContextKeyedAPI, template <> void BrowserContextKeyedAPIFactory<OmniboxAPI>::DeclareFactoryDependencies(); -class OmniboxSetDefaultSuggestionFunction : public UIThreadExtensionFunction { +class OmniboxSetDefaultSuggestionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("omnibox.setDefaultSuggestion", OMNIBOX_SETDEFAULTSUGGESTION) 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 1d92faec7e4..9ea3a3c7610 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 @@ -52,6 +52,7 @@ const char kPageCaptureNotAllowed[] = const char kUserDenied[] = "User denied request."; #endif constexpr base::TaskTraits kCreateTemporaryFileTaskTraits = { + base::ThreadPool(), // Requires IO. base::MayBlock(), @@ -74,7 +75,7 @@ PageCaptureSaveAsMHTMLFunction::PageCaptureSaveAsMHTMLFunction() { PageCaptureSaveAsMHTMLFunction::~PageCaptureSaveAsMHTMLFunction() { if (mhtml_file_.get()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ClearFileReferenceOnIOThread, std::move(mhtml_file_))); } @@ -118,7 +119,7 @@ bool PageCaptureSaveAsMHTMLFunction::RunAsync() { if (!CanCaptureCurrentPage()) { return false; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); @@ -179,7 +180,7 @@ bool PageCaptureSaveAsMHTMLFunction::OnMessageReceived( void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest( const PermissionIDSet& allowed_permissions) { if (allowed_permissions.ContainsID(APIPermission::kPageCapture)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); @@ -191,7 +192,7 @@ void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest( void PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile() { bool success = base::CreateTemporaryFile(&mhtml_path_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO, this, success)); @@ -204,8 +205,8 @@ void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO(bool success) { // once it is no longer used. mhtml_file_ = ShareableFileReference::GetOrCreate( mhtml_path_, ShareableFileReference::DELETE_ON_FINAL_RELEASE, - base::CreateSequencedTaskRunnerWithTraits( - {// Requires IO. + base::CreateSequencedTaskRunner( + {base::ThreadPool(), // Requires IO. base::MayBlock(), // TaskPriority: Inherit. @@ -217,7 +218,7 @@ void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO(bool success) { base::TaskShutdownBehavior::BLOCK_SHUTDOWN}) .get()); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnUI, this, success)); diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h index 5b944787663..b9521497512 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h @@ -17,7 +17,7 @@ namespace extensions { class PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction() {} DECLARE_EXTENSION_FUNCTION( @@ -35,8 +35,7 @@ class PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction); }; -class PasswordsPrivateChangeSavedPasswordFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateChangeSavedPasswordFunction : public ExtensionFunction { public: PasswordsPrivateChangeSavedPasswordFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.changeSavedPassword", @@ -52,8 +51,7 @@ class PasswordsPrivateChangeSavedPasswordFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateChangeSavedPasswordFunction); }; -class PasswordsPrivateRemoveSavedPasswordFunction : - public UIThreadExtensionFunction { +class PasswordsPrivateRemoveSavedPasswordFunction : public ExtensionFunction { public: PasswordsPrivateRemoveSavedPasswordFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.removeSavedPassword", @@ -69,8 +67,8 @@ class PasswordsPrivateRemoveSavedPasswordFunction : DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateRemoveSavedPasswordFunction); }; -class PasswordsPrivateRemovePasswordExceptionFunction : - public UIThreadExtensionFunction { +class PasswordsPrivateRemovePasswordExceptionFunction + : public ExtensionFunction { public: PasswordsPrivateRemovePasswordExceptionFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.removePasswordException", @@ -87,7 +85,7 @@ class PasswordsPrivateRemovePasswordExceptionFunction : }; class PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction() {} DECLARE_EXTENSION_FUNCTION( @@ -105,8 +103,8 @@ class PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction); }; -class PasswordsPrivateRequestPlaintextPasswordFunction : - public UIThreadExtensionFunction { +class PasswordsPrivateRequestPlaintextPasswordFunction + : public ExtensionFunction { public: PasswordsPrivateRequestPlaintextPasswordFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.requestPlaintextPassword", @@ -124,8 +122,7 @@ class PasswordsPrivateRequestPlaintextPasswordFunction : DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateRequestPlaintextPasswordFunction); }; -class PasswordsPrivateGetSavedPasswordListFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateGetSavedPasswordListFunction : public ExtensionFunction { public: PasswordsPrivateGetSavedPasswordListFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.getSavedPasswordList", @@ -145,7 +142,7 @@ class PasswordsPrivateGetSavedPasswordListFunction }; class PasswordsPrivateGetPasswordExceptionListFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateGetPasswordExceptionListFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.getPasswordExceptionList", @@ -164,8 +161,7 @@ class PasswordsPrivateGetPasswordExceptionListFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateGetPasswordExceptionListFunction); }; -class PasswordsPrivateImportPasswordsFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateImportPasswordsFunction : public ExtensionFunction { public: PasswordsPrivateImportPasswordsFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.importPasswords", @@ -181,8 +177,7 @@ class PasswordsPrivateImportPasswordsFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateImportPasswordsFunction); }; -class PasswordsPrivateExportPasswordsFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateExportPasswordsFunction : public ExtensionFunction { public: PasswordsPrivateExportPasswordsFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.exportPasswords", @@ -200,8 +195,7 @@ class PasswordsPrivateExportPasswordsFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateExportPasswordsFunction); }; -class PasswordsPrivateCancelExportPasswordsFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateCancelExportPasswordsFunction : public ExtensionFunction { public: PasswordsPrivateCancelExportPasswordsFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.cancelExportPasswords", @@ -218,7 +212,7 @@ class PasswordsPrivateCancelExportPasswordsFunction }; class PasswordsPrivateRequestExportProgressStatusFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateRequestExportProgressStatusFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.requestExportProgressStatus", diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc index 5ac9e7e8782..94758ce1b54 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc @@ -69,24 +69,10 @@ class TestDelegate : public PasswordsPrivateDelegate { } ~TestDelegate() override {} - void SendSavedPasswordsList() override { - PasswordsPrivateEventRouter* router = - PasswordsPrivateEventRouterFactory::GetForProfile(profile_); - if (router) - router->OnSavedPasswordsListChanged(current_entries_); - } - void GetSavedPasswordsList(UiEntriesCallback callback) override { std::move(callback).Run(current_entries_); } - void SendPasswordExceptionsList() override { - PasswordsPrivateEventRouter* router = - PasswordsPrivateEventRouterFactory::GetForProfile(profile_); - if (router) - router->OnPasswordExceptionsListChanged(current_exceptions_); - } - void GetPasswordExceptionsList( const ExceptionEntriesCallback& callback) override { callback.Run(current_exceptions_); @@ -181,6 +167,20 @@ class TestDelegate : public PasswordsPrivateDelegate { bool cancelExportPasswordsTriggered = false; private: + void SendSavedPasswordsList() { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) + router->OnSavedPasswordsListChanged(current_entries_); + } + + void SendPasswordExceptionsList() { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) + router->OnPasswordExceptionsListChanged(current_exceptions_); + } + // The current list of entries/exceptions. Cached here so that when new // observers are added, this delegate can send the current lists without // having to request them from |password_manager_presenter_| again. diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h index 9ea44f8d204..5c4bb1067a0 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h @@ -27,9 +27,9 @@ class WebContents; namespace extensions { -// Delegate used by the chrome.passwordsPrivate API to facilitate removing saved -// passwords and password exceptions and to notify listeners when these values -// have changed. +// Delegate used by the chrome.passwordsPrivate API to facilitate working with +// saved passwords and password exceptions (reading, changing, removing, +// import/export) and to notify listeners when these values have changed. class PasswordsPrivateDelegate : public KeyedService { public: using PlaintextPasswordCallback = @@ -37,17 +37,11 @@ class PasswordsPrivateDelegate : public KeyedService { ~PasswordsPrivateDelegate() override {} - // Sends the saved passwords list to the event router. - virtual void SendSavedPasswordsList() = 0; - // Gets the saved passwords list. using UiEntries = std::vector<api::passwords_private::PasswordUiEntry>; using UiEntriesCallback = base::OnceCallback<void(const UiEntries&)>; virtual void GetSavedPasswordsList(UiEntriesCallback callback) = 0; - // Sends the password exceptions list to the event router. - virtual void SendPasswordExceptionsList() = 0; - // Gets the password exceptions list. using ExceptionEntries = std::vector<api::passwords_private::ExceptionEntry>; using ExceptionEntriesCallback = diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h index 105f7e63375..03d191b747e 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h @@ -44,9 +44,7 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, ~PasswordsPrivateDelegateImpl() override; // PasswordsPrivateDelegate implementation. - void SendSavedPasswordsList() override; void GetSavedPasswordsList(UiEntriesCallback callback) override; - void SendPasswordExceptionsList() override; void GetPasswordExceptionsList( const ExceptionEntriesCallback& callback) override; void ChangeSavedPassword( @@ -99,6 +97,9 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, // has been initialized or by deferring it until initialization has completed. void ExecuteFunction(const base::Closure& callback); + void SendSavedPasswordsList(); + void SendPasswordExceptionsList(); + void RemoveSavedPasswordInternal(int id); void RemovePasswordExceptionInternal(int id); void UndoRemoveSavedPasswordOrExceptionInternal(); diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc index 84d25a7782d..274e5ac9496 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc @@ -25,7 +25,7 @@ #include "components/password_manager/core/browser/password_list_sorter.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/test_password_store.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/test_event_router.h" #include "testing/gtest/include/gtest/gtest.h" @@ -147,7 +147,7 @@ class PasswordsPrivateDelegateImplTest : public testing::Test { void SetUpRouters(); protected: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; extensions::TestEventRouter* event_router_ = nullptr; diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api.h b/chromium/chrome/browser/extensions/api/permissions/permissions_api.h index 87c04d94592..e25d14c49e0 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api.h +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api.h @@ -16,7 +16,7 @@ namespace extensions { // chrome.permissions.contains -class PermissionsContainsFunction : public UIThreadExtensionFunction { +class PermissionsContainsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.contains", PERMISSIONS_CONTAINS) @@ -28,7 +28,7 @@ class PermissionsContainsFunction : public UIThreadExtensionFunction { }; // chrome.permissions.getAll -class PermissionsGetAllFunction : public UIThreadExtensionFunction { +class PermissionsGetAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.getAll", PERMISSIONS_GETALL) @@ -40,7 +40,7 @@ class PermissionsGetAllFunction : public UIThreadExtensionFunction { }; // chrome.permissions.remove -class PermissionsRemoveFunction : public UIThreadExtensionFunction { +class PermissionsRemoveFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.remove", PERMISSIONS_REMOVE) @@ -52,7 +52,7 @@ class PermissionsRemoveFunction : public UIThreadExtensionFunction { }; // chrome.permissions.request -class PermissionsRequestFunction : public UIThreadExtensionFunction { +class PermissionsRequestFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.request", PERMISSIONS_REQUEST) diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc index e762b4a7776..02fb0b0860b 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc @@ -143,7 +143,7 @@ class PermissionsAPIUnitTest : public ExtensionServiceTestWithInstall { InitializeEmptyExtensionService(); browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); } diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h index b632e4e2700..4d1ece03673 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h @@ -33,7 +33,7 @@ std::string PlatformKeysTokenIdToApiId( } // namespace platform_keys class PlatformKeysInternalSelectClientCertificatesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~PlatformKeysInternalSelectClientCertificatesFunction() override; ResponseAction Run() override; @@ -47,8 +47,7 @@ class PlatformKeysInternalSelectClientCertificatesFunction PLATFORMKEYSINTERNAL_SELECTCLIENTCERTIFICATES) }; -class PlatformKeysInternalGetPublicKeyFunction - : public UIThreadExtensionFunction { +class PlatformKeysInternalGetPublicKeyFunction : public ExtensionFunction { private: ~PlatformKeysInternalGetPublicKeyFunction() override; ResponseAction Run() override; @@ -57,7 +56,7 @@ class PlatformKeysInternalGetPublicKeyFunction PLATFORMKEYSINTERNAL_GETPUBLICKEY) }; -class PlatformKeysInternalSignFunction : public UIThreadExtensionFunction { +class PlatformKeysInternalSignFunction : public ExtensionFunction { private: ~PlatformKeysInternalSignFunction() override; ResponseAction Run() override; @@ -71,7 +70,7 @@ class PlatformKeysInternalSignFunction : public UIThreadExtensionFunction { }; class PlatformKeysVerifyTLSServerCertificateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~PlatformKeysVerifyTLSServerCertificateFunction() override; ResponseAction Run() override; diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc index f6600316db6..2b6386c993b 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 @@ -53,7 +53,7 @@ class PlatformKeysTest : public PlatformKeysTestBase { // |PlatformKeysTestBase::SetUpOnMainThread| triggers the user sign-in. ASSERT_TRUE(user_private_slot_db_.is_open()); base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTest::SetPrivateSoftwareSlotOnIO, base::Unretained(this), @@ -188,11 +188,13 @@ class PlatformKeysTest : public PlatformKeysTestBase { EXPECT_EQ(user_private_slot_db_.slot(), cert_db->GetPrivateSlot().get()); EXPECT_NE(cert_db->GetPrivateSlot().get(), cert_db->GetPublicSlot().get()); - auto* slot = user_client_cert_slot_ == UserClientCertSlot::kPrivateSlot - ? cert_db->GetPrivateSlot().get() - : cert_db->GetPublicSlot().get(); + crypto::ScopedPK11Slot slot = + user_client_cert_slot_ == UserClientCertSlot::kPrivateSlot + ? cert_db->GetPrivateSlot() + : cert_db->GetPublicSlot(); client_cert1_ = net::ImportClientCertAndKeyFromFile( - net::GetTestCertsDirectory(), "client_1.pem", "client_1.pk8", slot); + net::GetTestCertsDirectory(), "client_1.pem", "client_1.pk8", + slot.get()); ASSERT_TRUE(client_cert1_.get()); // Import a second client cert signed by another CA than client_1 into the diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc index 305c68f0abf..166d76a626f 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc @@ -155,7 +155,7 @@ void PlatformKeysTestBase::SetUpOnMainThread() { if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTestBase::SetUpTestSystemSlotOnIO, base::Unretained(this), loop.QuitClosure())); @@ -170,7 +170,7 @@ void PlatformKeysTestBase::TearDownOnMainThread() { if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTestBase::TearDownTestSystemSlotOnIO, base::Unretained(this), loop.QuitClosure())); @@ -211,14 +211,14 @@ void PlatformKeysTestBase::SetUpTestSystemSlotOnIO( PrepareTestSystemSlotOnIO(test_system_slot_.get()); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(done_callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(done_callback)); } void PlatformKeysTestBase::TearDownTestSystemSlotOnIO( base::OnceClosure done_callback) { test_system_slot_.reset(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(done_callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(done_callback)); } diff --git a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc index d05673e9883..7462a0021d7 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc +++ b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc @@ -91,7 +91,7 @@ void BrowserContextKeyedAPIFactory< } VerifyTrustAPI::VerifyTrustAPI(content::BrowserContext* context) - : io_part_(new IOPart), registry_observer_(this), weak_factory_(this) { + : io_part_(new IOPart), registry_observer_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); registry_observer_.Add(ExtensionRegistry::Get(context)); } @@ -112,7 +112,7 @@ void VerifyTrustAPI::Verify(std::unique_ptr<Params> params, &CallBackOnUI, base::Bind(&VerifyTrustAPI::FinishedVerificationOnUI, weak_factory_.GetWeakPtr(), ui_callback))); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOPart::Verify, base::Unretained(io_part_.get()), base::Passed(¶ms), extension_id, finish_callback)); @@ -122,7 +122,7 @@ void VerifyTrustAPI::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionReason reason) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOPart::OnExtensionUnloaded, base::Unretained(io_part_.get()), extension->id())); @@ -142,9 +142,8 @@ void VerifyTrustAPI::CallBackOnUI(const VerifyCallback& ui_callback, const std::string& error, int return_value, int cert_status) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(ui_callback, error, return_value, cert_status)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(ui_callback, error, return_value, cert_status)); } VerifyTrustAPI::IOPart::~IOPart() { diff --git a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h index 85a022ff8c9..7c08e3d6a3e 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h +++ b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h @@ -100,7 +100,7 @@ class VerifyTrustAPI : public BrowserContextKeyedAPI, ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> registry_observer_; - base::WeakPtrFactory<VerifyTrustAPI> weak_factory_; + base::WeakPtrFactory<VerifyTrustAPI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VerifyTrustAPI); }; diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.h b/chromium/chrome/browser/extensions/api/preference/preference_api.h index 80d27cc4f79..086434a7653 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api.h +++ b/chromium/chrome/browser/extensions/api/preference/preference_api.h @@ -175,7 +175,7 @@ class PrefTransformerInterface { // A base class to provide functionality common to the other *PreferenceFunction // classes. -class PreferenceFunction : public UIThreadExtensionFunction { +class PreferenceFunction : public ExtensionFunction { protected: enum PermissionType { PERMISSION_TYPE_READ, PERMISSION_TYPE_WRITE }; diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc index 462bda64f31..093fa4fd495 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc @@ -509,7 +509,7 @@ ExtensionFunction::ResponseAction ProcessesTerminateFunction::Run() { // This could be a non-renderer child process like a plugin or a nacl // process. Try to get its handle from the BrowserChildProcessHost on the // IO thread. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {content::BrowserThread::IO}, base::Bind(&ProcessesTerminateFunction::GetProcessHandleOnIO, this, child_process_host_id_), diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.h b/chromium/chrome/browser/extensions/api/processes/processes_api.h index f1ef0d6870d..f72d0525e5b 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.h +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.h @@ -110,9 +110,9 @@ class ProcessesAPI : public BrowserContextKeyedAPI, //////////////////////////////////////////////////////////////////////////////// // This extension function returns the Process object for the renderer process // currently in use by the specified Tab. -class ProcessesGetProcessIdForTabFunction : public UIThreadExtensionFunction { +class ProcessesGetProcessIdForTabFunction : public ExtensionFunction { public: - // UIThreadExtensionFunction: + // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("processes.getProcessIdForTab", @@ -128,9 +128,9 @@ class ProcessesGetProcessIdForTabFunction : public UIThreadExtensionFunction { // Using unique IDs instead of OS process IDs allows two advantages: // * guaranteed uniqueness, since OS process IDs can be reused. // * guards against killing non-Chrome processes. -class ProcessesTerminateFunction : public UIThreadExtensionFunction { +class ProcessesTerminateFunction : public ExtensionFunction { public: - // UIThreadExtensionFunction: + // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("processes.terminate", PROCESSES_TERMINATE) @@ -157,13 +157,13 @@ class ProcessesTerminateFunction : public UIThreadExtensionFunction { //////////////////////////////////////////////////////////////////////////////// // Extension function which returns a set of Process objects, containing the // details corresponding to the process IDs supplied as input. -class ProcessesGetProcessInfoFunction : - public UIThreadExtensionFunction, - public task_manager::TaskManagerObserver { +class ProcessesGetProcessInfoFunction + : public ExtensionFunction, + public task_manager::TaskManagerObserver { public: ProcessesGetProcessInfoFunction(); - // UIThreadExtensionFunction: + // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; // task_manager::TaskManagerObserver: diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc index 9bb8242b4e7..3c7a5953cae 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc @@ -49,11 +49,12 @@ void ProxyEventRouter::OnProxyError( event_router->DispatchEventToRenderers( events::PROXY_ON_PROXY_ERROR, proxy_api_constants::kProxyEventOnProxyError, std::move(args), profile, - true, GURL()); + true, GURL(), false); } else { event_router->BroadcastEventToRenderers( events::PROXY_ON_PROXY_ERROR, - proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL()); + proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL(), + false); } } @@ -82,11 +83,12 @@ void ProxyEventRouter::OnPACScriptError( event_router->DispatchEventToRenderers( events::PROXY_ON_PROXY_ERROR, proxy_api_constants::kProxyEventOnProxyError, std::move(args), profile, - true, GURL()); + true, GURL(), false); } else { event_router->BroadcastEventToRenderers( events::PROXY_ON_PROXY_ERROR, - proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL()); + proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL(), + false); } } diff --git a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h index ce37f9dcb86..4440d65734f 100644 --- a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h +++ b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h @@ -10,7 +10,7 @@ namespace extensions { -class ResourcesPrivateGetStringsFunction : public UIThreadExtensionFunction { +class ResourcesPrivateGetStringsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("resourcesPrivate.getStrings", RESOURCESPRIVATE_GETSTRINGS) diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS b/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS index ba1319fe08a..fede9e2915a 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS @@ -1,3 +1,4 @@ +drubery@chromium.org nparker@chromium.org vakh@chromium.org diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc index 9ad16e7df19..579d813e1be 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc @@ -46,8 +46,8 @@ SafeBrowsingPrivateGetReferrerChainFunction::Run() { content::WebContents* contents = nullptr; if (!ExtensionTabUtil::GetTabById(params->tab_id, browser_context(), - include_incognito_information(), nullptr, - nullptr, &contents, nullptr)) { + include_incognito_information(), + &contents)) { return RespondNow(Error( base::StringPrintf("Could not find tab with id %d.", params->tab_id))); } diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h index d28ce05089d..13980a7608a 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h @@ -9,8 +9,7 @@ namespace extensions { -class SafeBrowsingPrivateGetReferrerChainFunction - : public UIThreadExtensionFunction { +class SafeBrowsingPrivateGetReferrerChainFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("safeBrowsingPrivate.getReferrerChain", SAFEBROWSINGPRIVATE_GETREFERRERCHAIN) diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc index e9e97071061..bafb52e22ec 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc @@ -25,7 +25,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/navigation_entry.h" #include "content/public/test/browser_side_navigation_test_utils.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/web_contents_tester.h" #include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_test_util.h" @@ -91,7 +91,7 @@ void SafeBrowsingPrivateApiUnitTest::SetUp() { browser_window_ = std::make_unique<TestBrowserWindow>(); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_ = std::make_unique<Browser>(params); diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc index 5516d33789c..7b0692cb8de 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc @@ -8,13 +8,22 @@ #include "base/strings/stringprintf.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/policy/browser_dm_token_storage.h" #include "chrome/browser/policy/chrome_browser_policy_connector.h" +#include "chrome/browser/policy/machine_level_user_cloud_policy_controller.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/signin/identity_manager_factory.h" #include "chrome/common/extensions/api/safe_browsing_private.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h" +#include "components/prefs/pref_service.h" +#include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "components/safe_browsing/proto/webprotect.pb.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/event_router.h" @@ -24,7 +33,7 @@ namespace extensions { const base::Feature SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature{ - "SafeBrowsingRealtimeReporting", base::FEATURE_DISABLED_BY_DEFAULT}; + "SafeBrowsingRealtimeReporting", base::FEATURE_ENABLED_BY_DEFAULT}; // Key names used with when building the dictionary to pass to the real-time // reporting API. @@ -41,6 +50,9 @@ const char SafeBrowsingPrivateEventRouter::kKeyReason[] = "reason"; const char SafeBrowsingPrivateEventRouter::kKeyNetErrorCode[] = "netErrorCode"; const char SafeBrowsingPrivateEventRouter::kKeyClickedThrough[] = "clickedThrough"; +const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRules[] = + "triggeredRules"; +const char SafeBrowsingPrivateEventRouter::kKeyThreatType[] = "threatType"; const char SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent[] = "passwordReuseEvent"; @@ -50,12 +62,51 @@ const char SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent[] = "dangerousDownloadEvent"; const char SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent[] = "interstitialEvent"; +const char SafeBrowsingPrivateEventRouter::kKeySensitiveDataEvent[] = + "sensitiveDataEvent"; +const char SafeBrowsingPrivateEventRouter::kKeyLargeUnscannedFileEvent[] = + "largeUnscannedFileEvent"; SafeBrowsingPrivateEventRouter::SafeBrowsingPrivateEventRouter( content::BrowserContext* context) : context_(context) { event_router_ = EventRouter::Get(context_); - InitRealtimeReportingClient(); + + // g_browser_process and/or g_browser_process->local_state() may be null + // in tests. + if (g_browser_process && g_browser_process->local_state()) { + RealtimeReportingPrefChanged(std::string()); + registrar_.Init(g_browser_process->local_state()); + registrar_.Add( + prefs::kUnsafeEventsReportingEnabled, + base::BindRepeating( + &SafeBrowsingPrivateEventRouter::RealtimeReportingPrefChanged, + base::Unretained(this))); + } +} + +// TODO(rogerta): once new event types are implemented, will likely want to +// move this to a more common place. +base::Value BuildRealtimeReport(Profile* profile, base::Value event) { + base::Value context(base::Value::Type::DICTIONARY); + + ProfileAttributesStorage& storage = + g_browser_process->profile_manager()->GetProfileAttributesStorage(); + ProfileAttributesEntry* entry = nullptr; + if (storage.GetProfileAttributesWithPath(profile->GetPath(), &entry)) { + context.SetStringPath("profile.profileName", entry->GetName()); + context.SetStringPath("profile.gaiaEmail", entry->GetUserName()); + } + + context.SetStringPath("profile.profilePath", profile->GetPath().value()); + context.SetStringPath("browser.userAgent", GetUserAgent()); + + base::Value report(base::Value::Type::DICTIONARY); + report.SetKey(policy::RealtimeReportingJobConfiguration::kContextKey, + std::move(context)); + report.SetKey(policy::RealtimeReportingJobConfiguration::kEventKey, + std::move(event)); + return report; } SafeBrowsingPrivateEventRouter::~SafeBrowsingPrivateEventRouter() {} @@ -83,7 +134,7 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordReuseDetected( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -108,7 +159,7 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordChanged( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUserName, user_name); @@ -139,7 +190,7 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadOpened( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -175,7 +226,7 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialShown( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -212,7 +263,7 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -224,6 +275,60 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded( } } +void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult( + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256, + const std::string& threat_type) { + if (IsRealtimeReportingEnabled()) { + // Create a real-time event dictionary from the arguments and report it. + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetStringKey(kKeyFileName, file_name); + event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + event.SetStringKey(kKeyThreatType, threat_type); + ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event)); + } +} + +void SafeBrowsingPrivateEventRouter::OnSensitiveDataEvent( + const safe_browsing::DlpDeepScanningVerdict& verdict, + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256) { + if (IsRealtimeReportingEnabled()) { + // Create a real-time event dictionary from the arguments and report it. + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetStringKey(kKeyFileName, file_name); + event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + + base::ListValue triggered_rules; + for (auto rule : verdict.triggered_rules()) { + triggered_rules.AppendString(rule.rule_name()); + } + event.SetKey(kKeyTriggeredRules, std::move(triggered_rules)); + ReportRealtimeEvent(kKeySensitiveDataEvent, std::move(event)); + } +} + +void SafeBrowsingPrivateEventRouter::OnLargeUnscannedFileEvent( + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256) { + if (IsRealtimeReportingEnabled()) { + // Create a real-time event dictionary from the arguments and report it. + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetStringKey(kKeyFileName, file_name); + event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + ReportRealtimeEvent(kKeyLargeUnscannedFileEvent, std::move(event)); + } +} + void SafeBrowsingPrivateEventRouter::SetCloudPolicyClientForTesting( std::unique_ptr<policy::CloudPolicyClient> client) { DCHECK_EQ(nullptr, client_.get()); @@ -231,6 +336,20 @@ void SafeBrowsingPrivateEventRouter::SetCloudPolicyClientForTesting( } void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() { +#if !defined(OS_CHROMEOS) + // This method is not compiled on chromeos because + // MachineLevelUserCloudPolicyController does not exist. Also, + // policy::BrowserDMTokenStorage::Get()->RetrieveDMToken() does return a + // valid token either. Once these are fixed the #if !define can be removed. + // If already initialized, do nothing. + if (client_) + return; + + if (!policy::MachineLevelUserCloudPolicyController:: + IsMachineLevelUserCloudPolicyEnabled()) { + return; + } + if (!base::FeatureList::IsEnabled(kRealtimeReportingFeature)) return; @@ -242,7 +361,7 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() { if (!identity_manager_) return; - // |device_management_service| may be null in tests. If there is no device + // |device_management_service| may be null in tests. If there is no device // management service don't enable the real-time reporting API since the // router won't be able to create the reporting server client below. policy::DeviceManagementService* device_management_service = @@ -284,6 +403,22 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() { dm_token, client_id, /*user_affiliation_ids=*/std::vector<std::string>()); } +#endif +} + +bool SafeBrowsingPrivateEventRouter::IsRealtimeReportingEnabled() { + // g_browser_process and/or g_browser_process->local_state() may be null + // in tests. + return g_browser_process && g_browser_process->local_state() && + g_browser_process->local_state()->GetBoolean( + prefs::kUnsafeEventsReportingEnabled); +} + +void SafeBrowsingPrivateEventRouter::RealtimeReportingPrefChanged( + const std::string& pref) { + // If the reporting policy has been turned on, try to initialized now. + if (IsRealtimeReportingEnabled()) + InitRealtimeReportingClient(); } void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent(const char* name, @@ -300,7 +435,10 @@ void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent(const char* name, wrapper.SetStringKey("time", now_str); wrapper.SetKey(name, std::move(event)); - client_->UploadRealtimeReport(std::move(wrapper), base::DoNothing()); + client_->UploadRealtimeReport( + BuildRealtimeReport(Profile::FromBrowserContext(context_), + std::move(wrapper)), + base::DoNothing()); } std::string SafeBrowsingPrivateEventRouter::GetProfileUserName() { diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h index aa247397917..9a3441613dc 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h @@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/values.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/prefs/pref_change_registrar.h" namespace content { class BrowserContext; @@ -31,6 +32,10 @@ namespace policy { class CloudPolicyClient; } +namespace safe_browsing { +class DlpDeepScanningVerdict; +} + namespace extensions { // An event router that observes Safe Browsing events and notifies listeners. @@ -52,11 +57,15 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { static const char kKeyReason[]; static const char kKeyNetErrorCode[]; static const char kKeyClickedThrough[]; + static const char kKeyTriggeredRules[]; + static const char kKeyThreatType[]; static const char kKeyPasswordReuseEvent[]; static const char kKeyPasswordChangedEvent[]; static const char kKeyDangerousDownloadEvent[]; static const char kKeyInterstitialEvent[]; + static const char kKeySensitiveDataEvent[]; + static const char kKeyLargeUnscannedFileEvent[]; explicit SafeBrowsingPrivateEventRouter(content::BrowserContext* context); @@ -86,6 +95,24 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { const std::string& reason, int net_error_code); + // Notifies listeners that deep scanning detected a dangerous download. + void OnDangerousDeepScanningResult(const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256, + const std::string& threat_type); + + // Notifies listeners that scanning for sensitive data detected a violation. + void OnSensitiveDataEvent( + const safe_browsing::DlpDeepScanningVerdict& verdict, + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256); + + // Notifies listeners that deep scanning failed, since the file was too large. + void OnLargeUnscannedFileEvent(const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256); + void SetCloudPolicyClientForTesting( std::unique_ptr<policy::CloudPolicyClient> client); @@ -95,6 +122,12 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { // with CBCM and the appropriate policies are enabled. void InitRealtimeReportingClient(); + // Determines if the real-time reporting feature is enabled. + bool IsRealtimeReportingEnabled(); + + // Called whenever the real-time reporting policy changes. + void RealtimeReportingPrefChanged(const std::string& pref); + // Report safe browsing event through real-time reporting channel, if enabled. void ReportRealtimeEvent(const char* name, base::Value event); @@ -106,6 +139,7 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { signin::IdentityManager* identity_manager_ = nullptr; EventRouter* event_router_ = nullptr; std::unique_ptr<policy::CloudPolicyClient> client_; + PrefChangeRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouter); }; diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc index bf6702672f3..26c8393207c 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc @@ -6,13 +6,16 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/test/mock_callback.h" -#include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h" #include "chrome/common/extensions/api/safe_browsing_private.h" +#include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" +#include "chrome/test/base/testing_profile_manager.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h" +#include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/test_event_router.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -67,64 +70,77 @@ std::unique_ptr<KeyedService> BuildSafeBrowsingPrivateEventRouter( class SafeBrowsingPrivateEventRouterTest : public testing::Test { public: - SafeBrowsingPrivateEventRouterTest() = default; + SafeBrowsingPrivateEventRouterTest() + : profile_manager_(TestingBrowserProcess::GetGlobal()) { + EXPECT_TRUE(profile_manager_.SetUp()); + profile_ = profile_manager_.CreateTestingProfile("test-user"); + } + ~SafeBrowsingPrivateEventRouterTest() override = default; void TriggerOnPolicySpecifiedPasswordReuseDetectedEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnPolicySpecifiedPasswordReuseDetected(GURL("https://phishing.com/"), "user_name_1", /*is_phishing_url*/ true); } void TriggerOnPolicySpecifiedPasswordChangedEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnPolicySpecifiedPasswordChanged("user_name_2"); } void TriggerOnDangerousDownloadOpenedEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnDangerousDownloadOpened(GURL("https://evil.com/malware.exe"), "/path/to/malware.exe", "sha256_or_malware_exe"); } void TriggerOnSecurityInterstitialShownEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnSecurityInterstitialShown(GURL("https://phishing.com/"), "PHISHING", 0); } void TriggerOnSecurityInterstitialProceededEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnSecurityInterstitialProceeded(GURL("https://phishing.com/"), "PHISHING", -201); } - void SetUpRouters() { - event_router_ = extensions::CreateAndUseTestEventRouter(&profile_); - SafeBrowsingPrivateEventRouterFactory::GetInstance()->SetTestingFactory( - &profile_, base::BindRepeating(&BuildSafeBrowsingPrivateEventRouter)); + void SetReportingPolicy(bool enabled) { + TestingBrowserProcess::GetGlobal()->local_state()->SetBoolean( + prefs::kUnsafeEventsReportingEnabled, enabled); - // Make sure real-time feature is eanbled so that the tests will run. - scoped_feature_list_.InitAndEnableFeature( - SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature); + // If we are not enabling reporting, or if the client has already been + // set for testing, just return. + if (!enabled || client_) + return; // Set a mock cloud policy client in the router. The router will own the // client, but a pointer to the client is maintained in the test class to // manage expectations. client_ = new policy::MockCloudPolicyClient(); std::unique_ptr<policy::CloudPolicyClient> client(client_); - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->SetCloudPolicyClientForTesting(std::move(client)); } + void SetUpRouters(bool realtime_reporting_enable = true) { + event_router_ = extensions::CreateAndUseTestEventRouter(profile_); + SafeBrowsingPrivateEventRouterFactory::GetInstance()->SetTestingFactory( + profile_, base::BindRepeating(&BuildSafeBrowsingPrivateEventRouter)); + + SetReportingPolicy(realtime_reporting_enable); + } + protected: - content::TestBrowserThreadBundle thread_bundle_; - base::test::ScopedFeatureList scoped_feature_list_; - TestingProfile profile_; + content::BrowserTaskEnvironment task_environment_; + TestingProfileManager profile_manager_; + TestingProfile* profile_; extensions::TestEventRouter* event_router_ = nullptr; - policy::MockCloudPolicyClient* client_; + policy::MockCloudPolicyClient* client_ = nullptr; private: DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouterTest); @@ -137,9 +153,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnReuseDetected) { kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnPolicySpecifiedPasswordReuseDetectedEvent(); base::RunLoop().RunUntilIdle(); @@ -149,9 +165,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnReuseDetected) { EXPECT_EQ("user_name_1", captured_args.FindKey("userName")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent); + wrapper->FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("https://phishing.com/", *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyUrl)); @@ -165,9 +185,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordChanged) { api::safe_browsing_private::OnPolicySpecifiedPasswordChanged::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnPolicySpecifiedPasswordChangedEvent(); base::RunLoop().RunUntilIdle(); @@ -176,9 +196,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordChanged) { EXPECT_EQ("user_name_2", captured_args.GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); - base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); + base::Value* event = wrapper->FindKey( + SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("user_name_2", *event->FindStringKey( SafeBrowsingPrivateEventRouter::kKeyUserName)); @@ -190,9 +214,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) { api::safe_browsing_private::OnDangerousDownloadOpened::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnDangerousDownloadOpenedEvent(); base::RunLoop().RunUntilIdle(); @@ -207,8 +231,12 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) { captured_args.FindKey("downloadDigestSha256")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); - base::Value* event = wrapper.FindKey( + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); + base::Value* event = wrapper->FindKey( SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent); EXPECT_NE(nullptr, event); EXPECT_EQ( @@ -223,9 +251,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, api::safe_browsing_private::OnSecurityInterstitialProceeded::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnSecurityInterstitialProceededEvent(); base::RunLoop().RunUntilIdle(); @@ -237,9 +265,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, EXPECT_EQ("", captured_args.FindKey("userName")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); + wrapper->FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("PHISHING", *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason)); @@ -255,9 +287,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) { api::safe_browsing_private::OnSecurityInterstitialShown::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnSecurityInterstitialShownEvent(); base::RunLoop().RunUntilIdle(); @@ -269,9 +301,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) { EXPECT_EQ("", captured_args.FindKey("userName")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); + wrapper->FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("PHISHING", *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason)); @@ -280,4 +316,45 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) { EXPECT_FALSE( *event->FindBoolKey(SafeBrowsingPrivateEventRouter::kKeyClickedThrough)); } + +TEST_F(SafeBrowsingPrivateEventRouterTest, PolicyControlOnToOffIsDynamic) { + SetUpRouters(); + SafeBrowsingEventObserver event_observer( + api::safe_browsing_private::OnSecurityInterstitialShown::kEventName); + event_router_->AddEventObserver(&event_observer); + + EXPECT_CALL(*client_, UploadRealtimeReport(_, _)).Times(1); + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + Mock::VerifyAndClearExpectations(client_); + + // Now turn off policy. This time no report should be generated. + SetReportingPolicy(false); + EXPECT_CALL(*client_, UploadRealtimeReport(_, _)).Times(0); + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + Mock::VerifyAndClearExpectations(client_); +} + +TEST_F(SafeBrowsingPrivateEventRouterTest, PolicyControlOffToOnIsDynamic) { + SetUpRouters(/*realtime_reporting_enable=*/false); + SafeBrowsingEventObserver event_observer( + api::safe_browsing_private::OnSecurityInterstitialShown::kEventName); + event_router_->AddEventObserver(&event_observer); + + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + + // Now turn on policy. + SetReportingPolicy(true); + EXPECT_CALL(*client_, UploadRealtimeReport(_, _)).Times(1); + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + Mock::VerifyAndClearExpectations(client_); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc index 7156357f02b..882f22b3fdf 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc @@ -81,7 +81,8 @@ api::tabs::Tab CreateTabModelHelper( int index, bool pinned, bool active, - const Extension* extension) { + const Extension* extension, + Feature::Context context) { api::tabs::Tab tab_struct; const GURL& url = current_navigation.virtual_url(); @@ -100,7 +101,13 @@ api::tabs::Tab CreateTabModelHelper( tab_struct.index = index; tab_struct.pinned = pinned; tab_struct.active = active; - ExtensionTabUtil::ScrubTabForExtension(extension, nullptr, &tab_struct); + + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, context, url); + if (scrub_tab_behavior != ExtensionTabUtil::kDontScrubTab) { + ExtensionTabUtil::ScrubTabForExtension(extension, nullptr, &tab_struct, + scrub_tab_behavior); + } return tab_struct; } @@ -148,7 +155,7 @@ api::tabs::Tab SessionsGetRecentlyClosedFunction::CreateTabModel( return CreateTabModelHelper(tab.navigations[tab.current_navigation_index], base::NumberToString(tab.id.id()), tab.tabstrip_index, tab.pinned, active, - extension()); + extension(), source_context_type()); } std::unique_ptr<api::windows::Window> @@ -228,7 +235,7 @@ api::tabs::Tab SessionsGetDevicesFunction::CreateTabModel( std::string session_id = SessionId(session_tag, tab.tab_id.id()).ToString(); return CreateTabModelHelper( tab.navigations[tab.normalized_navigation_index()], session_id, tab_index, - tab.pinned, active, extension()); + tab.pinned, active, extension(), source_context_type()); } std::unique_ptr<api::windows::Window> @@ -269,12 +276,18 @@ SessionsGetDevicesFunction::CreateWindowModel( api::windows::WindowType type = api::windows::WINDOW_TYPE_NONE; switch (window.type) { - case sessions::SessionWindow::TYPE_TABBED: + case sessions::SessionWindow::TYPE_NORMAL: type = api::windows::WINDOW_TYPE_NORMAL; break; case sessions::SessionWindow::TYPE_POPUP: type = api::windows::WINDOW_TYPE_POPUP; break; + case sessions::SessionWindow::TYPE_APP: + type = api::windows::WINDOW_TYPE_APP; + break; + case sessions::SessionWindow::TYPE_DEVTOOLS: + type = api::windows::WINDOW_TYPE_DEVTOOLS; + break; } api::windows::WindowState state = api::windows::WINDOW_STATE_NONE; @@ -383,8 +396,11 @@ ExtensionFunction::ResponseAction SessionsGetDevicesFunction::Run() { ExtensionFunction::ResponseValue SessionsRestoreFunction::GetRestoredTabResult( content::WebContents* contents) { + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension(), source_context_type(), + contents); std::unique_ptr<api::tabs::Tab> tab(ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension())); + contents, scrub_tab_behavior, extension())); std::unique_ptr<api::sessions::Session> restored_session( CreateSessionModelHelper(base::Time::Now().ToTimeT(), std::move(tab), std::unique_ptr<api::windows::Window>())); @@ -401,7 +417,8 @@ SessionsRestoreFunction::GetRestoredWindowResult(int window_id) { } std::unique_ptr<base::DictionaryValue> window_value( ExtensionTabUtil::CreateWindowValueForExtension( - *browser, extension(), ExtensionTabUtil::kPopulateTabs)); + *browser, extension(), ExtensionTabUtil::kPopulateTabs, + source_context_type())); std::unique_ptr<api::windows::Window> window( api::windows::Window::FromValue(*window_value)); return ArgumentList(Restore::Results::Create(*CreateSessionModelHelper( diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h index d859f6434bb..6d177c1ce6e 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h @@ -27,7 +27,7 @@ namespace extensions { class SessionId; -class SessionsGetRecentlyClosedFunction : public UIThreadExtensionFunction { +class SessionsGetRecentlyClosedFunction : public ExtensionFunction { protected: ~SessionsGetRecentlyClosedFunction() override {} ResponseAction Run() override; @@ -43,7 +43,7 @@ class SessionsGetRecentlyClosedFunction : public UIThreadExtensionFunction { const sessions::TabRestoreService::Entry& entry); }; -class SessionsGetDevicesFunction : public UIThreadExtensionFunction { +class SessionsGetDevicesFunction : public ExtensionFunction { protected: ~SessionsGetDevicesFunction() override {} ResponseAction Run() override; @@ -64,7 +64,7 @@ class SessionsGetDevicesFunction : public UIThreadExtensionFunction { const sync_sessions::SyncedSession* session); }; -class SessionsRestoreFunction : public UIThreadExtensionFunction { +class SessionsRestoreFunction : public ExtensionFunction { protected: ~SessionsRestoreFunction() override {} ResponseAction Run() override; diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc index 3d9892b6d8b..ed9c0d567e0 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc @@ -190,7 +190,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, OverridenDSEPersists) { std::string new_tab_url_ext = ext_turl.new_tab_url_ref().ReplaceSearchTerms( TemplateURLRef::SearchTermsArgs(base::string16()), - UIThreadSearchTermsData(profile)); + UIThreadSearchTermsData()); EXPECT_EQ(new_tab_url_ext, search::GetNewTabPageURL(profile).spec()); diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc index 620e7fa6e2f..9e1dae7356f 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc @@ -42,11 +42,14 @@ void GeneratedTimeZonePrefBase::UpdateTimeZonePrefControlledBy( IsTimeZoneResolutionPolicyControlled()) { out_pref->controlled_by = settings_api::CONTROLLED_BY_DEVICE_POLICY; out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED; - } else if (profile_->IsChild() && - !base::FeatureList::IsEnabled( - features::kParentAccessCodeForTimeChange)) { - out_pref->controlled_by = settings_api::ControlledBy::CONTROLLED_BY_PARENT; - out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED; + } else if (profile_->IsChild()) { + out_pref->controlled_by = settings_api::CONTROLLED_BY_PARENT; + if (base::FeatureList::IsEnabled( + features::kParentAccessCodeForTimeChange)) { + out_pref->enforcement = settings_api::ENFORCEMENT_PARENT_SUPERVISED; + } else { + out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED; + } } else if (!profile_->IsSameProfile( ProfileManager::GetPrimaryUserProfile())) { out_pref->controlled_by = settings_api::CONTROLLED_BY_PRIMARY_USER; diff --git a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc index f41d39b5833..40e299858d2 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/settings_private/prefs_util.h" #include "base/feature_list.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/settings_private/generated_prefs.h" @@ -50,11 +51,10 @@ #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/settings/supervised_user_cros_settings_provider.h" #include "chrome/browser/chromeos/system/timezone_util.h" #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h" #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/settings/cros_settings_names.h" @@ -83,8 +83,9 @@ bool IsRestrictedCrosSettingForChildUser(Profile* profile, if (!profile->IsChild()) return false; - return SupervisedUserServiceFactory::GetForProfile(profile) - ->IsRestrictedCrosSettingForChildUser(pref_name); + return chromeos::CrosSettings::Get() + ->supervised_user_cros_settings_provider() + ->HandlesSetting(pref_name); } const base::Value* GetRestrictedCrosSettingValueForChildUser( @@ -94,8 +95,9 @@ const base::Value* GetRestrictedCrosSettingValueForChildUser( // pre-set. DCHECK(IsRestrictedCrosSettingForChildUser(profile, pref_name)); - return SupervisedUserServiceFactory::GetForProfile(profile) - ->GetRestrictedCrosSettingValueForChildUser(pref_name); + return chromeos::CrosSettings::Get() + ->supervised_user_cros_settings_provider() + ->Get(pref_name); } #endif @@ -230,6 +232,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[password_manager::prefs::kCredentialsEnableAutosignin] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[password_manager::prefs::kPasswordLeakDetectionEnabled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; // Privacy page (*s_whitelist)[::prefs::kSigninAllowedOnNextStartup] = @@ -410,6 +414,9 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessAutoScanSpeedMs] = settings_api::PrefType::PREF_TYPE_NUMBER; + (*s_whitelist) + [ash::prefs::kAccessibilitySwitchAccessAutoScanKeyboardSpeedMs] = + settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[ash::prefs::kAccessibilityVirtualKeyboardEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[ash::prefs::kAccessibilityMonoAudioEnabled] = @@ -444,13 +451,13 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[chromeos::assistant::prefs::kAssistantDisabledByPolicy] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[arc::prefs::kVoiceInteractionEnabled] = + (*s_whitelist)[chromeos::assistant::prefs::kAssistantEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[arc::prefs::kVoiceInteractionContextEnabled] = + (*s_whitelist)[chromeos::assistant::prefs::kAssistantContextEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[chromeos::assistant::prefs::kAssistantHotwordAlwaysOn] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[arc::prefs::kVoiceInteractionHotwordEnabled] = + (*s_whitelist)[chromeos::assistant::prefs::kAssistantHotwordEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[chromeos::assistant::prefs::kAssistantLaunchWithMicOpen] = settings_api::PrefType::PREF_TYPE_BOOLEAN; @@ -470,7 +477,9 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[prefs::kRestoreLastLockScreenNote] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[ash::prefs::kLockScreenMediaKeysEnabled] = + (*s_whitelist)[::prefs::kSettingsShowBrowserBanner] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kSettingsShowOSBanner] = settings_api::PrefType::PREF_TYPE_BOOLEAN; // Bluetooth & Internet settings. @@ -546,6 +555,10 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kMouseReverseScroll] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kMouseAcceleration] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kTouchpadAcceleration] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kMouseSensitivity] = settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[::prefs::kLanguageRemapSearchKeyTo] = @@ -578,8 +591,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_DICTIONARY; (*s_whitelist)[chromeos::kDisplayRotationDefault] = settings_api::PrefType::PREF_TYPE_DICTIONARY; - (*s_whitelist)[arc::prefs::kArcHasAccessToRemovableMedia] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[arc::prefs::kArcVisibleExternalStorages] = + settings_api::PrefType::PREF_TYPE_LIST; // Native Printing settings. (*s_whitelist)[::prefs::kUserNativePrintersAllowed] = @@ -612,12 +625,12 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { (*s_whitelist)[proxy_config::prefs::kProxy] = settings_api::PrefType::PREF_TYPE_DICTIONARY; -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) (*s_whitelist)[::prefs::kMediaRouterEnableCloudServices] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kUserFeedbackAllowed] = settings_api::PrefType::PREF_TYPE_BOOLEAN; -#endif // defined(GOOGLE_CHROME_BUILD) +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) // Media Remoting settings. (*s_whitelist)[::prefs::kMediaRouterMediaRemotingEnabled] = @@ -773,7 +786,7 @@ std::unique_ptr<settings_api::PrefObject> PrefsUtil::GetPref( if (IsRestrictedCrosSettingForChildUser(profile_, name)) { pref_object->controlled_by = - settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTIONS; + settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTION; pref_object->enforcement = settings_api::Enforcement::ENFORCEMENT_ENFORCED; pref_object->value = std::make_unique<base::Value>( GetRestrictedCrosSettingValueForChildUser(profile_, name)->Clone()); diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h index f9a377d7a86..ec333f223f1 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h @@ -13,7 +13,7 @@ namespace extensions { // Implements the chrome.settingsPrivate.setPref method. -class SettingsPrivateSetPrefFunction : public UIThreadExtensionFunction { +class SettingsPrivateSetPrefFunction : public ExtensionFunction { public: SettingsPrivateSetPrefFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.setPref", SETTINGSPRIVATE_SETPREF) @@ -21,14 +21,14 @@ class SettingsPrivateSetPrefFunction : public UIThreadExtensionFunction { protected: ~SettingsPrivateSetPrefFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateSetPrefFunction); }; // Implements the chrome.settingsPrivate.getAllPrefs method. -class SettingsPrivateGetAllPrefsFunction : public UIThreadExtensionFunction { +class SettingsPrivateGetAllPrefsFunction : public ExtensionFunction { public: SettingsPrivateGetAllPrefsFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.getAllPrefs", @@ -37,14 +37,14 @@ class SettingsPrivateGetAllPrefsFunction : public UIThreadExtensionFunction { protected: ~SettingsPrivateGetAllPrefsFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetAllPrefsFunction); }; // Implements the chrome.settingsPrivate.getPref method. -class SettingsPrivateGetPrefFunction : public UIThreadExtensionFunction { +class SettingsPrivateGetPrefFunction : public ExtensionFunction { public: SettingsPrivateGetPrefFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.getPref", SETTINGSPRIVATE_GETPREF) @@ -52,15 +52,14 @@ class SettingsPrivateGetPrefFunction : public UIThreadExtensionFunction { protected: ~SettingsPrivateGetPrefFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetPrefFunction); }; // Implements the chrome.settingsPrivate.getDefaultZoom method. -class SettingsPrivateGetDefaultZoomFunction - : public UIThreadExtensionFunction { +class SettingsPrivateGetDefaultZoomFunction : public ExtensionFunction { public: SettingsPrivateGetDefaultZoomFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.getDefaultZoom", @@ -69,15 +68,14 @@ class SettingsPrivateGetDefaultZoomFunction protected: ~SettingsPrivateGetDefaultZoomFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetDefaultZoomFunction); }; // Implements the chrome.settingsPrivate.setDefaultZoom method. -class SettingsPrivateSetDefaultZoomFunction - : public UIThreadExtensionFunction { +class SettingsPrivateSetDefaultZoomFunction : public ExtensionFunction { public: SettingsPrivateSetDefaultZoomFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.setDefaultZoom", @@ -86,7 +84,7 @@ class SettingsPrivateSetDefaultZoomFunction protected: ~SettingsPrivateSetDefaultZoomFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateSetDefaultZoomFunction); diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc index 6b7a7b7f1c6..877aebd6539 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc @@ -3,7 +3,6 @@ // found in the LICENSE file. #include "base/values.h" -#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" #include "chrome/browser/chromeos/login/test/guest_session_mixin.h" #include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h" #include "chrome/browser/extensions/api/settings_private/settings_private_api.h" @@ -13,14 +12,14 @@ #include "chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" +#include "chrome/test/base/mixin_based_in_process_browser_test.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { namespace { -class SettingsPrivateGuestModeTest - : public chromeos::MixinBasedInProcessBrowserTest { +class SettingsPrivateGuestModeTest : public MixinBasedInProcessBrowserTest { protected: chromeos::GuestSessionMixin guest_session_{&mixin_host_}; }; diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h index b24066be1e8..c46442ec14b 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h @@ -37,7 +37,7 @@ std::vector<std::unique_ptr<syncer::DeviceInfo>> GetAllSignedInDevices( syncer::DeviceInfoTracker* device_tracker, ExtensionPrefs* extension_prefs); -class SignedInDevicesGetFunction : public UIThreadExtensionFunction { +class SignedInDevicesGetFunction : public ExtensionFunction { protected: ~SignedInDevicesGetFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc index ad64682385f..1d5d4eac138 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc @@ -20,7 +20,7 @@ #include "components/sync_device_info/device_info.h" #include "components/sync_device_info/device_info_sync_service.h" #include "components/sync_device_info/fake_device_info_tracker.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -32,7 +32,7 @@ using testing::Return; namespace extensions { TEST(SignedInDevicesAPITest, GetSignedInDevices) { - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; TestingProfile profile; FakeDeviceInfoTracker device_tracker; TestExtensionPrefs extension_prefs(base::ThreadTaskRunnerHandle::Get().get()); diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc index 17081c07d58..73286a5e48d 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc @@ -14,7 +14,7 @@ #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_store.h" #include "components/signin/public/identity_manager/identity_test_environment.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/event_router.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,7 +23,7 @@ namespace extensions { // Adds a listener and removes it. TEST(SignedInDevicesManager, UpdateListener) { - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; std::unique_ptr<TestingProfile> profile = IdentityTestEnvironmentProfileAdaptor:: diff --git a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc index 5baa299ebe1..10356bc10a2 100644 --- a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc @@ -38,13 +38,13 @@ class UDPSocketUnitTest : public extensions::ExtensionServiceTestBase { content::BrowserContext::GetDefaultStoragePartition(profile()) ->GetNetworkContext(); network::mojom::UDPSocketPtrInfo socket; - network::mojom::UDPSocketReceiverPtr receiver_ptr; - network::mojom::UDPSocketReceiverRequest receiver_request = - mojo::MakeRequest(&receiver_ptr); + network::mojom::UDPSocketListenerPtr listener_ptr; + network::mojom::UDPSocketListenerRequest listener_request = + mojo::MakeRequest(&listener_ptr); network_context->CreateUDPSocket(mojo::MakeRequest(&socket), - std::move(receiver_ptr)); + std::move(listener_ptr)); return std::make_unique<UDPSocket>( - std::move(socket), std::move(receiver_request), "abcdefghijklmnopqrst"); + std::move(socket), std::move(listener_request), "abcdefghijklmnopqrst"); } }; @@ -174,7 +174,7 @@ TEST_F(UDPSocketUnitTest, TestUDPMulticastRecv) { std::unique_ptr<UDPSocket> src = CreateSocket(); std::unique_ptr<UDPSocket> dest = CreateSocket(); - // Receiver + // Listener { net::TestCompletionCallback callback; dest->Bind("0.0.0.0", kPort, callback.callback()); diff --git a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc index ef8acf121ef..91b42ede413 100644 --- a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc +++ b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc @@ -205,9 +205,9 @@ void ManagedValueStoreCache::ExtensionTracker::LoadSchemasOnFileTaskRunner( (*components)[(*it)->id()] = schema; } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ExtensionTracker::Register, self, - base::Owned(components.release()))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ExtensionTracker::Register, self, + base::Owned(components.release()))); } void ManagedValueStoreCache::ExtensionTracker::Register( 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 c0ff25c4e0c..0da80d2208f 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 @@ -15,7 +15,7 @@ #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/settings_observer.h" @@ -126,7 +126,7 @@ class PolicyValueStoreTest : public testing::Test { } base::ScopedTempDir scoped_temp_dir_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<PolicyValueStore> store_; MockSettingsObserver observer_; scoped_refptr<SettingsObserverList> observers_; @@ -174,7 +174,7 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { const base::Value value("111"); { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("aaa", nullptr, value.CreateDeepCopy())); + changes.push_back(ValueStoreChange("aaa", base::nullopt, value.Clone())); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, @@ -190,7 +190,7 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { // Notify when new policies are added. { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("bbb", nullptr, value.CreateDeepCopy())); + changes.push_back(ValueStoreChange("bbb", base::nullopt, value.Clone())); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, @@ -206,8 +206,8 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { const base::Value new_value("222"); { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("bbb", value.CreateDeepCopy(), - new_value.CreateDeepCopy())); + changes.push_back( + ValueStoreChange("bbb", value.Clone(), new_value.Clone())); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, @@ -224,7 +224,7 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange("bbb", new_value.CreateDeepCopy(), nullptr)); + ValueStoreChange("bbb", new_value.Clone(), base::nullopt)); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, 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 3d81dd4973e..12638792609 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc @@ -22,7 +22,7 @@ #include "components/sync/model/sync_change_processor_wrapper_for_test.h" #include "components/sync/model/sync_error_factory.h" #include "components/sync/model/sync_error_factory_mock.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/settings_test_util.h" @@ -261,7 +261,7 @@ class ExtensionSettingsSyncTest : public testing::Test { } // Needed so that the DCHECKs for running on FILE or UI threads pass. - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; std::unique_ptr<TestingProfile> profile_; diff --git a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc index 7088ea82779..28d68f7dced 100644 --- a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc +++ b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc @@ -191,7 +191,7 @@ syncer::SyncError SyncableSettingsStorage::SendLocalSettingsToSync( std::string key = base::DictionaryValue::Iterator(*local_state).key(); std::unique_ptr<base::Value> value; local_state->RemoveWithoutPathExpansion(key, &value); - changes.push_back(ValueStoreChange(key, nullptr, std::move(value))); + changes.push_back(ValueStoreChange(key, base::nullopt, std::move(*value))); } syncer::SyncError error = sync_processor_->SendChanges(changes); @@ -356,7 +356,8 @@ syncer::SyncError SyncableSettingsStorage::OnSyncAdd( result.status().message.c_str()), sync_processor_->type()); } - changes->push_back(ValueStoreChange(key, nullptr, std::move(new_value))); + changes->push_back( + ValueStoreChange(key, base::nullopt, std::move(*new_value))); return syncer::SyncError(); } @@ -377,7 +378,7 @@ syncer::SyncError SyncableSettingsStorage::OnSyncUpdate( sync_processor_->type()); } changes->push_back( - ValueStoreChange(key, std::move(old_value), std::move(new_value))); + ValueStoreChange(key, std::move(*old_value), std::move(*new_value))); return syncer::SyncError(); } @@ -394,7 +395,8 @@ syncer::SyncError SyncableSettingsStorage::OnSyncDelete( result.status().message.c_str()), sync_processor_->type()); } - changes->push_back(ValueStoreChange(key, std::move(old_value), nullptr)); + changes->push_back( + ValueStoreChange(key, std::move(*old_value), base::nullopt)); return syncer::SyncError(); } diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h index 5506ae5e985..01197a0c561 100644 --- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h +++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h @@ -20,12 +20,11 @@ class StreamsPrivateAPI { // Send the onExecuteMimeTypeHandler event to |extension_id|. If the viewer is // being opened in a BrowserPlugin, specify a non-empty |view_id| of the // plugin. |embedded| should be set to whether the document is embedded - // within another document. The |frame_tree_node_id| parameter is used for - // PlzNavigate for the top level plugins case. (PDF, etc). If this parameter - // has a valid value then it overrides the |render_process_id| and - // |render_frame_id| parameters. The |render_process_id| is the id of the - // renderer process. The |render_frame_id| is the routing id of the - // RenderFrameHost. + // within another document. The |frame_tree_node_id| parameter is used for the + // top level plugins case. (PDF, etc). If this parameter has a valid value + // then it overrides the |render_process_id| and |render_frame_id| parameters. + // The |render_process_id| is the id of the renderer process. The + // |render_frame_id| is the routing id of the RenderFrameHost. // // If the network service is not enabled, |stream| is used; otherwise, // |transferrable_loader| and |original_url| are used instead. diff --git a/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc b/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc index ccf9916eb27..b2ce3b0cacd 100644 --- a/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc +++ b/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc @@ -35,7 +35,7 @@ IN_PROC_BROWSER_TEST_F(SystemDisplayChromeOSApiTest, extensions::DisplayInfoProvider::Get()); // Change Tablet Mode then ensure that OnDisplayChangedEvent is triggered - provider->OnTabletModeToggled(true); + provider->OnTabletModeStarted(); extensions::ResultCatcher catcher; EXPECT_TRUE(catcher.GetNextResult()); diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h index b0bd25e0404..5b3ca7b5bc5 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h @@ -9,7 +9,7 @@ namespace extensions { -class SystemIndicatorSetIconFunction : public UIThreadExtensionFunction { +class SystemIndicatorSetIconFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemIndicator.setIcon", SYSTEMINDICATOR_SETICON) @@ -19,7 +19,7 @@ class SystemIndicatorSetIconFunction : public UIThreadExtensionFunction { ~SystemIndicatorSetIconFunction() override {} }; -class SystemIndicatorEnableFunction : public UIThreadExtensionFunction { +class SystemIndicatorEnableFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemIndicator.enable", SYSTEMINDICATOR_ENABLE) @@ -29,7 +29,7 @@ class SystemIndicatorEnableFunction : public UIThreadExtensionFunction { ~SystemIndicatorEnableFunction() override {} }; -class SystemIndicatorDisableFunction : public UIThreadExtensionFunction { +class SystemIndicatorDisableFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemIndicator.disable", SYSTEMINDICATOR_DISABLE) diff --git a/chromium/chrome/browser/extensions/api/system_private/system_private_api.h b/chromium/chrome/browser/extensions/api/system_private/system_private_api.h index 5d6fb2bcc71..9c912f005a3 100644 --- a/chromium/chrome/browser/extensions/api/system_private/system_private_api.h +++ b/chromium/chrome/browser/extensions/api/system_private/system_private_api.h @@ -13,7 +13,7 @@ namespace extensions { class SystemPrivateGetIncognitoModeAvailabilityFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getIncognitoModeAvailability", SYSTEMPRIVATE_GETINCOGNITOMODEAVAILABILITY) @@ -26,7 +26,7 @@ class SystemPrivateGetIncognitoModeAvailabilityFunction }; // API function which returns the status of system update. -class SystemPrivateGetUpdateStatusFunction : public UIThreadExtensionFunction { +class SystemPrivateGetUpdateStatusFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getUpdateStatus", SYSTEMPRIVATE_GETUPDATESTATUS) @@ -39,7 +39,7 @@ class SystemPrivateGetUpdateStatusFunction : public UIThreadExtensionFunction { }; // API function which returns the Google API key. -class SystemPrivateGetApiKeyFunction : public UIThreadExtensionFunction { +class SystemPrivateGetApiKeyFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getApiKey", SYSTEMPRIVATE_GETAPIKEY) diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc index cbeaa34fdf3..0fdb361b5a2 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc @@ -412,8 +412,8 @@ ExtensionFunction::ResponseAction TabCaptureGetMediaStreamIdFunction::Run() { content::WebContents* target_contents = nullptr; if (params->options && params->options->target_tab_id) { if (!ExtensionTabUtil::GetTabById(*(params->options->target_tab_id), - browser_context(), true, nullptr, nullptr, - &target_contents, nullptr)) { + browser_context(), true, + &target_contents)) { return RespondNow(Error(kInvalidTabIdError)); } } else { @@ -447,8 +447,8 @@ ExtensionFunction::ResponseAction TabCaptureGetMediaStreamIdFunction::Run() { GURL origin; if (params->options && params->options->consumer_tab_id) { if (!ExtensionTabUtil::GetTabById(*(params->options->consumer_tab_id), - browser_context(), true, nullptr, nullptr, - &consumer_contents, nullptr)) { + browser_context(), true, + &consumer_contents)) { return RespondNow(Error(kInvalidTabIdError)); } diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h index 2f3979bf75a..15c0827eec9 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h @@ -22,7 +22,7 @@ extern const char* const kStableChromecastExtensionId; // Extension ids for the chromecast. extern const char* const kChromecastExtensionIds[6]; -class TabCaptureCaptureFunction : public UIThreadExtensionFunction { +class TabCaptureCaptureFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.capture", TABCAPTURE_CAPTURE) @@ -33,7 +33,7 @@ class TabCaptureCaptureFunction : public UIThreadExtensionFunction { ResponseAction Run() final; }; -class TabCaptureGetCapturedTabsFunction : public UIThreadExtensionFunction { +class TabCaptureGetCapturedTabsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.getCapturedTabs", TABCAPTURE_GETCAPTUREDTABS) @@ -45,7 +45,7 @@ class TabCaptureGetCapturedTabsFunction : public UIThreadExtensionFunction { ResponseAction Run() final; }; -class TabCaptureCaptureOffscreenTabFunction : public UIThreadExtensionFunction { +class TabCaptureCaptureOffscreenTabFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.captureOffscreenTab", TABCAPTURE_CAPTUREOFFSCREENTAB) @@ -62,7 +62,7 @@ class TabCaptureCaptureOffscreenTabFunction : public UIThreadExtensionFunction { ResponseAction Run() final; }; -class TabCaptureGetMediaStreamIdFunction : public UIThreadExtensionFunction { +class TabCaptureGetMediaStreamIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.getMediaStreamId", TABCAPTURE_GETMEDIASTREAMID) 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 2e1bab0f511..414887222cd 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 @@ -161,8 +161,9 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ApiTests) { ASSERT_TRUE(RunExtensionSubtest("tab_capture", "api_tests.html")) << message_; } -#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER) -// Flaky on ASAN on Mac. See https://crbug.com/674497. +#if (defined(OS_MACOSX) && defined(ADDRESS_SANITIZER)) || defined(OS_LINUX) || \ + defined(OS_WIN) +// Flaky on ASAN on Mac, and on Linux and Windows. See https://crbug.com/674497. #define MAYBE_MaxOffscreenTabs DISABLED_MaxOffscreenTabs #else #define MAYBE_MaxOffscreenTabs MaxOffscreenTabs @@ -431,10 +432,6 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_TabIndicator) { browser_->tab_strip_model()->AddObserver(this); } - ~IndicatorChangeObserver() override { - browser_->tab_strip_model()->RemoveObserver(this); - } - TabAlertState last_alert_state() const { return last_alert_state_; } void TabChangedAt(content::WebContents* contents, diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc index 7433a5793f0..874af5d556c 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -16,6 +16,7 @@ #include "base/location.h" #include "base/logging.h" #include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" @@ -148,7 +149,7 @@ bool GetBrowserFromWindowID(const ChromeExtensionFunctionDetails& details, return true; } -bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(ExtensionFunction* function, int window_id, Browser** browser, std::string* error) { @@ -182,10 +183,9 @@ bool GetTabById(int tab_id, // Gets the WebContents for |tab_id| if it is specified. Otherwise get the // WebContents for the active tab in the |function|'s current window. // Returns nullptr and fills |error| if failed. -content::WebContents* GetTabsAPIDefaultWebContents( - UIThreadExtensionFunction* function, - int tab_id, - std::string* error) { +content::WebContents* GetTabsAPIDefaultWebContents(ExtensionFunction* function, + int tab_id, + std::string* error) { content::WebContents* web_contents = nullptr; if (tab_id != -1) { // We assume this call leaves web_contents unchanged if it is unsuccessful. @@ -267,6 +267,18 @@ bool ExtensionHasLockedFullscreenPermission(const Extension* extension) { APIPermission::kLockWindowFullscreenPrivate); } +std::unique_ptr<api::tabs::Tab> CreateTabObjectHelper( + WebContents* contents, + const Extension* extension, + Feature::Context context, + TabStripModel* tab_strip, + int tab_index) { + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, context, contents); + return ExtensionTabUtil::CreateTabObject(contents, scrub_tab_behavior, + extension, tab_strip, tab_index); +} + } // namespace void ZoomModeToZoomSettings(ZoomController::ZoomMode zoom_mode, @@ -312,8 +324,8 @@ ExtensionFunction::ResponseAction WindowsGetFunction::Run() { extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), - populate_tab_behavior); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), populate_tab_behavior, source_context_type()); return RespondNow(OneArgument(std::move(windows))); } @@ -335,8 +347,8 @@ ExtensionFunction::ResponseAction WindowsGetCurrentFunction::Run() { extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), - populate_tab_behavior); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), populate_tab_behavior, source_context_type()); return RespondNow(OneArgument(std::move(windows))); } @@ -369,8 +381,8 @@ ExtensionFunction::ResponseAction WindowsGetLastFocusedFunction::Run() { extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), - populate_tab_behavior); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), populate_tab_behavior, source_context_type()); return RespondNow(OneArgument(std::move(windows))); } @@ -391,7 +403,8 @@ ExtensionFunction::ResponseAction WindowsGetAllFunction::Run() { continue; } window_list->Append(ExtensionTabUtil::CreateWindowValueForExtension( - *controller->GetBrowser(), extension(), populate_tab_behavior)); + *controller->GetBrowser(), extension(), populate_tab_behavior, + source_context_type())); } return RespondNow(OneArgument(std::move(window_list))); @@ -508,7 +521,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { if (!IsValidStateForWindowsCreateFunction(create_data)) return RespondNow(Error(tabs_constants::kInvalidWindowStateError)); - Browser::Type window_type = Browser::TYPE_TABBED; + Browser::Type window_type = Browser::TYPE_NORMAL; gfx::Rect window_bounds; bool focused = true; @@ -532,13 +545,10 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { } // Initialize default window bounds according to window type. - if (window_type == Browser::TYPE_TABBED || - window_type == Browser::TYPE_POPUP) { - ui::WindowShowState ignored_show_state = ui::SHOW_STATE_DEFAULT; - WindowSizer::GetBrowserWindowBoundsAndShowState( - std::string(), gfx::Rect(), nullptr, &window_bounds, - &ignored_show_state); - } + ui::WindowShowState ignored_show_state = ui::SHOW_STATE_DEFAULT; + WindowSizer::GetBrowserWindowBoundsAndShowState(std::string(), gfx::Rect(), + nullptr, &window_bounds, + &ignored_show_state); // Any part of the bounds can optionally be set by the caller. if (create_data->left) @@ -592,9 +602,19 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { // https://crbug.com/713888. bool set_self_as_opener = create_data->set_self_as_opener && // present? *create_data->set_self_as_opener; // set to true? - navigate_params.opener = set_self_as_opener ? render_frame_host() : nullptr; - navigate_params.source_site_instance = - render_frame_host()->GetSiteInstance(); + if (set_self_as_opener) { + if (is_from_service_worker()) { + // TODO(crbug.com/984350): Add test for this. + return RespondNow( + Error("Cannot specify setSelfAsOpener Service Worker extension.")); + } + // TODO(crbug.com/984350): Add tests for checking opener SiteInstance + // behavior from a SW based extension's extension frame (e.g. from popup). + // See ExtensionApiTest.WindowsCreate* tests for details. + navigate_params.opener = render_frame_host(); + navigate_params.source_site_instance = + render_frame_host()->GetSiteInstance(); + } Navigate(&navigate_params); } @@ -602,8 +622,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { WebContents* contents = NULL; // Move the tab into the created window only if it's an empty popup or it's // a tabbed window. - if ((window_type == Browser::TYPE_POPUP && urls.empty()) || - window_type == Browser::TYPE_TABBED) { + if (window_type == Browser::TYPE_NORMAL || urls.empty()) { if (source_tab_strip) { std::unique_ptr<content::WebContents> detached_tab = source_tab_strip->DetachWebContentsAt(tab_index); @@ -615,7 +634,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { } // Create a new tab if the created window is still empty. Don't create a new // tab when it is intended to create an empty popup. - if (!contents && urls.empty() && window_type != Browser::TYPE_POPUP) { + if (!contents && urls.empty() && window_type == Browser::TYPE_NORMAL) { chrome::NewTab(new_window); } chrome::SelectNumberedTab(new_window, 0, {TabStripModel::GestureType::kNone}); @@ -642,7 +661,8 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { result = std::make_unique<base::Value>(); } else { result = ExtensionTabUtil::CreateWindowValueForExtension( - *new_window, extension(), ExtensionTabUtil::kPopulateTabs); + *new_window, extension(), ExtensionTabUtil::kPopulateTabs, + source_context_type()); } return RespondNow(OneArgument(std::move(result))); @@ -772,7 +792,8 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { browser->window()->FlashFrame(*params->update_info.draw_attention); return RespondNow(OneArgument(ExtensionTabUtil::CreateWindowValueForExtension( - *browser, extension(), ExtensionTabUtil::kDontPopulateTabs))); + *browser, extension(), ExtensionTabUtil::kDontPopulateTabs, + source_context_type()))); } ExtensionFunction::ResponseAction WindowsRemoveFunction::Run() { @@ -826,10 +847,9 @@ ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() { WebContents* contents = tab_strip->GetActiveWebContents(); if (!contents) return RespondNow(Error(tabs_constants::kNoSelectedTabError)); - return RespondNow(ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension(), tab_strip, - tab_strip->active_index())))); + return RespondNow(ArgumentList(tabs::Get::Results::Create( + *CreateTabObjectHelper(contents, extension(), source_context_type(), + tab_strip, tab_strip->active_index())))); } ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { @@ -846,8 +866,8 @@ ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { if (!GetBrowserFromWindowID(this, window_id, &browser, &error)) return RespondNow(Error(error)); - return RespondNow( - OneArgument(ExtensionTabUtil::CreateTabList(browser, extension()))); + return RespondNow(OneArgument(ExtensionTabUtil::CreateTabList( + browser, extension(), source_context_type()))); } ExtensionFunction::ResponseAction TabsQueryFunction::Run() { @@ -1016,9 +1036,8 @@ ExtensionFunction::ResponseAction TabsQueryFunction::Run() { if (loading_status_set && loading != web_contents->IsLoading()) continue; - result->Append(ExtensionTabUtil::CreateTabObject( - web_contents, ExtensionTabUtil::kScrubTab, extension(), - tab_strip, i) + result->Append(CreateTabObjectHelper(web_contents, extension(), + source_context_type(), tab_strip, i) ->ToValue()); } } @@ -1083,10 +1102,9 @@ ExtensionFunction::ResponseAction TabsDuplicateFunction::Run() { return RespondNow(Error(kUnknownErrorDoNotUse)); } - return RespondNow(ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - new_contents, ExtensionTabUtil::kScrubTab, extension(), new_tab_strip, - new_tab_index)))); + return RespondNow(ArgumentList(tabs::Get::Results::Create( + *CreateTabObjectHelper(new_contents, extension(), source_context_type(), + new_tab_strip, new_tab_index)))); } ExtensionFunction::ResponseAction TabsGetFunction::Run() { @@ -1104,8 +1122,8 @@ ExtensionFunction::ResponseAction TabsGetFunction::Run() { } return RespondNow(ArgumentList(tabs::Get::Results::Create( - *ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, - extension(), tab_strip, tab_index)))); + *CreateTabObjectHelper(contents, extension(), source_context_type(), + tab_strip, tab_index)))); } ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { @@ -1116,8 +1134,8 @@ ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { WebContents* caller_contents = GetSenderWebContents(); std::unique_ptr<base::ListValue> results; if (caller_contents && ExtensionTabUtil::GetTabId(caller_contents) >= 0) { - results = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - caller_contents, ExtensionTabUtil::kScrubTab, extension())); + results = tabs::Get::Results::Create(*CreateTabObjectHelper( + caller_contents, extension(), source_context_type(), nullptr, -1)); } return RespondNow(results ? ArgumentList(std::move(results)) : NoArguments()); } @@ -1165,7 +1183,8 @@ ExtensionFunction::ResponseAction TabsHighlightFunction::Run() { selection.set_active(active_index); browser->tab_strip_model()->SetSelectionFromModel(std::move(selection)); return RespondNow(OneArgument(ExtensionTabUtil::CreateWindowValueForExtension( - *browser, extension(), ExtensionTabUtil::kPopulateTabs))); + *browser, extension(), ExtensionTabUtil::kPopulateTabs, + source_context_type()))); } bool TabsHighlightFunction::HighlightTab(TabStripModel* tabstrip, @@ -1359,9 +1378,8 @@ ExtensionFunction::ResponseValue TabsUpdateFunction::GetResult() { if (!has_callback()) return NoArguments(); - return ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - web_contents_, ExtensionTabUtil::kScrubTab, extension()))); + return ArgumentList(tabs::Get::Results::Create(*CreateTabObjectHelper( + web_contents_, extension(), source_context_type(), nullptr, -1))); } void TabsUpdateFunction::OnExecuteCodeFinished( @@ -1458,7 +1476,9 @@ bool TabsMoveFunction::MoveTab(int tab_id, return false; } - if (!target_browser->is_type_tabbed()) { + // TODO(crbug.com/990158): Rather than calling is_type_normal(), should + // this call SupportsWindowFeature(Browser::FEATURE_TABSTRIP)? + if (!target_browser->is_type_normal()) { *error = tabs_constants::kCanOnlyMoveTabsWithinNormalWindowsError; return false; } @@ -1492,9 +1512,9 @@ bool TabsMoveFunction::MoveTab(int tab_id, *new_index, std::move(web_contents), TabStripModel::ADD_NONE); if (has_callback()) { - tab_values->Append(ExtensionTabUtil::CreateTabObject( - web_contents_raw, ExtensionTabUtil::kScrubTab, - extension(), target_tab_strip, *new_index) + tab_values->Append(CreateTabObjectHelper(web_contents_raw, extension(), + source_context_type(), + target_tab_strip, *new_index) ->ToValue()); } @@ -1514,9 +1534,9 @@ bool TabsMoveFunction::MoveTab(int tab_id, source_tab_strip->MoveWebContentsAt(tab_index, *new_index, false); if (has_callback()) { - tab_values->Append(ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension(), - source_tab_strip, *new_index) + tab_values->Append(CreateTabObjectHelper(contents, extension(), + source_context_type(), + source_tab_strip, *new_index) ->ToValue()); } @@ -1790,7 +1810,7 @@ ExtensionFunction::ResponseAction TabsDetectLanguageFunction::Run() { // Observe the WebContents' lifetime and navigations. Observe(contents); // Wait until the language is determined. - chrome_translate_client->translate_driver().AddObserver(this); + chrome_translate_client->translate_driver()->AddObserver(this); is_observing_ = true; return RespondLater(); @@ -1820,7 +1840,7 @@ void TabsDetectLanguageFunction::RespondWithLanguage( if (is_observing_) { ChromeTranslateClient::FromWebContents(web_contents()) ->translate_driver() - .RemoveObserver(this); + ->RemoveObserver(this); Observe(nullptr); } @@ -1983,8 +2003,7 @@ ExtensionFunction::ResponseAction TabsSetZoomFunction::Run() { ? content::ZoomFactorToZoomLevel(params->zoom_factor) : zoom_controller->GetDefaultZoomLevel(); - scoped_refptr<ExtensionZoomRequestClient> client( - new ExtensionZoomRequestClient(extension())); + auto client = base::MakeRefCounted<ExtensionZoomRequestClient>(extension()); if (!zoom_controller->SetZoomLevelByClient(zoom_level, client)) { // Tried to zoom a tab in disabled mode. return RespondNow(Error(tabs_constants::kCannotZoomDisabledTabError)); @@ -2111,9 +2130,9 @@ ExtensionFunction::ResponseAction TabsDiscardFunction::Run() { // Create the Tab object and return it in case of success. if (contents) { - return RespondNow(ArgumentList( - tabs::Discard::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension())))); + return RespondNow( + ArgumentList(tabs::Discard::Results::Create(*CreateTabObjectHelper( + contents, extension(), source_context_type(), nullptr, -1)))); } // Return appropriate error message otherwise. diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h index 37c2da5cf71..ed3aa5336d5 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h @@ -44,27 +44,27 @@ void ZoomModeToZoomSettings(zoom::ZoomController::ZoomMode zoom_mode, api::tabs::ZoomSettings* zoom_settings); // Windows -class WindowsGetFunction : public UIThreadExtensionFunction { +class WindowsGetFunction : public ExtensionFunction { ~WindowsGetFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.get", WINDOWS_GET) }; -class WindowsGetCurrentFunction : public UIThreadExtensionFunction { +class WindowsGetCurrentFunction : public ExtensionFunction { ~WindowsGetCurrentFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getCurrent", WINDOWS_GETCURRENT) }; -class WindowsGetLastFocusedFunction : public UIThreadExtensionFunction { +class WindowsGetLastFocusedFunction : public ExtensionFunction { ~WindowsGetLastFocusedFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getLastFocused", WINDOWS_GETLASTFOCUSED) }; -class WindowsGetAllFunction : public UIThreadExtensionFunction { +class WindowsGetAllFunction : public ExtensionFunction { ~WindowsGetAllFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getAll", WINDOWS_GETALL) }; -class WindowsCreateFunction : public UIThreadExtensionFunction { +class WindowsCreateFunction : public ExtensionFunction { ~WindowsCreateFunction() override {} ResponseAction Run() override; // Returns whether the window should be created in incognito mode. @@ -80,54 +80,54 @@ class WindowsCreateFunction : public UIThreadExtensionFunction { std::string* error); DECLARE_EXTENSION_FUNCTION("windows.create", WINDOWS_CREATE) }; -class WindowsUpdateFunction : public UIThreadExtensionFunction { +class WindowsUpdateFunction : public ExtensionFunction { ~WindowsUpdateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.update", WINDOWS_UPDATE) }; -class WindowsRemoveFunction : public UIThreadExtensionFunction { +class WindowsRemoveFunction : public ExtensionFunction { ~WindowsRemoveFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.remove", WINDOWS_REMOVE) }; // Tabs -class TabsGetFunction : public UIThreadExtensionFunction { +class TabsGetFunction : public ExtensionFunction { ~TabsGetFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.get", TABS_GET) }; -class TabsGetCurrentFunction : public UIThreadExtensionFunction { +class TabsGetCurrentFunction : public ExtensionFunction { ~TabsGetCurrentFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getCurrent", TABS_GETCURRENT) }; -class TabsGetSelectedFunction : public UIThreadExtensionFunction { +class TabsGetSelectedFunction : public ExtensionFunction { ~TabsGetSelectedFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getSelected", TABS_GETSELECTED) }; -class TabsGetAllInWindowFunction : public UIThreadExtensionFunction { +class TabsGetAllInWindowFunction : public ExtensionFunction { ~TabsGetAllInWindowFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getAllInWindow", TABS_GETALLINWINDOW) }; -class TabsQueryFunction : public UIThreadExtensionFunction { +class TabsQueryFunction : public ExtensionFunction { ~TabsQueryFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.query", TABS_QUERY) }; -class TabsCreateFunction : public UIThreadExtensionFunction { +class TabsCreateFunction : public ExtensionFunction { ~TabsCreateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.create", TABS_CREATE) }; -class TabsDuplicateFunction : public UIThreadExtensionFunction { +class TabsDuplicateFunction : public ExtensionFunction { ~TabsDuplicateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.duplicate", TABS_DUPLICATE) }; -class TabsHighlightFunction : public UIThreadExtensionFunction { +class TabsHighlightFunction : public ExtensionFunction { ~TabsHighlightFunction() override {} ResponseAction Run() override; bool HighlightTab(TabStripModel* tabstrip, @@ -137,7 +137,7 @@ class TabsHighlightFunction : public UIThreadExtensionFunction { std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.highlight", TABS_HIGHLIGHT) }; -class TabsUpdateFunction : public UIThreadExtensionFunction { +class TabsUpdateFunction : public ExtensionFunction { public: TabsUpdateFunction(); @@ -158,7 +158,7 @@ class TabsUpdateFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.update", TABS_UPDATE) }; -class TabsMoveFunction : public UIThreadExtensionFunction { +class TabsMoveFunction : public ExtensionFunction { ~TabsMoveFunction() override {} ResponseAction Run() override; bool MoveTab(int tab_id, @@ -169,19 +169,19 @@ class TabsMoveFunction : public UIThreadExtensionFunction { std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.move", TABS_MOVE) }; -class TabsReloadFunction : public UIThreadExtensionFunction { +class TabsReloadFunction : public ExtensionFunction { ~TabsReloadFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.reload", TABS_RELOAD) }; -class TabsRemoveFunction : public UIThreadExtensionFunction { +class TabsRemoveFunction : public ExtensionFunction { ~TabsRemoveFunction() override {} ResponseAction Run() override; bool RemoveTab(int tab_id, std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.remove", TABS_REMOVE) }; class TabsDetectLanguageFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public content::WebContentsObserver, public translate::ContentTranslateDriver::Observer { private: @@ -209,7 +209,7 @@ class TabsDetectLanguageFunction class TabsCaptureVisibleTabFunction : public extensions::WebContentsCaptureClient, - public UIThreadExtensionFunction { + public ExtensionFunction { public: TabsCaptureVisibleTabFunction(); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); @@ -280,7 +280,7 @@ class TabsInsertCSSFunction : public ExecuteCodeInTabFunction { DECLARE_EXTENSION_FUNCTION("tabs.insertCSS", TABS_INSERTCSS) }; -class TabsSetZoomFunction : public UIThreadExtensionFunction { +class TabsSetZoomFunction : public ExtensionFunction { private: ~TabsSetZoomFunction() override {} @@ -289,7 +289,7 @@ class TabsSetZoomFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.setZoom", TABS_SETZOOM) }; -class TabsGetZoomFunction : public UIThreadExtensionFunction { +class TabsGetZoomFunction : public ExtensionFunction { private: ~TabsGetZoomFunction() override {} @@ -298,7 +298,7 @@ class TabsGetZoomFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.getZoom", TABS_GETZOOM) }; -class TabsSetZoomSettingsFunction : public UIThreadExtensionFunction { +class TabsSetZoomSettingsFunction : public ExtensionFunction { private: ~TabsSetZoomSettingsFunction() override {} @@ -307,7 +307,7 @@ class TabsSetZoomSettingsFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.setZoomSettings", TABS_SETZOOMSETTINGS) }; -class TabsGetZoomSettingsFunction : public UIThreadExtensionFunction { +class TabsGetZoomSettingsFunction : public ExtensionFunction { private: ~TabsGetZoomSettingsFunction() override {} @@ -316,7 +316,7 @@ class TabsGetZoomSettingsFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.getZoomSettings", TABS_GETZOOMSETTINGS) }; -class TabsDiscardFunction : public UIThreadExtensionFunction { +class TabsDiscardFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabs.discard", TABS_DISCARD) @@ -331,7 +331,7 @@ class TabsDiscardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(TabsDiscardFunction); }; -class TabsGoForwardFunction : public UIThreadExtensionFunction { +class TabsGoForwardFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabs.goForward", TABS_GOFORWARD) @@ -346,7 +346,7 @@ class TabsGoForwardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(TabsGoForwardFunction); }; -class TabsGoBackFunction : public UIThreadExtensionFunction { +class TabsGoBackFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabs.goBack", TABS_GOBACK) 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 60915b4d639..8b1853957cd 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc @@ -106,7 +106,7 @@ void TabsApiUnitTest::SetUp() { browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); scoped_screen_override_ = 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 ead6f0a7144..f86ebb9b063 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc @@ -27,6 +27,7 @@ #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" +#include "extensions/common/features/feature.h" using base::DictionaryValue; using base::ListValue; @@ -41,12 +42,16 @@ namespace { bool WillDispatchTabUpdatedEvent( WebContents* contents, const std::set<std::string> changed_property_names, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, target_context, + contents); std::unique_ptr<api::tabs::Tab> tab_object = - ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, + ExtensionTabUtil::CreateTabObject(contents, scrub_tab_behavior, extension); std::unique_ptr<base::DictionaryValue> tab_value = tab_object->ToValue(); @@ -66,14 +71,17 @@ bool WillDispatchTabUpdatedEvent( bool WillDispatchTabCreatedEvent(WebContents* contents, bool active, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { event->event_args->Clear(); + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, target_context, + contents); std::unique_ptr<base::DictionaryValue> tab_value = - ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, - extension) + ExtensionTabUtil::CreateTabObject(contents, scrub_tab_behavior, extension) ->ToValue(); tab_value->SetBoolean(tabs_constants::kSelectedKey, active); tab_value->SetBoolean(tabs_constants::kActiveKey, active); 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 9d43155a027..77050a952f3 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc @@ -21,6 +21,7 @@ namespace extensions { namespace keys = tabs_constants; namespace utils = extension_function_test_utils; +using ContextType = ExtensionBrowserTest::ContextType; using ExtensionTabsTest = InProcessBrowserTest; IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetLastFocusedWindow) { @@ -117,8 +118,35 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryLastFocusedWindowTabs) { } } -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCurrentWindow) { - ASSERT_TRUE(RunExtensionTest("tabs/current_window")) << message_; +class NonPersistentExtensionTabsTest + : public ExtensionApiTest, + public testing::WithParamInterface<ContextType> { + protected: + const Extension* LoadNonPersistentExtension(const char* relative_path) { + return LoadExtensionWithFlags(test_data_dir_.AppendASCII(relative_path), + GetParam() == ContextType::kEventPage + ? kFlagNone + : kFlagRunAsServiceWorkerBasedExtension); + } +}; + +// Tests chrome.windows.create. +// TODO(crbug.com/984350): Expand the test to verify that setSelfAsOpener +// param is ignored from Service Worker extension scripts. +IN_PROC_BROWSER_TEST_P(NonPersistentExtensionTabsTest, TabCurrentWindow) { + ASSERT_TRUE(RunExtensionTestWithFlags( + "tabs/current_window", GetParam() == ContextType::kServiceWorker + ? kFlagRunAsServiceWorkerBasedExtension + : kFlagNone)) + << message_; } +INSTANTIATE_TEST_SUITE_P(EventPage, + NonPersistentExtensionTabsTest, + ::testing::Values(ContextType::kEventPage)); + +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + NonPersistentExtensionTabsTest, + ::testing::Values(ContextType::kServiceWorker)); + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc index 748dc56a796..f5fb14246df 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -795,7 +795,7 @@ class ExtensionWindowLastFocusedTest : public ExtensionTabsTest { int GetTabId(const base::DictionaryValue* value) const; - base::Value* RunFunction(UIThreadExtensionFunction* function, + base::Value* RunFunction(ExtensionFunction* function, const std::string& params); const Extension* extension() { return extension_.get(); } @@ -880,7 +880,7 @@ int ExtensionWindowLastFocusedTest::GetTabId( } base::Value* ExtensionWindowLastFocusedTest::RunFunction( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& params) { function->set_extension(extension_.get()); return utils::RunFunctionAndReturnSingleResult(function, params, browser()); @@ -2238,4 +2238,87 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_NoOpener) { // (we hope this can be limited to background pages / contents). } +// Tests the origin of tabs created through chrome.windows.create(). +IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_OpenerAndOrigin) { + const extensions::Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("../simple_with_file")); + ASSERT_TRUE(extension); + + // Navigate a tab to an extension page. + GURL extension_url = extension->GetResourceURL("file.html"); + ui_test_utils::NavigateToURL(browser(), extension_url); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + const std::string extension_origin_str = + url::Origin::Create(extension->url()).Serialize(); + constexpr char kDataURL[] = "data:text/html,<html>test</html>"; + std::string extension_url_str = extension_url.spec(); + struct TestCase { + // The url to use in chrome.windows.create(). + std::string url; + // If set, its value will be used to specify |setSelfAsOpener|. + base::Optional<bool> set_self_as_opener; + // The origin we expect the new tab to be in, opaque origins will be "null". + std::string expected_origin_str; + } test_cases[] = { + // about:blank URLs. + // With opener relationship, about:blank urls will get the extension's + // origin, without opener relationship, they will get opaque/"null" + // origin. + {url::kAboutBlankURL, true, extension_origin_str}, + {url::kAboutBlankURL, false, "null"}, + {url::kAboutBlankURL, base::nullopt, "null"}, + + // data:... URLs. + // With opener relationship or not, "data:..." URLs always gets unique + // origin, so origin will always be "null" in these cases. + {kDataURL, true, "null"}, + {kDataURL, false, "null"}, + {kDataURL, base::nullopt, "null"}, + + // chrome-extension:// URLs. + // These always get extension origin. + {extension_url_str, true, extension_origin_str}, + {extension_url_str, false, extension_origin_str}, + {extension_url_str, base::nullopt, extension_origin_str}, + }; + + auto run_test_case = [&web_contents](const TestCase& test_case) { + std::string maybe_specify_set_self_as_opener = ""; + if (test_case.set_self_as_opener) { + maybe_specify_set_self_as_opener = + base::StringPrintf(", setSelfAsOpener: %s", + *test_case.set_self_as_opener ? "true" : "false"); + } + std::string script = base::StringPrintf( + R"( chrome.windows.create({url: '%s'%s}); )", test_case.url.c_str(), + maybe_specify_set_self_as_opener.c_str()); + + content::WebContents* new_contents = nullptr; + { + content::WebContentsAddedObserver observer; + ASSERT_TRUE(content::ExecuteScript(web_contents, script)); + new_contents = observer.GetWebContents(); + } + ASSERT_TRUE(new_contents); + ASSERT_TRUE(content::WaitForLoadStop(new_contents)); + + std::string actual_origin_str; + EXPECT_TRUE(ExecuteScriptAndExtractString( + new_contents, "window.domAutomationController.send(origin);", + &actual_origin_str)); + EXPECT_EQ(test_case.expected_origin_str, actual_origin_str); + const bool is_opaque_origin = + new_contents->GetMainFrame()->GetLastCommittedOrigin().opaque(); + EXPECT_EQ(test_case.expected_origin_str == "null", is_opaque_origin); + }; + for (size_t i = 0; i < base::size(test_cases); ++i) { + const auto& test_case = test_cases[i]; + SCOPED_TRACE( + base::StringPrintf("#%" PRIuS " %s", i, test_case.url.c_str())); + run_test_case(test_case); + } +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc index 0a076f31c73..6a0c9a2833f 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc @@ -19,7 +19,7 @@ #include "content/public/browser/devtools_agent_host.h" #include "ui/aura/window.h" #include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/clipboard_types.h" +#include "ui/base/clipboard/clipboard_buffer.h" namespace extensions { namespace tabs_util { @@ -27,14 +27,6 @@ namespace tabs_util { void SetLockedFullscreenState(Browser* browser, bool locked) { UMA_HISTOGRAM_BOOLEAN("Extensions.LockedFullscreenStateRequest", locked); - // Disable ChromeVox before entering locked fullscreen. Quickfix for - // crbug.com/957950. - auto* const accessibility_manager = chromeos::AccessibilityManager::Get(); - if (locked && accessibility_manager && - accessibility_manager->IsSpokenFeedbackEnabled()) { - accessibility_manager->EnableSpokenFeedback(false); - } - aura::Window* window = browser->window()->GetNativeWindow(); // TRUSTED_PINNED is used here because that one locks the window fullscreen // without allowing the user to exit (as opposed to regular PINNED). @@ -50,7 +42,7 @@ void SetLockedFullscreenState(Browser* browser, bool locked) { // Reset the clipboard and kill dev tools when entering or exiting locked // fullscreen (security concerns). - ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardType::kCopyPaste); + ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); content::DevToolsAgentHost::DetachAllClients(); // Disable ARC while in the locked fullscreen mode. diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc index b27e4bca86e..c890c88293c 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc @@ -60,7 +60,8 @@ bool ControllerVisibleToListener(WindowController* window_controller, } bool WillDispatchWindowEvent(WindowController* window_controller, - BrowserContext* context, + BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { @@ -88,7 +89,8 @@ bool WillDispatchWindowEvent(WindowController* window_controller, bool WillDispatchWindowFocusedEvent( WindowController* window_controller, - BrowserContext* context, + BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { @@ -123,9 +125,9 @@ bool WillDispatchWindowFocusedEvent( // dispatch WINDOW_ID_NONE to extensions whose profile lost focus that // can't see the new focused window across the incognito boundary. // See crbug.com/46610. - bool cant_cross_incognito = new_active_context && - new_active_context != context && - !util::CanCrossIncognito(extension, context); + bool cant_cross_incognito = + new_active_context && new_active_context != browser_context && + !util::CanCrossIncognito(extension, browser_context); // If the window is not visible by the listener, we also need to // clear out the window id from the event. bool visible_to_listener = ControllerVisibleToListener( @@ -214,9 +216,13 @@ void WindowsEventRouter::OnWindowControllerAdded( return; std::unique_ptr<base::ListValue> args(new base::ListValue()); + // Since we don't populate tab info here, the context type doesn't matter. + constexpr ExtensionTabUtil::PopulateTabBehavior populate_behavior = + ExtensionTabUtil::kDontPopulateTabs; + constexpr Feature::Context context_type = Feature::UNSPECIFIED_CONTEXT; args->Append(ExtensionTabUtil::CreateWindowValueForExtension( - *window_controller->GetBrowser(), nullptr, - ExtensionTabUtil::kDontPopulateTabs)); + *window_controller->GetBrowser(), nullptr, populate_behavior, + context_type)); DispatchEvent(events::WINDOWS_ON_CREATED, windows::OnCreated::kEventName, window_controller, std::move(args)); } diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc index 684183d770a..ae70d408258 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc @@ -23,7 +23,7 @@ namespace windows_util { -bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(ExtensionFunction* function, int window_id, extensions::WindowController::TypeFilter filter, Browser** browser, @@ -68,7 +68,7 @@ bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, return true; } -bool CanOperateOnWindow(const UIThreadExtensionFunction* function, +bool CanOperateOnWindow(const ExtensionFunction* function, const extensions::WindowController* controller, extensions::WindowController::TypeFilter filter) { if (filter && !controller->MatchesFilter(filter)) diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.h b/chromium/chrome/browser/extensions/api/tabs/windows_util.h index f080d068c72..551e1bbbb89 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.h @@ -9,7 +9,7 @@ #include "chrome/browser/extensions/window_controller_list.h" -class UIThreadExtensionFunction; +class ExtensionFunction; namespace extensions { class WindowController; @@ -19,7 +19,7 @@ namespace windows_util { // Populates |browser| for given |window_id|. If the window is not found, // returns false and sets |error|. -bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(ExtensionFunction* function, int window_id, extensions::WindowController::TypeFilter filter, Browser** browser, @@ -31,7 +31,7 @@ bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, // kind of window (including app and devtools), otherwise it will // return true only for normal browser windows as well as windows // created by the extension. -bool CanOperateOnWindow(const UIThreadExtensionFunction* function, +bool CanOperateOnWindow(const ExtensionFunction* function, const extensions::WindowController* controller, extensions::WindowController::TypeFilter filter); 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 1dc03aa89af..a84c77ebbe5 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/terminal/terminal_private_api.h" #include <memory> +#include <string> #include <utility> #include <vector> @@ -14,9 +15,13 @@ #include "base/system/sys_info.h" #include "base/task/post_task.h" #include "base/values.h" +#include "chrome/browser/chromeos/crostini/crostini_manager.h" +#include "chrome/browser/chromeos/crostini/crostini_simple_types.h" +#include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/api/terminal_private.h" #include "chromeos/process_proxy/process_proxy_registry.h" @@ -49,33 +54,29 @@ const char kStubbedCroshCommand[] = "cat"; const char kVmShellName[] = "vmshell"; const char kVmShellCommand[] = "/usr/bin/vsh"; -std::string GetCroshPath() { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kCroshCommand)) - return command_line->GetSwitchValueASCII(switches::kCroshCommand); - - if (base::SysInfo::IsRunningOnChromeOS()) - return std::string(kCroshCommand); - - return std::string(kStubbedCroshCommand); -} - -// Get the program to run based on the openTerminalProcess JS request. -std::string GetProcessCommandForName(const std::string& name) { - if (name == kCroshName) - return GetCroshPath(); - else if (name == kVmShellName) - return kVmShellCommand; - else - return std::string(); +const char kSwitchOwnerId[] = "owner_id"; +const char kSwitchVmName[] = "vm_name"; +const char kSwitchTargetContainer[] = "target_container"; + +// Returns the value of the specified |switch_name| if present. If not present, +// sets that switch to and returns |default_value|. +std::string GetSwitch(base::CommandLine* command_line, + const std::string& switch_name, + const std::string& default_value) { + if (command_line->HasSwitch(switch_name)) { + return command_line->GetSwitchValueASCII(switch_name); + } + command_line->AppendSwitchASCII(switch_name, default_value); + return default_value; } -// Whether the program accepts arbitrary command line arguments. -bool CommandSupportsArguments(const std::string& name) { - if (name == kVmShellName) - return true; - - return false; +void OnCrostiniRestarted(base::OnceClosure callback, + crostini::CrostiniResult result) { + if (result != crostini::CrostiniResult::SUCCESS) { + LOG(ERROR) << "Error restarting crostini for terminal: " + << static_cast<int>(result); + } + std::move(callback).Run(); } void NotifyProcessOutput(content::BrowserContext* browser_context, @@ -84,10 +85,9 @@ void NotifyProcessOutput(content::BrowserContext* browser_context, const std::string& output_type, const std::string& output) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&NotifyProcessOutput, browser_context, tab_id, - terminal_id, output_type, output)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&NotifyProcessOutput, browser_context, tab_id, + terminal_id, output_type, output)); return; } @@ -135,27 +135,62 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { OpenTerminalProcess::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - const std::string command = GetProcessCommandForName(params->process_name); - if (command.empty()) - return RespondNow(Error("Invalid process name.")); - - const std::string user_id_hash = - ExtensionsBrowserClient::Get()->GetUserIdHashFromContext( - browser_context()); - - std::vector<std::string> arguments; - arguments.push_back(command); - if (params->args) { - for (const std::string& arg : *params->args) - arguments.push_back(arg); + // Passing --crosh-command overrides any JS process name. + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kCroshCommand)) { + OpenProcess({command_line->GetSwitchValueASCII(switches::kCroshCommand)}); + + } else if (params->process_name == kCroshName) { + // command=crosh: use '/usr/bin/crosh' on a device, 'cat' otherwise. + if (base::SysInfo::IsRunningOnChromeOS()) { + OpenProcess({kCroshCommand}); + } else { + OpenProcess({kStubbedCroshCommand}); + } + + } else if (params->process_name == kVmShellName) { + // command=vmshell: ensure --owner_id, --vm_name, --target_container are set + // and the specified vm/container is running. + std::vector<std::string> args = {kVmShellCommand}; + if (params->args) + args.insert(args.end(), params->args->begin(), params->args->end()); + base::CommandLine vmshell_cmd(args); + std::string owner_id = + GetSwitch(&vmshell_cmd, kSwitchOwnerId, UserIdHash()); + std::string vm_name = GetSwitch(&vmshell_cmd, kSwitchVmName, + crostini::kCrostiniDefaultVmName); + std::string container_name = + GetSwitch(&vmshell_cmd, kSwitchTargetContainer, + crostini::kCrostiniDefaultContainerName); + + auto open_process = + base::BindOnce(&TerminalPrivateOpenTerminalProcessFunction::OpenProcess, + this, vmshell_cmd.argv()); + crostini::CrostiniManager::GetForProfile( + Profile::FromBrowserContext(browser_context())) + ->RestartCrostini( + vm_name, container_name, + base::BindOnce(&OnCrostiniRestarted, std::move(open_process))); + + } else { + // command=[unrecognized]. + return RespondNow(Error("Invalid process name: " + params->process_name)); } + return RespondLater(); +} - if (arguments.size() > 1 && !CommandSupportsArguments(params->process_name)) - return RespondNow(Error("Specified command does not support arguments.")); +std::string TerminalPrivateOpenTerminalProcessFunction::UserIdHash() { + return extensions::ExtensionsBrowserClient::Get()->GetUserIdHashFromContext( + browser_context()); +} + +void TerminalPrivateOpenTerminalProcessFunction::OpenProcess( + const std::vector<std::string> arguments) { + DCHECK(!arguments.empty()); content::WebContents* caller_contents = GetSenderWebContents(); if (!caller_contents) - return RespondNow(Error("No web contents.")); + return Respond(Error("No web contents.")); // Passed to terminalPrivate.ackOutput, which is called from the API's custom // bindings after terminalPrivate.onProcessOutput is dispatched. It is used to @@ -169,7 +204,7 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { // needed to fix crbug.com/210295. int tab_id = GetTabOrWindowSessionId(browser_context(), caller_contents); if (tab_id < 0) - return RespondNow(Error("Not called from a tab or app window")); + return Respond(Error("Not called from a tab or app window")); // Registry lives on its own task runner. chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask( @@ -180,8 +215,7 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { base::Bind( &TerminalPrivateOpenTerminalProcessFunction::RespondOnUIThread, this), - arguments, user_id_hash)); - return RespondLater(); + arguments, UserIdHash())); } void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner( @@ -197,8 +231,8 @@ void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner( bool success = registry->OpenProcess(cmdline, user_id_hash, output_callback, &terminal_id); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(callback, success, terminal_id)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(callback, success, terminal_id)); } TerminalPrivateSendInputFunction::~TerminalPrivateSendInputFunction() {} @@ -232,7 +266,7 @@ void TerminalPrivateSendInputFunction::SendInputOnRegistryTaskRunner( bool success = chromeos::ProcessProxyRegistry::Get()->SendInput(terminal_id, text); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TerminalPrivateSendInputFunction::RespondOnUIThread, this, success)); @@ -265,7 +299,7 @@ void TerminalPrivateCloseTerminalProcessFunction::CloseOnRegistryTaskRunner( bool success = chromeos::ProcessProxyRegistry::Get()->CloseProcess(terminal_id); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TerminalPrivateCloseTerminalProcessFunction::RespondOnUIThread, this, @@ -303,7 +337,7 @@ void TerminalPrivateOnTerminalResizeFunction::OnResizeOnRegistryTaskRunner( bool success = chromeos::ProcessProxyRegistry::Get()->OnTerminalResize( terminal_id, width, height); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TerminalPrivateOnTerminalResizeFunction::RespondOnUIThread, this, 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 601c34eb004..802d2f7c445 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h @@ -13,8 +13,7 @@ namespace extensions { // Opens new terminal process. Returns the new terminal id. -class TerminalPrivateOpenTerminalProcessFunction - : public UIThreadExtensionFunction { +class TerminalPrivateOpenTerminalProcessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.openTerminalProcess", TERMINALPRIVATE_OPENTERMINALPROCESS) @@ -34,6 +33,8 @@ class TerminalPrivateOpenTerminalProcessFunction using OpenProcessCallback = base::Callback<void(bool success, const std::string& terminal_id)>; + std::string UserIdHash(); + void OpenProcess(const std::vector<std::string> arguments); void OpenOnRegistryTaskRunner(const ProcessOutputCallback& output_callback, const OpenProcessCallback& callback, const std::vector<std::string>& arguments, @@ -43,7 +44,7 @@ class TerminalPrivateOpenTerminalProcessFunction // Send input to the terminal process specified by the terminal ID, which is set // as an argument. -class TerminalPrivateSendInputFunction : public UIThreadExtensionFunction { +class TerminalPrivateSendInputFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.sendInput", TERMINALPRIVATE_SENDINPUT) @@ -60,8 +61,7 @@ class TerminalPrivateSendInputFunction : public UIThreadExtensionFunction { }; // Closes terminal process. -class TerminalPrivateCloseTerminalProcessFunction - : public UIThreadExtensionFunction { +class TerminalPrivateCloseTerminalProcessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.closeTerminalProcess", TERMINALPRIVATE_CLOSETERMINALPROCESS) @@ -77,8 +77,7 @@ class TerminalPrivateCloseTerminalProcessFunction }; // Called by extension when terminal size changes. -class TerminalPrivateOnTerminalResizeFunction - : public UIThreadExtensionFunction { +class TerminalPrivateOnTerminalResizeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.onTerminalResize", TERMINALPRIVATE_ONTERMINALRESIZE) @@ -95,7 +94,7 @@ class TerminalPrivateOnTerminalResizeFunction void RespondOnUIThread(bool success); }; -class TerminalPrivateAckOutputFunction : public UIThreadExtensionFunction { +class TerminalPrivateAckOutputFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.ackOutput", TERMINALPRIVATE_ACKOUTPUT) diff --git a/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h b/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h index 1b8689303ef..0bcfa273d1a 100644 --- a/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h +++ b/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h @@ -10,7 +10,7 @@ namespace extensions { -class TopSitesGetFunction : public UIThreadExtensionFunction { +class TopSitesGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("topSites.get", TOPSITES_GET) 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 7f27757fb74..2a0832b667a 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 @@ -163,7 +163,7 @@ namespace extensions { ChromeVirtualKeyboardDelegate::ChromeVirtualKeyboardDelegate( content::BrowserContext* browser_context) - : browser_context_(browser_context), weak_factory_(this) { + : browser_context_(browser_context) { weak_this_ = weak_factory_.GetWeakPtr(); } @@ -361,7 +361,6 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices( features->AppendString(GenerateFeatureFlag("gestureediting", false)); features->AppendString(GenerateFeatureFlag("fullscreenhandwriting", false)); features->AppendString(GenerateFeatureFlag("virtualkeyboardmdui", true)); - features->AppendString(GenerateFeatureFlag("imeservice", true)); keyboard::KeyboardConfig config = keyboard_client->GetKeyboardConfig(); // TODO(oka): Change this to use config.voice_input. @@ -378,8 +377,14 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices( "handwritinggesture", base::FeatureList::IsEnabled(features::kHandwritingGesture))); features->AppendString(GenerateFeatureFlag( + "hmminputlogic", + base::FeatureList::IsEnabled(chromeos::features::kImeInputLogicHmm))); + features->AppendString(GenerateFeatureFlag( "fstinputlogic", base::FeatureList::IsEnabled(chromeos::features::kImeInputLogicFst))); + features->AppendString(GenerateFeatureFlag( + "fstnonenglish", base::FeatureList::IsEnabled( + chromeos::features::kImeInputLogicFstNonEnglish))); results->Set("features", std::move(features)); diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h index cb2cc995a7f..96a8b6d3194 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h @@ -65,7 +65,7 @@ class ChromeVirtualKeyboardDelegate : public VirtualKeyboardDelegate { content::BrowserContext* browser_context_; std::unique_ptr<media::AudioSystem> audio_system_; base::WeakPtr<ChromeVirtualKeyboardDelegate> weak_this_; - base::WeakPtrFactory<ChromeVirtualKeyboardDelegate> weak_factory_; + base::WeakPtrFactory<ChromeVirtualKeyboardDelegate> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ChromeVirtualKeyboardDelegate); }; 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 7677465aa8f..98483bc6950 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 @@ -9,7 +9,6 @@ #include <memory> #include "base/no_destructor.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api_constants.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h" #include "chrome/browser/extensions/extension_tab_util.h" @@ -19,8 +18,6 @@ #include "chrome/common/extensions/api/web_navigation.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_handle.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/notification_types.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" @@ -51,41 +48,36 @@ TabObserverMap& GetTabObserverMap() { // WebNavigtionEventRouter ------------------------------------------- -WebNavigationEventRouter::PendingWebContents::PendingWebContents() - : source_web_contents(NULL), - source_frame_host(NULL), - target_web_contents(NULL), - target_url() { -} +WebNavigationEventRouter::PendingWebContents::PendingWebContents() = default; +WebNavigationEventRouter::PendingWebContents::~PendingWebContents() {} -WebNavigationEventRouter::PendingWebContents::PendingWebContents( - content::WebContents* source_web_contents, - content::RenderFrameHost* source_frame_host, +void WebNavigationEventRouter::PendingWebContents::Set( + int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, content::WebContents* target_web_contents, - const GURL& target_url) - : source_web_contents(source_web_contents), - source_frame_host(source_frame_host), - target_web_contents(target_web_contents), - target_url(target_url) { + const GURL& target_url, + base::OnceCallback<void(content::WebContents*)> on_destroy) { + Observe(target_web_contents); + source_tab_id_ = source_tab_id; + source_render_process_id_ = source_render_process_id; + source_extension_frame_id_ = source_extension_frame_id; + target_web_contents_ = target_web_contents; + target_url_ = target_url; + on_destroy_ = std::move(on_destroy); } -WebNavigationEventRouter::PendingWebContents::~PendingWebContents() {} +void WebNavigationEventRouter::PendingWebContents::WebContentsDestroyed() { + std::move(on_destroy_).Run(target_web_contents_); + // |this| is deleted! +} WebNavigationEventRouter::WebNavigationEventRouter(Profile* profile) : profile_(profile), browser_tab_strip_tracker_(this, this, nullptr) { - CHECK(registrar_.IsEmpty()); - registrar_.Add(this, - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - registrar_.Add(this, - content::NOTIFICATION_WEB_CONTENTS_DESTROYED, - content::NotificationService::AllSources()); - browser_tab_strip_tracker_.Init(); } -WebNavigationEventRouter::~WebNavigationEventRouter() { -} +WebNavigationEventRouter::~WebNavigationEventRouter() = default; bool WebNavigationEventRouter::ShouldTrackBrowser(Browser* browser) { return profile_->IsSameProfile(browser->profile()); @@ -95,42 +87,26 @@ void WebNavigationEventRouter::OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) { - if (change.type() != TabStripModelChange::kReplaced) - return; - - auto* replace = change.GetReplace(); - WebNavigationTabObserver* tab_observer = - WebNavigationTabObserver::Get(replace->old_contents); - - if (!tab_observer) { - // If you hit this DCHECK(), please add reproduction steps to - // http://crbug.com/109464. - DCHECK(GetViewType(replace->old_contents) != VIEW_TYPE_TAB_CONTENTS); - return; - } - if (!FrameNavigationState::IsValidUrl(replace->old_contents->GetURL()) || - !FrameNavigationState::IsValidUrl(replace->new_contents->GetURL())) - return; - - web_navigation_api_helpers::DispatchOnTabReplaced( - replace->old_contents, profile_, replace->new_contents); -} - -void WebNavigationEventRouter::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - switch (type) { - case chrome::NOTIFICATION_TAB_ADDED: - TabAdded(content::Details<content::WebContents>(details).ptr()); - break; - - case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: - TabDestroyed(content::Source<content::WebContents>(source).ptr()); - break; - - default: - NOTREACHED(); + if (change.type() == TabStripModelChange::kReplaced) { + auto* replace = change.GetReplace(); + WebNavigationTabObserver* tab_observer = + WebNavigationTabObserver::Get(replace->old_contents); + + if (!tab_observer) { + // If you hit this DCHECK(), please add reproduction steps to + // http://crbug.com/109464. + DCHECK(GetViewType(replace->old_contents) != VIEW_TYPE_TAB_CONTENTS); + return; + } + if (!FrameNavigationState::IsValidUrl(replace->old_contents->GetURL()) || + !FrameNavigationState::IsValidUrl(replace->new_contents->GetURL())) + return; + + web_navigation_api_helpers::DispatchOnTabReplaced( + replace->old_contents, profile_, replace->new_contents); + } else if (change.type() == TabStripModelChange::kInserted) { + for (auto& tab : change.GetInsert()->contents) + TabAdded(tab.contents); } } @@ -159,15 +135,23 @@ void WebNavigationEventRouter::RecordNewWebContents( if (!frame_navigation_state.CanSendEvents(frame_host)) return; + int source_extension_frame_id = + ExtensionApiFrameIdMap::GetFrameId(frame_host); + int source_tab_id = ExtensionTabUtil::GetTabId(source_web_contents); + // If the WebContents isn't yet inserted into a tab strip, we need to delay // the extension event until the WebContents is fully initialized. if (not_yet_in_tabstrip) { - pending_web_contents_[target_web_contents] = PendingWebContents( - source_web_contents, frame_host, target_web_contents, target_url); + pending_web_contents_[target_web_contents].Set( + source_tab_id, source_render_process_id, source_extension_frame_id, + target_web_contents, target_url, + base::BindOnce(&WebNavigationEventRouter::PendingWebContentsDestroyed, + base::Unretained(this))); } else { web_navigation_api_helpers::DispatchOnCreatedNavigationTarget( - source_web_contents, target_web_contents->GetBrowserContext(), - frame_host, target_web_contents, target_url); + source_tab_id, source_render_process_id, source_extension_frame_id, + target_web_contents->GetBrowserContext(), target_web_contents, + target_url); } } @@ -176,34 +160,18 @@ void WebNavigationEventRouter::TabAdded(content::WebContents* tab) { if (iter == pending_web_contents_.end()) return; - WebNavigationTabObserver* tab_observer = - WebNavigationTabObserver::Get(iter->second.source_web_contents); - if (!tab_observer) { - NOTREACHED(); - return; - } - const FrameNavigationState& frame_navigation_state = - tab_observer->frame_navigation_state(); - - if (frame_navigation_state.CanSendEvents(iter->second.source_frame_host)) { - web_navigation_api_helpers::DispatchOnCreatedNavigationTarget( - iter->second.source_web_contents, - iter->second.target_web_contents->GetBrowserContext(), - iter->second.source_frame_host, iter->second.target_web_contents, - iter->second.target_url); - } + const PendingWebContents& pending_tab = iter->second; + web_navigation_api_helpers::DispatchOnCreatedNavigationTarget( + pending_tab.source_tab_id(), pending_tab.source_render_process_id(), + pending_tab.source_extension_frame_id(), + pending_tab.target_web_contents()->GetBrowserContext(), + pending_tab.target_web_contents(), pending_tab.target_url()); pending_web_contents_.erase(iter); } -void WebNavigationEventRouter::TabDestroyed(content::WebContents* tab) { +void WebNavigationEventRouter::PendingWebContentsDestroyed( + content::WebContents* tab) { pending_web_contents_.erase(tab); - for (auto i = pending_web_contents_.begin(); - i != pending_web_contents_.end();) { - if (i->second.source_web_contents == tab) - pending_web_contents_.erase(i++); - else - ++i; - } } // WebNavigationTabObserver ------------------------------------------ @@ -264,14 +232,14 @@ void WebNavigationTabObserver::DidStartNavigation( // and sent after the addition, to preserve the ordering of events. // // TODO(nasko|devlin): This check is necessary because chrome::Navigate() - // begins the navigation before the sending the TAB_ADDED notification, and it + // begins the navigation before adding the tab to the TabStripModel, and it // is used an indication of that. It would be best if instead it was known // when the tab was created and immediately sent the created event instead of - // waiting for the later TAB_ADDED notification, but this appears to work for - // now. + // waiting for the later TabStripModel kInserted change, but this appears to + // work for now. if (ExtensionTabUtil::GetTabById(ExtensionTabUtil::GetTabId(web_contents()), web_contents()->GetBrowserContext(), false, - nullptr, nullptr, nullptr, nullptr)) { + nullptr)) { DispatchCachedOnBeforeNavigate(); } } @@ -400,7 +368,6 @@ void WebNavigationTabObserver::DidOpenRequestedURL( void WebNavigationTabObserver::WebContentsDestroyed() { GetTabObserverMap().erase(web_contents()); - registrar_.RemoveAll(); } void WebNavigationTabObserver::DispatchCachedOnBeforeNavigate() { @@ -500,8 +467,8 @@ ExtensionFunction::ResponseAction WebNavigationGetFrameFunction::Run() { content::WebContents* web_contents; if (!ExtensionTabUtil::GetTabById(tab_id, browser_context(), - include_incognito_information(), nullptr, - nullptr, &web_contents, nullptr) || + include_incognito_information(), + &web_contents) || !web_contents) { return RespondNow(OneArgument(std::make_unique<base::Value>())); } @@ -540,8 +507,8 @@ ExtensionFunction::ResponseAction WebNavigationGetAllFramesFunction::Run() { content::WebContents* web_contents; if (!ExtensionTabUtil::GetTabById(tab_id, browser_context(), - include_incognito_information(), nullptr, - nullptr, &web_contents, nullptr) || + include_incognito_information(), + &web_contents) || !web_contents) { return RespondNow(OneArgument(std::make_unique<base::Value>())); } 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 d76a63e1fcb..d5169edb107 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 @@ -11,6 +11,7 @@ #include <map> #include <set> +#include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "chrome/browser/extensions/api/web_navigation/frame_navigation_state.h" @@ -19,8 +20,6 @@ #include "chrome/browser/ui/browser_tab_strip_tracker.h" #include "chrome/browser/ui/browser_tab_strip_tracker_delegate.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/browser_context_keyed_api_factory.h" @@ -97,19 +96,14 @@ class WebNavigationTabObserver // the tab strip and is ready to dispatch events. std::unique_ptr<Event> pending_on_before_navigate_event_; - // Used for tracking registrations to redirect notifications. - content::NotificationRegistrar registrar_; - WEB_CONTENTS_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(WebNavigationTabObserver); }; -// Observes navigation notifications and routes them as events to the extension -// system. +// Tracks new tab navigations and routes them as events to the extension system. class WebNavigationEventRouter : public TabStripModelObserver, - public BrowserTabStripTrackerDelegate, - public content::NotificationObserver { + public BrowserTabStripTrackerDelegate { public: explicit WebNavigationEventRouter(Profile* profile); ~WebNavigationEventRouter() override; @@ -117,7 +111,7 @@ class WebNavigationEventRouter : public TabStripModelObserver, // Router level handler for the creation of WebContents. Stores information // about the newly created WebContents. This information is later used when // the WebContents for the tab is added to the tabstrip and we receive the - // TAB_ADDED notification. + // TabStripModelChanged insertion. void RecordNewWebContents(content::WebContents* source_web_contents, int source_render_process_id, int source_render_frame_id, @@ -127,18 +121,42 @@ class WebNavigationEventRouter : public TabStripModelObserver, private: // Used to cache the information about newly created WebContents objects. - struct PendingWebContents{ + // Will run |on_destroy_| if/when the target WebContents is destroyed. + class PendingWebContents : public content::WebContentsObserver { + public: PendingWebContents(); - PendingWebContents(content::WebContents* source_web_contents, - content::RenderFrameHost* source_frame_host, - content::WebContents* target_web_contents, - const GURL& target_url); - ~PendingWebContents(); - - content::WebContents* source_web_contents; - content::RenderFrameHost* source_frame_host; - content::WebContents* target_web_contents; - GURL target_url; + ~PendingWebContents() override; + + void Set(int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, + content::WebContents* target_web_contents, + const GURL& target_url, + base::OnceCallback<void(content::WebContents*)> on_destroy); + + // content::WebContentsObserver: + void WebContentsDestroyed() override; + + int source_tab_id() const { return source_tab_id_; } + int source_render_process_id() const { return source_render_process_id_; } + int source_extension_frame_id() const { return source_extension_frame_id_; } + content::WebContents* target_web_contents() const { + return target_web_contents_; + } + GURL target_url() const { return target_url_; } + + private: + // The Extensions API ID for the source tab. + int source_tab_id_ = -1; + // The source frame's RenderProcessHost ID. + int source_render_process_id_ = -1; + // The Extensions API ID for the source frame. + int source_extension_frame_id_ = -1; + content::WebContents* target_web_contents_ = nullptr; + GURL target_url_; + base::OnceCallback<void(content::WebContents*)> on_destroy_; + + DISALLOW_COPY_AND_ASSIGN(PendingWebContents); }; // BrowserTabStripTrackerDelegate implementation. @@ -150,26 +168,17 @@ class WebNavigationEventRouter : public TabStripModelObserver, const TabStripModelChange& change, const TabStripSelectionChange& selection) override; - // content::NotificationObserver implementation. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - - // Handler for the NOTIFICATION_TAB_ADDED event. The method takes the details - // of such an event and creates a JSON formated extension event from it. + // The method takes the details of such an event and creates a JSON formatted + // extension event from it. void TabAdded(content::WebContents* tab); - // Handler for NOTIFICATION_WEB_CONTENTS_DESTROYED. If |tab| is in - // |pending_web_contents_|, it is removed. - void TabDestroyed(content::WebContents* tab); + // Removes |tab| from |pending_web_contents_| if it is there. + void PendingWebContentsDestroyed(content::WebContents* tab); // Mapping pointers to WebContents objects to information about how they got // created. std::map<content::WebContents*, PendingWebContents> pending_web_contents_; - // Used for tracking registrations to navigation notifications. - content::NotificationRegistrar registrar_; - // The profile that owns us via ExtensionService. Profile* profile_; @@ -179,14 +188,14 @@ class WebNavigationEventRouter : public TabStripModelObserver, }; // API function that returns the state of a given frame. -class WebNavigationGetFrameFunction : public UIThreadExtensionFunction { +class WebNavigationGetFrameFunction : public ExtensionFunction { ~WebNavigationGetFrameFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("webNavigation.getFrame", WEBNAVIGATION_GETFRAME) }; // API function that returns the states of all frames in a given tab. -class WebNavigationGetAllFramesFunction : public UIThreadExtensionFunction { +class WebNavigationGetAllFramesFunction : public ExtensionFunction { ~WebNavigationGetAllFramesFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("webNavigation.getAllFrames", diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc index ce5b7603702..2f27a224fd5 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc @@ -192,9 +192,10 @@ void DispatchOnCompleted(content::WebContents* web_contents, // Constructs and dispatches an onCreatedNavigationTarget event. void DispatchOnCreatedNavigationTarget( - content::WebContents* web_contents, + int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, content::BrowserContext* browser_context, - content::RenderFrameHost* source_frame_host, content::WebContents* target_web_contents, const GURL& target_url) { // Check that the tab is already inserted into a tab strip model. This code @@ -202,13 +203,12 @@ void DispatchOnCreatedNavigationTarget( DCHECK(ExtensionTabUtil::GetTabById( ExtensionTabUtil::GetTabId(target_web_contents), Profile::FromBrowserContext(target_web_contents->GetBrowserContext()), - false, NULL, NULL, NULL, NULL)); + false, nullptr)); web_navigation::OnCreatedNavigationTarget::Details details; - details.source_tab_id = ExtensionTabUtil::GetTabId(web_contents); - details.source_process_id = source_frame_host->GetProcess()->GetID(); - details.source_frame_id = - ExtensionApiFrameIdMap::GetFrameId(source_frame_host); + details.source_tab_id = source_tab_id; + details.source_process_id = source_render_process_id; + details.source_frame_id = source_extension_frame_id; details.url = target_url.possibly_invalid_spec(); details.tab_id = ExtensionTabUtil::GetTabId(target_web_contents); details.time_stamp = MilliSecondsFromTime(base::Time::Now()); diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h index 5a447c9285a..10d3658c2a6 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h @@ -48,9 +48,10 @@ void DispatchOnCompleted(content::WebContents* web_contents, const GURL& url); void DispatchOnCreatedNavigationTarget( - content::WebContents* web_contents, + int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, content::BrowserContext* browser_context, - content::RenderFrameHost* source_frame_host, content::WebContents* target_web_contents, const GURL& target_url); diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc index b06f9750014..2110bfc8a4e 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc @@ -23,7 +23,6 @@ #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/ui/browser.h" @@ -44,7 +43,7 @@ #include "content/public/test/download_test_observer.h" #include "content/public/test/no_renderer_crashes_assertion.h" #include "content/public/test/test_utils.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" #include "extensions/common/switches.h" #include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" @@ -77,7 +76,7 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, delay_url_(delay_url), until_url_suffix_(until_url_suffix), script_(script) { - tab_strip_observer_.Add(browser->tab_strip_model()); + browser->tab_strip_model()->AddObserver(this); } ~DelayLoadStartAndExecuteJavascript() override {} @@ -92,7 +91,7 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, content::WebContentsObserver::Observe( change.GetInsert()->contents[0].contents); - tab_strip_observer_.RemoveAll(); + tab_strip_model->RemoveObserver(this); } // WebContentsObserver: @@ -166,8 +165,6 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, base::WeakPtr<WillStartRequestObserverThrottle> throttle_; - ScopedObserver<TabStripModel, TabStripModelObserver> tab_strip_observer_{ - this}; GURL delay_url_; std::string until_url_suffix_; std::string script_; @@ -360,10 +357,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, MAYBE_UserAction) { ResultCatcher catcher; - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); const extensions::Extension* extension = - service->GetExtensionById(last_loaded_extension_id(), false); + extension_registry()->GetExtensionById(last_loaded_extension_id(), + ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL( "a.html?" + base::NumberToString(embedded_test_server()->port())); @@ -400,10 +396,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { ResultCatcher catcher; - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); const extensions::Extension* extension = - service->GetExtensionById(last_loaded_extension_id(), false); + extension_registry()->GetExtensionById(last_loaded_extension_id(), + ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL("a.html"); ui_test_utils::NavigateToURL(browser(), 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 e0dbdfd790e..2e416ee7641 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 @@ -39,7 +39,7 @@ #include "components/prefs/pref_member.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/common/url_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/upload_data_presenter.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" @@ -154,7 +154,7 @@ class TestIPCSender : public IPC::Sender { class ExtensionWebRequestTest : public testing::Test { public: ExtensionWebRequestTest() - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP), profile_manager_(TestingBrowserProcess::GetGlobal()) {} protected: @@ -162,7 +162,7 @@ class ExtensionWebRequestTest : public testing::Test { ASSERT_TRUE(profile_manager_.SetUp()); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; TestingProfileManager profile_manager_; }; 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 1398d76db6b..622cdec21a1 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 @@ -78,7 +78,8 @@ #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/blocked_action_type.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/process_manager.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_features.h" #include "extensions/common/features/feature.h" @@ -93,6 +94,7 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +#include "net/test/embedded_test_server/request_handler_util.h" #include "net/test/test_data_directory.h" #include "net/test/url_request/url_request_mock_http_job.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" @@ -242,41 +244,6 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest { const char* expected_content_regular_window, const char* exptected_content_incognito_window); - void InstallRequestHeaderModifyingExtension() { - TestExtensionDir test_dir; - test_dir.WriteManifest(R"({ - "name": "Web Request Header Modifying Extension", - "manifest_version": 2, - "version": "0.1", - "background": { "scripts": ["background.js"] }, - "permissions": ["<all_urls>", "webRequest", "webRequestBlocking"] - })"); - test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"( - chrome.webRequest.onBeforeSendHeaders.addListener(function(details) { - details.requestHeaders.push({name: 'foo', value: 'bar'}); - details.requestHeaders.push({ - name: 'frameId', - value: details.frameId.toString() - }); - details.requestHeaders.push({ - name: 'resourceType', - value: details.type - }); - return {requestHeaders: details.requestHeaders}; - }, {urls: ['*://*/echoheader*']}, ['blocking', 'requestHeaders']); - - chrome.test.sendMessage('ready'); - )"); - - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath())); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - } - - // Ensures requests made by the |worker_script_name| service worker can be - // intercepted by extensions. - void RunServiceWorkerFetchTest(const std::string& worker_script_name); - network::mojom::URLLoaderFactoryPtr CreateURLLoaderFactory() { network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); @@ -305,18 +272,6 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest { test_dirs_.push_back(std::move(dir)); } - void RegisterServiceWorker(const std::string& worker_path, - const base::Optional<std::string>& scope) { - GURL url = embedded_test_server()->GetURL( - "/service_worker/create_service_worker.html"); - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - std::string script = content::JsReplace("register($1, $2);", worker_path, - scope ? *scope : std::string()); - EXPECT_EQ( - "DONE", - EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), script)); - } - private: std::vector<std::unique_ptr<TestExtensionDir>> test_dirs_; }; @@ -534,8 +489,15 @@ IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest, << message_; } +// TODO(crbug.com/998369): Flaky on Win ASAN. +#if defined(OS_WIN) && defined(ADDRESS_SANITIZER) +#define MAYBE_WebRequestAuthRequiredParallel \ + DISABLED_WebRequestAuthRequiredParallel +#else +#define MAYBE_WebRequestAuthRequiredParallel WebRequestAuthRequiredParallel +#endif IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest, - WebRequestAuthRequiredParallel) { + MAYBE_WebRequestAuthRequiredParallel) { CancelLoginDialog login_dialog_helper; ASSERT_TRUE(StartEmbeddedTestServer()); @@ -581,6 +543,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestExtraHeaders) { << message_; } +IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, + WebRequestCORSWithExtraHeaders) { + ASSERT_TRUE(StartEmbeddedTestServer()); + ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_cors.html")) << message_; +} + IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestRedirects) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_redirects.html")) @@ -652,10 +620,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestNewTab) { ResultCatcher catcher; - ExtensionService* service = - ExtensionSystem::Get(browser()->profile())->extension_service(); - const Extension* extension = - service->GetExtensionById(last_loaded_extension_id(), false); + ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + const Extension* extension = registry->GetExtensionById( + last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL("newTab/a.html"); ui_test_utils::NavigateToURL(browser(), url); @@ -758,30 +725,6 @@ void ExtensionWebRequestApiTest::RunPermissionTest( EXPECT_EQ(exptected_content_incognito_window, body); } -void ExtensionWebRequestApiTest::RunServiceWorkerFetchTest( - const std::string& worker_script_name) { - embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); - ASSERT_TRUE(embedded_test_server()->Start()); - - // Install the test extension. - InstallRequestHeaderModifyingExtension(); - - // Register a service worker and navigate to a page it controls. - RegisterServiceWorker(worker_script_name, base::nullopt); - EXPECT_TRUE(ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/service_worker/fetch_from_page.html"))); - - // Make a fetch from the controlled page. Depending on the worker script, the - // fetch might go to the service worker and be re-issued, or might fallback to - // network, or skip the worker, etc. In any case, this function expects a - // network request to happen, and that the extension modify the headers of the - // request before it goes to network. Verify that it was able to inject a - // header of "foo=bar". - EXPECT_EQ("bar", EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), - "fetch_from_page('/echoheader?foo');")); -} - IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestDeclarativePermissionSpanning1) { // Test spanning with incognito permission. @@ -949,9 +892,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HostedAppRequest) { .Build()) .Build()) .Build(); - ExtensionSystem::Get(browser()->profile()) - ->extension_service() - ->AddExtension(hosted_app.get()); + extension_service()->AddExtension(hosted_app.get()); ExtensionTestMessageListener listener1("main_frame", false); ExtensionTestMessageListener listener2("xmlhttprequest", false); @@ -1778,7 +1719,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, content::RenderFrameHost* frame = temp_web_contents->GetMainFrame(); EXPECT_TRUE(api->MaybeProxyURLLoaderFactory( frame->GetProcess()->GetBrowserContext(), frame, - frame->GetProcess()->GetID(), false, false, &pending_receiver, nullptr)); + frame->GetProcess()->GetID(), + content::ContentBrowserClient::URLLoaderFactoryType::kDocumentSubResource, + &pending_receiver, nullptr)); temp_web_contents.reset(); auto params = network::mojom::URLLoaderFactoryParams::New(); params->process_id = 0; @@ -2498,22 +2441,177 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, RemoveHeaderUMAs) { ResponseHeaderType::kNone, 1); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ServiceWorkerFetch) { +// The parameter is for opt_extraInfoSpec passed to addEventListener. +// 'blocking' and 'requestHeaders' if it's false, and 'extraHeaders' in addition +// to them if it's true. +class ServiceWorkerWebRequestApiTest : public testing::WithParamInterface<bool>, + public ExtensionApiTest { + public: + // The options passed as opt_extraInfoSpec to addEventListener. + enum class ExtraInfoSpec { + // 'blocking', 'requestHeaders' + kDefault, + // kDefault + 'extraHeaders' + kExtraHeaders + }; + + static ExtraInfoSpec GetExtraInfoSpec() { + return GetParam() ? ExtraInfoSpec::kExtraHeaders : ExtraInfoSpec::kDefault; + } + + void InstallRequestHeaderModifyingExtension() { + TestExtensionDir test_dir; + test_dir.WriteManifest(R"({ + "name": "Web Request Header Modifying Extension", + "manifest_version": 2, + "version": "0.1", + "background": { "scripts": ["background.js"] }, + "permissions": ["<all_urls>", "webRequest", "webRequestBlocking"] + })"); + + const char kBackgroundScript[] = R"( + chrome.webRequest.onBeforeSendHeaders.addListener(function(details) { + details.requestHeaders.push({name: 'foo', value: 'bar'}); + details.requestHeaders.push({ + name: 'frameId', + value: details.frameId.toString() + }); + details.requestHeaders.push({ + name: 'resourceType', + value: details.type + }); + return {requestHeaders: details.requestHeaders}; + }, + {urls: ['*://*/echoheader*']}, + [%s]); + + chrome.test.sendMessage('ready'); + )"; + std::string opt_extra_info_spec = "'blocking', 'requestHeaders'"; + if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) + opt_extra_info_spec += ", 'extraHeaders'"; + test_dir.WriteFile( + FILE_PATH_LITERAL("background.js"), + base::StringPrintf(kBackgroundScript, opt_extra_info_spec.c_str())); + + ExtensionTestMessageListener listener("ready", false); + ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath())); + EXPECT_TRUE(listener.WaitUntilSatisfied()); + } + + void RegisterServiceWorker(const std::string& worker_path, + const base::Optional<std::string>& scope) { + GURL url = embedded_test_server()->GetURL( + "/service_worker/create_service_worker.html"); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + std::string script = content::JsReplace("register($1, $2);", worker_path, + scope ? *scope : std::string()); + EXPECT_EQ( + "DONE", + EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), script)); + } + + // Ensures requests made by the |worker_script_name| service worker can be + // intercepted by extensions. + void RunServiceWorkerFetchTest(const std::string& worker_script_name) { + embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); + ASSERT_TRUE(embedded_test_server()->Start()); + + // Install the test extension. + InstallRequestHeaderModifyingExtension(); + + // Register a service worker and navigate to a page it controls. + RegisterServiceWorker(worker_script_name, base::nullopt); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL( + "/service_worker/fetch_from_page.html"))); + + // Make a fetch from the controlled page. Depending on the worker script, + // the fetch might go to the service worker and be re-issued, or might + // fallback to network, or skip the worker, etc. In any case, this function + // expects a network request to happen, and that the extension modify the + // headers of the request before it goes to network. Verify that it was able + // to inject a header of "foo=bar". + EXPECT_EQ("bar", + EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), + "fetch_from_page('/echoheader?foo');")); + } +}; + +INSTANTIATE_TEST_SUITE_P(/* No prefix */, + ServiceWorkerWebRequestApiTest, + ::testing::Bool()); + +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerFetch) { RunServiceWorkerFetchTest("fetch_event_respond_with_fetch.js"); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ServiceWorkerFallback) { +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerFallback) { RunServiceWorkerFetchTest("fetch_event_pass_through.js"); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerNoFetchHandler) { RunServiceWorkerFetchTest("empty.js"); } +// An extension should be able to modify the request header for service worker +// script by using WebRequest API. +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerScript) { + // The extension to be used in this test adds foo=bar request header. + const char kScriptPath[] = "/echoheader_service_worker.js"; + int served_service_worker_count = 0; + std::string foo_header_value; + + // Capture the value of a request header foo, which should be added if + // extension modifies the request header. + embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting( + [&](const net::test_server::HttpRequest& request) + -> std::unique_ptr<net::test_server::HttpResponse> { + if (request.relative_url != kScriptPath) + return nullptr; + + ++served_service_worker_count; + foo_header_value.clear(); + if (request.headers.find("foo") != request.headers.end()) + foo_header_value = request.headers.at("foo"); + + auto response = std::make_unique<net::test_server::BasicHttpResponse>(); + response->set_code(net::HTTP_OK); + response->set_content_type("text/javascript"); + response->AddCustomHeader("Cache-Control", "no-cache"); + response->set_content("// empty"); + return response; + })); + ASSERT_TRUE(embedded_test_server()->Start()); + + InstallRequestHeaderModifyingExtension(); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + GURL url = embedded_test_server()->GetURL( + "/service_worker/create_service_worker.html"); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + + // Register a service worker. The worker script should have "foo: bar" request + // header added by the extension. + std::string script = + content::JsReplace("register($1, './in-scope');", kScriptPath); + EXPECT_EQ("DONE", EvalJs(web_contents, script)); + EXPECT_EQ(1, served_service_worker_count); + EXPECT_EQ("bar", foo_header_value); + + // Update the worker. The worker should have "foo: bar" request header in the + // request for update checking. + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_EQ("DONE", EvalJs(web_contents, "update('./in-scope');")); + EXPECT_EQ(2, served_service_worker_count); + EXPECT_EQ("bar", foo_header_value); +} + // Ensure that extensions can intercept service worker navigation preload // requests. -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerNavigationPreload) { ASSERT_TRUE(embedded_test_server()->Start()); diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc index c73e3247c93..d58a7afb20d 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc @@ -11,7 +11,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chrome/common/url_constants.h" #include "chromeos/login/login_state/scoped_test_public_session_login_state.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/permission_helper.h" #include "extensions/browser/api/web_request/web_request_info.h" #include "extensions/browser/api/web_request/web_request_permissions.h" diff --git a/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h b/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h index 9ca71edf5f6..b9f63549d5a 100644 --- a/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h +++ b/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h @@ -17,7 +17,7 @@ namespace extensions { class ChromeWebViewInternalContextMenusCreateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusCreate", WEBVIEWINTERNAL_CONTEXTMENUSCREATE) @@ -26,7 +26,7 @@ class ChromeWebViewInternalContextMenusCreateFunction protected: ~ChromeWebViewInternalContextMenusCreateFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: @@ -34,7 +34,7 @@ class ChromeWebViewInternalContextMenusCreateFunction }; class ChromeWebViewInternalContextMenusUpdateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusUpdate", WEBVIEWINTERNAL_CONTEXTMENUSUPDATE) @@ -43,7 +43,7 @@ class ChromeWebViewInternalContextMenusUpdateFunction protected: ~ChromeWebViewInternalContextMenusUpdateFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: @@ -51,7 +51,7 @@ class ChromeWebViewInternalContextMenusUpdateFunction }; class ChromeWebViewInternalContextMenusRemoveFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusRemove", WEBVIEWINTERNAL_CONTEXTMENUSREMOVE) @@ -60,7 +60,7 @@ class ChromeWebViewInternalContextMenusRemoveFunction protected: ~ChromeWebViewInternalContextMenusRemoveFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: @@ -68,7 +68,7 @@ class ChromeWebViewInternalContextMenusRemoveFunction }; class ChromeWebViewInternalContextMenusRemoveAllFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusRemoveAll", WEBVIEWINTERNAL_CONTEXTMENUSREMOVEALL) @@ -77,7 +77,7 @@ class ChromeWebViewInternalContextMenusRemoveAllFunction protected: ~ChromeWebViewInternalContextMenusRemoveAllFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc index 3896f0b9e8f..bb110a5ba9b 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc @@ -150,8 +150,7 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest( int tab_id = *request.tab_id; content::WebContents* contents = nullptr; - if (!ExtensionTabUtil::GetTabById(tab_id, GetProfile(), true, nullptr, - nullptr, &contents, nullptr)) { + if (!ExtensionTabUtil::GetTabById(tab_id, GetProfile(), true, &contents)) { SetError(extensions::ErrorUtils::FormatErrorMessage( extensions::tabs_constants::kTabNotFoundError, base::NumberToString(tab_id))); @@ -176,8 +175,8 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest( return rph; } -WebRtcLoggingHandlerHost* -WebrtcLoggingPrivateFunction::LoggingHandlerFromRequest( +WebRtcLoggingController* +WebrtcLoggingPrivateFunction::LoggingControllerFromRequest( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin) { content::RenderProcessHost* host = RphFromRequest(request, security_origin); @@ -185,17 +184,17 @@ WebrtcLoggingPrivateFunction::LoggingHandlerFromRequest( // SetError() will have been called by RphFromRequest(). return nullptr; } - return WebRtcLoggingHandlerHost::FromRenderProcessHost(host); + return WebRtcLoggingController::FromRenderProcessHost(host); } -WebRtcLoggingHandlerHost* +WebRtcLoggingController* WebrtcLoggingPrivateFunctionWithGenericCallback::PrepareTask( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin, - WebRtcLoggingHandlerHost::GenericDoneCallback* callback) { + WebRtcLoggingController::GenericDoneCallback* callback) { *callback = base::Bind( &WebrtcLoggingPrivateFunctionWithGenericCallback::FireCallback, this); - return LoggingHandlerFromRequest(request, security_origin); + return LoggingControllerFromRequest(request, security_origin); } void WebrtcLoggingPrivateFunctionWithGenericCallback::FireCallback( @@ -245,17 +244,17 @@ bool WebrtcLoggingPrivateSetMetaDataFunction::RunAsync() { SetMetaData::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - std::unique_ptr<MetaDataMap> meta_data(new MetaDataMap()); + std::unique_ptr<WebRtcLogMetaDataMap> meta_data(new WebRtcLogMetaDataMap()); for (const MetaDataEntry& entry : params->meta_data) (*meta_data)[entry.key] = entry.value; - webrtc_logging_handler_host->SetMetaData(std::move(meta_data), callback); + webrtc_logging_controller->SetMetaData(std::move(meta_data), callback); return true; } @@ -263,13 +262,13 @@ bool WebrtcLoggingPrivateStartFunction::RunAsync() { std::unique_ptr<Start::Params> params(Start::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->StartLogging(callback); + webrtc_logging_controller->StartLogging(callback); return true; } @@ -278,18 +277,18 @@ bool WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::RunAsync() { SetUploadOnRenderClose::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost* webrtc_logging_handler_host( - LoggingHandlerFromRequest(params->request, params->security_origin)); - if (!webrtc_logging_handler_host) + WebRtcLoggingController* webrtc_logging_controller( + LoggingControllerFromRequest(params->request, params->security_origin)); + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->set_upload_log_on_render_close( + webrtc_logging_controller->set_upload_log_on_render_close( params->should_upload); // Post a task since this is an asynchronous extension function. // TODO(devlin): This is unneccessary; this should just be a - // UIThreadExtensionFunction. Fix this. - base::PostTaskWithTraits( + // ExtensionFunction. Fix this. + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::SendResponse, @@ -301,13 +300,13 @@ bool WebrtcLoggingPrivateStopFunction::RunAsync() { std::unique_ptr<Stop::Params> params(Stop::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->StopLogging(callback); + webrtc_logging_controller->StopLogging(callback); return true; } @@ -315,16 +314,16 @@ bool WebrtcLoggingPrivateStoreFunction::RunAsync() { std::unique_ptr<Store::Params> params(Store::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; const std::string local_log_id(HashIdWithOrigin(params->security_origin, params->log_id)); - webrtc_logging_handler_host->StoreLog(local_log_id, callback); + webrtc_logging_controller->StoreLog(local_log_id, callback); return true; } @@ -333,18 +332,18 @@ bool WebrtcLoggingPrivateUploadStoredFunction::RunAsync() { UploadStored::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost* logging_handler = - LoggingHandlerFromRequest(params->request, params->security_origin); - if (!logging_handler) + WebRtcLoggingController* logging_controller = + LoggingControllerFromRequest(params->request, params->security_origin); + if (!logging_controller) return false; - WebRtcLoggingHandlerHost::UploadDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateUploadStoredFunction::FireCallback, this); + WebRtcLoggingController::UploadDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateUploadStoredFunction::FireCallback, this); const std::string local_log_id(HashIdWithOrigin(params->security_origin, params->log_id)); - logging_handler->UploadStoredLog(local_log_id, callback); + logging_controller->UploadStoredLog(local_log_id, callback); return true; } @@ -352,15 +351,15 @@ bool WebrtcLoggingPrivateUploadFunction::RunAsync() { std::unique_ptr<Upload::Params> params(Upload::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost* logging_handler = - LoggingHandlerFromRequest(params->request, params->security_origin); - if (!logging_handler) + WebRtcLoggingController* logging_controller = + LoggingControllerFromRequest(params->request, params->security_origin); + if (!logging_controller) return false; - WebRtcLoggingHandlerHost::UploadDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateUploadFunction::FireCallback, this); + WebRtcLoggingController::UploadDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateUploadFunction::FireCallback, this); - logging_handler->UploadLog(callback); + logging_controller->UploadLog(callback); return true; } @@ -368,13 +367,13 @@ bool WebrtcLoggingPrivateDiscardFunction::RunAsync() { std::unique_ptr<Discard::Params> params(Discard::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->DiscardLog(callback); + webrtc_logging_controller->DiscardLog(callback); return true; } @@ -400,19 +399,13 @@ bool WebrtcLoggingPrivateStartRtpDumpFunction::RunAsync() { return false; } - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); - WebRtcLoggingHandlerHost::GenericDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateStartRtpDumpFunction::FireCallback, this); + WebRtcLoggingController::GenericDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateStartRtpDumpFunction::FireCallback, this); - // This call cannot fail. - content::RenderProcessHost::WebRtcStopRtpDumpCallback stop_callback = - host->StartRtpDump(params->incoming, params->outgoing, - base::Bind(&WebRtcLoggingHandlerHost::OnRtpPacket, - webrtc_logging_handler_host->GetWeakPtr())); - - webrtc_logging_handler_host->StartRtpDump(type, callback, stop_callback); + webrtc_logging_controller->StartRtpDump(type, callback); return true; } @@ -438,13 +431,13 @@ bool WebrtcLoggingPrivateStopRtpDumpFunction::RunAsync() { return false; } - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); - WebRtcLoggingHandlerHost::GenericDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateStopRtpDumpFunction::FireCallback, this); + WebRtcLoggingController::GenericDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateStopRtpDumpFunction::FireCallback, this); - webrtc_logging_handler_host->StopRtpDump(type, callback); + webrtc_logging_controller->StopRtpDump(type, callback); return true; } @@ -527,18 +520,18 @@ bool WebrtcLoggingPrivateStartEventLoggingFunction::RunAsync() { return false; } - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); - if (!webrtc_logging_handler_host) { - SetError("WebRTC logging handler not found."); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); + if (!webrtc_logging_controller) { + SetError("WebRTC logging controller not found."); return false; } - WebRtcLoggingHandlerHost::StartEventLoggingCallback callback = + WebRtcLoggingController::StartEventLoggingCallback callback = base::BindRepeating( &WebrtcLoggingPrivateStartEventLoggingFunction::FireCallback, this); - webrtc_logging_handler_host->StartEventLogging( + webrtc_logging_controller->StartEventLogging( params->session_id, params->max_log_size_bytes, params->output_period_ms, params->web_app_id, callback); return true; @@ -573,14 +566,14 @@ bool WebrtcLoggingPrivateGetLogsDirectoryFunction::RunAsync() { // that should be granted access to the logs directory. content::RenderProcessHost* host = render_frame_host()->GetProcess(); - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); - if (!webrtc_logging_handler_host) { - FireErrorCallback("WebRTC logging handler not found."); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); + if (!webrtc_logging_controller) { + FireErrorCallback("WebRTC logging controller not found."); return true; } - webrtc_logging_handler_host->GetLogsDirectory( + webrtc_logging_controller->GetLogsDirectory( base::Bind(&WebrtcLoggingPrivateGetLogsDirectoryFunction::FireCallback, this), base::Bind( diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h index 34b1124f71e..3ded513b39b 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h @@ -9,7 +9,7 @@ #include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h" -#include "chrome/browser/media/webrtc/webrtc_logging_handler_host.h" +#include "chrome/browser/media/webrtc/webrtc_logging_controller.h" #include "chrome/common/extensions/api/webrtc_logging_private.h" #include "media/media_buildflags.h" @@ -32,7 +32,7 @@ class WebrtcLoggingPrivateFunction : public ChromeAsyncExtensionFunction { const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin); - WebRtcLoggingHandlerHost* LoggingHandlerFromRequest( + WebRtcLoggingController* LoggingControllerFromRequest( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin); }; @@ -42,14 +42,14 @@ class WebrtcLoggingPrivateFunctionWithGenericCallback protected: ~WebrtcLoggingPrivateFunctionWithGenericCallback() override {} - // Finds the appropriate logging handler for performing the task and prepares - // a generic callback object for when the task is completed. - // If the logging handler can't be found for the given request+origin, the + // Finds the appropriate logging controller for performing the task and + // prepares a generic callback object for when the task is completed. If the + // logging controller can't be found for the given request+origin, the // returned ptr will be null. - WebRtcLoggingHandlerHost* PrepareTask( + WebRtcLoggingController* PrepareTask( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin, - WebRtcLoggingHandlerHost::GenericDoneCallback* callback); + WebRtcLoggingController::GenericDoneCallback* callback); // Must be called on UI thread. void FireCallback(bool success, const std::string& error_message); diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc index ce5a5c00e6e..dcff38d5276 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 @@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/lazy_instance.h" #include "base/macros.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -234,7 +235,7 @@ WebstorePrivateBeginInstallWithManifest3Function::Run() { .get(); } - scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper( + auto helper = base::MakeRefCounted<WebstoreInstallHelper>( this, details().id, details().manifest, icon_url); // The helper will call us back via OnWebstoreParseSuccess or diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h index 0e74942a8fd..72f65444b0c 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h @@ -42,7 +42,7 @@ class WebstorePrivateApi { }; class WebstorePrivateBeginInstallWithManifest3Function - : public UIThreadExtensionFunction, + : public ExtensionFunction, public WebstoreInstallHelper::Delegate { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.beginInstallWithManifest3", @@ -97,7 +97,7 @@ class WebstorePrivateBeginInstallWithManifest3Function }; class WebstorePrivateCompleteInstallFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public WebstoreInstaller::Delegate { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.completeInstall", @@ -126,8 +126,7 @@ class WebstorePrivateCompleteInstallFunction std::unique_ptr<ScopedActiveInstall> scoped_active_install_; }; -class WebstorePrivateEnableAppLauncherFunction - : public UIThreadExtensionFunction { +class WebstorePrivateEnableAppLauncherFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.enableAppLauncher", WEBSTOREPRIVATE_ENABLEAPPLAUNCHER) @@ -143,8 +142,7 @@ class WebstorePrivateEnableAppLauncherFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetBrowserLoginFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetBrowserLoginFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getBrowserLogin", WEBSTOREPRIVATE_GETBROWSERLOGIN) @@ -160,8 +158,7 @@ class WebstorePrivateGetBrowserLoginFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetStoreLoginFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetStoreLoginFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getStoreLogin", WEBSTOREPRIVATE_GETSTORELOGIN) @@ -177,8 +174,7 @@ class WebstorePrivateGetStoreLoginFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateSetStoreLoginFunction - : public UIThreadExtensionFunction { +class WebstorePrivateSetStoreLoginFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.setStoreLogin", WEBSTOREPRIVATE_SETSTORELOGIN) @@ -194,8 +190,7 @@ class WebstorePrivateSetStoreLoginFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetWebGLStatusFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetWebGLStatusFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getWebGLStatus", WEBSTOREPRIVATE_GETWEBGLSTATUS) @@ -213,8 +208,7 @@ class WebstorePrivateGetWebGLStatusFunction scoped_refptr<content::GpuFeatureChecker> feature_checker_; }; -class WebstorePrivateGetIsLauncherEnabledFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetIsLauncherEnabledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getIsLauncherEnabled", WEBSTOREPRIVATE_GETISLAUNCHERENABLED) @@ -230,8 +224,7 @@ class WebstorePrivateGetIsLauncherEnabledFunction void OnIsLauncherCheckCompleted(bool is_enabled); }; -class WebstorePrivateIsInIncognitoModeFunction - : public UIThreadExtensionFunction { +class WebstorePrivateIsInIncognitoModeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.isInIncognitoMode", WEBSTOREPRIVATE_ISININCOGNITOMODEFUNCTION) @@ -247,8 +240,7 @@ class WebstorePrivateIsInIncognitoModeFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateLaunchEphemeralAppFunction - : public UIThreadExtensionFunction { +class WebstorePrivateLaunchEphemeralAppFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.launchEphemeralApp", WEBSTOREPRIVATE_LAUNCHEPHEMERALAPP) @@ -272,7 +264,7 @@ class WebstorePrivateLaunchEphemeralAppFunction }; class WebstorePrivateGetEphemeralAppsEnabledFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getEphemeralAppsEnabled", WEBSTOREPRIVATE_GETEPHEMERALAPPSENABLED) @@ -287,7 +279,7 @@ class WebstorePrivateGetEphemeralAppsEnabledFunction }; class WebstorePrivateIsPendingCustodianApprovalFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.isPendingCustodianApproval", WEBSTOREPRIVATE_ISPENDINGCUSTODIANAPPROVAL) @@ -305,8 +297,7 @@ class WebstorePrivateIsPendingCustodianApprovalFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetReferrerChainFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetReferrerChainFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getReferrerChain", WEBSTOREPRIVATE_GETREFERRERCHAIN) 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 b544f0de6ee..e88e6e1865d 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 @@ -42,6 +42,7 @@ #include "ui/gl/gl_switches.h" #if BUILDFLAG(ENABLE_SUPERVISED_USERS) +#include "chrome/browser/supervised_user/logged_in_user_mixin.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" #if defined(OS_CHROMEOS) @@ -375,23 +376,89 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, EmptyCrx) { class ExtensionWebstorePrivateApiTestChild : public ExtensionWebstorePrivateApiTest { public: + ExtensionWebstorePrivateApiTestChild() + : embedded_test_server_(std::make_unique<net::EmbeddedTestServer>()), + logged_in_user_mixin_(&mixin_host_, + chromeos::LoggedInUserMixin::LogInType::kChild, + embedded_test_server_.get()) { + // Suppress regular user login to enable child user login. + set_chromeos_user_ = false; + } + + void SetUp() override { + mixin_host_.SetUp(); + ExtensionWebstorePrivateApiTest::SetUp(); + } + void SetUpCommandLine(base::CommandLine* command_line) override { + mixin_host_.SetUpCommandLine(command_line); ExtensionWebstorePrivateApiTest::SetUpCommandLine(command_line); - command_line->AppendSwitchASCII(switches::kSupervisedUserId, - supervised_users::kChildAccountSUID); -#if defined(OS_CHROMEOS) - command_line->AppendSwitchASCII( - chromeos::switches::kLoginUser, - "supervised_user@locally-managed.localhost"); - command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "hash"); -#endif + // Shortens the merge session timeout from 20 to 1 seconds to speed up the + // test by about 19 seconds. + // TODO (crbug.com/995575): figure out why this switch speeds up the test, + // and fix the test setup so this is not required. + command_line->AppendSwitch(switches::kShortMergeSessionTimeoutForTest); + } + + void SetUpDefaultCommandLine(base::CommandLine* command_line) override { + mixin_host_.SetUpDefaultCommandLine(command_line); + ExtensionWebstorePrivateApiTest::SetUpDefaultCommandLine(command_line); + } + + bool SetUpUserDataDirectory() override { + return mixin_host_.SetUpUserDataDirectory() && + ExtensionWebstorePrivateApiTest::SetUpUserDataDirectory(); + } + + void SetUpInProcessBrowserTestFixture() override { + mixin_host_.SetUpInProcessBrowserTestFixture(); + ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture(); + } + + void CreatedBrowserMainParts( + content::BrowserMainParts* browser_main_parts) override { + mixin_host_.CreatedBrowserMainParts(browser_main_parts); + ExtensionWebstorePrivateApiTest::CreatedBrowserMainParts( + browser_main_parts); + } + + void SetUpOnMainThread() override { + mixin_host_.SetUpOnMainThread(); + ExtensionWebstorePrivateApiTest::SetUpOnMainThread(); + logged_in_user_mixin_.SetUpOnMainThreadHelper( + host_resolver(), this, true /* issue_any_scope_token */); + } + + void TearDownOnMainThread() override { + mixin_host_.TearDownOnMainThread(); + ExtensionWebstorePrivateApiTest::TearDownOnMainThread(); } + + void TearDownInProcessBrowserTestFixture() override { + mixin_host_.TearDownInProcessBrowserTestFixture(); + ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture(); + } + + void TearDown() override { + mixin_host_.TearDown(); + ExtensionWebstorePrivateApiTest::TearDown(); + } + + private: + // Replicate what MixinBasedInProcessBrowserTest does since inheriting from + // that class is inconvenient here. + InProcessBrowserTestMixinHost mixin_host_; + // Create another embedded test server to avoid starting the same one twice. + std::unique_ptr<net::EmbeddedTestServer> embedded_test_server_; + + chromeos::LoggedInUserMixin logged_in_user_mixin_; }; // Tests that extension installation is blocked for child accounts, and // attempting to do so produces a special error code. // Note: This will have to be updated when we enable child-initiated installs. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTestChild, InstallBlocked) { + ASSERT_TRUE(browser()); ASSERT_TRUE(RunInstallTest("begin_install_fail_child.html", "extension.crx")); } diff --git a/chromium/chrome/browser/flag-metadata.json b/chromium/chrome/browser/flag-metadata.json index 3c264eb1246..ec2a104c72d 100644 --- a/chromium/chrome/browser/flag-metadata.json +++ b/chromium/chrome/browser/flag-metadata.json @@ -29,34 +29,24 @@ [ { - "name": "BundledConnectionHelp", - "owners": [ "carlosil" ], - "expiry_milestone": 76 - }, - { - "name": "PasswordImport", - "owners": [ "vasilii" ], - "expiry_milestone": 76 - }, - { - "name": "SupervisedUserCommittedInterstitials", - "owners": [ "carlosil" ], - "expiry_milestone": 77 - }, - { "name": "account-consistency", "owners": [ "droger", "msarda" ], "expiry_milestone": 80 }, { - "name": "show-sync-paused-reason-cookies-cleared-on-exit", - "owners": [ "msalama" ], - "expiry_milestone": 85 + "name": "aggregated-ml-app-ranking", + "owners": [ "pdyson", "jiameng" ], + "expiry_milestone": 81 + }, + { + "name": "allow-disable-mouse-acceleration", + "owners": [ "zentaro" ], + "expiry_milestone": 82 }, { "name": "allow-insecure-localhost", "owners": [ "security-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "allow-popups-during-page-unload", @@ -76,11 +66,6 @@ "expiry_milestone": 74 }, { - "name": "allow-starting-service-manager-only", - "owners": [ "hanxi", "hnakashima" ], - "expiry_milestone": 76 - }, - { "name": "allow-sxg-certs-without-extension", "owners": [ "//content/browser/web_package/OWNERS" ], // Used by developers for testing signed exchange loading using normal @@ -88,6 +73,11 @@ "expiry_milestone": 83 }, { + "name": "allow-sync-xhr-in-page-dismissal", + "owners": [ "kdillon@chromium.org" ], + "expiry_milestone": 82 + }, + { "name": "android-files-in-files-app", "owners": [ "fukino" ], "expiry_milestone": 76 @@ -98,6 +88,11 @@ "expiry_milestone": 78 }, { + "name": "android-setup-search-engine", + "owners": [ "pavely", "wylieb" ], + "expiry_milestone": 83 + }, + { "name": "android-site-settings-ui-refresh", "owners": [ "hkamila" ], "expiry_milestone": 76 @@ -110,12 +105,17 @@ { "name": "app-management", "owners": [ "//chrome/browser/resources/app_management/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 79 }, { "name": "app-service-ash", "owners": [ "//chrome/services/app_service/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 79 + }, + { + "name": "app-service-shelf", + "owners": [ "//chrome/services/app_service/OWNERS" ], + "expiry_milestone": 79 }, { "name": "arc-available-for-child", @@ -124,7 +124,7 @@ }, { "name": "arc-boot-completed-broadcast", - "owners": [ "//components/arc/common/ARC_SECURITY_OWNERS" ], + "owners": [ "//components/arc/mojom/ARC_SECURITY_OWNERS" ], "expiry_milestone": 76 }, { @@ -148,9 +148,11 @@ "expiry_milestone": 76 }, { - "name": "arc-native-bridge-experiment", + "name": "arc-native-bridge-toggle", "owners": [ "levarum@google.com" ], - "expiry_milestone": 76 + // Used on ChromeOS to compare and debug different ARC native-bridge + // implementations which are normally used on different platforms. + "expiry_milestone": -1 }, { "name": "arc-print-spooler-experiment", @@ -197,11 +199,6 @@ "expiry_milestone": -1 }, { - "name": "ash-notification-stacking-bar-redesign", - "owners": [ "tengs" ], - "expiry_milestone": 75 - }, - { "name": "ash-swap-side-volume-buttons-for-orientation", "owners": [ "minch" ], "expiry_milestone": 78 @@ -242,11 +239,6 @@ "expiry_milestone": 72 }, { - "name": "autofill-dynamic-forms", - "owners": [ "sebsg" ], - "expiry_milestone": 72 - }, - { "name": "autofill-enable-company-name", "owners": [ "sebsg" ], "expiry_milestone": 73 @@ -254,12 +246,12 @@ { "name": "autofill-enable-local-card-migration-for-non-sync-user", "owners": [ "siyua" ], - "expiry_milestone": 76 + "expiry_milestone": 83 }, { "name": "autofill-enable-toolbar-status-chip", "owners": [ "siyua" ], - "expiry_milestone": 77 + "expiry_milestone": 83 }, { "name": "autofill-enforce-min-required-fields-for-heuristics", @@ -278,26 +270,24 @@ }, { "name": "autofill-keyboard-accessory-view", - "owners": [ "ftirelo" ], - "expiry_milestone": 74 - }, - { - "name": "autofill-prune-suggestions", - "owners": ["ftirelo", "tmartino"], - "expiry_milestone": 78 + "owners": [ "fhorschig@chromium.org" ], + "expiry_milestone": 79 }, { "name": "autofill-no-local-save-on-unmask-success", "owners": [ "jsaul@google.com" ], - // Currently unclear if this is launching independently with M75 or - // alongside the Autofill Auth Project, which could be as late as ~Q3. - "expiry_milestone": 79 + // Must wait for the Autofill Auth Project to be launched. + "expiry_milestone": 84 }, { "name": "autofill-no-local-save-on-upload-success", "owners": [ "jsaul@google.com", "annelim@google.com" ], - // Currently unclear if this is launching independently with M75 or - // alongside the Autofill Auth Project, which could be as late as ~Q3. + // Must wait for the Autofill Auth Project to be launched. + "expiry_milestone": 84 + }, + { + "name": "autofill-off-no-server-data", + "owners": [ "seblalancette" ], "expiry_milestone": 79 }, { @@ -311,6 +301,11 @@ "expiry_milestone": 77 }, { + "name": "autofill-prune-suggestions", + "owners": ["ftirelo", "tmartino"], + "expiry_milestone": 78 + }, + { "name": "autofill-reject-company-birthyear", "owners": [ "parastoog" ], "expiry_milestone": 79 @@ -326,16 +321,6 @@ "expiry_milestone": 76 }, { - "name": "omnibox-local-entity-suggestions", - "owners": [ "manukh", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 - }, - { - "name": "autofill-settings-split-by-card-type", - "owners": [ "sebsg" ], - "expiry_milestone": 75 - }, - { "name": "autofill-use-improved-label-disambiguation", "owners": [ "ftirelo", "tmartino" ], "expiry_milestone": 77 @@ -346,26 +331,6 @@ "expiry_milestone": 79 }, { - "name": "enable-ambient-authentication-in-incognito", - "owners": ["rhalavati", "chrome-privacy-core@google.com"], - "expiry_milestone": 87 - }, - { - "name": "enable-ambient-authentication-in-guest-session", - "owners": ["rhalavati", "chrome-privacy-core@google.com"], - "expiry_milestone": 87 - }, - { - "name": "enable-autofill-save-card-show-no-thanks", - "owners": ["siashah", "jsaul@google.com"], - "expiry_milestone": 82 - }, - { - "name": "automatic-password-generation", - "owners": [ "ioanap", "fhorschig" ], - "expiry_milestone": 76 - }, - { "name": "background-task-component-update", "owners": [ "sorin", "waffles", "tiborg" ], "expiry_milestone": 76 @@ -376,6 +341,16 @@ "expiry_milestone": 80 }, { + "name": "bundled-exchanges", + "owners": [ "toyoshim", "ksakamoto", "horo", "kinuko" ], + "expiry_milestone": 83 + }, + { + "name": "BundledConnectionHelp", + "owners": [ "carlosil" ], + "expiry_milestone": 76 + }, + { "name": "bypass-app-banner-engagement-checks", "owners": [ "dominickn" ], "expiry_milestone": 78 @@ -383,7 +358,7 @@ { "name": "calculate-native-win-occlusion", "owners": [ "davidbienvenu", "fdoray" ], - "expiry_milestone": 76 + "expiry_milestone": 81 }, { "name": "camera-system-web-app", @@ -438,7 +413,7 @@ { "name": "chrome-colors", "owners": ["gayane"], - "expiry_milestone": 78 + "expiry_milestone": 79 }, { "name": "chrome-colors-custom-color-picker", @@ -450,6 +425,16 @@ "owners": [ "dullweber" ], "expiry_milestone": 78 }, + { + "name": "click-to-call-context-menu-selected-text", + "owners": [ "//chrome/browser/sharing/OWNERS" ], + "expiry_milestone": 80 + }, + { + "name": "click-to-call-open-dialer-directly", + "owners": [ "//chrome/browser/sharing/OWNERS" ], + "expiry_milestone": 81 + }, { "name": "click-to-call-receiver", "owners": [ "//chrome/browser/sharing/OWNERS" ], @@ -476,44 +461,44 @@ "expiry_milestone": 80 }, { - "name": "contextual-search", - "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 74 + "name": "context-menu-search-with-google-lens", + "owners": [ "benwgold", "lens-chrome" ], + "expiry_milestone": 88 }, { - "name": "contextual-search-longpress-resolve", + "name": "contextual-search-definitions", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 78 + "expiry_milestone": 80 }, { - "name": "contextual-search-ml-tap-suppression", + "name": "contextual-search-longpress-resolve", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { - "name": "contextual-search-definitions", + "name": "contextual-search-ml-tap-suppression", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 77 + "expiry_milestone": 82 }, { "name": "contextual-search-ranker-query", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "contextual-search-second-tap", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "contextual-search-simplified-server", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 78 + "expiry_milestone": 81 }, { "name": "contextual-search-translation-model", "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/OWNERS" ], - "expiry_milestone": 77 + "expiry_milestone": 79 }, { "name": "contextual-search-unity-integration", @@ -546,11 +531,6 @@ "expiry_milestone": 77 }, { - "name": "crostini-webui-installer", - "owners": [ "lxj", "timloh", "benwells" ], - "expiry_milestone": 82 - }, - { "name": "crostini-gpu-support", "owners": [ "nverne", "benwells" ], "expiry_milestone": 78 @@ -566,9 +546,14 @@ "expiry_milestone": 76 }, { + "name": "crostini-webui-installer", + "owners": [ "lxj", "timloh", "benwells" ], + "expiry_milestone": 82 + }, + { "name": "cryptauth-v2-enrollment", - "owners": [ "jlklein", "khorimoto", "nohle" ], - "expiry_milestone": 76 + "owners": [ "khorimoto", "nohle" ], + "expiry_milestone": 82 }, { "name": "d3d11-video-decoder", @@ -594,6 +579,16 @@ "expiry_milestone": 88 }, { + "name": "decode-jpeg-images-to-yuv", + "owners": [ "sashamcintosh", "chromeos-gfx@google.com" ], + "expiry_milestone": 88 + }, + { + "name": "decode-webp-images-to-yuv", + "owners": [ "andrescj", "chromeos-gfx@google.com" ], + "expiry_milestone": 80 + }, + { "name": "delegate-overscroll-swipes", "owners": [ "chrome-android-app@chromium.org" ], "expiry_milestone": 88 @@ -681,6 +676,11 @@ "expiry_milestone": -1 }, { + "name": "disable-keepalive-fetch", + "owners": [ "yhirano" ], + "expiry_milestone": 83 + }, + { // See https://crbug.com/882238. "name": "disable-pushstate-throttle", "owners": [ "arthursonzogni@chromium.org", "palmer@chromium.org" ], @@ -731,6 +731,11 @@ "expiry_milestone": 80 }, { + "name": "dns-over-https", + "owners": [ "dalyk", "doh-core@google.com" ], + "expiry_milestone": 81 + }, + { "name": "document-passive-event-listeners", "owners": [ "nzolghadr, input-dev" ], "expiry_milestone": 76 @@ -746,16 +751,16 @@ "expiry_milestone": 80 }, { + "name": "download-auto-resumption-native", + "owners": [ "shaktisahu", "qinmin" ], + "expiry_milestone": 80 + }, + { "name": "download-home-v2", "owners": [ "shaktisahu", "xingliu", "dtrainor" ], "expiry_milestone": 76 }, { - "name": "download-progress-infobar", - "owners": [ "shaktisahu", "dtrainor" ], - "expiry_milestone": 75 - }, - { "name": "download-rename", "owners": [ "hesen", "dtrainor" ], "expiry_milestone": 76 @@ -766,11 +771,22 @@ "expiry_milestone": 80 }, { + "name": "drag-to-pin-tabs", + "owners": ["chrome-desktop-ui-seattle@google.com", "cyan", "tbergquist"], + "expiry_milestone": 82 + }, + { "name": "draw-vertically-edge-to-edge", "owners": [ "chrome-android-app@chromium.org" ], "expiry_milestone": 88 }, { + // See: https://crbug.com/993569. + "name": "dynamic-tcmalloc-tuning", + "owners": [ "bgeffon", "sonnyrao" ], + "expiry_milestone": 89 + }, + { "name": "enable-accessibility-image-descriptions", "owners": [ "//ui/accessibility/OWNERS" ], "expiry_milestone": 77 @@ -786,14 +802,24 @@ "expiry_milestone": 80 }, { + "name": "enable-ambient-authentication-in-guest-session", + "owners": ["rhalavati", "chrome-privacy-core@google.com"], + "expiry_milestone": 87 + }, + { + "name": "enable-ambient-authentication-in-incognito", + "owners": ["rhalavati", "chrome-privacy-core@google.com"], + "expiry_milestone": 87 + }, + { "name": "enable-android-autofill-accessibility", "owners": [ "ftirelo" ], "expiry_milestone": 73 }, { "name": "enable-android-night-mode", - "owners": [ "huayinz", "twellington", "tedchoc" ], - "expiry_milestone": 76 + "owners": [ "twellington", "tedchoc" ], + "expiry_milestone": 80 }, { "name": "enable-android-spellchecker", @@ -802,8 +828,8 @@ }, { "name": "enable-android-web-contents-dark-mode", - "owners": [ "huayinz", "tedchoc" ], - "expiry_milestone": 76 + "owners": [ "tedchoc" ], + "expiry_milestone": 80 }, { "name": "enable-app-data-search", @@ -816,11 +842,6 @@ "expiry_milestone": 78 }, { - "name": "enable-search-box-selection", - "owners": [ "ginko", "newcomer" ], - "expiry_milestone": 78 - }, - { "name": "enable-app-list-search-autocomplete", "owners": [ "newcomer" ], "expiry_milestone": 75 @@ -831,11 +852,6 @@ "expiry_milestone": 74 }, { - "name": "enable-appcontainer", - "owners": [ "forshaw", "wfh" ], - "expiry_milestone": 76 - }, - { "name": "enable-arc-cups-api", "owners": [ "luum", "skau" ], "expiry_milestone": 76 @@ -846,39 +862,39 @@ "expiry_milestone": 76 }, { - "name": "enable-assistant-launcher-integration", + "name": "enable-assistant-app-support", "owners": [ "croissant-eng" ], "expiry_milestone": 78 }, { - "name": "enable-assistant-media-session-integration", + "name": "enable-assistant-dsp", "owners": [ "croissant-eng" ], - "expiry_milestone": 78 + "expiry_milestone": 80 }, { - "name": "enable-assistant-app-support", + "name": "enable-assistant-key-remapping", "owners": [ "croissant-eng" ], "expiry_milestone": 78 }, { - "name": "enable-assistant-dsp", + "name": "enable-assistant-launcher-integration", "owners": [ "croissant-eng" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { - "name": "enable-assistant-key-remapping", + "name": "enable-assistant-media-session-integration", "owners": [ "croissant-eng" ], "expiry_milestone": 78 }, { - "name": "enable-assistant-stereo-input", + "name": "enable-assistant-routines", "owners": [ "croissant-eng" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { - "name": "enable-assistant-routines", + "name": "enable-assistant-stereo-input", "owners": [ "croissant-eng" ], - "expiry_milestone": 82 + "expiry_milestone": 80 }, { "name": "enable-async-dns", @@ -897,18 +913,18 @@ }, { "name": "enable-autofill-account-wallet-storage", - "owners": [ "feuunk", "butter-team@google.com" ], - "expiry_milestone": 76 + "owners": [ "treib", "jsaul@google.com", "butter-team@google.com" ], + "expiry_milestone": 81 }, { "name": "enable-autofill-credit-card-ablation-experiment", "owners": [ "dlkumar@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 88 }, { "name": "enable-autofill-credit-card-authentication", "owners": [ "jsaul@google.com", "manasverma@google.com" ], - "expiry_milestone": 79 + "expiry_milestone": 84 }, { "name": "enable-autofill-credit-card-upload", @@ -921,17 +937,17 @@ { "name": "enable-autofill-credit-card-upload-editable-cardholder-name", "owners": [ "jsaul@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 83 }, { "name": "enable-autofill-credit-card-upload-editable-expiration-date", "owners": [ "hozhng@google.com", "jsaul@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 83 }, { "name": "enable-autofill-credit-card-upload-feedback", "owners": [ "siyua@chromium.org, payments-autofill-team@google.com" ], - "expiry_milestone": 79 + "expiry_milestone": 84 }, { "name": "enable-autofill-do-not-migrate-unsupported-local-cards", @@ -939,29 +955,19 @@ "expiry_milestone": 80 }, { - "name": "enable-autofill-do-not-upload-save-unsupported-cards", - "owners": [ "annelim@google.com", "jsaul@google.com" ], - "expiry_milestone": 76 - }, - { "name": "enable-autofill-import-dynamic-forms", "owners": [ "hozhng@google.com", "jiahuiguo@google.com" ], - "expiry_milestone": 76 - }, - { - "name": "enable-autofill-import-non-focusable-credit-card-forms", - "owners": [ "hozhng@google.com", "jiahuiguo@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 79 }, { "name": "enable-autofill-local-card-migration-uses-strike-system-v2", "owners": [ "annelim@google.com", "jsaul@google.com" , "jiahuiguo@google.com"], - "expiry_milestone": 76 + "expiry_milestone": 84 }, { "name": "enable-autofill-manual-fallback", - "owners": [ "tmartino@chromium.org" ], - "expiry_milestone": 78 + "owners": [ "fhorschig@chromium.org" ], + "expiry_milestone": 79 }, { "name": "enable-autofill-refresh-style", @@ -969,24 +975,29 @@ "expiry_milestone": 78 }, { - "name": "enable-autofill-save-credit-card-uses-improved-messaging", - "owners": [ "siyua@chromium.org", "payments-autofill-team@google.com" ], - "expiry_milestone": 78 + "name": "enable-autofill-save-card-show-no-thanks", + "owners": ["siashah", "jsaul@google.com"], + "expiry_milestone": 82 }, { - "name": "enable-autofill-send-experiment-ids-in-payments-rpcs", - "owners": [ "dlkumar@google.com" ], - "expiry_milestone": 76 + "name": "enable-autofill-save-credit-card-uses-improved-messaging", + "owners": [ "siyua@chromium.org", "payments-autofill-team@google.com" ], + "expiry_milestone": 80 }, { - "name": "autofill-off-no-server-data", - "owners": [ "seblalancette" ], - "expiry_milestone": 79 + "name": "enable-autofill-updated-card-unmask-prompt-ui", + "owners": ["siyua", "payments-autofill-team@google.com"], + "expiry_milestone": 87 }, { "name": "enable-avoid-flash-between-navigation", "owners": [ "schenney", "paint-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 80 + }, + { + "name": "enable-backdrop-filter", + "owners": [ "masonfreed", "paint-dev@chromium.org" ], + "expiry_milestone": 78 }, { "name": "enable-background-blur", @@ -994,9 +1005,24 @@ "expiry_milestone": 86 }, { - "name": "enable-bloated-renderer-detection", - "owners": [ "ulan" ], - "expiry_milestone": 75 + "name": "enable-bookmark-reorder", + "owners": ["jhimawan@google.com", "twellington" ], + "expiry_milestone": 80 + }, + { + "name": "enable-built-in-module-all", + "owners": [ "hiroshige", "domenic" ], + "expiry_milestone": 80 + }, + { + "name": "enable-built-in-module-infra", + "owners": [ "hiroshige", "domenic" ], + "expiry_milestone": 80 + }, + { + "name": "enable-built-in-module-kv-storage", + "owners": [ "hiroshige", "domenic" ], + "expiry_milestone": 80 }, { "name": "enable-bulk-printers", @@ -1024,14 +1050,24 @@ "expiry_milestone": 79 }, { + "name": "enable-clipboard-provider-text-suggestions", + "owners": [ "gangwu", "chromium-omnibox-team"], + "expiry_milestone": 84 + }, + { + "name": "enable-close-tab-suggestions-stale", + "owners": [ "memex-team@google.com" ], + "expiry_milestone": 82 + }, + { "name": "enable-cloud-print-xps", "owners": [ "//printing/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 79 }, { "name": "enable-cloud-printer-handler", "owners": [ "//printing/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "enable-command-line-on-non-rooted-devices", @@ -1041,9 +1077,9 @@ "expiry_milestone": -1 }, { - "name": "enable-immersive-fullscreen-toolbar", - "owners": [ "sdy", "chrome/browser/ui/cocoa/OWNERS" ], - "expiry_milestone": 76 + "name": "enable-cooperative-scheduling", + "owners": [ "keishi" ], + "expiry_milestone": 85 }, { "name": "enable-credit-card-assist", @@ -1067,8 +1103,8 @@ }, { "name": "enable-custom-mac-paper-sizes", - "owners": [ "//printing/OWNERS" ], - "expiry_milestone": 76 + "owners": [ "thestig" ], + "expiry_milestone": 82 }, { "name": "enable-data-reduction-proxy-server-experiment", @@ -1082,6 +1118,26 @@ "expiry_milestone": 79 }, { + "name": "enable-dbus-and-x11-status-icons", + "owners": [ "thestig", "thomasanderson" ], + "expiry_milestone": 80 + }, + { + "name": "enable-de-jelly", + "owners": [ "ericrk", "//components/viz/OWNERS" ], + "expiry_milestone": 94 + }, + { + "name": "enable-defer-all-script", + "owners": [ "//components/data_reduction_proxy/OWNERS" ], + "expiry_milestone": 82 + }, + { + "name": "enable-defer-all-script-without-optimization-hints", + "owners": [ "//components/data_reduction_proxy/OWNERS" ], + "expiry_milestone": 82 + }, + { "name": "enable-desktop-pwas-local-updating", "owners": [ "desktop-pwas-team@google.com" ], "expiry_milestone": 80 @@ -1092,11 +1148,6 @@ "expiry_milestone": 79 }, { - "name": "enable-desktop-pwas-unified-install", - "owners": [ "desktop-pwas-team@google.com" ], - "expiry_milestone": 78 - }, - { "name": "enable-devtools-experiments", "owners": [ "//third_party/blink/renderer/devtools/OWNERS" ], // This is a catch-all for ongoing devtools experiments. @@ -1118,6 +1169,21 @@ "expiry_milestone": 80 }, { + "name": "enable-experimental-accessibility-autoclick", + "owners": [ "katie", "dmazzoni", "dtseng" ], + "expiry_milestone": 78 + }, + { + "name": "enable-experimental-accessibility-chromevox-language-switching", + "owners": [ "akihiroota", "dmazzoni", "dtseng" ], + "expiry_milestone": 78 + }, + { + "name": "enable-experimental-accessibility-chromevox-sub-node-language-switching", + "owners": [ "akihiroota", "dmazzoni", "dtseng", "//ui/accessibility/OWNERS"], + "expiry_milestone": 82 + }, + { "name": "enable-experimental-accessibility-features", "owners": [ "//ui/accessibility/OWNERS" ], "expiry_milestone": 76 @@ -1138,21 +1204,6 @@ "expiry_milestone": 80 }, { - "name": "enable-experimental-accessibility-autoclick", - "owners": [ "katie", "dmazzoni", "dtseng" ], - "expiry_milestone": 78 - }, - { - "name": "enable-experimental-accessibility-chromevox-language-switching", - "owners": [ "akihiroota", "dmazzoni", "dtseng" ], - "expiry_milestone": 78 - }, - { - "name": "enable-experimental-accessibility-chromevox-rich-text-indication", - "owners": [ "akihiroota", "dtseng" ], - "expiry_milestone": 78 - }, - { "name": "enable-experimental-kernel-vm-support", "owners": [ "jflat", "zwisler" ], "expiry_milestone": 78 @@ -1160,7 +1211,7 @@ { "name": "enable-experimental-productivity-features", "owners": [ "feature-control@chromium.org" ], - "expiry_milestone": 76 + "expiry_milestone": 81 }, { "name": "enable-experimental-web-platform-features", @@ -1170,14 +1221,26 @@ "expiry_milestone": -1 }, { + "name": "enable-experimental-webassembly-features", + "owners": [ "adamk", "hablich" ], + // This flag is used by web developers to test upcoming WebAssembly + // features. + "expiry_milestone": -1 + }, + { "name": "enable-filesystem-in-incognito", "owners": [ "rhalavati" ], "expiry_milestone": 78 }, { - "name": "enable-forbid-sync-xhr-in-page-dismissal", - "owners": [ "kdillon@chromium.org" ], - "expiry_milestone": 82 + "name": "enable-filtering-scroll-events", + "owners": [ "axantoine", "eirage", "nzolghadr", "input-dev" ], + "expiry_milestone": 80 + }, + { + "name": "enable-force-dark", + "owners": [ "gilmanmh@google.com" ], + "expiry_milestone": 80 }, { "name": "enable-fs-nosymfollow", @@ -1192,19 +1255,9 @@ "expiry_milestone": -1 }, { - "name": "enable-winrt-sensor-implementation", - "owners": [ "wensh@microsoft.com" ], - "expiry_milestone": 80 - }, - { - "name": "enable-generic-sensor", - "owners": [ "reillyg@chromium.org", "raphael.kubo.da.costa@intel.com" ], - "expiry_milestone": 72 - }, - { "name": "enable-generic-sensor-extra-classes", "owners": [ "reillyg@chromium.org", "raphael.kubo.da.costa@intel.com" ], - "expiry_milestone": 76 + "expiry_milestone": 83 }, { "name": "enable-google-branded-context-menu", @@ -1214,7 +1267,7 @@ { "name": "enable-gpu-appcontainer", "owners": [ "forshaw", "wfh" ], - "expiry_milestone": 78 + "expiry_milestone": 82 }, { "name": "enable-gpu-rasterization", @@ -1231,16 +1284,23 @@ "expiry_milestone": -1 }, { - "name": "enable-history-favicons-google-server-query", - "owners": ["victorvianna", "jkrcal"], - "expiry_milestone": 78 - }, + "name": "enable-heuristic-stylus-palm-rejection", + "owners": ["robsc", "napper"], + // We add a heuristic that changes the way fingers are handled. We should + // always let users switch it off if needed. However, for now, during + // experiments, we set milestone deep into future. + "expiry_milestone": 90}, { "name": "enable-hide-arc-media-notifications", "owners": [ "beccahughes", "media-dev" ], "expiry_milestone": 80 }, { + "name": "enable-history-favicons-google-server-query", + "owners": ["victorvianna", "jkrcal"], + "expiry_milestone": 78 + }, + { "name": "enable-history-manipulation-intervention", "owners": [ "shivanisha" ], "expiry_milestone": 76 @@ -1261,24 +1321,14 @@ "expiry_milestone": 77 }, { - "name": "identity-disc", - "owners": ["//chrome/android/java/src/org/chromium/chrome/browser/toolbar/OWNERS"], - "expiry_milestone": 78 - }, - { - "name": "enable-dbus-and-x11-status-icons", - "owners": [ "thestig", "thomasanderson" ], + "name": "enable-immersive-fullscreen-toolbar", + "owners": [ "sdy" ], "expiry_milestone": 80 }, { "name": "enable-implicit-root-scroller", "owners": [ "bokan", "input-dev" ], - "expiry_milestone": 75 - }, - { - "name": "enable-improved-geolanguage-data", - "owners": [ "frechette", "chrome-language@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-incognito-window-counter", @@ -1288,7 +1338,7 @@ { "name": "enable-inline-update-flow", "owners": [ "nyquist", "dtrainor" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-intent-picker", @@ -1302,41 +1352,6 @@ "expiry_milestone": -1 }, { - "name": "enable-built-in-module-all", - "owners": [ "hiroshige", "domenic" ], - "expiry_milestone": 80 - }, - { - "name": "enable-built-in-module-infra", - "owners": [ "hiroshige", "domenic" ], - "expiry_milestone": 80 - }, - { - "name": "enable-built-in-module-kv-storage", - "owners": [ "hiroshige", "domenic" ], - "expiry_milestone": 80 - }, - { - "name": "enable-blink-gen-property-trees", - "owners": [ "paint-dev@chromium.org" ], - "expiry_milestone": 74 - }, - { - "name": "enable-backdrop-filter", - "owners": [ "masonfreed", "paint-dev@chromium.org" ], - "expiry_milestone": 78 - }, - { - "name": "enable-defer-all-script", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 82 - }, - { - "name": "enable-defer-all-script-without-optimization-hints", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 82 - }, - { "name": "enable-layout-ng", "owners": [ "layout-dev@chromium.org" ], "expiry_milestone": 80 @@ -1358,11 +1373,6 @@ "expiry_milestone": -1 }, { - "name": "enable-url-loader-lite-page-server-previews", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 79 - }, - { "name": "enable-lock-screen-notification", "owners": [ "tengs" ], "expiry_milestone": 80 @@ -1401,14 +1411,14 @@ "expiry_milestone": 76 }, { - "name": "enable-myfiles-volume", - "owners": [ "lucmult", "noel" ], + "name": "enable_messages_web_push", + "owners": [ "azeemarshad", "jlklein", "khorimoto" ], "expiry_milestone": 76 }, { - "name": "enable-nacl", - "owners": [ "dschuff", "native-client-dev@googlegroups.com" ], - "expiry_milestone": 87 + "name": "enable-nacl", + "owners": [ "dschuff", "native-client-dev@googlegroups.com" ], + "expiry_milestone": 87 }, { "name": "enable-native-controls", @@ -1416,11 +1426,6 @@ "expiry_milestone": 75 }, { - "name": "enable-native-google-assistant", - "owners": [ "croissant-eng" ], - "expiry_milestone": 76 - }, - { "name": "enable-native-notifications", "owners": [ "peter", "finnur" ], "expiry_milestone": 76 @@ -1438,19 +1443,9 @@ "expiry_milestone": -1 }, { - "name": "download-auto-resumption-native", - "owners": [ "shaktisahu", "qinmin" ], - "expiry_milestone": 76 - }, - { - "name": "drag-to-pin-tabs", - "owners": ["chrome-desktop-ui-seattle@google.com", "cyan", "tbergquist"], - "expiry_milestone": 82 - }, - { "name": "enable-new-download-backend", "owners": [ "shaktisahu", "dtrainor" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-new-photo-picker", @@ -1481,12 +1476,12 @@ { "name": "enable-ntp-remote-suggestions", "owners": [ "fgorski" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-offer-store-unmasked-wallet-cards", "owners": [ "jsaul@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 86 }, { "name": "enable-offline-previews", @@ -1497,14 +1492,7 @@ { "name": "enable-oop-rasterization", "owners": [ "enne", "khushalsagar" ], - "expiry_milestone": 76 - }, - { - "name" : "enable-parental-controls-settings", - "owners" : [ "danan", "michaelpg" ], - // This flag is used to enable parental controls options in ChromeOS - // settings. - "expiry_milestone" : 79 + "expiry_milestone": 80 }, { "name": "enable-parallel-downloading", @@ -1514,6 +1502,13 @@ "expiry_milestone": -1 }, { + "name" : "enable-parental-controls-settings", + "owners" : [ "danan", "michaelpg" ], + // This flag is used to enable parental controls options in ChromeOS + // settings. + "expiry_milestone" : 79 + }, + { "name": "enable-pixel-canvas-recording", "owners": [ "malaykeshav", "oshima" ], "expiry_milestone": 77 @@ -1524,11 +1519,21 @@ "expiry_milestone": 78 }, { + "name" : "enable-pointer-lock-options", + "owners" : [ "eirage", "nzolghadr", "input-dev" ], + "expiry_milestone" : 85 + }, + { "name": "enable-portals", "owners": [ "adithyas", "jbroman", "lfg" ], "expiry_milestone": 80 }, { + "name": "enable-previews-coin-flip", + "owners": [ "//components/data_reduction_proxy/OWNERS" ], + "expiry_milestone": 90 + }, + { "name": "enable-process-sharing-with-default-site-instances", "owners": [ "acolwell" ], "expiry_milestone": 81 @@ -1541,7 +1546,7 @@ { "name": "enable-query-in-omnibox", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-quic", @@ -1559,6 +1564,11 @@ "expiry_milestone": 78 }, { + "name": "enable-removing-all-third-party-cookies", + "owners": [ "dullweber" ], + "expiry_milestone": 82 + }, + { "name": "enable-reopen-tab-in-product-help", "owners": [ "collinbaker" ], "expiry_milestone": 76 @@ -1579,11 +1589,6 @@ "expiry_milestone": 80 }, { - "name": "enable-filtering-scroll-events", - "owners": [ "axantoine", "eirage", "nzolghadr", "input-dev" ], - "expiry_milestone": 80 - }, - { "name": "enable-resource-load-scheduler", "owners": [ "toyoshim" ], "expiry_milestone": 78 @@ -1597,7 +1602,7 @@ { "name": "enable-revamped-context-menu", "owners": [ "twellington" ], - "expiry_milestone": 77 + "expiry_milestone": 80 }, { "name": "enable-safe-browsing-ap-download-verdicts", @@ -1616,9 +1621,9 @@ "expiry_milestone": 76 }, { - "name": "enable-search-ready-omnibox", - "owners": [ "mdjones" ], - "expiry_milestone": 75 + "name": "enable-search-box-selection", + "owners": [ "ginko", "newcomer" ], + "expiry_milestone": 78 }, { "name": "enable-send-tab-to-self", @@ -1641,11 +1646,6 @@ "expiry_milestone": 78 }, { - "name": "enable-sensor-content-setting", - "owners": [ "reillyg@chromium.org", "raphael.kubo.da.costa@intel.com" ], - "expiry_milestone": 76 - }, - { "name": "enable-service-worker-imported-script-update-check", "owners": [ "worker-dev@chromium.org" ], // It's still in development. Tentatively set to M76 as the expiry_milestone. @@ -1657,16 +1657,16 @@ "expiry_milestone": 77 }, { - "name": "enable-shill-sandboxing", - "owners": [ "mortonm" ], - "expiry_milestone": 77 - }, - { "name": "enable-sharing-device-registration", "owners": [ "//chrome/browser/sharing/OWNERS" ], "expiry_milestone": 79 }, { + "name": "enable-shill-sandboxing", + "owners": [ "mortonm" ], + "expiry_milestone": 77 + }, + { "name": "enable-show-autofill-signatures", "owners": [ "kolos" ], // Used for debugging and QA by the autofill team for the indefinite future. @@ -1675,7 +1675,9 @@ { "name": "enable-site-isolation-for-password-sites", "owners": [ "site-isolation-dev", "alexmos", "lukasza" ], - "expiry_milestone": 79 + // Note: consider keeping this flag even after password-triggered site + // isolation launches to allow users of low-memory devices to opt in. + "expiry_milestone": 80 }, { "name": "enable-site-per-process", @@ -1696,6 +1698,26 @@ "expiry_milestone": 78 }, { + "name": "enable-start-surface", + "owners": [ "gogerald"], + "expiry_milestone": 83 + }, + { + "name": "enable-storage-pressure-ui", + "owners": [ "jarrydg"], + "expiry_milestone": 82 + }, + { + "name": "enable-streamlined-usb-printer-setup", + "owners": [ "baileyberro" ], + "expiry_milestone": 77 + }, + { + "name" : "enable-subresource-redirect", + "owners" : [ "robertogden", "tbansal" ], + "expiry_milestone": 85 + }, + { "name": "enable-suggestions-with-substring-match", "owners": [ "tmartino" ], "expiry_milestone": 77 @@ -1703,7 +1725,7 @@ { "name": "enable-surfacecontrol", "owners": [ "khushalsagar" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-surfaces-for-videos", @@ -1711,19 +1733,19 @@ "expiry_milestone": 76 }, { - "name": "enable-sxg-subresource-prefetching", + "name": "enable-sxg-prefetch-cache-for-navigations", "owners": [ "horo", "//content/browser/web_package/OWNERS" ], "expiry_milestone": 80 }, { - "name": "enable-sxg-prefetch-cache-for-navigations", + "name": "enable-sxg-subresource-prefetching", "owners": [ "horo", "//content/browser/web_package/OWNERS" ], "expiry_milestone": 80 }, { "name": "enable-sync-uss-bookmarks", "owners": [ "mamir", "//components/sync/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-sync-uss-nigori", @@ -1741,39 +1763,39 @@ "expiry_milestone": 78 }, { + "name": "enable-tab-engagement-reporting", + "owners": [ "memex-team@google.com" ], + "expiry_milestone": 82 + }, + { "name": "enable-tab-grid-layout", "owners": [ "memex-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "enable-tab-groups", "owners": [ "memex-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 82 }, { "name": "enable-tab-groups-ui-improvements", "owners": [ "memex-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 82 }, { "name": "enable-tab-switcher-on-return", "owners": [ "memex-team@google.com" ], - "expiry_milestone": 76 - }, - { - "name": "enable-tab-engagement-reporting", - "owners": [ "memex-team@google.com" ], "expiry_milestone": 82 }, { "name": "enable-tab-to-gts-animation", "owners": [ "memex-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 82 }, { "name": "enable-text-fragment-anchor", "owners": [ "bokan", "input-dev" ], - "expiry_milestone": 77 + "expiry_milestone": 80 }, { "name": "enable-tls13-early-data", @@ -1793,9 +1815,11 @@ "expiry_milestone": -1 }, { - "name": "enable-two-panes-start-surface", - "owners": [ "gogerald"], - "expiry_milestone": 83 + "name": "enable-ui-devtools", + "owners": [ "//components/ui_devtools/OWNERS" ], + // Convenience debugging flag for non-stable ChromeOS Builds. + // Devtools spins up a server which is not appropriate in the default case. + "expiry_milestone": -1 }, { "name": "enable-unsafe-webgpu", @@ -1803,11 +1827,9 @@ "expiry_milestone": 82 }, { - "name": "enable-ui-devtools", - "owners": [ "//components/ui_devtools/OWNERS" ], - // Convenience debugging flag for non-stable ChromeOS Builds. - // Devtools spins up a server which is not appropriate in the default case. - "expiry_milestone": -1 + "name": "enable-url-loader-lite-page-server-previews", + "owners": [ "//components/data_reduction_proxy/OWNERS" ], + "expiry_milestone": 79 }, { "name": "enable-usbguard", @@ -1821,8 +1843,24 @@ }, { "name": "enable-vaapi-jpeg-image-decode-acceleration", - "owners": [ "chromeos-camera-eng@google.com" ], - "expiry_milestone": 76 + "owners": [ "chromeos-gfx@google.com" ], + "expiry_milestone": 79 + }, + { + "name": "enable-vaapi-webp-image-decode-acceleration", + "owners": [ "chromeos-gfx@google.com" ], + "expiry_milestone": 79 + }, + { + "name": "enable-virtual-desks", + "owners": [ "afakhry" ], + // This is a flag to enable or disable the Virtual Desks feature. + "expiry_milestone": 81 + }, + { + "name": "enable-virtual-desks-gestures", + "owners": [ "afakhry" ], + "expiry_milestone": 81 }, { "name": "enable-virtual-keyboard", @@ -1832,18 +1870,18 @@ }, { "name": "enable-viz-display-compositor", - "owners": [ "fsamuel", "kylechar" ], - "expiry_milestone": 76 + "owners": [ "kylechar", "rjkroege" ], + "expiry_milestone": 79 }, { "name": "enable-viz-hit-test-surface-layer", "owners": [ "yigu", "rjkroege", "kylechar" ], - "expiry_milestone": 78 + "expiry_milestone": 79 }, { "name": "enable-web-authentication-ble-support", "owners": [ "webauthn-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "enable-web-authentication-cable-support", @@ -1851,15 +1889,15 @@ "expiry_milestone": 80 }, { - "name": "enable-web-authentication-testing-api", + "name": "enable-web-authentication-pin-support", "owners": [ "webauthn-team@google.com" ], - // This is required for testing. - "expiry_milestone": -1 + "expiry_milestone": 77 }, { - "name": "enable-web-authentication-pin-support", + "name": "enable-web-authentication-testing-api", "owners": [ "webauthn-team@google.com" ], - "expiry_milestone": 77 + // This is required for testing. + "expiry_milestone": -1 }, { "name": "enable-web-payments-experimental-features", @@ -1869,11 +1907,6 @@ "expiry_milestone": -1 }, { - "name": "enable-webassembly", - "owners": [ "titzer", "wasm-team@google.com" ], - "expiry_milestone": 72 - }, - { "name": "enable-webassembly-baseline", "owners": [ "clemensh", "wasm-team@google.com" ], "expiry_milestone": 83 @@ -1899,11 +1932,6 @@ "expiry_milestone": 83 }, { - "name": "enable-webgl2-compute-context", - "owners": [ "webgl-team@google.com" ], - "expiry_milestone": 77 - }, - { "name": "enable-webgl-draft-extensions", "owners": [ "webgl-team@google.com" ], // This flag is the only way for end users to test upcoming WebGL @@ -1911,6 +1939,11 @@ "expiry_milestone": -1 }, { + "name": "enable-webgl2-compute-context", + "owners": [ "webgl-team@google.com" ], + "expiry_milestone": 77 + }, + { "name": "enable-webnfc", "owners": [ "rijubrata.bhaumik@intel.com","reillyg" ], "expiry_milestone": 79 @@ -1948,7 +1981,7 @@ { "name": "enable-webrtc-pipewire-capturer", "owners": [ "tomas.popela@gmail.com" ], - "expiry_milestone": 76 + "expiry_milestone": 79 }, { "name": "enable-webrtc-remote-event-log", @@ -1971,6 +2004,11 @@ "expiry_milestone": 79 }, { + "name": "enable-winrt-sensor-implementation", + "owners": [ "wensh@microsoft.com" ], + "expiry_milestone": 80 + }, + { "name": "enable-zero-copy", "owners": [ "ccameron", "chrome-gpu@google.com" ], // This flag is commonly used when asking users to help gather debug info. @@ -1987,29 +2025,9 @@ "expiry_milestone": 75 }, { - "name": "updated_cellular_activation_ui", - "owners": [ "azeemarshad", "khorimoto" ], - "expiry_milestone": 80 - }, - { - "name": "use_messages_google_com_domain", - "owners": [ "azeemarshad", "khorimoto" ], - "expiry_milestone": 76 - }, - { - "name": "use_messages_staging_url", - "owners": [ "azeemarshad", "khorimoto" ], - "expiry_milestone": 76 - }, - { - "name": "enable_messages_web_push", - "owners": [ "azeemarshad", "jlklein", "khorimoto" ], - "expiry_milestone": 76 - }, - { "name": "enforce-tls13-downgrade", "owners": [ "davidben", "svaldez" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "enterprise-reporting-in-browser", @@ -2039,12 +2057,7 @@ { "name": "extension-content-verification", "owners": [ "//extensions/OWNERS" ], - "expiry_milestone": 76 - }, - { - "name": "extensions-toolbar-menu", - "owners": [ "//extensions/OWNERS", "pbos" ], - "expiry_milestone": 80 + "expiry_milestone": 86 }, { "name": "extensions-on-chrome-urls", @@ -2054,16 +2067,11 @@ "expiry_milestone": -1 }, { - "name": "font-src-local-matching", - "owners": [ "drott", "layout-dev" ], + "name": "extensions-toolbar-menu", + "owners": [ "//extensions/OWNERS", "pbos" ], "expiry_milestone": 82 }, { - "name": "force-use-chrome-camera", - "owners": [ "shenghao", "chromeos-camera-app-eng@google.com" ], - "expiry_milestone": 76 - }, - { "name": "fcm-invalidations", "owners": [ "melandory", "chrome-sync-dev@google.com" ], "expiry_milestone": 76 @@ -2090,6 +2098,11 @@ "expiry_milestone": 79 }, { + "name": "files-ng", + "owners": [ "adanilo", "noel" ], + "expiry_milestone": 82 + }, + { "name": "fill-on-account-select", "owners": [ "jdoerrie" ], "expiry_milestone": 80 @@ -2097,12 +2110,17 @@ { "name": "fill-on-account-select-http", "owners": [ "jdoerrie" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "focus-mode", "owners": [ "dfried", "pbos", "yiningwang@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 82 + }, + { + "name": "font-src-local-matching", + "owners": [ "drott", "layout-dev" ], + "expiry_milestone": 82 }, { "name": "force-color-profile", @@ -2110,6 +2128,11 @@ "expiry_milestone": 81 }, { + "name": "force-dice-migration", + "owners": [ "msalama" ], + "expiry_milestone": 85 + }, + { "name": "force-effective-connection-type", "owners": [ "//components/data_reduction_proxy/OWNERS" ], // ECT is a baked-in feature of Chrome. This flag is used for frequent @@ -2119,7 +2142,7 @@ { "name": "force-enable-home-page-button", "owners": [ "twellington", "chrome-android-app" ], - "expiry_milestone": 78 + "expiry_milestone": 81 }, { "name": "force-enable-system-aec", @@ -2153,7 +2176,7 @@ "owners": [ "//chrome/android/java/src/org/chromium/chrome/browser/omaha/OWNERS" ], // This is required by test teams to verify functionality on devices which // have no access to commandline flags. - "expiry_milestone": -1 + "expiry_milestone": -1 }, { "name": "foreground-notification-manager", @@ -2166,6 +2189,11 @@ "expiry_milestone": 78 }, { + "name": "fractional-scroll-offsets", + "owners": [ "bokan" ], + "expiry_milestone": 81 + }, + { "name": "gaia-action-buttons", "owners": [ "jeroendh", "rsorokin" ], "expiry_milestone": 79 @@ -2173,7 +2201,7 @@ { "name": "gdi-text-printing", "owners": [ "//printing/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 84 }, { "name": "gesture-properties-dbus-service", @@ -2189,7 +2217,7 @@ { "name": "google-password-manager", "owners": [ "ioanap", "jdoerrie" ], - "expiry_milestone": 76 + "expiry_milestone": 82 }, { "name": "grid-layout-for-ntp-shortcuts", @@ -2198,12 +2226,20 @@ }, { "name": "handwriting-gesture", - "owners": [ "shend" ], - "expiry_milestone": 76 + "owners": [ "essential-inputs-team@google.com" ], + "expiry_milestone": 80 }, { "name": "happiness-tracking-surveys-for-desktop", - "owners": [ "robliao" ], + "owners": [ "//chrome/browser/ui/hats/OWNERS" ], + "expiry_milestone": 78 + }, + { + "name": "happiness-tracking-surveys-for-desktop-demo", + "owners": [ "//chrome/browser/ui/hats/OWNERS" ], + // A debugging and demo flag to allow UI/dev/testing team to always show the UI + // components for the survey without being limited by the triggering mechanism. + // This flag should expire along with the above feature flag. "expiry_milestone": 78 }, { @@ -2222,6 +2258,11 @@ "expiry_milestone": 77 }, { + "name": "identity-disc", + "owners": ["//chrome/android/java/src/org/chromium/chrome/browser/toolbar/OWNERS"], + "expiry_milestone": 78 + }, + { "name": "ignore-gpu-blacklist", "owners": [ "kbr", "zmo" ], // A debugging flag intended for end-users where there may not be any other @@ -2229,6 +2270,11 @@ "expiry_milestone": -1 }, { + "name": "ignore-litepage-redirect-optimization-blacklist", + "owners": [ "//components/data_reduction_proxy/OWNERS" ], + "expiry_milestone": 79 + }, + { "name": "ignore-previews-blocklist", "owners": [ "//components/data_reduction_proxy/OWNERS" ], // Previews is a baked-in feature of Chrome. This flag is used for frequent @@ -2236,9 +2282,9 @@ "expiry_milestone": -1 }, { - "name": "ignore-litepage-redirect-optimization-blacklist", - "owners": [ "//components/data_reduction_proxy/OWNERS" ], - "expiry_milestone": 79 + "name": "improved-cookie-controls", + "owners": [ "dullweber", "huanzhong" ], + "expiry_milestone": 84 }, { "name": "in-product-help-demo-mode-choice", @@ -2250,7 +2296,7 @@ { "name": "installable-ink-drop", "owners": [ "collinbaker", "pbos" ], - "expiry_milestone": 77 + "expiry_milestone": 82 }, { "name": "instant-tethering", @@ -2260,17 +2306,20 @@ { "name": "interest-feed-content-suggestions", "owners": [ "//chrome/android/feed/OWNERS" ], - "expiry_milestone": 78 + "expiry_milestone": 80 }, { "name": "interest-feed-notifications", "owners": [ "iwells", "//chrome/android/feed/OWNERS" ], - "expiry_milestone": 78 + "expiry_milestone": 80 }, { "name": "isolate-origins", "owners": [ "site-isolation-dev", "alexmos", "creis", "lukasza" ], - "expiry_milestone": 79 + // This is useful for isolating additional origins beyond the normal site + // isolation policy, as well as for diagnosing problems when site isolation + // only applies to some sites. + "expiry_milestone": 90 }, { "name": "kids-management-url-classification", @@ -2294,9 +2343,14 @@ "expiry_milestone": -1 }, { - "name": "mac-v2-gpu-sandbox", + "name": "lock-screen-media-controls", + "owners": [ "beccahughes", "media-dev" ], + "expiry_milestone": 82 + }, + { + "name": "mac-syscall-sandbox", "owners": [ "kerrnel@google.com" ], - "expiry_milestone": 78 + "expiry_milestone": 80 }, { "name": "mac-system-media-permissions-info-ui", @@ -2304,6 +2358,11 @@ "expiry_milestone": 78 }, { + "name": "mac-v2-gpu-sandbox", + "owners": [ "kerrnel@google.com" ], + "expiry_milestone": 78 + }, + { "name": "mac-views-task-manager", "owners": [ "ellyjones" ], "expiry_milestone": 77 @@ -2311,7 +2370,7 @@ { "name": "manual-password-generation-android", "owners": [ "ioanap" ], - "expiry_milestone": 76 + "expiry_milestone": 78 }, { "name": "media-router-cast-allow-all-ips", @@ -2375,14 +2434,9 @@ "expiry_milestone": 80 }, { - "name": "network-service", - "owners": [ "network-service-dev" ], - "expiry_milestone": 76 - }, - { "name": "network-service-in-process", "owners": [ "network-service-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 84 }, { "name": "new-net-error-page-ui", @@ -2390,24 +2444,19 @@ "expiry_milestone": 75 }, { - "name": "new-password-form-parsing", - "owners": [ "dvadym" ], - "expiry_milestone": 76 - }, - { - "name": "new-password-form-parsing-for-saving", - "owners": [ "dvadym" ], - "expiry_milestone": 76 + "name": "new-overview-tablet-layout", + "owners": [ "sammiequon" ], + "expiry_milestone": 85 }, { - "name": "new-tab-loading-animation", - "owners": [ "pbos@chromium.org" ], - "expiry_milestone": 76 + "name": "new-tabstrip-animation", + "owners": [ "tbergquist" ], + "expiry_milestone": 81 }, { "name": "new-usb-backend", "owners": [ "reillyg@chromium.org" ], - "expiry_milestone": 76 + "expiry_milestone": 83 }, { "name": "newblue", @@ -2427,7 +2476,7 @@ { "name": "ntp-customization-menu-v2", "owners": ["kmilka", "ramyan"], - "expiry_milestone": 77 + "expiry_milestone": 79 }, { "name": "ntp-disable-initial-most-visited-fade-in", @@ -2435,6 +2484,11 @@ "expiry_milestone": 80 }, { + "name": "ntp-realbox", + "owners": ["dbeam", "mahmadi"], + "expiry_milestone": 85 + }, + { "name": "oculus-vr", "owners": [ "//device/vr/OWNERS", "xr-dev@chromium.org" ], "expiry_milestone": 79 @@ -2482,12 +2536,12 @@ { "name": "offline-pages-live-page-sharing", "owners": [ "petewil", "jianli", "offline-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 86 }, { "name": "offline-pages-load-signal-collecting", "owners": [ "petewil", "offline-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 86 }, { "name": "offline-pages-pending-download", @@ -2502,12 +2556,12 @@ { "name": "offline-pages-renovations", "owners": [ "petewil", "offline-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 86 }, { "name": "offline-pages-resource-based-snapshot", "owners": [ "petewil", "offline-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 86 }, { "name": "offlining-recent-pages", @@ -2537,17 +2591,22 @@ { "name": "omnibox-experimental-keyword-mode", "owners": [ "krb", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "omnibox-group-suggestions-by-search-vs-url", "owners": [ "krb", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 78 + }, + { + "name": "omnibox-local-entity-suggestions", + "owners": [ "manukh", "chrome-omnibox-team@google.com" ], "expiry_milestone": 80 }, { "name": "omnibox-material-design-weather-icons", - "owners": [ "manukh", "chromium-omnibox-team" ], - "expiry_milestone": 76 + "owners": [ "manukh", "ender", "chromium-omnibox-team" ], + "expiry_milestone": 80 }, { "name": "omnibox-max-url-matches", @@ -2560,13 +2619,18 @@ "expiry_milestone": 80 }, { + "name": "omnibox-on-focus-suggestions", + "owners": [ "chrome-omnibox-team@google.com" ], + "expiry_milestone": 85 + }, + { "name": "omnibox-pedal-suggestions", "owners": [ "orinj", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "omnibox-reverse-answers", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { @@ -2576,8 +2640,8 @@ }, { "name": "omnibox-rich-entity-suggestions", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 80 }, { "name": "omnibox-search-engine-logo", @@ -2605,29 +2669,34 @@ "expiry_milestone": 76 }, { + "name": "omnibox-tab-switch-suggestions-dedicated-row", + "owners": [ "krb", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 82 + }, + { "name": "omnibox-ui-cues-for-search-history-matches", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 78 }, { "name": "omnibox-ui-hide-steady-state-url-path-query-and-ref", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { "name": "omnibox-ui-hide-steady-state-url-scheme", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { "name": "omnibox-ui-hide-steady-state-url-trivial-subdomains", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { "name": "omnibox-ui-max-autocomplete-matches", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 80 }, { "name": "omnibox-ui-one-click-unelide", @@ -2636,45 +2705,30 @@ }, { "name": "omnibox-ui-show-placeholder-when-caret-showing", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 76 }, { "name": "omnibox-ui-show-suggestion-favicons", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "owners": [ "ender", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 79 }, { "name": "omnibox-ui-swap-title-and-url", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 - }, - { - "name": "omnibox-ui-vertical-margin", - "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 - }, - { - "name": "omnibox-ui-vertical-margin-limit-to-non-touch-only", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 76 }, { "name": "omnibox-wrap-popup-position", "owners": [ "krb", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 81 + "expiry_milestone": 78 }, { "name": "omnibox-zero-suggestions-on-ntp", - "owners": [ "chrome-android-omnibox-team@google.com" ], + "owners": [ "chrome-omnibox-team@google.com" ], "expiry_milestone": 81 }, { - "name": "only-new-password-form-parsing", - "owners": [ "dvadym" ], - "expiry_milestone": 76 - }, - { "name": "on-the-fly-mhtml-hash-computation", "owners": [ "mtlieuu", "offline-dev@chromium.org" ], "expiry_milestone": 76 @@ -2692,7 +2746,7 @@ { "name": "out-of-blink-cors", "owners": [ "toyoshim" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "overlay-new-layout", @@ -2724,7 +2778,7 @@ { "name": "overscroll-history-navigation", "owners": [ "mohsen", "jinsukkim" ], - "expiry_milestone": 77 + "expiry_milestone": 80 }, { "name": "passive-event-listeners-due-to-fling", @@ -2742,19 +2796,24 @@ "expiry_milestone": 80 }, { + "name": "password-leak-detection", + "owners": [ "jdoerrie", "vasilii" ], + "expiry_milestone": 80 + }, + { "name": "password-manager-onboarding-android", "owners": ["achulkov", "ioanap"], "expiry_milestone": 80 }, { - "name": "passwords-keyboard-accessory", - "owners": [ "fhorschig" ], + "name": "PasswordImport", + "owners": [ "vasilii" ], "expiry_milestone": 76 }, { - "name": "passwords-migrate-linux-to-login-db", - "owners": [ "cfroussios" ], - "expiry_milestone": 76 + "name": "passwords-account-storage", + "owners": ["mamir", "treib"], + "expiry_milestone": 85 }, { "name": "pdf-annotations", @@ -2764,7 +2823,7 @@ { "name": "pdf-form-save", "owners": [ "thestig" ], - "expiry_milestone": 78 + "expiry_milestone": 82 }, { "name": "pdf-isolation", @@ -2792,14 +2851,24 @@ "expiry_milestone": 76 }, { + "name": "prefetch-main-resource-network-isolation-key", + "owners": [ "dom", "yhirano" ], + "expiry_milestone": 85 + }, + { + "name": "prefetch-privacy-changes", + "owners": [ "dom", "yhirano" ], + "expiry_milestone": 85 + }, + { "name": "proactive-tab-freeze-and-discard", "owners": [ "fdoray" ], "expiry_milestone": 75 }, { - "name": "progress-bar-throttle", - "owners": [ "mdjones" ], - "expiry_milestone": 76 + "name": "profile-menu-revamp", + "owners": [ "tangltom" ], + "expiry_milestone": 82 }, { "name": "pull-to-refresh", @@ -2807,6 +2876,11 @@ "expiry_milestone": 83 }, { + "name": "quiet-notification-prompts", + "owners": [ "engedy", "mkwst", "andypaicu", "hkamila" ], + "expiry_milestone": 80 + }, + { "name": "reader-mode-heuristics", "owners": [ "mdjones" ], "expiry_milestone": 78 @@ -2817,9 +2891,19 @@ "expiry_milestone": 78 }, { - "name": "remove-ntp-fakebox", - "owners": [ "kristipark", "ramyan" ], - "expiry_milestone": 76 + "name": "release-notes", + "owners": [ "yulunwu" ], + "expiry_milestone": 79 + }, + { + "name": "release-notes-notification", + "owners": [ "yulunwu" ], + "expiry_milestone": 79 + }, + { + "name": "request-unbuffered-dispatch", + "owners": [ "bokan" ], + "expiry_milestone": 80 }, { "name": "rewrite-leveldb-on-deletion", @@ -2842,11 +2926,21 @@ "expiry_milestone": 83 }, { + "name": "scalable-app-list", + "owners": [ "tbarzic" ], + "expiry_milestone": 82 + }, + { "name": "scheduler-configuration", "owners": [ "kerrnel", "mnissler" ], "expiry_milestone": 77 }, { + "name": "scrollable-tabstrip", + "owners": ["chrome-desktop-ui-seattle@google.com", "tbergquist"], + "expiry_milestone": 82 + }, + { "name": "security-interstitials-dark-mode", "owners": ["estark"], "expiry_milestone": 79 @@ -2868,6 +2962,21 @@ "owners": [ "binji" ], "expiry_milestone": 78 }, + { + "name": "shared-clipboard-receiver", + "owners": [ "//chrome/browser/sharing/OWNERS" ], + "expiry_milestone": 80 + }, + { + "name": "shared-clipboard-ui", + "owners": [ "//chrome/browser/sharing/OWNERS" ], + "expiry_milestone": 80 + }, + { + "name": "sharing-use-device-info", + "owners": [ "//chrome/browser/sharing/OWNERS" ], + "expiry_milestone": 80 + }, { "name": "shelf-dense-clamshell", "owners": [ "manucornet", "mmourgos" ], @@ -2906,6 +3015,11 @@ "expiry_milestone": 80 }, { + "name": "show-sync-paused-reason-cookies-cleared-on-exit", + "owners": [ "msalama" ], + "expiry_milestone": 85 + }, + { "name": "show-taps", "owners": [ "//ash/OWNERS" ], // This is a debug flag, so that video bug reports can show input taps to @@ -2920,17 +3034,6 @@ "expiry_milestone": -1 }, { - "name": "enable-bookmark-reorder", - "owners": ["jhimawan@google.com", "twellington" ], - "expiry_milestone": 80 - }, - { - "name": "enable-virtual-desks", - "owners": [ "afakhry" ], - // This is a flag to enable or disable the Virtual Desks feature. - "expiry_milestone": 79 - }, - { "name": "silent-debugger-extension-api", "owners": [ "//extensions/OWNERS" ], "expiry_milestone": 77 @@ -2945,7 +3048,7 @@ "_comment2": "in https://crbug.com/849815.", "name": "site-isolation-trial-opt-out", "owners": [ "site-isolation-dev", "alexmos", "creis", "lukasza" ], - "expiry_milestone": 77 + "expiry_milestone": 85 }, { "name": "site-settings", @@ -2953,11 +3056,6 @@ "expiry_milestone": 78 }, { - "name": "release-notes", - "owners": [ "yulunwu" ], - "expiry_milestone": 79 - }, - { "name": "smart-dim-model-v3", "owners": [ "amoylan", "jiameng" ], "expiry_milestone": 80 @@ -2988,14 +3086,34 @@ "expiry_milestone": 75 }, { + "name": "storage-access-api", + "owners": [ "brandm@microsoft.com" ], + "expiry_milestone": 80 + }, + { "name": "strict-origin-isolation", "owners": ["wjmaclean", "alexmos", "creis"], + // This can be used to opt in to origin isolation which isolates full + // origins rather than sites. Note that this breaks document.domain and is + // therefore unlikely to ship anytime soon, but this allows experimenting + // with a stronger isolation policy for users who may not care about + // breaking compatibility with document.domain. + "expiry_milestone": 90 + }, + { + "name": "SupervisedUserCommittedInterstitials", + "owners": [ "carlosil" ], + "expiry_milestone": 77 + }, + { + "name": "sync-clipboard-service", + "owners": [ "joaodasilva" ], "expiry_milestone": 80 }, { "name": "sync-support-secondary-account", "owners": [ "treib", "//components/sync/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "sync-wifi-configurations", @@ -3008,33 +3126,43 @@ "expiry_milestone": 79 }, { + "name": "system-tray-pagination", + "owners": ["amehfooz", "tengs"], + "expiry_milestone": 81 + }, + { "name": "tab-groups", "owners": [ "chrome-desktop-ui-seattle@google.com", "bsep" ], "expiry_milestone": 82 }, { + "name": "tab-hover-card-images", + "owners": [ "dfried", "corising", "//chrome/browser/ui/views/tabs/OWNERS" ], + "expiry_milestone": 82 + }, + { "name": "tab-hover-cards", "owners": [ "corising", "//chrome/browser/ui/views/tabs/OWNERS" ], "expiry_milestone": 82 }, { - "name": "tab-hover-card-images", - "owners": [ "dfried", "corising", "//chrome/browser/ui/views/tabs/OWNERS" ], - "expiry_milestone": 82 + "name": "tab-outlines-in-low-contrast-themes", + "owners": [ "dfried" ], + "expiry_milestone": 82 }, { - "name": "terminal-system-app", - "owners": [ "joelhockey", "benwells", "//chrome/browser/chromeos/guest_os/OWNERS" ], - "expiry_milestone": 82 + "name": "tab-switcher-longpress-menu", + "owners": [ "lazzzis@google.com", "twellington" ], + "expiry_milestone": 81 }, { - "name": "treat-unsafe-downloads-as-active-content", - "owners": [ "jdeblasio", "cthomp" ], - "expiry_milestone": 79 + "name": "temporary-unexpire-flags-m76", + "owners": [ "ellyjones", "flags-dev" ], + "expiry_milestone": 80 }, { - "name": "scrollable-tabstrip", - "owners": ["chrome-desktop-ui-seattle@google.com", "tbergquist"], + "name": "terminal-system-app", + "owners": [ "joelhockey", "benwells", "//chrome/browser/chromeos/guest_os/OWNERS" ], "expiry_milestone": 82 }, { @@ -3092,11 +3220,31 @@ "expiry_milestone": 78 }, { + "name": "treat-unsafe-downloads-as-active-content", + "owners": [ "jdeblasio", "cthomp" ], + "expiry_milestone": 79 + }, + { + "name": "trim-on-all-frames-frozen", + "owners": [ "bgeffon", "sonnyrao" ], + "expiry_milestone": 81 + }, + { + "name": "trim-on-memory-pressure", + "owners": [ "bgeffon", "sonnyrao" ], + "expiry_milestone": 81 + }, + { "name": "try-supported-channel-layouts", "owners": [ "dalecurtis" ], "expiry_milestone": 76 }, { + "name": "turn-off-streaming-media-caching", + "owners": [ "shawnpi@microsoft.com" ], + "expiry_milestone": 82 + }, + { "name": "ui-disable-partial-swap", "owners": [ "//components/viz/OWNERS" ], // This flag is used for in-the-field debugging of rendering issues, @@ -3116,19 +3264,19 @@ "expiry_milestone": -1 }, { - "name": "unfiltered-bluetooth-devices", - "owners": [ "sonnysasaka", "qiyuh@google.com" ], - "expiry_milestone": 76 - }, - { "name": "unified-consent", "owners": [ "msarda", "tangltom" ], - "expiry_milestone": 76 + "expiry_milestone": 79 }, { "name": "unsafely-treat-insecure-origin-as-secure", "owners": [ "security-dev" ], - "expiry_milestone": 76 + "expiry_milestone": 82 + }, + { + "name": "update-hover-at-begin-frame", + "owners": [ "lanwei", "input-dev" ], + "expiry_milestone": 81 }, { "name": "update-menu-item-custom-summary", @@ -3138,6 +3286,11 @@ "expiry_milestone": -1 }, { + "name": "updated_cellular_activation_ui", + "owners": [ "azeemarshad", "khorimoto" ], + "expiry_milestone": 80 + }, + { "name": "usage-stats", "owners": [ "pnoland", "chromeshine@google.com" ], "expiry_milestone": 80 @@ -3152,6 +3305,22 @@ "expiry_milestone": -1 }, { + "name": "use-fake-device-for-media-stream", + "owners": [ "mcasas", "chromeos-gfx@google.com" ], + "expiry_milestone": 81 + }, + { + "name": "use_messages_google_com_domain", + "owners": [ "azeemarshad", "khorimoto" ], + "expiry_milestone": 76 + }, + { + "name": "use_messages_staging_url", + "owners": [ "azeemarshad", "khorimoto", "jonmann" ], + // This flag is required for QA and dogfood testing. + "expiry_milestone": -1 + }, + { "name": "use-multilogin-endpoint", "owners": [ "droger", "msarda" ], "expiry_milestone": 78 @@ -3164,7 +3333,7 @@ { "name": "use-pdf-compositor-service-for-print", "owners": [ "//printing/OWNERS" ], - "expiry_milestone": 76 + "expiry_milestone": 79 }, { "name": "use-search-click-for-right-click", @@ -3194,11 +3363,6 @@ "expiry_milestone": 80 }, { - "name": "views-cast-dialog", - "owners": [ "//chrome/browser/media/router/OWNERS" ], - "expiry_milestone": 76 - }, - { "name": "wake-on-wifi-packet", "owners": [ "abhishekbh", "chirantan" ], "expiry_milestone": 76 @@ -3213,7 +3377,12 @@ { "name": "web-contents-occlusion", "owners": [ "davidbienvenu" ], - "expiry_milestone": 77 + "expiry_milestone": 81 + }, + { + "name": "webui-tab-strip", + "owners": [ "johntlee", "pbos" ], + "expiry_milestone": 82 }, { "name": "webxr", @@ -3221,6 +3390,16 @@ "expiry_milestone": 79 }, { + "name": "webxr-anchors", + "owners": [ "//third_party/blink/renderer/modules/xr/OWNERS", "xr-dev@chromium.org" ], + "expiry_milestone": 79 + }, + { + "name": "webxr-ar-module", + "owners": [ "//third_party/blink/renderer/modules/xr/OWNERS", "xr-dev@chromium.org" ], + "expiry_milestone": 80 + }, + { "name": "webxr-hit-test", "owners": [ "//third_party/blink/renderer/modules/xr/OWNERS", "xr-dev@chromium.org" ], "expiry_milestone": 79 @@ -3251,16 +3430,8 @@ "expiry_milestone": 79 }, { - "name": "enable-streamlined-usb-printer-setup", - "owners": [ "baileyberro" ], - "expiry_milestone": 77 - }, - { - "name": "update-hover-at-begin-frame", - "owners": [ "lanwei", "input-dev" ], - "expiry_milestone": 81 + "name": "zero-state-files", + "owners": [ "tby", "jiameng" ], + "expiry_milestone": 82 } - - // This is an alphabetized list; please do your part to keep it organized by - // inserting your entry in alphabetical order. ] diff --git a/chromium/chrome/browser/flag-never-expire-list.json b/chromium/chrome/browser/flag-never-expire-list.json index 0abc52c88cd..a3f6b9fdc7e 100644 --- a/chromium/chrome/browser/flag-never-expire-list.json +++ b/chromium/chrome/browser/flag-never-expire-list.json @@ -14,6 +14,7 @@ // test (AboutFlagsTest.OnlyPermittedFlagsNeverExpire). [ "allow-previews", + "arc-native-bridge-toggle", "ash-debug-shortcuts", "ash-enable-unified-desktop", "data-saver-server-previews", @@ -33,6 +34,7 @@ "enable-data-reduction-proxy-server-experiment", "enable-devtools-experiments", "enable-experimental-web-platform-features", + "enable-experimental-webassembly-features", "enable-future-v8-vm-features", "enable-gpu-rasterization", "enable-gpu-service-logging", @@ -81,6 +83,7 @@ "ui-slow-animations", "update-menu-item-custom-summary", "use-angle", + "use_messages_staging_url", "use-sync-sandbox", "wallet-service-use-sandbox" ] diff --git a/chromium/chrome/browser/media/BUILD.gn b/chromium/chrome/browser/media/BUILD.gn index c6768520d73..4ffc0e9a556 100644 --- a/chromium/chrome/browser/media/BUILD.gn +++ b/chromium/chrome/browser/media/BUILD.gn @@ -13,9 +13,6 @@ mojom("mojo_bindings") { public_deps = [ "//url/mojom:url_mojom_origin", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } proto_library("media_engagement_preload_proto") { diff --git a/chromium/chrome/browser/media/media_engagement_score_details.mojom b/chromium/chrome/browser/media/media_engagement_score_details.mojom index 342c65c6d63..54db84482fb 100644 --- a/chromium/chrome/browser/media/media_engagement_score_details.mojom +++ b/chromium/chrome/browser/media/media_engagement_score_details.mojom @@ -19,17 +19,6 @@ struct MediaEngagementScoreDetails { // Whether the score is considered to be high. bool is_high; - - // Data used for experiments. - int32 audible_playbacks; - int32 significant_playbacks; - - // How many time the score changed `is_high` status. - int32 high_score_changes; - - // Details of the components which make up |media_playbacks|. - int32 audio_context_playbacks; - int32 media_element_playbacks; }; struct MediaEngagementConfig { diff --git a/chromium/chrome/browser/media/router/BUILD.gn b/chromium/chrome/browser/media/router/BUILD.gn index 29707ed15c0..b4083546482 100644 --- a/chromium/chrome/browser/media/router/BUILD.gn +++ b/chromium/chrome/browser/media/router/BUILD.gn @@ -11,6 +11,7 @@ static_library("router") { deps = [ "//base", "//chrome/common:constants", + "//components/cast_channel", "//components/keyed_service/content", "//components/keyed_service/core", "//content/public/browser", @@ -25,7 +26,7 @@ static_library("router") { ] public_deps = [ "//chrome/common/media_router:router", - "//chrome/common/media_router/mojo:media_router", + "//chrome/common/media_router/mojom:media_router", ] sources = [ "issue_manager.cc", @@ -82,8 +83,6 @@ static_library("router") { "event_page_request_manager.h", "event_page_request_manager_factory.cc", "event_page_request_manager_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", @@ -110,6 +109,8 @@ static_library("router") { "providers/cast/cast_app_discovery_service.h", "providers/cast/cast_internal_message_util.cc", "providers/cast/cast_internal_message_util.h", + "providers/cast/cast_media_controller.cc", + "providers/cast/cast_media_controller.h", "providers/cast/cast_media_route_provider.cc", "providers/cast/cast_media_route_provider.h", "providers/cast/cast_media_route_provider_metrics.cc", @@ -156,6 +157,8 @@ static_library("router") { "providers/openscreen/platform/task_runner.h", "providers/openscreen/platform/time.cc", "providers/openscreen/platform/trace_logging_platform.cc", + "providers/openscreen/platform/udp_socket.cc", + "providers/openscreen/platform/udp_socket.h", ] configs += @@ -191,8 +194,8 @@ static_library("test_support") { if (enable_extensions) { deps += [ "discovery", - "//chrome/common/media_router/mojo:media_router", - "//chrome/common/media_router/mojo:media_router_test_interfaces", + "//chrome/common/media_router/mojom:media_router", + "//chrome/common/media_router/mojom:media_router_test_interfaces", "//extensions/browser", "//extensions/common", ] diff --git a/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn index 8b0d12c2d4d..fd22666e58a 100644 --- a/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn +++ b/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn @@ -17,8 +17,9 @@ source_set("lib") { "collection_store.h", "display_decider.cc", "display_decider.h", - "distribution_policy.cc", - "distribution_policy.h", + "icon_converter.h", + "icon_converter_result.cc", + "icon_converter_result.h", "icon_entry.cc", "icon_entry.h", "icon_store.cc", @@ -43,6 +44,8 @@ source_set("lib") { "notification_scheduler_context.h", "notification_store.cc", "notification_store.h", + "png_icon_converter_impl.cc", + "png_icon_converter_impl.h", "proto_conversion.cc", "proto_conversion.h", "scheduled_notification_manager.cc", @@ -51,6 +54,8 @@ source_set("lib") { "scheduler_config.h", "scheduler_utils.cc", "scheduler_utils.h", + "stats.cc", + "stats.h", "webui_client.cc", "webui_client.h", ] @@ -58,11 +63,13 @@ source_set("lib") { # This target should not depend on anything in //chrome/* except the proto library. deps = [ "//base", + "//chrome/app:generated_resources", "//chrome/browser/notifications/proto", "//chrome/browser/notifications/scheduler/public", "//components/keyed_service/core", "//components/leveldb_proto", "//skia", + "//ui/base", "//ui/gfx/codec", ] } @@ -72,15 +79,18 @@ source_set("unit_tests") { sources = [ "background_task_coordinator_unittest.cc", "display_decider_unittest.cc", - "distribution_policy_unittest.cc", + "icon_converter_unittest.cc", "icon_store_unittest.cc", "impression_history_tracker_unittest.cc", "impression_store_unittest.cc", + "impression_types_unittest.cc", "init_aware_scheduler_unittest.cc", + "notification_scheduler_unittest.cc", "notification_store_unittest.cc", "proto_conversion_unittest.cc", "scheduled_notification_manager_unittest.cc", "scheduler_utils_unittest.cc", + "stats_unittest.cc", ] deps = [ diff --git a/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn index 23e87ae65e5..a08c8aa0d3c 100644 --- a/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn +++ b/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn @@ -12,6 +12,8 @@ source_set("public") { "display_agent.h", "features.cc", "features.h", + "icon_bundle.cc", + "icon_bundle.h", "impression_detail.cc", "impression_detail.h", "notification_background_task_scheduler.h", @@ -23,6 +25,8 @@ source_set("public") { "notification_scheduler_client.h", "notification_scheduler_client_registrar.cc", "notification_scheduler_client_registrar.h", + "notification_scheduler_constant.h", + "notification_scheduler_types.cc", "notification_scheduler_types.h", "schedule_params.cc", "schedule_params.h", diff --git a/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn index ec4d2213eb5..ac7bef4d697 100644 --- a/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn +++ b/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn @@ -10,6 +10,8 @@ source_set("test_lib") { sources = [ "fake_clock.cc", "fake_clock.h", + "mock_background_task_coordinator.cc", + "mock_background_task_coordinator.h", "mock_display_agent.cc", "mock_display_agent.h", "mock_display_decider.cc", @@ -18,6 +20,8 @@ source_set("test_lib") { "mock_impression_history_tracker.h", "mock_notification_background_task_scheduler.cc", "mock_notification_background_task_scheduler.h", + "mock_notification_scheduler_client.cc", + "mock_notification_scheduler_client.h", "mock_scheduled_notification_manager.cc", "mock_scheduled_notification_manager.h", "test_utils.cc", diff --git a/chromium/chrome/browser/printing/OWNERS b/chromium/chrome/browser/printing/OWNERS index 9b08c6620bd..01ea38e435d 100644 --- a/chromium/chrome/browser/printing/OWNERS +++ b/chromium/chrome/browser/printing/OWNERS @@ -1 +1,2 @@ file://printing/OWNERS +# COMPONENT: Internals>Printing 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 9c689685bca..dd0565c9fcc 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 @@ -28,7 +28,7 @@ #include "components/prefs/testing_pref_service.h" #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 "content/public/test/browser_task_environment.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -213,7 +213,7 @@ class CloudPrintProxyPolicyTest : public ::testing::Test { } protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; 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 4d0de850450..a790a424c0f 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 @@ -122,8 +122,7 @@ void GCDApiFlowImpl::OnAccessTokenFetchComplete( auto request = std::make_unique<network::ResourceRequest>(); request->url = request_->GetURL(); - request->load_flags = - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES; + request->credentials_mode = network::mojom::CredentialsMode::kOmit; request->headers.SetHeader(kCloudPrintOAuthHeaderKey, GetOAuthHeaderValue(access_token_info.token)); diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc index f312905ad0a..b6e7f2ea963 100644 --- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc +++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc @@ -16,7 +16,7 @@ #include "base/values.h" #include "chrome/browser/printing/cloud_print/gcd_api_flow_impl.h" #include "components/signin/public/identity_manager/identity_test_environment.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "google_apis/gaia/google_service_auth_error.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" @@ -82,7 +82,7 @@ class GCDApiFlowTest : public testing::Test { MockDelegate* mock_delegate_; private: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; signin::IdentityTestEnvironment identity_test_environment_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_url_loader_factory_; 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 2d64da95326..84fb22c6872 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc +++ b/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc @@ -17,11 +17,11 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/bind_test_util.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/printing/cloud_print/privet_http_impl.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "printing/buildflags/buildflags.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" @@ -353,7 +353,7 @@ class PrivetHTTPTest : public TestWithParam<const char*> { const GURL kSubmitDocWithJobIDURL; const GURL kCreateJobURL; - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_url_loader_factory_; @@ -986,7 +986,7 @@ TEST_P(PrivetLocalPrintTest, LocalPrintRetryOnInvalidJobID) { class PrivetHttpWithServerTest : public ::testing::Test { protected: PrivetHttpWithServerTest() - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP), shared_url_loader_factory_( base::MakeRefCounted<network::TestSharedURLLoaderFactory>()) {} @@ -1004,7 +1004,7 @@ class PrivetHttpWithServerTest : public ::testing::Test { "test", server_->host_port_pair(), shared_url_loader_factory_); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<EmbeddedTestServer> server_; std::unique_ptr<PrivetHTTPClientImpl> client_; scoped_refptr<network::TestSharedURLLoaderFactory> shared_url_loader_factory_; diff --git a/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister_unittest.cc index ec884a04011..c9e4ada4fc5 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister_unittest.cc +++ b/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister_unittest.cc @@ -13,7 +13,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/local_discovery/test_service_discovery_client.h" #include "chrome/browser/printing/cloud_print/privet_http_asynchronous_factory_impl.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "net/url_request/url_request_test_util.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" @@ -137,7 +137,7 @@ class PrivetLocalPrinterListerTest : public testing::Test { } protected: - content::TestBrowserThreadBundle test_thread_bundle; + content::BrowserTaskEnvironment task_environment; scoped_refptr<TestServiceDiscoveryClient> test_service_discovery_client_; std::unique_ptr<PrivetLocalPrinterLister> local_printer_lister_; StrictMock<MockLocalPrinterListerDelegate> delegate_; diff --git a/chromium/chrome/browser/printing/cloud_print/privet_notifications_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_notifications_unittest.cc index 9ac3c06ac13..3293ddc528b 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_notifications_unittest.cc +++ b/chromium/chrome/browser/printing/cloud_print/privet_notifications_unittest.cc @@ -16,7 +16,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" #include "services/network/test/test_utils.h" @@ -108,7 +108,7 @@ class PrivetNotificationsListenerTest : public testing::Test { } protected: - content::TestBrowserThreadBundle test_thread_bundle; + content::BrowserTaskEnvironment task_environment; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_url_loader_factory_; @@ -266,7 +266,7 @@ class PrivetNotificationsNotificationTest : public testing::Test { Profile* profile() { return profile_; } // The thread bundle must be first so it is destroyed last. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<NotificationDisplayServiceTester> display_service_; diff --git a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc index 60ae78cb53f..f9070dffd50 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc +++ b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc @@ -49,9 +49,8 @@ void OnGetNetworkList( "lo", "lo", 0, net::NetworkChangeNotifier::CONNECTION_UNKNOWN, localhost_prefix, 8, net::IP_ADDRESS_ATTRIBUTE_NONE)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(std::move(callback), std::move(ip4_networks))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(std::move(callback), std::move(ip4_networks))); } void GetNetworkListOnUIThread( @@ -65,12 +64,12 @@ void GetNetworkListOnUIThread( void CreateUDPSocketOnUIThread( content::BrowserContext* profile, network::mojom::UDPSocketRequest request, - network::mojom::UDPSocketReceiverPtr receiver_ptr) { + network::mojom::UDPSocketListenerPtr listener_ptr) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); network::mojom::NetworkContext* network_context = content::BrowserContext::GetDefaultStoragePartition(profile) ->GetNetworkContext(); - network_context->CreateUDPSocket(std::move(request), std::move(receiver_ptr)); + network_context->CreateUDPSocket(std::move(request), std::move(listener_ptr)); } } // namespace @@ -83,10 +82,9 @@ PrivetTrafficDetector::PrivetTrafficDetector( : helper_(new Helper(profile, on_traffic_detected)) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&PrivetTrafficDetector::Helper::ScheduleRestart, - base::Unretained(helper_))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&PrivetTrafficDetector::Helper::ScheduleRestart, + base::Unretained(helper_))); } PrivetTrafficDetector::~PrivetTrafficDetector() { @@ -99,7 +97,7 @@ PrivetTrafficDetector::~PrivetTrafficDetector() { void PrivetTrafficDetector::OnConnectionChanged( network::mojom::ConnectionType type) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrivetTrafficDetector::Helper::HandleConnectionChanged, base::Unretained(helper_), type)); @@ -111,7 +109,7 @@ PrivetTrafficDetector::Helper::Helper( : profile_(profile), on_traffic_detected_(on_traffic_detected), restart_attempts_(kMaxRestartAttempts), - receiver_binding_(this) { + listener_binding_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); } @@ -132,7 +130,7 @@ void PrivetTrafficDetector::Helper::ScheduleRestart() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); ResetConnection(); weak_ptr_factory_.InvalidateWeakPtrs(); - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &GetNetworkListOnUIThread, @@ -150,14 +148,14 @@ void PrivetTrafficDetector::Helper::Restart( void PrivetTrafficDetector::Helper::Bind() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - network::mojom::UDPSocketReceiverPtr receiver_ptr; - network::mojom::UDPSocketReceiverRequest receiver_request = - mojo::MakeRequest(&receiver_ptr); - receiver_binding_.Bind(std::move(receiver_request)); - base::PostTaskWithTraits( + network::mojom::UDPSocketListenerPtr listener_ptr; + network::mojom::UDPSocketListenerRequest listener_request = + mojo::MakeRequest(&listener_ptr); + listener_binding_.Bind(std::move(listener_request)); + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&CreateUDPSocketOnUIThread, profile_, - mojo::MakeRequest(&socket_), std::move(receiver_ptr))); + mojo::MakeRequest(&socket_), std::move(listener_ptr))); network::mojom::UDPSocketOptionsPtr socket_options = network::mojom::UDPSocketOptions::New(); @@ -240,7 +238,7 @@ void PrivetTrafficDetector::Helper::OnJoinGroupComplete(int rv) { void PrivetTrafficDetector::Helper::ResetConnection() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); socket_.reset(); - receiver_binding_.Close(); + listener_binding_.Close(); } void PrivetTrafficDetector::Helper::OnReceived( @@ -256,8 +254,8 @@ void PrivetTrafficDetector::Helper::OnReceived( recv_addr_ = src_addr.value(); if (IsPrivetPacket(data.value())) { ResetConnection(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - on_traffic_detected_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + on_traffic_detected_); } else { socket_->ReceiveMoreWithBufferSize(1, net::dns_protocol::kMaxMulticastSize); } diff --git a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h index f34c0e65518..52df267f286 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h +++ b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h @@ -43,13 +43,13 @@ class PrivetTrafficDetector private: // Constructed by PrivetTrafficDetector on the UI thread. but lives on the IO // thread and destroyed on the IO thread. - class Helper : public network::mojom::UDPSocketReceiver { + class Helper : public network::mojom::UDPSocketListener { public: Helper(content::BrowserContext* profile, base::RepeatingClosure on_traffic_detected); ~Helper() override; - // network::mojom::UDPSocketReceiver: + // network::mojom::UDPSocketListener: void OnReceived(int32_t result, const base::Optional<net::IPEndPoint>& src_addr, base::Optional<base::span<const uint8_t>> data) override; @@ -81,9 +81,9 @@ class PrivetTrafficDetector net::IPEndPoint recv_addr_; network::mojom::UDPSocketPtr socket_; - // Implementation of socket receiver callback. + // Implementation of socket listener callback. // Initialized on the UI thread, but only accessed on the IO thread. - mojo::Binding<network::mojom::UDPSocketReceiver> receiver_binding_; + mojo::Binding<network::mojom::UDPSocketListener> listener_binding_; base::WeakPtrFactory<Helper> weak_ptr_factory_{this}; diff --git a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc index dc6c66fd913..7f82e017dfb 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc +++ b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc @@ -155,7 +155,7 @@ void PrivetURLLoader::Try() { request->method = request_type_; // Privet requests are relevant to hosts on local network only. request->load_flags = net::LOAD_BYPASS_PROXY | net::LOAD_DISABLE_CACHE; - request->allow_credentials = false; + request->credentials_mode = network::mojom::CredentialsMode::kOmit; std::string token = GetPrivetAccessToken(); if (token.empty()) diff --git a/chromium/chrome/browser/printing/cloud_print/privet_url_loader_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_url_loader_unittest.cc index 39306252aac..32eac3b5d7c 100644 --- a/chromium/chrome/browser/printing/cloud_print/privet_url_loader_unittest.cc +++ b/chromium/chrome/browser/printing/cloud_print/privet_url_loader_unittest.cc @@ -11,7 +11,7 @@ #include "base/files/file_util.h" #include "base/run_loop.h" #include "base/test/bind_test_util.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" @@ -100,12 +100,11 @@ class MockPrivetURLLoaderDelegate : public PrivetURLLoader::Delegate { class PrivetURLLoaderTest : public ::testing::Test { public: PrivetURLLoaderTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::IO), + : task_environment_(base::test::TaskEnvironment::MainThreadType::IO), test_shared_url_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)), - delegate_(scoped_task_environment_.GetMainThreadTaskRunner()) { + delegate_(task_environment_.GetMainThreadTaskRunner()) { privet_url_loader_ = std::make_unique<PrivetURLLoader>( GURL(kSamplePrivetURL), "POST", test_shared_url_loader_factory_, TRAFFIC_ANNOTATION_FOR_TESTS, &delegate_); @@ -126,7 +125,7 @@ class PrivetURLLoaderTest : public ::testing::Test { test_url_loader_factory_.SetInterceptor(base::NullCallback()); } - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_url_loader_factory_; diff --git a/chromium/chrome/browser/printing/pdf_nup_converter_client.cc b/chromium/chrome/browser/printing/pdf_nup_converter_client.cc index 7f1bc0b0310..a251fe6b559 100644 --- a/chromium/chrome/browser/printing/pdf_nup_converter_client.cc +++ b/chromium/chrome/browser/printing/pdf_nup_converter_client.cc @@ -7,10 +7,8 @@ #include <utility> #include "base/bind.h" -#include "chrome/services/printing/public/mojom/constants.mojom.h" +#include "chrome/browser/printing/printing_service.h" #include "chrome/services/printing/public/mojom/pdf_nup_converter.mojom.h" -#include "content/public/browser/system_connector.h" -#include "services/service_manager/public/cpp/connector.h" namespace printing { @@ -77,11 +75,9 @@ void PdfNupConverterClient::RemovePdfNupConverterRequest(int cookie) { mojom::PdfNupConverterPtr PdfNupConverterClient::CreatePdfNupConverterRequest() { - if (!connector_) - connector_ = content::GetSystemConnector()->Clone(); mojom::PdfNupConverterPtr pdf_nup_converter; - connector_->BindInterface(printing::mojom::kChromePrintingServiceName, - &pdf_nup_converter); + GetPrintingService()->BindPdfNupConverter( + mojo::MakeRequest(&pdf_nup_converter)); pdf_nup_converter->SetWebContentsURL(web_contents_->GetLastCommittedURL()); return pdf_nup_converter; } diff --git a/chromium/chrome/browser/printing/pdf_to_emf_converter.cc b/chromium/chrome/browser/printing/pdf_to_emf_converter.cc index a6f2dcbb563..962a023b0da 100644 --- a/chromium/chrome/browser/printing/pdf_to_emf_converter.cc +++ b/chromium/chrome/browser/printing/pdf_to_emf_converter.cc @@ -24,15 +24,13 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" -#include "chrome/services/printing/public/mojom/constants.mojom.h" +#include "chrome/browser/printing/printing_service.h" #include "chrome/services/printing/public/mojom/pdf_to_emf_converter.mojom.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" -#include "content/public/browser/system_connector.h" #include "mojo/public/cpp/bindings/binding.h" #include "printing/emf_win.h" #include "printing/pdf_render_settings.h" -#include "services/service_manager/public/cpp/connector.h" using content::BrowserThread; @@ -197,7 +195,7 @@ class PdfConverterImpl : public PdfConverter { mojom::PdfToEmfConverterFactoryPtr pdf_to_emf_converter_factory_; - base::WeakPtrFactory<PdfConverterImpl> weak_ptr_factory_; + base::WeakPtrFactory<PdfConverterImpl> weak_ptr_factory_{this}; static bool simulate_failure_initializing_conversion_; @@ -242,9 +240,7 @@ bool PostScriptMetaFile::SafePlayback(HDC hdc) const { PdfConverterImpl::PdfConverterImpl(scoped_refptr<base::RefCountedMemory> data, const PdfRenderSettings& settings, StartCallback start_callback) - : settings_(settings), - start_callback_(std::move(start_callback)), - weak_ptr_factory_(this) { + : settings_(settings), start_callback_(std::move(start_callback)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(start_callback_); @@ -272,9 +268,8 @@ void PdfConverterImpl::Initialize(scoped_refptr<base::RefCountedMemory> data) { memcpy(memory.mapping.memory(), data->front(), data->size()); - content::GetSystemConnector()->BindInterface( - printing::mojom::kChromePrintingServiceName, - &pdf_to_emf_converter_factory_); + GetPrintingService()->BindPdfToEmfConverterFactory( + mojo::MakeRequest(&pdf_to_emf_converter_factory_)); pdf_to_emf_converter_factory_.set_connection_error_handler(base::BindOnce( &PdfConverterImpl::OnFailed, weak_ptr_factory_.GetWeakPtr(), std::string("Connection to PdfToEmfConverterFactory error."))); diff --git a/chromium/chrome/browser/printing/print_dialog_cloud.cc b/chromium/chrome/browser/printing/print_dialog_cloud.cc index 363c7915aac..af444311aeb 100644 --- a/chromium/chrome/browser/printing/print_dialog_cloud.cc +++ b/chromium/chrome/browser/printing/print_dialog_cloud.cc @@ -14,7 +14,6 @@ #include "chrome/browser/ui/browser_window.h" #include "components/cloud_devices/common/cloud_devices_urls.h" #include "components/google/core/common/google_util.h" -#include "components/signin/core/browser/signin_header_helper.h" #include "components/signin/public/base/signin_metrics.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" @@ -71,7 +70,7 @@ void CreateCloudPrintSigninTab(Browser* browser, browser->window()->ShowAvatarBubbleFromAvatarButton( add_account ? BrowserWindow::AVATAR_BUBBLE_MODE_ADD_ACCOUNT : BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, - signin::ManageAccountsParams(), + signin_metrics::AccessPoint::ACCESS_POINT_CLOUD_PRINT, false); } else { GURL url = add_account ? cloud_devices::GetCloudPrintAddAccountURL() diff --git a/chromium/chrome/browser/printing/print_dialog_cloud_win.cc b/chromium/chrome/browser/printing/print_dialog_cloud_win.cc index 0880b837865..b77e8bc0cdb 100644 --- a/chromium/chrome/browser/printing/print_dialog_cloud_win.cc +++ b/chromium/chrome/browser/printing/print_dialog_cloud_win.cc @@ -130,8 +130,9 @@ void CreatePrintDialogForFile(content::BrowserContext* browser_context, const base::string16& print_ticket, const std::string& file_type) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFile, path_to_file), base::BindOnce(&CreatePrintDialog, browser_context, print_job_title, print_ticket, file_type)); diff --git a/chromium/chrome/browser/printing/print_error_dialog.cc b/chromium/chrome/browser/printing/print_error_dialog.cc index 66343db266e..1f95636f43a 100644 --- a/chromium/chrome/browser/printing/print_error_dialog.cc +++ b/chromium/chrome/browser/printing/print_error_dialog.cc @@ -28,6 +28,6 @@ void ShowPrintErrorDialogTask() { void ShowPrintErrorDialog() { // Nested loop may destroy caller. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ShowPrintErrorDialogTask)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ShowPrintErrorDialogTask)); } diff --git a/chromium/chrome/browser/printing/print_job.cc b/chromium/chrome/browser/printing/print_job.cc index b039a047907..c01d535bddb 100644 --- a/chromium/chrome/browser/printing/print_job.cc +++ b/chromium/chrome/browser/printing/print_job.cc @@ -61,21 +61,21 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query, DCHECK(!document_); worker_ = query->DetachWorker(); worker_->SetPrintJob(this); - const PrintSettings& settings = query->settings(); - - auto new_doc = - base::MakeRefCounted<PrintedDocument>(settings, name, query->cookie()); - new_doc->set_page_count(page_count); - UpdatePrintedDocument(new_doc); + std::unique_ptr<PrintSettings> settings = query->ExtractSettings(); #if defined(OS_WIN) - pdf_page_mapping_ = PageRange::GetPages(settings.ranges()); + pdf_page_mapping_ = PageRange::GetPages(settings->ranges()); if (pdf_page_mapping_.empty()) { for (int i = 0; i < page_count; i++) pdf_page_mapping_.push_back(i); } #endif + auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings), + name, query->cookie()); + new_doc->set_page_count(page_count); + UpdatePrintedDocument(new_doc); + // Don't forget to register to our own messages. registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(this)); @@ -219,8 +219,8 @@ bool PrintJob::FlushJob(base::TimeDelta timeout) { base::RunLoop loop(base::RunLoop::Type::kNestableTasksAllowed); quit_closure_ = loop.QuitClosure(); - base::PostDelayedTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - loop.QuitClosure(), timeout); + base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI}, + loop.QuitClosure(), timeout); loop.Run(); @@ -239,6 +239,22 @@ const PrintSettings& PrintJob::settings() const { return document()->settings(); } +#if defined(OS_CHROMEOS) +void PrintJob::SetSource(PrintJob::Source source, + const std::string& source_id) { + source_ = source; + source_id_ = source_id; +} + +PrintJob::Source PrintJob::source() const { + return source_; +} + +const std::string& PrintJob::source_id() const { + return source_id_; +} +#endif // defined(OS_CHROMEOS) + #if defined(OS_WIN) class PrintJob::PdfConversionState { public: @@ -451,8 +467,8 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) { } case JobEventDetails::DOC_DONE: { // This will call Stop() and broadcast a JOB_DONE message. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PrintJob::OnDocumentDone, this)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&PrintJob::OnDocumentDone, this)); break; } #if defined(OS_WIN) @@ -508,7 +524,7 @@ void PrintJob::ControlledWorkerShutdown() { // Delay shutdown until the worker terminates. We want this code path // to wait on the thread to quit before continuing. if (worker_->IsRunning()) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&PrintJob::ControlledWorkerShutdown, this), base::TimeDelta::FromMilliseconds(100)); @@ -518,9 +534,9 @@ void PrintJob::ControlledWorkerShutdown() { // Now make sure the thread object is cleaned up. Do this on a worker // thread because it may block. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::WithBaseSyncPrimitives(), + {base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PrintJobWorker::Stop, base::Unretained(worker_.get())), @@ -533,8 +549,8 @@ void PrintJob::ControlledWorkerShutdown() { bool PrintJob::PostTask(const base::Location& from_here, base::OnceClosure task) { - return base::PostTaskWithTraits(from_here, {content::BrowserThread::UI}, - std::move(task)); + return base::PostTask(from_here, {content::BrowserThread::UI}, + std::move(task)); } void PrintJob::HoldUntilStopIsCalled() { diff --git a/chromium/chrome/browser/printing/print_job.h b/chromium/chrome/browser/printing/print_job.h index b50220ddb73..15adc312478 100644 --- a/chromium/chrome/browser/printing/print_job.h +++ b/chromium/chrome/browser/printing/print_job.h @@ -44,8 +44,18 @@ class PrintSettings; class PrintJob : public base::RefCountedThreadSafe<PrintJob>, public content::NotificationObserver { public: +#if defined(OS_CHROMEOS) + // An enumeration of components where print jobs can come from. + enum class Source { + PRINT_PREVIEW, + ARC, + }; +#endif // defined(OS_CHROMEOS) + // Create a empty PrintJob. When initializing with this constructor, // post-constructor initialization must be done with Initialize(). + // If PrintJob is created on Chrome OS, call SetSource() to set which + // component initiated this print job. PrintJob(); // Grabs the ownership of the PrintJobWorker from a PrinterQuery along with @@ -106,6 +116,17 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob>, // Access stored settings. const PrintSettings& settings() const; +#if defined(OS_CHROMEOS) + // Sets the component which initiated the print job. + void SetSource(Source source, const std::string& source_id); + + // Returns the source of print job. + Source source() const; + + // Returns the ID of the source. + const std::string& source_id() const; +#endif // defined(OS_CHROMEOS) + // Posts the given task to be run. bool PostTask(const base::Location& from_here, base::OnceClosure task); @@ -196,6 +217,15 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob>, std::vector<int> pdf_page_mapping_; #endif // defined(OS_WIN) +#if defined(OS_CHROMEOS) + // The component which initiated the print job. + Source source_; + + // ID of the source. + // This should be blank if the source is PRINT_PREVIEW or ARC. + std::string source_id_; +#endif // defined(OS_CHROMEOS) + // Holds the quit closure while running a nested RunLoop to flush tasks. base::OnceClosure quit_closure_; diff --git a/chromium/chrome/browser/printing/print_job_unittest.cc b/chromium/chrome/browser/printing/print_job_unittest.cc index bd50607d5e0..56414e8ceb2 100644 --- a/chromium/chrome/browser/printing/print_job_unittest.cc +++ b/chromium/chrome/browser/printing/print_job_unittest.cc @@ -17,7 +17,7 @@ #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/common/child_process_host.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace printing { @@ -39,7 +39,7 @@ class TestQuery : public PrinterQuery { content::ChildProcessHost::kInvalidUniqueID) {} void GetSettingsDone(base::OnceClosure callback, - const PrintSettings& new_settings, + std::unique_ptr<PrintSettings> new_settings, PrintingContext::Result result) override { FAIL(); } @@ -57,16 +57,12 @@ class TestQuery : public PrinterQuery { auto worker = std::make_unique<TestPrintJobWorker>(); EXPECT_TRUE(worker->Start()); worker->printing_context()->UseDefaultSettings(); - settings_ = worker->printing_context()->settings(); + SetSettingsForTest(worker->printing_context()->TakeAndResetSettings()); return std::move(worker); } - const PrintSettings& settings() const override { return settings_; } - private: - PrintSettings settings_; - DISALLOW_COPY_AND_ASSIGN(TestQuery); }; @@ -95,7 +91,7 @@ TEST(PrintJobTest, SimplePrint) { // Test the multi-threaded nature of PrintJob to make sure we can use it with // known lifetime. - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; content::NotificationRegistrar registrar; TestPrintNotificationObserver observer; registrar.Add(&observer, content::NOTIFICATION_ALL, @@ -103,6 +99,9 @@ TEST(PrintJobTest, SimplePrint) { volatile bool check = false; scoped_refptr<PrintJob> job(new TestPrintJob(&check)); job->Initialize(std::make_unique<TestQuery>(), base::string16(), 1); +#if defined(OS_CHROMEOS) + job->SetSource(PrintJob::Source::PRINT_PREVIEW, /*source_id=*/""); +#endif // defined(OS_CHROMEOS) job->Stop(); while (job->document()) { base::RunLoop().RunUntilIdle(); @@ -117,7 +116,7 @@ TEST(PrintJobTest, SimplePrint) { TEST(PrintJobTest, SimplePrintLateInit) { volatile bool check = false; - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; scoped_refptr<PrintJob> job(new TestPrintJob(&check)); job = nullptr; EXPECT_TRUE(check); @@ -147,7 +146,7 @@ TEST(PrintJobTest, SimplePrintLateInit) { #if defined(OS_WIN) TEST(PrintJobTest, PageRangeMapping) { - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; int page_count = 4; std::vector<int> input_full = {0, 1, 2, 3}; diff --git a/chromium/chrome/browser/printing/print_job_worker.cc b/chromium/chrome/browser/printing/print_job_worker.cc index 63f432b5837..13f9d7af3ae 100644 --- a/chromium/chrome/browser/printing/print_job_worker.cc +++ b/chromium/chrome/browser/printing/print_job_worker.cc @@ -165,16 +165,15 @@ void PrintJobWorker::GetSettings(bool ask_user_for_settings, // When we delegate to a destination, we don't ask the user for settings. // TODO(mad): Ask the destination for settings. if (ask_user_for_settings) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PrintJobWorker::GetSettingsWithUI, base::Unretained(this), document_page_count, has_selection, is_scripted, std::move(callback))); } else { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PrintJobWorker::UseDefaultSettings, - base::Unretained(this), std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PrintJobWorker::UseDefaultSettings, + base::Unretained(this), std::move(callback))); } } @@ -182,11 +181,10 @@ void PrintJobWorker::SetSettings(base::Value new_settings, SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PrintJobWorker::UpdatePrintSettings, - base::Unretained(this), std::move(new_settings), - std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PrintJobWorker::UpdatePrintSettings, + base::Unretained(this), std::move(new_settings), + std::move(callback))); } #if defined(OS_CHROMEOS) @@ -195,11 +193,10 @@ void PrintJobWorker::SetSettingsFromPOD( SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD, - base::Unretained(this), std::move(new_settings), - std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD, + base::Unretained(this), std::move(new_settings), + std::move(callback))); } #endif @@ -224,7 +221,7 @@ void PrintJobWorker::UpdatePrintSettingsFromPOD( void PrintJobWorker::GetSettingsDone(SettingsCallback callback, PrintingContext::Result result) { - std::move(callback).Run(printing_context_->settings(), result); + std::move(callback).Run(printing_context_->TakeAndResetSettings(), result); } void PrintJobWorker::GetSettingsWithUI(int document_page_count, diff --git a/chromium/chrome/browser/printing/print_job_worker.h b/chromium/chrome/browser/printing/print_job_worker.h index d5711196e32..4b3557e5941 100644 --- a/chromium/chrome/browser/printing/print_job_worker.h +++ b/chromium/chrome/browser/printing/print_job_worker.h @@ -32,7 +32,8 @@ class PrintedPage; class PrintJobWorker { public: using SettingsCallback = - base::OnceCallback<void(const PrintSettings&, PrintingContext::Result)>; + base::OnceCallback<void(std::unique_ptr<PrintSettings>, + PrintingContext::Result)>; PrintJobWorker(int render_process_id, int render_frame_id); virtual ~PrintJobWorker(); diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc index d2a3be7590a..3dcc3aa7bea 100644 --- a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc +++ b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc @@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h" @@ -42,10 +43,14 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/web_dialogs/web_dialog_delegate.h" -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) #include "chrome/browser/win/conflicts/module_database.h" #endif +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/arc/print_spooler/print_session_impl.h" +#endif + using content::NavigationController; using content::WebContents; using content::WebUIMessageHandler; @@ -60,6 +65,17 @@ PrintPreviewUI* GetPrintPreviewUIForDialog(WebContents* dialog) { : nullptr; } +#if defined(OS_CHROMEOS) +void CloseArcPrintSession(WebContents* initiator) { + WebContents* outermost_web_contents = + guest_view::GuestViewBase::GetTopLevelWebContents(initiator); + auto* arc_print_session = + arc::PrintSessionImpl::FromWebContents(outermost_web_contents); + if (arc_print_session) + arc_print_session->OnPrintPreviewClosed(); +} +#endif + // A ui::WebDialogDelegate that specifies the print preview dialog appearance. class PrintPreviewDialogDelegate : public ui::WebDialogDelegate, public content::WebContentsObserver { @@ -241,7 +257,7 @@ PrintPreviewDialogController* PrintPreviewDialogController::GetInstance() { // static void PrintPreviewDialogController::PrintPreview(WebContents* initiator) { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) ModuleDatabase::GetInstance()->DisableThirdPartyBlocking(); #endif @@ -494,6 +510,10 @@ void PrintPreviewDialogController::RemoveInitiator( PrintViewManager::FromWebContents(initiator)->PrintPreviewDone(); +#if defined(OS_CHROMEOS) + CloseArcPrintSession(initiator); +#endif + // Initiator is closed. Close the print preview dialog too. auto* print_preview_ui = GetPrintPreviewUIForDialog(preview_dialog); if (print_preview_ui) @@ -507,6 +527,10 @@ void PrintPreviewDialogController::RemovePreviewDialog( if (initiator) { RemoveObserver(initiator); PrintViewManager::FromWebContents(initiator)->PrintPreviewDone(); + +#if defined(OS_CHROMEOS) + CloseArcPrintSession(initiator); +#endif } preview_dialog_map_.erase(preview_dialog); diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc index 77354643bdf..03083c800de 100644 --- a/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc +++ b/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc @@ -146,8 +146,8 @@ void CheckPdfPluginForRenderFrame(content::RenderFrameHost* frame) { ChromePluginServiceFilter* filter = ChromePluginServiceFilter::GetInstance(); EXPECT_TRUE(filter->IsPluginAvailable( - frame->GetProcess()->GetID(), frame->GetRoutingID(), nullptr, - GURL(kDummyPrintUrl), url::Origin(), &pdf_plugin_info)); + frame->GetProcess()->GetID(), frame->GetRoutingID(), GURL(kDummyPrintUrl), + url::Origin(), &pdf_plugin_info)); } } // namespace @@ -308,8 +308,7 @@ IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, content::WebPluginInfo dummy_pdf_plugin_info = pdf_plugin_info; EXPECT_FALSE(filter->IsPluginAvailable( initiator()->GetMainFrame()->GetProcess()->GetID(), - initiator()->GetMainFrame()->GetRoutingID(), - browser()->profile()->GetResourceContext(), GURL(), + initiator()->GetMainFrame()->GetRoutingID(), GURL(), url::Origin::Create(GURL("http://google.com")), &dummy_pdf_plugin_info)); PrintPreview(); diff --git a/chromium/chrome/browser/printing/print_preview_message_handler.cc b/chromium/chrome/browser/printing/print_preview_message_handler.cc index 5fd2ea6af9f..e18eeb6a3b7 100644 --- a/chromium/chrome/browser/printing/print_preview_message_handler.cc +++ b/chromium/chrome/browser/printing/print_preview_message_handler.cc @@ -51,7 +51,7 @@ void StopWorker(int document_cookie) { std::unique_ptr<PrinterQuery> printer_query = queue->PopPrinterQuery(document_cookie); if (printer_query) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); } diff --git a/chromium/chrome/browser/printing/print_view_manager_base.cc b/chromium/chrome/browser/printing/print_view_manager_base.cc index c4e0992f626..da3383624ff 100644 --- a/chromium/chrome/browser/printing/print_view_manager_base.cc +++ b/chromium/chrome/browser/printing/print_view_manager_base.cc @@ -79,7 +79,7 @@ void OnPrintSettingsDoneWrapper(PrintSettingsCallback settings_callback, std::unique_ptr<PrinterQuery> query) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(settings_callback), std::move(query))); } @@ -143,7 +143,7 @@ void PrintViewManagerBase::PrintForPrintPreview( weak_ptr_factory_.GetWeakPtr(), print_data, job_settings.FindIntKey(kSettingPreviewPageCount).value(), std::move(callback)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(CreateQueryWithSettings, std::move(job_settings), rfh->GetProcess()->GetID(), rfh->GetRoutingID(), queue_, @@ -184,17 +184,16 @@ void PrintViewManagerBase::OnPrintSettingsDone( if (printer_query->last_status() == PrintingContext::CANCEL) { queue_->QueuePrinterQuery(std::move(printer_query)); #if defined(OS_WIN) - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PrintViewManagerBase::SystemDialogCancelled, - weak_ptr_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&PrintViewManagerBase::SystemDialogCancelled, + weak_ptr_factory_.GetWeakPtr())); #endif std::move(callback).Run(base::Value()); return; } if (!printer_query->cookie() || !printer_query->settings().dpi()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); std::move(callback).Run(base::Value("Update settings failed")); @@ -205,11 +204,10 @@ void PrintViewManagerBase::OnPrintSettingsDone( // OnDidGetPrintedPagesCount(). int cookie = printer_query->cookie(); queue_->QueuePrinterQuery(std::move(printer_query)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob, - weak_ptr_factory_.GetWeakPtr(), print_data, page_count, - cookie, std::move(callback))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob, + weak_ptr_factory_.GetWeakPtr(), print_data, + page_count, cookie, std::move(callback))); } void PrintViewManagerBase::StartLocalPrintJob( @@ -281,6 +279,7 @@ void PrintViewManagerBase::OnComposePdfDone( const gfx::Size& page_size, const gfx::Rect& content_area, const gfx::Point& physical_offsets, + std::unique_ptr<DelayedFrameDispatchHelper> helper, mojom::PdfCompositor::Status status, base::ReadOnlySharedMemoryRegion region) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -298,11 +297,13 @@ void PrintViewManagerBase::OnComposePdfDone( return; PrintDocument(data, page_size, content_area, physical_offsets); + helper->SendCompleted(); } void PrintViewManagerBase::OnDidPrintDocument( content::RenderFrameHost* render_frame_host, - const PrintHostMsg_DidPrintDocument_Params& params) { + const PrintHostMsg_DidPrintDocument_Params& params, + std::unique_ptr<DelayedFrameDispatchHelper> helper) { if (!PrintJobHasDocument(params.document_cookie)) return; @@ -319,7 +320,8 @@ void PrintViewManagerBase::OnDidPrintDocument( params.document_cookie, render_frame_host, content, base::BindOnce(&PrintViewManagerBase::OnComposePdfDone, weak_ptr_factory_.GetWeakPtr(), params.page_size, - params.content_area, params.physical_offsets)); + params.content_area, params.physical_offsets, + std::move(helper))); return; } auto data = base::RefCountedSharedMemoryMapping::CreateFromWholeRegion( @@ -332,6 +334,13 @@ void PrintViewManagerBase::OnDidPrintDocument( PrintDocument(data, params.page_size, params.content_area, params.physical_offsets); + helper->SendCompleted(); +} + +void PrintViewManagerBase::OnGetDefaultPrintSettings( + content::RenderFrameHost* render_frame_host, + IPC::Message* reply_msg) { + NOTREACHED() << "should be handled by printing::PrintingMessageFilter"; } void PrintViewManagerBase::OnPrintingFailed(int cookie) { @@ -349,6 +358,13 @@ void PrintViewManagerBase::OnPrintingFailed(int cookie) { content::NotificationService::NoDetails()); } +void PrintViewManagerBase::OnScriptedPrint( + content::RenderFrameHost* render_frame_host, + const PrintHostMsg_ScriptedPrint_Params& params, + IPC::Message* reply_msg) { + NOTREACHED() << "should be handled by printing:: PrintingMessageFilter"; +} + void PrintViewManagerBase::OnShowInvalidPrinterSettingsError() { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ShowWarningMessageBox, @@ -401,15 +417,6 @@ bool PrintViewManagerBase::OnMessageReceived( const IPC::Message& message, content::RenderFrameHost* render_frame_host) { bool handled = true; - IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(PrintViewManagerBase, message, - render_frame_host) - IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintDocument, OnDidPrintDocument) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - if (handled) - return true; - - handled = true; IPC_BEGIN_MESSAGE_MAP(PrintViewManagerBase, message) IPC_MESSAGE_HANDLER(PrintHostMsg_ShowInvalidPrinterSettingsError, OnShowInvalidPrinterSettingsError) @@ -547,6 +554,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( DCHECK(!print_job_); print_job_ = base::MakeRefCounted<PrintJob>(); print_job_->Initialize(std::move(query), RenderSourceName(), number_pages_); +#if defined(OS_CHROMEOS) + print_job_->SetSource(PrintJob::Source::PRINT_PREVIEW, /*source_id=*/""); +#endif // defined(OS_CHROMEOS) + registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(print_job_.get())); printing_succeeded_ = false; @@ -700,7 +711,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() { std::unique_ptr<PrinterQuery> printer_query = queue_->PopPrinterQuery(cookie); if (!printer_query) return; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); } diff --git a/chromium/chrome/browser/printing/print_view_manager_base.h b/chromium/chrome/browser/printing/print_view_manager_base.h index 925736d379c..9dc22fa933e 100644 --- a/chromium/chrome/browser/printing/print_view_manager_base.h +++ b/chromium/chrome/browser/printing/print_view_manager_base.h @@ -22,16 +22,10 @@ #include "content/public/browser/notification_registrar.h" #include "printing/buildflags/buildflags.h" -struct PrintHostMsg_DidPrintDocument_Params; - namespace base { class RefCountedMemory; } -namespace content { -class RenderFrameHost; -} - namespace printing { class JobEventDetails; @@ -72,6 +66,10 @@ class PrintViewManagerBase : public content::NotificationObserver, base::string16 RenderSourceName(); + content::RenderFrameHost* GetPrintingRFHForTesting() const { + return printing_rfh_; + } + protected: explicit PrintViewManagerBase(content::WebContents* web_contents); @@ -92,6 +90,10 @@ class PrintViewManagerBase : public content::NotificationObserver, // impossible to create a new print job. virtual bool CreateNewPrintJob(std::unique_ptr<PrinterQuery> query); + // Makes sure the current print_job_ has all its data before continuing, and + // disconnect from it. + void DisconnectFromCurrentPrintJob(); + // Manages the low-level talk to the printer. scoped_refptr<PrintJob> print_job_; @@ -107,17 +109,26 @@ class PrintViewManagerBase : public content::NotificationObserver, // Cancels the print job. void NavigationStopped() override; - // IPC Message handlers. + // printing::PrintManager: void OnDidGetPrintedPagesCount(int cookie, int number_pages) override; + void OnDidPrintDocument( + content::RenderFrameHost* render_frame_host, + const PrintHostMsg_DidPrintDocument_Params& params, + std::unique_ptr<DelayedFrameDispatchHelper> helper) override; + void OnGetDefaultPrintSettings(content::RenderFrameHost* render_frame_host, + IPC::Message* reply_msg) override; void OnPrintingFailed(int cookie) override; + void OnScriptedPrint(content::RenderFrameHost* render_frame_host, + const PrintHostMsg_ScriptedPrint_Params& params, + IPC::Message* reply_msg) override; + void OnShowInvalidPrinterSettingsError(); - void OnDidPrintDocument(content::RenderFrameHost* render_frame_host, - const PrintHostMsg_DidPrintDocument_Params& params); // IPC message handlers for service. void OnComposePdfDone(const gfx::Size& page_size, const gfx::Rect& content_area, const gfx::Point& physical_offsets, + std::unique_ptr<DelayedFrameDispatchHelper> helper, mojom::PdfCompositor::Status status, base::ReadOnlySharedMemoryRegion region); @@ -160,10 +171,6 @@ class PrintViewManagerBase : public content::NotificationObserver, // RenderAllMissingPagesNow(). void ShouldQuitFromInnerMessageLoop(); - // Makes sure the current print_job_ has all its data before continuing, and - // disconnect from it. - void DisconnectFromCurrentPrintJob(); - // Terminates the print job. No-op if no print job has been created. If // |cancel| is true, cancel it instead of waiting for the job to finish. Will // call ReleasePrintJob(). diff --git a/chromium/chrome/browser/printing/print_view_manager_basic.cc b/chromium/chrome/browser/printing/print_view_manager_basic.cc index 326396cf119..8ef4e820498 100644 --- a/chromium/chrome/browser/printing/print_view_manager_basic.cc +++ b/chromium/chrome/browser/printing/print_view_manager_basic.cc @@ -17,11 +17,18 @@ PrintViewManagerBasic::PrintViewManagerBasic(content::WebContents* web_contents) : PrintViewManagerBase(web_contents) { #if defined(OS_ANDROID) pdf_writing_done_callback_ = - base::Bind(&PrintingContextAndroid::PdfWritingDone); + base::BindRepeating(&PrintingContextAndroid::PdfWritingDone); #endif } -PrintViewManagerBasic::~PrintViewManagerBasic() = default; +PrintViewManagerBasic::~PrintViewManagerBasic() { +#if defined(OS_ANDROID) + // Must do this call here and not let ~PrintViewManagerBase do it as + // TerminatePrintJob() calls PdfWritingDone() and if that is done from + // ~PrintViewManagerBase then a pure virtual call is done. + DisconnectFromCurrentPrintJob(); +#endif +} #if defined(OS_ANDROID) void PrintViewManagerBasic::PdfWritingDone(int page_count) { diff --git a/chromium/chrome/browser/printing/print_view_manager_basic_unittest.cc b/chromium/chrome/browser/printing/print_view_manager_basic_unittest.cc new file mode 100644 index 00000000000..2d90b8df7bd --- /dev/null +++ b/chromium/chrome/browser/printing/print_view_manager_basic_unittest.cc @@ -0,0 +1,70 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/printing/print_view_manager_basic.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/browser/printing/print_job_manager.h" +#include "chrome/browser/printing/print_test_utils.h" +#include "chrome/browser/printing/printer_query.h" +#include "chrome/browser/printing/printing_init.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "components/printing/common/print_messages.h" +#include "content/public/browser/render_process_host.h" + +namespace printing { + +class PrintViewManagerBasicTest : public ChromeRenderViewHostTestHarness { + protected: + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); + InitializePrinting(web_contents()); + content::RenderFrameHostTester::For(main_rfh()) + ->InitializeRenderFrameIfNeeded(); + } +}; + +TEST_F(PrintViewManagerBasicTest, PrintSubFrameAndDestroy) { + auto* sub_frame = + content::RenderFrameHostTester::For(main_rfh())->AppendChild("child"); + ASSERT_TRUE(sub_frame); + + auto* print_view_manager = + PrintViewManagerBasic::FromWebContents(web_contents()); + ASSERT_TRUE(print_view_manager); + EXPECT_FALSE(print_view_manager->GetPrintingRFHForTesting()); + + print_view_manager->PrintNow(sub_frame); + EXPECT_TRUE(print_view_manager->GetPrintingRFHForTesting()); + + content::RenderFrameHostTester::For(sub_frame)->Detach(); + EXPECT_FALSE(print_view_manager->GetPrintingRFHForTesting()); +} + +TEST_F(PrintViewManagerBasicTest, CancelJobDuringDestruction) { + auto* print_view_manager = + PrintViewManagerBasic::FromWebContents(web_contents()); + ASSERT_TRUE(print_view_manager); + + ASSERT_TRUE(print_view_manager->PrintNow(main_rfh())); + + // Setup enough of a PrinterQuery to make GetPrintedPagesCount work + auto queue = g_browser_process->print_job_manager()->queue(); + auto query = queue->CreatePrinterQuery(main_rfh()->GetProcess()->GetID(), + main_rfh()->GetRoutingID()); + base::RunLoop runloop; + query->SetSettings(GetPrintTicket(printing::kLocalPrinter, false), + runloop.QuitClosure()); + runloop.Run(); + auto cookie = query->cookie(); + queue->QueuePrinterQuery(std::move(query)); + + // Fake GetPrintedPagesCount message to cause print_job to be created + content::RenderFrameHostTester::TestOnMessageReceived( + main_rfh(), PrintHostMsg_DidGetPrintedPagesCount(0, cookie, 1)); + + DeleteContents(); +} + +} // namespace printing diff --git a/chromium/chrome/browser/printing/print_view_manager_common.cc b/chromium/chrome/browser/printing/print_view_manager_common.cc index 11ac8569ee7..449b31c33c3 100644 --- a/chromium/chrome/browser/printing/print_view_manager_common.cc +++ b/chromium/chrome/browser/printing/print_view_manager_common.cc @@ -38,21 +38,6 @@ bool StoreFullPagePlugin(content::WebContents** result, } #endif // BUILDFLAG(ENABLE_EXTENSIONS) -// If we have a single full-page embedded mime handler view guest, print the -// guest's WebContents instead. -content::WebContents* GetWebContentsToUse(content::WebContents* contents) { -#if BUILDFLAG(ENABLE_EXTENSIONS) - guest_view::GuestViewManager* guest_view_manager = - guest_view::GuestViewManager::FromBrowserContext( - contents->GetBrowserContext()); - if (guest_view_manager) { - guest_view_manager->ForEachGuest( - contents, base::BindRepeating(&StoreFullPagePlugin, &contents)); - } -#endif // BUILDFLAG(ENABLE_EXTENSIONS) - return contents; -} - // Pick the right RenderFrameHost based on the WebContentses. content::RenderFrameHost* GetRenderFrameHostToUse( content::WebContents* original_contents, @@ -118,4 +103,17 @@ content::RenderFrameHost* GetFrameToPrint(content::WebContents* contents) { : contents->GetMainFrame(); } +content::WebContents* GetWebContentsToUse(content::WebContents* contents) { +#if BUILDFLAG(ENABLE_EXTENSIONS) + guest_view::GuestViewManager* guest_view_manager = + guest_view::GuestViewManager::FromBrowserContext( + contents->GetBrowserContext()); + if (guest_view_manager) { + guest_view_manager->ForEachGuest( + contents, base::BindRepeating(&StoreFullPagePlugin, &contents)); + } +#endif // BUILDFLAG(ENABLE_EXTENSIONS) + return contents; +} + } // namespace printing diff --git a/chromium/chrome/browser/printing/print_view_manager_common.h b/chromium/chrome/browser/printing/print_view_manager_common.h index 16b4373214d..b3c34616c73 100644 --- a/chromium/chrome/browser/printing/print_view_manager_common.h +++ b/chromium/chrome/browser/printing/print_view_manager_common.h @@ -26,6 +26,10 @@ void StartBasicPrint(content::WebContents* contents); // frame (this makes print selection work for multiple frames). content::RenderFrameHost* GetFrameToPrint(content::WebContents* contents); +// If we have a single full-page embedded mime handler view guest, print the +// guest's WebContents instead. +content::WebContents* GetWebContentsToUse(content::WebContents* contents); + } // namespace printing #endif // CHROME_BROWSER_PRINTING_PRINT_VIEW_MANAGER_COMMON_H_ diff --git a/chromium/chrome/browser/printing/print_view_manager_unittest.cc b/chromium/chrome/browser/printing/print_view_manager_unittest.cc index 89e5c28f2c8..18f1bea8802 100644 --- a/chromium/chrome/browser/printing/print_view_manager_unittest.cc +++ b/chromium/chrome/browser/printing/print_view_manager_unittest.cc @@ -77,6 +77,9 @@ class TestPrintViewManager : public PrintViewManagerBase { bool CreateNewPrintJob(std::unique_ptr<PrinterQuery> query) override { print_job_ = base::MakeRefCounted<TestPrintJob>(); print_job_->Initialize(std::move(query), RenderSourceName(), number_pages_); +#if defined(OS_CHROMEOS) + print_job_->SetSource(PrintJob::Source::PRINT_PREVIEW, /*source_id=*/""); +#endif // defined(OS_CHROMEOS) return true; } diff --git a/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc b/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc index 672a6c5cc4f..f236c055c16 100644 --- a/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc +++ b/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc @@ -88,8 +88,9 @@ void DetectAndOpenPrinterConfigDialog() { namespace printing { void PrinterManagerDialog::ShowPrinterManagerDialog(Profile* profile) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&DetectAndOpenPrinterConfigDialog)); } diff --git a/chromium/chrome/browser/printing/printer_manager_dialog_win.cc b/chromium/chrome/browser/printing/printer_manager_dialog_win.cc index 3bb3253522e..a6a4e9c1800 100644 --- a/chromium/chrome/browser/printing/printer_manager_dialog_win.cc +++ b/chromium/chrome/browser/printing/printer_manager_dialog_win.cc @@ -39,9 +39,10 @@ void PrinterManagerDialog::ShowPrinterManagerDialog(Profile* profile) { if (base::win::GetVersion() >= base::win::Version::WIN10_RS1) { platform_util::OpenExternal(profile, GURL("ms-settings:printers")); } else { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, - base::BindOnce(OpenPrintersDialogCallback)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING}, + base::BindOnce(OpenPrintersDialogCallback)); } } diff --git a/chromium/chrome/browser/printing/printer_query.cc b/chromium/chrome/browser/printing/printer_query.cc index 6bd6dd72b58..db7ee262b81 100644 --- a/chromium/chrome/browser/printing/printer_query.cc +++ b/chromium/chrome/browser/printing/printer_query.cc @@ -37,13 +37,13 @@ PrinterQuery::~PrinterQuery() { } void PrinterQuery::GetSettingsDone(base::OnceClosure callback, - const PrintSettings& new_settings, + std::unique_ptr<PrintSettings> new_settings, PrintingContext::Result result) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); is_print_dialog_box_shown_ = false; last_status_ = result; if (result != PrintingContext::FAILED) { - settings_ = new_settings; + settings_ = std::move(new_settings); cookie_ = PrintSettings::NewCookie(); } else { // Failure. @@ -53,14 +53,15 @@ void PrinterQuery::GetSettingsDone(base::OnceClosure callback, std::move(callback).Run(); } -void PrinterQuery::PostSettingsDoneToIO(base::OnceClosure callback, - const PrintSettings& new_settings, - PrintingContext::Result result) { +void PrinterQuery::PostSettingsDoneToIO( + base::OnceClosure callback, + std::unique_ptr<PrintSettings> new_settings, + PrintingContext::Result result) { // |this| is owned by |callback|, so |base::Unretained()| is safe. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::GetSettingsDone, base::Unretained(this), - std::move(callback), new_settings, result)); + std::move(callback), std::move(new_settings), result)); } std::unique_ptr<PrintJobWorker> PrinterQuery::DetachWorker() { @@ -71,7 +72,15 @@ std::unique_ptr<PrintJobWorker> PrinterQuery::DetachWorker() { } const PrintSettings& PrinterQuery::settings() const { - return settings_; + return *settings_; +} + +std::unique_ptr<PrintSettings> PrinterQuery::ExtractSettings() { + return std::move(settings_); +} + +void PrinterQuery::SetSettingsForTest(std::unique_ptr<PrintSettings> settings) { + settings_ = std::move(settings); } int PrinterQuery::cookie() const { @@ -161,8 +170,8 @@ void PrinterQuery::StopWorker() { bool PrinterQuery::PostTask(const base::Location& from_here, base::OnceClosure task) { - return base::PostTaskWithTraits(from_here, {content::BrowserThread::IO}, - std::move(task)); + return base::PostTask(from_here, {content::BrowserThread::IO}, + std::move(task)); } bool PrinterQuery::is_valid() const { diff --git a/chromium/chrome/browser/printing/printer_query.h b/chromium/chrome/browser/printing/printer_query.h index 03047d9a425..00cf15c8b8d 100644 --- a/chromium/chrome/browser/printing/printer_query.h +++ b/chromium/chrome/browser/printing/printer_query.h @@ -41,8 +41,9 @@ class PrinterQuery { // TODO(thestig): Do |worker_| and |callback_| need locks? virtual std::unique_ptr<PrintJobWorker> DetachWorker(); - // Virtual so that tests can override. - virtual const PrintSettings& settings() const; + const PrintSettings& settings() const; + + std::unique_ptr<PrintSettings> ExtractSettings(); // Initializes the printing context. It is fine to call this function multiple // times to reinitialize the settings. |web_contents_observer| can be queried @@ -84,19 +85,21 @@ class PrinterQuery { protected: // Virtual so that tests can override. virtual void GetSettingsDone(base::OnceClosure callback, - const PrintSettings& new_settings, + std::unique_ptr<PrintSettings> new_settings, PrintingContext::Result result); void PostSettingsDoneToIO(base::OnceClosure callback, - const PrintSettings& new_settings, + std::unique_ptr<PrintSettings> new_settings, PrintingContext::Result result); + void SetSettingsForTest(std::unique_ptr<PrintSettings> settings); + private: // Lazy create the worker thread. There is one worker thread per print job. void StartWorker(); // Cache of the print context settings for access in the UI thread. - PrintSettings settings_; + std::unique_ptr<PrintSettings> settings_; // Is the Print... dialog box currently shown. bool is_print_dialog_box_shown_ = false; diff --git a/chromium/chrome/browser/printing/printing_message_filter.cc b/chromium/chrome/browser/printing/printing_message_filter.cc index 706617b7924..40762a36024 100644 --- a/chromium/chrome/browser/printing/printing_message_filter.cc +++ b/chromium/chrome/browser/printing/printing_message_filter.cc @@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/memory/singleton.h" #include "base/task/post_task.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job_manager.h" @@ -31,7 +32,7 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #endif -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) #include "chrome/browser/win/conflicts/module_database.h" #endif @@ -102,7 +103,7 @@ PrintingMessageFilter::PrintingMessageFilter(int render_process_id, base::Unretained(this))); is_printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); is_printing_enabled_.MoveToSequence( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); + base::CreateSingleThreadTaskRunner({BrowserThread::IO})); } PrintingMessageFilter::~PrintingMessageFilter() { @@ -184,7 +185,7 @@ void PrintingMessageFilter::OnGetDefaultPrintSettingsReply( void PrintingMessageFilter::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, IPC::Message* reply_msg) { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) ModuleDatabase::GetInstance()->DisableThirdPartyBlocking(); #endif @@ -269,7 +270,7 @@ void PrintingMessageFilter::OnUpdatePrintSettingsReply( #if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW) if (canceled) { int routing_id = reply_msg->routing_id(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PrintingMessageFilter::NotifySystemDialogCancelled, this, routing_id)); diff --git a/chromium/chrome/browser/printing/printing_service.cc b/chromium/chrome/browser/printing/printing_service.cc new file mode 100644 index 00000000000..9b0f43d94ac --- /dev/null +++ b/chromium/chrome/browser/printing/printing_service.cc @@ -0,0 +1,32 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/printing/printing_service.h" + +#include "base/no_destructor.h" +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/service_process_host.h" + +const mojo::Remote<printing::mojom::PrintingService>& GetPrintingService() { + static base::NoDestructor<mojo::Remote<printing::mojom::PrintingService>> + remote; + if (!*remote) { + content::ServiceProcessHost::Launch( + remote->BindNewPipeAndPassReceiver(), + content::ServiceProcessHost::Options() + .WithDisplayName(IDS_UTILITY_PROCESS_PRINTING_SERVICE_NAME) + .WithSandboxType(service_manager::SANDBOX_TYPE_UTILITY) + .Pass()); + + // Ensure that if the interface is ever disconnected (e.g. the service + // process crashes) or goes idle for a short period of time -- meaning there + // are no in-flight messages and no other interfaces bound through this + // one -- then we will reset |remote|, causing the service process to be + // terminated if it isn't already. + remote->reset_on_disconnect(); + remote->reset_on_idle_timeout(base::TimeDelta::FromSeconds(5)); + } + + return *remote; +} diff --git a/chromium/chrome/browser/printing/printing_service.h b/chromium/chrome/browser/printing/printing_service.h new file mode 100644 index 00000000000..59529e75940 --- /dev/null +++ b/chromium/chrome/browser/printing/printing_service.h @@ -0,0 +1,15 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_PRINTING_PRINTING_SERVICE_H_ +#define CHROME_BROWSER_PRINTING_PRINTING_SERVICE_H_ + +#include "chrome/services/printing/public/mojom/printing_service.mojom.h" +#include "mojo/public/cpp/bindings/remote.h" + +// Acquires a remote handle to the sandboxed Printing Service +// instance, launching a process to host the service if necessary. +const mojo::Remote<printing::mojom::PrintingService>& GetPrintingService(); + +#endif // CHROME_BROWSER_PRINTING_PRINTING_SERVICE_H_ diff --git a/chromium/chrome/browser/printing/pwg_raster_converter.cc b/chromium/chrome/browser/printing/pwg_raster_converter.cc index 5a505349612..bf25bc4540e 100644 --- a/chromium/chrome/browser/printing/pwg_raster_converter.cc +++ b/chromium/chrome/browser/printing/pwg_raster_converter.cc @@ -14,18 +14,16 @@ #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" -#include "chrome/services/printing/public/mojom/constants.mojom.h" +#include "chrome/browser/printing/printing_service.h" #include "chrome/services/printing/public/mojom/pdf_to_pwg_raster_converter.mojom.h" #include "components/cloud_devices/common/cloud_device_description.h" #include "components/cloud_devices/common/printer_description.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" -#include "content/public/browser/system_connector.h" #include "mojo/public/cpp/system/platform_handle.h" #include "printing/pdf_render_settings.h" #include "printing/pwg_raster_settings.h" #include "printing/units.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" @@ -80,10 +78,8 @@ void PwgRasterConverterHelper::Convert( callback_ = std::move(callback); - content::GetSystemConnector()->BindInterface( - printing::mojom::kChromePrintingServiceName, - &pdf_to_pwg_raster_converter_ptr_); - + GetPrintingService()->BindPdfToPwgRasterConverter( + mojo::MakeRequest(&pdf_to_pwg_raster_converter_ptr_)); pdf_to_pwg_raster_converter_ptr_.set_connection_error_handler( base::BindOnce(&PwgRasterConverterHelper::RunCallback, this, base::ReadOnlySharedMemoryRegion(), /*page_count=*/0)); diff --git a/chromium/chrome/browser/printing/test_print_job.cc b/chromium/chrome/browser/printing/test_print_job.cc index 29bd1a4aa2f..ccf0dc10570 100644 --- a/chromium/chrome/browser/printing/test_print_job.cc +++ b/chromium/chrome/browser/printing/test_print_job.cc @@ -24,7 +24,7 @@ void TestPrintJob::Initialize(std::unique_ptr<PrinterQuery> query, std::unique_ptr<PrintJobWorker> worker = query->DetachWorker(); scoped_refptr<PrintedDocument> new_doc = - base::MakeRefCounted<PrintedDocument>(query->settings(), name, + base::MakeRefCounted<PrintedDocument>(query->ExtractSettings(), name, query->cookie()); new_doc->set_page_count(page_count); diff --git a/chromium/chrome/browser/printing/test_printer_query.cc b/chromium/chrome/browser/printing/test_printer_query.cc index 8049255aa3f..b1e6d24d7e8 100644 --- a/chromium/chrome/browser/printing/test_printer_query.cc +++ b/chromium/chrome/browser/printing/test_printer_query.cc @@ -52,27 +52,27 @@ void TestPrinterQuery::SetSettings(base::Value new_settings, #if defined(OS_WIN) DCHECK(printer_type_); #endif - PrintSettings settings; + auto settings = std::make_unique<PrintSettings>(); PrintingContext::Result result = - PrintSettingsFromJobSettings(new_settings, &settings) + PrintSettingsFromJobSettings(new_settings, settings.get()) ? PrintingContext::OK : PrintingContext::FAILED; float device_microns_per_device_unit = - static_cast<float>(kMicronsPerInch) / settings.device_units_per_inch(); + static_cast<float>(kMicronsPerInch) / settings->device_units_per_inch(); gfx::Size paper_size = - gfx::Size(settings.requested_media().size_microns.width() / + gfx::Size(settings->requested_media().size_microns.width() / device_microns_per_device_unit, - settings.requested_media().size_microns.height() / + settings->requested_media().size_microns.height() / device_microns_per_device_unit); gfx::Rect paper_rect(0, 0, paper_size.width(), paper_size.height()); paper_rect.Inset(offsets_->x(), offsets_->y()); - settings.SetPrinterPrintableArea(paper_size, paper_rect, true); + settings->SetPrinterPrintableArea(paper_size, paper_rect, true); #if defined(OS_WIN) - settings.set_printer_type(*printer_type_); + settings->set_printer_type(*printer_type_); #endif - GetSettingsDone(std::move(callback), settings, result); + GetSettingsDone(std::move(callback), std::move(settings), result); } #if defined(OS_WIN) diff --git a/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc b/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc index bb5a147e496..712e0a74b95 100644 --- a/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc +++ b/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc @@ -76,9 +76,8 @@ bool DeviceIDFetcher::Start(const IDCallback& callback) { in_progress_ = true; callback_ = callback; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DeviceIDFetcher::CheckPrefsOnUIThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DeviceIDFetcher::CheckPrefsOnUIThread, this)); return true; } @@ -125,10 +124,11 @@ void DeviceIDFetcher::CheckPrefsOnUIThread() { #if defined(OS_CHROMEOS) // Try the legacy path first for ChromeOS. We pass the new salt in as well // in case the legacy id doesn't exist. - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(&DeviceIDFetcher::LegacyComputeAsync, - this, profile->GetPath(), salt)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&DeviceIDFetcher::LegacyComputeAsync, this, + profile->GetPath(), salt)); #else // Get the machine ID and call ComputeOnUIThread with salt + machine_id. GetMachineIDAsync( @@ -191,20 +191,18 @@ void DeviceIDFetcher::LegacyComputeAsync(const base::FilePath& profile_path, } // If we didn't find an ID, get the machine ID and call the new code path to // generate an ID. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &GetMachineIDAsync, - base::Bind(&DeviceIDFetcher::ComputeOnUIThread, this, salt))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&GetMachineIDAsync, + base::Bind(&DeviceIDFetcher::ComputeOnUIThread, + this, salt))); } void DeviceIDFetcher::RunCallbackOnIOThread(const std::string& id, int32_t result) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&DeviceIDFetcher::RunCallbackOnIOThread, this, id, - result)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&DeviceIDFetcher::RunCallbackOnIOThread, this, + id, result)); return; } in_progress_ = false; diff --git a/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm b/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm index 087cba25a27..41f0611dbc2 100644 --- a/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm +++ b/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm @@ -30,9 +30,8 @@ int64_t MonitorFinder::GetMonitor() { request_sent_ = true; } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this)); return display_id_; } diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc index 83cedb4c9e1..37245c48cac 100644 --- a/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc +++ b/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc @@ -37,7 +37,7 @@ PepperBrokerMessageFilter::~PepperBrokerMessageFilter() {} scoped_refptr<base::TaskRunner> PepperBrokerMessageFilter::OverrideTaskRunnerForMessage( const IPC::Message& message) { - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); } int32_t PepperBrokerMessageFilter::OnResourceMessageReceived( diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc index 9d28e920676..91c1562d989 100644 --- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc +++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc @@ -135,7 +135,7 @@ int32_t PepperFlashBrowserHost::OnGetLocalDataRestrictions( plugin_url, cookie_settings_); } else { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::Bind(&GetCookieSettings, render_process_id_), base::Bind(&PepperFlashBrowserHost::GetLocalDataRestrictions, @@ -180,8 +180,6 @@ device::mojom::WakeLock* PepperFlashBrowserHost::GetWakeLock() { if (wake_lock_) return wake_lock_.get(); - device::mojom::WakeLockRequest request = mojo::MakeRequest(&wake_lock_); - // The system Connector might be not initialized in some testing environments. if (!content::GetSystemConnector()) return wake_lock_.get(); @@ -192,16 +190,16 @@ device::mojom::WakeLock* PepperFlashBrowserHost::GetWakeLock() { // The existing connector is bound to the UI thread, the current thread is // IO thread. So bind the ConnectorRequest of IO thread to the connector // in UI thread. - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PepperBindConnectorRequest, - std::move(connector_request))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PepperBindConnectorRequest, + std::move(connector_request))); - device::mojom::WakeLockProviderPtr wake_lock_provider; - connector->BindInterface(device::mojom::kServiceName, - mojo::MakeRequest(&wake_lock_provider)); + mojo::Remote<device::mojom::WakeLockProvider> wake_lock_provider; + connector->Connect(device::mojom::kServiceName, + wake_lock_provider.BindNewPipeAndPassReceiver()); wake_lock_provider->GetWakeLockWithoutContext( device::mojom::WakeLockType::kPreventDisplaySleep, device::mojom::WakeLockReason::kOther, "Requested By PepperFlash", - std::move(request)); + wake_lock_.BindNewPipeAndPassReceiver()); return wake_lock_.get(); } diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h index f2f40b636a4..6b13bae8def 100644 --- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h +++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h @@ -11,6 +11,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" +#include "mojo/public/cpp/bindings/remote.h" #include "ppapi/host/host_message_context.h" #include "ppapi/host/resource_host.h" #include "services/device/public/mojom/wake_lock.mojom.h" @@ -62,7 +63,7 @@ class PepperFlashBrowserHost : public ppapi::host::ResourceHost { // Requests a wake lock to prevent going to sleep, and a timer to cancel it // after a certain amount of time has elapsed without an UpdateActivity. - device::mojom::WakeLockPtr wake_lock_; + mojo::Remote<device::mojom::WakeLock> wake_lock_; base::DelayTimer delay_timer_; // For fetching the Flash LSO settings. diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc index da447131553..8a57873a375 100644 --- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc +++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc @@ -29,15 +29,15 @@ namespace { const size_t kMaxClipboardWriteSize = 1000000; -ui::ClipboardType ConvertClipboardType(uint32_t type) { +ui::ClipboardBuffer ConvertClipboardType(uint32_t type) { switch (type) { case PP_FLASH_CLIPBOARD_TYPE_STANDARD: - return ui::ClipboardType::kCopyPaste; + return ui::ClipboardBuffer::kCopyPaste; case PP_FLASH_CLIPBOARD_TYPE_SELECTION: - return ui::ClipboardType::kSelection; + return ui::ClipboardBuffer::kSelection; } NOTREACHED(); - return ui::ClipboardType::kCopyPaste; + return ui::ClipboardBuffer::kCopyPaste; } // Functions to pack/unpack custom data from a pickle. See the header file for @@ -106,16 +106,16 @@ PepperFlashClipboardMessageFilter::OverrideTaskRunnerForMessage( // restrictions of various platform APIs. In general, the clipboard is not // thread-safe, so all clipboard calls should be serviced from the UI thread. if (msg.type() == PpapiHostMsg_FlashClipboard_WriteData::ID) - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); // Windows needs clipboard reads to be serviced from the IO thread because // these are sync IPCs which can result in deadlocks with plugins if serviced // from the UI thread. Note that Windows clipboard calls ARE thread-safe so it // is ok for reads and writes to be serviced from different threads. #if !defined(OS_WIN) - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); #else - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + return base::CreateSingleThreadTaskRunner({BrowserThread::IO}); #endif } @@ -159,24 +159,24 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgIsFormatAvailable( } ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); - ui::ClipboardType type = ConvertClipboardType(clipboard_type); + ui::ClipboardBuffer clipboard_buffer = ConvertClipboardType(clipboard_type); bool available = false; switch (format) { case PP_FLASH_CLIPBOARD_FORMAT_PLAINTEXT: { bool plain = clipboard->IsFormatAvailable( - ui::ClipboardFormatType::GetPlainTextType(), type); + ui::ClipboardFormatType::GetPlainTextType(), clipboard_buffer); bool plainw = clipboard->IsFormatAvailable( - ui::ClipboardFormatType::GetPlainTextWType(), type); + ui::ClipboardFormatType::GetPlainTextWType(), clipboard_buffer); available = plain || plainw; break; } case PP_FLASH_CLIPBOARD_FORMAT_HTML: available = clipboard->IsFormatAvailable( - ui::ClipboardFormatType::GetHtmlType(), type); + ui::ClipboardFormatType::GetHtmlType(), clipboard_buffer); break; case PP_FLASH_CLIPBOARD_FORMAT_RTF: available = clipboard->IsFormatAvailable( - ui::ClipboardFormatType::GetRtfType(), type); + ui::ClipboardFormatType::GetRtfType(), clipboard_buffer); break; case PP_FLASH_CLIPBOARD_FORMAT_INVALID: break; @@ -206,15 +206,15 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgReadData( } ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); - ui::ClipboardType type = ConvertClipboardType(clipboard_type); + ui::ClipboardBuffer clipboard_buffer = ConvertClipboardType(clipboard_type); std::string clipboard_string; int32_t result = PP_ERROR_FAILED; switch (format) { case PP_FLASH_CLIPBOARD_FORMAT_PLAINTEXT: { if (clipboard->IsFormatAvailable( - ui::ClipboardFormatType::GetPlainTextWType(), type)) { + ui::ClipboardFormatType::GetPlainTextWType(), clipboard_buffer)) { base::string16 text; - clipboard->ReadText(type, &text); + clipboard->ReadText(clipboard_buffer, &text); if (!text.empty()) { result = PP_OK; clipboard_string = base::UTF16ToUTF8(text); @@ -224,15 +224,15 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgReadData( // If the PlainTextW format isn't available or is empty, take the // ASCII text format. if (clipboard->IsFormatAvailable( - ui::ClipboardFormatType::GetPlainTextType(), type)) { + ui::ClipboardFormatType::GetPlainTextType(), clipboard_buffer)) { result = PP_OK; - clipboard->ReadAsciiText(type, &clipboard_string); + clipboard->ReadAsciiText(clipboard_buffer, &clipboard_string); } break; } case PP_FLASH_CLIPBOARD_FORMAT_HTML: { if (!clipboard->IsFormatAvailable(ui::ClipboardFormatType::GetHtmlType(), - type)) { + clipboard_buffer)) { break; } @@ -240,7 +240,8 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgReadData( std::string url; uint32_t fragment_start; uint32_t fragment_end; - clipboard->ReadHTML(type, &html, &url, &fragment_start, &fragment_end); + clipboard->ReadHTML(clipboard_buffer, &html, &url, &fragment_start, + &fragment_end); result = PP_OK; clipboard_string = base::UTF16ToUTF8( html.substr(fragment_start, fragment_end - fragment_start)); @@ -248,11 +249,11 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgReadData( } case PP_FLASH_CLIPBOARD_FORMAT_RTF: { if (!clipboard->IsFormatAvailable(ui::ClipboardFormatType::GetRtfType(), - type)) { + clipboard_buffer)) { break; } result = PP_OK; - clipboard->ReadRTF(type, &clipboard_string); + clipboard->ReadRTF(clipboard_buffer, &clipboard_string); break; } case PP_FLASH_CLIPBOARD_FORMAT_INVALID: @@ -294,14 +295,14 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgWriteData( return PP_ERROR_FAILED; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); - ui::ClipboardType type = ConvertClipboardType(clipboard_type); + ui::ClipboardBuffer clipboard_buffer = ConvertClipboardType(clipboard_type); // If no formats are passed in clear the clipboard. if (formats.empty()) { - clipboard->Clear(type); + clipboard->Clear(clipboard_buffer); return PP_OK; } - ui::ScopedClipboardWriter scw(type); + ui::ScopedClipboardWriter scw(clipboard_buffer); std::map<base::string16, std::string> custom_data_map; int32_t res = PP_OK; for (uint32_t i = 0; i < formats.size(); ++i) { @@ -362,8 +363,8 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgGetSequenceNumber( } ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); - ui::ClipboardType type = ConvertClipboardType(clipboard_type); - int64_t sequence_number = clipboard->GetSequenceNumber(type); + ui::ClipboardBuffer clipboard_buffer = ConvertClipboardType(clipboard_type); + int64_t sequence_number = clipboard->GetSequenceNumber(clipboard_buffer); host_context->reply_msg = PpapiPluginMsg_FlashClipboard_GetSequenceNumberReply(sequence_number); return PP_OK; diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc index 0a727e8c438..2e51425cb66 100644 --- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc +++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc @@ -61,7 +61,7 @@ class MonitorFinder : public base::RefCountedThreadSafe<MonitorFinder> { // do this because we don't know how often our client is going // to call and we can't cache the |monitor_| value. if (InterlockedCompareExchange(&request_sent_, 1, 0) == 0) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this)); } diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc index 0d083bb09ff..00db4e2fa2a 100644 --- a/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc +++ b/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc @@ -81,8 +81,7 @@ PepperIsolatedFileSystemMessageFilter::OverrideTaskRunnerForMessage( const IPC::Message& msg) { // In order to reach ExtensionSystem, we need to get ProfileManager first. // ProfileManager lives in UI thread, so we need to do this in UI thread. - return base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}); } int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived( diff --git a/chromium/chrome/browser/resource_coordinator/tab_ranker/BUILD.gn b/chromium/chrome/browser/resource_coordinator/tab_ranker/BUILD.gn index 2c9c59937ca..23125cc476e 100644 --- a/chromium/chrome/browser/resource_coordinator/tab_ranker/BUILD.gn +++ b/chromium/chrome/browser/resource_coordinator/tab_ranker/BUILD.gn @@ -14,6 +14,8 @@ source_set("tab_ranker") { sources = [ "native_inference.cc", "native_inference.h", + "pairwise_inference.cc", + "pairwise_inference.h", "tab_features.cc", "tab_score_predictor.cc", "window_features.cc", diff --git a/chromium/chrome/browser/resources/BUILD.gn b/chromium/chrome/browser/resources/BUILD.gn index 5f26c76da3c..d1b6a8b7b45 100644 --- a/chromium/chrome/browser/resources/BUILD.gn +++ b/chromium/chrome/browser/resources/BUILD.gn @@ -12,6 +12,7 @@ if (closure_compile) { deps = [ "engagement:closure_compile", "interventions_internals:closure_compile", + "reset_password:closure_compile", ] if (is_linux || is_win || is_mac) { deps += [ @@ -30,6 +31,7 @@ if (closure_compile) { "quota_internals:closure_compile", "settings:closure_compile", "signin/sync_confirmation:closure_compile", + "usb_internals:closure_compile", "user_manager:closure_compile", "welcome:closure_compile", ] @@ -40,6 +42,9 @@ if (closure_compile) { if (enable_extensions) { deps += [ "extensions:closure_compile" ] } + if (enable_webui_tab_strip) { + deps += [ "tab_strip:closure_compile" ] + } if (is_android) { deps += [ "explore_sites_internals:closure_compile", @@ -49,9 +54,6 @@ if (closure_compile) { "webapks:closure_compile", ] } - if (!is_android) { - deps += [ "app_management:closure_compile" ] - } if (is_win || is_mac || is_desktop_linux) { deps += [ "browser_switch:closure_compile" ] } @@ -219,15 +221,15 @@ if (is_chromeos) { } if (!is_android && !is_chromeos) { - grit("onboarding_welcome_resources") { - source = "welcome/onboarding_welcome_resources.grd" + grit("welcome_resources") { + source = "welcome/welcome_resources.grd" defines = chrome_grit_defines outputs = [ - "grit/onboarding_welcome_resources.h", - "grit/onboarding_welcome_resources_map.cc", - "grit/onboarding_welcome_resources_map.h", - "onboarding_welcome_resources.pak", + "grit/welcome_resources.h", + "grit/welcome_resources_map.cc", + "grit/welcome_resources_map.h", + "welcome_resources.pak", ] output_dir = "$root_gen_dir/chrome" } @@ -303,3 +305,25 @@ if (enable_print_preview) { output_dir = "$root_gen_dir/chrome" } } + +if (enable_webui_tab_strip) { + grit("tab_strip_resources") { + source = "tab_strip/tab_strip_resources.grd" + defines = chrome_grit_defines + deps = [ + "tab_strip:tab_strip_modules", + ] + source_is_generated = true + outputs = [ + "grit/tab_strip_resources.h", + "grit/tab_strip_resources_map.cc", + "grit/tab_strip_resources_map.h", + "tab_strip_resources.pak", + ] + output_dir = "$root_gen_dir/chrome" + grit_flags = [ + "-E", + "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir), + ] + } +} diff --git a/chromium/chrome/browser/resources/app_management/BUILD.gn b/chromium/chrome/browser/resources/app_management/BUILD.gn index d52e422fd0e..05147eec84f 100644 --- a/chromium/chrome/browser/resources/app_management/BUILD.gn +++ b/chromium/chrome/browser/resources/app_management/BUILD.gn @@ -256,6 +256,7 @@ if (!is_android) { js_library("toggle_row") { deps = [ ":types", + "//ui/webui/resources/cr_elements/cr_toggle:cr_toggle", ] } diff --git a/chromium/chrome/browser/resources/app_management/OWNERS b/chromium/chrome/browser/resources/app_management/OWNERS index 54640cb9d84..94b2e07d850 100644 --- a/chromium/chrome/browser/resources/app_management/OWNERS +++ b/chromium/chrome/browser/resources/app_management/OWNERS @@ -1,5 +1,4 @@ -calamity@chromium.org dominickn@chromium.org -ericwilligers@chromium.org +jshikaram@chromium.org -# COMPONENT: Platform>Apps>Foundation
\ No newline at end of file +# COMPONENT: Platform>Apps>Foundation diff --git a/chromium/chrome/browser/resources/app_management/actions.html b/chromium/chrome/browser/resources/app_management/actions.html deleted file mode 100644 index ad1570cd227..00000000000 --- a/chromium/chrome/browser/resources/app_management/actions.html +++ /dev/null @@ -1,2 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<script src="actions.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/actions.js b/chromium/chrome/browser/resources/app_management/actions.js deleted file mode 100644 index 24cdddee569..00000000000 --- a/chromium/chrome/browser/resources/app_management/actions.js +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Module for functions which produce action objects. These are - * listed in one place to document available actions and their parameters. - */ - -cr.define('app_management.actions', function() { - /** - * @param {App} app - */ - function addApp(app) { - return { - name: 'add-app', - app: app, - }; - } - - /** - * @param {App} app - */ - function changeApp(app) { - return { - name: 'change-app', - app: app, - }; - } - - /** - * @param {string} id - */ - function removeApp(id) { - return { - name: 'remove-app', - id: id, - }; - } - - /** - * @param {PageType} pageType - * @param {string=} id - */ - function changePage(pageType, id) { - if (pageType === PageType.DETAIL && !id) { - console.warn( - 'Tried to load app detail page without providing an app id.'); - } - - return { - name: 'change-page', - pageType: pageType, - id: id, - }; - } - - /** @return {!cr.ui.Action} */ - function clearSearch() { - return { - name: 'clear-search', - }; - } - - /** - * @param {string} term - * @return {!cr.ui.Action} - */ - function setSearchTerm(term) { - if (!term) { - return clearSearch(); - } - return { - name: 'start-search', - term: term, - }; - } - - /** - * @param {boolean} isSupported - * @return {!cr.ui.Action} - */ - function updateArcSupported(isSupported) { - return { - name: 'update-arc-supported', - value: isSupported, - }; - } - - - return { - addApp: addApp, - changeApp: changeApp, - removeApp: removeApp, - changePage: changePage, - clearSearch: clearSearch, - setSearchTerm: setSearchTerm, - updateArcSupported: updateArcSupported, - }; -}); diff --git a/chromium/chrome/browser/resources/app_management/api_listener.html b/chromium/chrome/browser/resources/app_management/api_listener.html deleted file mode 100644 index 751d6c4e553..00000000000 --- a/chromium/chrome/browser/resources/app_management/api_listener.html +++ /dev/null @@ -1,5 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<link rel="import" href="actions.html"> -<link rel="import" href="store.html"> -<link rel="import" href="util.html"> -<script src="api_listener.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/api_listener.js b/chromium/chrome/browser/resources/app_management/api_listener.js deleted file mode 100644 index 617e94b83c6..00000000000 --- a/chromium/chrome/browser/resources/app_management/api_listener.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -cr.define('app_management.apiListener', function() { - let initialized = false; - - async function init() { - assert(!initialized); - - const {apps: initialApps} = - await app_management.BrowserProxy.getInstance().handler.getApps(); - const initialState = app_management.util.createInitialState(initialApps); - app_management.Store.getInstance().init(initialState); - - const callbackRouter = - app_management.BrowserProxy.getInstance().callbackRouter; - - callbackRouter.onAppAdded.addListener(onAppAdded); - callbackRouter.onAppChanged.addListener(onAppChanged); - callbackRouter.onAppRemoved.addListener(onAppRemoved); - callbackRouter.onArcSupportChanged.addListener(onArcSupportChanged); - - initialized = true; - } - - /** - * @param {cr.ui.Action} action - */ - function dispatch(action) { - app_management.Store.getInstance().dispatch(action); - } - - /** - * @param {App} app - */ - function onAppAdded(app) { - dispatch(app_management.actions.addApp(app)); - } - - /** - * @param {App} app - */ - function onAppChanged(app) { - dispatch(app_management.actions.changeApp(app)); - } - - /** - * @param {string} appId - */ - function onAppRemoved(appId) { - dispatch(app_management.actions.removeApp(appId)); - } - - /** - * @param {boolean} isSupported - */ - function onArcSupportChanged(isSupported) { - dispatch(app_management.actions.updateArcSupported(isSupported)); - } - - init(); - - return {}; -}); diff --git a/chromium/chrome/browser/resources/app_management/app_item.html b/chromium/chrome/browser/resources/app_management/app_item.html deleted file mode 100644 index b7a7576080d..00000000000 --- a/chromium/chrome/browser/resources/app_management/app_item.html +++ /dev/null @@ -1,41 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="actions.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="shared_vars.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> - -<dom-module id="app-management-app-item"> - <template> - <style include="app-management-shared-css cr-icons"> - :host { - align-items: center; - border-top: var(--card-separator); - color: var(--primary-text-color); - cursor: pointer; - display: flex; - flex-direction: row; - font-weight: 400; - height: 64px; - } - - #app-title { - flex: 1; - overflow: hidden; - text-overflow: ellipsis; - } - - #app-icon { - height: 32px; - margin-inline-end: 20px; - margin-inline-start: 24px; - width: 32px; - } - </style> - <img id="app-icon" src="[[iconUrlFromId_(app)]]"> - <div id="app-title">[[app.title]]</div> - <slot name="right-content"></slot> - </template> - <script src="app_item.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/app_item.js b/chromium/chrome/browser/resources/app_management/app_item.js deleted file mode 100644 index aaceae573f1..00000000000 --- a/chromium/chrome/browser/resources/app_management/app_item.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-app-item', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** @type {App} */ - app: { - type: Object, - }, - }, - - listeners: { - 'click': 'onClick_', - }, - - /** - * @private - */ - onClick_: function() { - this.dispatch( - app_management.actions.changePage(PageType.DETAIL, this.app.id)); - }, - - /** - * @param {App} app - * @return {string} - * @private - */ - iconUrlFromId_: function(app) { - return app_management.util.getAppIcon(app); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/arc_permission_view.html b/chromium/chrome/browser/resources/app_management/arc_permission_view.html deleted file mode 100644 index 1ffb3a6b0cb..00000000000 --- a/chromium/chrome/browser/resources/app_management/arc_permission_view.html +++ /dev/null @@ -1,82 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="browser_proxy.html"> -<link rel="import" href="icons.html"> -<link rel="import" href="metadata_view.html"> -<link rel="import" href="permission_item.html"> -<link rel="import" href="permission_view_header.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="pin_to_shelf_item.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> -<link rel="import" href="chrome://resources/cr_elements/icons.html"> - -<dom-module id="app-management-arc-permission-view"> - <template> - <style include="app-management-shared-css"> - </style> - - <app-management-permission-view-header> - </app-management-permission-view-header> - - <div class="permission-list card-container"> - <app-management-pin-to-shelf-item - id="pin-to-shelf-setting" - class="permission-card-row separated-row header-text" - app_="[[app_]]"> - </app-management-pin-to-shelf-item> - <app-management-permission-item id="notifications-card" - class="permission-card-row separated-row header-text" - permission-label="$i18n{notifications}" permission-type="NOTIFICATIONS" - hidden$="[[!isArcSupported_]]"> - </app-management-permission-item> - <div id="permissions-card" - class="permission-card-row" - hidden$="[[!isArcSupported_]]"> - <div class="subpermission-list"> - <div id="subpermission-expand-row" - class="subpermission-row separated-row" - hidden$="[[!isArcSupported_]]"> - <div class="header-text">$i18n{permissions}</div> - </div> - <app-management-permission-item class="subpermission-row" - icon="cr:location-on" - permission-label="$i18n{location}" - permission-type="LOCATION"> - </app-management-permission-item> - <app-management-permission-item class="subpermission-row" - icon="cr:videocam" - permission-label="$i18n{camera}" - permission-type="CAMERA"> - </app-management-permission-item> - <app-management-permission-item class="subpermission-row" - icon="cr:mic" - permission-label="$i18n{microphone}" - permission-type="MICROPHONE"> - </app-management-permission-item> - <app-management-permission-item class="subpermission-row" - icon="app-management:contacts" - permission-label="$i18n{contacts}" - permission-type="CONTACTS"> - </app-management-permission-item> - <app-management-permission-item class="subpermission-row" - icon="app-management:storage" - permission-label="$i18n{storage}" - permission-type="STORAGE"> - </app-management-permission-item> - </div> - </div> - <div id="more-settings" - class="permission-card-row separated-row header-text clickable" - on-click="onClickNativeSettingsButton_"> - <div class="header-text">$i18n{moreSettings}</div> - <div class="permission-row-controls"> - <cr-icon-button class="native-settings-icon icon-external" - tabindex="0"> - </cr-icon-button> - </div> - </div> - </div> - </template> - <script src="arc_permission_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/arc_permission_view.js b/chromium/chrome/browser/resources/app_management/arc_permission_view.js deleted file mode 100644 index 0242a758b5c..00000000000 --- a/chromium/chrome/browser/resources/app_management/arc_permission_view.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-arc-permission-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * @private {App} - */ - app_: Object, - - /** - * @private {boolean} - */ - listExpanded_: { - type: Boolean, - value: false, - }, - - /** - * @private {boolean} - */ - isArcSupported_: { - type: Boolean, - } - }, - - attached: function() { - this.watch('app_', state => app_management.util.getSelectedApp(state)); - this.watch('isArcSupported_', state => state.arcSupported); - this.updateFromStore(); - - this.listExpanded_ = false; - }, - - onClickNativeSettingsButton_: function() { - app_management.BrowserProxy.getInstance().handler.openNativeSettings( - this.app_.id); - }, - - /** - * @private - */ - toggleListExpanded_: function() { - this.listExpanded_ = !this.listExpanded_; - }, - - /** - * @param {App} app - * @return {string} - * @private - */ - iconUrlFromId_: function(app) { - return app_management.util.getAppIcon(app); - }, - - /** - * @param {boolean} listExpanded - * @return {string} - * @private - */ - getCollapsedIcon_: function(listExpanded) { - return listExpanded ? 'cr:expand-less' : 'cr:expand-more'; - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/browser_proxy.html b/chromium/chrome/browser/resources/app_management/browser_proxy.html deleted file mode 100644 index e66afd27a8a..00000000000 --- a/chromium/chrome/browser/resources/app_management/browser_proxy.html +++ /dev/null @@ -1,13 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<link rel="import" href="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.html"> -<link rel="import" href="chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom.html"> -<link rel="import" href="chrome://resources/mojo/mojo/public/mojom/base/time.mojom.html"> - -<script src="image_info.mojom-lite.js"></script> -<script src="bitmap.mojom-lite.js"></script> -<script src="image.mojom-lite.js"></script> -<script src="types.mojom-lite.js"></script> -<script src="app_management.mojom-lite.js"></script> - -<script src="browser_proxy.js"></script> -<script src="fake_page_handler.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/browser_proxy.js b/chromium/chrome/browser/resources/app_management/browser_proxy.js deleted file mode 100644 index f824557fc9c..00000000000 --- a/chromium/chrome/browser/resources/app_management/browser_proxy.js +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('app_management', function() { - class BrowserProxy { - constructor() { - /** @type {appManagement.mojom.PageCallbackRouter} */ - this.callbackRouter = new appManagement.mojom.PageCallbackRouter(); - - /** @type {appManagement.mojom.PageHandlerRemote} */ - this.handler = null; - - const urlParams = new URLSearchParams(window.location.search); - const arcSupported = urlParams.get('arcSupported'); - const useFake = urlParams.get('fakeBackend'); - - if (useFake) { - if (arcSupported) { - loadTimeData.overrideValues({ - 'isSupportedArcVersion': arcSupported.toLowerCase() === 'true', - }); - } else { - loadTimeData.overrideValues({ - 'isSupportedArcVersion': true, - }); - } - - this.fakeHandler = new app_management.FakePageHandler( - this.callbackRouter.$.bindNewPipeAndPassRemote()); - this.handler = this.fakeHandler.getRemote(); - - const permissionOptions = {}; - permissionOptions[PwaPermissionType.CONTENT_SETTINGS_TYPE_GEOLOCATION] = - { - permissionValue: TriState.kAllow, - isManaged: true, - }; - permissionOptions[PwaPermissionType - .CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA] = { - permissionValue: TriState.kBlock, - isManaged: true - }; - - const /** @type {!Array<App>}*/ appList = [ - app_management.FakePageHandler.createApp( - 'blpcfgokakmgnkcojhhkbfblekacnbeo', - { - title: 'Built in app, not implemented', - type: AppType.kBuiltIn, - installSource: InstallSource.kSystem, - }, - ), - app_management.FakePageHandler.createApp( - 'aohghmighlieiainnegkcijnfilokake', - { - title: 'Arc app', - type: AppType.kArc, - installSource: InstallSource.kUser, - }, - ), - app_management.FakePageHandler.createApp( - 'blpcfgokakmgnkcojhhkbfbldkacnbeo', - { - title: 'Crostini app, not implemented', - type: AppType.kCrostini, - installSource: InstallSource.kUser, - }, - ), - app_management.FakePageHandler.createApp( - 'pjkljhegncpnkkknowihdijeoejaedia', - { - title: 'Chrome App', - type: AppType.kExtension, - description: - 'A Chrome App installed from the Chrome Web Store.', - }, - ), - app_management.FakePageHandler.createApp( - 'aapocclcdoekwnckovdopfmtonfmgok', - { - title: 'Web App', - type: AppType.kWeb, - }, - ), - app_management.FakePageHandler.createApp( - 'pjkljhegncpnkkknbcohdijeoejaedia', - { - title: 'Chrome App, OEM installed', - type: AppType.kExtension, - description: 'A Chrome App installed by an OEM.', - installSource: InstallSource.kOem, - }, - ), - app_management.FakePageHandler.createApp( - 'aapocclcgogkmnckokdopfmhonfmgok', - { - title: 'Web App, policy applied', - type: AppType.kWeb, - isPinned: apps.mojom.OptionalBool.kTrue, - isPolicyPinned: apps.mojom.OptionalBool.kTrue, - installSource: apps.mojom.InstallSource.kPolicy, - permissions: - app_management.FakePageHandler.createWebPermissions( - permissionOptions), - }, - ), - ]; - - this.fakeHandler.setApps(appList); - - } else { - this.handler = new appManagement.mojom.PageHandlerRemote(); - const factory = appManagement.mojom.PageHandlerFactory.getRemote(); - factory.createPageHandler( - this.callbackRouter.$.bindNewPipeAndPassRemote(), - this.handler.$.bindNewPipeAndPassReceiver()); - } - } - } - - cr.addSingletonGetter(BrowserProxy); - - return {BrowserProxy: BrowserProxy}; -}); diff --git a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html b/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html deleted file mode 100644 index 64b890ff985..00000000000 --- a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html +++ /dev/null @@ -1,92 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="util.html"> -<link rel="import" href="pin_to_shelf_item.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> - -<dom-module id="app-management-chrome-app-permission-view"> - <template> - <style include="app-management-shared-css"> - ul { - list-style: disc inside; - margin: 0; - margin-inline-start: 24px; - padding: 0; - } - - #app-description { - padding: 24px; - } - - #no-permissions { - padding-inline-start: 24px; - } - - #pin-to-shelf-setting { - border-top: var(--card-separator); - } - - </style> - <app-management-permission-view-header> - </app-management-permission-view-header> - <div class="card-container"> - <div id="app-description" class="permission-card-row secondary-text"> - [[app_.description]] - </div> - <div class="permission-list"> - <app-management-pin-to-shelf-item - id="pin-to-shelf-setting" - class="permission-card-row separated-row header-text" - app_="[[app_]]"> - </app-management-pin-to-shelf-item> - - <div id="permissions-card" class="permission-card-row"> - <div class="subpermission-list"> - <div class="subpermission-row separated-row"> - <div class="header-text">$i18n{thisAppCan}</div> - </div> - <template is="dom-if" if="[[!hasPermissions_(messages_)]]"> - <div id="no-permissions"> - $i18n{appNoPermission} - </div> - </template> - <ul> - <template is="dom-repeat" - items="[[getPermissionMessages_(messages_)]]" as="message"> - <li>[[message]]</li> - <ul> - <template is="dom-repeat" - items="[[getPermissionSubmessagesByMessage_(index, messages_)]]" - as="submessage"> - <li>[[submessage]]</li> - </template> - </ul> - </template> - </ul> - <!-- TODO(crbug.com/906508): For apps which are hosted apps but not - bookmark apps, this button will actually open the site settings page - corresponding to the app, since hosted apps are not listed in - chrome://extensions. - This is not a long-term problem since hosted apps are being - replaced, but in the mean time it might be necessary to change the - text of the button depending on whether or not it is a hosted - app. --> - <!-- TODO:(crbug.com/958269) Change behaviour of "more settings" - based on the app. --> - <div id="more-settings" - class="subpermission-row separated-row clickable" - on-click="onClickExtensionsSettingsButton_" - hidden$="[[app_.hideMoreSettings]]"> - <div class="header-text">$i18n{moreSettings}</div> - <cr-icon-button class="native-settings-icon icon-external" - tabindex="0"> - </cr-icon-button> - </div> - </div> - </div> - </div> - </template> - <script src="chrome_app_permission_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js b/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js deleted file mode 100644 index f697f55754e..00000000000 --- a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-chrome-app-permission-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * @private {App} - */ - app_: { - type: Object, - observer: 'onAppChanged_', - }, - - /** - * @private {Array<ExtensionAppPermissionMessage>} - */ - messages_: Object, - }, - - attached: function() { - this.watch('app_', state => app_management.util.getSelectedApp(state)); - this.updateFromStore(); - }, - - /** - * @private - */ - onAppChanged_: async function() { - const {messages: messages} = - await app_management.BrowserProxy.getInstance() - .handler.getExtensionAppPermissionMessages(this.app_.id); - this.$['app-description'].hidden = this.app_.description.length === 0; - this.messages_ = messages; - }, - - onClickExtensionsSettingsButton_: function() { - app_management.BrowserProxy.getInstance().handler.openNativeSettings( - this.app_.id); - }, - - /** - * @param {!Array<ExtensionAppPermissionMessage>} messages - * @return {Array<string>} - * @private - */ - getPermissionMessages_: function(messages) { - return messages.map(m => m.message); - }, - - /** - * @param {number} index - * @param {!Array<ExtensionAppPermissionMessage>} messages - * @return {?Array<string>} - * @private - */ - getPermissionSubmessagesByMessage_: function(index, messages) { - // Dom-repeat still tries to access messages[0] when app has no - // permission therefore we add an extra check. - if (!messages[index]) { - return null; - } - return messages[index].submessages; - }, - - /** - * @param {!Array<ExtensionAppPermissionMessage>} messages - * @return {boolean} - * @private - */ - hasPermissions_: function(messages) { - return messages.length > 0; - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/constants.html b/chromium/chrome/browser/resources/app_management/constants.html deleted file mode 100644 index 2b6bc6b93e9..00000000000 --- a/chromium/chrome/browser/resources/app_management/constants.html +++ /dev/null @@ -1 +0,0 @@ -<script src="constants.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/constants.js b/chromium/chrome/browser/resources/app_management/constants.js deleted file mode 100644 index a3ca5777e9e..00000000000 --- a/chromium/chrome/browser/resources/app_management/constants.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * The number of apps displayed in app list in the main view before expanding. - * @const {number} - */ -const NUMBER_OF_APPS_DISPLAYED_DEFAULT = 4; - -/** - * The maximum number of apps' titles previewed in notification sublabel. - * @const {number} - */ -const APP_LIST_PREVIEW_APP_TITLES = 3; - -/** - * Enumeration of the different subpage types within the app management page. - * @enum {number} - * @const - */ -const PageType = { - MAIN: 0, - DETAIL: 1, - NOTIFICATIONS: 2, -}; - -/** - * A number representation of a Bool. Permission values should be of this type - * for permissions with value type PermissionValueType.kBool. - * @enum {number} - * @const - */ -const Bool = { - kFalse: 0, - kTrue: 1, -}; - -const PwaPermissionType = appManagement.mojom.PwaPermissionType; - -const ArcPermissionType = appManagement.mojom.ArcPermissionType; - -const AppType = apps.mojom.AppType; - -const PermissionValueType = apps.mojom.PermissionValueType; - -const TriState = apps.mojom.TriState; - -const OptionalBool = apps.mojom.OptionalBool; - -const InstallSource = apps.mojom.InstallSource; diff --git a/chromium/chrome/browser/resources/app_management/dom_switch.html b/chromium/chrome/browser/resources/app_management/dom_switch.html deleted file mode 100644 index 23af2ec0fbc..00000000000 --- a/chromium/chrome/browser/resources/app_management/dom_switch.html +++ /dev/null @@ -1,8 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<dom-module id="app-management-dom-switch"> - <template> - <slot></slot> - </template> - <script src="dom_switch.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/dom_switch.js b/chromium/chrome/browser/resources/app_management/dom_switch.js deleted file mode 100644 index b5117bf76ce..00000000000 --- a/chromium/chrome/browser/resources/app_management/dom_switch.js +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview - * app-management-dom-switch is used to select one element to be displayed at a - * time from a group of elements. When an element is selected, it is attached - * to the DOM. When another element is selected, the first element is - * detached, meaning only one of the elements is attached at a time. - * - * The elements are selected by giving them each a route-id attribute, then - * setting the route property of the dom-switch equal to the route-id of the - * element to be shown. - * - * Data binding from the parent element of the dom-switch to its child - * elements works as usual. - * - * Usage: - * <parent-element> - * <app-management-dom-switch id="view-selector"> - * <template> - * <view-one route-id="view-one" title="[[parentProperty]]"></view-one> - * <view-two route-id="view-two"></view-two> - * <view-three route-id="view-three"></view-three> - * </template> - * </app-management-dom-switch> - * </parent-element> - * - * this.$['view-selector'].route = 'view-two'; - */ - -Polymer({ - is: 'app-management-dom-switch', - - behaviors: [Polymer.Templatizer], - - properties: { - /** - * Should contain the route-id of one of the elements within the dom-switch. - * @private {?string} - */ - route: { - type: String, - observer: 'onRouteChanged_', - }, - - /** - * The template instance. - * @private {?Element} - */ - instance_: { - type: Object, - value: null, - }, - - /** - * Maps the route-id of each element within the dom-switch to the element - * itself. - * @private {Object<string, Element>} - */ - children_: { - type: Object, - value: () => ({}), - }, - - /** - * The element whose route-id corresponds to the current route. This is the - * only element within the dom-switch which is attached to the DOM. - * @private {?Element} - */ - selectedChild_: { - type: Object, - value: null, - }, - }, - - firstRenderForTesting_: new PromiseResolver(), - - attached: function() { - const template = this.getContentChildren()[0]; - this.templatize(template); - - // This call stamps all the child elements of the dom-switch at once - // (calling their created Polymer lifecycle callbacks). If optimisations - // are required in the future, it may be possible to only stamp children - // on demand as they are rendered. - this.instance_ = this.stamp({}); - - const children = this.instance_.root.children; - for (const child of children) { - this.children_[child.getAttribute('route-id')] = child; - } - }, - - /** - * @param {string} newRouteId - */ - onRouteChanged_: function(newRouteId) { - if (!this.instance_) { - return; - } - - const newSelectedChild = this.children_[newRouteId]; - assert( - newSelectedChild, - 'The route must be equal to the route-id of a child element.'); - - if (this.selectedChild_) { - this.parentNode.replaceChild(newSelectedChild, this.selectedChild_); - } else { - this.parentNode.insertBefore(newSelectedChild, this); - } - - this.selectedChild_ = newSelectedChild; - this.firstRenderForTesting_.resolve(); - }, - - /** - * @param {string} prop - * @param {Object} value - */ - _forwardHostPropV2: function(prop, value) { - if (this.instance_) { - this.instance_.forwardHostProp(prop, value); - } - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/expandable_app_list.html b/chromium/chrome/browser/resources/app_management/expandable_app_list.html index 88558d0c8d1..189b4c08822 100644 --- a/chromium/chrome/browser/resources/app_management/expandable_app_list.html +++ b/chromium/chrome/browser/resources/app_management/expandable_app_list.html @@ -4,7 +4,6 @@ <link rel="import" href="constants.html"> <link rel="import" href="shared_style.html"> <link rel="import" href="store_client.html"> -<link rel="import" href="permission_toggle.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> diff --git a/chromium/chrome/browser/resources/app_management/fake_page_handler.js b/chromium/chrome/browser/resources/app_management/fake_page_handler.js deleted file mode 100644 index 6c8b2492ded..00000000000 --- a/chromium/chrome/browser/resources/app_management/fake_page_handler.js +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('app_management', function() { - /** - * @implements {appManagement.mojom.PageHandlerInterface} - */ - class FakePageHandler { - /** - * @param {Object=} options - * @return {!Object<number, Permission>} - */ - static createWebPermissions(options) { - const permissionIds = [ - PwaPermissionType.CONTENT_SETTINGS_TYPE_GEOLOCATION, - PwaPermissionType.CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - PwaPermissionType.CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, - PwaPermissionType.CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, - ]; - - const permissions = {}; - - for (const permissionId of permissionIds) { - let permissionValue = TriState.kAllow; - let isManaged = false; - - if (options && options[permissionId]) { - const opts = options[permissionId]; - permissionValue = opts.permissionValue || permissionValue; - isManaged = opts.isManaged || isManaged; - } - permissions[permissionId] = app_management.util.createPermission( - permissionId, PermissionValueType.kTriState, permissionValue, - isManaged); - } - - return permissions; - } - - /** - * @param {Array<number>=} optIds - * @return {!Object<number, Permission>} - */ - static createArcPermissions(optIds) { - const permissionIds = optIds || [ - ArcPermissionType.CAMERA, - ArcPermissionType.LOCATION, - ArcPermissionType.MICROPHONE, - ArcPermissionType.NOTIFICATIONS, - ArcPermissionType.CONTACTS, - ArcPermissionType.STORAGE, - ]; - - const permissions = {}; - - for (const permissionId of permissionIds) { - permissions[permissionId] = app_management.util.createPermission( - permissionId, PermissionValueType.kBool, Bool.kTrue, - false /*is_managed*/); - } - - return permissions; - } - - /** - * @param {AppType} appType - * @return {!Object<number, Permission>} - */ - static createPermissions(appType) { - switch (appType) { - case (AppType.kWeb): - return FakePageHandler.createWebPermissions(); - case (AppType.kArc): - return FakePageHandler.createArcPermissions(); - default: - return {}; - } - } - - /** - * @param {string} id - * @param {Object=} optConfig - * @return {!App} - */ - static createApp(id, optConfig) { - const app = { - id: id, - type: apps.mojom.AppType.kWeb, - title: 'App Title', - description: '', - version: '5.1', - size: '9.0MB', - isPinned: apps.mojom.OptionalBool.kFalse, - isPolicyPinned: apps.mojom.OptionalBool.kFalse, - installSource: apps.mojom.InstallSource.kUser, - permissions: {}, - hideMoreSettings: false, - hidePinToShelf: false, - }; - - if (optConfig) { - Object.assign(app, optConfig); - } - - // Only create default permissions if none were provided in the config. - if (!optConfig || optConfig.permissions === undefined) { - app.permissions = FakePageHandler.createPermissions(app.type); - } - - return app; - } - - /** - * @param {appManagement.mojom.PageRemote} page - */ - constructor(page) { - this.receiver_ = new appManagement.mojom.PageHandlerReceiver(this); - /** @type {appManagement.mojom.PageRemote} */ - this.page = page; - - /** @type {!Array<App>} */ - this.apps_ = []; - - /** @type {number} */ - this.guid = 0; - } - - /** - * @returns {!appManagement.mojom.PageHandlerRemote} - */ - getRemote() { - return this.receiver_.$.bindNewPipeAndPassRemote(); - } - - async flushPipesForTesting() { - await this.page.$.flushForTesting(); - } - - async getApps() { - return {apps: this.apps_}; - } - - /** - * @param {string} appId - * @return {!Promise} - */ - async getExtensionAppPermissionMessages(appId) { - return []; - } - - /** - * @param {!Array<App>} appList - */ - setApps(appList) { - this.apps_ = appList; - } - - /** - * @param {string} appId - * @param {OptionalBool} pinnedValue - */ - setPinned(appId, pinnedValue) { - const app = app_management.Store.getInstance().data.apps[appId]; - - const newApp = - /** @type {App} */ (Object.assign({}, app, {isPinned: pinnedValue})); - this.page.onAppChanged(newApp); - } - - /** - * @param {string} appId - * @param {Permission} permission - */ - setPermission(appId, permission) { - const app = app_management.Store.getInstance().data.apps[appId]; - - // Check that the app had a previous value for the given permission - assert(app.permissions[permission.permissionId]); - - const newPermissions = Object.assign({}, app.permissions); - newPermissions[permission.permissionId] = permission; - const newApp = /** @type {App} */ ( - Object.assign({}, app, {permissions: newPermissions})); - this.page.onAppChanged(newApp); - } - - /** - * @param {string} appId - */ - uninstall(appId) { - this.page.onAppRemoved(appId); - } - - /** - * @param {string} appId - */ - openNativeSettings(appId) {} - - /** - * @param {string} optId - * @param {Object=} optConfig - * @return {!Promise<!App>} - */ - async addApp(optId, optConfig) { - optId = optId || String(this.guid++); - const app = FakePageHandler.createApp(optId, optConfig); - this.page.onAppAdded(app); - await this.flushPipesForTesting(); - return app; - } - - /** - * Takes an app id and an object mapping app fields to the values they - * should be changed to, and dispatches an action to carry out these - * changes. - * @param {string} id - * @param {Object} changes - */ - async changeApp(id, changes) { - this.page.onAppChanged(FakePageHandler.createApp(id, changes)); - await this.flushPipesForTesting(); - } - } - - return {FakePageHandler: FakePageHandler}; -}); diff --git a/chromium/chrome/browser/resources/app_management/icons.html b/chromium/chrome/browser/resources/app_management/icons.html deleted file mode 100644 index ccb16326e6b..00000000000 --- a/chromium/chrome/browser/resources/app_management/icons.html +++ /dev/null @@ -1,17 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html"> - -<iron-iconset-svg name="app-management" size="24"> - <svg> - <!-- - These icons are copied from material.io and kept in sorted order. - See http://goo.gl/Y1OdAq for instructions on adding additional icons. - --> - <defs> - <!-- From https://material.io/tools/icons/?icon=account_box&style=baseline --> - <g id="contacts"><path d="M19 3H5c-1.11 0-2 .89-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5a2 2 0 0 0-2-2zm-7 3c1.65 0 3 1.35 3 3 0 1.66-1.35 3-3 3s-3-1.34-3-3c0-1.65 1.35-3 3-3zm6 12H6v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1z"></path><path fill="none" d="M0 0h24v24H0z"></path></g> - <!-- From https://material.io/tools/icons/?icon=storage&style=baseline --> - <g id="storage"><path d="M2 20h20v-4H2v4zm2-3h2v2H4v-2zM2 4v4h20V4H2zm4 3H4V5h2v2zm-4 7h20v-4H2v4zm2-3h2v2H4v-2z"></path></g> - </defs> - </svg> -</iron-iconset-svg> diff --git a/chromium/chrome/browser/resources/app_management/main_view.html b/chromium/chrome/browser/resources/app_management/main_view.html deleted file mode 100644 index 364a6702961..00000000000 --- a/chromium/chrome/browser/resources/app_management/main_view.html +++ /dev/null @@ -1,73 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="expandable_app_list.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> - -<dom-module id="app-management-main-view"> - <template> - <style include="app-management-shared-css"> - .notification-row-sublabel { - display: flex; - flex-direction: column; - overflow: hidden; - padding: 11px 0; - } - - .collapsible { - max-width: 250px; - overflow: hidden; - text-overflow: ellipsis; - } - - #notifications-sublabel { - display: flex; - overflow: hidden; - } - - #notifications-sublabel > span { - white-space: pre; - } - - .notification-row { - align-items: center; - cursor: pointer; - display: inline-flex; - justify-content: space-between; - padding: 0 24px; - } - - .app-management-item-arrow { - margin-inline-end: 8px; - padding: 12px; - } - </style> - <app-management-expandable-app-list - apps="[[appsList]]" - list-title="$i18n{appListTitle}" - collapsed-size="[[appsList.length]]"> - <template is="dom-repeat" items="[[appsList]]" as="app"> - <app-management-app-item app="[[app]]"> - <cr-icon-button slot="right-content" - class="subpage-arrow app-management-item-arrow" actionable> - </cr-icon-button> - </app-management-app-item> - </template> - </app-management-expandable-app-list> - - <div class="card-container" hidden> - <span class="notification-row" on-click="onClickNotificationSublabel_"> - <div class="notification-row-sublabel"> - <div class="header-text"> - $i18n{notifications} - </div> - <div id="notifications-sublabel" class="secondary-text"></div> - </div> - <cr-icon-button class="subpage-arrow" actionable></cr-icon-button> - </span> - </div> - </template> - <script src="main_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/main_view.js b/chromium/chrome/browser/resources/app_management/main_view.js deleted file mode 100644 index de2073cb289..00000000000 --- a/chromium/chrome/browser/resources/app_management/main_view.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -Polymer({ - is: 'app-management-main-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * @private {AppMap} - */ - apps_: { - type: Object, - observer: 'onAppsChanged_', - }, - - /** - * List of apps displayed before expanding the app list. - * @private {Array<App>} - */ - appsList: { - type: Array, - value: () => [], - }, - - /** - * A set containing the ids of all the apps with notifications enabled. - * @private {!Set<string>} - */ - notificationAppIds_: { - type: Object, - observer: 'getNotificationSublabel_', - }, - }, - - attached: function() { - this.watch('apps_', state => state.apps); - this.watch('notificationAppIds_', state => state.notifications.allowedIds); - this.updateFromStore(); - this.onAppsChanged_(); - }, - - /** - * @private - */ - onAppsChanged_: function() { - this.appsList = Object.values(this.apps_) - .sort( - (a, b) => app_management.util.alphabeticalSort( - assert(a.title), assert(b.title))); - }, - - /** @private */ - onClickNotificationSublabel_: function() { - this.dispatch(app_management.actions.changePage(PageType.NOTIFICATIONS)); - }, - - /** - * Show a string with apps' |title|(s) previewed into a label, with each - * title ellipsised if too long. - * @private - */ - getNotificationSublabelPieces_: async function() { - const notificationApps = - Array.from(this.notificationAppIds_, id => this.getState().apps[id]); - - const /** @type {string} */ label = await cr.sendWithPromise( - 'getPluralString', 'appListPreview', notificationApps.length); - - const substitutions = []; - for (let i = 0; - i < APP_LIST_PREVIEW_APP_TITLES && i < notificationApps.length; i++) { - substitutions.push(notificationApps[i].title); - } - - // Add X more apps if the length is more than APP_LIST_PREVIEW_APP_TITLES. - if (notificationApps.length >= APP_LIST_PREVIEW_APP_TITLES + 1) { - substitutions.push(notificationApps.length - APP_LIST_PREVIEW_APP_TITLES); - } - // Only APP_LIST_PREVIEW_APP_TITLES of apps' titles get ellipsised - // if too long. the element after that is "X other apps" - const placeholder = APP_LIST_PREVIEW_APP_TITLES + 1; - const pieces = - loadTimeData.getSubstitutedStringPieces(label, ...substitutions) - .map(function(p) { - // Make the titles of app collapsible but make the number in the - // "X other app(s)" part non-collapsible. - p.collapsible = !!p.arg && p.arg !== '$' + placeholder; - return p; - }); - return pieces; - }, - - /** - * Create <span> for each app title previewed, - * making certain text fragments collapsible. - */ - getNotificationSublabel_: async function() { - const pieces = await this.getNotificationSublabelPieces_(); - // Create <span> for each app title previewed, - // making certain text fragments collapsible. - const textContainer = this.$['notifications-sublabel']; - textContainer.textContent = ''; - for (const p of pieces) { - if (!p.value || p.value.length === 0) { - return; - } - - const span = document.createElement('span'); - span.textContent = p.value; - if (p.collapsible) { - span.classList.add('collapsible'); - } - - textContainer.appendChild(span); - } - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/metadata_view.html b/chromium/chrome/browser/resources/app_management/metadata_view.html deleted file mode 100644 index 43948aeb5f3..00000000000 --- a/chromium/chrome/browser/resources/app_management/metadata_view.html +++ /dev/null @@ -1,72 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="browser_proxy.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> - -<dom-module id="app-management-metadata-view"> - <template> - <style include="app-management-shared-css"> - #shelf-switch-row { - align-items: center; - display: flex; - justify-content: space-around; - padding-bottom: 20px; - } - - #shelf-switch { - align-items: center; - display: flex; - justify-content: space-between; - } - - cr-toggle { - margin-inline-start: 12px; - } - - #metadata-overview { - display: flex; - flex-direction: column; - } - - #metadata-overview > span { - text-align: center; - } - - .metadata-row { - display: flex; - justify-content: space-around; - } - - #policy-indicator { - fill: var(--google-grey-refresh-700); - margin-inline-end: 12px; - } - </style> - <template is="dom-if" if="[[pinToShelfToggleVisible_(app_)]]"> - <div id="shelf-switch-row"> - <span id="shelf-switch" class="header-text"> - <template is="dom-if" if="[[isPolicyPinned_(app_)]]"> - <iron-icon id="policy-indicator" icon="cr:domain" tabindex="0" - aria-describedby="tooltip"> - </iron-icon> - <paper-tooltip id="tooltip" for="policy-indicator" - position="top" fit-to-visible-bounds> - $i18n{pinControlledByPolicy} - </paper-tooltip> - </template> - $i18n{pinToShelf} - <cr-toggle id="pin-to-shelf-toggle" checked="[[isPinned_(app_)]]" - on-change="togglePinned_" disabled$="[[isPolicyPinned_(app_)]]"> - </cr-toggle> - </span> - </div> - </template> - - <div id="metadata-overview" class="secondary-text"> - <span>[[versionString_(app_)]]</span> - <span>[[sizeString_(app_)]]</span> - </div> - </template> - <script src="metadata_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/metadata_view.js b/chromium/chrome/browser/resources/app_management/metadata_view.js deleted file mode 100644 index d063cdc2196..00000000000 --- a/chromium/chrome/browser/resources/app_management/metadata_view.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -Polymer({ - is: 'app-management-metadata-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** @type {App} */ - app_: { - type: Object, - }, - }, - - attached: function() { - this.watch('app_', state => app_management.util.getSelectedApp(state)); - this.updateFromStore(); - }, - - /** - * @param {App} app - * @return bool - * @private - */ - pinToShelfToggleVisible_: function(app) { - return app.isPinned !== OptionalBool.kUnknown; - }, - - /** - * Returns a bool representation of the app's isPinned value, used to - * determine the position of the "Pin to Shelf" toggle. - * @param {App} app - * @return bool - * @private - */ - isPinned_: function(app) { - return app.isPinned === OptionalBool.kTrue; - }, - - isPolicyPinned_: function(app) { - return app.isPolicyPinned === OptionalBool.kTrue; - }, - - /** @private */ - togglePinned_: function() { - let newPinnedValue; - - switch (this.app_.isPinned) { - case OptionalBool.kFalse: - newPinnedValue = OptionalBool.kTrue; - break; - case OptionalBool.kTrue: - newPinnedValue = OptionalBool.kFalse; - break; - default: - assertNotReached(); - } - - app_management.BrowserProxy.getInstance().handler.setPinned( - this.app_.id, assert(newPinnedValue)); - }, - - /** - * @param {App} app - * @return {?string} - * @private - */ - versionString_: function(app) { - if (!app.version) { - return null; - } - - return loadTimeData.getStringF('version', assert(app.version)); - }, - - /** - * @param {App} app - * @return {?string} - * @private - */ - sizeString_: function(app) { - if (!app.size) { - return null; - } - - return loadTimeData.getStringF('size', assert(app.size)); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/notifications_view.html b/chromium/chrome/browser/resources/app_management/notifications_view.html deleted file mode 100644 index c66bcb2ce6c..00000000000 --- a/chromium/chrome/browser/resources/app_management/notifications_view.html +++ /dev/null @@ -1,53 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="expandable_app_list.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> - -<dom-module id="app-management-notifications-view"> - <template> - <style include="app-management-shared-css"> - cr-icon-button { - margin: 0; - } - - app-management-permission-toggle { - margin-inline-end: 24px; - } - - #notification-view-header { - align-items: center; - display: flex; - margin: 24px auto; - max-width: var(--card-max-width); - min-width: var(--card-min-width); - } - - #notification-title { - padding-inline-start: 12px; - } - </style> - <!-- TODO(crbug.com/906508): Implement display when there is no apps at - all --> - <div id="notification-view-header"> - <cr-icon-button class="icon-arrow-back" id="closeButton" - on-click="onClickBackButton_" aria-label="$i18n{back}"> - </cr-icon-button> - <div id="notification-title" class="page-title">$i18n{notifications}</div> - </div> - <app-management-expandable-app-list - apps="[[appsList_]]" - collapsed-size="[[getCollapsedSize_(appsList_)]]"> - <template is="dom-repeat" items="[[appsList_]]" as="app"> - <app-management-app-item app="[[app]]"> - <app-management-permission-toggle slot="right-content" - app="[[app]]" - permission-type="CONTENT_SETTINGS_TYPE_NOTIFICATIONS"> - </app-management-permission-toggle> - </app-management-app-item> - </template> - </app-management-expandable-app-list> - </template> - <script src="notifications_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/notifications_view.js b/chromium/chrome/browser/resources/app_management/notifications_view.js deleted file mode 100644 index aae8cffaf05..00000000000 --- a/chromium/chrome/browser/resources/app_management/notifications_view.js +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -Polymer({ - is: 'app-management-notifications-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * @private {AppMap} - */ - apps_: { - type: Object, - observer: 'onAppsChanged_', - }, - - /** @private {!Array<!App>} */ - appsList_: { - type: Array, - computed: 'calculateAppsList_(allowed_.*, blocked_.*)', - }, - - /** - * List of apps with notification permission - * displayed before expanding the app list. - * @private {!Array<App>} - */ - allowed_: { - type: Array, - value: () => [], - }, - - /** - * List of apps without notification permission - * displayed after expanding app list. - * @private {!Array<App>} - */ - blocked_: { - type: Array, - value: () => [], - }, - }, - - attached: function() { - this.watch('apps_', state => state.apps); - this.updateFromStore(); - - this.onViewLoaded_(); - }, - - /** - * Creates arrays of displayed and collapsed apps based on the sets of apps - * with notifications allowed and blocked in the Store. The orders of apps - * in these arrays should then remain fixed while this view is showing. - * - * If all the apps have / don't have notification permission, display the - * whole list, else display those with notification permission before - * expanding. - * @private - */ - onViewLoaded_: function() { - const state = this.getState(); - this.allowed_ = - Array.from(state.notifications.allowedIds, id => state.apps[id]); - this.blocked_ = - Array.from(state.notifications.blockedIds, id => state.apps[id]); - }, - - /** - * Updates the lists of displayed and collapsed apps when any changes occur - * to the apps in the Store, maintaining the original order of apps in the - * lists. New lists are created so that Polymer bindings will re-evaluate. - * @private - */ - onAppsChanged_() { - const unhandledAppIds = new Set(Object.keys(this.apps_)); - this.allowed_ = this.updateAppList_(this.allowed_, unhandledAppIds); - this.blocked_ = this.updateAppList_(this.blocked_, unhandledAppIds); - - // If any new apps have been added, append them to the appropriate list. - for (const appId of unhandledAppIds) { - const app = this.apps_[appId]; - const allowed = app_management.util.notificationsAllowed(app); - - if (allowed === OptionalBool.kUnknown) { - continue; - } - - if (allowed === OptionalBool.kTrue) { - this.push('allowed_', app); - } else { - this.push('blocked_', app); - } - } - }, - - /** - * @private - * @return {!Array<!App>} - */ - calculateAppsList_() { - return this.allowed_.concat(this.blocked_); - }, - - /** - * @private - * @return {number} - */ - getCollapsedSize_() { - return this.allowed_.length || this.blocked_.length; - }, - - /** - * Creates a new list of apps with the same order as the original appList, - * but using the updated apps from this.apps_. As each app is added to the - * new list, it is also removed from the unhandledAppIds set. - * @param {!Array<App>} appList - * @param {!Set<string>} unhandledAppIds - * @return {!Array<App>} - * @private - */ - updateAppList_(appList, unhandledAppIds) { - const newApps = []; - for (const app of appList) { - if (unhandledAppIds.has(app.id)) { - newApps.push(this.apps_[app.id]); - unhandledAppIds.delete(app.id); - } - } - return newApps; - }, - - /** @private */ - onClickBackButton_: function() { - if (!window.history.state) { - this.dispatch(app_management.actions.changePage(PageType.MAIN)); - } else { - window.history.back(); - } - }, - - /** - * Returns a boolean representation of the permission value, which used to - * determine the position of the permission toggle. - * @param {App} app - * @return {boolean} - * @private - */ - getNotificationValueBool_: function(app) { - return app_management.util.getPermissionValueBool( - app, this.notificationsPermissionType(app)); - }, - - /** - * @param {App} app - * @return {string} - * @private - */ - notificationsPermissionType_: function(app) { - return assert(app_management.util.notificationsPermissionType(app)); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/permission_item.html b/chromium/chrome/browser/resources/app_management/permission_item.html deleted file mode 100644 index 915351268c6..00000000000 --- a/chromium/chrome/browser/resources/app_management/permission_item.html +++ /dev/null @@ -1,42 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="shared_style.html"> -<link rel="import" href="permission_toggle.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> - -<dom-module id="app-management-permission-item"> - <template> - <style include="app-management-shared-css"> - :host { - align-items: center; - cursor: pointer; - display: flex; - justify-content: space-between; - } - - :host(:not([available_])) { - display: none; - } - - #permission-icon { - color: var(--permission-icon-color); - padding-inline-end: var(--permission-icon-padding); - } - </style> - <!-- `permission-item` does not include any icon-set, so containing - elements should import the icon-set needed for the specified |icon|. --> - <template is="dom-if" if="[[available_]]"> - <div class="permission-row-controls"> - <template is="dom-if" if="[[icon]]"> - <iron-icon id="permission-icon" icon="[[icon]]"></iron-icon> - </template> - <div id="permission-label">[[permissionLabel]]</div> - </div> - <app-management-permission-toggle id="permission-toggle" - app="[[app_]]" permission-type="[[permissionType]]"> - </app-management-permission-toggle> - </template> - </template> - <script src="permission_item.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/permission_item.js b/chromium/chrome/browser/resources/app_management/permission_item.js deleted file mode 100644 index cf610ef9bcb..00000000000 --- a/chromium/chrome/browser/resources/app_management/permission_item.js +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-permission-item', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * The name of the permission, to be displayed to the user. - * @type {string} - */ - permissionLabel: String, - - /** - * A string version of the permission type. Must be a value of the - * permission type enum corresponding to the AppType of app_. - * E.g. A value of PwaPermissionType if app_.type === AppType.kWeb. - * @type {string} - */ - permissionType: String, - - /** - * @type {App} - */ - app_: Object, - - /** - * @type {string} - */ - icon: String, - - /** - * True if the permission type is available for the app. - * @private - */ - available_: { - type: Boolean, - computed: 'isAvailable_(app_, permissionType)', - reflectToAttribute: true, - }, - }, - - listeners: { - 'click': 'onClick_', - }, - - /** - * Returns true if the permission type is available for the app. - * - * @param {App} app - * @param {string} permissionType - * @private - */ - isAvailable_: function(app, permissionType) { - if (app === undefined || permissionType === undefined) { - return false; - } - - assert(app); - - return app_management.util.getPermission(app, permissionType) !== undefined; - }, - - attached: function() { - this.watch('app_', state => app_management.util.getSelectedApp(state)); - this.updateFromStore(); - }, - - /** - * @param {MouseEvent} e - * @private - */ - onClick_: function(e) { - e.preventDefault(); - - const toggle = /** @type {AppManagementPermissionToggleElement} */ ( - assert(this.$$('#permission-toggle'))); - toggle.togglePermission_(); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/permission_toggle.html b/chromium/chrome/browser/resources/app_management/permission_toggle.html deleted file mode 100644 index 7086ec640ad..00000000000 --- a/chromium/chrome/browser/resources/app_management/permission_toggle.html +++ /dev/null @@ -1,37 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="chrome://resources/cr_elements/policy/cr_tooltip_icon.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> - -<!-- TODO(jshikaram): use toggle-row here. --> - -<dom-module id="app-management-permission-toggle"> - <template> - <style> - :host { - align-items: center; - display: flex; - } - - #policy-indicator { - fill: var(--google-grey-refresh-700); - padding-inline-end: 12px; - } - </style> - <template is="dom-if" - if="[[isPermissionManaged_(app, permissionType)]]"> - <iron-icon id="policy-indicator" icon="cr:domain" tabindex="0" - aria-describedby="tooltip"> - </iron-icon> - <paper-tooltip id="tooltip" for="policy-indicator" - position="top" fit-to-visible-bounds> - $i18n{controlledByPolicy} - </paper-tooltip> - </template> - <cr-toggle checked="[[getPermissionValueBool_(app, permissionType)]]" - on-change="togglePermission_" - disabled$="[[isPermissionManaged_(app, permissionType)]]"> - </cr-toggle> - </template> - <script src="permission_toggle.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/permission_toggle.js b/chromium/chrome/browser/resources/app_management/permission_toggle.js deleted file mode 100644 index 7856395ea6f..00000000000 --- a/chromium/chrome/browser/resources/app_management/permission_toggle.js +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-permission-toggle', - - properties: { - /** - * @type {App} - */ - app: Object, - - /** - * A string version of the permission type. Must be a value of the - * permission type enum corresponding to the AppType of app_. - * E.g. A value of PwaPermissionType if app_.type === AppType.kWeb. - * @type {string} - */ - permissionType: String, - }, - - /** - * @param {App} app - * @param {string} permissionType - * @return {boolean} - */ - getPermissionValueBool_: function(app, permissionType) { - if (app === undefined || permissionType === undefined) { - return false; - } - - assert(app); - - return app_management.util.getPermissionValueBool(app, permissionType); - }, - - /** - * @param {App} app - * @param {string} permissionType - * @return {boolean} - */ - isPermissionManaged_: function(app, permissionType) { - if (app === undefined || permissionType === undefined) { - return false; - } - - assert(app); - - const permission = app_management.util.getPermission(app, permissionType); - assert(permission); - return permission.isManaged; - }, - - togglePermission_: function() { - assert(this.app); - - /** @type {!Permission} */ - let newPermission; - - switch (app_management.util.getPermission(this.app, this.permissionType) - .valueType) { - case PermissionValueType.kBool: - newPermission = - this.getNewPermissionBoolean_(this.app, this.permissionType); - break; - case PermissionValueType.kTriState: - newPermission = - this.getNewPermissionTriState_(this.app, this.permissionType); - break; - default: - assertNotReached(); - } - - app_management.BrowserProxy.getInstance().handler.setPermission( - this.app.id, newPermission); - }, - - /** - * @param {App} app - * @param {string} permissionType - * @return {!Permission} - * @private - */ - getNewPermissionBoolean_: function(app, permissionType) { - let newPermissionValue; - const currentPermission = - app_management.util.getPermission(app, permissionType); - - switch (currentPermission.value) { - case Bool.kFalse: - newPermissionValue = Bool.kTrue; - break; - case Bool.kTrue: - newPermissionValue = Bool.kFalse; - break; - default: - assertNotReached(); - } - - assert(newPermissionValue !== undefined); - return app_management.util.createPermission( - app_management.util.permissionTypeHandle(app, permissionType), - PermissionValueType.kBool, newPermissionValue, - currentPermission.isManaged); - }, - - /** - * @param {App} app - * @param {string} permissionType - * @return {!Permission} - * @private - */ - getNewPermissionTriState_: function(app, permissionType) { - let newPermissionValue; - const currentPermission = - app_management.util.getPermission(app, permissionType); - - switch (currentPermission.value) { - case TriState.kBlock: - newPermissionValue = TriState.kAllow; - break; - case TriState.kAsk: - newPermissionValue = TriState.kAllow; - break; - case TriState.kAllow: - // TODO(rekanorman): Eventually TriState.kAsk, but currently changing a - // permission to kAsk then opening the site settings page for the app - // produces the error: - // "Only extensions or enterprise policy can change the setting to ASK." - newPermissionValue = TriState.kBlock; - break; - default: - assertNotReached(); - } - - assert(newPermissionValue !== undefined); - return app_management.util.createPermission( - app_management.util.permissionTypeHandle(app, permissionType), - PermissionValueType.kTriState, newPermissionValue, - currentPermission.isManaged); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/permission_view_header.html b/chromium/chrome/browser/resources/app_management/permission_view_header.html deleted file mode 100644 index d0c6f0c9e55..00000000000 --- a/chromium/chrome/browser/resources/app_management/permission_view_header.html +++ /dev/null @@ -1,62 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="shared_style.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> - -<dom-module id="app-management-permission-view-header"> - <template> - <style include="app-management-shared-css"> - :host { - align-items: center; - display: flex; - margin: 24px auto; - max-width: var(--card-max-width); - min-width: var(--card-min-width); - } - - #permission-view-header-icon { - height: 26px; - margin-inline-end: 8px; - margin-inline-start: 24px; - width: 26px; - } - - #app-title { - flex: 1; - font-size: 16px; - overflow: hidden; - text-overflow: ellipsis; - } - - cr-icon-button { - margin: 0; - } - - #uninstall-button { - background: white; - } - - #policy-indicator { - fill: var(--google-grey-refresh-700); - margin-inline-end: 12px; - } - </style> - <cr-icon-button class="icon-arrow-back" id="backButton" - on-click="onClickBackButton_" aria-label="$i18n{back}"></cr-icon-button> - <img id="permission-view-header-icon" src="[[iconUrlFromId_(app_)]]"> - <div class="page-title">[[app_.title]]</div> - - <div id="uninstall-wrapper" title$="[[getUninstallButtonHoverText_(app_)]]"> - <template is="dom-if" if="[[isPolicyApp_(app_)]]"> - <iron-icon id="policy-indicator" icon="cr:domain"></iron-icon> - </template> - <cr-button id="uninstall-button" on-click="onClickUninstallButton_" - disabled$="[[getUninstallButtonDisableState_(app_)]]"> - $i18n{uninstall} - </cr-button> - </div> - </template> - <script src="permission_view_header.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/permission_view_header.js b/chromium/chrome/browser/resources/app_management/permission_view_header.js deleted file mode 100644 index a6caf895c2e..00000000000 --- a/chromium/chrome/browser/resources/app_management/permission_view_header.js +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-permission-view-header', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** @type {App} */ - app_: { - type: Object, - }, - }, - - attached: function() { - this.watch('app_', state => app_management.util.getSelectedApp(state)); - this.updateFromStore(); - }, - - /** - * - * Returns True if the uninstall button should be disabled due to app install - * type. - * - * @param {App} app - * @return {boolean} - * @private - */ - getUninstallButtonDisableState_: function(app) { - switch (app.installSource) { - case InstallSource.kSystem: - case InstallSource.kPolicy: - return true; - case InstallSource.kOem: - case InstallSource.kDefault: - case InstallSource.kSync: - case InstallSource.kUser: - case InstallSource.kUnknown: - return false; - default: - assertNotReached(); - } - }, - - /** - * Returns string to be shown as a tool tip over the uninstall button. - * - * @param {App} app - * @return {string} - * @private - */ - getUninstallButtonHoverText_: function(app) { - // TODO(crbug.com/957795) Replace strings and add them into i18n. - switch (app.installSource) { - case InstallSource.kSystem: - return app.title + ' cannot be uninstalled as it is part of Chrome OS.'; - case InstallSource.kPolicy: - return app.title + ' cannot be uninstalled as it has been' + - ' installed by your administrator.'; - case InstallSource.kOem: - case InstallSource.kDefault: - case InstallSource.kSync: - case InstallSource.kUser: - case InstallSource.kUnknown: - return `Click to uninstall ${app.title}.`; - default: - assertNotReached(); - } - }, - - /** - * Returns true if the app was installed by a policy - * - * @param {App} app - * @returns {boolean} - * @private - */ - isPolicyApp_: function(app) { - return app.installSource === InstallSource.kPolicy; - }, - - /** - * @param {App} app - * @return {string} - * @private - */ - iconUrlFromId_: function(app) { - return app_management.util.getAppIcon(app); - }, - - /** - * @private - */ - onClickBackButton_: function() { - if (!window.history.state) { - this.dispatch(app_management.actions.changePage(PageType.MAIN)); - } else { - window.history.back(); - } - }, - - /** - * @private - */ - onClickUninstallButton_: function() { - app_management.BrowserProxy.getInstance().handler.uninstall(this.app_.id); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html b/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html deleted file mode 100644 index fe4821f2988..00000000000 --- a/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html +++ /dev/null @@ -1,19 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="toggle_row.html"> - -<dom-module id="app-management-pin-to-shelf-item"> - <template> - <style> - :host(:not([disabled])) { - cursor: pointer; - } - </style> - <app-management-toggle-row - label_="$i18n{pinToShelf}" - managed_$="[[isManaged_(app_)]]" - policy-label_="$i18n{pinControlledByPolicy}" - value_$="[[getValue_(app_)]]"> - </app-management-toggle-row> - </template> - <script src="pin_to_shelf_item.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js b/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js deleted file mode 100644 index ee5d2ac0df4..00000000000 --- a/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-pin-to-shelf-item', - - properties: { - /** - * @type {App} - * @private - */ - app_: Object, - - /** - * @type {boolean} - * @private - */ - hidden: { - type: Boolean, - computed: 'isAvailable_(app_)', - reflectToAttribute: true, - }, - - /** - * @type {boolean} - * @private - */ - disabled: { - type: Boolean, - computed: 'isManaged_(app_)', - reflectToAttribute: true, - }, - }, - - ready: function() { - // capture the onClick event before it reaches the toggle. - this.addEventListener('click', this.onClick_, true); - }, - - /** - * @param {App} app - * @returns {boolean} true if the app is pinned - * @private - */ - getValue_: function(app) { - if (app === undefined) { - return false; - } - assert(app); - return app.isPinned === OptionalBool.kTrue; - }, - - /** - * @param {App} app - * @returns {boolean} true if pinning is available. - */ - isAvailable_: function(app) { - if (app === undefined) { - return false; - } - assert(app); - return app.hidePinToShelf; - }, - - /** - * @param {App} app - * @returns {boolean} true if the pinning is managed by policy. - * @private - */ - isManaged_: function(app) { - if (app === undefined) { - return false; - } - assert(app); - return app.isPolicyPinned === OptionalBool.kTrue; - }, - - /** - * @param {Event} event - * @private - */ - onClick_: function(event) { - event.stopPropagation(); - - // Disabled - if (this.isManaged_(this.app_)) { - return; - } - - app_management.BrowserProxy.getInstance().handler.setPinned( - this.app_.id, - assert(app_management.util.toggleOptionalBool(this.app_.isPinned)), - ); - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/pwa_permission_view.html b/chromium/chrome/browser/resources/app_management/pwa_permission_view.html deleted file mode 100644 index 17952e85e3f..00000000000 --- a/chromium/chrome/browser/resources/app_management/pwa_permission_view.html +++ /dev/null @@ -1,65 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="browser_proxy.html"> -<link rel="import" href="metadata_view.html"> -<link rel="import" href="permission_item.html"> -<link rel="import" href="permission_view_header.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="pin_to_shelf_item.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> -<link rel="import" href="chrome://resources/cr_elements/icons.html"> - -<dom-module id="app-management-pwa-permission-view"> - <template> - <style include="app-management-shared-css"> - </style> - - <app-management-permission-view-header> - </app-management-permission-view-header> - - <div class="permission-list card-container"> - <app-management-pin-to-shelf-item - id="pin-to-shelf-setting" - class="permission-card-row separated-row header-text" - app_="[[app_]]"> - </app-management-pin-to-shelf-item> - <app-management-permission-item id="notifications-card" - class="permission-card-row separated-row header-text" - permission-label="$i18n{notifications}" - permission-type="CONTENT_SETTINGS_TYPE_NOTIFICATIONS"> - </app-management-permission-item> - <div id="permissions-card" class="permission-card-row"> - <div class="subpermission-list"> - <div class="subpermission-row separated-row"> - <div class="header-text">$i18n{permissions}</div> - </div> - <app-management-permission-item id="location" - class="subpermission-row" icon="cr:location-on" - permission-label="$i18n{location}" - permission-type="CONTENT_SETTINGS_TYPE_GEOLOCATION"> - </app-management-permission-item> - <app-management-permission-item id="camera" class="subpermission-row" - icon="cr:videocam" permission-label="$i18n{camera}" - permission-type="CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA"> - </app-management-permission-item> - <app-management-permission-item id="microphone" - class="subpermission-row" icon="cr:mic" - permission-label="$i18n{microphone}" - permission-type="CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC"> - </app-management-permission-item> - <div class="subpermission-row separated-row clickable" - on-click="onClickSiteSettingsButton_"> - <div class="header-text">$i18n{moreSettings}</div> - <div class="permission-row-controls"> - <cr-icon-button class="native-settings-icon icon-external" - tabindex="0"> - </cr-icon-button> - </div> - </div> - </div> - </div> - </div> - </template> - <script src="pwa_permission_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/pwa_permission_view.js b/chromium/chrome/browser/resources/app_management/pwa_permission_view.js deleted file mode 100644 index bc475ed9085..00000000000 --- a/chromium/chrome/browser/resources/app_management/pwa_permission_view.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-pwa-permission-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * @private {App} - */ - app_: Object, - - /** - * @private {boolean} - */ - listExpanded_: { - type: Boolean, - value: false, - }, - }, - - attached: function() { - this.watch('app_', state => app_management.util.getSelectedApp(state)); - this.updateFromStore(); - - this.listExpanded_ = false; - }, - - /** - * @private - */ - onClickSiteSettingsButton_: function() { - app_management.BrowserProxy.getInstance().handler.openNativeSettings( - this.app_.id); - }, - - /** - * @private - */ - toggleListExpanded_: function() { - this.listExpanded_ = !this.listExpanded_; - }, - - /** - * @param {App} app - * @return {string} - * @private - */ - iconUrlFromId_: function(app) { - return app_management.util.getAppIcon(app); - }, - - /** - * @param {boolean} listExpanded - * @return {string} - * @private - */ - getCollapsedIcon_: function(listExpanded) { - return listExpanded ? 'cr:expand-less' : 'cr:expand-more'; - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/reducers.html b/chromium/chrome/browser/resources/app_management/reducers.html deleted file mode 100644 index 6eda04966b8..00000000000 --- a/chromium/chrome/browser/resources/app_management/reducers.html +++ /dev/null @@ -1,2 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<script src="reducers.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/reducers.js b/chromium/chrome/browser/resources/app_management/reducers.js deleted file mode 100644 index 3b9de9038d9..00000000000 --- a/chromium/chrome/browser/resources/app_management/reducers.js +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Module of functions which produce a new page state in response - * to an action. Reducers (in the same sense as Array.prototype.reduce) must be - * pure functions: they must not modify existing state objects, or make any API - * calls. - */ - -cr.define('app_management', function() { - const AppState = {}; - - /** - * @param {AppMap} apps - * @param {Object} action - * @return {AppMap} - */ - AppState.addApp = function(apps, action) { - assert(!apps[action.app.id]); - - const newAppEntry = {}; - newAppEntry[action.app.id] = action.app; - return Object.assign({}, apps, newAppEntry); - }; - - /** - * @param {AppMap} apps - * @param {Object} action - * @return {AppMap} - */ - AppState.changeApp = function(apps, action) { - assert(apps[action.app.id]); - - const changedAppEntry = {}; - changedAppEntry[action.app.id] = action.app; - return Object.assign({}, apps, changedAppEntry); - }; - - /** - * @param {AppMap} apps - * @param {Object} action - * @return {AppMap} - */ - AppState.removeApp = function(apps, action) { - if (!apps.hasOwnProperty(action.id)) { - return apps; - } - - delete apps[action.id]; - return Object.assign({}, apps); - }; - - /** - * @param {AppMap} apps - * @param {Object} action - * @return {AppMap} - */ - AppState.updateApps = function(apps, action) { - switch (action.name) { - case 'add-app': - return AppState.addApp(apps, action); - case 'change-app': - return AppState.changeApp(apps, action); - case 'remove-app': - return AppState.removeApp(apps, action); - default: - return apps; - } - }; - - const CurrentPageState = {}; - - /** - * @param {AppMap} apps - * @param {Object} action - * @return {Page} - */ - CurrentPageState.changePage = function(apps, action) { - if (action.pageType === PageType.DETAIL && apps[action.id]) { - return { - pageType: PageType.DETAIL, - selectedAppId: action.id, - }; - } else if (action.pageType === PageType.NOTIFICATIONS) { - return { - pageType: PageType.NOTIFICATIONS, - selectedAppId: null, - }; - } else { - return { - pageType: PageType.MAIN, - selectedAppId: null, - }; - } - }; - - /** - * @param {Page} currentPage - * @param {Object} action - * @return {Page} - */ - CurrentPageState.removeApp = function(currentPage, action) { - if (currentPage.pageType === PageType.DETAIL && - currentPage.selectedAppId === action.id) { - return { - pageType: PageType.MAIN, - selectedAppId: null, - }; - } else { - return currentPage; - } - }; - - /** - * @param {AppMap} apps - * @param {Page} currentPage - * @param {Object} action - * @return {Page} - */ - CurrentPageState.updateCurrentPage = function(apps, currentPage, action) { - switch (action.name) { - case 'change-page': - return CurrentPageState.changePage(apps, action); - case 'remove-app': - return CurrentPageState.removeApp(currentPage, action); - default: - return currentPage; - } - }; - - const SearchState = {}; - - /** - * @param {AppMap} apps - * @param {SearchState} search - * @param {Object} action - * @return {SearchState} - */ - SearchState.startSearch = function(apps, search, action) { - if (action.term === search.term) { - return search; - } - - const results = []; - - for (const app of Object.values(apps)) { - if (app.title.toLowerCase().includes(action.term.toLowerCase())) { - results.push(app); - } - } - - results.sort( - (a, b) => app_management.util.alphabeticalSort( - assert(a.title), assert(b.title))); - - return /** @type {SearchState} */ (Object.assign({}, search, { - term: action.term, - results: results, - })); - }; - - /** @return {SearchState} */ - SearchState.clearSearch = function() { - return { - term: null, - results: null, - }; - }; - - /** - * @param {AppMap} apps - * @param {SearchState} search - * @param {Object} action - * @return {SearchState} - */ - SearchState.updateSearch = function(apps, search, action) { - switch (action.name) { - case 'start-search': - return SearchState.startSearch(apps, search, action); - case 'clear-search': - case 'change-page': - return SearchState.clearSearch(); - default: - return search; - } - }; - - const NotificationsState = {}; - - /** - * @param {NotificationsState} notifications - * @param {Object} action - * @return {NotificationsState} - */ - NotificationsState.addApp = function(notifications, action) { - let {allowedIds, blockedIds} = notifications; - const allowed = app_management.util.notificationsAllowed(action.app); - - if (allowed === OptionalBool.kUnknown) { - return {allowedIds, blockedIds}; - } - - if (allowed === OptionalBool.kTrue) { - allowedIds = app_management.util.addIfNeeded(allowedIds, action.app.id); - } else { - blockedIds = app_management.util.addIfNeeded(blockedIds, action.app.id); - } - - return {allowedIds, blockedIds}; - }; - - /** - * @param {NotificationsState} notifications - * @param {Object} action - * @return {NotificationsState} - */ - NotificationsState.changeApp = function(notifications, action) { - let {allowedIds, blockedIds} = notifications; - const allowed = app_management.util.notificationsAllowed(action.app); - const id = action.app.id; - - if (allowed === OptionalBool.kUnknown) { - assert(!blockedIds.has(id) && !allowedIds.has(id)); - return {allowedIds, blockedIds}; - } - - if (allowed === OptionalBool.kTrue) { - allowedIds = app_management.util.addIfNeeded(allowedIds, id); - blockedIds = app_management.util.removeIfNeeded(blockedIds, id); - } else { - allowedIds = app_management.util.removeIfNeeded(allowedIds, id); - blockedIds = app_management.util.addIfNeeded(blockedIds, id); - } - - return {allowedIds, blockedIds}; - }; - - /** - * @param {NotificationsState} notifications - * @param {Object} action - * @return {NotificationsState} - */ - NotificationsState.removeApp = function(notifications, action) { - let {allowedIds, blockedIds} = notifications; - allowedIds = app_management.util.removeIfNeeded(allowedIds, action.id); - blockedIds = app_management.util.removeIfNeeded(blockedIds, action.id); - - return {allowedIds, blockedIds}; - }; - - /** - * @param {NotificationsState} notifications - * @param {Object} action - * @return {NotificationsState} - */ - NotificationsState.updateNotifications = function(notifications, action) { - switch (action.name) { - case 'add-app': - return NotificationsState.addApp(notifications, action); - case 'change-app': - return NotificationsState.changeApp(notifications, action); - case 'remove-app': - return NotificationsState.removeApp(notifications, action); - default: - return notifications; - } - }; - - const ArcSupported = {}; - - /** - * @param {boolean} arcSupported - * @param {Object} action - * @return {boolean} - */ - ArcSupported.updateArcSupported = function(arcSupported, action) { - switch (action.name) { - case 'update-arc-supported': - return action.value; - default: - return arcSupported; - } - }; - - /** - * Root reducer for the App Management page. This is called by the store in - * response to an action, and the return value is used to update the UI. - * @param {!AppManagementPageState} state - * @param {Object} action - * @return {!AppManagementPageState} - */ - function reduceAction(state, action) { - return { - apps: AppState.updateApps(state.apps, action), - currentPage: CurrentPageState.updateCurrentPage( - state.apps, state.currentPage, action), - arcSupported: ArcSupported.updateArcSupported(state.arcSupported, action), - search: SearchState.updateSearch(state.apps, state.search, action), - notifications: - NotificationsState.updateNotifications(state.notifications, action), - }; - } - - return { - reduceAction: reduceAction, - AppState: AppState, - CurrentPageState: CurrentPageState, - ArcSupported: ArcSupported, - NotificationsState: NotificationsState, - SearchState: SearchState, - }; -}); diff --git a/chromium/chrome/browser/resources/app_management/router.html b/chromium/chrome/browser/resources/app_management/router.html deleted file mode 100644 index bbe2548c83a..00000000000 --- a/chromium/chrome/browser/resources/app_management/router.html +++ /dev/null @@ -1,17 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="actions.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="constants.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-location/iron-location.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-location/iron-query-params.html"> - -<dom-module id="app-management-router"> - <template> - <iron-location id="iron-location" query="{{urlQuery_}}" path="{{path_}}"> - </iron-location> - <iron-query-params params-string="{{query_}}" - params-object="{{queryParams_}}"></iron-query-params> - </template> - <script src="router.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/router.js b/chromium/chrome/browser/resources/app_management/router.js deleted file mode 100644 index f0f96baff33..00000000000 --- a/chromium/chrome/browser/resources/app_management/router.js +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -Polymer({ - is: 'app-management-router', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** @private {string} */ - path_: String, - - /** @private {Object} */ - queryParams_: Object, - - /** @private {string} */ - query_: { - type: String, - observer: 'onQueryChanged_', - }, - - /** @private {string} */ - urlQuery_: { - type: String, - observer: 'onUrlQueryChanged_', - }, - - /** @private */ - searchTerm_: { - type: String, - value: '', - }, - - /** @private {PageType} */ - currentPageType_: { - type: Number, - }, - - /** @private {?string} */ - selectedAppId_: { - type: String, - }, - }, - - urlParsed_: false, - - observers: [ - 'onUrlChanged_(path_, queryParams_)', - 'onStateChanged_(currentPageType_, selectedAppId_, searchTerm_)', - ], - - attached: function() { - this.watch('currentPageType_', (state) => { - return state.currentPage.pageType; - }); - this.watch('selectedAppId_', (state) => { - return state.currentPage.selectedAppId; - }); - this.watch('searchTerm_', (state) => { - return state.search.term; - }); - this.updateFromStore(); - }, - - /** - * @param {?string} current Current value of the query. - * @param {?string} previous Previous value of the query. - * @private - */ - onQueryChanged_: function(current, previous) { - if (previous !== undefined) { - this.urlQuery_ = this.query_; - } - }, - - /** @private */ - onUrlQueryChanged_: function() { - this.query_ = this.urlQuery_; - }, - - /** @private */ - onStateChanged_: function() { - if (!this.urlParsed_) { - return; - } - this.debounce('publishUrl', this.publishUrl_); - }, - - /** @private */ - publishUrl_: function() { - // Disable pushing urls into the history stack, so that we only push one - // state. - this.$['iron-location'].dwellTime = Infinity; - this.publishQueryParams_(); - // Re-enable pushing urls into the history stack. - this.$['iron-location'].dwellTime = 0; - this.publishPath_(); - }, - - /** @private */ - publishQueryParams_: function() { - const newQueryParams = Object.assign({}, this.queryParams_); - - newQueryParams.q = this.searchTerm_ || undefined; - newQueryParams.id = this.selectedAppId_ || undefined; - - // Can't update |this.queryParams_| every time since assigning a new object - // to it triggers a state change which causes the URL to change, which - // recurses into a loop. JSON.stringify is used here to compare objects as - // it is always going to be a key value (string) pair and will serialize - // correctly. - if (JSON.stringify(newQueryParams) !== JSON.stringify(this.queryParams_)) { - this.queryParams_ = newQueryParams; - } - }, - - /** @private */ - publishPath_: function() { - let path = ''; - if (this.currentPageType_ === PageType.DETAIL) { - path = 'detail'; - } else if (this.currentPageType_ === PageType.NOTIFICATIONS) { - path = 'notifications'; - } - this.path_ = '/' + path; - }, - - /** @private */ - onUrlChanged_: function() { - this.debounce('parseUrl', this.parseUrl_); - }, - - /** @private */ - parseUrl_: function() { - const newId = this.queryParams_.id; - const searchTerm = this.queryParams_.q; - - const pageFromUrl = this.path_.substr(1).split('/')[0]; - let newPage = PageType.MAIN; - if (pageFromUrl === 'detail') { - newPage = PageType.DETAIL; - } else if (pageFromUrl === 'notifications') { - newPage = PageType.NOTIFICATIONS; - } else { - newPage = PageType.MAIN; - } - - if (newPage === PageType.DETAIL) { - this.dispatch(app_management.actions.changePage(PageType.DETAIL, newId)); - } else { - this.dispatch(app_management.actions.changePage(newPage)); - } - - if (searchTerm) { - this.dispatch(app_management.actions.setSearchTerm(searchTerm)); - } - this.urlParsed_ = true; - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/search_view.html b/chromium/chrome/browser/resources/app_management/search_view.html deleted file mode 100644 index c2d94266af7..00000000000 --- a/chromium/chrome/browser/resources/app_management/search_view.html +++ /dev/null @@ -1,43 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="app_item.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html"> - -<dom-module id="app-management-search-view"> - <template> - <style include="app-management-shared-css"> - #centered-message { - align-items: center; - color: #6e6e6e; - cursor: default; - display: flex; - font-size: 14px; - font-weight: 500; - height: 100%; - justify-content: center; - user-select: none; - white-space: nowrap; - } - - .app-management-item-arrow { - margin-inline-end: 8px; - padding: 12px; - } - </style> - <div class="card-container" hidden$="[[isEmptyList_(apps_)]]"> - <template is="dom-repeat" items="[[apps_]]"> - <app-management-app-item app="[[item]]"> - <cr-icon-button slot="right-content" - class="subpage-arrow app-management-item-arrow" actionable> - </cr-icon-button> - </app-management-app-item> - </template> - </div> - <div id="centered-message" - hidden$="[[!isEmptyList_(apps_)]]"> - $i18n{noSearchResults} - </div> - </template> - <script src="search_view.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/search_view.js b/chromium/chrome/browser/resources/app_management/search_view.js deleted file mode 100644 index b149e94e119..00000000000 --- a/chromium/chrome/browser/resources/app_management/search_view.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-search-view', - - behaviors: [ - app_management.StoreClient, - ], - - properties: { - /** - * List of apps returned from search results. - * @private {Array<App>} - */ - apps_: { - type: Array, - value: () => [], - }, - }, - - attached: function() { - this.watch('apps_', (state) => { - return state.search.results; - }); - }, - - /** - * Check whether there is search results. - * @param {Array<App>} apps - * @return {boolean} - * @private - */ - isEmptyList_: function(apps) { - if (!apps) { - return true; - } - return apps.length === 0; - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/shared_style.html b/chromium/chrome/browser/resources/app_management/shared_style.html deleted file mode 100644 index 57215df600e..00000000000 --- a/chromium/chrome/browser/resources/app_management/shared_style.html +++ /dev/null @@ -1,113 +0,0 @@ -<link rel="import" href="shared_vars.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"> - -<!-- Common styles for App Management. --> -<dom-module id="app-management-shared-css"> - <template> - <style include="cr-shared-style"> - .card-container { - @apply --cr-card-elevation; - background-color: #fff; - border-radius: var(--cr-card-border-radius); - display: flex; - flex-direction: column; - margin: 24px auto; - max-width: var(--card-max-width); - min-width: var(--card-min-width); - } - - .separated-row { - align-items: center; - display: inline-flex; - justify-content: space-between; - } - - .card-row { - border-top: var(--card-separator); - padding: 0 24px; - } - - .permission-card-row { - border-top: var(--card-separator); - padding: 0 24px; - } - - .clickable { - cursor: pointer; - } - - .permission-card-row:first-child { - border-style: none; - } - - .header-text { - color: var(--header-text-color); - font-weight: var(--header-font-weight); - } - - .permission-row-controls { - align-items: center; - display: inline-flex; - } - - .permission-list { - display: flex; - flex-direction: column; - } - - .permission-list > * { - flex: 0 0 var(--permission-list-item-height); - } - - .native-settings-icon { - display: flex; - margin-inline-start: 0; - } - - .subpermission-row { - height: 48px; - } - - .subpermission-list { - align-items: stretch; - display: flex; - flex-direction: column; - padding: 8px 0; - } - - .secondary-text { - color: var(--secondary-text-color); - font-weight: var(--secondary-font-weight); - } - - .expand-button { - height: 36px; - margin-inline-end: 12px; - width: 36px; - } - - .horizontal-align { - align-items: center; - display: flex; - } - - .expander-list-row { - align-items: center; - border-top: var(--card-separator); - color: var(--secondary-text-color); - display: flex; - height: 50px; - justify-content: space-between; - padding-inline-end: 8px; - padding-inline-start: 24px; - } - - .page-title { - flex: 1; - font-size: 16px; - overflow: hidden; - text-overflow: ellipsis; - } - </style> - </template> diff --git a/chromium/chrome/browser/resources/app_management/shared_vars.html b/chromium/chrome/browser/resources/app_management/shared_vars.html deleted file mode 100644 index d42cace22d1..00000000000 --- a/chromium/chrome/browser/resources/app_management/shared_vars.html +++ /dev/null @@ -1,27 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> - -<custom-style> -<style> - html { - --app-management-font-size: 13px; - --app-management-line-height: 1.54; /* 20px */ - --card-max-width: 676px; - --card-min-width: 550px; - --card-separator: 1px solid rgba(0, 0, 0, 0.12); - --control-separator-color: rgb(218, 220, 224); - --expanded-permission-row-height: 48px; - --header-font-weight: 500; - --header-text-color: #5A5A5A; - --permission-icon-color: #757575; - --permission-icon-padding: 12px; - --permission-list-item-height: 64px; - --primary-text-color: rgba(0, 0, 0, 0.87); - --row-item-icon-padding: 12px; - --secondary-font-weight: 400; - --secondary-text-color: rgba(0, 0, 0, 0.54); - } -</style> -</custom-style> diff --git a/chromium/chrome/browser/resources/app_management/store.html b/chromium/chrome/browser/resources/app_management/store.html deleted file mode 100644 index dd30152b65f..00000000000 --- a/chromium/chrome/browser/resources/app_management/store.html +++ /dev/null @@ -1,6 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<link rel="import" href="chrome://resources/html/cr/ui/store.html"> -<link rel="import" href="reducers.html"> -<link rel="import" href="util.html"> - -<script src="store.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/store.js b/chromium/chrome/browser/resources/app_management/store.js deleted file mode 100644 index 9790d51dae6..00000000000 --- a/chromium/chrome/browser/resources/app_management/store.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview A singleton datastore for the App Management page. Page state - * is publicly readable, but can only be modified by dispatching an Action to - * the store. - */ - -cr.define('app_management', function() { - class Store extends cr.ui.Store { - constructor() { - super( - app_management.util.createEmptyState(), app_management.reduceAction); - } - } - - cr.addSingletonGetter(Store); - - return { - Store: Store, - }; -}); diff --git a/chromium/chrome/browser/resources/app_management/store_client.html b/chromium/chrome/browser/resources/app_management/store_client.html deleted file mode 100644 index e7d72ccfd35..00000000000 --- a/chromium/chrome/browser/resources/app_management/store_client.html +++ /dev/null @@ -1,5 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<link rel="import" href="chrome://resources/html/cr/ui/store_client.html"> -<link rel="import" href="store.html"> - -<script src="store_client.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/store_client.js b/chromium/chrome/browser/resources/app_management/store_client.js deleted file mode 100644 index 0469381c537..00000000000 --- a/chromium/chrome/browser/resources/app_management/store_client.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Defines StoreClient, a Polymer behavior to tie a front-end - * element to back-end data from the store. - */ - -cr.define('app_management', function() { - /** - * @polymerBehavior - */ - const AppManagementStoreClientImpl = { - /** - * @param {string} localProperty - * @param {function(!AppManagementPageState)} valueGetter - */ - watch: function(localProperty, valueGetter) { - this.watch_(localProperty, valueGetter); - }, - - /** - * @return {AppManagementPageState} - */ - getState: function() { - return this.getStore().data; - }, - - /** - * @return {cr.ui.Store<AppManagementPageState>} - */ - getStore: function() { - return app_management.Store.getInstance(); - }, - }; - - /** - * @polymerBehavior - * @implements {cr.ui.StoreObserver} - */ - const StoreClient = [cr.ui.StoreClient, AppManagementStoreClientImpl]; - - return { - AppManagementStoreClientImpl: AppManagementStoreClientImpl, - StoreClient: StoreClient, - }; -}); diff --git a/chromium/chrome/browser/resources/app_management/toggle_row.html b/chromium/chrome/browser/resources/app_management/toggle_row.html deleted file mode 100644 index 8e2ccf129b8..00000000000 --- a/chromium/chrome/browser/resources/app_management/toggle_row.html +++ /dev/null @@ -1,55 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="browser_proxy.html"> -<link rel="import" href="shared_style.html"> -<link rel="import" href="store_client.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> - -<dom-module id="app-management-toggle-row"> - <template> - <style include="app-management-shared-css"> - :host { - align-items: center; - display: flex; - flex: 1; - justify-content: space-between; - } - - #icon { - padding-inline-end: var(--row-item-icon-padding); - } - - #policy-indicator { - fill: var(--google-grey-refresh-700); - padding-inline-end: 12px; - } - </style> - - <div id="left-content" class="horizontal-align"> - <template is="dom-if" if="[[icon_]]"> - <iron-icon id="icon" icon="[[icon_]]"></iron-icon> - </template> - <div id="label">[[label_]]</div> - </div> - <div id="right-content" class="horizontal-align"> - <iron-icon id="policy-indicator" - icon="cr:domain" - tabindex="0" - aria-describedby="tooltip" - hidden$="[[!managed_]]"> - </iron-icon> - <paper-tooltip id="tooltip" - for="policy-indicator" - position="top" - fit-to-visible-bounds> - [[policyLabel_]] - </paper-tooltip> - <cr-toggle id="toggle" - checked="[[value_]]" - disabled$="[[managed_]]"> - </cr-toggle> - </div> - </template> - <script src="toggle_row.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/app_management/toggle_row.js b/chromium/chrome/browser/resources/app_management/toggle_row.js deleted file mode 100644 index 16aff0bb109..00000000000 --- a/chromium/chrome/browser/resources/app_management/toggle_row.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -Polymer({ - is: 'app-management-toggle-row', - - properties: { - /** - * @type {string} - * @private - */ - icon_: String, - /** - * @type {string} - * @private - */ - label_: String, - /** - * @type {boolean} - * @private - */ - managed_: {type: Boolean, value: false, reflectToAttribute: true}, - /** - * @type {string} - * @private - */ - policyLabel_: String, - /** - * @type {boolean} - * @private - */ - value_: {type: Boolean, value: false, reflectToAttribute: true}, - }, -}); diff --git a/chromium/chrome/browser/resources/app_management/types.js b/chromium/chrome/browser/resources/app_management/types.js deleted file mode 100644 index 725836f9596..00000000000 --- a/chromium/chrome/browser/resources/app_management/types.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Closure typedefs for App Management. - */ - -/** - * @typedef {appManagement.mojom.App} - */ -let App; - -/** - * @typedef {appManagement.mojom.ExtensionAppPermissionMessage} - */ -let ExtensionAppPermissionMessage; - -/** - * @typedef {apps.mojom.Permission} - */ -let Permission; - -/** - * Maps app ids to Apps. - * @typedef {!Object<string, App>} - */ -let AppMap; - -/** - * @typedef {{ - * pageType: PageType, - * selectedAppId: ?string, - * }} - */ -let Page; - -/** - * @typedef {{ - * term: ?string, - * results: ?Array<App>, - * }} - */ -let SearchState; - -/** - * @typedef {{ - * allowedIds: !Set<string>, - * blockedIds: !Set<string>, - * }} - */ -let NotificationsState; - -/** - * @typedef {{ - * apps: !AppMap, - * currentPage: !Page, - * arcSupported: boolean, - * search: !SearchState, - * notifications: !NotificationsState, - * }} - */ -let AppManagementPageState; diff --git a/chromium/chrome/browser/resources/app_management/util.html b/chromium/chrome/browser/resources/app_management/util.html deleted file mode 100644 index d521fc5bd60..00000000000 --- a/chromium/chrome/browser/resources/app_management/util.html +++ /dev/null @@ -1,2 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<script src="util.js"></script> diff --git a/chromium/chrome/browser/resources/app_management/util.js b/chromium/chrome/browser/resources/app_management/util.js deleted file mode 100644 index 1e94d7cce9a..00000000000 --- a/chromium/chrome/browser/resources/app_management/util.js +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Utility functions for the App Management page. - */ - -cr.define('app_management.util', function() { - /** - * @return {!AppManagementPageState} - */ - function createEmptyState() { - return { - apps: {}, - currentPage: { - pageType: PageType.MAIN, - selectedAppId: null, - }, - arcSupported: false, - search: { - term: null, - results: null, - }, - notifications: { - allowedIds: new Set(), - blockedIds: new Set(), - }, - }; - } - - /** - * @param {!Array<App>} apps - * @return {!AppManagementPageState} - */ - function createInitialState(apps) { - const initialState = createEmptyState(); - - initialState.arcSupported = - loadTimeData.valueExists('isSupportedArcVersion') && - loadTimeData.getBoolean('isSupportedArcVersion'); - - for (const app of apps) { - initialState.apps[app.id] = app; - - const allowed = notificationsAllowed(app); - - if (allowed === OptionalBool.kUnknown) { - continue; - } - - if (allowed === OptionalBool.kTrue) { - initialState.notifications.allowedIds.add(app.id); - } else { - initialState.notifications.blockedIds.add(app.id); - } - } - - return initialState; - } - - /** - * @param {number} permissionId - * @param {!PermissionValueType} valueType - * @param {number} value - * @param {boolean} isManaged - * @return {!Permission} - */ - function createPermission(permissionId, valueType, value, isManaged) { - return { - permissionId, - valueType, - value, - isManaged, - }; - } - - /** - * @param {App} app - * @return {string} - */ - function getAppIcon(app) { - return `chrome://app-icon/${app.id}/128`; - } - - /** - * If the given value is not in the set, returns a new set with the value - * added, otherwise returns the old set. - * @template T - * @param {!Set<T>} set - * @param {T} value - * @return {!Set<T>} - */ - function addIfNeeded(set, value) { - if (!set.has(value)) { - set = new Set(set); - set.add(value); - } - return set; - } - - /** - * If the given value is in the set, returns a new set without the value, - * otherwise returns the old set. - * @template T - * @param {!Set<T>} set - * @param {T} value - * @return {!Set<T>} - */ - function removeIfNeeded(set, value) { - if (set.has(value)) { - set = new Set(set); - set.delete(value); - } - return set; - } - - /** - * This function determines whether the given app should be treated by the - * notifications view as having notifications allowed or blocked, or not - * having a notifications permission at all. - * - * There are three possible cases: - * - kUnknown is returned if the given app does not have a notifications - * permission, due to how permissions work for its AppType. - * - kTrue is returned if the notifications permission of the app is allowed. - * - kFalse is returned if the notifications permission of the app is - * - blocked, or set to ask in the case of a tristate permission. - * - * @param {App} app - * @return {OptionalBool} - */ - function notificationsAllowed(app) { - const permissionType = notificationsPermissionType(app); - - if (!permissionType) { - return OptionalBool.kUnknown; - } - - if (getPermissionValueBool(app, permissionType)) { - return OptionalBool.kTrue; - } else { - return OptionalBool.kFalse; - } - } - - /** - * Returns a string corresponding to the notifications value of the - * appropriate permission type enum, based on the type of the app. - * Returns null if the app type doesn't have a notifications permission. - * @param {App} app - * @return {?string} - */ - function notificationsPermissionType(app) { - switch (app.type) { - case AppType.kWeb: - return 'CONTENT_SETTINGS_TYPE_NOTIFICATIONS'; - // TODO(rekanorman): Add another case once notifications permissions - // are implemented for ARC. - default: - return null; - } - } - - /** - * @param {App} app - * @param {string} permissionType - * @return {boolean} - */ - function getPermissionValueBool(app, permissionType) { - const permission = getPermission(app, permissionType); - assert(permission); - - switch (permission.valueType) { - case PermissionValueType.kBool: - return permission.value === Bool.kTrue; - case PermissionValueType.kTriState: - return permission.value === TriState.kAllow; - default: - assertNotReached(); - } - } - - /** - * @param {App} app - * @param {string} permissionType - * @return {Permission} - */ - function getPermission(app, permissionType) { - return app.permissions[permissionTypeHandle(app, permissionType)]; - } - - /** - * @param {App} app - * @param {string} permissionType - * @return {number} - */ - function permissionTypeHandle(app, permissionType) { - switch (app.type) { - case AppType.kWeb: - return PwaPermissionType[permissionType]; - case AppType.kArc: - return ArcPermissionType[permissionType]; - default: - assertNotReached(); - } - } - - /** - * @param {AppManagementPageState} state - * @return {?App} - */ - function getSelectedApp(state) { - const selectedAppId = state.currentPage.selectedAppId; - return selectedAppId ? state.apps[selectedAppId] : null; - } - - /** - * A comparator function to sort strings alphabetically. - * - * @param {string} a - * @param {string} b - */ - function alphabeticalSort(a, b) { - return a.localeCompare(b); - } - - /** - * Toggles an OptionalBool - * - * @param {OptionalBool} bool - * @return {OptionalBool} - */ - function toggleOptionalBool(bool) { - switch (bool) { - case OptionalBool.kFalse: - return OptionalBool.kTrue; - case OptionalBool.kTrue: - return OptionalBool.kFalse; - default: - assertNotReached(); - } - } - - return { - addIfNeeded: addIfNeeded, - alphabeticalSort: alphabeticalSort, - createEmptyState: createEmptyState, - createInitialState: createInitialState, - createPermission: createPermission, - getAppIcon: getAppIcon, - getPermission: getPermission, - getPermissionValueBool: getPermissionValueBool, - getSelectedApp: getSelectedApp, - notificationsAllowed: notificationsAllowed, - notificationsPermissionType: notificationsPermissionType, - permissionTypeHandle: permissionTypeHandle, - removeIfNeeded: removeIfNeeded, - toggleOptionalBool: toggleOptionalBool, - }; -}); diff --git a/chromium/chrome/browser/resources/bluetooth_internals/BUILD.gn b/chromium/chrome/browser/resources/bluetooth_internals/BUILD.gn index 88abbb1f3ee..7ab5c808a39 100644 --- a/chromium/chrome/browser/resources/bluetooth_internals/BUILD.gn +++ b/chromium/chrome/browser/resources/bluetooth_internals/BUILD.gn @@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/grit/grit_rule.gni") js_type_check("closure_compile") { deps = [ @@ -41,3 +42,25 @@ js_library("bluetooth_internals") { "//ui/webui/resources/js/cr/ui/page_manager:page_manager", ] } + +grit("resources") { + source = "resources.grd" + + # The .grd contains references to generated files. + source_is_generated = true + outputs = [ + "grit/bluetooth_internals_resources.h", + "grit/bluetooth_internals_resources_map.h", + "grit/bluetooth_internals_resources_map.cc", + "bluetooth_internals_resources.pak", + ] + output_dir = "$root_gen_dir/chrome" + depfile_dir = target_gen_dir + grit_flags = [ + "-E", + "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir), + ] + deps = [ + "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js", + ] +} diff --git a/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js b/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js index 918c700cce3..0da84a773fe 100644 --- a/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js +++ b/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js @@ -7,12 +7,12 @@ * chrome://bluetooth-internals/. */ cr.define('adapter_broker', function() { - /** @typedef {bluetooth.mojom.AdapterProxy} */ - let AdapterProxy; - /** @typedef {bluetooth.mojom.DeviceProxy} */ - let DeviceProxy; - /** @typedef {bluetooth.mojom.DiscoverySessionProxy} */ - let DiscoverySessionProxy; + /** @typedef {bluetooth.mojom.AdapterRemote} */ + let AdapterRemote; + /** @typedef {bluetooth.mojom.DeviceRemote} */ + let DeviceRemote; + /** @typedef {bluetooth.mojom.DiscoverySessionRemote} */ + let DiscoverySessionRemote; /** * Enum of adapter property names. Used for adapterchanged events. @@ -29,18 +29,20 @@ cr.define('adapter_broker', function() { * The proxy class of an adapter and router of adapter events. * Exposes an EventTarget interface that allows other object to subscribe to * to specific AdapterClient events. - * Provides proxy access to Adapter functions. Converts parameters to Mojo + * Provides remote access to Adapter functions. Converts parameters to Mojo * handles and back when necessary. * * @implements {bluetooth.mojom.AdapterClientInterface} */ class AdapterBroker extends cr.EventTarget { - /** @param {!AdapterProxy} adapter */ + /** @param {!AdapterRemote} adapter */ constructor(adapter) { super(); - this.adapterClient_ = new bluetooth.mojom.AdapterClient(this); + this.adapterClientReceiver_ = + new bluetooth.mojom.AdapterClientReceiver(this); this.adapter_ = adapter; - this.adapter_.setClient(this.adapterClient_.$.createProxy()); + this.adapter_.setClient( + this.adapterClientReceiver_.$.bindNewPipeAndPassRemote()); } presentChanged(present) { @@ -135,7 +137,7 @@ cr.define('adapter_broker', function() { /** * Requests the adapter to start a new discovery session. - * @return {!Promise<!bluetooth.mojom.DiscoverySessionProxy>} + * @return {!Promise<!bluetooth.mojom.DiscoverySessionRemote>} */ startDiscoverySession() { return this.adapter_.startDiscoverySession().then(function(response) { @@ -161,7 +163,7 @@ cr.define('adapter_broker', function() { } const bluetoothInternalsHandler = - mojom.BluetoothInternalsHandler.getProxy(); + mojom.BluetoothInternalsHandler.getRemote(); // Get an Adapter service. return bluetoothInternalsHandler.getAdapter().then(function(response) { diff --git a/chromium/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js b/chromium/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js index 12521d2de95..de4b6d0a4d9 100644 --- a/chromium/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js +++ b/chromium/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js @@ -30,7 +30,7 @@ cr.define('bluetooth_internals', function() { /** @type {devices_page.DevicesPage} */ let devicesPage = null; - /** @type {bluetooth.mojom.DiscoverySessionProxy} */ + /** @type {bluetooth.mojom.DiscoverySessionRemote} */ let discoverySession = null; /** @type {boolean} */ diff --git a/chromium/chrome/browser/resources/bluetooth_internals/device_broker.js b/chromium/chrome/browser/resources/bluetooth_internals/device_broker.js index e166d114d56..3c417d9f7ce 100644 --- a/chromium/chrome/browser/resources/bluetooth_internals/device_broker.js +++ b/chromium/chrome/browser/resources/bluetooth_internals/device_broker.js @@ -4,15 +4,15 @@ /** * Javascript for device_broker, served from chrome://bluetooth-internals/. - * Provides a single source to access DeviceProxys. DeviceProxys are cached for + * Provides a single source to access DeviceRemotes. DeviceRemotes are cached * for repeated use. Multiple connection requests will result in the same - * DeviceProxy being shared among all requesters. + * DeviceRemote being shared among all requesters. */ // Expose for testing. /** * @type {?Map<string, - * !bluetooth.mojom.DeviceProxy|!Promise<!bluetooth.mojom.DeviceProxy>>} + * !bluetooth.mojom.DeviceRemote|!Promise<!bluetooth.mojom.DeviceRemote>>} */ let connectedDevices = null; @@ -22,10 +22,10 @@ cr.define('device_broker', function() { /** * Creates a GATT connection to the device with |address|. If a connection to * the device already exists, the promise is resolved with the existing - * DeviceProxy. If a connection is in progress, the promise resolves when + * DeviceRemote. If a connection is in progress, the promise resolves when * the existing connection request promise is fulfilled. * @param {string} address - * @return {!Promise<!bluetooth.mojom.DeviceProxy>} + * @return {!Promise<!bluetooth.mojom.DeviceRemote>} */ function connectToDevice(address) { const deviceOrPromise = connectedDevices.get(address) || null; @@ -33,7 +33,7 @@ cr.define('device_broker', function() { return Promise.resolve(deviceOrPromise); } - const promise = /** @type {!Promise<!bluetooth.mojom.DeviceProxy>} */ ( + const promise = /** @type {!Promise<!bluetooth.mojom.DeviceRemote>} */ ( adapter_broker.getAdapterBroker() .then(function(adapterBroker) { return adapterBroker.connectToDevice(address); diff --git a/chromium/chrome/browser/resources/bluetooth_internals/device_details_page.js b/chromium/chrome/browser/resources/bluetooth_internals/device_details_page.js index 0a2f977ed75..876d45e68ec 100644 --- a/chromium/chrome/browser/resources/bluetooth_internals/device_details_page.js +++ b/chromium/chrome/browser/resources/bluetooth_internals/device_details_page.js @@ -46,8 +46,8 @@ cr.define('device_details_page', function() { /** @type {?Array<bluetooth.mojom.ServiceInfo>} */ this.services = null; - /** @private {?bluetooth.mojom.DeviceProxy} */ - this.deviceProxy_ = null; + /** @private {?bluetooth.mojom.DeviceRemote} */ + this.device_ = null; /** @private {!object_fieldset.ObjectFieldSet} */ this.deviceFieldSet_ = new object_fieldset.ObjectFieldSet(); @@ -81,7 +81,7 @@ cr.define('device_details_page', function() { this.connectBtn_ = this.pageDiv.querySelector('.disconnect'); this.connectBtn_.addEventListener('click', function() { - this.deviceProxy_ !== null ? this.disconnect() : this.connect(); + this.device_ !== null ? this.disconnect() : this.connect(); }.bind(this)); this.redraw(); @@ -97,14 +97,14 @@ cr.define('device_details_page', function() { device_collection.ConnectionStatus.CONNECTING); device_broker.connectToDevice(this.deviceInfo.address) - .then(function(deviceProxy) { - this.deviceProxy_ = deviceProxy; + .then(function(device) { + this.device_ = device; this.updateConnectionStatus_( device_collection.ConnectionStatus.CONNECTED); // Fetch services asynchronously. - return this.deviceProxy_.getServices(); + return this.device_.getServices(); }.bind(this)) .then(function(response) { this.services = response.services; @@ -114,10 +114,10 @@ cr.define('device_details_page', function() { }.bind(this)) .catch(function(error) { // If a connection error occurs while fetching the services, the - // DeviceProxy reference must be removed. - if (this.deviceProxy_) { - this.deviceProxy_.disconnect(); - this.deviceProxy_ = null; + // DeviceRemote reference must be removed. + if (this.device_) { + this.device_.disconnect(); + this.device_ = null; } Snackbar.show( @@ -131,12 +131,12 @@ cr.define('device_details_page', function() { /** Disconnects the page from the Bluetooth device. */ disconnect() { - if (!this.deviceProxy_) { + if (!this.device_) { return; } - this.deviceProxy_.disconnect(); - this.deviceProxy_ = null; + this.device_.disconnect(); + this.device_ = null; this.updateConnectionStatus_( device_collection.ConnectionStatus.DISCONNECTED); } diff --git a/chromium/chrome/browser/resources/bluetooth_internals/resources.grd b/chromium/chrome/browser/resources/bluetooth_internals/resources.grd new file mode 100644 index 00000000000..786dc15be70 --- /dev/null +++ b/chromium/chrome/browser/resources/bluetooth_internals/resources.grd @@ -0,0 +1,115 @@ +<?xml version="1.0" encoding="UTF-8"?> +<grit latest_public_release="0" + current_release="1" + output_all_resource_defines="false"> + <outputs> + <output filename="grit/bluetooth_internals_resources.h" + type="rc_header"> + <emit emit_type='prepend'></emit> + </output> + <output filename="grit/bluetooth_internals_resources_map.cc" + type="resource_file_map_source" /> + <output filename="grit/bluetooth_internals_resources_map.h" + type="resource_map_header" /> + <output filename="bluetooth_internals_resources.pak" + type="data_package" /> + </outputs> + <release seq="1"> + <includes> + <include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_BROKER_JS" + file="adapter_broker.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_MOJO_JS" + file="${root_gen_dir}\device\bluetooth\public\mojom\adapter.mojom-lite.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_PAGE_JS" + file="adapter_page.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_CHARACTERISTIC_LIST_JS" + file="characteristic_list.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_CSS" + file="bluetooth_internals.css" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DESCRIPTOR_LIST_JS" + file="descriptor_list.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_BROKER_JS" + file="device_broker.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_COLLECTION_JS" + file="device_collection.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_DETAILS_PAGE_JS" + file="device_details_page.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_MOJO_JS" + file="${root_gen_dir}\device\bluetooth\public\mojom\device.mojom-lite.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DEVICE_TABLE_JS" + file="device_table.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_DEVICES_PAGE_JS" + file="devices_page.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_EXPANDABLE_LIST_JS" + file="expandable_list.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_HTML" + file="bluetooth_internals.html" + flattenhtml="true" + allowexternalscript="true" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_JS" + file="bluetooth_internals.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_MOJO_JS" + file="${root_gen_dir}\chrome\browser\ui\webui\bluetooth_internals\bluetooth_internals.mojom-lite.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_OBJECT_FIELDSET_JS" + file="object_fieldset.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_SERVICE_LIST_JS" + file="service_list.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_SIDEBAR_JS" + file="sidebar.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_SNACKBAR_JS" + file="snackbar.js" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_UUID_MOJO_JS" + file="${root_gen_dir}\device\bluetooth\public\mojom\uuid.mojom-lite.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_BLUETOOTH_INTERNALS_VALUE_CONTROL_JS" + file="value_control.js" + type="BINDATA" + compress="gzip" /> + </includes> + </release> +</grit> diff --git a/chromium/chrome/browser/resources/bookmarks/command_manager.js b/chromium/chrome/browser/resources/bookmarks/command_manager.js index a1675b32d14..3d83ab732f6 100644 --- a/chromium/chrome/browser/resources/bookmarks/command_manager.js +++ b/chromium/chrome/browser/resources/bookmarks/command_manager.js @@ -214,7 +214,11 @@ cr.define('bookmarks', function() { isCommandVisible_: function(command, itemIds) { switch (command) { case Command.EDIT: + case Command.PASTE: return itemIds.size == 1 && this.globalCanEdit_; + case Command.CUT: + case Command.COPY: + return itemIds.size >= 1 && this.globalCanEdit_; case Command.COPY_URL: return this.isSingleBookmark_(itemIds); case Command.DELETE: @@ -269,6 +273,8 @@ cr.define('bookmarks', function() { return this.canChangeList_(); case Command.IMPORT: return this.globalCanEdit_; + case Command.PASTE: + return true; // TODO(hcarmona): Add check for CanPasteFromClipboard. default: return true; } @@ -613,9 +619,18 @@ cr.define('bookmarks', function() { const itemUrl = this.getState().nodes[id].url; label = itemUrl ? 'menuEdit' : 'menuRename'; break; + case Command.CUT: + label = 'menuCut'; + break; + case Command.COPY: + label = 'menuCopy'; + break; case Command.COPY_URL: label = 'menuCopyURL'; break; + case Command.PASTE: + label = 'menuPaste'; + break; case Command.DELETE: label = 'menuDelete'; break; @@ -681,10 +696,14 @@ cr.define('bookmarks', function() { case MenuSource.TREE: return [ Command.EDIT, - Command.COPY_URL, Command.SHOW_IN_FOLDER, Command.DELETE, // <hr> + Command.CUT, + Command.COPY, + Command.COPY_URL, + Command.PASTE, + // <hr> Command.OPEN_NEW_TAB, Command.OPEN_NEW_WINDOW, Command.OPEN_INCOGNITO, @@ -732,11 +751,17 @@ cr.define('bookmarks', function() { * @private */ showDividerAfter_: function(command, itemIds) { - return ((command == Command.SORT || command == Command.ADD_FOLDER || - command == Command.EXPORT) && - this.menuSource_ == MenuSource.TOOLBAR) || - (command == Command.DELETE && - (this.globalCanEdit_ || this.isSingleBookmark_(itemIds))); + switch (command) { + case Command.SORT: + case Command.ADD_FOLDER: + case Command.EXPORT: + return this.menuSource_ == MenuSource.TOOLBAR; + case Command.DELETE: + return this.globalCanEdit_; + case Command.PASTE: + return this.globalCanEdit_ || this.isSingleBookmark_(itemIds); + } + return false; }, /** diff --git a/chromium/chrome/browser/resources/bookmarks/folder_node.html b/chromium/chrome/browser/resources/bookmarks/folder_node.html index bfb8b4da408..4c57f2ad54d 100644 --- a/chromium/chrome/browser/resources/bookmarks/folder_node.html +++ b/chromium/chrome/browser/resources/bookmarks/folder_node.html @@ -24,7 +24,7 @@ height: 40px; min-width: fit-content; overflow: hidden; - padding-inline-start: calc(var(--node-depth, 0) * 10px); + padding-inline-start: calc(var(--node-depth, 0) * 15px); } #arrow { diff --git a/chromium/chrome/browser/resources/bookmarks/folder_node.js b/chromium/chrome/browser/resources/bookmarks/folder_node.js index dea00a6ebae..a540184a601 100644 --- a/chromium/chrome/browser/resources/bookmarks/folder_node.js +++ b/chromium/chrome/browser/resources/bookmarks/folder_node.js @@ -79,10 +79,7 @@ Polymer({ this.updateFromStore(); }, - /** - * Overriden from bookmarks.MouseFocusBehavior. - * @return {!HTMLElement} - */ + /** @return {!HTMLElement} */ getFocusTarget: function() { return this.$.container; }, diff --git a/chromium/chrome/browser/resources/bookmarks/item.html b/chromium/chrome/browser/resources/bookmarks/item.html index c4fc5e0d617..9191430e622 100644 --- a/chromium/chrome/browser/resources/bookmarks/item.html +++ b/chromium/chrome/browser/resources/bookmarks/item.html @@ -107,7 +107,8 @@ id="menuButton" tabindex="[[ironListTabIndex]]" title="$i18n{moreActionsButtonTitle}" - aria-label$="[[getButtonAriaLabel_(item_)]]" + aria-label$="[[getButtonAriaLabel_(item_, isSelectedItem_, + isMultiSelect_)]]" on-click="onMenuButtonClick_" aria-haspopup="menu"></cr-icon-button> </template> diff --git a/chromium/chrome/browser/resources/bookmarks/item.js b/chromium/chrome/browser/resources/bookmarks/item.js index f013a78094c..e2f0aa78f08 100644 --- a/chromium/chrome/browser/resources/bookmarks/item.js +++ b/chromium/chrome/browser/resources/bookmarks/item.js @@ -36,6 +36,9 @@ Polymer({ }, /** @private */ + isMultiSelect_: Boolean, + + /** @private */ isFolder_: Boolean, /** @private */ @@ -66,6 +69,7 @@ Polymer({ this.watch('item_', store => store.nodes[this.itemId]); this.watch( 'isSelectedItem_', store => store.selection.items.has(this.itemId)); + this.watch('isMultiSelect_', store => store.selection.items.size > 1); this.updateFromStore(); }, @@ -113,7 +117,12 @@ Polymer({ onMenuButtonClick_: function(e) { e.stopPropagation(); e.preventDefault(); - this.selectThisItem_(); + + // Skip selecting the item if this item is part of a multi-selected group. + if (!this.isMultiSelectMenu_()) { + this.selectThisItem_(); + } + this.fire('open-command-menu', { targetElement: e.target, source: MenuSource.ITEM, @@ -248,12 +257,32 @@ Polymer({ updateFavicon_: function(url) { this.$.icon.className = url ? 'website-icon' : 'folder-icon'; this.$.icon.style.backgroundImage = - url ? cr.icon.getFavicon(url, false) : null; + url ? cr.icon.getFaviconForPageURL(url, false) : null; }, - /** @private */ + /** + * @return {string} + * @private + */ getButtonAriaLabel_: function() { + if (!this.item_) { + return ''; // Item hasn't loaded, skip for now. + } + + if (this.isMultiSelectMenu_()) { + return loadTimeData.getStringF('moreActionsMultiButtonAxLabel'); + } + return loadTimeData.getStringF( 'moreActionsButtonAxLabel', this.item_.title); - } + }, + + /** + * This item is part of a group selection. + * @return {boolean} + * @private + */ + isMultiSelectMenu_: function() { + return this.isSelectedItem_ && this.isMultiSelect_; + }, }); diff --git a/chromium/chrome/browser/resources/bookmarks/shared_style.html b/chromium/chrome/browser/resources/bookmarks/shared_style.html index 22bfc62568e..723f2db2e60 100644 --- a/chromium/chrome/browser/resources/bookmarks/shared_style.html +++ b/chromium/chrome/browser/resources/bookmarks/shared_style.html @@ -56,6 +56,9 @@ .folder-icon { content: url(chrome://theme/IDR_FOLDER_CLOSED); + height: 20px; + min-width: 20px; + width: 20px; } <if expr="is_macosx or is_ios"> diff --git a/chromium/chrome/browser/resources/cast/OWNERS b/chromium/chrome/browser/resources/cast/OWNERS deleted file mode 100644 index 5b34f4712ed..00000000000 --- a/chromium/chrome/browser/resources/cast/OWNERS +++ /dev/null @@ -1 +0,0 @@ -sheretov@chromium.org diff --git a/chromium/chrome/browser/resources/cast/cast.css b/chromium/chrome/browser/resources/cast/cast.css deleted file mode 100644 index 5193f40523b..00000000000 --- a/chromium/chrome/browser/resources/cast/cast.css +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright 2016 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -body, -extensionview, -html { - border: 0; - height: 100%; - margin: 0; - padding: 0; - width: 100%; -} - -extensionview { - overflow: hidden; - position: absolute; -} diff --git a/chromium/chrome/browser/resources/cast/cast.html b/chromium/chrome/browser/resources/cast/cast.html index 4510540eb9f..8247cee9ee7 100644 --- a/chromium/chrome/browser/resources/cast/cast.html +++ b/chromium/chrome/browser/resources/cast/cast.html @@ -3,13 +3,10 @@ <head> <meta charset="utf-8"> <title>Google Cast</title> - <link rel="stylesheet" href="cast.css"> - <link rel="shortcut icon" href="cast_favicon.ico"> <script src="chrome://resources/js/load_time_data.js"></script> <script src="strings.js"></script> <script src="cast.js"></script> </head> <body> - <extensionview></extensionview> </body> </html> diff --git a/chromium/chrome/browser/resources/cast/cast.js b/chromium/chrome/browser/resources/cast/cast.js index 3cb9c1473de..75a7afbf4f6 100644 --- a/chromium/chrome/browser/resources/cast/cast.js +++ b/chromium/chrome/browser/resources/cast/cast.js @@ -2,37 +2,5 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.addEventListener('load', function init() { - const extensionView = document.querySelector('extensionview'); - - /** - * @param {string} str - * @return {!Array<string>} - */ - const splitUrlOnHash = function(str) { - str = str || ''; - const pos = str.indexOf('#'); - return (pos !== -1) ? [str.substr(0, pos), str.substr(pos + 1)] : [str, '']; - }; - - new MutationObserver(function() { - const newHash = splitUrlOnHash(extensionView.getAttribute('src'))[1]; - const oldHash = window.location.hash.substr(1); - if (newHash !== oldHash) { - window.location.hash = newHash; - } - }).observe(extensionView, {attributes: true}); - - window.addEventListener('hashchange', function() { - const newHash = window.location.hash.substr(1); - const extensionViewSrcParts = - splitUrlOnHash(extensionView.getAttribute('src')); - if (newHash !== extensionViewSrcParts[1] && newHash.startsWith('offers')) { - extensionView.load(extensionViewSrcParts[0] + '#' + newHash); - } - }); - - extensionView.load( - 'chrome-extension://' + loadTimeData.getString('extensionId') + - '/cast_setup/index.html#offers'); -}); +window.location = 'chrome-extension://' + + loadTimeData.getString('extensionId') + '/cast_setup/index.html#offers'; diff --git a/chromium/chrome/browser/resources/cast/cast_favicon.ico b/chromium/chrome/browser/resources/cast/cast_favicon.ico Binary files differdeleted file mode 100644 index 7f72553e0e8..00000000000 --- a/chromium/chrome/browser/resources/cast/cast_favicon.ico +++ /dev/null diff --git a/chromium/chrome/browser/resources/chromeos/BUILD.gn b/chromium/chrome/browser/resources/chromeos/BUILD.gn index 72b6c86c832..6d5a60739fa 100644 --- a/chromium/chrome/browser/resources/chromeos/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/BUILD.gn @@ -47,7 +47,7 @@ grit("camera_resources") { output_dir = "$root_gen_dir/chrome" deps = [ - "//media/capture/video/chromeos/mojo:cros_camera_js", + "//media/capture/video/chromeos/mojom:cros_camera_js", ] # The .grd contains references to generated files. diff --git a/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn index 813d058f946..d41c627794d 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn @@ -158,6 +158,8 @@ copy("chrome_camera_app_js_models") { "src/js/models/filenamer.js", "src/js/models/filesystem.js", "src/js/models/gallery.js", + "src/js/models/result_saver.js", + "src/js/models/video_saver.js", ] outputs = [ @@ -167,7 +169,8 @@ copy("chrome_camera_app_js_models") { copy("chrome_camera_app_js_mojo") { sources = [ - "src/js/mojo/imagecapture.js", + "src/js/mojo/device_operator.js", + "src/js/mojo/image_capture.js", ] outputs = [ @@ -232,17 +235,21 @@ copy("chrome_camera_app_views") { copy("chrome_camera_app_mojo_generated") { sources = [ "$root_gen_dir/media/capture/mojom/image_capture.mojom-lite.js", - "$root_gen_dir/media/capture/video/chromeos/mojo/camera_common.mojom-lite.js", - "$root_gen_dir/media/capture/video/chromeos/mojo/camera_metadata.mojom-lite.js", - "$root_gen_dir/media/capture/video/chromeos/mojo/camera_metadata_tags.mojom-lite.js", - "$root_gen_dir/media/capture/video/chromeos/mojo/cros_image_capture.mojom-lite.js", + "$root_gen_dir/media/capture/video/chromeos/mojom/camera_app.mojom-lite.js", + "$root_gen_dir/media/capture/video/chromeos/mojom/camera_common.mojom-lite.js", + "$root_gen_dir/media/capture/video/chromeos/mojom/camera_metadata.mojom-lite.js", + "$root_gen_dir/media/capture/video/chromeos/mojom/camera_metadata_tags.mojom-lite.js", "$root_gen_dir/mojo/public/js/mojo_bindings_lite.js", + "$root_gen_dir/ui/gfx/geometry/mojom/geometry.mojom-lite.js", + "$root_gen_dir/ui/gfx/range/mojom/range.mojom-lite.js", ] deps = [ "//media/capture/mojom:image_capture_js", - "//media/capture/video/chromeos/mojo:cros_camera_js", + "//media/capture/video/chromeos/mojom:cros_camera_js", "//mojo/public/js:bindings_lite", + "//ui/gfx/geometry/mojom:mojom_js", + "//ui/gfx/range/mojom:mojom_js", ] outputs = [ diff --git a/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd b/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd index 0f24c24ff64..0a9ac124ab1 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd +++ b/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd @@ -18,6 +18,7 @@ <structure name="IDR_CAMERA_CAMERA3_DEVICE_INFO_JS" file="src/js/device/camera3_device_info.js" type="chrome_html" /> <structure name="IDR_CAMERA_CAMERA_JS" file="src/js/views/camera.js" type="chrome_html" /> <structure name="IDR_CAMERA_CONSTRAINTS_PREFERRER_JS" file="src/js/device/constraints_preferrer.js" type="chrome_html" /> + <structure name="IDR_CAMERA_DEVICE_OPERATOR_JS" file="src/js/mojo/device_operator.js" type="chrome_html" /> <structure name="IDR_CAMERA_DEVICE_INFO_UPDATER_JS" file="src/js/device/device_info_updater.js" type="chrome_html" /> <structure name="IDR_CAMERA_DIALOG_JS" file="src/js/views/dialog.js" type="chrome_html" /> <structure name="IDR_CAMERA_FILENAMER_JS" file="src/js/models/filenamer.js" type="chrome_html" /> @@ -25,7 +26,7 @@ <structure name="IDR_CAMERA_GALLERY_BASE_JS" file="src/js/views/gallery_base.js" type="chrome_html" /> <structure name="IDR_CAMERA_GALLERY_JS" file="src/js/models/gallery.js" type="chrome_html" /> <structure name="IDR_CAMERA_GALLERYBUTTON_JS" file="src/js/gallerybutton.js" type="chrome_html" /> - <structure name="IDR_CAMERA_IMAGECAPTURE_JS" file="src/js/mojo/imagecapture.js" type="chrome_html" /> + <structure name="IDR_CAMERA_IMAGECAPTURE_JS" file="src/js/mojo/image_capture.js" type="chrome_html" /> <structure name="IDR_CAMERA_LAYOUT_JS" file="src/js/views/camera/layout.js" type="chrome_html" /> <structure name="IDR_CAMERA_MAIN_CSS" file="src/css/main.css" type="chrome_html" /> <structure name="IDR_CAMERA_MAIN_HTML" file="src/views/main.html" type="chrome_html" /> @@ -38,6 +39,7 @@ <structure name="IDR_CAMERA_PREVIEW_JS" file="src/js/views/camera/preview.js" type="chrome_html" /> <structure name="IDR_CAMERA_RECORDTIME_JS" file="src/js/views/camera/recordtime.js" type="chrome_html" /> <structure name="IDR_CAMERA_RESOLUTION_EVENT_BROKER_JS" file="src/js/resolution_event_broker.js" type="chrome_html" /> + <structure name="IDR_CAMERA_RESULT_SAVER_JS" file="src/js/models/result_saver.js" type="chrome_html" /> <structure name="IDR_CAMERA_SCROLLBAR_JS" file="src/js/scrollbar.js" type="chrome_html" /> <structure name="IDR_CAMERA_SETTINGS_JS" file="src/js/views/settings.js" type="chrome_html" /> <structure name="IDR_CAMERA_SOUND_JS" file="src/js/sound.js" type="chrome_html" /> @@ -46,6 +48,7 @@ <structure name="IDR_CAMERA_TOAST_JS" file="src/js/toast.js" type="chrome_html" /> <structure name="IDR_CAMERA_TOOLTIP_JS" file="src/js/tooltip.js" type="chrome_html" /> <structure name="IDR_CAMERA_UTIL_JS" file="src/js/util.js" type="chrome_html" /> + <structure name="IDR_CAMERA_VIDEO_SAVER_JS" file="src/js/models/video_saver.js" type="chrome_html" /> <structure name="IDR_CAMERA_VIEW_JS" file="src/js/views/view.js" type="chrome_html" /> <structure name="IDR_CAMERA_WARNING_JS" file="src/js/views/warning.js" type="chrome_html" /> <structure name="IDR_CAMERA_WEBUI_BROWSER_PROXY" file="src/js/browser_proxy/webui_browser_proxy.js" type="chrome_html" /> @@ -57,19 +60,19 @@ use_base_dir="false" type="BINDATA"/> <include name="IDR_CAMERA_CAMERA_COMMON_MOJOM_LITE_JS" - file="${root_gen_dir}/media/capture/video/chromeos/mojo/camera_common.mojom-lite.js" + file="${root_gen_dir}/media/capture/video/chromeos/mojom/camera_common.mojom-lite.js" use_base_dir="false" type="BINDATA"/> <include name="IDR_CAMERA_CAMERA_METADATA_MOJOM_LITE_JS" - file="${root_gen_dir}/media/capture/video/chromeos/mojo/camera_metadata.mojom-lite.js" + file="${root_gen_dir}/media/capture/video/chromeos/mojom/camera_metadata.mojom-lite.js" use_base_dir="false" type="BINDATA"/> <include name="IDR_CAMERA_CAMERA_METADATA_TAGS_MOJOM_LITE_JS" - file="${root_gen_dir}/media/capture/video/chromeos/mojo/camera_metadata_tags.mojom-lite.js" + file="${root_gen_dir}/media/capture/video/chromeos/mojom/camera_metadata_tags.mojom-lite.js" use_base_dir="false" type="BINDATA"/> - <include name="IDR_CAMERA_CROS_IMAGE_CAPTURE_MOJOM_LITE_JS" - file="${root_gen_dir}/media/capture/video/chromeos/mojo/cros_image_capture.mojom-lite.js" + <include name="IDR_CAMERA_APP_MOJOM_LITE_JS" + file="${root_gen_dir}/media/capture/video/chromeos/mojom/camera_app.mojom-lite.js" use_base_dir="false" type="BINDATA"/> diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json b/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json index 5a9f048411f..cf3600060c5 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json +++ b/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json @@ -45,6 +45,10 @@ "message": "Nothing recorded", "description": "Error message shown when no data is recorded for a recording and it won't be added to the gallery." }, + "ERROR_MSG_EXPERT_MODE_NOT_SUPPORTED": { + "message": "Expert mode is not supported on this device", + "description": "Error message when the device does not support expert mode but tries to enable it." + }, "STATUS_MSG_RECORDING_STOPPED": { "message": "Recording stopped", "description": "Status message for spoken feedback when video recording has been stopped." @@ -103,6 +107,18 @@ "message": "Camera resolution", "description": "Label for the button of camera resolution options." }, + "EXPERT_MODE_BUTTON": { + "message": "Expert mode", + "description": "Label for the button of expert mode options." + }, + "EXPERT_PREVIEW_METADATA": { + "message": "Preview metadata", + "description": "Label for expert mode option: preview metadata." + }, + "EXPERT_SAVE_METADATA": { + "message": "Save metadata", + "description": "Label for expert mode option: save metadata." + }, "FEEDBACK_BUTTON": { "message": "Send feedback", "description": "Label for the feedback button." diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn index 7a0dd53b11e..059505eb02c 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn @@ -11,13 +11,16 @@ group("closure_compile") { "device:closure_compile", "models:closure_compile", "mojo:closure_compile", + "views:closure_compile", ] } js_type_check("compile_resources") { deps = [ + ":nav", ":resolution_event_broker", ":state", + ":toast", ":tooltip", ":util", ] @@ -26,9 +29,22 @@ js_type_check("compile_resources") { js_library("resolution_event_broker") { } +js_library("nav") { + deps = [ + "mojo:device_operator", + "views:view", + ] +} + js_library("state") { } +js_library("toast") { + deps = [ + ":util", + ] +} + js_library("tooltip") { } diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn index 013d454061a..cc01ba9b370 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn @@ -14,22 +14,23 @@ js_type_check("closure_compile") { js_library("camera3_device_info") { deps = [ - "../mojo:imagecapture", + "../mojo:image_capture", ] } js_library("constraints_preferrer") { deps = [ + ":camera3_device_info", "..:resolution_event_broker", + "..:state", "../browser_proxy:browser_proxy", ] } js_library("device_info_updater") { deps = [ - "..:state", - "../mojo:imagecapture", ":camera3_device_info", ":constraints_preferrer", + "..:state", ] } diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn index 89ebf568fe6..db0f77e3e3f 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn @@ -9,6 +9,8 @@ js_type_check("closure_compile") { ":filenamer", ":filesystem", ":gallery", + ":result_saver", + ":video_saver", ] } @@ -26,3 +28,9 @@ js_library("gallery") { ":filesystem", ] } + +js_library("result_saver") { +} + +js_library("video_saver") { +} diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn index 9d131abf33c..3be85b7f5c2 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn @@ -6,14 +6,23 @@ import("//third_party/closure_compiler/compile_js.gni") js_type_check("closure_compile") { deps = [ - ":imagecapture", + ":device_operator", + ":image_capture", ] } -js_library("imagecapture") { +js_library("device_operator") { deps = [ + "//media/capture/video/chromeos/mojom:cros_camera_js_library_for_compile", + ] + externs_list = [ "$externs_path/pending.js" ] +} + +js_library("image_capture") { + deps = [ + ":device_operator", + "..:util", "//media/capture/mojom:image_capture_js_library_for_compile", - "//media/capture/video/chromeos/mojo:cros_camera_js_library_for_compile", ] externs_list = [ "$externs_path/pending.js" ] } diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn new file mode 100644 index 00000000000..84560373b2c --- /dev/null +++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +group("closure_compile") { + deps = [ + ":compile_resources", + ] +} + +js_type_check("compile_resources") { + deps = [ + ":view", + ] +} + +js_library("view") { + deps = [ + "..:toast", + ] +} diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd b/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd index 834cc2109d1..299d99fff8c 100644 --- a/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd +++ b/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd @@ -222,6 +222,18 @@ <message desc="Label for the checkbox to toggle the microphone for recording video." name="IDS_TOGGLE_MIC_BUTTON"> Microphone </message> + <message desc="Label for the button of expert mode options." name="IDS_EXPERT_MODE_BUTTON"> + Expert mode + </message> + <message desc="Label for expert mode option: preview metadata." name="IDS_EXPERT_PREVIEW_METADATA"> + Preview metadata + </message> + <message desc="Label for expert mode option: save metadata." name="IDS_EXPERT_SAVE_METADATA"> + Save metadata + </message> + <message desc="Error message when the device does not support expert mode but tries to enable it." name="IDS_ERROR_MSG_EXPERT_MODE_NOT_SUPPORTED"> + Expert mode is not supported on this device + </message> <message desc="Label for the feedback button." name="IDS_FEEDBACK_BUTTON"> Send feedback </message> diff --git a/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn b/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn index 32d9da3e2e8..39bba1fa5d9 100644 --- a/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn @@ -146,6 +146,7 @@ chromevox_modules = [ "cvox2/background/live_regions.js", "cvox2/background/log.js", "cvox2/background/log_store.js", + "cvox2/background/log_types.js", "cvox2/background/math_handler.js", "cvox2/background/media_automation_handler.js", "cvox2/background/mouse_handler.js", 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 83d4ec0c1ad..2028ad38ee8 100644 --- a/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd +++ b/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd @@ -2971,25 +2971,18 @@ If you're done with the tutorial, use ChromeVox to navigate to the Close button <message desc="Description of a command that toggles between 6 and 8 dot braille." name="IDS_CHROMEVOX_TOGGLE_BRAILLE_TABLE"> Toggle between 6 and 8 dot braille </message> - <message desc="Spoken when a user navigates to the beginning of a misspelled word." name="IDS_CHROMEVOX_MISSPELLING_START"> - Misspelling start + <message desc="Spoken when a user navigates into a misspelled word." name="IDS_CHROMEVOX_MISSPELLING_START"> + Misspelled </message> - <message desc="Spoken when a user navigates to the end of a misspelled word." name="IDS_CHROMEVOX_MISSPELLING_END"> - Misspelling end + <message desc="Spoken when a user navigates out of a misspelled word." name="IDS_CHROMEVOX_MISSPELLING_END"> + Leaving misspelled </message> - <message desc="Spoken when a user navigates to the beginning of a grammar error." name="IDS_CHROMEVOX_GRAMMAR_START"> - Grammar error start + <message desc="Spoken when a user navigates into a grammar error." name="IDS_CHROMEVOX_GRAMMAR_START"> + Grammar error </message> - <message desc="Spoken when a user navigates to the end of a grammar error." name="IDS_CHROMEVOX_GRAMMAR_END"> - Grammar error end + <message desc="Spoken when a user navigates out of a grammar error." name="IDS_CHROMEVOX_GRAMMAR_END"> + Leaving grammar error </message> - <message desc="Spoken when a user navigates to the beginning of a text match from a find in page." name="IDS_CHROMEVOX_TEXT_MATCH_START"> - Text match start - </message> - <message desc="Spoken when a user navigates to the end of a text match from a find in page." name="IDS_CHROMEVOX_TEXT_MATCH_END"> - Text match end - </message> - <message desc="Spoken to describe text that is superscript." name="IDS_CHROMEVOX_SUPERSCRIPT"> Superscript </message> @@ -3221,7 +3214,7 @@ If you're done with the tutorial, use ChromeVox to navigate to the Close button </message> <message desc="The text label for ChromeVox language switching checkbox." name="IDS_CHROMEVOX_OPTIONS_LANG_SWITCHING_CHECKBOX_LABEL"> - Automatically detect and switch ChromeVox language. + Automatically switch ChromeVox voice based on language </message> <message desc="Spoken to describe all rich text attributes of a node." name="IDS_CHROMEVOX_RICH_TEXT_ATTRIBUTES"> Text formatting. @@ -3656,10 +3649,10 @@ If you're done with the tutorial, use ChromeVox to navigate to the Close button Dodger Blue </message> <message desc="An options page section header for options about ChromeVox rich text behavior. This section lets users set preferences on how rich text attributes should be indicated." name="IDS_CHROMEVOX_OPTIONS_RICH_TEXT_HEADER"> - Rich Text Attributes + Formatting </message> <message desc="The text label for ChromeVox automatic rich text indication checkbox." name="IDS_CHROMEVOX_OPTIONS_RICH_TEXT_CHECKBOX_LABEL"> - Announce rich text attributes + Announce text styling </message> <message desc="Labels the misspell list box." name="IDS_CHROMEVOX_OPTIONS_MISSPELL_DESCRIPTION"> Indicate misspell: diff --git a/chromium/chrome/browser/resources/chromeos/genius_app/manifest.json b/chromium/chrome/browser/resources/chromeos/genius_app/manifest.json index e0f1b720490..c79cf9eda03 100644 --- a/chromium/chrome/browser/resources/chromeos/genius_app/manifest.json +++ b/chromium/chrome/browser/resources/chromeos/genius_app/manifest.json @@ -3,7 +3,7 @@ "manifest_version": 2, "name": "__MSG_app_name__", "description": "__MSG_app_description__", - "version": "0.3", + "version": "0.4", "minimum_chrome_version": "28", "default_locale": "en", "incognito" : "split", @@ -36,6 +36,7 @@ "https://*.ytimg.com/*", "https://www.google.com/*", "https://support.google.com/*", + "https://scone-pa.clients6.google.com/*", "https://commondatastorage.googleapis.com/*", "https://storage.googleapis.com/*", "https://www.google-analytics.com/" diff --git a/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn b/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn index 13434201e78..7f45f293dd0 100644 --- a/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn @@ -26,7 +26,7 @@ js_library("internet_detail_dialog") { deps = [ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", - "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior", + "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior_mojo", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js/chromeos:onc_mojo", diff --git a/chromium/chrome/browser/resources/chromeos/login/BUILD.gn b/chromium/chrome/browser/resources/chromeos/login/BUILD.gn index 16625518952..77459dd1bf6 100644 --- a/chromium/chrome/browser/resources/chromeos/login/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/login/BUILD.gn @@ -192,7 +192,8 @@ js_library("enrollment_license_card") { js_library("fingerprint_setup") { deps = [ ":oobe_dialog_host_behavior", - "//ui/webui/resources/cr_elements/chromeos/fingerprint:cr_fingerprint_progress_arc", + "//ui/webui/resources/cr_elements/chromeos/cr_lottie:cr_lottie", + "//ui/webui/resources/cr_elements/cr_fingerprint:cr_fingerprint_progress_arc", "//ui/webui/resources/js:i18n_behavior", ] } diff --git a/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn b/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn index 33cef10b2fc..a38c408d0f3 100644 --- a/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn +++ b/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn @@ -36,7 +36,10 @@ run_jsbundler("switch_access_copied_files") { "back_button_manager.js", "background.js", "commands.js", + "focus_ring_manager.js", "icons/back.svg", + "icons/copy.svg", + "icons/cut.svg", "icons/decrement.svg", "icons/dictation.svg", "icons/increment.svg", @@ -45,29 +48,27 @@ run_jsbundler("switch_access_copied_files") { "icons/keyboard.svg", "icons/moveBackwardOneCharOfText.svg", "icons/moveBackwardOneWordOfText.svg", + "icons/moveCursor.svg", "icons/moveDownOneLineOfText.svg", "icons/moveForwardOneCharOfText.svg", "icons/moveForwardOneWordOfText.svg", "icons/moveUpOneLineOfText.svg", - "icons/options.svg", + "icons/paste.svg", "icons/scrollDownOrForward.svg", "icons/scrollLeft.svg", "icons/scrollRight.svg", "icons/scrollUpOrBackward.svg", "icons/select.svg", + "icons/settings.svg", "icons/showContextMenu.svg", "icons/textSelectionEnd.svg", "icons/textSelectionStart.svg", - "key_event_handler.js", "menu_manager.js", "menu_panel.css", "menu_panel.html", "menu_panel.js", "menu_panel_interface.js", "navigation_manager.js", - "options.css", - "options.html", - "options.js", "preferences.js", "rect_helper.js", "switch_access.js", @@ -174,12 +175,11 @@ js_type_check("closure_compile") { ":back_button_manager", ":background", ":commands", - ":key_event_handler", + ":focus_ring_manager", ":menu_manager", ":menu_panel", ":menu_panel_interface", ":navigation_manager", - ":options", ":preferences", ":rect_helper", ":switch_access", @@ -203,10 +203,12 @@ js_library("auto_scan_manager") { js_library("navigation_manager") { deps = [ ":back_button_manager", + ":focus_ring_manager", ":menu_manager", ":menu_panel_interface", ":rect_helper", ":switch_access_constants", + ":switch_access_interface", ":switch_access_predicate", ":text_input_manager", ":text_navigation_manager", @@ -242,9 +244,9 @@ js_library("commands") { ] } -js_library("key_event_handler") { +js_library("focus_ring_manager") { deps = [ - ":switch_access_interface", + ":back_button_manager", ] externs_list = [ "$externs_path/accessibility_private.js" ] } @@ -254,6 +256,7 @@ js_library("menu_manager") { ":menu_panel_interface", ":switch_access_interface", ] + externs_list = [ "$externs_path/accessibility_private.js" ] } js_library("menu_panel") { @@ -265,19 +268,11 @@ js_library("menu_panel") { js_library("menu_panel_interface") { } -js_library("options") { - deps = [ - ":background", - ":switch_access", - ] - externs_list = [ "$externs_path/chrome_extensions.js" ] -} - js_library("preferences") { deps = [ ":switch_access_interface", ] - externs_list = [ "$externs_path/chrome_extensions.js" ] + externs_list = [ "$externs_path/settings_private.js" ] } js_library("rect_helper") { @@ -288,7 +283,6 @@ js_library("switch_access") { deps = [ ":auto_scan_manager", ":commands", - ":key_event_handler", ":menu_panel_interface", ":navigation_manager", ":preferences", @@ -296,6 +290,7 @@ js_library("switch_access") { externs_list = [ "$externs_path/automation.js", "$externs_path/chrome_extensions.js", + "$externs_path/clipboard.js", "$externs_path/command_line_private.js", ] } diff --git a/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd b/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd index 637e823fe73..6795d3cbda3 100644 --- a/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd +++ b/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd @@ -162,6 +162,9 @@ <message desc="The Switch Access action to open the Switch Access settings page. Should be short." name="IDS_SWITCH_ACCESS_SETTINGS_ACTION"> Settings </message> + <message desc="The Switch Access action to show the text navigation menu for moving the text caret within a text element." name="IDS_SWITCH_ACCESS_MOVE_CURSOR"> + Move cursor + </message> <message desc="The Switch Access action for moving the text caret to the beginning of the text element." name="IDS_SWITCH_ACCESS_JUMP_TO_BEGINNING_OF_TEXT"> Jump to beginning </message> @@ -192,6 +195,15 @@ <message desc="The Switch Access action to set the end of a text selection area." name="IDS_SWITCH_ACCESS_SELECTION_END"> Selection end </message> + <message desc="The Switch Access action to cut text." name="IDS_SWITCH_ACCESS_CUT"> + Cut + </message> + <message desc="The Switch Access action to copy text." name="IDS_SWITCH_ACCESS_COPY"> + Copy + </message> + <message desc="The Switch Access action to paste text." name="IDS_SWITCH_ACCESS_PASTE"> + Paste + </message> </messages> </release> </grit> diff --git a/chromium/chrome/browser/resources/component_extension_resources.grd b/chromium/chrome/browser/resources/component_extension_resources.grd index 21fb200503d..f159f9a242b 100644 --- a/chromium/chrome/browser/resources/component_extension_resources.grd +++ b/chromium/chrome/browser/resources/component_extension_resources.grd @@ -103,7 +103,6 @@ <include name="IDR_PDF_TOOLBAR_MANAGER_JS" file="pdf/toolbar_manager.js" type="BINDATA" /> <include name="IDR_PDF_PDF_FITTING_TYPE_JS" file="pdf/pdf_fitting_type.js" type="BINDATA" /> <include name="IDR_PDF_VIEWPORT_JS" file="pdf/viewport.js" type="BINDATA" /> - <include name="IDR_PDF_VIEWPORT_INTERFACE_JS" file="pdf/viewport_interface.js" type="BINDATA" /> <include name="IDR_PDF_OPEN_PDF_PARAMS_PARSER_JS" file="pdf/open_pdf_params_parser.js" type="BINDATA" /> <include name="IDR_PDF_NAVIGATOR_JS" file="pdf/navigator.js" type="BINDATA" /> <include name="IDR_PDF_VIEWPORT_SCROLLER_JS" file="pdf/viewport_scroller.js" type="BINDATA" /> @@ -117,8 +116,6 @@ <include name="IDR_PDF_ICONS_HTML" file="pdf/elements/icons.html" type="BINDATA" /> <include name="IDR_PDF_VIEWER_BOOKMARK_HTML" file="pdf/elements/viewer-bookmark/viewer-bookmark.html" type="BINDATA" /> <include name="IDR_PDF_VIEWER_BOOKMARK_JS" file="pdf/elements/viewer-bookmark/viewer-bookmark.js" type="BINDATA" /> - <include name="IDR_PDF_VIEWER_BOOKMARKS_CONTENT_HTML" file="pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html" type="BINDATA" /> - <include name="IDR_PDF_VIEWER_BOOKMARKS_CONTENT_JS" file="pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js" type="BINDATA" /> <include name="IDR_PDF_VIEWER_ERROR_SCREEN_HTML" file="pdf/elements/viewer-error-screen/viewer-error-screen.html" type="BINDATA" /> <include name="IDR_PDF_VIEWER_ERROR_SCREEN_JS" file="pdf/elements/viewer-error-screen/viewer-error-screen.js" type="BINDATA" /> <if expr="chromeos"> diff --git a/chromium/chrome/browser/resources/cryptotoken/cryptotokenbackground.js b/chromium/chrome/browser/resources/cryptotoken/cryptotokenbackground.js index 13c0e886205..977b3804a0d 100644 --- a/chromium/chrome/browser/resources/cryptotoken/cryptotokenbackground.js +++ b/chromium/chrome/browser/resources/cryptotoken/cryptotokenbackground.js @@ -9,9 +9,6 @@ 'use strict'; /** @const */ -var BROWSER_SUPPORTS_TLS_CHANNEL_ID = true; - -/** @const */ var HTTP_ORIGINS_ALLOWED = false; /** @const */ diff --git a/chromium/chrome/browser/resources/cryptotoken/enroller.js b/chromium/chrome/browser/resources/cryptotoken/enroller.js index 4fb1bef7c44..7bde035b0a1 100644 --- a/chromium/chrome/browser/resources/cryptotoken/enroller.js +++ b/chromium/chrome/browser/resources/cryptotoken/enroller.js @@ -1119,8 +1119,8 @@ Enroller.prototype.encodeEnrollChallenges_ = function( // which we're constructing here. The browser data object contains, among // other things, the server challenge. var serverChallenge = enrollChallenge['challenge']; - var browserData = makeEnrollBrowserData( - serverChallenge, this.sender_.origin, this.sender_.tlsChannelId); + var browserData = + makeEnrollBrowserData(serverChallenge, this.sender_.origin); // Replace the challenge with the hash of the browser data. modifiedChallenge['challenge'] = B64_encode(sha256HashOfString(browserData)); diff --git a/chromium/chrome/browser/resources/cryptotoken/manifest.json b/chromium/chrome/browser/resources/cryptotoken/manifest.json index dec5bb9e130..d6a8329a3e0 100644 --- a/chromium/chrome/browser/resources/cryptotoken/manifest.json +++ b/chromium/chrome/browser/resources/cryptotoken/manifest.json @@ -17,8 +17,7 @@ ], "ids": [ "fjajfjhkeibgmiggdfehjplbhmfkialk" - ], - "accepts_tls_channel_id": true + ] }, "background": { "persistent": false, diff --git a/chromium/chrome/browser/resources/cryptotoken/signer.js b/chromium/chrome/browser/resources/cryptotoken/signer.js index 5dae63eedf8..30cd3ca9097 100644 --- a/chromium/chrome/browser/resources/cryptotoken/signer.js +++ b/chromium/chrome/browser/resources/cryptotoken/signer.js @@ -445,8 +445,7 @@ Signer.prototype.doSign_ = async function() { } var keyHandle = challenge['keyHandle']; - var browserData = makeSignBrowserData( - serverChallenge, this.sender_.origin, this.sender_.tlsChannelId); + var browserData = makeSignBrowserData(serverChallenge, this.sender_.origin); this.browserData_[keyHandle] = browserData; this.serverChallenges_[keyHandle] = challenge; } diff --git a/chromium/chrome/browser/resources/cryptotoken/webrequest.js b/chromium/chrome/browser/resources/cryptotoken/webrequest.js index d9c9b4fc9d0..1bd2c3d0e8b 100644 --- a/chromium/chrome/browser/resources/cryptotoken/webrequest.js +++ b/chromium/chrome/browser/resources/cryptotoken/webrequest.js @@ -258,58 +258,20 @@ function sha256HashOfString(string) { var UNUSED_CID_PUBKEY_VALUE = 'unused'; /** - * Normalizes the TLS channel ID value: - * 1. Converts semantically empty values (undefined, null, 0) to the empty - * string. - * 2. Converts valid JSON strings to a JS object. - * 3. Otherwise, returns the input value unmodified. - * @param {Object|string|undefined} opt_tlsChannelId TLS Channel id - * @return {Object|string} The normalized TLS channel ID value. - */ -function tlsChannelIdValue(opt_tlsChannelId) { - if (!opt_tlsChannelId) { - // Case 1: Always set some value for TLS channel ID, even if it's the empty - // string: this browser definitely supports them. - return UNUSED_CID_PUBKEY_VALUE; - } - if (typeof opt_tlsChannelId === 'string') { - try { - var obj = JSON.parse(opt_tlsChannelId); - if (!obj) { - // Case 1: The string value 'null' parses as the Javascript object null, - // so return an empty string: the browser definitely supports TLS - // channel id. - return UNUSED_CID_PUBKEY_VALUE; - } - // Case 2: return the value as a JS object. - return /** @type {Object} */ (obj); - } catch (e) { - console.warn('Unparseable TLS channel ID value ' + opt_tlsChannelId); - // Case 3: return the value unmodified. - } - } - return opt_tlsChannelId; -} - -/** * Creates a browser data object with the given values. * @param {!string} type A string representing the "type" of this browser data * object. * @param {!string} serverChallenge The server's challenge, as a base64- * encoded string. * @param {!string} origin The server's origin, as seen by the browser. - * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id * @return {string} A string representation of the browser data object. */ -function makeBrowserData(type, serverChallenge, origin, opt_tlsChannelId) { +function makeBrowserData(type, serverChallenge, origin) { var browserData = { 'typ': type, 'challenge': serverChallenge, 'origin': origin }; - if (BROWSER_SUPPORTS_TLS_CHANNEL_ID) { - browserData['cid_pubkey'] = tlsChannelIdValue(opt_tlsChannelId); - } return JSON.stringify(browserData); } @@ -318,13 +280,11 @@ function makeBrowserData(type, serverChallenge, origin, opt_tlsChannelId) { * @param {!string} serverChallenge The server's challenge, as a base64- * encoded string. * @param {!string} origin The server's origin, as seen by the browser. - * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id * @return {string} A string representation of the browser data object. */ -function makeEnrollBrowserData(serverChallenge, origin, opt_tlsChannelId) { +function makeEnrollBrowserData(serverChallenge, origin) { return makeBrowserData( - 'navigator.id.finishEnrollment', serverChallenge, origin, - opt_tlsChannelId); + 'navigator.id.finishEnrollment', serverChallenge, origin); } /** @@ -332,12 +292,10 @@ function makeEnrollBrowserData(serverChallenge, origin, opt_tlsChannelId) { * @param {!string} serverChallenge The server's challenge, as a base64- * encoded string. * @param {!string} origin The server's origin, as seen by the browser. - * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id * @return {string} A string representation of the browser data object. */ -function makeSignBrowserData(serverChallenge, origin, opt_tlsChannelId) { - return makeBrowserData( - 'navigator.id.getAssertion', serverChallenge, origin, opt_tlsChannelId); +function makeSignBrowserData(serverChallenge, origin) { + return makeBrowserData('navigator.id.getAssertion', serverChallenge, origin); } /** diff --git a/chromium/chrome/browser/resources/cryptotoken/webrequestsender.js b/chromium/chrome/browser/resources/cryptotoken/webrequestsender.js index 4b54896c085..9630de47e9d 100644 --- a/chromium/chrome/browser/resources/cryptotoken/webrequestsender.js +++ b/chromium/chrome/browser/resources/cryptotoken/webrequestsender.js @@ -11,7 +11,6 @@ /** * @typedef {{ * origin: string, - * tlsChannelId: (string|undefined), * tabId: (number|undefined) * }} */ @@ -30,9 +29,6 @@ function createSenderFromMessageSender(messageSender) { return null; } var sender = {origin: origin}; - if (messageSender.tlsChannelId) { - sender.tlsChannelId = messageSender.tlsChannelId; - } if (messageSender.tab) { sender.tabId = messageSender.tab.id; } diff --git a/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.css b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.css new file mode 100644 index 00000000000..aa35e0acfab --- /dev/null +++ b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.css @@ -0,0 +1,45 @@ +/* Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + +body { + align-items: center; + display: flex; + flex-direction: column; + font-family: sans, Arial, sans-serif; + font-size: 93.75%; + justify-content: flex-start; +} + +/* This is needed to hide elements that have "display" set. */ +[hidden] { + display: none !important; +} + +#failure-message { + display: inline-block; + padding-top: 100px; +} + +h1.heading { + color: rgb(32, 33, 36); + font-size: 1.6em; + font-weight: normal; + line-height: 1.25em; + margin: 0 0 15px 0; +} + +.list-header { + color: #2B2B2B; + line-height: 1.61em; + margin: 0 8px 0 0; +} + +ul.suggestions-list { + margin-top: 0; +} + +ul.suggestions-list li { + color: #2B2B2B; + line-height: 1.55; +} diff --git a/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.grdp b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.grdp new file mode 100644 index 00000000000..547e30b812d --- /dev/null +++ b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.grdp @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<grit-part> + <include name="IDR_DEV_UI_LOADER_HTML" file="resources/dev_ui_loader/dev_ui_loader.html" compress="gzip" type="BINDATA" /> + <include name="IDR_DEV_UI_LOADER_CSS" file="resources/dev_ui_loader/dev_ui_loader.css" compress="gzip" type="BINDATA" /> + <include name="IDR_DEV_UI_LOADER_JS" file="resources/dev_ui_loader/dev_ui_loader.js" compress="gzip" type="BINDATA" /> +</grit-part> diff --git a/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.html b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.html new file mode 100644 index 00000000000..fc95229fb39 --- /dev/null +++ b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.html @@ -0,0 +1,22 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>DevUI DFM Loader</title> + <link rel="stylesheet" href="dev_ui_loader.css"> + <script src="chrome://resources/js/cr.js"></script> + <script src="chrome://resources/js/promise_resolver.js"></script> + <script src="dev_ui_loader.js"></script> +</head> +<body> +<div id="failure-message" hidden> + <h1 class="heading">Something went wrong</h1> + <p class="list-header">Try:</p> + <ul class="suggestions-list"> + <li>Reloading this page</li> + <li>Checking your internet connection</li> + </ul> +</div> +</body> +</html> diff --git a/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.js b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.js new file mode 100644 index 00000000000..61bc4c25be8 --- /dev/null +++ b/chromium/chrome/browser/resources/dev_ui_loader/dev_ui_loader.js @@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(function() { +'use strict'; + +/** @return {!URL} */ +function getRedirectUrl() { + try { // For potential TypeError from new URL(). + const urlString = new URL(location).searchParams.get('url'); + if (urlString) { + const url = new URL(decodeURIComponent(urlString)); + // Perform basic filtering. Also skip 'dev-ui-loader' to avoid redirect + // cycle (benign but bizarre). Note that |url.host| is always lowercase. + if (url.protocol === 'chrome:' && url.host.match(/[a-z0-9_\-]+/) && + url.host !== 'dev-ui-loader') { + return url; + } + } + } catch (e) { + } + return new URL('chrome://chrome-urls'); +} + +function redirectToChromePage() { + // Use replace() so the current page disappears from history. + location.replace(getRedirectUrl()); +} + +function doInstall() { + cr.sendWithPromise('installAndLoadDevUiDfm').then((response) => { + const status = response[0]; + if (status === 'success' || status === 'noop') { + redirectToChromePage(); + } else if (status === 'failure') { + document.querySelector('#failure-message').hidden = false; + } + }); +} + +document.addEventListener('DOMContentLoaded', () => { + cr.sendWithPromise('getDevUiDfmState').then((state) => { + if (state === 'ready') { + redirectToChromePage(); + } else if (state === 'not-installed' || 'not-loaded') { + doInstall(); + } + }); +}); +})(); diff --git a/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js b/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js index 11103072caa..2e4181171db 100644 --- a/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js +++ b/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js @@ -124,9 +124,9 @@ const DeviceLogUI = (function() { * Sets refresh rate if the interval is found in the url. */ const setRefresh = function() { - const interval = parseQueryParams(window.location)['refresh']; - if (interval && interval != '') { - setInterval(requestLog, parseInt(interval) * 1000); + const interval = new URL(window.location).searchParams.get('refresh'); + if (interval) { + setInterval(requestLog, parseInt(interval, 10) * 1000); } }; diff --git a/chromium/chrome/browser/resources/discards/discards_tab.js b/chromium/chrome/browser/resources/discards/discards_tab.js index fd729e3119a..b7a64869944 100644 --- a/chromium/chrome/browser/resources/discards/discards_tab.js +++ b/chromium/chrome/browser/resources/discards/discards_tab.js @@ -295,7 +295,8 @@ Polymer({ * @private */ getFavIconStyle_: function(item) { - return 'background-image:' + cr.icon.getFavicon(item.tabUrl, false); + return 'background-image:' + + cr.icon.getFaviconForPageURL(item.tabUrl, false); }, /** diff --git a/chromium/chrome/browser/resources/downloads/item.js b/chromium/chrome/browser/resources/downloads/item.js index 5eb28c74d35..dff416ea746 100644 --- a/chromium/chrome/browser/resources/downloads/item.js +++ b/chromium/chrome/browser/resources/downloads/item.js @@ -474,7 +474,13 @@ cr.define('downloads', function() { // Make the file name collapsible. p.collapsible = !!p.arg; }); - cr.toastManager.getInstance().showForStringPieces(pieces, true); + cr.toastManager.getInstance().showForStringPieces( + /** + * @type {!Array<{collapsible: boolean, + * value: string, + * arg: (string|null)}>} + */ + (pieces), true); this.mojoHandler_.remove(this.data.id); }, diff --git a/chromium/chrome/browser/resources/extensions/BUILD.gn b/chromium/chrome/browser/resources/extensions/BUILD.gn index 7a60d45137f..1798f6238a7 100644 --- a/chromium/chrome/browser/resources/extensions/BUILD.gn +++ b/chromium/chrome/browser/resources/extensions/BUILD.gn @@ -165,6 +165,7 @@ js_library("item") { ":item_behavior", ":item_util", ":navigation_helper", + "//ui/webui/resources/cr_elements/cr_toast:cr_toast_manager", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:i18n_behavior", @@ -370,7 +371,7 @@ js_library("sidebar") { js_library("toolbar") { deps = [ "//third_party/polymer/v1_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer-extracted", - "//ui/webui/resources/cr_elements/cr_toast:cr_toast", + "//ui/webui/resources/cr_elements/cr_toast:cr_toast_manager", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js:util", diff --git a/chromium/chrome/browser/resources/extensions/item.html b/chromium/chrome/browser/resources/extensions/item.html index 4dd4b1c830c..a69c6b4c656 100644 --- a/chromium/chrome/browser/resources/extensions/item.html +++ b/chromium/chrome/browser/resources/extensions/item.html @@ -3,6 +3,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> diff --git a/chromium/chrome/browser/resources/extensions/item.js b/chromium/chrome/browser/resources/extensions/item.js index 008beca6c32..d1fc8e973ab 100644 --- a/chromium/chrome/browser/resources/extensions/item.js +++ b/chromium/chrome/browser/resources/extensions/item.js @@ -117,6 +117,9 @@ cr.define('extensions', function() { }, }, + /** Prevents reloading the same item while it's already being reloaded. */ + isReloading_: false, + observers: [ 'observeIdVisibility_(inDevMode, showingDetails_, data.id)', ], @@ -213,9 +216,30 @@ cr.define('extensions', function() { /** @private */ onReloadTap_: function() { - this.delegate.reloadItem(this.data.id).catch(loadError => { - this.fire('load-error', loadError); - }); + // Don't reload if in the middle of an update. + if (this.isReloading_) { + return; + } + + this.isReloading_ = true; + + const toastManager = cr.toastManager.getInstance(); + // Keep the toast open indefinitely. + toastManager.duration = 0; + toastManager.show(this.i18n('itemReloading'), false); + this.delegate.reloadItem(this.data.id) + .then( + () => { + toastManager.hide(); + toastManager.duration = 3000; + toastManager.show(this.i18n('itemReloaded'), false); + this.isReloading_ = false; + }, + loadError => { + this.fire('load-error', loadError); + toastManager.hide(); + this.isReloading_ = false; + }); }, /** @private */ diff --git a/chromium/chrome/browser/resources/extensions/manager.html b/chromium/chrome/browser/resources/extensions/manager.html index 0acd9673c75..1c35c285068 100644 --- a/chromium/chrome/browser/resources/extensions/manager.html +++ b/chromium/chrome/browser/resources/extensions/manager.html @@ -2,6 +2,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_drawer/cr_drawer.html"> <link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html"> <link rel="import" href="chrome://resources/cr_elements/cr_view_manager/cr_view_manager.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> @@ -138,6 +139,7 @@ install-warnings="[[installWarnings_]]"> </extensions-install-warnings-dialog> </template> + <cr-toast-manager></cr-toast-manager> </template> <script src="manager.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/extensions/toolbar.html b/chromium/chrome/browser/resources/extensions/toolbar.html index 7e08974284a..9b8706bd762 100644 --- a/chromium/chrome/browser/resources/extensions/toolbar.html +++ b/chromium/chrome/browser/resources/extensions/toolbar.html @@ -1,7 +1,7 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> @@ -91,14 +91,6 @@ .more-actions span { margin-inline-end: 16px; } - - cr-toast > div { - display: flex; - flex: 1; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } </style> <cr-toolbar page-name="$i18n{toolbarTitle}" search-prompt="$i18n{search}" clear-label="$i18n{clearSearch}" menu-label="$i18n{mainMenu}" show-menu @@ -143,9 +135,6 @@ </if> </div> </div> - <cr-toast> - <div>[[toastLabel_]]</div> - </cr-toast> </template> <script src="toolbar.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/extensions/toolbar.js b/chromium/chrome/browser/resources/extensions/toolbar.js index 7792f175221..bd3590edcba 100644 --- a/chromium/chrome/browser/resources/extensions/toolbar.js +++ b/chromium/chrome/browser/resources/extensions/toolbar.js @@ -55,12 +55,6 @@ cr.define('extensions', function() { showPackDialog_: Boolean, /** - * Text to display in update toast - * @private - */ - toastLabel_: String, - - /** * Prevents initiating update while update is in progress. * @private */ @@ -73,14 +67,6 @@ cr.define('extensions', function() { role: 'banner', }, - /** @override */ - detached: function() { - const openToastElement = this.$$('cr-toast[open]'); - if (openToastElement) { - openToastElement.hide(); - } - }, - /** * @return {boolean} * @private @@ -163,23 +149,20 @@ cr.define('extensions', function() { } this.isUpdating_ = true; - const toastElement = this.$$('cr-toast'); - this.toastLabel_ = this.i18n('toolbarUpdatingToast'); + const toastManager = cr.toastManager.getInstance(); // Keep the toast open indefinitely. - toastElement.duration = 0; - toastElement.show(); - this.delegate.updateAllExtensions() - .then(() => { - Polymer.IronA11yAnnouncer.requestAvailability(); - const doneText = this.i18n('toolbarUpdateDone'); - this.fire('iron-announce', {text: doneText}); - this.toastLabel_ = doneText; - toastElement.show(3000); + toastManager.duration = 0; + toastManager.show(this.i18n('toolbarUpdatingToast'), false); + this.delegate.updateAllExtensions().then( + () => { + toastManager.hide(); + toastManager.duration = 3000; + toastManager.show(this.i18n('toolbarUpdateDone'), false); this.isUpdating_ = false; - }) - .catch(function() { - toastElement.hide(); + }, + () => { + toastManager.hide(); this.isUpdating_ = false; }); }, diff --git a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js index dc1a35b1729..7161b0893c1 100644 --- a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js +++ b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js @@ -6,7 +6,7 @@ // Note: webview_event_manager.js is already included by saml_handler.js. /** - * @fileoverview An UI component to authenciate to Chrome. The component hosts + * @fileoverview An UI component to authenticate to Chrome. The component hosts * IdP web pages in a webview. A client who is interested in monitoring * authentication events should subscribe itself via addEventListener(). After * initialization, call {@code load} to start the authentication flow. @@ -109,6 +109,12 @@ cr.define('cr.login', function() { 'email', 'readOnlyEmail', 'realm', + // If the authentication is done via external IdP, 'startsOnSamlPage' + // indicates whether the flow should start on the IdP page. + 'startsOnSamlPage', + // SAML assertion consumer URL, used to detect when Gaia-less SAML flows end + // (e.g. for SAML managed guest sessions). + 'samlAclUrl', ]; @@ -255,6 +261,7 @@ cr.define('cr.login', function() { * @private */ this.isSamlUserPasswordless_ = null; + this.samlAclUrl_ = null; window.addEventListener( 'message', this.onMessageFromWebview_.bind(this), false); @@ -455,12 +462,23 @@ cr.define('cr.login', function() { this.initialFrameUrl_ = this.constructInitialFrameUrl_(data); this.reloadUrl_ = data.frameUrl || this.initialFrameUrl_; + this.samlAclUrl_ = data.samlAclUrl; + // The email field is repurposed as public session email in SAML guest + // mode, ie when frameUrl is not empty. + if (data.samlAclUrl) { + this.email_ = data.email; + } + + if (data.startsOnSamlPage) { + this.samlHandler_.startsOnSamlPage = true; + } // Don't block insecure content for desktop flow because it lands on // http. Otherwise, block insecure content as long as gaia is https. this.samlHandler_.blockInsecureContent = authMode != AuthMode.DESKTOP && this.idpOrigin_.startsWith('https://'); this.samlHandler_.extractSamlPasswordAttributes = data.extractSamlPasswordAttributes; + this.needPassword = !('needPassword' in data) || data.needPassword; this.webview_.contextMenus.onShow.addListener(function(e) { @@ -578,6 +596,9 @@ cr.define('cr.login', function() { if (data.ignoreCrOSIdpSetting === true) { url = appendParam(url, 'ignoreCrOSIdpSetting', 'true'); } + if (data.enableGaiaActionButtons) { + url = appendParam(url, 'use_native_navigation', 1); + } return url; } @@ -960,6 +981,7 @@ cr.define('cr.login', function() { gaiaId: this.gaiaId_ || '', password: this.password_ || '', usingSAML: this.authFlow == AuthFlow.SAML, + publicSAML: this.samlAclUrl_ || false, chooseWhatToSync: this.chooseWhatToSync_, skipForNow: this.skipForNow_, sessionIndex: this.sessionIndex_ || '', @@ -1085,6 +1107,9 @@ cr.define('cr.login', function() { this.webview_.focus(); } else if (currentUrl == BLANK_PAGE_URL) { this.fireReadyEvent_(); + } else if (currentUrl == this.samlAclUrl_) { + this.skipForNow_ = true; + this.onAuthCompleted_(); } } @@ -1094,7 +1119,7 @@ cr.define('cr.login', function() { */ onLoadAbort_(e) { this.dispatchEvent(new CustomEvent( - 'loadAbort', {detail: {error: e.reason, src: e.url}})); + 'loadAbort', {detail: {error_code: e.code, src: e.url}})); } /** 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 4a1af059feb..789f6fec084 100644 --- a/chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js +++ b/chromium/chrome/browser/resources/gaia_auth_host/saml_handler.js @@ -150,7 +150,7 @@ cr.define('cr.login', function() { this.apiPasswordBytes_ = null; /** - * Whether to abort the authentication flow and show an error messagen + * Whether to abort the authentication flow and show an error message * when content served over an unencrypted connection is detected. * @type {boolean} */ @@ -282,6 +282,15 @@ cr.define('cr.login', function() { } /** + * Sets the startsOnSamlPage attribute of the SAML handler. + * @param {boolean} value + */ + set startsOnSamlPage(value) { + this.startsOnSamlPage_ = value; + this.reset(); + } + + /** * Removes the injected content script and unbinds all listeners from the * webview passed to the constructor. This SAMLHandler will be unusable * after this function returns. diff --git a/chromium/chrome/browser/resources/hats/hats.html b/chromium/chrome/browser/resources/hats/hats.html index 08793f12a1d..18ec74d79e5 100644 --- a/chromium/chrome/browser/resources/hats/hats.html +++ b/chromium/chrome/browser/resources/hats/hats.html @@ -1,30 +1,27 @@ +<!doctype html> <html> <head> <style> - /** - * The style used to draw done-button. - * Use z-index to make sure the button is in front of the survey content. - * TODO(weili): we need to make it RTL friendly if we need to support RTL. + /* 402 is the project code name used in the content loaded by this page. + * We need to override their focus behavior to improve keyboard focus + * accessibility. */ - .done-button { - bottom: 17px; - color: rgb(33, 150, 243); - display: block; - font: 400 16px Roboto,RobotoDraft,Helvetica,sans-serif; - position: fixed; - right: 25px; - text-transform: uppercase; - z-index: 10; + .t402-prompt-websat .t402-prompt-root .t402-button:focus { + outline-style: auto; } - - #id-done-button[hidden] { - display: none; + .t402-css-theme-hats-material1 .t402-titlebar-title-alt:focus { + outline-style: auto; + } + :focus { + /* Needs to override dynamically loaded, more specific styles. */ + outline-color: rgb(77, 144, 254) !important; } </style> <script> /** - * Handles the callback when the survey is submitted or when the survey - * has already been submitted in the past. + * Close the window when the survey is submitted or when the survey + * has already been submitted in the past. It is called through HaTS + * javascript library's accessGrantedCallback function. * @param {boolean} isFirstRun Will be true when the user just earned * access to the content and false if the user had already had access * previously. @@ -34,36 +31,49 @@ return; } - /* Display the done button at the end of the survey. */ - document.getElementById('id-done-button').hidden = false; + // HaTS 1 library will post the answer through a form to an iframe. + // Once the iframe is loaded, it will be disposed. We can not listen to + // the iframe's load event since the previous listener will dispose the + // iframe so our listener will not be notified. Instead, we listen to + // the iframe's disposal to make sure the iframe is already loaded, + // which means the answer has been posted to the server. + // TODO(weili): Once this issue is fixed in HaTS library + // (https://b.corp.google.com/issues/143494318), remove the following + // work around. + const element = document.querySelector(`iframe[id^='closure_frame']`); + if (element === null) { + // No iframe found. + window.close(); + } + + const observer = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + for (let i = 0; i < mutation.removedNodes.length; i++) { + if (element === mutation.removedNodes[i]) { + window.close(); + } + } + }) + }); - /* Auto dismiss after two seconds. */ - setTimeout(function(){ window.close(); }, 2000); - }; + // Watch for the iframe disposal event. + observer.observe(element.parentNode, {childList: true}); + } /** * Called after the survey HTML is injected into the page. + * It is called through HaTS javascript library's afterShowCallback + * function. */ function onSurveyShown() { - /* Don't show logo on the survey */ + // Don't show logo on the survey. const elements = document.getElementsByClassName('t402-prompt-logo'); for (const element of elements) element.style.display = 'none'; } - - document.addEventListener('DOMContentLoaded', function() { - document.getElementById('id-link-done-button').onclick = function() { - window.close(); - } - }) </script> - <script src="$SCRIPT_SRC"></script> + <script src="$i18n{scriptSrc}"></script> </head> <body> - <a id="id-link-done-button" href="#" role="button"> - <div id="id-done-button" class="done-button" hidden> - $DONE_BUTTON_LABEL - </div> - </a> </body> </html> diff --git a/chromium/chrome/browser/resources/help_app/OWNERS b/chromium/chrome/browser/resources/help_app/OWNERS index 925462999cb..8ccf6d7cd2f 100644 --- a/chromium/chrome/browser/resources/help_app/OWNERS +++ b/chromium/chrome/browser/resources/help_app/OWNERS @@ -1,4 +1,2 @@ achuith@chromium.org -cnwan@chromium.org -cylee@chromium.org -davidyu@chromium.org +carpenterr@chromium.org diff --git a/chromium/chrome/browser/resources/history/constants.js b/chromium/chrome/browser/resources/history/constants.js index cbf92a0697d..970d4001f0e 100644 --- a/chromium/chrome/browser/resources/history/constants.js +++ b/chromium/chrome/browser/resources/history/constants.js @@ -15,12 +15,16 @@ const BROWSING_GAP_TIME = 15 * 60 * 1000; /** * The largest bucket value for UMA histogram, based on entry ID. All entries * with IDs greater than this will be included in this bucket. + * Keep consistent with the UMA constants on the Android history page + * (see HistoryManager.java). * @type {number} */ const UMA_MAX_BUCKET_VALUE = 1000; /** * The largest bucket value for a UMA histogram that is a subset of above. + * Keep consistent with the UMA constants on the Android history page + * (see HistoryManager.java). * @type {number} */ const UMA_MAX_SUBSET_BUCKET_VALUE = 100; diff --git a/chromium/chrome/browser/resources/history/externs.js b/chromium/chrome/browser/resources/history/externs.js index d772532ad2d..553d51d971e 100644 --- a/chromium/chrome/browser/resources/history/externs.js +++ b/chromium/chrome/browser/resources/history/externs.js @@ -12,6 +12,7 @@ * chrome/browser/ui/webui/browsing_history_handler.cc: * BrowsingHistoryHandler::HistoryEntry::ToValue() * @typedef {{allTimestamps: Array<number>, + * remoteIconUrlForUma: string, * isUrlInRemoteUserData: boolean, * blockedVisit: boolean, * dateRelativeDay: string, @@ -43,6 +44,7 @@ let HistoryQuery; * The type of the foreign session tab object. This definition is based on * chrome/browser/ui/webui/foreign_session_handler.cc: * @typedef {{direction: string, + * remoteIconUrlForUma: string, * sessionId: number, * timestamp: number, * title: string, diff --git a/chromium/chrome/browser/resources/history/history_item.js b/chromium/chrome/browser/resources/history/history_item.js index ad4a3f2a597..5d48e9220bc 100644 --- a/chromium/chrome/browser/resources/history/history_item.js +++ b/chromium/chrome/browser/resources/history/history_item.js @@ -234,15 +234,29 @@ cr.define('history', function() { return; } + const ageInDays = Math.ceil( + (new Date() - new Date(this.item.time)) / 1000 /* s/ms */ / + 60 /* m/s */ / 60 /* h/m */ / 24 /* d/h */); + browserService.recordHistogram( 'HistoryPage.ClickPosition', Math.min(this.index, UMA_MAX_BUCKET_VALUE), UMA_MAX_BUCKET_VALUE); + browserService.recordHistogram( + 'HistoryPage.ClickAgeInDays', + Math.min(ageInDays, UMA_MAX_BUCKET_VALUE), UMA_MAX_BUCKET_VALUE); + if (this.index <= UMA_MAX_SUBSET_BUCKET_VALUE) { browserService.recordHistogram( 'HistoryPage.ClickPositionSubset', this.index, UMA_MAX_SUBSET_BUCKET_VALUE); } + + if (ageInDays <= UMA_MAX_SUBSET_BUCKET_VALUE) { + browserService.recordHistogram( + 'HistoryPage.ClickAgeInDaysSubset', ageInDays, + UMA_MAX_SUBSET_BUCKET_VALUE); + } }, onLinkRightClick_: function() { @@ -254,8 +268,9 @@ cr.define('history', function() { * @private */ itemChanged_: function() { - this.$.icon.style.backgroundImage = - cr.icon.getFavicon(this.item.url, this.item.isUrlInRemoteUserData); + this.$.icon.style.backgroundImage = cr.icon.getFaviconForPageURL( + this.item.url, this.item.isUrlInRemoteUserData, + this.item.remoteIconUrlForUma); this.listen(this.$['time-accessed'], 'mouseover', 'addTimeTitle_'); }, diff --git a/chromium/chrome/browser/resources/history/synced_device_card.js b/chromium/chrome/browser/resources/history/synced_device_card.js index d1a1f8db25b..dbcb3ced83e 100644 --- a/chromium/chrome/browser/resources/history/synced_device_card.js +++ b/chromium/chrome/browser/resources/history/synced_device_card.js @@ -115,8 +115,8 @@ Polymer({ for (let i = 0; i < this.tabs.length; i++) { // Entries on this UI are coming strictly from sync, so we can set // |isSyncedUrlForHistoryUi| to true on the getFavicon call below. - icons[i].style.backgroundImage = - cr.icon.getFavicon(this.tabs[i].url, true); + icons[i].style.backgroundImage = cr.icon.getFaviconForPageURL( + this.tabs[i].url, true, this.tabs[i].remoteIconUrlForUma); } }); }, diff --git a/chromium/chrome/browser/resources/inline_login/inline_login.css b/chromium/chrome/browser/resources/inline_login/inline_login.css index a749a40f08e..dfbe238a01e 100644 --- a/chromium/chrome/browser/resources/inline_login/inline_login.css +++ b/chromium/chrome/browser/resources/inline_login/inline_login.css @@ -15,7 +15,7 @@ body, #signin-frame, #spinner-container { - background-color: #f5f5f5; + background-color: var(--cr-card-background-color); bottom: 0; left: 0; position: absolute; @@ -24,9 +24,9 @@ body, } #spinner-container { - -webkit-box-align: center; - -webkit-box-pack: center; - display: -webkit-box; + align-items: center; + display: flex; + justify-content: center; } #contents:not(.loading) #spinner-container { @@ -34,13 +34,46 @@ body, } #navigation-button { - --cr-icon-button-color: white; - margin: 0; + background: white; + bottom: 32px; + left: 32px; + padding-inline-start: 10px; position: absolute; - top: 0; visibility: hidden; } +:host-context([dir='rtl']) #navigation-button { + left: auto; + right: 32px; +} + #navigation-button.enabled { visibility: visible; } + +/* On Chrome OS, we need to shift the webview a bit to accommodate the Back + * button at the bottom. + */ +<if expr="chromeos"> +#contents, +#signin-frame { + height: calc(100% - 96px); +} + +@media (max-width: 767px) { + #contents, + #signin-frame { + height: calc(100% - 80px); + } + + #navigation-button { + bottom: 24px; + left: 24px; + } + + :host-context([dir='rtl']) #navigation-button { + left: auto; + right: 24px; + } +} +</if> diff --git a/chromium/chrome/browser/resources/inline_login/inline_login.html b/chromium/chrome/browser/resources/inline_login/inline_login.html index ab872711e2c..3bc61db7ddc 100644 --- a/chromium/chrome/browser/resources/inline_login/inline_login.html +++ b/chromium/chrome/browser/resources/inline_login/inline_login.html @@ -3,10 +3,12 @@ <head> <title>$i18n{title}</title> <link rel="import" href="chrome://resources/html/polymer.html"> - <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="stylesheet" href="chrome://resources/css/spinner.css"> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> + <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> + <link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> + <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="stylesheet" href="chrome://chrome-signin/inline_login.css"> <script src="chrome://resources/js/cr.js"></script> <script src="chrome://resources/js/cr/event_target.js"></script> @@ -23,6 +25,12 @@ <div class="spinner"></div> </div> </div> - <cr-icon-button id="navigation-button" iron-icon="cr:close"></cr-icon-button> + + <cr-button + id="navigation-button" + aria-label="$i18n{accessibleBackButtonLabel}"> + <iron-icon id="navigation-icon"></iron-icon> + $i18n{accessibleBackButtonLabel} + </cr-button> </body> </html> diff --git a/chromium/chrome/browser/resources/inline_login/inline_login.js b/chromium/chrome/browser/resources/inline_login/inline_login.js index 5fde3c18ab5..98b6518a718 100644 --- a/chromium/chrome/browser/resources/inline_login/inline_login.js +++ b/chromium/chrome/browser/resources/inline_login/inline_login.js @@ -35,6 +35,7 @@ cr.define('inline.login', function() { if (isLoginPrimaryAccount) { chrome.send('metricsHandler:recordAction', ['Signin_SigninPage_Shown']); } + chrome.send('authExtensionReady'); } function onDropLink(e) { @@ -65,6 +66,8 @@ cr.define('inline.login', function() { */ function initialize() { $('navigation-button').addEventListener('click', navigationButtonClicked); + cr.addWebUIListener('showBackButton', showBackButton); + cr.addWebUIListener('navigateBackInWebview', navigateBackInWebview); authExtHost = new cr.login.Authenticator('signin-frame'); authExtHost.addEventListener('dropLink', onDropLink); authExtHost.addEventListener('ready', onAuthReady); @@ -134,20 +137,17 @@ cr.define('inline.login', function() { } function showBackButton() { - $('navigation-button').ironIcon = - isRTL() ? 'cr:arrow-forward' : 'cr:arrow-back'; - - $('navigation-button') - .setAttribute( - 'aria-label', loadTimeData.getString('accessibleBackButtonLabel')); + $('navigation-icon').icon = + isRTL() ? 'cr:chevron-right' : 'cr:chevron-left'; + $('navigation-button').classList.add('enabled'); } - function showCloseButton() { - $('navigation-button').ironIcon = 'cr:close'; - $('navigation-button').classList.add('enabled'); - $('navigation-button') - .setAttribute( - 'aria-label', loadTimeData.getString('accessibleCloseButtonLabel')); + function navigateBackInWebview() { + if ($('signin-frame').canGoBack()) { + $('signin-frame').back(); + } else { + closeDialog(); + } } function navigationButtonClicked() { @@ -164,7 +164,6 @@ cr.define('inline.login', function() { loadAuthExtension: loadAuthExtension, navigationButtonClicked: navigationButtonClicked, showBackButton: showBackButton, - showCloseButton: showCloseButton }; }); diff --git a/chromium/chrome/browser/resources/local_discovery/local_discovery.js b/chromium/chrome/browser/resources/local_discovery/local_discovery.js index 7094e5cec6b..1d2a54502cf 100644 --- a/chromium/chrome/browser/resources/local_discovery/local_discovery.js +++ b/chromium/chrome/browser/resources/local_discovery/local_discovery.js @@ -520,8 +520,7 @@ cr.define('local_discovery', function() { function getOverlayIDFromPath() { if (document.location.pathname == '/register') { - const params = parseQueryParams(document.location); - return params['id'] || null; + return new URL(document.location).searchParams.get('id'); } } diff --git a/chromium/chrome/browser/resources/local_ntp/BUILD.gn b/chromium/chrome/browser/resources/local_ntp/BUILD.gn index 9b5c6384365..15edd04f0af 100644 --- a/chromium/chrome/browser/resources/local_ntp/BUILD.gn +++ b/chromium/chrome/browser/resources/local_ntp/BUILD.gn @@ -23,5 +23,8 @@ js_library("local_ntp") { "utils.js", "voice.js", ] + deps = [ + "//ui/webui/resources/js:assert", + ] externs_list = [ "externs.js" ] } diff --git a/chromium/chrome/browser/resources/local_ntp/customize.css b/chromium/chrome/browser/resources/local_ntp/customize.css index 0022263c7be..ec345861118 100644 --- a/chromium/chrome/browser/resources/local_ntp/customize.css +++ b/chromium/chrome/browser/resources/local_ntp/customize.css @@ -95,6 +95,7 @@ html[dir=rtl] #edit-bg { color: rgb(var(--GB600-rgb)); display: none; font-size: 14px; + line-height: 1; padding-inline-end: 12px; padding-inline-start: 8px; user-select: none; @@ -286,7 +287,8 @@ html[dir=rtl] .bg-option-img { box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3), 0 4px 8px 3px rgba(var(--GG800-rgb), .15); height: 400px; - padding: 0 0 0 0; + max-height: 100vh; /* Constrain the dialog within viewport boundaries. */ + padding: 0; position: fixed; top: 0; /* Suitable for 3 columns of tiles on all platforms, accounting for larger @@ -295,6 +297,13 @@ html[dir=rtl] .bg-option-img { z-index: 10000; } +/* Prevent footer from overlapping with header at small window heights. */ +@media only screen and (max-height: 116px) { + #bg-sel-menu { + max-height: 116px; + } +} + @media (prefers-color-scheme: dark) { #bg-sel-menu { background-color: rgb(var(--dark-mode-dialog-rgb)); @@ -312,6 +321,9 @@ right, so that every text can stay on its row even on the smallest window */ #bg-sel-tiles { height: 284px; + /* Compress the tile section in order to constrain the dialog within viewport + * boundaries. 116px = 284px - (header + footer height) */ + max-height: calc(100vh - 116px); overflow-y: scroll; padding-inline-start: 8px; } diff --git a/chromium/chrome/browser/resources/local_ntp/customize.js b/chromium/chrome/browser/resources/local_ntp/customize.js index 658c6766a5f..ce243db2718 100644 --- a/chromium/chrome/browser/resources/local_ntp/customize.js +++ b/chromium/chrome/browser/resources/local_ntp/customize.js @@ -170,6 +170,7 @@ customize.CLASSES = { COLLECTION_TILE: 'bg-sel-tile', // Preview tile for background customization COLLECTION_TILE_BG: 'bg-sel-tile-bg', COLLECTION_TITLE: 'bg-sel-tile-title', // Title of a background image + HIDDEN_SELECTED: 'hidden-selected', IMAGE_DIALOG: 'is-img-sel', ON_IMAGE_MENU: 'on-img-menu', OPTION: 'bg-option', @@ -328,8 +329,6 @@ customize.setMenuVisibility = function() { $(customize.IDS.UPLOAD_IMAGE).hidden = false; $(customize.IDS.RESTORE_DEFAULT).hidden = false; $(customize.IDS.EDIT_BG_DIVIDER).hidden = false; - $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).hidden = - configData.hideShortcuts; $(customize.IDS.COLORS_BUTTON).hidden = !configData.chromeColors; $(customize.IDS.COLOR_PICKER_CONTAINER) .classList.toggle( @@ -410,6 +409,9 @@ customize.clearAttribution = function() { }; customize.unselectTile = function() { + if (configData.richerPicker) { + return; + } $(customize.IDS.DONE).disabled = true; customize.selectedOptions.background = null; $(customize.IDS.DONE).tabIndex = -1; @@ -736,13 +738,13 @@ customize.tileOnKeyDownInteraction = function(event) { let target = null; if (event.keyCode === customize.KEYCODES.LEFT) { target = customize.getNextTile( - document.documentElement.classList.contains('rtl') ? 1 : -1, 0, + window.chrome.embeddedSearch.searchBox.rtl ? 1 : -1, 0, /** @type HTMLElement */ (tile)); } else if (event.keyCode === customize.KEYCODES.UP) { target = customize.getNextTile(0, -1, /** @type HTMLElement */ (tile)); } else if (event.keyCode === customize.KEYCODES.RIGHT) { target = customize.getNextTile( - document.documentElement.classList.contains('rtl') ? -1 : 1, 0, + window.chrome.embeddedSearch.searchBox.rtl ? -1 : 1, 0, /** @type HTMLElement */ (tile)); } else if (event.keyCode === customize.KEYCODES.DOWN) { target = customize.getNextTile(0, 1, /** @type HTMLElement */ (tile)); @@ -976,10 +978,7 @@ customize.richerPicker_selectBackgroundTile = function(tile) { return; } - $(customize.IDS.REFRESH_TOGGLE).checked = false; - - if (customize.selectedOptions.background && - customize.selectedOptions.background.id == tile.id) { + if (tile.parentElement.classList.contains(customize.CLASSES.SELECTED)) { // If the clicked tile is already selected do nothing. return; } else if (customize.selectedOptions.background) { @@ -988,6 +987,8 @@ customize.richerPicker_selectBackgroundTile = function(tile) { customize.selectedOptions.background); } + $(customize.IDS.REFRESH_TOGGLE).checked = false; + // Remove any existing preview. customize.richerPicker_unpreviewImage(); @@ -1032,6 +1033,8 @@ customize.richerPicker_selectShortcutType = function(shortcutType) { /** * Handles hide shortcuts toggle. Apply/remove styling for the toggle and * enable/disable the done button. + * Note: If the toggle is enabled, the options for shortcut type will appear + * "disabled". * @param {boolean} areHidden True if the shortcuts are hidden, i.e. the toggle * is on. */ @@ -1040,6 +1043,8 @@ customize.richerPicker_toggleShortcutHide = function(areHidden) { $(customize.IDS.SHORTCUTS_HIDE) .classList.toggle(customize.CLASSES.SELECTED, areHidden); $(customize.IDS.SHORTCUTS_HIDE_TOGGLE).checked = areHidden; + $(customize.IDS.SHORTCUTS_MENU) + .classList.toggle(customize.CLASSES.HIDDEN_SELECTED, areHidden); customize.selectedOptions.shortcutsAreHidden = areHidden; }; @@ -1052,7 +1057,7 @@ customize.richerPicker_toggleRefreshDaily = function(toggledOn) { $(customize.IDS.REFRESH_TOGGLE).checked = toggledOn; if (!toggledOn) { customize.richerPicker_selectBackgroundTile( - $(customize.IDS.BACKGROUNDS_DEFAULT)); + $(customize.IDS.BACKGROUNDS_DEFAULT_ICON)); return; } @@ -1061,6 +1066,7 @@ customize.richerPicker_toggleRefreshDaily = function(toggledOn) { customize.selectedOptions.background); } + customize.selectedOptions.background = null; customize.selectedOptions.backgroundData = { id: '', url: '', @@ -1200,7 +1206,7 @@ customize.showImageSelectionDialog = function(dialogTitle, collIndex) { tileId = 'coll_' + collIndex + '_' + tileId; } const tile = customize.createTileThumbnail( - tileId, collImg[i].imageUrl, dataset, tileOnClickInteraction, + tileId, collImg[i].thumbnailImageUrl, dataset, tileOnClickInteraction, customize.tileOnKeyDownInteraction); tile.setAttribute('aria-label', collImg[i].attributions[0]); @@ -1422,7 +1428,7 @@ customize.richerPicker_preselectBackgroundOption = function() { customize.preselectedOptions.backgroundsMenuTile = null; - const themeInfo = ntpApiHandle.themeBackgroundInfo; + const themeInfo = assert(ntpApiHandle.themeBackgroundInfo); if (!themeInfo.customBackgroundConfigured) { // Default. customize.preselectedOptions.backgroundsMenuTile = @@ -1751,7 +1757,7 @@ customize.initCustomBackgrounds = function(showErrorNotification) { const restoreDefaultInteraction = function() { editDialog.close(); customize.clearAttribution(); - window.chrome.embeddedSearch.newTabPage.setBackgroundURL(''); + window.chrome.embeddedSearch.newTabPage.resetBackgroundInfo(); }; $(customize.IDS.RESTORE_DEFAULT).onclick = (event) => { if (!$(customize.IDS.RESTORE_DEFAULT) @@ -1931,6 +1937,7 @@ customize.initCustomBackgrounds = function(showErrorNotification) { $(customize.IDS.BACKGROUNDS_MENU).onkeydown = function(event) { if (document.activeElement === $(customize.IDS.BACKGROUNDS_MENU) && customize.arrowKeys.includes(event.keyCode)) { + event.preventDefault(); $(customize.IDS.BACKGROUNDS_UPLOAD_ICON).focus(); } }; @@ -1938,6 +1945,7 @@ customize.initCustomBackgrounds = function(showErrorNotification) { $(customize.IDS.BACKGROUNDS_IMAGE_MENU).onkeydown = function(event) { if (document.activeElement === $(customize.IDS.BACKGROUNDS_IMAGE_MENU) && customize.arrowKeys.includes(event.keyCode)) { + event.preventDefault(); document.querySelector('[id$="img_tile_0"]').focus(); } }; @@ -1970,7 +1978,7 @@ customize.initCustomBackgrounds = function(showErrorNotification) { }; const richerPicker = $(customize.IDS.CUSTOMIZATION_MENU); - richerPicker.onclick = function(event) { + richerPicker.onmousedown = function(event) { richerPicker.classList.add(customize.CLASSES.MOUSE_NAV); }; richerPicker.onkeydown = function(event) { @@ -2006,6 +2014,12 @@ customize.initCustomBackgrounds = function(showErrorNotification) { const clOption = $(customize.IDS.SHORTCUTS_OPTION_CUSTOM_LINKS); const mvOption = $(customize.IDS.SHORTCUTS_OPTION_MOST_VISITED); const hideToggle = $(customize.IDS.SHORTCUTS_HIDE_TOGGLE); + + const rtl = window.chrome.embeddedSearch.searchBox.rtl; + const forwardArrowKey = + rtl ? customize.KEYCODES.LEFT : customize.KEYCODES.RIGHT; + const backArrowKey = rtl ? customize.KEYCODES.RIGHT : customize.KEYCODES.LEFT; + $(customize.IDS.SHORTCUTS_MENU).onkeydown = function(event) { if (customize.arrowKeys.includes(event.keyCode)) { clOption.focus(); @@ -2018,22 +2032,27 @@ customize.initCustomBackgrounds = function(showErrorNotification) { customize.LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_CUSTOM_LINKS_CLICKED); } customize.richerPicker_selectShortcutType(clOption); + // Selecting a shortcut type will turn off hidden shortcuts. + customize.richerPicker_toggleShortcutHide(false); }; clOption.onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.ENTER || - event.keyCode === customize.KEYCODES.SPACE) { - clOption.click(); - } else if (customize.arrowKeys.includes(event.keyCode)) { + if (customize.arrowKeys.includes(event.keyCode)) { // Handle arrow key navigation. event.preventDefault(); event.stopPropagation(); - if (event.keyCode === customize.KEYCODES.RIGHT) { + if (event.keyCode === forwardArrowKey) { mvOption.focus(); } else if (event.keyCode === customize.KEYCODES.DOWN) { hideToggle.focus(); } } }; + clOption.onkeyup = function(event) { + if (event.keyCode === customize.KEYCODES.ENTER || + event.keyCode === customize.KEYCODES.SPACE) { + clOption.click(); + } + }; mvOption.onclick = function() { if (customize.selectedOptions.shortcutType !== mvOption) { @@ -2041,24 +2060,29 @@ customize.initCustomBackgrounds = function(showErrorNotification) { customize.LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_MOST_VISITED_CLICKED); } customize.richerPicker_selectShortcutType(mvOption); + // Selecting a shortcut type will turn off hidden shortcuts. + customize.richerPicker_toggleShortcutHide(false); }; mvOption.onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.ENTER || - event.keyCode === customize.KEYCODES.SPACE) { - mvOption.click(); - } else if (customize.arrowKeys.includes(event.keyCode)) { + if (customize.arrowKeys.includes(event.keyCode)) { // Handle arrow key navigation. event.preventDefault(); event.stopPropagation(); - if (event.keyCode === customize.KEYCODES.LEFT) { + if (event.keyCode === backArrowKey) { clOption.focus(); } else if ( - event.keyCode === customize.KEYCODES.RIGHT || + event.keyCode === forwardArrowKey || event.keyCode === customize.KEYCODES.DOWN) { hideToggle.focus(); } } }; + mvOption.onkeyup = function(event) { + if (event.keyCode === customize.KEYCODES.ENTER || + event.keyCode === customize.KEYCODES.SPACE) { + mvOption.click(); + } + }; hideToggle.onchange = function(event) { customize.richerPicker_toggleShortcutHide(hideToggle.checked); @@ -2066,19 +2090,22 @@ customize.initCustomBackgrounds = function(showErrorNotification) { customize.LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_VISIBILITY_TOGGLE_CLICKED); }; hideToggle.onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.ENTER || - event.keyCode === customize.KEYCODES.SPACE) { - hideToggle.onchange(event); - } else if (customize.arrowKeys.includes(event.keyCode)) { + if (customize.arrowKeys.includes(event.keyCode)) { // Handle arrow key navigation. event.preventDefault(); event.stopPropagation(); - if (event.keyCode === customize.KEYCODES.LEFT || + if (event.keyCode === backArrowKey || event.keyCode === customize.KEYCODES.UP) { mvOption.focus(); } } }; + hideToggle.onkeyup = function(event) { + // Handle enter since, unlike space, it does not trigger a click event. + if (event.keyCode === customize.KEYCODES.ENTER) { + hideToggle.click(); + } + }; hideToggle.onclick = function(event) { // Enter and space fire the 'onclick' event (which will remove special // keyboard navigation styling) unless propagation is stopped. @@ -2091,10 +2118,10 @@ customize.initCustomBackgrounds = function(showErrorNotification) { customize.LOG_TYPE.NTP_BACKGROUND_REFRESH_TOGGLE_CLICKED); customize.richerPicker_toggleRefreshDaily(refreshToggle.checked); }; - refreshToggle.onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.ENTER || - event.keyCode === customize.KEYCODES.SPACE) { - refreshToggle.onchange(event); + refreshToggle.onkeyup = function(event) { + // Handle enter since, unlike space, it does not trigger a click event. + if (event.keyCode === customize.KEYCODES.ENTER) { + refreshToggle.click(); } }; refreshToggle.onclick = function(event) { @@ -2240,10 +2267,8 @@ customize.loadColorsMenu = function() { const tile = customize.createTileWithoutTitle( id, imageUrl, dataset, customize.colorTileInteraction, customize.tileOnKeyDownInteraction); - const label = configData.translatedStrings.colorLabelPrefix + ' ' + - colorArrayToHex(colorsColl[i].color); - tile.firstElementChild.setAttribute('aria-label', label); - tile.firstElementChild.setAttribute('title', label); + tile.firstElementChild.setAttribute('aria-label', colorsColl[i].label); + tile.firstElementChild.setAttribute('title', colorsColl[i].label); $(customize.IDS.COLORS_MENU).appendChild(tile); } @@ -2263,6 +2288,7 @@ customize.loadColorsMenu = function() { } else { $(customize.IDS.COLORS_DEFAULT_ICON).focus(); } + event.preventDefault(); } }; @@ -2289,7 +2315,7 @@ customize.loadColorsMenu = function() { */ customize.colorsMenuOnThemeChange = function() { // Update webstore theme information. - const themeInfo = ntpApiHandle.themeBackgroundInfo; + const themeInfo = assert(ntpApiHandle.themeBackgroundInfo); if (themeInfo.themeId && themeInfo.themeName) { $(customize.IDS.COLORS_THEME).classList.add(customize.CLASSES.VISIBLE); $(customize.IDS.COLORS_THEME_NAME).innerHTML = themeInfo.themeName; @@ -2297,19 +2323,26 @@ customize.colorsMenuOnThemeChange = function() { 'https://chrome.google.com/webstore/detail/' + themeInfo.themeId; $(customize.IDS.COLORS_THEME_UNINSTALL).onclick = ntpApiHandle.useDefaultTheme; + + // Clear the previous selection, if any. + if (customize.selectedOptions.color) { + customize.richerPicker_removeSelectedState( + customize.selectedOptions.color); + customize.selectedOptions.color = null; + } } else { $(customize.IDS.COLORS_THEME).classList.remove(customize.CLASSES.VISIBLE); - } - // Select the tile corresponding to the current theme/color. - customize.colorsMenuPreselectTile(); + // Select the tile corresponding to the current theme/color. + customize.colorsMenuPreselectTile(); + } }; /** * Preselect Colors menu tile according to the theme info. */ customize.colorsMenuPreselectTile = function() { - const themeInfo = ntpApiHandle.themeBackgroundInfo; + const themeInfo = assert(ntpApiHandle.themeBackgroundInfo); let tile; if (themeInfo.usingDefaultTheme) { diff --git a/chromium/chrome/browser/resources/local_ntp/externs.js b/chromium/chrome/browser/resources/local_ntp/externs.js index a520ad5e2e1..04feef1b03c 100644 --- a/chromium/chrome/browser/resources/local_ntp/externs.js +++ b/chromium/chrome/browser/resources/local_ntp/externs.js @@ -29,7 +29,6 @@ let MostVisitedData; * @typedef {{chromeColors: boolean, * enableShortcutsGrid: boolean, * googleBaseUrl: string, - * hideShortcuts: boolean, * isAccessibleBrowser: boolean, * isGooglePage: boolean, * richerPicker: boolean, @@ -290,9 +289,9 @@ window.chrome.embeddedSearch.newTabPage.searchSuggestionSelected; window.chrome.embeddedSearch.newTabPage.selectLocalBackgroundImage; /** - * @param {string} background_url + * No params. */ -window.chrome.embeddedSearch.newTabPage.setBackgroundURL; +window.chrome.embeddedSearch.newTabPage.resetBackgroundInfo; /** * @param {string} background_url @@ -304,8 +303,38 @@ window.chrome.embeddedSearch.newTabPage.setBackgroundURL; window.chrome.embeddedSearch.newTabPage.setBackgroundInfo; /** - * @return {Object} theme_background_info - */ + * @typedef {{ + * alternateLogo: boolean, + * attribution1: (string|undefined), + * attribution2: (string|undefined), + * attributionActionUrl: (string|undefined), + * attributionUrl: (string|undefined), + * backgroundColorRgba: !Array<number>, + * collectionId: (string|undefined), + * colorDark: (!Array<number>|undefined), + * colorId: (number|undefined), + * colorLight: (!Array<number>|undefined), + * colorPicked: (!Array<number>|undefined), + * customBackgroundConfigured: boolean, + * iconBackgroundColor: !Array<number>, + * imageHorizontalAlignment: (string|undefined), + * imageTiling: (string|undefined), + * imageUrl: (string|undefined), + * imageVerticalAlignment: (string|undefined), + * isNtpBackgroundDark: boolean, + * logoColor: (!Array<number>|undefined), + * textColorLightRgba: !Array<number>, + * textColorRgba: !Array<number>, + * themeId: (string|undefined), + * themeName: (string|undefined), + * useTitleContainer: boolean, + * useWhiteAddIcon: boolean, + * usingDefaultTheme: boolean, + * }} + */ +let ThemeBackgroundInfo; + +/** @type {?ThemeBackgroundInfo} */ window.chrome.embeddedSearch.newTabPage.themeBackgroundInfo; /** @@ -352,6 +381,7 @@ window.chrome.embeddedSearch.newTabPage.updateCustomLink; window.chrome.embeddedSearch.searchBox; window.chrome.embeddedSearch.searchBox.isKeyCaptureEnabled; window.chrome.embeddedSearch.searchBox.paste; +window.chrome.embeddedSearch.searchBox.rtl; window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes; window.chrome.embeddedSearch.searchBox.stopCapturingKeyStrokes; @@ -371,7 +401,6 @@ configData.translatedStrings.audioError; configData.translatedStrings.backLabel; configData.translatedStrings.backgroundsUnavailable; configData.translatedStrings.clickToViewDoodle; -configData.translatedStrings.colorLabelPrefix; configData.translatedStrings.connectionError; configData.translatedStrings.connectionErrorNoPeriod; configData.translatedStrings.copyLink; diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.css b/chromium/chrome/browser/resources/local_ntp/local_ntp.css index ee6457ca9e8..206b5f9e96f 100644 --- a/chromium/chrome/browser/resources/local_ntp/local_ntp.css +++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.css @@ -36,7 +36,6 @@ html { /* These can be overridden by themes. */ --text-color: #000; --text-color-light: #fff; - --text-color-link: rgb(17, 85, 204); height: 100%; } @@ -46,7 +45,6 @@ html { /* These can be overridden by themes. */ --text-color: rgb(var(--GG200-rgb)); --text-color-light: rgb(var(--GG200-rgb)); - --text-color-link: rgb(var(--GB400-dark-rgb)); } } @@ -73,7 +71,7 @@ body { min-height: 100%; } -body.inited { +html.inited body { display: block; } @@ -200,6 +198,7 @@ html[dir=rtl] #fakebox-search-icon { text-align: initial; text-overflow: ellipsis; top: 0; + user-select: none; vertical-align: middle; visibility: inherit; white-space: nowrap; @@ -831,7 +830,7 @@ html[dir=rtl] .menu-option { height: 32px; line-height: 32px; margin-inline-start: 16px; - max-width: 126px; + max-width: 125px; overflow: hidden; text-overflow: ellipsis; user-select: none; @@ -892,6 +891,7 @@ html[dir=rtl] .menu-option { margin-inline-start: 40px; position: relative; width: 568px; + z-index: 1; } .menu-panel { @@ -1233,6 +1233,10 @@ html[dir=rtl] #customization-menu .bg-sel-tile .selected-check { width: 268px; } +#shortcuts-menu.hidden-selected .sh-option { + color: rgb(var(--GG500-rgb)); +} + .sh-option-image { border: 1px solid rgb(var(--GG300-rgb)); border-radius: 4px; @@ -1249,13 +1253,13 @@ html[dir=rtl] #customization-menu .bg-sel-tile .selected-check { } } -.selected .sh-option-image { +#shortcuts-menu:not(.hidden-selected) .selected .sh-option-image { background-color: rgb(var(--GB050-rgb)); border-color: rgb(var(--GB600-rgb)); } @media (prefers-color-scheme: dark) { - .selected .sh-option-image { + #shortcuts-menu:not(.hidden-selected) .selected .sh-option-image { background-color: rgba(var(--GB200-rgb), .1); border-color: rgb(var(--GB300-rgb)); } @@ -1285,13 +1289,13 @@ html[dir=rtl] .sh-option-mini { right: unset; } -.selected .sh-option-mini { +#shortcuts-menu:not(.hidden-selected) .selected .sh-option-mini { box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3), 0 4px 8px 3px rgba(var(--GG800-rgb), .15); } @media (prefers-color-scheme: dark) { - .selected .sh-option-mini { + #shortcuts-menu:not(.hidden-selected) .selected .sh-option-mini { border-color: transparent; box-shadow: var(--dark-mode-shadow); } @@ -1301,12 +1305,12 @@ html[dir=rtl] .sh-option-mini { background-color: rgb(var(--GG500-rgb)); } -.selected .sh-option-mini .mini-shortcuts { +#shortcuts-menu:not(.hidden-selected) .selected .mini-shortcuts { background-color: rgb(var(--GB600-rgb)); } @media (prefers-color-scheme: dark) { - .selected .sh-option-mini .mini-shortcuts { + #shortcuts-menu:not(.hidden-selected) .selected .mini-shortcuts { background-color: rgb(var(--GB300-rgb)); } } @@ -1340,12 +1344,12 @@ html[dir=rtl] .sh-option-icon { } } -.selected .sh-option-icon { +#shortcuts-menu:not(.hidden-selected) .selected .sh-option-icon { background-color: rgba(var(--GB600-rgb), .24); } @media (prefers-color-scheme: dark) { - .selected .sh-option-icon { + #shortcuts-menu:not(.hidden-selected) .selected .sh-option-icon { background-color: rgb(var(--GB300-rgb)); } } @@ -1375,6 +1379,11 @@ html[dir=rtl] .sh-option-image .selected-check { right: initial; } +#shortcuts-menu.hidden-selected .sh-option-image + :-webkit-any(.selected-circle, .selected-check) { + display: none; +} + .sh-option-title { font-weight: bold; margin: 8px 0; @@ -1768,6 +1777,12 @@ html[dir=rtl] #left-semicircle { border-top-right-radius: var(--tile-size); } +#colors-theme-info { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + #refresh-daily-wrapper { display: none; margin-inline-start: auto; diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.html b/chromium/chrome/browser/resources/local_ntp/local_ntp.html index f394f37fe88..0893eb63f94 100644 --- a/chromium/chrome/browser/resources/local_ntp/local_ntp.html +++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.html @@ -14,6 +14,8 @@ $i18nRaw{bgPreloader} <meta http-equiv="Content-Security-Policy" content="$i18nRaw{contentSecurityPolicy}"> + <script src="chrome-search://local-ntp/assert.js" + integrity="$i18n{assertIntegrity}"></script> <script src="chrome-search://local-ntp/animations.js" integrity="$i18n{animationsIntegrity}"></script> <script src="chrome-search://local-ntp/config.js" @@ -230,7 +232,7 @@ <div id="backgrounds-upload" class="bg-sel-tile-bg"> <div id="backgrounds-upload-icon" class="bg-sel-tile" tabindex="-1" role="button" aria-label="$i18n{uploadImage}" - title="$i18n{uploadImage}" aria-pressed="false"> + aria-pressed="false" title="$i18n{uploadImage}"> <div id="backgrounds-upload-arrow"></div> <div id="backgrounds-upload-text">$i18n{uploadImage}</div> </div> @@ -309,7 +311,7 @@ aria-label="$i18n{colorsOption}"> <div id="colors-theme" tabindex="0"> <div id="colors-theme-icon"></div> - <div> + <div id="colors-theme-info"> <div id="colors-theme-name"></div> $i18n{installedThemeDesc} </div> @@ -333,9 +335,10 @@ </div> <div id="colors-default" class="bg-sel-tile-bg"> <div id="colors-default-icon" class="bg-sel-tile" tabindex="-1" - aria-label="$i18n{defaultThemeLabel}" - title="$i18n{defaultThemeLabel}" - role="button" aria-pressed="false"></div> + aria-label="$i18n{defaultThemeLabel}" + title="$i18n{defaultThemeLabel}" tabindex="-1" + role="button" aria-pressed="false"> + </div> </div> </div> </div> diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.js b/chromium/chrome/browser/resources/local_ntp/local_ntp.js index 0622671e086..21ebc4ef20f 100644 --- a/chromium/chrome/browser/resources/local_ntp/local_ntp.js +++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.js @@ -6,13 +6,7 @@ * @fileoverview The local InstantExtended NTP. */ -/** - * Whether the most visited tiles have finished loading, i.e. we've received the - * 'loaded' postMessage from the iframe. Used by tests to detect that loading - * has completed. - * @type {boolean} - */ -let tilesAreLoaded = false; +// Global local statics (visible for testing). /** * Whether the Most Visited and edit custom link iframes should be created while @@ -23,51 +17,21 @@ let tilesAreLoaded = false; let iframesAndVoiceSearchDisabledForTesting = false; /** + * Whether the most visited tiles have finished loading, i.e. we've received the + * 'loaded' postMessage from the iframe. Used by tests to detect that loading + * has completed. + * @type {boolean} + */ +let tilesAreLoaded = false; + +/** * Controls rendering the new tab page for InstantExtended. * @return {Object} A limited interface for testing the local NTP. */ function LocalNTP() { 'use strict'; -/** - * Called by tests to disable the creation of Most Visited and edit custom link - * iframes. - */ -function disableIframesAndVoiceSearchForTesting() { - iframesAndVoiceSearchDisabledForTesting = true; -} - -/** - * Specifications for an NTP design (not comprehensive). - * - * backgroundColor: The 4-component color of default background, - * darkBackgroundColor: The 4-component color of default dark background, - * iconBackgroundColor: The 4-component color of default dark icon background, - * iconDarkBackgroundColor: The 4-component color of default icon background, - * numTitleLines: Number of lines to display in titles. - * titleColor: The 4-component color of title text. - * titleColorAgainstDark: The 4-component color of title text against a dark - * theme. - * - * @type {{ - * backgroundColor: Array<number>, - * darkBackgroundColor: Array<number>, - * iconBackgroundColor: Array<number>, - * iconDarkBackgroundColor: Array<number>, - * numTitleLines: number, - * titleColor: Array<number>, - * titleColorAgainstDark: Array<number>, - * }} - */ -const NTP_DESIGN = { - backgroundColor: [255, 255, 255, 255], - darkBackgroundColor: [50, 54, 57, 255], - iconBackgroundColor: [241, 243, 244, 255], /** GG100 */ - iconDarkBackgroundColor: [32, 33, 36, 255], /** GG900 */ - numTitleLines: 1, - titleColor: [60, 64, 67, 255], /** GG800 */ - titleColorAgainstDark: [248, 249, 250, 255], /** GG050 */ -}; +// Constants. /** * Enum for classnames. @@ -107,6 +71,21 @@ const CLASSES = { }; /** + * Background color for Chrome dark mode. Used to determine if it is possible to + * display a Google Doodle, or if the notifier should be used instead. + * @type {string} + * @const + */ +const DARK_MODE_BACKGROUND_COLOR = 'rgba(50,54,57,1)'; + +/** + * The period of time (ms) before transitions can be applied to a toast + * notification after modifying the "display" property. + * @type {number} + */ +const DISPLAY_TIMEOUT = 20; + +/** * Enum for HTML element ids. * @enum {string} * @const @@ -165,6 +144,14 @@ const LOG_TYPE = { }; /** + * The maximum number of tiles to show in the Most Visited section if custom + * links is enabled. + * @type {number} + * @const + */ +const MAX_NUM_TILES_CUSTOM_LINKS = 10; + +/** * The maximum number of tiles to show in the Most Visited section. * @type {number} * @const @@ -172,12 +159,42 @@ const LOG_TYPE = { const MAX_NUM_TILES_MOST_VISITED = 8; /** - * The maximum number of tiles to show in the Most Visited section if custom - * links is enabled. + * The period of time (ms) before the Most Visited notification is hidden. * @type {number} - * @const */ -const MAX_NUM_TILES_CUSTOM_LINKS = 10; +const NOTIFICATION_TIMEOUT = 10000; + +/** + * Specifications for an NTP design (not comprehensive). + * + * backgroundColor: The 4-component color of default background, + * darkBackgroundColor: The 4-component color of default dark background, + * iconBackgroundColor: The 4-component color of default dark icon background, + * iconDarkBackgroundColor: The 4-component color of default icon background, + * numTitleLines: Number of lines to display in titles. + * titleColor: The 4-component color of title text. + * titleColorAgainstDark: The 4-component color of title text against a dark + * theme. + * + * @type {{ + * backgroundColor: !Array<number>, + * darkBackgroundColor: !Array<number>, + * iconBackgroundColor: !Array<number>, + * iconDarkBackgroundColor: !Array<number>, + * numTitleLines: number, + * titleColor: !Array<number>, + * titleColorAgainstDark: !Array<number>, + * }} + */ +const NTP_DESIGN = { + backgroundColor: [255, 255, 255, 255], + darkBackgroundColor: [50, 54, 57, 255], + iconBackgroundColor: [241, 243, 244, 255], /** GG100 */ + iconDarkBackgroundColor: [32, 33, 36, 255], /** GG900 */ + numTitleLines: 1, + titleColor: [60, 64, 67, 255], /** GG800 */ + titleColorAgainstDark: [248, 249, 250, 255], /** GG050 */ +}; /** * Background colors considered "white". Used to determine if it is possible to @@ -187,33 +204,27 @@ const MAX_NUM_TILES_CUSTOM_LINKS = 10; */ const WHITE_BACKGROUND_COLORS = ['rgba(255,255,255,1)', 'rgba(0,0,0,0)']; -/** - * Background color for Chrome dark mode. Used to determine if it is possible to - * display a Google Doodle, or if the notifier should be used instead. - * @type {string} - * @const - */ -const DARK_MODE_BACKGROUND_COLOR = 'rgba(50,54,57,1)'; +// Local statics. /** - * Enum for keycodes. - * @enum {number} - * @const + * The currently visible notification element. Null if no notification is + * present. + * @type {?Object} */ -const KEYCODE = {ENTER: 13, SPACE: 32}; +let currNotification = null; /** - * The period of time (ms) before the Most Visited notification is hidden. - * @type {number} + * The timeout function for automatically hiding the pop-up notification. Only + * set if a notification is visible. + * @type {?Object} */ -const NOTIFICATION_TIMEOUT = 10000; +let delayedHideNotification = null; /** - * The period of time (ms) before transitions can be applied to a toast - * notification after modifying the "display" property. - * @type {number} + * True if dark mode is enabled. + * @type {boolean} */ -const DISPLAY_TIMEOUT = 20; +let isDarkModeEnabled = false; /** * The last blacklisted tile rid if any, which by definition should not be @@ -223,30 +234,22 @@ const DISPLAY_TIMEOUT = 20; let lastBlacklistedTile = null; /** - * The timeout function for automatically hiding the pop-up notification. Only - * set if a notification is visible. - * @type {?Object} - */ -let delayedHideNotification = null; - -/** - * The currently visible notification element. Null if no notification is - * present. - * @type {?Object} - */ -let currNotification = null; - -/** * The browser embeddedSearch.newTabPage object. * @type {Object} */ let ntpApiHandle; +// Helper methods. + /** - * True if dark mode is enabled. - * @type {boolean} + * Converts an Array of color components into RGBA format "rgba(R,G,B,A)". + * @param {Array<number>} color Array of rgba color components. + * @return {string} CSS color in RGBA format. */ -let isDarkModeEnabled = false; +function convertToRGBAColor(color) { + return 'rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ',' + + color[3] / 255 + ')'; +} /** * Returns a timeout that can be executed early. Calls back true if this was @@ -270,419 +273,174 @@ function createExecutableTimeout(timeout, delay) { }; } -/** - * Called by tests to override the executable timeout with a test timeout. - * @param {!Function} timeout The timeout function. Requires a boolean param. - */ -function overrideExecutableTimeoutForTesting(timeout) { - createExecutableTimeout = timeout; -} - -/** - * Returns theme background info, first checking for history.state.notheme. If - * the page has notheme set, returns a fallback light-colored theme (or dark- - * colored theme if dark mode is enabled). This is used when the doodle is - * displayed after clicking the notifier. - */ -function getThemeBackgroundInfo() { - if (history.state && history.state.notheme) { - return { - alternateLogo: false, - backgroundColorRgba: - (isDarkModeEnabled ? NTP_DESIGN.darkBackgroundColor : - NTP_DESIGN.backgroundColor), - customBackgroundConfigured: false, - iconBackgroundColor: - (isDarkModeEnabled ? NTP_DESIGN.iconDarkBackgroundColor : - NTP_DESIGN.iconBackgroundColor), - isNtpBackgroundDark: isDarkModeEnabled, - textColorLightRgba: [102, 102, 102, 255], - textColorRgba: - (isDarkModeEnabled ? NTP_DESIGN.titleColorAgainstDark : - NTP_DESIGN.titleColor), - useTitleContainer: false, - useWhiteAddIcon: isDarkModeEnabled, - usingDarkMode: isDarkModeEnabled, - usingDefaultTheme: true, - }; - } - - const info = window.chrome.embeddedSearch.newTabPage.themeBackgroundInfo; - const preview = $(customize.IDS.CUSTOM_BG_PREVIEW); - if (preview.dataset.hasPreview === 'true') { - info.isNtpBackgroundDark = preview.dataset.hasImage === 'true'; - info.customBackgroundConfigured = preview.dataset.hasImage === 'true'; - info.alternateLogo = preview.dataset.hasImage === 'true'; - // backgroundImage is in the form: url("actual url"). Remove everything - // except the actual url. - info.imageUrl = preview.style.backgroundImage.slice(5, -2); - } - return info; -} - -/** - * Determine whether dark chips should be used if dark mode is enabled. This is - * is the case when dark mode is enabled and a background image (from a custom - * background or user theme) is not set. - * - * @param {!Object} info Theme background information. - * @return {boolean} Whether the chips should be dark. - */ -function getUseDarkChips(info) { - return window.matchMedia('(prefers-color-scheme: dark)').matches && - !info.imageUrl; -} - -/** - * Updates the NTP based on the current theme. - */ -function renderTheme() { - const info = getThemeBackgroundInfo(); - if (!info) { - return; - } - - $(IDS.NTP_CONTENTS).classList.toggle(CLASSES.DARK, info.isNtpBackgroundDark); - - // Update dark mode styling. - isDarkModeEnabled = window.matchMedia('(prefers-color-scheme: dark)').matches; - document.body.classList.toggle('light-chip', !getUseDarkChips(info)); +/** Create the Most Visited and edit custom links iframes. */ +function createIframes() { + // Collect arguments for the most visited iframe. + const args = []; - const background = [ - convertToRGBAColor(info.backgroundColorRgba), info.imageUrl, - info.imageTiling, info.imageHorizontalAlignment, info.imageVerticalAlignment - ].join(' ').trim(); + const searchboxApiHandle = window.chrome.embeddedSearch.searchBox; - // If a custom background has been selected the image will be applied to the - // custom-background element instead of the body. - if (!info.customBackgroundConfigured) { - document.body.style.background = background; + if (searchboxApiHandle.rtl) { + args.push('rtl=1'); } - - // Dark mode uses a white Google logo. - const useWhiteLogo = - info.alternateLogo || (info.usingDefaultTheme && isDarkModeEnabled); - document.body.classList.toggle(CLASSES.ALTERNATE_LOGO, useWhiteLogo); - const isNonWhiteBackground = !WHITE_BACKGROUND_COLORS.includes(background); - document.body.classList.toggle(CLASSES.NON_WHITE_BG, isNonWhiteBackground); - - if (info.logoColor) { - document.body.style.setProperty( - '--logo-color', convertToRGBAColor(info.logoColor)); + if (NTP_DESIGN.numTitleLines > 1) { + args.push('ntl=' + NTP_DESIGN.numTitleLines); } - // The doodle notifier should be shown for non-default backgrounds. This - // includes non-white backgrounds, excluding dark mode gray if dark mode is - // enabled. - const isDefaultBackground = WHITE_BACKGROUND_COLORS.includes(background) || - (isDarkModeEnabled && background === DARK_MODE_BACKGROUND_COLOR); - document.body.classList.toggle(CLASSES.USE_NOTIFIER, !isDefaultBackground); - - updateThemeAttribution(info.attributionUrl, info.imageHorizontalAlignment); - setCustomThemeStyle(info); - - if (info.customBackgroundConfigured) { - // Do anything only if the custom background changed. - if (!$(IDS.CUSTOM_BG).style.backgroundImage.includes(info.imageUrl)) { - const imageWithOverlay = [ - customize.CUSTOM_BACKGROUND_OVERLAY, 'url(' + info.imageUrl + ')' - ].join(',').trim(); - // If the theme update is because of uploading a local image then we - // should close the customization menu. Closing the menu before the image - // is selected doesn't look good. - const localImageFileName = 'background.jpg'; - if (!configData.richerPicker && - imageWithOverlay.includes(localImageFileName) && - !$(IDS.CUSTOM_BG) - .style.backgroundImage.includes(localImageFileName)) { - customize.closeCustomizationDialog(); - } - // |image| and |imageWithOverlay| use the same url as their source. - // Waiting to display the custom background until |image| is fully - // loaded ensures that |imageWithOverlay| is also loaded. - $(IDS.CUSTOM_BG).style.backgroundImage = imageWithOverlay; - const image = new Image(); - image.onload = function() { - $(IDS.CUSTOM_BG).style.opacity = '1'; - }; - image.src = info.imageUrl; + args.push( + 'title=' + + encodeURIComponent(configData.translatedStrings.mostVisitedTitle)); + args.push( + 'removeTooltip=' + + encodeURIComponent(configData.translatedStrings.removeThumbnailTooltip)); - customize.clearAttribution(); - customize.setAttribution( - info.attribution1, info.attribution2, info.attributionActionUrl); + if (configData.isGooglePage) { + args.push('enableCustomLinks=1'); + if (configData.enableShortcutsGrid) { + args.push('enableGrid=1'); } - } else { - $(IDS.CUSTOM_BG).style.opacity = '0'; - customize.clearAttribution(); + args.push( + 'addLink=' + + encodeURIComponent(configData.translatedStrings.addLinkTitle)); + args.push( + 'addLinkTooltip=' + + encodeURIComponent(configData.translatedStrings.addLinkTooltip)); + args.push( + 'editLinkTooltip=' + + encodeURIComponent(configData.translatedStrings.editLinkTooltip)); } - $(customize.IDS.RESTORE_DEFAULT) - .classList.toggle( - customize.CLASSES.OPTION_DISABLED, !info.customBackgroundConfigured); - $(customize.IDS.RESTORE_DEFAULT).tabIndex = - (info.customBackgroundConfigured ? 0 : -1); + // Create the most visited iframe. + const iframe = document.createElement('iframe'); + iframe.id = IDS.TILES_IFRAME; + iframe.name = IDS.TILES_IFRAME; + iframe.title = configData.translatedStrings.mostVisitedTitle; + iframe.src = 'chrome-search://most-visited/single.html?' + args.join('&'); + $(IDS.TILES).appendChild(iframe); - $(customize.IDS.EDIT_BG) - .classList.toggle( - CLASSES.ENTRY_POINT_ENHANCED, !info.customBackgroundConfigured); + iframe.onload = function() { + sendThemeInfoToMostVisitedIframe(); + reloadTiles(); + }; if (configData.isGooglePage) { - customize.onThemeChange(); - } -} - -/** - * Sends the current theme info to the most visited iframe. - */ -function sendThemeInfoToMostVisitedIframe() { - const info = getThemeBackgroundInfo(); - if (!info) { - return; - } + // Collect arguments for the edit custom link iframe. + const clArgs = []; - const message = {cmd: 'updateTheme'}; - message.isThemeDark = info.isNtpBackgroundDark; - message.customBackground = info.customBackgroundConfigured; - message.useTitleContainer = info.useTitleContainer; - message.iconBackgroundColor = convertToRGBAColor(info.iconBackgroundColor); - message.useWhiteAddIcon = info.useWhiteAddIcon; + if (searchboxApiHandle.rtl) { + clArgs.push('rtl=1'); + } - let titleColor = NTP_DESIGN.titleColor; - if (!info.usingDefaultTheme && info.textColorRgba) { - titleColor = info.textColorRgba; - } else if (info.isNtpBackgroundDark) { - titleColor = NTP_DESIGN.titleColorAgainstDark; - } - message.tileTitleColor = convertToRGBAColor(titleColor); + clArgs.push( + 'addTitle=' + + encodeURIComponent(configData.translatedStrings.addLinkTitle)); + clArgs.push( + 'editTitle=' + + encodeURIComponent(configData.translatedStrings.editLinkTitle)); + clArgs.push( + 'nameField=' + + encodeURIComponent(configData.translatedStrings.nameField)); + clArgs.push( + 'urlField=' + + encodeURIComponent(configData.translatedStrings.urlField)); + clArgs.push( + 'linkRemove=' + + encodeURIComponent(configData.translatedStrings.linkRemove)); + clArgs.push( + 'linkCancel=' + + encodeURIComponent(configData.translatedStrings.linkCancel)); + clArgs.push( + 'linkDone=' + + encodeURIComponent(configData.translatedStrings.linkDone)); + clArgs.push( + 'invalidUrl=' + + encodeURIComponent(configData.translatedStrings.invalidUrl)); - const iframe = $(IDS.TILES_IFRAME); - if (iframe) { - iframe.contentWindow.postMessage(message, '*'); + // Create the edit custom link iframe. + const clIframe = document.createElement('iframe'); + clIframe.id = IDS.CUSTOM_LINKS_EDIT_IFRAME; + clIframe.name = IDS.CUSTOM_LINKS_EDIT_IFRAME; + clIframe.title = configData.translatedStrings.editLinkTitle; + clIframe.src = 'chrome-search://most-visited/edit.html?' + clArgs.join('&'); + const clIframeDialog = document.createElement('dialog'); + clIframeDialog.id = IDS.CUSTOM_LINKS_EDIT_IFRAME_DIALOG; + clIframeDialog.classList.add(CLASSES.CUSTOMIZE_DIALOG); + clIframeDialog.appendChild(clIframe); + document.body.appendChild(clIframeDialog); } -} -/** - * Updates the OneGoogleBar (if it is loaded) based on the current theme. - * TODO(crbug.com/918582): Add support for OGB dark mode. - */ -function renderOneGoogleBarTheme() { - if (!window.gbar) { - return; - } - try { - const oneGoogleBarApi = window.gbar.a; - const oneGoogleBarPromise = oneGoogleBarApi.bf(); - oneGoogleBarPromise.then(function(oneGoogleBar) { - const setForegroundStyle = oneGoogleBar.pc.bind(oneGoogleBar); - setForegroundStyle(getThemeBackgroundInfo().isNtpBackgroundDark ? 1 : 0); - }); - } catch (err) { - console.log('Failed setting OneGoogleBar theme:\n' + err); - } + window.addEventListener('message', handlePostMessage); } /** - * Callback for embeddedSearch.newTabPage.onthemechange. + * Return true if custom links are enabled. + * @return {boolean} */ -function onThemeChange() { - renderTheme(); - renderOneGoogleBarTheme(); - sendThemeInfoToMostVisitedIframe(); +function customLinksEnabled() { + return configData.isGooglePage && + !chrome.embeddedSearch.newTabPage.isUsingMostVisited; } /** - * Updates the NTP style according to theme. - * @param {Object} themeInfo The information about the theme. + * Called by tests to disable the creation of Most Visited and edit custom link + * iframes. */ -function setCustomThemeStyle(themeInfo) { - let textColor = ''; - let textColorLight = ''; - let mvxFilter = ''; - if (!themeInfo.usingDefaultTheme) { - textColor = convertToRGBAColor(themeInfo.textColorRgba); - textColorLight = convertToRGBAColor(themeInfo.textColorLightRgba); - mvxFilter = 'drop-shadow(0 0 0 ' + textColor + ')'; - } - - $(IDS.NTP_CONTENTS) - .classList.toggle(CLASSES.DEFAULT_THEME, themeInfo.usingDefaultTheme); - - document.body.style.setProperty('--text-color', textColor); - document.body.style.setProperty('--text-color-light', textColorLight); - // Themes reuse the "light" text color for links too. - document.body.style.setProperty('--text-color-link', textColorLight); +function disableIframesAndVoiceSearchForTesting() { + iframesAndVoiceSearchDisabledForTesting = true; } /** - * Renders the attribution if the URL is present, otherwise hides it. - * @param {string} url The URL of the attribution image, if any. - * @param {string} themeBackgroundAlignment The alignment of the theme - * background image. This is used to compute the attribution's alignment. + * Animates the pop-up notification to float down, and clears the timeout to + * hide the notification. + * @param {?Element} notification The notification element. + * @param {?Element} notificationContainer The notification container element. + * @param {boolean} showPromo Do show the promo if present. */ -function updateThemeAttribution(url, themeBackgroundAlignment) { - if (!url) { - setAttributionVisibility_(false); +function floatDownNotification(notification, notificationContainer, showPromo) { + if (!notification || !notificationContainer) { return; } - const attribution = $(IDS.ATTRIBUTION); - let attributionImage = attribution.querySelector('img'); - if (!attributionImage) { - attributionImage = new Image(); - attribution.appendChild(attributionImage); - } - attributionImage.style.content = url; - - // To avoid conflicts, place the attribution on the left for themes that - // right align their background images. - attribution.classList.toggle( - CLASSES.LEFT_ALIGN_ATTRIBUTION, themeBackgroundAlignment == 'right'); - setAttributionVisibility_(true); -} - -/** - * Sets the visibility of the theme attribution. - * @param {boolean} show True to show the attribution. - */ -function setAttributionVisibility_(show) { - $(IDS.ATTRIBUTION).style.display = show ? '' : 'none'; -} - -/** - * Converts an Array of color components into RGBA format "rgba(R,G,B,A)". - * @param {Array<number>} color Array of rgba color components. - * @return {string} CSS color in RGBA format. - */ -function convertToRGBAColor(color) { - return 'rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ',' + - color[3] / 255 + ')'; -} - -/** - * Callback for embeddedSearch.newTabPage.onmostvisitedchange. Called when the - * NTP tiles are updated. - */ -function onMostVisitedChange() { - reloadTiles(); -} - -/** - * Fetches new data (RIDs) from the embeddedSearch.newTabPage API and passes - * them to the iframe. - */ -function reloadTiles() { - // Don't attempt to load tiles if the MV data isn't available yet - this can - // happen occasionally, see https://crbug.com/794942. In that case, we should - // get an onMostVisitedChange call once they are available. - // Note that MV data being available is different from having > 0 tiles. There - // can legitimately be 0 tiles, e.g. if the user blacklisted them all. - if (!ntpApiHandle.mostVisitedAvailable) { + if (!notificationContainer.classList.contains(CLASSES.FLOAT_UP)) { return; } - const pages = ntpApiHandle.mostVisited; - const cmds = []; - const maxNumTiles = customLinksEnabled() ? MAX_NUM_TILES_CUSTOM_LINKS : - MAX_NUM_TILES_MOST_VISITED; - for (let i = 0; i < Math.min(maxNumTiles, pages.length); ++i) { - cmds.push({cmd: 'tile', rid: pages[i].rid}); - } - cmds.push({cmd: 'show'}); - - const iframe = $(IDS.TILES_IFRAME); - if (iframe) { - iframe.contentWindow.postMessage(cmds, '*'); - } -} - -/** - * Callback for embeddedSearch.newTabPage.onaddcustomlinkdone. Called when the - * custom link was successfully added. Shows the "Shortcut added" notification. - * @param {boolean} success True if the link was successfully added. - */ -function onAddCustomLinkDone(success) { - if (success) { - showNotification(configData.translatedStrings.linkAddedMsg); - } else { - showErrorNotification( - configData.translatedStrings.linkCantCreate, null, null); - } - ntpApiHandle.logEvent(LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_DONE); -} - -/** - * Callback for embeddedSearch.newTabPage.onupdatecustomlinkdone. Called when - * the custom link was successfully updated. Shows the "Shortcut edited" - * notification. - * @param {boolean} success True if the link was successfully updated. - */ -function onUpdateCustomLinkDone(success) { - if (success) { - showNotification(configData.translatedStrings.linkEditedMsg); - } else { - showErrorNotification( - configData.translatedStrings.linkCantEdit, null, null); + // Clear the timeout to hide the notification. + if (delayedHideNotification) { + delayedHideNotification.clear(); + delayedHideNotification = null; + currNotification = null; } -} -/** - * Callback for embeddedSearch.newTabPage.ondeletecustomlinkdone. Called when - * the custom link was successfully deleted. Shows the "Shortcut deleted" - * notification. - * @param {boolean} success True if the link was successfully deleted. - */ -function onDeleteCustomLinkDone(success) { - if (success) { - showNotification(configData.translatedStrings.linkRemovedMsg); - } else { - showErrorNotification( - configData.translatedStrings.linkCantRemove, null, null); + if (showPromo) { + // Show middle-slot promo if one is present. + const promo = $(IDS.PROMO); + if (promo) { + promo.classList.remove(CLASSES.HIDE_NOTIFICATION); + // Timeout is required for the "float" transition to work. Modifying the + // "display" property prevents transitions from activating for a brief + // period of time. + window.setTimeout(() => { + promo.classList.remove(CLASSES.FLOAT_DOWN); + }, DISPLAY_TIMEOUT); + } } -} -/** - * Shows the Most Visited pop-up notification and triggers a delay to hide it. - * The message will be set to |msg|. - * @param {string} msg The notification message. - */ -function showNotification(msg) { - $(IDS.NOTIFICATION_MESSAGE).textContent = msg; - $(IDS.RESTORE_ALL_LINK).textContent = customLinksEnabled() ? - configData.translatedStrings.restoreDefaultLinks : - configData.translatedStrings.restoreThumbnailsShort; - floatUpNotification($(IDS.NOTIFICATION), $(IDS.NOTIFICATION_CONTAINER)); - $(IDS.UNDO_LINK).focus(); -} - -/** - * Hides the Most Visited pop-up notification. - */ -function hideNotification() { - floatDownNotification( - $(IDS.NOTIFICATION), $(IDS.NOTIFICATION_CONTAINER), /*showPromo=*/ true); -} - -/** - * Shows the error pop-up notification and triggers a delay to hide it. The - * message will be set to |msg|. If |linkName| and |linkOnClick| are present, - * shows an error link with text set to |linkName| and onclick handled by - * |linkOnClick|. - * @param {string} msg The notification message. - * @param {?string} linkName The error link text. - * @param {?Function} linkOnClick The error link onclick handler. - */ -function showErrorNotification(msg, linkName, linkOnClick) { - const notification = $(IDS.ERROR_NOTIFICATION); - $(IDS.ERROR_NOTIFICATION_MSG).textContent = msg; - if (linkName && linkOnClick) { - const notificationLink = $(IDS.ERROR_NOTIFICATION_LINK); - notificationLink.textContent = linkName; - notificationLink.onclick = linkOnClick; - notification.classList.add(CLASSES.HAS_LINK); - } else { - notification.classList.remove(CLASSES.HAS_LINK); - } - floatUpNotification(notification, $(IDS.ERROR_NOTIFICATION_CONTAINER)); + // Reset notification visibility once the animation is complete. + notificationContainer.addEventListener('transitionend', (event) => { + // Blur the hidden items. + $(IDS.UNDO_LINK).blur(); + $(IDS.RESTORE_ALL_LINK).blur(); + if (notification.classList.contains(CLASSES.HAS_LINK)) { + notification.classList.remove(CLASSES.HAS_LINK); + $(IDS.ERROR_NOTIFICATION_LINK).blur(); + } + // Hide the notification + if (!notification.classList.contains(CLASSES.FLOAT_UP)) { + notification.classList.add(CLASSES.HIDE_NOTIFICATION); + } + }, {once: true}); + notificationContainer.classList.remove(CLASSES.FLOAT_UP); } /** @@ -741,168 +499,58 @@ function floatUpNotification(notification, notificationContainer) { } /** - * Animates the pop-up notification to float down, and clears the timeout to - * hide the notification. - * @param {?Element} notification The notification element. - * @param {?Element} notificationContainer The notification container element. - * @param {boolean} showPromo Do show the promo if present. - */ -function floatDownNotification(notification, notificationContainer, showPromo) { - if (!notification || !notificationContainer) { - return; - } - - if (!notificationContainer.classList.contains(CLASSES.FLOAT_UP)) { - return; - } - - // Clear the timeout to hide the notification. - if (delayedHideNotification) { - delayedHideNotification.clear(); - delayedHideNotification = null; - currNotification = null; - } - - if (showPromo) { - // Show middle-slot promo if one is present. - const promo = $(IDS.PROMO); - if (promo) { - promo.classList.remove(CLASSES.HIDE_NOTIFICATION); - // Timeout is required for the "float" transition to work. Modifying the - // "display" property prevents transitions from activating for a brief - // period of time. - window.setTimeout(() => { - promo.classList.remove(CLASSES.FLOAT_DOWN); - }, DISPLAY_TIMEOUT); - } - } - - // Reset notification visibility once the animation is complete. - notificationContainer.addEventListener('transitionend', (event) => { - // Blur the hidden items. - $(IDS.UNDO_LINK).blur(); - $(IDS.RESTORE_ALL_LINK).blur(); - if (notification.classList.contains(CLASSES.HAS_LINK)) { - notification.classList.remove(CLASSES.HAS_LINK); - $(IDS.ERROR_NOTIFICATION_LINK).blur(); - } - // Hide the notification - if (!notification.classList.contains(CLASSES.FLOAT_UP)) { - notification.classList.add(CLASSES.HIDE_NOTIFICATION); - } - }, {once: true}); - notificationContainer.classList.remove(CLASSES.FLOAT_UP); -} - -/** - * Return true if custom links are enabled. - * @return {boolean} - */ -function customLinksEnabled() { - return configData.isGooglePage && - !chrome.embeddedSearch.newTabPage.isUsingMostVisited; -} - -/** - * Handles a click on the notification undo link by hiding the notification and - * informing Chrome. - */ -function onUndo() { - hideNotification(); - // Focus on the omnibox after the notification is hidden. - window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes(); - if (customLinksEnabled()) { - ntpApiHandle.undoCustomLinkAction(); - } else if (lastBlacklistedTile != null) { - ntpApiHandle.undoMostVisitedDeletion(lastBlacklistedTile); - } -} - -/** - * Handles a click on the restore all notification link by hiding the - * notification and informing Chrome. + * Returns theme background info, first checking for history.state.notheme. If + * the page has notheme set, returns a fallback light-colored theme (or dark- + * colored theme if dark mode is enabled). This is used when the doodle is + * displayed after clicking the notifier. + * @return {?ThemeBackgroundInfo} */ -function onRestoreAll() { - hideNotification(); - // Focus on the omnibox after the notification is hidden. - window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes(); - if (customLinksEnabled()) { - ntpApiHandle.resetCustomLinks(); - } else { - ntpApiHandle.undoAllMostVisitedDeletions(); +function getThemeBackgroundInfo() { + if (history.state && history.state.notheme) { + return { + alternateLogo: false, + backgroundColorRgba: + (isDarkModeEnabled ? NTP_DESIGN.darkBackgroundColor : + NTP_DESIGN.backgroundColor), + customBackgroundConfigured: false, + iconBackgroundColor: + (isDarkModeEnabled ? NTP_DESIGN.iconDarkBackgroundColor : + NTP_DESIGN.iconBackgroundColor), + isNtpBackgroundDark: isDarkModeEnabled, + textColorLightRgba: [102, 102, 102, 255], + textColorRgba: + (isDarkModeEnabled ? NTP_DESIGN.titleColorAgainstDark : + NTP_DESIGN.titleColor), + useTitleContainer: false, + useWhiteAddIcon: isDarkModeEnabled, + usingDefaultTheme: true, + }; } -} -/** - * Callback for embeddedSearch.newTabPage.oninputstart. Handles new input by - * disposing the NTP, according to where the input was entered. - */ -function onInputStart() { - if (isFakeboxFocused()) { - setFakeboxFocus(false); - setFakeboxDragFocus(false); - setFakeboxVisibility(false); + const info = window.chrome.embeddedSearch.newTabPage.themeBackgroundInfo; + const preview = $(customize.IDS.CUSTOM_BG_PREVIEW); + if (preview.dataset.hasPreview === 'true') { + info.isNtpBackgroundDark = preview.dataset.hasImage === 'true'; + info.customBackgroundConfigured = preview.dataset.hasImage === 'true'; + info.alternateLogo = preview.dataset.hasImage === 'true'; + // backgroundImage is in the form: url("actual url"). Remove everything + // except the actual url. + info.imageUrl = preview.style.backgroundImage.slice(5, -2); } + return info; } /** - * Callback for embeddedSearch.newTabPage.oninputcancel. Restores the NTP - * (re-enables the fakebox and unhides the logo.) - */ -function onInputCancel() { - setFakeboxVisibility(true); -} - -/** - * @param {boolean} focus True to focus the fakebox. - */ -function setFakeboxFocus(focus) { - document.body.classList.toggle(CLASSES.FAKEBOX_FOCUS, focus); -} - -/** - * @param {boolean} focus True to show a dragging focus on the fakebox. - */ -function setFakeboxDragFocus(focus) { - document.body.classList.toggle(CLASSES.FAKEBOX_DRAG_FOCUS, focus); -} - -/** - * @return {boolean} True if the fakebox has focus. - */ -function isFakeboxFocused() { - return document.body.classList.contains(CLASSES.FAKEBOX_FOCUS) || - document.body.classList.contains(CLASSES.FAKEBOX_DRAG_FOCUS); -} - -/** - * @param {!Event} event The click event. - * @return {boolean} True if the click occurred in an enabled fakebox. - */ -function isFakeboxClick(event) { - return $(IDS.FAKEBOX).contains(/** @type HTMLElement */ (event.target)) && - !$(IDS.FAKEBOX_MICROPHONE) - .contains(/** @type HTMLElement */ (event.target)); -} - -/** - * @param {boolean} show True to show the fakebox and logo. - */ -function setFakeboxVisibility(show) { - document.body.classList.toggle(CLASSES.HIDE_FAKEBOX, !show); -} - -/** - * @param {!Element} element The element to register the handler for. - * @param {number} keycode The keycode of the key to register. - * @param {!Function} handler The key handler to register. + * Determine whether dark chips should be used if dark mode is enabled. This is + * is the case when dark mode is enabled and a background image (from a custom + * background or user theme) is not set. + * + * @param {!Object} info Theme background information. + * @return {boolean} Whether the chips should be dark. */ -function registerKeyHandler(element, keycode, handler) { - element.addEventListener('keydown', function(event) { - if (event.keyCode == keycode) { - handler(event); - } - }); +function getUseDarkChips(info) { + return window.matchMedia('(prefers-color-scheme: dark)').matches && + !info.imageUrl; } /** @@ -923,7 +571,7 @@ function handlePostMessage(event) { if ($(IDS.PROMO)) { $(IDS.PROMO).classList.add(CLASSES.SHOW_ELEMENT); } - if (customLinksEnabled() && !configData.hideShortcuts) { + if (customLinksEnabled()) { $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT) .classList.toggle( customize.CLASSES.OPTION_DISABLED, !args.showRestoreDefault); @@ -963,43 +611,10 @@ function handlePostMessage(event) { } } -/** - * Request data for search suggestions, promo, and the OGB. Insert it into - * the page once it's available. For search suggestions this should be almost - * immediately as cached data is always used. Promos and the OGB may need - * to wait for the asynchronous network request to complete. - */ -function requestAndInsertGoogleResources() { - if (!$('search-suggestions-loader')) { - const ssScript = document.createElement('script'); - ssScript.id = 'search-suggestions-loader'; - ssScript.src = 'chrome-search://local-ntp/search-suggestions.js'; - ssScript.async = false; - document.body.appendChild(ssScript); - ssScript.onload = function() { - injectSearchSuggestions(searchSuggestions); - }; - } - if (!$('one-google-loader')) { - // Load the OneGoogleBar script. It'll create a global variable |og| which - // is a JSON object corresponding to the native OneGoogleBarData type. - const ogScript = document.createElement('script'); - ogScript.id = 'one-google-loader'; - ogScript.src = 'chrome-search://local-ntp/one-google.js'; - document.body.appendChild(ogScript); - ogScript.onload = function() { - injectOneGoogleBar(og); - }; - } - if (!$('promo-loader')) { - const promoScript = document.createElement('script'); - promoScript.id = 'promo-loader'; - promoScript.src = 'chrome-search://local-ntp/promo.js'; - document.body.appendChild(promoScript); - promoScript.onload = function() { - injectPromo(promo); - }; - } +/** Hides the Most Visited pop-up notification. */ +function hideNotification() { + floatDownNotification( + $(IDS.NOTIFICATION), $(IDS.NOTIFICATION_CONTAINER), /*showPromo=*/ true); } /** @@ -1025,14 +640,12 @@ function init() { const undoLink = $(IDS.UNDO_LINK); undoLink.addEventListener('click', onUndo); - registerKeyHandler(undoLink, KEYCODE.ENTER, onUndo); - registerKeyHandler(undoLink, KEYCODE.SPACE, onUndo); + registerKeyHandler(undoLink, ['Enter', ' '], onUndo); undoLink.textContent = configData.translatedStrings.undoThumbnailRemove; const restoreAllLink = $(IDS.RESTORE_ALL_LINK); restoreAllLink.addEventListener('click', onRestoreAll); - registerKeyHandler(restoreAllLink, KEYCODE.ENTER, onRestoreAll); - registerKeyHandler(restoreAllLink, KEYCODE.SPACE, onRestoreAll); + registerKeyHandler(restoreAllLink, ['Enter', ' '], onRestoreAll); $(IDS.ATTRIBUTION_TEXT).textContent = configData.translatedStrings.attributionIntro; @@ -1045,6 +658,8 @@ function init() { renderTheme(); + window.matchMedia('(prefers-color-scheme: dark)').onchange = onThemeChange; + const searchboxApiHandle = embeddedSearchApiHandle.searchBox; if (configData.isGooglePage) { @@ -1145,120 +760,46 @@ function init() { utils.setPlatformClass(document.body); utils.disableOutlineOnMouseClick($(customize.IDS.EDIT_BG)); - document.body.classList.add(CLASSES.INITED); + document.documentElement.classList.add(CLASSES.INITED); } /** - * Create the Most Visited and edit custom links iframes. + * Injects the One Google Bar into the page. Called asynchronously, so that it + * doesn't block the main page load. */ -function createIframes() { - // Collect arguments for the most visited iframe. - const args = []; - - const searchboxApiHandle = window.chrome.embeddedSearch.searchBox; - - if (searchboxApiHandle.rtl) { - args.push('rtl=1'); - } - if (NTP_DESIGN.numTitleLines > 1) { - args.push('ntl=' + NTP_DESIGN.numTitleLines); - } - - args.push( - 'title=' + - encodeURIComponent(configData.translatedStrings.mostVisitedTitle)); - args.push( - 'removeTooltip=' + - encodeURIComponent(configData.translatedStrings.removeThumbnailTooltip)); - - if (configData.isGooglePage) { - args.push('enableCustomLinks=1'); - if (configData.enableShortcutsGrid) { - args.push('enableGrid=1'); - } - args.push( - 'addLink=' + - encodeURIComponent(configData.translatedStrings.addLinkTitle)); - args.push( - 'addLinkTooltip=' + - encodeURIComponent(configData.translatedStrings.addLinkTooltip)); - args.push( - 'editLinkTooltip=' + - encodeURIComponent(configData.translatedStrings.editLinkTooltip)); +function injectOneGoogleBar(ogb) { + if (ogb.barHtml === '') { + return; } - // Create the most visited iframe. - const iframe = document.createElement('iframe'); - iframe.id = IDS.TILES_IFRAME; - iframe.name = IDS.TILES_IFRAME; - iframe.title = configData.translatedStrings.mostVisitedTitle; - iframe.src = 'chrome-search://most-visited/single.html?' + args.join('&'); - $(IDS.TILES).appendChild(iframe); - - iframe.onload = function() { - sendThemeInfoToMostVisitedIframe(); - reloadTiles(); - }; + const inHeadStyle = document.createElement('style'); + inHeadStyle.type = 'text/css'; + inHeadStyle.appendChild(document.createTextNode(ogb.inHeadStyle)); + document.head.appendChild(inHeadStyle); - if (configData.isGooglePage) { - // Collect arguments for the edit custom link iframe. - const clArgs = []; + const inHeadScript = document.createElement('script'); + inHeadScript.type = 'text/javascript'; + inHeadScript.appendChild(document.createTextNode(ogb.inHeadScript)); + document.head.appendChild(inHeadScript); - if (searchboxApiHandle.rtl) { - clArgs.push('rtl=1'); - } + renderOneGoogleBarTheme(); - clArgs.push( - 'addTitle=' + - encodeURIComponent(configData.translatedStrings.addLinkTitle)); - clArgs.push( - 'editTitle=' + - encodeURIComponent(configData.translatedStrings.editLinkTitle)); - clArgs.push( - 'nameField=' + - encodeURIComponent(configData.translatedStrings.nameField)); - clArgs.push( - 'urlField=' + - encodeURIComponent(configData.translatedStrings.urlField)); - clArgs.push( - 'linkRemove=' + - encodeURIComponent(configData.translatedStrings.linkRemove)); - clArgs.push( - 'linkCancel=' + - encodeURIComponent(configData.translatedStrings.linkCancel)); - clArgs.push( - 'linkDone=' + - encodeURIComponent(configData.translatedStrings.linkDone)); - clArgs.push( - 'invalidUrl=' + - encodeURIComponent(configData.translatedStrings.invalidUrl)); + const ogElem = $('one-google'); + ogElem.innerHTML = ogb.barHtml; - // Create the edit custom link iframe. - const clIframe = document.createElement('iframe'); - clIframe.id = IDS.CUSTOM_LINKS_EDIT_IFRAME; - clIframe.name = IDS.CUSTOM_LINKS_EDIT_IFRAME; - clIframe.title = configData.translatedStrings.editLinkTitle; - clIframe.src = 'chrome-search://most-visited/edit.html?' + clArgs.join('&'); - const clIframeDialog = document.createElement('dialog'); - clIframeDialog.id = IDS.CUSTOM_LINKS_EDIT_IFRAME_DIALOG; - clIframeDialog.classList.add(CLASSES.CUSTOMIZE_DIALOG); - clIframeDialog.appendChild(clIframe); - document.body.appendChild(clIframeDialog); + const afterBarScript = document.createElement('script'); + afterBarScript.type = 'text/javascript'; + afterBarScript.appendChild(document.createTextNode(ogb.afterBarScript)); + ogElem.parentNode.insertBefore(afterBarScript, ogElem.nextSibling); - if (configData.hideShortcuts) { - $(IDS.TILES).style.display = 'none'; - clIframeDialog.style.display = 'none'; - } - } + $('one-google-end-of-body').innerHTML = ogb.endOfBodyHtml; - window.addEventListener('message', handlePostMessage); -} + const endOfBodyScript = document.createElement('script'); + endOfBodyScript.type = 'text/javascript'; + endOfBodyScript.appendChild(document.createTextNode(ogb.endOfBodyScript)); + document.body.appendChild(endOfBodyScript); -/** - * Binds event listeners. - */ -function listen() { - document.addEventListener('DOMContentLoaded', init); + ntpApiHandle.logEvent(LOG_TYPE.NTP_ONE_GOOGLE_BAR_SHOWN); } /** @@ -1317,42 +858,488 @@ function injectSearchSuggestions(suggestions) { } /** - * Injects the One Google Bar into the page. Called asynchronously, so that it - * doesn't block the main page load. + * @param {!Event} event The click event. + * @return {boolean} True if the click occurred in an enabled fakebox. */ -function injectOneGoogleBar(ogb) { - if (ogb.barHtml === '') { - return; +function isFakeboxClick(event) { + return $(IDS.FAKEBOX).contains(/** @type HTMLElement */ (event.target)) && + !$(IDS.FAKEBOX_MICROPHONE) + .contains(/** @type HTMLElement */ (event.target)); +} + +/** @return {boolean} True if the fakebox has focus. */ +function isFakeboxFocused() { + return document.body.classList.contains(CLASSES.FAKEBOX_FOCUS) || + document.body.classList.contains(CLASSES.FAKEBOX_DRAG_FOCUS); +} + +/** Binds event listeners. */ +function listen() { + document.addEventListener('DOMContentLoaded', init); +} + +/** + * Callback for embeddedSearch.newTabPage.onaddcustomlinkdone. Called when the + * custom link was successfully added. Shows the "Shortcut added" notification. + * @param {boolean} success True if the link was successfully added. + */ +function onAddCustomLinkDone(success) { + if (success) { + showNotification(configData.translatedStrings.linkAddedMsg); + } else { + showErrorNotification( + configData.translatedStrings.linkCantCreate, null, null); } + ntpApiHandle.logEvent(LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_DONE); +} - const inHeadStyle = document.createElement('style'); - inHeadStyle.type = 'text/css'; - inHeadStyle.appendChild(document.createTextNode(ogb.inHeadStyle)); - document.head.appendChild(inHeadStyle); +/** + * Callback for embeddedSearch.newTabPage.ondeletecustomlinkdone. Called when + * the custom link was successfully deleted. Shows the "Shortcut deleted" + * notification. + * @param {boolean} success True if the link was successfully deleted. + */ +function onDeleteCustomLinkDone(success) { + if (success) { + showNotification(configData.translatedStrings.linkRemovedMsg); + } else { + showErrorNotification( + configData.translatedStrings.linkCantRemove, null, null); + } +} - const inHeadScript = document.createElement('script'); - inHeadScript.type = 'text/javascript'; - inHeadScript.appendChild(document.createTextNode(ogb.inHeadScript)); - document.head.appendChild(inHeadScript); +/** + * Callback for embeddedSearch.newTabPage.oninputcancel. Restores the NTP + * (re-enables the fakebox and unhides the logo.) + */ +function onInputCancel() { + setFakeboxVisibility(true); +} +/** + * Callback for embeddedSearch.newTabPage.oninputstart. Handles new input by + * disposing the NTP, according to where the input was entered. + */ +function onInputStart() { + if (isFakeboxFocused()) { + setFakeboxFocus(false); + setFakeboxDragFocus(false); + setFakeboxVisibility(false); + } +} + +/** + * Callback for embeddedSearch.newTabPage.onmostvisitedchange. Called when the + * NTP tiles are updated. + */ +function onMostVisitedChange() { + reloadTiles(); +} + +/** + * Handles a click on the restore all notification link by hiding the + * notification and informing Chrome. + */ +function onRestoreAll() { + hideNotification(); + // Focus on the omnibox after the notification is hidden. + window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes(); + if (customLinksEnabled()) { + ntpApiHandle.resetCustomLinks(); + } else { + ntpApiHandle.undoAllMostVisitedDeletions(); + } +} + +/** + * Callback for embeddedSearch.newTabPage.onthemechange. + */ +function onThemeChange() { + renderTheme(); renderOneGoogleBarTheme(); + sendThemeInfoToMostVisitedIframe(); +} - const ogElem = $('one-google'); - ogElem.innerHTML = ogb.barHtml; +/** + * Handles a click on the notification undo link by hiding the notification and + * informing Chrome. + */ +function onUndo() { + hideNotification(); + // Focus on the omnibox after the notification is hidden. + window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes(); + if (customLinksEnabled()) { + ntpApiHandle.undoCustomLinkAction(); + } else if (lastBlacklistedTile != null) { + ntpApiHandle.undoMostVisitedDeletion(lastBlacklistedTile); + } +} - const afterBarScript = document.createElement('script'); - afterBarScript.type = 'text/javascript'; - afterBarScript.appendChild(document.createTextNode(ogb.afterBarScript)); - ogElem.parentNode.insertBefore(afterBarScript, ogElem.nextSibling); +/** + * Callback for embeddedSearch.newTabPage.onupdatecustomlinkdone. Called when + * the custom link was successfully updated. Shows the "Shortcut edited" + * notification. + * @param {boolean} success True if the link was successfully updated. + */ +function onUpdateCustomLinkDone(success) { + if (success) { + showNotification(configData.translatedStrings.linkEditedMsg); + } else { + showErrorNotification( + configData.translatedStrings.linkCantEdit, null, null); + } +} - $('one-google-end-of-body').innerHTML = ogb.endOfBodyHtml; +/** + * Called by tests to override the executable timeout with a test timeout. + * @param {!Function} timeout The timeout function. Requires a boolean param. + */ +function overrideExecutableTimeoutForTesting(timeout) { + createExecutableTimeout = timeout; +} - const endOfBodyScript = document.createElement('script'); - endOfBodyScript.type = 'text/javascript'; - endOfBodyScript.appendChild(document.createTextNode(ogb.endOfBodyScript)); - document.body.appendChild(endOfBodyScript); +/** + * @param {!Element} element + * @param {!Array<string>} keys + * @param {!function(Event)} handler + */ +function registerKeyHandler(element, keys, handler) { + element.addEventListener('keydown', e => { + if (keys.includes(e.key)) { + handler(e); + } + }); +} - ntpApiHandle.logEvent(LOG_TYPE.NTP_ONE_GOOGLE_BAR_SHOWN); +/** + * Fetches new data (RIDs) from the embeddedSearch.newTabPage API and passes + * them to the iframe. + */ +function reloadTiles() { + // Don't attempt to load tiles if the MV data isn't available yet - this can + // happen occasionally, see https://crbug.com/794942. In that case, we should + // get an onMostVisitedChange call once they are available. + // Note that MV data being available is different from having > 0 tiles. There + // can legitimately be 0 tiles, e.g. if the user blacklisted them all. + if (!ntpApiHandle.mostVisitedAvailable) { + return; + } + + const pages = ntpApiHandle.mostVisited; + const cmds = []; + const maxNumTiles = customLinksEnabled() ? MAX_NUM_TILES_CUSTOM_LINKS : + MAX_NUM_TILES_MOST_VISITED; + for (let i = 0; i < Math.min(maxNumTiles, pages.length); ++i) { + cmds.push({cmd: 'tile', rid: pages[i].rid}); + } + cmds.push({cmd: 'show'}); + + $(IDS.MOST_VISITED).hidden = + !chrome.embeddedSearch.newTabPage.areShortcutsVisible; + + const iframe = $(IDS.TILES_IFRAME); + if (iframe) { + iframe.contentWindow.postMessage(cmds, '*'); + } +} + +/** + * Updates the OneGoogleBar (if it is loaded) based on the current theme. + * TODO(crbug.com/918582): Add support for OGB dark mode. + */ +function renderOneGoogleBarTheme() { + if (!window.gbar) { + return; + } + try { + const oneGoogleBarApi = window.gbar.a; + const oneGoogleBarPromise = oneGoogleBarApi.bf(); + oneGoogleBarPromise.then(function(oneGoogleBar) { + const setForegroundStyle = oneGoogleBar.pc.bind(oneGoogleBar); + const themeInfo = getThemeBackgroundInfo(); + setForegroundStyle(themeInfo && themeInfo.isNtpBackgroundDark ? 1 : 0); + }); + } catch (err) { + console.log('Failed setting OneGoogleBar theme:\n' + err); + } +} + +/** Updates the NTP based on the current theme. */ +function renderTheme() { + const info = getThemeBackgroundInfo(); + if (!info) { + return; + } + + $(IDS.NTP_CONTENTS).classList.toggle(CLASSES.DARK, info.isNtpBackgroundDark); + + // Update dark mode styling. + isDarkModeEnabled = window.matchMedia('(prefers-color-scheme: dark)').matches; + document.body.classList.toggle('light-chip', !getUseDarkChips(info)); + + const background = [ + convertToRGBAColor(info.backgroundColorRgba), info.imageUrl, + info.imageTiling, info.imageHorizontalAlignment, info.imageVerticalAlignment + ].join(' ').trim(); + + // If a custom background has been selected the image will be applied to the + // custom-background element instead of the body. + if (!info.customBackgroundConfigured) { + document.body.style.background = background; + } + + // Dark mode uses a white Google logo. + const useWhiteLogo = + info.alternateLogo || (info.usingDefaultTheme && isDarkModeEnabled); + document.body.classList.toggle(CLASSES.ALTERNATE_LOGO, useWhiteLogo); + const isNonWhiteBackground = !WHITE_BACKGROUND_COLORS.includes(background); + document.body.classList.toggle(CLASSES.NON_WHITE_BG, isNonWhiteBackground); + + if (info.logoColor) { + document.body.style.setProperty( + '--logo-color', convertToRGBAColor(info.logoColor)); + } + + // The doodle notifier should be shown for non-default backgrounds. This + // includes non-white backgrounds, excluding dark mode gray if dark mode is + // enabled. + const isDefaultBackground = WHITE_BACKGROUND_COLORS.includes(background) || + (isDarkModeEnabled && background === DARK_MODE_BACKGROUND_COLOR); + document.body.classList.toggle(CLASSES.USE_NOTIFIER, !isDefaultBackground); + + updateThemeAttribution(info.attributionUrl, info.imageHorizontalAlignment); + setCustomThemeStyle(info); + + if (info.customBackgroundConfigured) { + // Do anything only if the custom background changed. + const imageUrl = assert(info.imageUrl); + if (!$(IDS.CUSTOM_BG).style.backgroundImage.includes(imageUrl)) { + const imageWithOverlay = [ + customize.CUSTOM_BACKGROUND_OVERLAY, 'url(' + imageUrl + ')' + ].join(',').trim(); + // If the theme update is because of uploading a local image then we + // should close the customization menu. Closing the menu before the image + // is selected doesn't look good. + const localImageFileName = 'background.jpg'; + if (!configData.richerPicker && + imageWithOverlay.includes(localImageFileName)) { + customize.closeCustomizationDialog(); + } + // |image| and |imageWithOverlay| use the same url as their source. + // Waiting to display the custom background until |image| is fully + // loaded ensures that |imageWithOverlay| is also loaded. + $(IDS.CUSTOM_BG).style.backgroundImage = imageWithOverlay; + const image = new Image(); + image.onload = function() { + $(IDS.CUSTOM_BG).style.opacity = '1'; + }; + image.src = imageUrl; + + customize.clearAttribution(); + customize.setAttribution( + '' + info.attribution1, '' + info.attribution2, + '' + info.attributionActionUrl); + } + } else { + $(IDS.CUSTOM_BG).style.opacity = '0'; + $(IDS.CUSTOM_BG).style.backgroundImage = ''; + customize.clearAttribution(); + } + + $(customize.IDS.RESTORE_DEFAULT) + .classList.toggle( + customize.CLASSES.OPTION_DISABLED, !info.customBackgroundConfigured); + $(customize.IDS.RESTORE_DEFAULT).tabIndex = + (info.customBackgroundConfigured ? 0 : -1); + + $(customize.IDS.EDIT_BG) + .classList.toggle( + CLASSES.ENTRY_POINT_ENHANCED, !info.customBackgroundConfigured); + + if (configData.isGooglePage) { + customize.onThemeChange(); + } +} + +/** + * Request data for search suggestions, promo, and the OGB. Insert it into + * the page once it's available. For search suggestions this should be almost + * immediately as cached data is always used. Promos and the OGB may need + * to wait for the asynchronous network request to complete. + */ +function requestAndInsertGoogleResources() { + if (!$('search-suggestions-loader')) { + const ssScript = document.createElement('script'); + ssScript.id = 'search-suggestions-loader'; + ssScript.src = 'chrome-search://local-ntp/search-suggestions.js'; + ssScript.async = false; + document.body.appendChild(ssScript); + ssScript.onload = function() { + injectSearchSuggestions(searchSuggestions); + }; + } + if (!$('one-google-loader')) { + // Load the OneGoogleBar script. It'll create a global variable |og| which + // is a JSON object corresponding to the native OneGoogleBarData type. + const ogScript = document.createElement('script'); + ogScript.id = 'one-google-loader'; + ogScript.src = 'chrome-search://local-ntp/one-google.js'; + document.body.appendChild(ogScript); + ogScript.onload = function() { + injectOneGoogleBar(og); + }; + } + if (!$('promo-loader')) { + const promoScript = document.createElement('script'); + promoScript.id = 'promo-loader'; + promoScript.src = 'chrome-search://local-ntp/promo.js'; + document.body.appendChild(promoScript); + promoScript.onload = function() { + injectPromo(promo); + }; + } +} + +/** Sends the current theme info to the most visited iframe. */ +function sendThemeInfoToMostVisitedIframe() { + const info = getThemeBackgroundInfo(); + if (!info) { + return; + } + + const message = {cmd: 'updateTheme'}; + message.isThemeDark = info.isNtpBackgroundDark; + message.customBackground = info.customBackgroundConfigured; + message.useTitleContainer = info.useTitleContainer; + message.iconBackgroundColor = convertToRGBAColor(info.iconBackgroundColor); + message.useWhiteAddIcon = info.useWhiteAddIcon; + + let titleColor = NTP_DESIGN.titleColor; + if (!info.usingDefaultTheme && info.textColorRgba) { + titleColor = info.textColorRgba; + } else if (info.isNtpBackgroundDark) { + titleColor = NTP_DESIGN.titleColorAgainstDark; + } + message.tileTitleColor = convertToRGBAColor(titleColor); + + const iframe = $(IDS.TILES_IFRAME); + if (iframe) { + iframe.contentWindow.postMessage(message, '*'); + } +} + +/** + * Sets the visibility of the theme attribution. + * @param {boolean} show True to show the attribution. + */ +function setAttributionVisibility(show) { + $(IDS.ATTRIBUTION).style.display = show ? '' : 'none'; +} + +/** + * Updates the NTP style according to theme. + * @param {Object} themeInfo The information about the theme. + */ +function setCustomThemeStyle(themeInfo) { + let textColor = ''; + let textColorLight = ''; + let mvxFilter = ''; + if (!themeInfo.usingDefaultTheme) { + textColor = convertToRGBAColor(themeInfo.textColorRgba); + textColorLight = convertToRGBAColor(themeInfo.textColorLightRgba); + mvxFilter = 'drop-shadow(0 0 0 ' + textColor + ')'; + } + + $(IDS.NTP_CONTENTS) + .classList.toggle(CLASSES.DEFAULT_THEME, themeInfo.usingDefaultTheme); + + document.body.style.setProperty('--text-color', textColor); + document.body.style.setProperty('--text-color-light', textColorLight); +} + +/** + * @param {boolean} focus True to show a dragging focus on the fakebox. + */ +function setFakeboxDragFocus(focus) { + document.body.classList.toggle(CLASSES.FAKEBOX_DRAG_FOCUS, focus); +} + +/** + * @param {boolean} focus True to focus the fakebox. + */ +function setFakeboxFocus(focus) { + document.body.classList.toggle(CLASSES.FAKEBOX_FOCUS, focus); +} + +/** + * @param {boolean} show True to show the fakebox and logo. + */ +function setFakeboxVisibility(show) { + document.body.classList.toggle(CLASSES.HIDE_FAKEBOX, !show); +} + +/** + * Shows the error pop-up notification and triggers a delay to hide it. The + * message will be set to |msg|. If |linkName| and |linkOnClick| are present, + * shows an error link with text set to |linkName| and onclick handled by + * |linkOnClick|. + * @param {string} msg The notification message. + * @param {?string} linkName The error link text. + * @param {?Function} linkOnClick The error link onclick handler. + */ +function showErrorNotification(msg, linkName, linkOnClick) { + const notification = $(IDS.ERROR_NOTIFICATION); + $(IDS.ERROR_NOTIFICATION_MSG).textContent = msg; + if (linkName && linkOnClick) { + const notificationLink = $(IDS.ERROR_NOTIFICATION_LINK); + notificationLink.textContent = linkName; + notificationLink.onclick = linkOnClick; + notification.classList.add(CLASSES.HAS_LINK); + } else { + notification.classList.remove(CLASSES.HAS_LINK); + } + floatUpNotification(notification, $(IDS.ERROR_NOTIFICATION_CONTAINER)); +} + +/** + * Shows the Most Visited pop-up notification and triggers a delay to hide it. + * The message will be set to |msg|. + * @param {string} msg The notification message. + */ +function showNotification(msg) { + $(IDS.NOTIFICATION_MESSAGE).textContent = msg; + $(IDS.RESTORE_ALL_LINK).textContent = customLinksEnabled() ? + configData.translatedStrings.restoreDefaultLinks : + configData.translatedStrings.restoreThumbnailsShort; + floatUpNotification($(IDS.NOTIFICATION), $(IDS.NOTIFICATION_CONTAINER)); + $(IDS.UNDO_LINK).focus(); +} + +/** + * Renders the attribution if the URL is present, otherwise hides it. + * @param {string|undefined} url The URL of the attribution image, if any. + * @param {string|undefined} themeBackgroundAlignment The alignment of the theme + * background image. This is used to compute the attribution's alignment. + */ +function updateThemeAttribution(url, themeBackgroundAlignment) { + if (!url) { + setAttributionVisibility(false); + return; + } + + const attribution = $(IDS.ATTRIBUTION); + let attributionImage = attribution.querySelector('img'); + if (!attributionImage) { + attributionImage = new Image(); + attribution.appendChild(attributionImage); + } + attributionImage.style.content = url; + + // To avoid conflicts, place the attribution on the left for themes that + // right align their background images. + attribution.classList.toggle( + CLASSES.LEFT_ALIGN_ATTRIBUTION, themeBackgroundAlignment == 'right'); + setAttributionVisibility(true); } return { 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 51a006495b6..995e9a8b6b6 100644 --- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.css +++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.css @@ -45,10 +45,6 @@ a:visited { text-decoration: none; } -body.hide { - display: none; -} - #most-visited { margin-top: 10px; text-align: -webkit-center; diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_single.html b/chromium/chrome/browser/resources/local_ntp/most_visited_single.html index 7047423ce7e..9d8db297c9a 100644 --- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.html +++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.html @@ -8,6 +8,7 @@ <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="local-ntp-common.css"> <link rel="stylesheet" type="text/css" href="single.css"> + <script src="assert.js"></script> <script src="utils.js"></script> <script src="single.js"></script> </head> 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 f26d493e0c4..c497599fdb4 100644 --- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.js +++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.js @@ -51,7 +51,6 @@ const CLASSES = { GRID_REORDER: 'grid-reorder', GRID_TILE: 'grid-tile', GRID_TILE_CONTAINER: 'grid-tile-container', - HIDE: 'hide', // Applied when the tiles are hidden by the user. REORDER: 'reorder', // Applied to the tile being moved while reordering. // Applied while we are reordering. Disables hover styling. REORDERING: 'reordering', @@ -830,7 +829,7 @@ function handleCommand(data) { // TODO(crbug.com/946225): If this happens before we have finished loading // the previous tiles, we probably get into a bad state. If/when the iframe // is removed this might no longer be a concern. - showTiles(data); + showTiles(); } else if (cmd == 'updateTheme') { updateTheme(data); } else if (cmd === 'focusMenu') { @@ -842,12 +841,8 @@ function handleCommand(data) { /** * Handler for the 'show' message from the host page. - * @param {!Object} info Data received in the message. */ -function showTiles(info) { - document.body.classList.toggle( - CLASSES.HIDE, !chrome.embeddedSearch.newTabPage.areShortcutsVisible); - +function showTiles() { utils.setPlatformClass(document.body); countLoad(); } diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_title.html b/chromium/chrome/browser/resources/local_ntp/most_visited_title.html index 5420eea02f9..11286d9cd6d 100644 --- a/chromium/chrome/browser/resources/local_ntp/most_visited_title.html +++ b/chromium/chrome/browser/resources/local_ntp/most_visited_title.html @@ -4,6 +4,7 @@ <meta charset="utf-8"> <link rel="stylesheet" href="common.css"> <link rel="stylesheet" href="title.css"> + <script src="assert.js"></script> <script src="util.js"></script> <script src="title.js"></script> </head> diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_util.js b/chromium/chrome/browser/resources/local_ntp/most_visited_util.js index 0ee762a9f45..fc6a744276b 100644 --- a/chromium/chrome/browser/resources/local_ntp/most_visited_util.js +++ b/chromium/chrome/browser/resources/local_ntp/most_visited_util.js @@ -60,6 +60,12 @@ function convertArrayToRGBAColor(rgbaColor) { * Parses query parameters from Location. * @param {!Location} location The URL to generate the CSS url for. * @return {Object} Dictionary containing name value pairs for URL. + * + * TODO(dbeam): we should update callers of this method to use + * URLSearchParams#get() instead (which I have a higher confidence handles + * escaping and edge cases correctly). Note: that calling URLSearchParams#get() + * also has the behavior of only returning the first ¶m= in the URL (i.e. + * ?param=1¶m=2 + .get('param') would return '1'). */ function parseQueryParams(location) { const params = Object.create(null); @@ -169,7 +175,7 @@ function getTextColor(params, isTitle) { // For backward compatibility with server-side NTP, look at themes directly // and use param.c for non-title or as fallback. const apiHandle = chrome.embeddedSearch.newTabPage; - const themeInfo = apiHandle.themeBackgroundInfo; + const themeInfo = assert(apiHandle.themeBackgroundInfo); let c = '#777'; if (isTitle && themeInfo && !themeInfo.usingDefaultTheme) { // Read from theme directly diff --git a/chromium/chrome/browser/resources/local_state/BUILD.gn b/chromium/chrome/browser/resources/local_state/BUILD.gn index 3a34954d26d..d621c9424d7 100644 --- a/chromium/chrome/browser/resources/local_state/BUILD.gn +++ b/chromium/chrome/browser/resources/local_state/BUILD.gn @@ -12,7 +12,7 @@ js_type_check("closure_compile") { js_library("local_state") { deps = [ - "//ui/webui/resources/js:cr", - "//ui/webui/resources/js:util", + "//ui/webui/resources/js:cr.m", + "//ui/webui/resources/js:util.m", ] } diff --git a/chromium/chrome/browser/resources/local_state/local_state.html b/chromium/chrome/browser/resources/local_state/local_state.html index 71dc1d4957d..72795b90cb4 100644 --- a/chromium/chrome/browser/resources/local_state/local_state.html +++ b/chromium/chrome/browser/resources/local_state/local_state.html @@ -4,10 +4,7 @@ <meta charset="utf-8"> <title>Local State Debug Page</title> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> - <script src="chrome://resources/js/promise_resolver.js"></script> - <script src="chrome://resources/js/cr.js"></script> - <script src="chrome://resources/js/util.js"></script> - <script src="local_state.js"></script> + <script type="module" src="local_state.js"></script> </head> <body> <pre id="content"> diff --git a/chromium/chrome/browser/resources/local_state/local_state.js b/chromium/chrome/browser/resources/local_state/local_state.js index 5dc929be49b..d5191e236ae 100644 --- a/chromium/chrome/browser/resources/local_state/local_state.js +++ b/chromium/chrome/browser/resources/local_state/local_state.js @@ -6,10 +6,12 @@ * Javascript for local_state.html, served from chrome://local-state/ * This is used to debug the contents of the Local State file. */ +import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; +import {$} from 'chrome://resources/js/util.m.js'; // When the page loads, request the JSON local state data from C++. document.addEventListener('DOMContentLoaded', function() { - cr.sendWithPromise('requestJson').then(localState => { + sendWithPromise('requestJson').then(localState => { $('content').textContent = localState; }); }); diff --git a/chromium/chrome/browser/resources/management/management_browser_proxy.js b/chromium/chrome/browser/resources/management/management_browser_proxy.js index 0633bdcb930..a86bbaa7b15 100644 --- a/chromium/chrome/browser/resources/management/management_browser_proxy.js +++ b/chromium/chrome/browser/resources/management/management_browser_proxy.js @@ -36,10 +36,27 @@ cr.define('management', function() { * managed: boolean, * overview: string, * customerLogo: string, + * threatProtectionDescription: string * }} */ let ManagedDataResponse; + /** + * @typedef {{ + * title: string, + * permission: string + * }} + */ + let ThreatProtectionPermission; + + /** + * @typedef {{ + * info: !Array<!ThreatProtectionPermission>, + * description: string + * }} + */ + let ThreatProtectionInfo; + // <if expr="chromeos"> /** * @enum {string} Look at ToJSDeviceReportingType usage in @@ -87,6 +104,9 @@ cr.define('management', function() { /** @return {!Promise<!management.ManagedDataResponse>} */ getContextualManagedData() {} + /** @return {!Promise<!management.ThreatProtectionInfo>} */ + getThreatProtectionInfo() {} + /** * @return {!Promise<!Array<!management.BrowserReportingResponse>>} The list * of browser reporting info messages. @@ -119,6 +139,11 @@ cr.define('management', function() { } /** @override */ + getThreatProtectionInfo() { + return cr.sendWithPromise('getThreatProtectionInfo'); + } + + /** @override */ initBrowserReportingInfo() { return cr.sendWithPromise('initBrowserReportingInfo'); } @@ -137,5 +162,6 @@ cr.define('management', function() { ManagementBrowserProxyImpl: ManagementBrowserProxyImpl, ManagementBrowserProxy: ManagementBrowserProxy, ReportingType: ReportingType, + ThreatProtectionInfo: ThreatProtectionInfo, }; }); diff --git a/chromium/chrome/browser/resources/management/management_ui.html b/chromium/chrome/browser/resources/management/management_ui.html index 725e38c4263..f52326d1ad8 100644 --- a/chromium/chrome/browser/resources/management/management_ui.html +++ b/chromium/chrome/browser/resources/management/management_ui.html @@ -52,9 +52,10 @@ .page-subtitle { align-items: center; + box-sizing: border-box; flex-direction: row; justify-content: start; - min-height: 40px; + min-height: 73px; padding-bottom: 24px; padding-top: 6px; } @@ -125,11 +126,12 @@ } .content-indented { - margin-inline-start: 24px; + padding-inline-start: 24px; } table { border-spacing: 0 16px; + box-sizing: border-box; width: 100%; } @@ -143,7 +145,8 @@ display: flex; } - .extension-name { + .extension-name, + .protection-name { width: 40%; } @@ -154,10 +157,16 @@ white-space: nowrap; } - .extension-permissions { + .extension-permissions, + .protection-permissions { width: 60%; } + .protection-name, + .protection-permissions { + vertical-align: top; + } + .extension-name img { height: 20px; margin-inline-end: 12px; @@ -199,6 +208,33 @@ </div> </if> </section> + <template is="dom-if" + if="[[showThreatProtectionInfo_(threatProtectionInfo_)]]"> + <section> + <h2 class="cr-title-text">$i18n{threatProtectionTitle}</h2> + <div class="subtitle"> + [[threatProtectionInfo_.description]] + </div> + <table class="content-indented"> + <tr> + <th class="protection-name">$i18n{extensionName}</th> + <th class="protection-permissions"> + $i18n{extensionPermissions} + </th> + </tr> + <template is="dom-repeat" + items="[[threatProtectionInfo_.info]]"> + <tr> + <td class="protection-name">[[i18n(item.title)]]</td> + <td class="protection-permissions"> + [[i18n(item.permission)]] + </td> + </tr> + </template> + </table> + </section> + </template> + <if expr="chromeos"> <div hidden="[[!localTrustRoots_]]"> <section> @@ -259,10 +295,10 @@ </div> <table class="content-indented"> <tr> - <th class="extension-name">$i18n{extensionName}</td> + <th class="extension-name">$i18n{extensionName}</th> <th class="extension-permissions"> $i18n{extensionPermissions} - </td> + </th> </tr> <template is="dom-repeat" items="[[extensions_]]"> <tr> diff --git a/chromium/chrome/browser/resources/management/management_ui.js b/chromium/chrome/browser/resources/management/management_ui.js index a4984aa83d7..a04d5ed4935 100644 --- a/chromium/chrome/browser/resources/management/management_ui.js +++ b/chromium/chrome/browser/resources/management/management_ui.js @@ -66,6 +66,9 @@ cr.define('management', function() { /** @private */ extensionReportingSubtitle_: String, + + /** @private {!management.ThreatProtectionInfo} */ + threatProtectionInfo_: Object, }, /** @private {?management.ManagementBrowserProxy} */ @@ -77,6 +80,7 @@ cr.define('management', function() { this.browserProxy_ = management.ManagementBrowserProxyImpl.getInstance(); this.updateManagedFields_(); this.initBrowserReportingInfo_(); + this.getThreatProtectionInfo_(); this.addWebUIListener( 'browser-reporting-info-updated', @@ -86,6 +90,10 @@ cr.define('management', function() { this.updateManagedFields_(); }); + this.addWebUIListener( + 'threat-protection-info-updated', + info => this.threatProtectionInfo_ = info); + this.getExtensions_(); // <if expr="chromeos"> this.getDeviceReportingInfo_(); @@ -134,6 +142,22 @@ cr.define('management', function() { }); }, + /** @private */ + getThreatProtectionInfo_() { + this.browserProxy_.getThreatProtectionInfo().then(info => { + this.threatProtectionInfo_ = info; + }); + }, + + /** + * @return {boolean} True if there is threat protection info to show. + * @private + */ + showThreatProtectionInfo_() { + return !!this.threatProtectionInfo_ && + this.threatProtectionInfo_.info.length > 0; + }, + // <if expr="chromeos"> /** @private */ getLocalTrustRootsInfo_() { diff --git a/chromium/chrome/browser/resources/media/media_engagement.html b/chromium/chrome/browser/resources/media/media_engagement.html index 8922e663882..b1a0fdf1a52 100644 --- a/chromium/chrome/browser/resources/media/media_engagement.html +++ b/chromium/chrome/browser/resources/media/media_engagement.html @@ -140,27 +140,12 @@ <th sort-key="mediaPlaybacks" sort-reverse> Sessions with playback </th> - <th sort-key="audioContextPlaybacks" sort-reverse> - Sessions with playback<br>(audio context only) - </th> - <th sort-key="mediaElementPlaybacks" sort-reverse> - Sessions with playback<br>(media element only) - </th> - <th sort-key="audiblePlaybacks" sort-reverse> - Audible Playbacks* - </th> - <th sort-key="significantPlaybacks" sort-reverse> - Significant Playbacks* - </th> <th sort-key="lastMediaPlaybackTime" sort-reverse> Last Playback </th> <th sort-key="isHigh" sort-reverse> Is High </th> - <th sort-key="highScoreChanges" sort-reverse> - Is High Changes - </th> <th sort-key="totalScore" class="sort-column" sort-reverse> Score </th> @@ -170,22 +155,13 @@ </tbody> </table> - <p> - * These columns are experimental and do not currently affect the MEI score. - </p> - <template id="datarow"> <tr> <td class="origin-cell"></td> <td class="visits-count-cell"></td> <td class="media-playbacks-count-cell"></td> - <td class="audio-context-playbacks-count-cell"></td> - <td class="media-element-playbacks-count-cell"></td> - <td class="audible-playbacks-count-cell"></td> - <td class="significant-playbacks-count-cell"></td> <td class="last-playback-time-cell"></td> <td class="is-high-cell"></td> - <td class="is-high-changes-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 5491928b222..d56ef21e6ff 100644 --- a/chromium/chrome/browser/resources/media/media_engagement.js +++ b/chromium/chrome/browser/resources/media/media_engagement.js @@ -13,7 +13,7 @@ function whenPageIsPopulatedForTest() { (function() { -let uiHandler = null; +let detailsProvider = null; let info = null; let engagementTableBody = null; let sortReverse = true; @@ -39,17 +39,12 @@ function createRow(rowInfo) { td[1].textContent = rowInfo.visits; td[2].textContent = rowInfo.mediaPlaybacks; - td[3].textContent = rowInfo.audioContextPlaybacks; - td[4].textContent = rowInfo.mediaElementPlaybacks; - td[5].textContent = rowInfo.audiblePlaybacks; - td[6].textContent = rowInfo.significantPlaybacks; - td[7].textContent = rowInfo.lastMediaPlaybackTime ? + td[3].textContent = rowInfo.lastMediaPlaybackTime ? new Date(rowInfo.lastMediaPlaybackTime).toISOString() : ''; - td[8].textContent = rowInfo.isHigh ? 'Yes' : 'No'; - td[9].textContent = rowInfo.highScoreChanges; - td[10].textContent = rowInfo.totalScore ? rowInfo.totalScore.toFixed(2) : '0'; - td[11].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); } @@ -180,20 +175,20 @@ function renderTable() { */ function updateEngagementTable() { // Populate engagement table. - uiHandler.getMediaEngagementScoreDetails().then(response => { + detailsProvider.getMediaEngagementScoreDetails().then(response => { info = response.info; renderTable(); pageIsPopulatedResolver.resolve(); }); // Populate config settings. - uiHandler.getMediaEngagementConfig().then(response => { + detailsProvider.getMediaEngagementConfig().then(response => { renderConfigTable(response.config); }); } document.addEventListener('DOMContentLoaded', function() { - uiHandler = media.mojom.MediaEngagementScoreDetailsProvider.getProxy(); + detailsProvider = media.mojom.MediaEngagementScoreDetailsProvider.getRemote(); updateEngagementTable(); engagementTableBody = $('engagement-table-body'); diff --git a/chromium/chrome/browser/resources/media_router/extension/BUILD.gn b/chromium/chrome/browser/resources/media_router/extension/BUILD.gn index 8728b3b4f02..a1b45248410 100644 --- a/chromium/chrome/browser/resources/media_router/extension/BUILD.gn +++ b/chromium/chrome/browser/resources/media_router/extension/BUILD.gn @@ -1,11 +1,5 @@ import("src/files.gni") -group("all") { - deps = [ - ":media_router", - ] -} - declare_args() { # Determines whether JSCompiler should be used to typecheck # JavaScript code for the Media Router extension. @@ -72,7 +66,7 @@ action("media_router") { outputs = [ "$target_gen_dir/manifest.json", ] - deps = [ + data_deps = [ ":copy_prelude", ":media_router_modules", ] diff --git a/chromium/chrome/browser/resources/ntp4/dot_list.js b/chromium/chrome/browser/resources/ntp4/dot_list.js index 9e5bdfaca44..d37ff53dfbc 100644 --- a/chromium/chrome/browser/resources/ntp4/dot_list.js +++ b/chromium/chrome/browser/resources/ntp4/dot_list.js @@ -11,7 +11,7 @@ cr.define('ntp', function() { /** * Live list of the navigation dots. - * @type {!NodeList|undefined} + * @type {!HTMLCollection<!Element>} */ let navDots; diff --git a/chromium/chrome/browser/resources/ntp4/new_tab.html b/chromium/chrome/browser/resources/ntp4/new_tab.html index 2cc968e011d..de19cad2443 100644 --- a/chromium/chrome/browser/resources/ntp4/new_tab.html +++ b/chromium/chrome/browser/resources/ntp4/new_tab.html @@ -34,7 +34,6 @@ document.write('<link id="themecss" rel="stylesheet" ' + <script src="../../../../ui/webui/resources/js/action_link.js"></script> <script src="../../../../ui/webui/resources/js/event_tracker.js"></script> <script src="../../../../ui/webui/resources/js/util.js"></script> -<script src="../../../../ui/webui/resources/js/icon.js"></script> <script src="../../../../ui/webui/resources/js/cr.js"></script> <script src="../../../../ui/webui/resources/js/cr/event_target.js"></script> @@ -49,6 +48,7 @@ document.write('<link id="themecss" rel="stylesheet" ' + <script src="../../../../ui/webui/resources/js/cr/ui/position_util.js"></script> <script src="../../../../ui/webui/resources/js/cr/ui/menu_button.js"></script> <script src="../../../../ui/webui/resources/js/cr/ui/touch_handler.js"></script> +<script src="../../../../ui/webui/resources/js/icon.js"></script> <script src="tile_page.js"></script> <script src="apps_page.js"></script> diff --git a/chromium/chrome/browser/resources/ntp4/page_list_view.js b/chromium/chrome/browser/resources/ntp4/page_list_view.js index 3a878c35ac5..b9e093a44e1 100644 --- a/chromium/chrome/browser/resources/ntp4/page_list_view.js +++ b/chromium/chrome/browser/resources/ntp4/page_list_view.js @@ -78,13 +78,13 @@ cr.define('ntp', function() { /** * A list of all 'tile-page' elements. - * @type {!NodeList|undefined} + * @type {!HTMLCollection<!ntp.TilePage>|undefined} */ tilePages: undefined, /** * A list of all 'apps-page' elements. - * @type {!NodeList|undefined} + * @type {!HTMLCollection<!ntp.AppsPage>|undefined} */ appsPages: undefined, @@ -175,8 +175,10 @@ cr.define('ntp', function() { document.addEventListener('keydown', this.onDocKeyDown_.bind(this)); - this.tilePages = this.pageList.getElementsByClassName('tile-page'); - this.appsPages = this.pageList.getElementsByClassName('apps-page'); + this.tilePages = /** @type {!HTMLCollection<!ntp.TilePage>} */ ( + this.pageList.getElementsByClassName('tile-page')); + this.appsPages = /** @type {!HTMLCollection<!ntp.AppsPage>} */ ( + this.pageList.getElementsByClassName('apps-page')); // Initialize the cardSlider without any cards at the moment. this.sliderFrame = cardSliderFrame; diff --git a/chromium/chrome/browser/resources/omnibox/omnibox.html b/chromium/chrome/browser/resources/omnibox/omnibox.html index 1f9f1f8e96b..402bef06eb3 100644 --- a/chromium/chrome/browser/resources/omnibox/omnibox.html +++ b/chromium/chrome/browser/resources/omnibox/omnibox.html @@ -6,6 +6,7 @@ <title>Omnibox Debug Page</title> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> <link rel="stylesheet" href="omnibox.css"> + <script src="chrome://resources/js/promise_resolver.js"></script> <script src="chrome://resources/js/cr.js"></script> <script src="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js"></script> <script src="chrome://resources/js/load_time_data.js"></script> @@ -108,6 +109,7 @@ </option> <option value="7">new tab page omnibox</option> <option value="8">new tab page fakebox</option> + <option value="15">new tab page realbox</option> <option value="1">(OBSOLETE) new tab page</option> </select> </div> diff --git a/chromium/chrome/browser/resources/omnibox/omnibox.js b/chromium/chrome/browser/resources/omnibox/omnibox.js index 5c2c818e7ec..c5d0e722454 100644 --- a/chromium/chrome/browser/resources/omnibox/omnibox.js +++ b/chromium/chrome/browser/resources/omnibox/omnibox.js @@ -71,7 +71,7 @@ class BrowserProxy { this.handler_.setClientPage( this.callbackRouter_.$.bindNewPipeAndPassRemote()); - /** @private {Request} */ + /** @private {?Request} */ this.lastRequest; } @@ -81,8 +81,13 @@ class BrowserProxy { * @param {boolean} isPageController */ handleNewAutocompleteResponse(response, isPageController) { + // Note: Using inputText is a sufficient fix for the way this is used today, + // but in principle it would be better to associate requests with responses + // using a unique session identifier, for example by rolling an integer each + // time a request is made. Doing so would require extra bookkeeping on the + // host side, so for now we keep it simple. const isForLastPageRequest = isPageController && this.lastRequest && - this.lastRequest.inputText === response.host; + this.lastRequest.inputText === response.inputText; // When unfocusing the browser omnibox, the autocomplete controller // sends a response with no combined results. This response is ignored @@ -95,6 +100,9 @@ class BrowserProxy { omniboxOutput.addAutocompleteResponse(response); } + // TODO(orinj|manukh): If |response.done| but not |isForLastPageRequest| + // then callback is being dropped. We should guarantee that callback is + // always called because some callers await promises. if (isForLastPageRequest && response.done) { this.lastRequest.callback(response); this.lastRequest = null; @@ -234,18 +242,29 @@ class ExportDelegate { }; batchExports.push(exportData); } + const variationInfo = + await cr.sendWithPromise('requestVariationInfo', true); + const pathInfo = await cr.sendWithPromise('requestPathInfo'); + const loadTimeDataKeys = ['cl', 'command_line', 'executable_path', + 'language', 'official', 'os_type', 'profile_path', 'useragent', + 'version', 'version_bitsize', 'version_modifier']; + const versionDetails = Object.fromEntries( + loadTimeDataKeys.map(key => [key, window.loadTimeData.getValue(key)])); + const now = new Date(); const fileName = `omnibox_batch_${ExportDelegate.getTimeStamp(now)}.json`; // If this data format changes, please roll schemaVersion. const batchData = { schemaKind: 'Omnibox Batch Export', - schemaVersion: 2, + schemaVersion: 3, dateCreated: now.toISOString(), author: '', description: '', authorTool: 'chrome://omnibox', batchName, - versionDetails: window.loadTimeData.data_, + versionDetails, + variationInfo, + pathInfo, appVersion: navigator.appVersion, batchExports }; @@ -322,7 +341,7 @@ class ExportDelegate { a.click(); } - /** + /** * @param {Date=} date * @return {string} A sortable timestamp string for use in filenames. */ diff --git a/chromium/chrome/browser/resources/omnibox/omnibox_output.js b/chromium/chrome/browser/resources/omnibox/omnibox_output.js index fb578cadce8..72184d02c97 100644 --- a/chromium/chrome/browser/resources/omnibox/omnibox_output.js +++ b/chromium/chrome/browser/resources/omnibox/omnibox_output.js @@ -727,7 +727,7 @@ cr.define('omnibox_output', function() { */ static renderClassifiedText_(container, string, classes) { clearChildren(container); - OutputAnswerProperty.classify(string + '\n', classes) + OutputAnswerProperty.classify(string, classes) .map( ({string, style}) => OutputJsonProperty.renderJsonWord( string, OutputAnswerProperty.styleToClasses_(style))) @@ -1054,6 +1054,10 @@ cr.define('omnibox_output', function() { ], OutputAnswerProperty), new Column( + ['S'], '', 'swapContentsAndDescription', false, + 'Swap Contents and Description', ['swapContentsAndDescription'], + OutputBooleanProperty), + new Column( ['D'], '', 'allowedToBeDefaultMatch', true, 'Can be Default\nA green checkmark indicates that the result can be ' + 'the default match (i.e., can be the match that pressing enter ' + diff --git a/chromium/chrome/browser/resources/omnibox/omnibox_output_column_widths.css b/chromium/chrome/browser/resources/omnibox/omnibox_output_column_widths.css index beff890c350..45c82783cde 100644 --- a/chromium/chrome/browser/resources/omnibox/omnibox_output_column_widths.css +++ b/chromium/chrome/browser/resources/omnibox/omnibox_output_column_widths.css @@ -36,6 +36,7 @@ width: 240%; } +.header-swap-contents-and-description, .header-allowed-to-be-default-match, .header-starred, .header-has-tab-match, diff --git a/chromium/chrome/browser/resources/omnibox/output_results_group.css b/chromium/chrome/browser/resources/omnibox/output_results_group.css index 56f5d510296..c46e20e82aa 100644 --- a/chromium/chrome/browser/resources/omnibox/output_results_group.css +++ b/chromium/chrome/browser/resources/omnibox/output_results_group.css @@ -54,6 +54,7 @@ table { } .body td { + white-space: pre-wrap; word-break: break-all; } @@ -62,7 +63,7 @@ table { } .body td.elided:not(:hover) { - white-space: nowrap; + white-space: pre; } .body td:not(:hover) * { diff --git a/chromium/chrome/browser/resources/pdf/BUILD.gn b/chromium/chrome/browser/resources/pdf/BUILD.gn index 1483ff4a9a0..89a0223ca86 100644 --- a/chromium/chrome/browser/resources/pdf/BUILD.gn +++ b/chromium/chrome/browser/resources/pdf/BUILD.gn @@ -14,6 +14,9 @@ group("closure_compile") { "elements/viewer-page-indicator:closure_compile", "elements/viewer-page-selector:closure_compile", "elements/viewer-password-screen:closure_compile", + "elements/viewer-pdf-toolbar:closure_compile", + "elements/viewer-toolbar-dropdown:closure_compile", + "elements/viewer-zoom-toolbar:closure_compile", ] if (is_chromeos) { deps += [ @@ -54,17 +57,12 @@ js_library("pdf_scripting_api") { js_library("viewport_scroller") { } -js_library("viewport_interface") { - deps = [ - ":pdf_fitting_type", - ] -} - js_library("viewport") { deps = [ ":gesture_detector", - ":viewport_interface", + ":pdf_fitting_type", ":zoom_manager", + "//ui/webui/resources/js:event_tracker", "//ui/webui/resources/js:util", ] externs_list = [ "$externs_path/pending.js" ] @@ -73,7 +71,7 @@ js_library("viewport") { js_library("zoom_manager") { deps = [ ":browser_api", - ":viewport_interface", + "//ui/webui/resources/js/cr:event_target", ] } @@ -81,16 +79,23 @@ js_library("metrics") { externs_list = [ "$externs_path/metrics_private.js" ] } +js_library("navigator") { + deps = [ + ":open_pdf_params_parser", + ":viewport", + ] +} + js_type_check("pdf_resources") { deps = [ ":browser_api", ":gesture_detector", ":metrics", + ":navigator", ":open_pdf_params_parser", ":pdf_fitting_type", ":pdf_scripting_api", ":viewport", - ":viewport_interface", ":viewport_scroller", ":zoom_manager", ] diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html index ae14eeb289f..004aa1b1677 100644 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html @@ -49,21 +49,21 @@ transform: rotate(180deg); } - :host([children-shown]) #expand { + :host([children-shown_]) #expand { transform: rotate(90deg); } </style> - <div id="item" on-click="onClick"> + <div id="item" on-click="onClick_"> <paper-ripple></paper-ripple> <cr-icon-button id="expand" iron-icon="cr:chevron-right" - on-click="toggleChildren"></cr-icon-button> + on-click="toggleChildren_"></cr-icon-button> <span id="title" tabindex="0">{{bookmark.title}}</span> </div> <!-- dom-if will stamp the complex bookmark tree lazily as individual nodes are opened. --> - <template is="dom-if" if="[[childrenShown]]" id="sub-bookmarks"> + <template is="dom-if" if="[[childrenShown_]]"> <template is="dom-repeat" items="[[bookmark.children]]"> - <viewer-bookmark bookmark="{{item}}" depth="{{childDepth}}"> + <viewer-bookmark bookmark="{{item}}" depth="[[childDepth_]]"> </viewer-bookmark> </template> </template> diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js index 160191b6ecb..f1cce48abaa 100644 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js @@ -15,9 +15,9 @@ * structure. * @typedef {{ * title: string, - * page: number, - * y: number, - * uri: string, + * page: (number | undefined), + * y: (number | undefined), + * uri: (string | undefined), * children: !Array<!Bookmark> * }} */ @@ -32,13 +32,25 @@ Polymer({ properties: { /** @type {Bookmark} */ - bookmark: {type: Object, observer: 'bookmarkChanged_'}, - - depth: {type: Number, observer: 'depthChanged'}, - - childDepth: Number, - - childrenShown: {type: Boolean, reflectToAttribute: true, value: false}, + bookmark: { + type: Object, + observer: 'bookmarkChanged_', + }, + + depth: { + type: Number, + observer: 'depthChanged_' + }, + + /** @private */ + childDepth_: Number, + + /** @private */ + childrenShown_: { + type: Boolean, + reflectToAttribute: true, + value: false, + }, /** @type {?HTMLElement} The target for the key bindings below. */ keyEventTarget: Object, @@ -53,18 +65,21 @@ Polymer({ this.keyEventTarget = this.$.item; }, + /** @private */ bookmarkChanged_: function() { this.$.expand.style.visibility = this.bookmark.children.length > 0 ? 'visible' : 'hidden'; }, - depthChanged: function() { - this.childDepth = this.depth + 1; + /** @private */ + depthChanged_: function() { + this.childDepth_ = this.depth + 1; this.$.item.style.paddingInlineStart = (this.depth * BOOKMARK_INDENT) + 'px'; }, - onClick: function() { + /** @private */ + onClick_: function() { if (this.bookmark.hasOwnProperty('page')) { if (this.bookmark.hasOwnProperty('y')) { this.fire('change-page-and-xy', { @@ -82,25 +97,37 @@ Polymer({ } }, + /** + * @param {!KeyboardEvent} e + * @private + */ onEnter_: function(e) { // Don't allow events which have propagated up from the expand button to // trigger a click. if (e.detail.keyboardEvent.target != this.$.expand) { - this.onClick(); + this.onClick_(); } }, + /** + * @param {!KeyboardEvent} e + * @private + */ onSpace_: function(e) { // cr-icon-button stops propagation of space events, so there's no need // to check the event source here. - this.onClick(); + this.onClick_(); // Prevent default space scroll behavior. e.detail.keyboardEvent.preventDefault(); }, - toggleChildren: function(e) { - this.childrenShown = !this.childrenShown; - e.stopPropagation(); // Prevent the above onClick handler from firing. + /** + * @param {!Event} e + * @private + */ + toggleChildren_: function(e) { + this.childrenShown_ = !this.childrenShown_; + e.stopPropagation(); // Prevent the above onClick_ handler from firing. } }); })(); diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html deleted file mode 100644 index 2277ec4d941..00000000000 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html +++ /dev/null @@ -1,12 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="../viewer-bookmark/viewer-bookmark.html"> - -<dom-module id="viewer-bookmarks-content"> - <template> - <template is="dom-repeat" items="[[bookmarks]]"> - <viewer-bookmark bookmark="{{item}}" depth="0"></viewer-bookmark> - </template> - </template> - <script src="viewer-bookmarks-content.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js deleted file mode 100644 index 32f3fd320d5..00000000000 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js +++ /dev/null @@ -1,5 +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. - -Polymer({is: 'viewer-bookmarks-content'}); diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host/viewer-ink-host.js b/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host/viewer-ink-host.js index 6bb2e4c68ed..285edf8a35d 100644 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host/viewer-ink-host.js +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host/viewer-ink-host.js @@ -47,7 +47,7 @@ Polymer({ /** @private {boolean} */ penMode_: false, - /** @type {Viewport} */ + /** @type {?Viewport} */ viewport: null, /** @type {?AnnotationTool} */ @@ -247,7 +247,7 @@ Polymer({ const viewport = this.viewport; const pos = viewport.position; const size = viewport.size; - const zoom = viewport.zoom; + const zoom = viewport.getZoom(); const documentWidth = viewport.getDocumentDimensions().width * zoom; // Adjust for page shadows. const y = pos.y - Viewport.PAGE_SHADOW.top * zoom; diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/BUILD.gn b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/BUILD.gn new file mode 100644 index 00000000000..fdc650f55b9 --- /dev/null +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +js_type_check("closure_compile") { + deps = [ + ":viewer-pdf-toolbar", + ] +} + +js_library("viewer-pdf-toolbar") { + deps = [ + "../viewer-bookmark:viewer-bookmark", + "../viewer-page-selector:viewer-page-selector", + "../viewer-toolbar-dropdown:viewer-toolbar-dropdown", + ] + externs_list = [ "$externs_path/pending.js" ] +} 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 f6454c97a5c..e183debc86d 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 @@ -5,7 +5,7 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-progress/paper-progress.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="../icons.html"> -<link rel="import" href="../viewer-bookmarks-content/viewer-bookmarks-content.html"> +<link rel="import" href="../viewer-bookmark/viewer-bookmark.html"> <link rel="import" href="../viewer-page-selector/viewer-page-selector.html"> <if expr="chromeos"> <link rel="import" href="../viewer-pen-options/viewer-pen-options.html"> @@ -214,8 +214,9 @@ open-icon="pdf:bookmark" closed-icon="pdf:bookmark-border" header="{{strings.bookmarks}}"> - <viewer-bookmarks-content bookmarks="{{bookmarks}}"> - </viewer-bookmarks-content> + <template is="dom-repeat" items="[[bookmarks]]"> + <viewer-bookmark bookmark="[[item]]" depth="0"></viewer-bookmark> + </template> </viewer-toolbar-dropdown> </div> </div> @@ -228,7 +229,7 @@ <div id="annotations-bar" hidden> <viewer-toolbar-dropdown id="pen" - selected$="[[equal_('pen', annotationTool.tool)]]" + selected$="[[isAnnotationTool_('pen', annotationTool.tool)]]" open-after-select on-click="annotationToolClicked_" open-icon="pdf:marker" @@ -247,7 +248,7 @@ </viewer-toolbar-dropdown> <viewer-toolbar-dropdown id="highlighter" - selected$="[[equal_('highlighter', annotationTool.tool)]]" + selected$="[[isAnnotationTool_('highlighter', annotationTool.tool)]]" open-after-select on-click="annotationToolClicked_" open-icon="pdf:highlighter" @@ -266,7 +267,7 @@ </viewer-toolbar-dropdown> <cr-icon-button id="eraser" - selected$="[[equal_('eraser', annotationTool.tool)]]" + selected$="[[isAnnotationTool_('eraser', annotationTool.tool)]]" on-click="annotationToolClicked_" iron-icon="pdf:eraser" aria-label$="{{strings.annotationEraser}}" title$="{{strings.annotationEraser}}"></cr-icon-button> diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js index 006aa5ca5b8..afb87dfe6b7 100644 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js @@ -7,38 +7,16 @@ Polymer({ properties: { /** - * The current loading progress of the PDF document (0 - 100). - */ - loadProgress: {type: Number, observer: 'loadProgressChanged_'}, - - /** - * The title of the PDF document. - */ - docTitle: String, - - /** - * The number of the page being viewed (1-based). - */ - pageNo: Number, - - /** - * Tree of PDF bookmarks (or null if the document has no bookmarks). - */ - bookmarks: {type: Object, value: null}, - - /** - * The number of pages in the PDF document. - */ - docLength: Number, - - /** - * Whether the toolbar is opened and visible. + * Whether annotation mode can be entered. This would be false if for + * example the PDF is encrypted or password protected. Note, this is + * true regardless of whether the feature flag is enabled. */ - opened: {type: Boolean, value: true}, + annotationAvailable: { + type: Boolean, + value: true, + }, - /** - * Whether the viewer is currently in annotation mode. - */ + /** Whether the viewer is currently in annotation mode. */ annotationMode: { type: Boolean, notify: true, @@ -46,6 +24,7 @@ Polymer({ reflectToAttribute: true, }, + /** @type {?Object} */ annotationTool: { type: Object, value: null, @@ -53,13 +32,17 @@ Polymer({ }, /** - * Whether annotation mode can be entered. This would be false if for - * example the PDF is encrypted or password protected. Note, this is - * true regardless of whether the feature flag is enabled. + * Tree of PDF bookmarks (empty if the document has no bookmarks). + * @type {!Array<!Bookmark>} */ - annotationAvailable: { + bookmarks: { + type: Array, + value: () => [], + }, + + canRedoAnnotation: { type: Boolean, - value: true, + value: false, }, canUndoAnnotation: { @@ -67,22 +50,34 @@ Polymer({ value: false, }, - canRedoAnnotation: { + /** The number of pages in the PDF document. */ + docLength: Number, + + /** The title of the PDF document. */ + docTitle: String, + + /** The current loading progress of the PDF document (0 - 100). */ + loadProgress: { + type: Number, + observer: 'loadProgressChanged_', + }, + + /** Whether the toolbar is opened and visible. */ + opened: { type: Boolean, - value: false, + value: true, }, - /** - * Whether the PDF Annotations feature is enabled. - */ + /** The number of the page being viewed (1-based). */ + pageNo: Number, + + /** Whether the PDF Annotations feature is enabled. */ pdfAnnotationsEnabled: { type: Boolean, value: false, }, - /** - * Whether the Printing feature is enabled. - */ + /** Whether the Printing feature is enabled. */ printingEnabled: { type: Boolean, value: false, @@ -91,6 +86,9 @@ Polymer({ strings: Object, }, + /** @type {?Object} */ + animation_: null, + /** * @param {number} newProgress * @param {number} oldProgress @@ -130,22 +128,16 @@ Polymer({ if (this.opened) { this.animation_ = this.animate( - { - transform: ['translateY(-100%)', 'translateY(0%)'], - }, - { - easing: 'cubic-bezier(0, 0, 0.2, 1)', + [{transform: 'translateY(-100%)'}, {transform: 'translateY(0%)'}], { duration: 250, + easing: 'cubic-bezier(0, 0, 0.2, 1)', fill: 'forwards', }); } else { this.animation_ = this.animate( - { - transform: ['translateY(0%)', 'translateY(-100%)'], - }, - { - easing: 'cubic-bezier(0.4, 0, 1, 1)', + [{transform: 'translateY(0%)'}, {transform: 'translateY(-100%)'}], { duration: 250, + easing: 'cubic-bezier(0.4, 0, 1, 1)', fill: 'forwards', }); } @@ -155,11 +147,13 @@ Polymer({ this.$.pageselector.select(); }, + /** @return {boolean} Whether the toolbar should be kept open. */ shouldKeepOpen: function() { return this.$.bookmarks.dropdownOpen || this.loadProgress < 100 || this.$.pageselector.isActive() || this.annotationMode; }, + /** @return {boolean} Whether a dropdown was open and was hidden. */ hideDropdowns: function() { let result = false; if (this.$.bookmarks.dropdownOpen) { @@ -177,6 +171,7 @@ Polymer({ return result; }, + /** @param {number} lowerBound */ setDropdownLowerBound: function(lowerBound) { this.$.bookmarks.lowerBound = lowerBound; }, @@ -214,12 +209,18 @@ Polymer({ })); }, - /** @param {Event} e */ + /** + * @param {!Event} e + * @private + */ annotationToolClicked_: function(e) { - this.updateAnnotationTool_(e.currentTarget); + this.updateAnnotationTool_(/** @type {!HTMLElement} */ (e.currentTarget)); }, - /** @param {Event} e */ + /** + * @param {!Event} e + * @private + */ annotationToolOptionChanged_: function(e) { const element = e.currentTarget.parentElement; if (!this.annotationTool || element.id != this.annotationTool.tool) { @@ -228,15 +229,19 @@ Polymer({ this.updateAnnotationTool_(e.currentTarget.parentElement); }, - /** @param {Element} element */ + /** + * @param {!HTMLElement} element + * @private + */ updateAnnotationTool_: function(element) { const tool = element.id; const options = element.querySelector('viewer-pen-options') || { selectedSize: 1, selectedColor: null, }; - element.attributeStyleMap.set('--pen-tip-fill', options.selectedColor); - element.attributeStyleMap.set( + const attributeStyleMap = element.attributeStyleMap; + attributeStyleMap.set('--pen-tip-fill', options.selectedColor); + attributeStyleMap.set( '--pen-tip-border', options.selectedColor == '#000000' ? 'currentcolor' : options.selectedColor); @@ -248,14 +253,12 @@ Polymer({ }, /** - * Used to determine equality in computed bindings. - * - * @param {*} a - * @param {*} b + * @param {string} toolName + * @return {boolean} Whether the annotation tool is using tool |toolName|. + * @private */ - equal_: function(a, b) { - return a == b; + isAnnotationTool_: function(toolName) { + return !!this.annotationTool && this.annotationTool.tool === toolName; }, - }); })(); diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/BUILD.gn b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/BUILD.gn new file mode 100644 index 00000000000..7a2ca5ce91a --- /dev/null +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/BUILD.gn @@ -0,0 +1,15 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +js_type_check("closure_compile") { + deps = [ + ":viewer-toolbar-dropdown", + ] +} + +js_library("viewer-toolbar-dropdown") { + deps = [] +} 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 c1964a19a20..1ebf0df604f 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 @@ -91,7 +91,7 @@ } </style> <cr-icon-button on-click="toggleDropdown" id="button" - iron-icon="[[dropdownIcon]],cr:arrow-drop-down" title$="[[header]]"> + iron-icon="[[dropdownIcon_]],cr:arrow-drop-down" title$="[[header]]"> </cr-icon-button> <div id="container"> 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 05f044afe47..00b2b676b45 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 @@ -18,6 +18,23 @@ Polymer({ is: 'viewer-toolbar-dropdown', properties: { + /** Icon to display when the dropdown is closed. */ + closedIcon: String, + + /** Whether the dropdown should be centered or right aligned. */ + dropdownCentered: { + type: Boolean, + reflectToAttribute: true, + value: false, + }, + + /** True if the dropdown is currently open. */ + dropdownOpen: { + type: Boolean, + reflectToAttribute: true, + value: false, + }, + /** * String to be displayed at the top of the dropdown and for the tooltip * of the button. @@ -25,43 +42,53 @@ Polymer({ header: String, /** Whether to hide the header at the top of the dropdown. */ - hideHeader: {type: Boolean, value: false}, - - /** Icon to display when the dropdown is closed. */ - closedIcon: String, + hideHeader: { + type: Boolean, + value: false, + }, - /** Icon to display when the dropdown is open. */ - openIcon: String, + /** Lowest vertical point that the dropdown should occupy (px). */ + lowerBound: { + type: Number, + observer: 'lowerBoundChanged_', + }, /** Unique id to identify this dropdown for metrics purposes. */ metricsId: String, - /** True if the dropdown is currently open. */ - dropdownOpen: {type: Boolean, reflectToAttribute: true, value: false}, + /** Whether the dropdown must be selected before opening. */ + openAfterSelect: { + type: Boolean, + value: false, + }, - /** Whether the dropdown should be centered or right aligned. */ - dropdownCentered: {type: Boolean, reflectToAttribute: true, value: false}, + /** Icon to display when the dropdown is open. */ + openIcon: String, /** Whether the dropdown is marked as selected. */ - selected: {type: Boolean, reflectToAttribute: true, value: false}, - - /** Whether the dropdown must be selected before opening. */ - openAfterSelect: {type: Boolean, reflectToAttribute: true, value: false}, + selected: { + type: Boolean, + reflectToAttribute: true, + value: false, + }, - /** Toolbar icon currently being displayed. */ - dropdownIcon: { + /** + * Toolbar icon currently being displayed. + * @private + */ + dropdownIcon_: { type: String, - computed: 'computeIcon_(dropdownOpen, closedIcon, openIcon)' + computed: 'computeIcon_(dropdownOpen, closedIcon, openIcon)', }, - - /** Lowest vertical point that the dropdown should occupy (px). */ - lowerBound: {type: Number, observer: 'lowerBoundChanged_'}, - - /** Current animation being played, or null if there is none. */ - animation_: Object }, /** + * Current animation being played, or null if there is none. + * @private {?Object} + */ + animation_: null, + + /** * True if the max-height CSS property for the dropdown scroll container * is valid. If false, the height will be updated the next time the * dropdown is visible. @@ -69,10 +96,15 @@ Polymer({ */ maxHeightValid_: false, + /** + * @return {string} Current icon for the dropdown. + * @private + */ computeIcon_: function(dropdownOpen, closedIcon, openIcon) { return dropdownOpen ? openIcon : closedIcon; }, + /** @private */ lowerBoundChanged_: function() { this.maxHeightValid_ = false; if (this.dropdownOpen) { @@ -137,6 +169,10 @@ Polymer({ }; }, + /** + * @return {!Object} Animation + * @private + */ animateEntry_: function() { let maxHeight = this.$.dropdown.getBoundingClientRect().height - DROPDOWN_OUTER_PADDING; @@ -164,6 +200,10 @@ Polymer({ }); }, + /** + * @return {!Object} Animation + * @private + */ animateExit_: function() { return this.$.dropdown.animate( [ diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/BUILD.gn b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/BUILD.gn new file mode 100644 index 00000000000..4c75971c261 --- /dev/null +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +js_type_check("closure_compile") { + deps = [ + ":viewer-zoom-button", + ":viewer-zoom-toolbar", + ] +} + +js_library("viewer-zoom-toolbar") { + deps = [ + ":viewer-zoom-button", + "../..:pdf_fitting_type", + "//ui/webui/resources/js:assert", + "//ui/webui/resources/js:util", + ] +} + +js_library("viewer-zoom-button") { + deps = [] +} diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html index a3ae841c93f..000d098cfb3 100644 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html @@ -19,14 +19,14 @@ transition-timing-function: cubic-bezier(0, 0, 0.2, 1); } - :host([closed]) #wrapper { + :host([closed_]) #wrapper { /* 132px roughly flips the location of the button across the right edge * of the page. */ transform: translateX(var(--translate-x-distance)); transition-timing-function: cubic-bezier(0.4, 0, 1, 1); } - :host([show-on-left][closed]) #wrapper { + :host([show-on-left][closed_]) #wrapper { transform: translateX(calc(-1 * var(--translate-x-distance))); } @@ -76,7 +76,7 @@ } </style> <div id="wrapper"> - <cr-icon-button iron-icon="[[visibleIcon_]]" on-click="fireClick" + <cr-icon-button iron-icon="[[visibleIcon_]]" on-click="fireClick_" aria-label$="[[visibleTooltip_]]" title="[[visibleTooltip_]]"> </cr-icon-button> </div> diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js index 361b292e81f..2359900d83c 100644 --- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js +++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js @@ -6,6 +6,17 @@ Polymer({ is: 'viewer-zoom-button', properties: { + /** Index of the icon currently being displayed. */ + activeIndex: { + type: Number, + value: 0, + }, + + delay: { + type: Number, + observer: 'delayChanged_', + }, + /** * Icons to be displayed on the FAB. Multiple icons should be separated with * spaces, and will be cycled through every time the FAB is clicked. @@ -13,14 +24,6 @@ Polymer({ icons: String, /** - * Array version of the list of icons. Polymer does not allow array - * properties to be set from HTML, so we must use a string property and - * perform the conversion manually. - * @private - */ - icons_: {type: Array, value: [''], computed: 'computeIconsArray_(icons)'}, - - /** * Used to show the appropriate drop shadow when buttons are focused with * the keyboard. */ @@ -29,59 +32,98 @@ Polymer({ reflectToAttribute: true, }, - tooltips: Array, - - closed: {type: Boolean, reflectToAttribute: true, value: false}, + newPrintPreview: { + type: Boolean, + reflectToAttribute: true, + }, - delay: {type: Number, observer: 'delayChanged_'}, + showOnLeft: { + type: Boolean, + reflectToAttribute: true, + }, - newPrintPreview: {type: Boolean, reflectToAttribute: true}, + /** @type {?Array<string>} */ + tooltips: Array, - showOnLeft: {type: Boolean, reflectToAttribute: true}, + /** @private */ + closed_: { + type: Boolean, + reflectToAttribute: true, + value: false, + }, /** - * Index of the icon currently being displayed. + * Array version of the list of icons. Polymer does not allow array + * properties to be set from HTML, so we must use a string property and + * perform the conversion manually. + * @private {!Array<string>} */ - activeIndex: {type: Number, value: 0}, + icons_: { + type: Array, + value: [''], + computed: 'computeIconsArray_(icons)', + }, /** * Icon currently being displayed on the FAB. * @private */ - visibleIcon_: - {type: String, computed: 'computeVisibleIcon_(icons_, activeIndex)'}, + visibleIcon_: { + type: String, + computed: 'computeVisibleIcon_(icons_, activeIndex)', + }, + /** @private */ visibleTooltip_: { type: String, - computed: 'computeVisibleTooltip_(tooltips, activeIndex)' + computed: 'computeVisibleTooltip_(tooltips, activeIndex)', } }, + /** + * @param {string} icons Icon names in a string, delimited by spaces + * @return {!Array<string>} Array of icon name strings + * @private + */ computeIconsArray_: function(icons) { return icons.split(' '); }, + /** + * @param {!Array<string>} icons Array of icon name strings. + * @param {number} activeIndex Index of the currently active icon. + * @return {string} Icon name for the currently visible icon. + * @private + */ computeVisibleIcon_: function(icons, activeIndex) { return icons[activeIndex]; }, + /** + * @param {?Array<string>} tooltips Array of tooltip strings. + * @param {number} activeIndex Index of the currently active icon. + * @return {string} Tooltip for the currently visible icon. + * @private + */ computeVisibleTooltip_: function(tooltips, activeIndex) { return tooltips === undefined ? '' : tooltips[activeIndex]; }, + /** @private */ delayChanged_: function() { this.$.wrapper.style.transitionDelay = this.delay + 'ms'; }, show: function() { - this.closed = false; + this.closed_ = false; }, hide: function() { - this.closed = true; + this.closed_ = true; }, - fireClick: function() { + /** @private */ + fireClick_: function() { // We cannot attach an on-click to the entire viewer-zoom-button, as this // will include clicks on the margins. Instead, proxy clicks on the FAB // through. 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 fb817a5a01d..fe24ab64645 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 @@ -52,6 +52,7 @@ Polymer({ return this.isPrintPreview_; }, + /** @return {boolean} */ isVisible: function() { return this.visible_; }, @@ -94,7 +95,10 @@ Polymer({ /** * Change button tooltips to match any changes to localized strings. - * @param {!Object} strings + * @param {!{tooltipFitToPage: string, + * tooltipFitToWidth: string, + * tooltipZoomIn: string, + * tooltipZoomOut: string}} strings */ setStrings: function(strings) { this.$['fit-button'].tooltips = @@ -103,9 +107,7 @@ Polymer({ this.$['zoom-out-button'].tooltips = [strings.tooltipZoomOut]; }, - /** - * Handle clicks of the fit-button. - */ + /** Handle clicks of the fit-button. */ fitToggle: function() { this.fireFitToChangedEvent_( this.$['fit-button'].activeIndex == FIT_TO_WIDTH_BUTTON_STATE ? @@ -114,9 +116,7 @@ Polymer({ true); }, - /** - * Handle the keyboard shortcut equivalent of fit-button clicks. - */ + /** Handle the keyboard shortcut equivalent of fit-button clicks. */ fitToggleFromHotKey: function() { this.fitToggle(); @@ -130,7 +130,7 @@ Polymer({ /** * Handle forcing zoom via scripting to a fitting type. - * @param {FittingType} fittingType Page fitting type to force. + * @param {!FittingType} fittingType Page fitting type to force. */ forceFit: function(fittingType) { this.fireFitToChangedEvent_(fittingType, false); @@ -143,11 +143,11 @@ Polymer({ }, /** - * @private * Fire a 'fit-to-changed' {CustomEvent} with the given FittingType as detail. - * @param {FittingType} fittingType to include as payload. + * @param {!FittingType} fittingType to include as payload. * @param {boolean} userInitiated whether the event was initiated by a user * action. + * @private */ fireFitToChangedEvent_: function(fittingType, userInitiated) { this.fire( diff --git a/chromium/chrome/browser/resources/pdf/index.html b/chromium/chrome/browser/resources/pdf/index.html index c1c362756b3..06d219a6c7e 100644 --- a/chromium/chrome/browser/resources/pdf/index.html +++ b/chromium/chrome/browser/resources/pdf/index.html @@ -12,6 +12,8 @@ <link rel="import" href="elements/viewer-zoom-toolbar/viewer-zoom-toolbar.html"> <link rel="import" href="elements/shared-vars.html"> <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> + <link rel="import" href="chrome://resources/html/cr/event_target.html"> + <link rel="import" href="chrome://resources/html/event_tracker.html"> <if expr="chromeos"> <link rel="import" href="elements/viewer-ink-host/viewer-ink-host.html"> @@ -43,7 +45,6 @@ </body> <script src="pdf_fitting_type.js"></script> <script src="toolbar_manager.js"></script> -<script src="viewport_interface.js"></script> <script src="viewport.js"></script> <script src="open_pdf_params_parser.js"></script> <script src="navigator.js"></script> diff --git a/chromium/chrome/browser/resources/pdf/navigator.js b/chromium/chrome/browser/resources/pdf/navigator.js index 0282e725de2..d2e21dde43e 100644 --- a/chromium/chrome/browser/resources/pdf/navigator.js +++ b/chromium/chrome/browser/resources/pdf/navigator.js @@ -5,42 +5,24 @@ 'use strict'; /** - * Creates a new NavigatorDelegate for calling browser-specific functions to - * do the actual navigating. - * - * @param {number} tabId The tab ID of the PDF viewer or -1 if the viewer is - * not displayed in a tab. - * @constructor + * NavigatorDelegate for calling browser-specific functions to do the actual + * navigating. */ -function NavigatorDelegate(tabId) { - this.tabId_ = tabId; -} - -/** - * Creates a new Navigator for navigating to links inside or outside the PDF. - * - * @param {string} originalUrl The original page URL. - * @param {Object} viewport The viewport info of the page. - * @param {Object} paramsParser The object for URL parsing. - * @param {Object} navigatorDelegate The object with callback functions that - * get called when navigation happens in the current tab, a new tab, - * and a new window. - * @constructor - */ -function Navigator(originalUrl, viewport, paramsParser, navigatorDelegate) { - this.originalUrl_ = originalUrl; - this.viewport_ = viewport; - this.paramsParser_ = paramsParser; - this.navigatorDelegate_ = navigatorDelegate; -} +class NavigatorDelegate { + /** + * @param {number} tabId The tab ID of the PDF viewer or -1 if the viewer is + * not displayed in a tab. + */ + constructor(tabId) { + /** @private {number} */ + this.tabId_ = tabId; + } -NavigatorDelegate.prototype = { /** * Called when navigation should happen in the current tab. - * * @param {string} url The url to be opened in the current tab. */ - navigateInCurrentTab: function(url) { + navigateInCurrentTab(url) { // When the PDFviewer is inside a browser tab, prefer the tabs API because // it can navigate from one file:// URL to another. if (chrome.tabs && this.tabId_ != -1) { @@ -48,15 +30,14 @@ NavigatorDelegate.prototype = { } else { window.location.href = url; } - }, + } /** * Called when navigation should happen in the new tab. - * * @param {string} url The url to be opened in the new tab. * @param {boolean} active Indicates if the new tab should be the active tab. */ - navigateInNewTab: function(url, active) { + navigateInNewTab(url, active) { // Prefer the tabs API because it guarantees we can just open a new tab. // window.open doesn't have this guarantee. if (chrome.tabs) { @@ -64,14 +45,13 @@ NavigatorDelegate.prototype = { } else { window.open(url); } - }, + } /** * Called when navigation should happen in the new window. - * * @param {string} url The url to be opened in the new window. */ - navigateInNewWindow: function(url) { + navigateInNewWindow(url) { // Prefer the windows API because it guarantees we can just open a new // window. window.open with '_blank' argument doesn't have this guarantee. if (chrome.windows) { @@ -80,52 +60,69 @@ NavigatorDelegate.prototype = { window.open(url, '_blank'); } } -}; +} -/** - * Represents options when navigating to a new url. C++ counterpart of - * the enum is in ui/base/window_open_disposition.h. This enum represents - * the only values that are passed from Plugin. - * @enum {number} - */ -Navigator.WindowOpenDisposition = { - CURRENT_TAB: 1, - NEW_FOREGROUND_TAB: 3, - NEW_BACKGROUND_TAB: 4, - NEW_WINDOW: 6, - SAVE_TO_DISK: 7 -}; +/** Navigator for navigating to links inside or outside the PDF. */ +class PdfNavigator { + /** + * @param {string} originalUrl The original page URL. + * @param {!Viewport} viewport The viewport info of the page. + * @param {!OpenPdfParamsParser} paramsParser The object for URL parsing. + * @param {!NavigatorDelegate} navigatorDelegate The object with callback + * functions that get called when navigation happens in the current tab, + * a new tab, and a new window. + */ + constructor(originalUrl, viewport, paramsParser, navigatorDelegate) { + /** @private {?URL} */ + this.originalUrl_ = null; + try { + this.originalUrl_ = new URL(originalUrl); + } catch (err) { + console.warn('Invalid original URL'); + } + + /** @private {!Viewport} */ + this.viewport_ = viewport; + + /** @private {!OpenPdfParamsParser} */ + this.paramsParser_ = paramsParser; + + /** @private {!NavigatorDelegate} */ + this.navigatorDelegate_ = navigatorDelegate; + } -Navigator.prototype = { /** * Function to navigate to the given URL. This might involve navigating * within the PDF page or opening a new url (in the same tab or a new tab). - * - * @param {string} url The URL to navigate to. - * @param {number} disposition The window open disposition when - * navigating to the new URL. + * @param {string} urlString The URL to navigate to. + * @param {!PdfNavigator.WindowOpenDisposition} disposition The window open + * disposition when navigating to the new URL. */ - navigate: function(url, disposition) { - if (url.length == 0) { + navigate(urlString, disposition) { + if (urlString.length == 0) { return; } // If |urlFragment| starts with '#', then it's for the same URL with a // different URL fragment. - if (url.charAt(0) == '#') { + if (urlString[0] === '#' && this.originalUrl_) { // if '#' is already present in |originalUrl| then remove old fragment // and add new url fragment. - const hashIndex = this.originalUrl_.search('#'); - if (hashIndex != -1) { - url = this.originalUrl_.substring(0, hashIndex) + url; - } else { - url = this.originalUrl_ + url; - } + const newUrl = new URL(this.originalUrl_.href); + newUrl.hash = urlString; + urlString = newUrl.href; } // If there's no scheme, then take a guess at the scheme. - if (url.indexOf('://') == -1 && url.indexOf('mailto:') == -1) { - url = this.guessUrlWithoutScheme_(url); + if (!urlString.includes('://') && !urlString.includes('mailto:')) { + urlString = this.guessUrlWithoutScheme_(urlString); + } + + let url = null; + try { + url = new URL(urlString); + } catch (err) { + return; } if (!this.isValidUrl_(url)) { @@ -133,147 +130,134 @@ Navigator.prototype = { } switch (disposition) { - case Navigator.WindowOpenDisposition.CURRENT_TAB: + case PdfNavigator.WindowOpenDisposition.CURRENT_TAB: this.paramsParser_.getViewportFromUrlParams( - url, this.onViewportReceived_.bind(this)); + url.href, this.onViewportReceived_.bind(this)); break; - case Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB: - this.navigatorDelegate_.navigateInNewTab(url, false); + case PdfNavigator.WindowOpenDisposition.NEW_BACKGROUND_TAB: + this.navigatorDelegate_.navigateInNewTab(url.href, false); break; - case Navigator.WindowOpenDisposition.NEW_FOREGROUND_TAB: - this.navigatorDelegate_.navigateInNewTab(url, true); + case PdfNavigator.WindowOpenDisposition.NEW_FOREGROUND_TAB: + this.navigatorDelegate_.navigateInNewTab(url.href, true); break; - case Navigator.WindowOpenDisposition.NEW_WINDOW: - this.navigatorDelegate_.navigateInNewWindow(url); + case PdfNavigator.WindowOpenDisposition.NEW_WINDOW: + this.navigatorDelegate_.navigateInNewWindow(url.href); break; - case Navigator.WindowOpenDisposition.SAVE_TO_DISK: + case PdfNavigator.WindowOpenDisposition.SAVE_TO_DISK: // TODO(jaepark): Alt + left clicking a link in PDF should // download the link. this.paramsParser_.getViewportFromUrlParams( - url, this.onViewportReceived_.bind(this)); + url.href, this.onViewportReceived_.bind(this)); break; default: break; } - }, + } /** * Called when the viewport position is received. - * * @param {Object} viewportPosition Dictionary containing the viewport * position. * @private */ - onViewportReceived_: function(viewportPosition) { - let originalUrl = this.originalUrl_; - let hashIndex = originalUrl.search('#'); - if (hashIndex != -1) { - originalUrl = originalUrl.substring(0, hashIndex); - } - - let newUrl = viewportPosition.url; - hashIndex = newUrl.search('#'); - if (hashIndex != -1) { - newUrl = newUrl.substring(0, hashIndex); + onViewportReceived_(viewportPosition) { + let newUrl = null; + try { + newUrl = new URL(viewportPosition.url); + } catch (err) { } const pageNumber = viewportPosition.page; - if (pageNumber != undefined && originalUrl == newUrl) { + if (pageNumber != undefined && this.originalUrl_ && newUrl && + this.originalUrl_.origin === newUrl.origin && + this.originalUrl_.pathname === newUrl.pathname) { this.viewport_.goToPage(pageNumber); } else { this.navigatorDelegate_.navigateInCurrentTab(viewportPosition.url); } - }, + } /** * Checks if the URL starts with a scheme and is not just a scheme. - * - * @param {string} url The input URL + * @param {!URL} url The input URL * @return {boolean} Whether the url is valid. * @private */ - isValidUrl_: function(url) { + isValidUrl_(url) { // Make sure |url| starts with a valid scheme. - if (!url.startsWith('http://') && !url.startsWith('https://') && - !url.startsWith('ftp://') && !url.startsWith('file://') && - !url.startsWith('mailto:')) { + const validSchemes = ['http:', 'https:', 'ftp:', 'file:', 'mailto:']; + if (!validSchemes.includes(url.protocol)) { return false; } // Navigations to file:-URLs are only allowed from file:-URLs. - if (url.startsWith('file:') && !this.originalUrl_.startsWith('file:')) { - return false; - } - - - // Make sure |url| is not only a scheme. - if (url == 'http://' || url == 'https://' || url == 'ftp://' || - url == 'file://' || url == 'mailto:') { + if (url.protocol === 'file:' && this.originalUrl_ && + this.originalUrl_.protocol !== 'file:') { return false; } return true; - }, + } /** * Attempt to figure out what a URL is when there is no scheme. - * * @param {string} url The input URL * @return {string} The URL with a scheme or the original URL if it is not * possible to determine the scheme. * @private */ - guessUrlWithoutScheme_: function(url) { + guessUrlWithoutScheme_(url) { // If the original URL is mailto:, that does not make sense to start with, // and neither does adding |url| to it. // If the original URL is not a valid URL, this cannot make a valid URL. // In both cases, just bail out. - if (this.originalUrl_.startsWith('mailto:') || + if (!this.originalUrl_ || this.originalUrl_.protocol === 'mailto:' || !this.isValidUrl_(this.originalUrl_)) { return url; } // Check for absolute paths. if (url.startsWith('/')) { - const schemeEndIndex = this.originalUrl_.indexOf('://'); - const firstSlash = this.originalUrl_.indexOf('/', schemeEndIndex + 3); - // e.g. http://www.foo.com/bar -> http://www.foo.com - const domain = firstSlash != -1 ? - this.originalUrl_.substr(0, firstSlash) : - this.originalUrl_; - return domain + url; - } - - // Check for obvious relative paths. - let isRelative = false; - if (url.startsWith('.') || url.startsWith('\\')) { - isRelative = true; + return this.originalUrl_.origin + url; } + // Check for other non-relative paths. // In Adobe Acrobat Reader XI, it looks as though links with less than // 2 dot separators in the domain are considered relative links, and - // those with 2 of more are considered http URLs. e.g. + // those with 2 or more are considered http URLs. e.g. // // www.foo.com/bar -> http // foo.com/bar -> relative link - if (!isRelative) { + if (url.startsWith('\\')) { + // Prepend so that the relative URL will be correctly computed by new + // URL() below. + url = './' + url; + } + if (!url.startsWith('.')) { const domainSeparatorIndex = url.indexOf('/'); const domainName = domainSeparatorIndex == -1 ? url : url.substr(0, domainSeparatorIndex); const domainDotCount = (domainName.match(/\./g) || []).length; - if (domainDotCount < 2) { - isRelative = true; + if (domainDotCount >= 2) { + return 'http://' + url; } } - if (isRelative) { - const slashIndex = this.originalUrl_.lastIndexOf('/'); - const path = slashIndex != -1 ? this.originalUrl_.substr(0, slashIndex) : - this.originalUrl_; - return path + '/' + url; - } - - return 'http://' + url; + return new URL(url, this.originalUrl_.href).href; } +} + +/** + * Represents options when navigating to a new url. C++ counterpart of + * the enum is in ui/base/window_open_disposition.h. This enum represents + * the only values that are passed from Plugin. + * @enum {number} + */ +PdfNavigator.WindowOpenDisposition = { + CURRENT_TAB: 1, + NEW_FOREGROUND_TAB: 3, + NEW_BACKGROUND_TAB: 4, + NEW_WINDOW: 6, + SAVE_TO_DISK: 7 }; diff --git a/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js b/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js index aacb7c437ec..d4a502a135f 100644 --- a/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js +++ b/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js @@ -2,15 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -(function() { - 'use strict'; /** * Parses the open pdf parameters passed in the url to set initial viewport * settings for opening the pdf. */ -window.OpenPDFParamsParser = class { +class OpenPdfParamsParser { /** * @param {function(Object)} postMessageCallback * Function called to fetch information for a named destination. @@ -206,6 +204,4 @@ window.OpenPDFParamsParser = class { } outstandingRequest.callback(outstandingRequest.params); } -}; - -}()); +} diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer.js b/chromium/chrome/browser/resources/pdf/pdf_viewer.js index 02763ae00c9..375663f029c 100644 --- a/chromium/chrome/browser/resources/pdf/pdf_viewer.js +++ b/chromium/chrome/browser/resources/pdf/pdf_viewer.js @@ -151,7 +151,7 @@ function PDFViewer(browserApi) { PDFMetrics.record(PDFMetrics.UserAction.DOCUMENT_OPENED); // Parse open pdf parameters. - this.paramsParser_ = new OpenPDFParamsParser( + this.paramsParser_ = new OpenPdfParamsParser( message => this.pluginController_.postMessage(message)); const toolbarEnabled = this.paramsParser_.getUiUrlParams(this.originalUrl_).toolbar && @@ -161,12 +161,13 @@ function PDFViewer(browserApi) { // to be displayed in the window. It is sized according to the document size // of the pdf and zoom level. this.sizer_ = $('sizer'); + if (this.isPrintPreview_) { this.pageIndicator_ = $('page-indicator'); } this.passwordScreen_ = $('password-screen'); this.passwordScreen_.addEventListener( - 'password-submitted', this.onPasswordSubmitted_.bind(this)); + 'password-submitted', e => this.onPasswordSubmitted_(e)); this.errorScreen_ = $('error-screen'); // Can only reload if we are in a normal tab. if (chrome.tabs && this.browserApi_.getStreamInfo().tabId != -1) { @@ -183,15 +184,16 @@ function PDFViewer(browserApi) { this.browserApi_.getZoomBehavior() == BrowserApi.ZoomBehavior.MANAGE ? this.browserApi_.getDefaultZoom() : 1.0; - this.viewport_ = new ViewportImpl( - window, this.sizer_, this.viewportChanged_.bind(this), - () => this.currentController_.beforeZoom(), - () => { - this.currentController_.afterZoom(); - this.zoomManager_.onPdfZoomChange(); - }, - this.setUserInitiated_.bind(this), getScrollbarWidth(), defaultZoom, - topToolbarHeight); + this.viewport_ = new Viewport( + window, this.sizer_, getScrollbarWidth(), defaultZoom, topToolbarHeight); + this.viewport_.setViewportChangedCallback(() => this.viewportChanged_()); + this.viewport_.setBeforeZoomCallback( + () => this.currentController_.beforeZoom()); + this.viewport_.setAfterZoomCallback( + () => this.currentController_.afterZoom()); + this.viewport_.setUserInitiatedCallback( + userInitiated => this.setUserInitiated_(userInitiated)); + window.addEventListener('beforeunload', () => this.viewport_.resetTracker()); // Create the plugin object dynamically so we can set its src. The plugin // element is sized to fill the entire window and is set to be fixed @@ -208,7 +210,7 @@ function PDFViewer(browserApi) { // with it. We also send a message indicating that extension has loaded and // is ready to receive messages. window.addEventListener( - 'message', this.handleScriptingMessage.bind(this), false); + 'message', message => this.handleScriptingMessage(message), false); this.plugin_.setAttribute('src', this.originalUrl_); this.plugin_.setAttribute( @@ -242,20 +244,18 @@ function PDFViewer(browserApi) { this.zoomToolbar_ = $('zoom-toolbar'); this.zoomToolbar_.setIsPrintPreview(this.isPrintPreview_); this.zoomToolbar_.addEventListener( - 'fit-to-changed', this.fitToChanged_.bind(this)); - this.zoomToolbar_.addEventListener( - 'zoom-in', this.viewport_.zoomIn.bind(this.viewport_)); + 'fit-to-changed', e => this.fitToChanged_(e)); + this.zoomToolbar_.addEventListener('zoom-in', () => this.viewport_.zoomIn()); this.zoomToolbar_.addEventListener( - 'zoom-out', this.viewport_.zoomOut.bind(this.viewport_)); + 'zoom-out', () => this.viewport_.zoomOut()); this.gestureDetector_ = new GestureDetector($('content')); this.gestureDetector_.addEventListener( - 'pinchstart', this.onPinchStart_.bind(this)); + 'pinchstart', e => this.onPinchStart_(e)); this.sentPinchEvent_ = false; this.gestureDetector_.addEventListener( - 'pinchupdate', this.onPinchUpdate_.bind(this)); - this.gestureDetector_.addEventListener( - 'pinchend', this.onPinchEnd_.bind(this)); + 'pinchupdate', e => this.onPinchUpdate_(e)); + this.gestureDetector_.addEventListener('pinchend', e => this.onPinchEnd_(e)); if (toolbarEnabled) { this.toolbar_ = $('toolbar'); @@ -293,8 +293,8 @@ function PDFViewer(browserApi) { document.body.addEventListener('navigate', e => { const disposition = e.detail.newtab ? - Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB : - Navigator.WindowOpenDisposition.CURRENT_TAB; + PdfNavigator.WindowOpenDisposition.NEW_BACKGROUND_TAB : + PdfNavigator.WindowOpenDisposition.CURRENT_TAB; this.navigator_.navigate(e.detail.uri, disposition); }); @@ -309,33 +309,34 @@ function PDFViewer(browserApi) { // Set up the ZoomManager. this.zoomManager_ = ZoomManager.create( - this.browserApi_.getZoomBehavior(), this.viewport_, - this.browserApi_.setZoom.bind(this.browserApi_), + this.browserApi_.getZoomBehavior(), () => this.viewport_.getZoom(), + zoom => this.browserApi_.setZoom(zoom), this.browserApi_.getInitialZoom()); - this.viewport_.zoomManager = this.zoomManager_; + this.viewport_.setZoomManager(this.zoomManager_); this.browserApi_.addZoomEventListener( - this.zoomManager_.onBrowserZoomChange.bind(this.zoomManager_)); + zoom => this.zoomManager_.onBrowserZoomChange(zoom)); // Setup the keyboard event listener. - document.addEventListener('keydown', this.handleKeyEvent_.bind(this)); - document.addEventListener('mousemove', this.handleMouseEvent_.bind(this)); - document.addEventListener('mouseout', this.handleMouseEvent_.bind(this)); + document.addEventListener('keydown', e => this.handleKeyEvent_(e)); + document.addEventListener('mousemove', e => this.handleMouseEvent_(e)); + document.addEventListener('mouseout', e => this.handleMouseEvent_(e)); document.addEventListener( - 'contextmenu', this.handleContextMenuEvent_.bind(this)); + 'contextmenu', e => this.handleContextMenuEvent_(e)); const tabId = this.browserApi_.getStreamInfo().tabId; - this.navigator_ = new Navigator( + this.navigator_ = new PdfNavigator( this.originalUrl_, this.viewport_, this.paramsParser_, new NavigatorDelegate(tabId)); this.viewportScroller_ = new ViewportScroller(this.viewport_, this.plugin_, window); // Request translated strings. - chrome.resourcesPrivate.getStrings('pdf', this.handleStrings_.bind(this)); + chrome.resourcesPrivate.getStrings( + 'pdf', strings => this.handleStrings_(strings)); // Listen for save commands from the browser. if (chrome.mimeHandlerPrivate && chrome.mimeHandlerPrivate.onSave) { - chrome.mimeHandlerPrivate.onSave.addListener(this.onSave.bind(this)); + chrome.mimeHandlerPrivate.onSave.addListener(url => this.onSave(url)); } } @@ -361,7 +362,7 @@ PDFViewer.prototype = { const pageUpHandler = () => { // Go to the previous page if we are fit-to-page or fit-to-height. if (this.viewport_.isPagedMode()) { - this.viewport_.goToPage(this.viewport_.getMostVisiblePage() - 1); + this.viewport_.goToPreviousPage(); // Since we do the movement of the page. e.preventDefault(); } else if (fromScriptingAPI) { @@ -372,7 +373,7 @@ PDFViewer.prototype = { const pageDownHandler = () => { // Go to the next page if we are fit-to-page or fit-to-height. if (this.viewport_.isPagedMode()) { - this.viewport_.goToPage(this.viewport_.getMostVisiblePage() + 1); + this.viewport_.goToNextPage(); // Since we do the movement of the page. e.preventDefault(); } else if (fromScriptingAPI) { @@ -410,7 +411,7 @@ PDFViewer.prototype = { // no form field is focused. if (!(this.viewport_.documentHasScrollbars().horizontal || this.isFormFieldFocused_)) { - this.viewport_.goToPage(this.viewport_.getMostVisiblePage() - 1); + this.viewport_.goToPreviousPage(); // Since we do the movement of the page. e.preventDefault(); } else if (fromScriptingAPI) { @@ -431,7 +432,7 @@ PDFViewer.prototype = { // form field is focused. if (!(this.viewport_.documentHasScrollbars().horizontal || this.isFormFieldFocused_)) { - this.viewport_.goToPage(this.viewport_.getMostVisiblePage() + 1); + this.viewport_.goToNextPage(); // Since we do the movement of the page. e.preventDefault(); } else if (fromScriptingAPI) { @@ -558,7 +559,7 @@ PDFViewer.prototype = { const result = await this.inkController_.save(true); await this.pluginController_.load(result.fileName, result.dataToSave); // Ensure the plugin gets the initial viewport. - this.viewport_.setZoom(this.viewport_.zoom); + this.pluginController_.afterZoom(); } }, @@ -641,7 +642,8 @@ PDFViewer.prototype = { this.isUserInitiatedEvent_ = false; this.zoomToolbar_.forceFit(params.view); if (params.viewPosition) { - const zoomedPositionShift = params.viewPosition * this.viewport_.zoom; + const zoomedPositionShift = + params.viewPosition * this.viewport_.getZoom(); const currentViewportPosition = this.viewport_.position; if (params.view == FittingType.FIT_TO_WIDTH) { currentViewportPosition.y += zoomedPositionShift; @@ -730,7 +732,7 @@ PDFViewer.prototype = { this.viewport_.position = this.lastViewportPosition_; } this.paramsParser_.getViewportFromUrlParams( - this.originalUrl_, this.handleURLParams_.bind(this)); + this.originalUrl_, params => this.handleURLParams_(params)); this.setLoadState_(LoadState.SUCCESS); this.sendDocumentLoadedMessage_(); while (this.delayedScriptingMessages_.length > 0) { @@ -1141,7 +1143,8 @@ PDFViewer.prototype = { handleNavigate: function(url, disposition) { // If in print preview, always open a new tab. if (this.isPrintPreview_) { - this.navigator_.navigate(url, Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB); + this.navigator_.navigate( + url, PdfNavigator.WindowOpenDisposition.NEW_BACKGROUND_TAB); } else { this.navigator_.navigate(url, disposition); } @@ -1306,7 +1309,7 @@ PDFViewer.prototype = { setAnnotationUndoState(state) { this.toolbar_.canUndoAnnotation = state.canUndo; this.toolbar_.canRedoAnnotation = state.canRedo; - } + }, }; /** @abstract */ @@ -1483,7 +1486,7 @@ class PluginController extends ContentController { if (this.viewport_.pinchPhase == Viewport.PinchPhase.PINCH_START) { const position = this.viewport_.position; - const zoom = this.viewport_.zoom; + const zoom = this.viewport_.getZoom(); const pinchPhase = this.viewport_.pinchPhase; this.postMessage({ type: 'viewport', @@ -1503,7 +1506,7 @@ class PluginController extends ContentController { */ afterZoom() { const position = this.viewport_.position; - const zoom = this.viewport_.zoom; + const zoom = this.viewport_.getZoom(); const pinchVector = this.viewport_.pinchPanVector || {x: 0, y: 0}; const pinchCenter = this.viewport_.pinchCenter || {x: 0, y: 0}; const pinchPhase = this.viewport_.pinchPhase; diff --git a/chromium/chrome/browser/resources/pdf/viewport.js b/chromium/chrome/browser/resources/pdf/viewport.js index 02664b3fe33..480664c014c 100644 --- a/chromium/chrome/browser/resources/pdf/viewport.js +++ b/chromium/chrome/browser/resources/pdf/viewport.js @@ -2,10 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/** + * @typedef {{ + * width: number, + * height: number, + * pageDimensions: Array<ViewportRect>, + * }} + */ +let DocumentDimensions; + +/** @typedef {{x: number, y: number}} */ +let Point; + +/** @typedef {{width: number, height: number}} */ +let Size; + +/** @typedef {{x: number, y: number, width: number, height: number}} */ +let ViewportRect; /** * Clamps the zoom factor (or page scale factor) to be within the limits. - * * @param {number} factor The zoom/scale factor. * @return {number} The factor clamped within the limits. */ @@ -16,30 +32,36 @@ function clampZoom(factor) { } /** - * Returns the height of the intersection of two rectangles. - * - * @param {!ViewportRect} rect1 the first rect - * @param {!ViewportRect} rect2 the second rect - * @return {number} the height of the intersection of the rects + * @param {!ViewportRect} rect1 + * @param {!ViewportRect} rect2 + * @return {number} The area of the intersection of the rects */ -function getIntersectionHeight(rect1, rect2) { - return Math.max( - 0, - Math.min(rect1.y + rect1.height, rect2.y + rect2.height) - - Math.max(rect1.y, rect2.y)); +function getIntersectionArea(rect1, rect2) { + const left = Math.max(rect1.x, rect2.x); + const top = Math.max(rect1.y, rect2.y); + const right = Math.min(rect1.x + rect1.width, rect2.x + rect2.width); + const bottom = Math.min(rect1.y + rect1.height, rect2.y + rect2.height); + + if (left >= right || top >= bottom) { + return 0; + } + + return (right - left) * (bottom - top); } /** - * Computes vector between two points. - * - * @param {!Point} p1 The first point. - * @param {!Point} p2 The second point. - * @return {!Point} The vector. + * @param {!Point} p1 + * @param {!Point} p2 + * @return {!Point} The vector between the two points. */ function vectorDelta(p1, p2) { return {x: p2.x - p1.x, y: p2.y - p1.y}; } +/** + * @param {!Point} coordinateInFrame + * @return {!Point} Coordinate converted to plugin coordinates. + */ function frameToPluginCoordinate(coordinateInFrame) { const container = $('plugin'); return { @@ -48,83 +70,149 @@ function frameToPluginCoordinate(coordinateInFrame) { }; } -/** @implements {Viewport} */ -class ViewportImpl { +class Viewport { /** - * Create a new viewport. - * - * @param {Window} window the window - * @param {Object} sizer is the element which represents the size of the + * @param {!Window} window + * @param {!HTMLDivElement} sizer The element which represents the size of the * document in the viewport - * @param {Function} viewportChangedCallback is run when the viewport changes - * @param {Function} beforeZoomCallback is run before a change in zoom - * @param {Function} afterZoomCallback is run after a change in zoom - * @param {Function} setUserInitiatedCallback is run to indicate whether a - * zoom event is user initiated. - * @param {number} scrollbarWidth the width of scrollbars on the page + * @param {number} scrollbarWidth The width of scrollbars on the page * @param {number} defaultZoom The default zoom level. * @param {number} topToolbarHeight The number of pixels that should initially * be left blank above the document for the toolbar. */ - constructor( - window, sizer, viewportChangedCallback, beforeZoomCallback, - afterZoomCallback, setUserInitiatedCallback, scrollbarWidth, defaultZoom, - topToolbarHeight) { + constructor(window, sizer, scrollbarWidth, defaultZoom, topToolbarHeight) { + /** @private {!Window} */ this.window_ = window; + + /** @private {!HTMLDivElement} */ this.sizer_ = sizer; - this.viewportChangedCallback_ = viewportChangedCallback; - this.beforeZoomCallback_ = beforeZoomCallback; - this.afterZoomCallback_ = afterZoomCallback; - this.setUserInitiatedCallback_ = setUserInitiatedCallback; + + /** @private {number} */ + this.scrollbarWidth_ = scrollbarWidth; + + /** @private {number} */ + this.defaultZoom_ = defaultZoom; + + /** @private {number} */ + this.topToolbarHeight_ = topToolbarHeight; + + /** @private {function():void} */ + this.viewportChangedCallback_ = function() {}; + + /** @private {function():void} */ + this.beforeZoomCallback_ = function() {}; + + /** @private {function():void} */ + this.afterZoomCallback_ = function() {}; + + /** @private {function(boolean):void} */ + this.userInitiatedCallback_ = function() {}; + + /** @private {boolean} */ this.allowedToChangeZoom_ = false; + + /** @private {number} */ this.internalZoom_ = 1; - this.zoomManager_ = new InactiveZoomManager(this, 1); + + /** @private {?ZoomManager} */ + this.zoomManager_ = null; + /** @private {?DocumentDimensions} */ this.documentDimensions_ = null; + /** @private {Array<ViewportRect>} */ this.pageDimensions_ = []; - this.scrollbarWidth_ = scrollbarWidth; + + /** @private {!FittingType} */ this.fittingType_ = FittingType.NONE; - this.defaultZoom_ = defaultZoom; - this.topToolbarHeight_ = topToolbarHeight; + + /** + * |twoUpView_| should be in sync with |two_up_view_| in PDFiumEngine. + * @private {boolean} + */ + this.twoUpView_ = false; + + /** @private {number} */ this.prevScale_ = 1; + + /** @private {!Viewport.PinchPhase} */ this.pinchPhase_ = Viewport.PinchPhase.PINCH_NONE; + + /** @private {?Point} */ this.pinchPanVector_ = null; + + /** @private {?Point} */ this.pinchCenter_ = null; + /** @private {?Point} */ this.firstPinchCenterInFrame_ = null; + + /** @private {number} */ this.rotations_ = 0; - // TODO(dstockwell): why isn't this private? - this.oldCenterInContent = null; - this.keepContentCentered_ = null; + + /** @private {?Point} */ + this.oldCenterInContent_ = null; + + /** @private {boolean} */ + this.keepContentCentered_ = false; + + /** @private {!EventTracker} */ + this.tracker_ = new EventTracker(); + + // Set to a default zoom manager - used in tests. + this.setZoomManager(new InactiveZoomManager(this.getZoom.bind(this), 1)); window.addEventListener('scroll', this.updateViewport_.bind(this)); window.addEventListener('resize', this.resizeWrapper_.bind(this)); } + /** @param {function():void} viewportChangedCallback */ + setViewportChangedCallback(viewportChangedCallback) { + this.viewportChangedCallback_ = viewportChangedCallback; + } + + /** @param {function():void} beforeZoomCallback */ + setBeforeZoomCallback(beforeZoomCallback) { + this.beforeZoomCallback_ = beforeZoomCallback; + } + + /** @param {function():void} afterZoomCallback */ + setAfterZoomCallback(afterZoomCallback) { + this.afterZoomCallback_ = afterZoomCallback; + } + + /** @param {function(boolean):void} userInitiatedCallback */ + setUserInitiatedCallback(userInitiatedCallback) { + this.userInitiatedCallback_ = userInitiatedCallback; + } + /** - * @param {number} n the number of clockwise 90-degree rotations to - * increment by. + * @param {number} n The number of clockwise 90-degree rotations to increment + * by. */ rotateClockwise(n) { this.rotations_ = (this.rotations_ + n) % 4; } /** - * @return {number} the number of clockwise 90-degree rotations that have been + * @return {number} The number of clockwise 90-degree rotations that have been * applied. */ getClockwiseRotations() { return this.rotations_; } + /** @param {boolean} twoUpView The new two up view state to set. */ + setTwoUpView(twoUpView) { + this.twoUpView_ = twoUpView; + } + /** * Converts a page position (e.g. the location of a bookmark) to a screen * position. - * * @param {number} page - * @param {Point} point The position on `page`. - * @return The screen position. + * @param {!Point} point The position on `page`. + * @return {!Point} The screen position. */ convertPageToScreen(page, point) { const dimensions = this.getPageInsetDimensions(page); @@ -168,9 +256,8 @@ class ViewportImpl { * Rounding is necessary when interacting with the renderer which tends to * operate in integral values (for example for determining if scrollbars * should be shown). - * * @param {number} zoom The zoom to use to compute the scaled dimensions. - * @return {Object} A dictionary with scaled 'width'/'height' of the document. + * @return {?Size} Scaled 'width' and 'height' of the document. * @private */ getZoomedDocumentDimensions_(zoom) { @@ -183,7 +270,7 @@ class ViewportImpl { }; } - /** @override */ + /** @return {!Size} A dictionary with the 'width'/'height' of the document. */ getDocumentDimensions() { return { width: this.documentDimensions_.width, @@ -192,8 +279,22 @@ class ViewportImpl { } /** - * @param {number} zoom compute whether scrollbars are needed at this zoom - * @return {{horizontal: boolean, vertical: boolean}} whether horizontal or + * @return {!ViewportRect} ViewportRect for the viewport given current zoom. + * @private + */ + getViewportRect_() { + const zoom = this.getZoom(); + return { + x: this.position.x / zoom, + y: this.position.y / zoom, + width: this.size.width / zoom, + height: this.size.height / zoom + }; + } + + /** + * @param {number} zoom Zoom to compute scrollbars for + * @return {{horizontal: boolean, vertical: boolean}} Whether horizontal or * vertical scrollbars are needed. * @private */ @@ -219,23 +320,20 @@ class ViewportImpl { } /** - * Returns true if the document needs scrollbars at the current zoom level. - * - * @return {Object} with 'x' and 'y' keys which map to bool values - * indicating if the horizontal and vertical scrollbars are needed - * respectively. + * @return {!{horizontal: boolean, vertical: boolean}} Whether horizontal and + * vertical scrollbars are needed. */ documentHasScrollbars() { - return this.documentNeedsScrollbars_(this.zoom); + return this.documentNeedsScrollbars_(this.getZoom()); } /** - * Helper function called when the zoomed document size changes. - * + * Helper function called when the zoomed document size changes. Updates the + * sizer's width and height. * @private */ contentSizeChanged_() { - const zoomedDimensions = this.getZoomedDocumentDimensions_(this.zoom); + const zoomedDimensions = this.getZoomedDocumentDimensions_(this.getZoom()); if (zoomedDimensions) { this.sizer_.style.width = zoomedDimensions.width + 'px'; this.sizer_.style.height = @@ -245,7 +343,6 @@ class ViewportImpl { /** * Called when the viewport should be updated. - * * @private */ updateViewport_() { @@ -254,18 +351,16 @@ class ViewportImpl { /** * Called when the browser window size changes. - * * @private */ resizeWrapper_() { - this.setUserInitiatedCallback_(false); + this.userInitiatedCallback_(false); this.resize_(); - this.setUserInitiatedCallback_(true); + this.userInitiatedCallback_(true); } /** * Called when the viewport size changes. - * * @private */ resize_() { @@ -282,7 +377,7 @@ class ViewportImpl { } } - /** @override */ + /** @return {!Point} The scroll position of the viewport. */ get position() { return { x: this.window_.pageXOffset, @@ -292,16 +387,15 @@ class ViewportImpl { /** * Scroll the viewport to the specified position. - * - * @param {Point} position The position to scroll to. + * @param {!Point} position The position to scroll to. */ set position(position) { this.window_.scrollTo(position.x, position.y + this.topToolbarHeight_); } - /** @override */ + /** @return {!Size} the size of the viewport excluding scrollbars. */ get size() { - const needsScrollbars = this.documentNeedsScrollbars_(this.zoom); + const needsScrollbars = this.documentNeedsScrollbars_(this.getZoom()); const scrollbarWidth = needsScrollbars.vertical ? this.scrollbarWidth_ : 0; const scrollbarHeight = needsScrollbars.horizontal ? this.scrollbarWidth_ : 0; @@ -311,22 +405,25 @@ class ViewportImpl { }; } - /** @override */ - get zoom() { + /** @return {number} The current zoom. */ + getZoom() { return this.zoomManager_.applyBrowserZoom(this.internalZoom_); } - /** - * Set the zoom manager. - * - * @type {ZoomManager} manager the zoom manager to set. - */ - set zoomManager(manager) { + /** @param {!ZoomManager} manager */ + setZoomManager(manager) { + this.resetTracker(); this.zoomManager_ = manager; + this.tracker_.add( + this.zoomManager_.getEventTarget(), 'set-zoom', + e => this.setZoom(e.detail)); + this.tracker_.add( + this.zoomManager_.getEventTarget(), 'update-zoom-from-browser', + this.updateZoomFromBrowserChange_.bind(this)); } /** - * @return {Viewport.PinchPhase} The phase of the current pinch gesture for + * @return {!Viewport.PinchPhase} The phase of the current pinch gesture for * the viewport. */ get pinchPhase() { @@ -334,7 +431,7 @@ class ViewportImpl { } /** - * @return {Object} The panning caused by the current pinch gesture (as + * @return {?Point} The panning caused by the current pinch gesture (as * the deltas of the x and y coordinates). */ get pinchPanVector() { @@ -342,7 +439,7 @@ class ViewportImpl { } /** - * @return {Object} The coordinates of the center of the current pinch + * @return {?Point} The coordinates of the center of the current pinch * gesture. */ get pinchCenter() { @@ -354,8 +451,7 @@ class ViewportImpl { * required so that we can notify the plugin that zooming is in progress * so that while zooming is taking place it can stop reacting to scroll events * from the viewport. This is to avoid flickering. - * - * @param {Function} f Function to wrap + * @param {function():void} f Function to wrap * @private */ mightZoom_(f) { @@ -364,12 +460,11 @@ class ViewportImpl { f(); this.allowedToChangeZoom_ = false; this.afterZoomCallback_(); + this.zoomManager_.onPdfZoomChange(); } /** - * Sets the zoom of the viewport. - * - * @param {number} newZoom the zoom level to zoom to. + * @param {number} newZoom The zoom level to set. * @private */ setZoomInternal_(newZoom) { @@ -378,26 +473,27 @@ class ViewportImpl { 'Called Viewport.setZoomInternal_ without calling ' + 'Viewport.mightZoom_.'); // Record the scroll position (relative to the top-left of the window). + let zoom = this.getZoom(); const currentScrollPos = { - x: this.position.x / this.zoom, - y: this.position.y / this.zoom + x: this.position.x / zoom, + y: this.position.y / zoom }; this.internalZoom_ = newZoom; this.contentSizeChanged_(); // Scroll to the scaled scroll position. + zoom = this.getZoom(); this.position = { - x: currentScrollPos.x * this.zoom, - y: currentScrollPos.y * this.zoom + x: currentScrollPos.x * zoom, + y: currentScrollPos.y * zoom }; } /** * Sets the zoom of the viewport. * Same as setZoomInternal_ but for pinch zoom we have some more operations. - * * @param {number} scaleDelta The zoom delta. - * @param {!Object} center The pinch center in content coordinates. + * @param {!Point} center The pinch center in content coordinates. * @private */ setPinchZoomInternal_(scaleDelta, center) { @@ -407,16 +503,17 @@ class ViewportImpl { 'Viewport.mightZoom_.'); this.internalZoom_ = clampZoom(this.internalZoom_ * scaleDelta); - const newCenterInContent = this.frameToContent(center); + const newCenterInContent = this.frameToContent_(center); const delta = { - x: (newCenterInContent.x - this.oldCenterInContent.x), - y: (newCenterInContent.y - this.oldCenterInContent.y) + x: (newCenterInContent.x - this.oldCenterInContent_.x), + y: (newCenterInContent.y - this.oldCenterInContent_.y) }; // Record the scroll position (relative to the pinch center). + const zoom = this.getZoom(); const currentScrollPos = { - x: this.position.x - delta.x * this.zoom, - y: this.position.y - delta.y * this.zoom + x: this.position.x - delta.x * zoom, + y: this.position.y - delta.y * zoom }; this.contentSizeChanged_(); @@ -426,24 +523,22 @@ class ViewportImpl { /** * Converts a point from frame to content coordinates. - * - * @param {!Object} framePoint The frame coordinates. - * @return {!Object} The content coordinates. + * @param {!Point} framePoint The frame coordinates. + * @return {!Point} The content coordinates. * @private */ - frameToContent(framePoint) { + frameToContent_(framePoint) { // TODO(mcnee) Add a helper Point class to avoid duplicating operations // on plain {x,y} objects. + const zoom = this.getZoom(); return { - x: (framePoint.x + this.position.x) / this.zoom, - y: (framePoint.y + this.position.y) / this.zoom + x: (framePoint.x + this.position.x) / zoom, + y: (framePoint.y + this.position.y) / zoom }; } /** - * Sets the zoom to the given zoom level. - * - * @param {number} newZoom the zoom level to zoom to. + * @param {number} newZoom The zoom level to zoom to. */ setZoom(newZoom) { this.fittingType_ = FittingType.NONE; @@ -453,8 +548,12 @@ class ViewportImpl { }); } - /** @override */ - updateZoomFromBrowserChange(oldBrowserZoom) { + /** + * @param {!CustomEvent<number>} e Event containing the old browser zoom. + * @private + */ + updateZoomFromBrowserChange_(e) { + const oldBrowserZoom = e.detail; this.mightZoom_(() => { // Record the scroll position (relative to the top-left of the window). const oldZoom = oldBrowserZoom * this.internalZoom_; @@ -463,34 +562,32 @@ class ViewportImpl { y: this.position.y / oldZoom }; this.contentSizeChanged_(); + const newZoom = this.getZoom(); // Scroll to the scaled scroll position. this.position = { - x: currentScrollPos.x * this.zoom, - y: currentScrollPos.y * this.zoom + x: currentScrollPos.x * newZoom, + y: currentScrollPos.y * newZoom }; this.updateViewport_(); }); } - /** - * @return {number} the width of scrollbars in the viewport in pixels. - */ + /** @return {number} The width of scrollbars in the viewport in pixels. */ get scrollbarWidth() { return this.scrollbarWidth_; } - /** - * @return {FittingType} the fitting type the viewport is currently in. - */ + /** @return {FittingType} The fitting type the viewport is currently in. */ get fittingType() { return this.fittingType_; } /** - * Get the which page is at a given y position. - * - * @param {number} y the y-coordinate to get the page at. - * @return {number} the index of a page overlapping the given y-coordinate. + * Get the page at a given y position. If there are multiple pages + * overlapping the given y-coordinate, return the page with the smallest + * index. + * @param {number} y The y-coordinate to get the page at. + * @return {number} The index of a page overlapping the given y-coordinate. * @private */ getPageAtY_(y) { @@ -521,9 +618,32 @@ class ViewportImpl { return 0; } - /** @override */ + /** + * Return the last page visible in the viewport. Returns the last index of the + * document if the viewport is below the document. + * @param {!ViewportRect} viewportRect + * @return {number} The highest index of the pages visible in the viewport. + * @private + */ + getLastPageInViewport_(viewportRect) { + const pageAtY = this.getPageAtY_(viewportRect.y + viewportRect.height); + + if (!this.twoUpView_ || pageAtY % 2 == 1 || + pageAtY + 1 >= this.pageDimensions_.length) { + return pageAtY; + } + + const nextPage = this.pageDimensions_[pageAtY + 1]; + return getIntersectionArea(viewportRect, nextPage) > 0 ? pageAtY + 1 : + pageAtY; + } + + /** + * @param {!Point} point + * @return {boolean} Whether |point| (in screen coordinates) is inside a page + */ isPointInsidePage(point) { - const zoom = this.zoom; + const zoom = this.getZoom(); const size = this.size; const position = this.position; const page = this.getPageAtY_((position.y + point.y) / zoom); @@ -544,48 +664,51 @@ class ViewportImpl { } /** - * Returns the page with the greatest proportion of its height in the current - * viewport. - * - * @return {number} the index of the most visible page. + * @return {number} The index of the page with the greatest proportion of its + * area in the current viewport. */ getMostVisiblePage() { - const firstVisiblePage = this.getPageAtY_(this.position.y / this.zoom); - if (firstVisiblePage == this.pageDimensions_.length - 1) { + const viewportRect = this.getViewportRect_(); + + const firstVisiblePage = this.getPageAtY_(viewportRect.y); + const lastPossibleVisiblePage = this.getLastPageInViewport_(viewportRect); + if (firstVisiblePage === lastPossibleVisiblePage) { return firstVisiblePage; } - const viewportRect = { - x: this.position.x / this.zoom, - y: this.position.y / this.zoom, - width: this.size.width / this.zoom, - height: this.size.height / this.zoom - }; - const firstVisiblePageVisibility = - getIntersectionHeight( - this.pageDimensions_[firstVisiblePage], viewportRect) / - this.pageDimensions_[firstVisiblePage].height; - const nextPageVisibility = - getIntersectionHeight( - this.pageDimensions_[firstVisiblePage + 1], viewportRect) / - this.pageDimensions_[firstVisiblePage + 1].height; - if (nextPageVisibility > firstVisiblePageVisibility) { - return firstVisiblePage + 1; + let mostVisiblePage = firstVisiblePage; + let largestIntersection = 0; + + for (let i = firstVisiblePage; i < lastPossibleVisiblePage + 1; i++) { + const pageArea = + this.pageDimensions_[i].width * this.pageDimensions_[i].height; + + // TODO(thestig): check whether we can remove this check. + if (pageArea <= 0) { + continue; + } + + const pageIntersectionArea = + getIntersectionArea(this.pageDimensions_[i], viewportRect) / pageArea; + + if (pageIntersectionArea > largestIntersection) { + mostVisiblePage = i; + largestIntersection = pageIntersectionArea; + } } - return firstVisiblePage; + + return mostVisiblePage; } /** * Compute the zoom level for fit-to-page, fit-to-width or fit-to-height. - * * At least one of {fitWidth, fitHeight} must be true. - * - * @param {Object} pageDimensions the dimensions of a given page in px. - * @param {boolean} fitWidth a bool indicating whether the whole width of the - * page needs to be in the viewport. - * @param {boolean} fitHeight a bool indicating whether the whole height of - * the page needs to be in the viewport. - * @return {number} the internal zoom to set + * @param {!Size} pageDimensions The dimensions of a given page in px. + * @param {boolean} fitWidth Whether the whole width of the page needs to be + * in the viewport. + * @param {boolean} fitHeight Whether the whole height of the page needs to be + * in the viewport. + * @return {number} The internal zoom to set * @private */ computeFittingZoom_(pageDimensions, fitWidth, fitHeight) { @@ -644,16 +767,15 @@ class ViewportImpl { /** * Compute a zoom level given the dimensions to fit and the actual numbers * in those dimensions. - * - * @param {boolean} fitWidth make sure the page width is totally contained in - * the window. - * @param {boolean} fitHeight make sure the page height is totally contained - * in the window. - * @param {number} windowWidth the width of the window in px. - * @param {number} windowHeight the height of the window in px. - * @param {number} pageWidth the width of the page in px. - * @param {number} pageHeight the height of the page in px. - * @return {number} the internal zoom to set + * @param {boolean} fitWidth Whether to constrain the page width to the + * window. + * @param {boolean} fitHeight Whether to constrain the page height to the + * window. + * @param {number} windowWidth Width of the window in px. + * @param {number} windowHeight Height of the window in px. + * @param {number} pageWidth Width of the page in px. + * @param {number} pageHeight Height of the page in px. + * @return {number} The internal zoom to set * @private */ computeFittingZoomGivenDimensions_( @@ -683,9 +805,7 @@ class ViewportImpl { return Math.max(zoom, 0); } - /** - * Zoom the viewport so that the page width consumes the entire viewport. - */ + /** Zoom the viewport so that the page width consumes the entire viewport. */ fitToWidth() { this.mightZoom_(() => { this.fittingType_ = FittingType.FIT_TO_WIDTH; @@ -702,7 +822,6 @@ class ViewportImpl { /** * Zoom the viewport so that the page height consumes the entire viewport. - * * @param {boolean} scrollToTopOfPage Set to true if the viewport should be * scrolled to the top of the current page. Set to false if the viewport * should remain at the current scroll position. @@ -723,25 +842,25 @@ class ViewportImpl { }; this.setZoomInternal_(this.computeFittingZoom_(dimensions, false, true)); if (scrollToTopOfPage) { - this.position = {x: 0, y: this.pageDimensions_[page].y * this.zoom}; + this.position = { + x: 0, + y: this.pageDimensions_[page].y * this.getZoom() + }; } this.updateViewport_(); }); } - /** - * Zoom the viewport so that the page height consumes the entire viewport. - */ + /** Zoom the viewport so that the page height consumes the entire viewport. */ fitToHeight() { this.fitToHeightInternal_(true); } /** * Zoom the viewport so that a page consumes as much as possible of the it. - * - * @param {boolean} scrollToTopOfPage Set to true if the viewport should be - * scrolled to the top of the current page. Set to false if the viewport - * should remain at the current scroll position. + * @param {boolean} scrollToTopOfPage Whether the viewport should be scrolled + * to the top of the current page. If false, the viewport will remain at + * the current scroll position. * @private */ fitToPageInternal_(scrollToTopOfPage) { @@ -758,7 +877,10 @@ class ViewportImpl { }; this.setZoomInternal_(this.computeFittingZoom_(dimensions, true, true)); if (scrollToTopOfPage) { - this.position = {x: 0, y: this.pageDimensions_[page].y * this.zoom}; + this.position = { + x: 0, + y: this.pageDimensions_[page].y * this.getZoom() + }; } this.updateViewport_(); }); @@ -772,9 +894,7 @@ class ViewportImpl { this.fitToPageInternal_(true); } - /** - * Zoom the viewport to the default zoom policy. - */ + /** Zoom the viewport to the default zoom. */ fitToNone() { this.mightZoom_(() => { this.fittingType_ = FittingType.NONE; @@ -788,9 +908,7 @@ class ViewportImpl { }); } - /** - * Zoom out to the next predefined zoom level. - */ + /** Zoom out to the next predefined zoom level. */ zoomOut() { this.mightZoom_(() => { this.fittingType_ = FittingType.NONE; @@ -805,9 +923,7 @@ class ViewportImpl { }); } - /** - * Zoom in to the next predefined zoom level. - */ + /** Zoom in to the next predefined zoom level. */ zoomIn() { this.mightZoom_(() => { this.fittingType_ = FittingType.NONE; @@ -824,7 +940,6 @@ class ViewportImpl { /** * Pinch zoom event handler. - * * @param {!Object} e The pinch event. */ pinchZoom(e) { @@ -857,8 +972,8 @@ class ViewportImpl { y: this.window_.innerHeight / 2 }; } else if (this.keepContentCentered_) { - this.oldCenterInContent = - this.frameToContent(frameToPluginCoordinate(e.center)); + this.oldCenterInContent_ = + this.frameToContent_(frameToPluginCoordinate(e.center)); this.keepContentCentered_ = false; } @@ -872,10 +987,10 @@ class ViewportImpl { pinchZoomStart(e) { this.pinchPhase_ = Viewport.PinchPhase.PINCH_START; this.prevScale_ = 1; - this.oldCenterInContent = - this.frameToContent(frameToPluginCoordinate(e.center)); + this.oldCenterInContent_ = + this.frameToContent_(frameToPluginCoordinate(e.center)); - const needsScrollbars = this.documentNeedsScrollbars_(this.zoom); + const needsScrollbars = this.documentNeedsScrollbars_(this.getZoom()); this.keepContentCentered_ = !needsScrollbars.horizontal; // We keep track of begining of the pinch. // By doing so we will be able to compute the pan distance. @@ -887,7 +1002,7 @@ class ViewportImpl { this.mightZoom_(() => { this.pinchPhase_ = Viewport.PinchPhase.PINCH_END; const scaleDelta = e.startScaleRatio / this.prevScale_; - this.pinchCenter_ = e.center; + this.pinchCenter_ = /** @type {!Point} */ (e.center); this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center)); this.updateViewport_(); @@ -900,8 +1015,32 @@ class ViewportImpl { } /** + * Go to the next page. If the document is in two-up view, go to the left page + * of the next row. + */ + goToNextPage() { + const currentPage = this.getMostVisiblePage(); + const nextPageOffset = (this.twoUpView_ && currentPage % 2 == 0) ? 2 : 1; + this.goToPage(currentPage + nextPageOffset); + } + + /** + * Go to the previous page. If the document is in two-up view, go to the left + * page of the previous row. + */ + goToPreviousPage() { + const currentPage = this.getMostVisiblePage(); + let previousPageOffset = -1; + + if (this.twoUpView_) { + previousPageOffset = (currentPage % 2 == 0) ? -2 : -3; + } + + this.goToPage(currentPage + previousPageOffset); + } + + /** * Go to the given page index. - * * @param {number} page the index of the page to go to. zero-based. */ goToPage(page) { @@ -910,7 +1049,6 @@ class ViewportImpl { /** * Go to the given y position in the given page index. - * * @param {number} page the index of the page to go to. zero-based. * @param {number} x the x position in the page to go to. * @param {number} y the y position in the page to go to. @@ -935,17 +1073,15 @@ class ViewportImpl { toolbarOffset = this.topToolbarHeight_; } this.position = { - x: (dimensions.x + x) * this.zoom, - y: (dimensions.y + y) * this.zoom - toolbarOffset + x: (dimensions.x + x) * this.getZoom(), + y: (dimensions.y + y) * this.getZoom() - toolbarOffset }; this.updateViewport_(); }); } /** - * Set the dimensions of the document. - * - * @param {DocumentDimensions} documentDimensions the dimensions of the + * @param {DocumentDimensions} documentDimensions The dimensions of the * document */ setDocumentDimensions(documentDimensions) { @@ -982,9 +1118,8 @@ class ViewportImpl { /** * Get the coordinates of the page contents (excluding the page shadow) * relative to the screen. - * - * @param {number} page the index of the page to get the rect for. - * @return {Object} a rect representing the page in screen coordinates. + * @param {number} page The index of the page to get the rect for. + * @return {!ViewportRect} A rect representing the page in screen coordinates. */ getPageScreenRect(page) { if (!this.documentDimensions_) { @@ -1006,24 +1141,23 @@ class ViewportImpl { Viewport.PAGE_SHADOW.left; // Compute the space on the left of the document if the document fits // completely in the screen. + const zoom = this.getZoom(); let spaceOnLeft = - (this.size.width - this.documentDimensions_.width * this.zoom) / 2; + (this.size.width - this.documentDimensions_.width * zoom) / 2; spaceOnLeft = Math.max(spaceOnLeft, 0); return { - x: x * this.zoom + spaceOnLeft - this.window_.pageXOffset, - y: insetDimensions.y * this.zoom - this.window_.pageYOffset, - width: insetDimensions.width * this.zoom, - height: insetDimensions.height * this.zoom + x: x * zoom + spaceOnLeft - this.window_.pageXOffset, + y: insetDimensions.y * zoom - this.window_.pageYOffset, + width: insetDimensions.width * zoom, + height: insetDimensions.height * zoom }; } /** * Check if the current fitting type is a paged mode. - * * In a paged mode, page up and page down scroll to the top of the * previous/next page and part of the page is under the toolbar. - * * @return {boolean} Whether the current fitting type is a paged mode. */ isPagedMode() { @@ -1032,11 +1166,7 @@ class ViewportImpl { this.fittingType_ == FittingType.FIT_TO_HEIGHT); } - /** - * Scroll the viewport to the specified position. - * - * @param {!Point} point The position to which to move the viewport. - */ + /** @param {!Point} point The position to which to scroll the viewport. */ scrollTo(point) { let changed = false; const newPosition = this.position; @@ -1054,15 +1184,64 @@ class ViewportImpl { } } - /** - * Scroll the viewport by the specified delta. - * - * @param {!Point} delta The delta by which to move the viewport. - */ + /** @param {!Point} delta The delta by which to scroll the viewport. */ scrollBy(delta) { const newPosition = this.position; newPosition.x += delta.x; newPosition.y += delta.y; this.scrollTo(newPosition); } + + /** Removes all events being tracked from the tracker. */ + resetTracker() { + if (this.tracker_) { + this.tracker_.removeAll(); + } + } } + +/** + * Enumeration of pinch states. + * This should match PinchPhase enum in pdf/out_of_process_instance.h + * @enum {number} + */ +Viewport.PinchPhase = { + PINCH_NONE: 0, + PINCH_START: 1, + PINCH_UPDATE_ZOOM_OUT: 2, + PINCH_UPDATE_ZOOM_IN: 3, + PINCH_END: 4 +}; + +/** + * The increment to scroll a page by in pixels when up/down/left/right arrow + * keys are pressed. Usually we just let the browser handle scrolling on the + * window when these keys are pressed but in certain cases we need to simulate + * these events. + */ +Viewport.SCROLL_INCREMENT = 40; + +/** + * Predefined zoom factors to be used when zooming in/out. These are in + * ascending order. This should match the lists in + * components/zoom/page_zoom_constants.h and + * chrome/browser/resources/settings/appearance_page/appearance_page.js + */ +Viewport.ZOOM_FACTORS = [ + 0.25, 1 / 3, 0.5, 2 / 3, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, + 4, 5 +]; + +/** The minimum and maximum range to be used to clip zoom factor. */ +Viewport.ZOOM_FACTOR_RANGE = { + min: Viewport.ZOOM_FACTORS[0], + max: Viewport.ZOOM_FACTORS[Viewport.ZOOM_FACTORS.length - 1] +}; + +/** The width of the page shadow around pages in pixels. */ +Viewport.PAGE_SHADOW = { + top: 3, + bottom: 7, + left: 5, + right: 5 +}; diff --git a/chromium/chrome/browser/resources/pdf/viewport_interface.js b/chromium/chrome/browser/resources/pdf/viewport_interface.js deleted file mode 100644 index c9f99aceb2f..00000000000 --- a/chromium/chrome/browser/resources/pdf/viewport_interface.js +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @typedef {{ - * width: number, - * height: number, - * pageDimensions: Array<ViewportRect>, - * }} - */ -let DocumentDimensions; - -/** - * @typedef {{ - * x: number, - * y: number - * }} - */ -let Point; - -/** - * @typedef {{ - * width: number, - * height: number, - * }} - */ -let Size; - -/** - * @typedef {{ - * x: number, - * y: number, - * width: number, - * height: number, - * }} - */ -let ViewportRect; - -/** - * @interface - */ -class Viewport { - /** - * Returns the document dimensions. - * - * @return {!Size} A dictionary with the 'width'/'height' of the document. - */ - getDocumentDimensions() {} - - /** - * @return {!Point} the scroll position of the viewport. - */ - get position() {} - - /** - * @return {!Size} the size of the viewport excluding scrollbars. - */ - get size() {} - - /** - * @return {number} the zoom level of the viewport. - */ - get zoom() {} - - /** - * Sets the zoom to the given zoom level. - * - * @param {number} newZoom the zoom level to zoom to. - */ - setZoom(newZoom) {} - - /** - * Gets notified of the browser zoom changing separately from the - * internal zoom. - * - * @param {number} oldBrowserZoom the previous value of the browser zoom. - */ - updateZoomFromBrowserChange(oldBrowserZoom) {} - - /** - * @param {!Point} point - * @return {boolean} Whether |point| (in screen coordinates) is inside a page - */ - isPointInsidePage(point) {} -} - -/** - * Enumeration of pinch states. - * This should match PinchPhase enum in pdf/out_of_process_instance.h - * @enum {number} - */ -Viewport.PinchPhase = { - PINCH_NONE: 0, - PINCH_START: 1, - PINCH_UPDATE_ZOOM_OUT: 2, - PINCH_UPDATE_ZOOM_IN: 3, - PINCH_END: 4 -}; - -/** - * The increment to scroll a page by in pixels when up/down/left/right arrow - * keys are pressed. Usually we just let the browser handle scrolling on the - * window when these keys are pressed but in certain cases we need to simulate - * these events. - */ -Viewport.SCROLL_INCREMENT = 40; - -/** - * Predefined zoom factors to be used when zooming in/out. These are in - * ascending order. This should match the lists in - * components/ui/zoom/page_zoom_constants.h and - * chrome/browser/resources/settings/appearance_page/appearance_page.js - */ -Viewport.ZOOM_FACTORS = [ - 0.25, 1 / 3, 0.5, 2 / 3, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, - 4, 5 -]; - -/** - * The minimum and maximum range to be used to clip zoom factor. - */ -Viewport.ZOOM_FACTOR_RANGE = { - min: Viewport.ZOOM_FACTORS[0], - max: Viewport.ZOOM_FACTORS[Viewport.ZOOM_FACTORS.length - 1] -}; - -/** - * The width of the page shadow around pages in pixels. - */ -Viewport.PAGE_SHADOW = { - top: 3, - bottom: 7, - left: 5, - right: 5 -}; diff --git a/chromium/chrome/browser/resources/pdf/zoom_manager.js b/chromium/chrome/browser/resources/pdf/zoom_manager.js index 6c3182d3fd1..db2878dd3d9 100644 --- a/chromium/chrome/browser/resources/pdf/zoom_manager.js +++ b/chromium/chrome/browser/resources/pdf/zoom_manager.js @@ -11,35 +11,50 @@ */ class ZoomManager { /** - * @param {!Viewport} viewport A Viewport for which to manage zoom. + * @param {function():number} getViewportZoom Callback to get the viewport's + * current zoom level. * @param {number} initialZoom The initial browser zoom level. */ - constructor(viewport, initialZoom) { + constructor(getViewportZoom, initialZoom) { if (this.constructor === ZoomManager) { throw new TypeError('Instantiated abstract class: ZoomManager'); } - this.viewport_ = viewport; + + /** @private {number} */ this.browserZoom_ = initialZoom; + + /** @private {function():number} */ + this.getViewportZoom_ = getViewportZoom; + + /** @private {!EventTarget} */ + this.eventTarget_ = new cr.EventTarget(); + } + + /** @return {!EventTarget} */ + getEventTarget() { + return this.eventTarget_; } /** * Creates the appropriate kind of zoom manager given the zoom behavior. * * @param {BrowserApi.ZoomBehavior} zoomBehavior How to manage zoom. - * @param {!Viewport} viewport A Viewport for which to manage zoom. - * @param {Function} setBrowserZoomFunction A function that sets the browser - * zoom to the provided value. + * @param {function():number} getViewportZoom A function that gets the current + * viewport zoom. + * @param {function(number):Promise} setBrowserZoomFunction A function that + * sets the browser zoom to the provided value. * @param {number} initialZoom The initial browser zoom level. */ - static create(zoomBehavior, viewport, setBrowserZoomFunction, initialZoom) { + static create( + zoomBehavior, getViewportZoom, setBrowserZoomFunction, initialZoom) { switch (zoomBehavior) { case BrowserApi.ZoomBehavior.MANAGE: return new ActiveZoomManager( - viewport, setBrowserZoomFunction, initialZoom); + getViewportZoom, setBrowserZoomFunction, initialZoom); case BrowserApi.ZoomBehavior.PROPAGATE_PARENT: - return new EmbeddedZoomManager(viewport, initialZoom); + return new EmbeddedZoomManager(getViewportZoom, initialZoom); default: - return new InactiveZoomManager(viewport, initialZoom); + return new InactiveZoomManager(getViewportZoom, initialZoom); } } @@ -104,15 +119,19 @@ class InactiveZoomManager extends ZoomManager {} class ActiveZoomManager extends ZoomManager { /** * Constructs a ActiveZoomManager. - * - * @param {!Viewport} viewport A Viewport for which to manage zoom. - * @param {Function} setBrowserZoomFunction A function that sets the browser - * zoom to the provided value. + * @param {function():number} getViewportZoom A function that gets the current + * viewport zoom level + * @param {function(number):Promise} setBrowserZoomFunction A function that + * sets the browser zoom to the provided value. * @param {number} initialZoom The initial browser zoom level. */ - constructor(viewport, setBrowserZoomFunction, initialZoom) { - super(viewport, initialZoom); + constructor(getViewportZoom, setBrowserZoomFunction, initialZoom) { + super(getViewportZoom, initialZoom); + + /** @private {function(number):Promise} */ this.setBrowserZoomFunction_ = setBrowserZoomFunction; + + /** @private {?Promise} */ this.changingBrowserZoom_ = null; } @@ -135,11 +154,13 @@ class ActiveZoomManager extends ZoomManager { } this.browserZoom_ = newZoom; - this.viewport_.setZoom(newZoom); + this.eventTarget_.dispatchEvent( + new CustomEvent('set-zoom', {detail: newZoom})); } /** * Invoked when an extension-initiated zoom-level change occurs. + * @override */ onPdfZoomChange() { // If we are already changing the browser zoom level in response to a @@ -150,20 +171,21 @@ class ActiveZoomManager extends ZoomManager { return; } - const zoom = this.viewport_.zoom; - if (this.floatingPointEquals(this.browserZoom_, zoom)) { + const viewportZoom = this.getViewportZoom_(); + if (this.floatingPointEquals(this.browserZoom_, viewportZoom)) { return; } - this.changingBrowserZoom_ = this.setBrowserZoomFunction_(zoom).then(() => { - this.browserZoom_ = zoom; - this.changingBrowserZoom_ = null; + this.changingBrowserZoom_ = + this.setBrowserZoomFunction_(viewportZoom).then(() => { + this.browserZoom_ = viewportZoom; + 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(); - }); + // 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(); + }); } /** @@ -206,6 +228,7 @@ class EmbeddedZoomManager extends ZoomManager { onBrowserZoomChange(newZoom) { const oldZoom = this.browserZoom_; this.browserZoom_ = newZoom; - this.viewport_.updateZoomFromBrowserChange(oldZoom); + this.eventTarget_.dispatchEvent( + new CustomEvent('update-zoom-from-browser', {detail: oldZoom})); } } diff --git a/chromium/chrome/browser/resources/policy/policy.css b/chromium/chrome/browser/resources/policy/policy.css index 67d7f688746..3f9e034434b 100644 --- a/chromium/chrome/browser/resources/policy/policy.css +++ b/chromium/chrome/browser/resources/policy/policy.css @@ -86,8 +86,9 @@ body > main { flex-grow: 1; max-height: 200px; overflow: auto; + overflow-wrap: break-word; text-overflow: unset; - white-space: pre; + white-space: pre-wrap; } <if expr="not is_android"> @@ -124,11 +125,11 @@ div.status-entry:last-child { } body > header { + align-items: center; padding: 12px; } -body > header, -.reload-show-unset-section { +.header-row { align-items: center; display: flex; height: 56px; @@ -219,4 +220,4 @@ body > main { display: block; flex: 1; } -</if>
\ No newline at end of file +</if> diff --git a/chromium/chrome/browser/resources/policy/policy.html b/chromium/chrome/browser/resources/policy/policy.html index b059bc46a4e..efcbbe51d73 100644 --- a/chromium/chrome/browser/resources/policy/policy.html +++ b/chromium/chrome/browser/resources/policy/policy.html @@ -18,13 +18,13 @@ <body> <header> - <h1>$i18n{title}</h1> - <input id="filter" class="search-field-container" type="search" - placeholder="$i18n{filterPlaceholder}" - aria-label="$i18n{filterPlaceholder}" incremental> - </header> - <main id="policy-ui"> - <section class="reload-show-unset-section"> + <div class="header-row"> + <h1>$i18n{title}</h1> + <input id="filter" class="search-field-container" type="search" + placeholder="$i18n{filterPlaceholder}" + aria-label="$i18n{filterPlaceholder}" incremental> + </div> + <div class="header-row"> <button id="reload-policies">$i18n{reloadPolicies}</button> <button id="export-policies">$i18n{exportPoliciesJSON}</button> <div id="show-unset-container" class="show-unset-checkbox"> @@ -33,7 +33,9 @@ <span>$i18n{showUnset}</span> </label> </div> - </section> + </div> + </header> + <main id="policy-ui"> <section id="status-section" class="status-box-section" hidden> <h3>$i18n{status}</h3> <div id="status-box-container"></div> diff --git a/chromium/chrome/browser/resources/print_preview/data/destination.js b/chromium/chrome/browser/resources/print_preview/data/destination.js index d037df020f5..403becbf6d1 100644 --- a/chromium/chrome/browser/resources/print_preview/data/destination.js +++ b/chromium/chrome/browser/resources/print_preview/data/destination.js @@ -2,248 +2,246 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); - -/** - * Enumeration of the types of destinations. - * @enum {string} - */ -print_preview.DestinationType = { - GOOGLE: 'google', - GOOGLE_PROMOTED: 'google_promoted', - LOCAL: 'local', - MOBILE: 'mobile' -}; - -/** - * Enumeration of the origin types for cloud destinations. - * @enum {string} - */ -print_preview.DestinationOrigin = { - LOCAL: 'local', - COOKIES: 'cookies', - // <if expr="chromeos"> - DEVICE: 'device', - // </if> - PRIVET: 'privet', - EXTENSION: 'extension', - CROS: 'chrome_os', -}; - -/** - * Cloud Print origins. - * @const {!Array<!print_preview.DestinationOrigin>} - */ -print_preview.CloudOrigins = [ - print_preview.DestinationOrigin.COOKIES, +cr.define('print_preview', function() { + 'use strict'; + + /** + * Enumeration of the types of destinations. + * @enum {string} + */ + const DestinationType = { + GOOGLE: 'google', + GOOGLE_PROMOTED: 'google_promoted', + LOCAL: 'local', + MOBILE: 'mobile', + }; + + /** + * Enumeration of the origin types for cloud destinations. + * @enum {string} + */ + const DestinationOrigin = { + LOCAL: 'local', + COOKIES: 'cookies', + // <if expr="chromeos"> + DEVICE: 'device', + // </if> + PRIVET: 'privet', + EXTENSION: 'extension', + CROS: 'chrome_os', + }; + + /** + * Cloud Print origins. + * @const {!Array<!print_preview.DestinationOrigin>} + */ + const CloudOrigins = [ + DestinationOrigin.COOKIES, + // <if expr="chromeos"> + DestinationOrigin.DEVICE, + // </if> + ]; + + /** + * Enumeration of the connection statuses of printer destinations. + * @enum {string} + */ + const DestinationConnectionStatus = { + DORMANT: 'DORMANT', + OFFLINE: 'OFFLINE', + ONLINE: 'ONLINE', + UNKNOWN: 'UNKNOWN', + UNREGISTERED: 'UNREGISTERED', + }; + + /** + * Enumeration specifying whether a destination is provisional and the reason + * the destination is provisional. + * @enum {string} + */ + const DestinationProvisionalType = { + // Destination is not provisional. + NONE: 'NONE', + // User has to grant USB access for the destination to its provider. + // Used for destinations with extension origin. + NEEDS_USB_PERMISSION: 'NEEDS_USB_PERMISSION', + }; + + /** + * Enumeration specifying the status of a destination's 2018 certificate. + * Values UNKNOWN and YES are returned directly by the GCP server. + * @enum {string} + */ + const DestinationCertificateStatus = { + // Destination is not a cloud printer or no status was retrieved. + NONE: 'NONE', + // Printer does not have a valid 2018 certificate. Currently unused, to be + // sent by GCP server. + NO: 'NO', + // Printer may or may not have a valid certificate. Sent by GCP server. + UNKNOWN: 'UNKNOWN', + // Printer has a valid 2018 certificate. Sent by GCP server. + YES: 'YES', + }; + + /** + * @typedef {{ + * display_name: (string), + * type: (string | undefined), + * value: (number | string | boolean), + * is_default: (boolean | undefined), + * }} + */ + let VendorCapabilitySelectOption; + + /** + * Specifies a custom vendor capability. + * @typedef {{ + * id: (string), + * display_name: (string), + * localized_display_name: (string | undefined), + * type: (string), + * select_cap: ({ + * option: (Array<!print_preview.VendorCapabilitySelectOption>|undefined), + * }|undefined), + * typed_value_cap: ({ + * default: (number | string | boolean | undefined), + * }|undefined), + * range_cap: ({ + * default: (number), + * }), + * }} + */ + let VendorCapability; + + /** + * Capabilities of a print destination represented in a CDD. + * Pin capability is not a part of standard CDD description and is defined + * only on Chrome OS. + * + * @typedef {{ + * vendor_capability: !Array<!print_preview.VendorCapability>, + * collate: ({default: (boolean|undefined)}|undefined), + * color: ({ + * option: !Array<{ + * type: (string|undefined), + * vendor_id: (string|undefined), + * custom_display_name: (string|undefined), + * is_default: (boolean|undefined) + * }> + * }|undefined), + * copies: ({default: (number|undefined), + * max: (number|undefined)}|undefined), + * duplex: ({option: !Array<{type: (string|undefined), + * is_default: (boolean|undefined)}>}|undefined), + * page_orientation: ({ + * option: !Array<{type: (string|undefined), + * is_default: (boolean|undefined)}> + * }|undefined), + * media_size: ({ + * option: !Array<{ + * type: (string|undefined), + * vendor_id: (string|undefined), + * custom_display_name: (string|undefined), + * is_default: (boolean|undefined) + * }> + * }|undefined), + * dpi: ({ + * option: !Array<{ + * vendor_id: (string|undefined), + * horizontal_dpi: number, + * vertical_dpi: number, + * is_default: (boolean|undefined) + * }> + * }|undefined), + * pin: ({supported: (boolean|undefined)}|undefined) + * }} + */ + let CddCapabilities; + + /** + * The CDD (Cloud Device Description) describes the capabilities of a print + * destination. + * + * @typedef {{ + * version: string, + * printer: !print_preview.CddCapabilities, + * }} + */ + let Cdd; + + /** + * Enumeration of color modes used by Chromium. + * @enum {number} + */ + const ColorMode = { + GRAY: 1, + COLOR: 2, + }; + // <if expr="chromeos"> - print_preview.DestinationOrigin.DEVICE + /** + * Enumeration of color mode restrictions used by Chromium. + * This has to coincide with |printing::ColorModeRestriction| as defined in + * printing/backend/printing_restrictions.h + * @enum {number} + */ + const ColorModeRestriction = { + UNSET: 0x0, + MONOCHROME: 0x1, + COLOR: 0x2, + }; + + /** + * Enumeration of duplex mode restrictions used by Chromium. + * This has to coincide with |printing::DuplexModeRestriction| as defined in + * printing/backend/printing_restrictions.h + * @enum {number} + */ + const DuplexModeRestriction = { + UNSET: 0x0, + SIMPLEX: 0x1, + LONG_EDGE: 0x2, + SHORT_EDGE: 0x4, + DUPLEX: 0x6, + }; + + /** + * Enumeration of PIN printing mode restrictions used by Chromium. + * This has to coincide with |printing::PinModeRestriction| as defined in + * printing/backend/printing_restrictions.h + * @enum {number} + */ + const PinModeRestriction = { + UNSET: 0, + PIN: 1, + NO_PIN: 2, + }; + + /** + * Policies affecting a destination. + * @typedef {{ + * allowedColorModes: ?print_preview.ColorModeRestriction, + * allowedDuplexModes: ?print_preview.DuplexModeRestriction, + * allowedPinMode: ?print_preview.PinModeRestriction, + * defaultColorMode: ?print_preview.ColorModeRestriction, + * defaultDuplexMode: ?print_preview.DuplexModeRestriction, + * defaultPinMode: ?print_preview.PinModeRestriction, + * }} + */ + let Policies; // </if> -]; - -/** - * Enumeration of the connection statuses of printer destinations. - * @enum {string} - */ -print_preview.DestinationConnectionStatus = { - DORMANT: 'DORMANT', - OFFLINE: 'OFFLINE', - ONLINE: 'ONLINE', - UNKNOWN: 'UNKNOWN', - UNREGISTERED: 'UNREGISTERED' -}; - -/** - * Enumeration specifying whether a destination is provisional and the reason - * the destination is provisional. - * @enum {string} - */ -print_preview.DestinationProvisionalType = { - // Destination is not provisional. - NONE: 'NONE', - // User has to grant USB access for the destination to its provider. - // Used for destinations with extension origin. - NEEDS_USB_PERMISSION: 'NEEDS_USB_PERMISSION' -}; - -/** - * Enumeration specifying the status of a destination's 2018 certificate. - * Values UNKNOWN and YES are returned directly by the GCP server. - * @enum {string} - */ -print_preview.DestinationCertificateStatus = { - // Destination is not a cloud printer or no status was retrieved. - NONE: 'NONE', - // Printer does not have a valid 2018 certificate. Currently unused, to be - // sent by GCP server. - NO: 'NO', - // Printer may or may not have a valid certificate. Sent by GCP server. - UNKNOWN: 'UNKNOWN', - // Printer has a valid 2018 certificate. Sent by GCP server. - YES: 'YES' -}; - -/** - * @typedef {{ - * display_name: (string), - * type: (string | undefined), - * value: (number | string | boolean), - * is_default: (boolean | undefined), - * }} - */ -print_preview.VendorCapabilitySelectOption; - -/** - * Specifies a custom vendor capability. - * @typedef {{ - * id: (string), - * display_name: (string), - * localized_display_name: (string | undefined), - * type: (string), - * select_cap: ({ - * option: (Array<!print_preview.VendorCapabilitySelectOption>|undefined), - * }|undefined), - * typed_value_cap: ({ - * default: (number | string | boolean | undefined), - * }|undefined), - * range_cap: ({ - * default: (number), - * }), - * }} - */ -print_preview.VendorCapability; - -/** - * Capabilities of a print destination represented in a CDD. - * Pin capability is not a part of standard CDD description and is defined only - * on Chrome OS. - * - * @typedef {{ - * vendor_capability: !Array<!print_preview.VendorCapability>, - * collate: ({default: (boolean|undefined)}|undefined), - * color: ({ - * option: !Array<{ - * type: (string|undefined), - * vendor_id: (string|undefined), - * custom_display_name: (string|undefined), - * is_default: (boolean|undefined) - * }> - * }|undefined), - * copies: ({default: (number|undefined), - * max: (number|undefined)}|undefined), - * duplex: ({option: !Array<{type: (string|undefined), - * is_default: (boolean|undefined)}>}|undefined), - * page_orientation: ({ - * option: !Array<{type: (string|undefined), - * is_default: (boolean|undefined)}> - * }|undefined), - * media_size: ({ - * option: !Array<{ - * type: (string|undefined), - * vendor_id: (string|undefined), - * custom_display_name: (string|undefined), - * is_default: (boolean|undefined) - * }> - * }|undefined), - * dpi: ({ - * option: !Array<{ - * vendor_id: (string|undefined), - * horizontal_dpi: number, - * vertical_dpi: number, - * is_default: (boolean|undefined) - * }> - * }|undefined), - * pin: ({supported: (boolean|undefined)}|undefined) - * }} - */ -print_preview.CddCapabilities; - -/** - * The CDD (Cloud Device Description) describes the capabilities of a print - * destination. - * - * @typedef {{ - * version: string, - * printer: !print_preview.CddCapabilities, - * }} - */ -print_preview.Cdd; - -/** - * Enumeration of color modes used by Chromium. - * @enum {number} - */ -print_preview.ColorMode = { - GRAY: 1, - COLOR: 2 -}; - -// <if expr="chromeos"> -/** - * Enumeration of color mode restrictions used by Chromium. - * This has to coincide with |printing::ColorModeRestriction| as defined in - * printing/backend/printing_restrictions.h - * @enum {number} - */ -print_preview.ColorModeRestriction = { - UNSET: 0x0, - MONOCHROME: 0x1, - COLOR: 0x2, -}; - -/** - * Enumeration of duplex mode restrictions used by Chromium. - * This has to coincide with |printing::DuplexModeRestriction| as defined in - * printing/backend/printing_restrictions.h - * @enum {number} - */ -print_preview.DuplexModeRestriction = { - UNSET: 0x0, - SIMPLEX: 0x1, - LONG_EDGE: 0x2, - SHORT_EDGE: 0x4, - DUPLEX: 0x6 -}; - -/** - * Enumeration of PIN printing mode restrictions used by Chromium. - * This has to coincide with |printing::PinModeRestriction| as defined in - * printing/backend/printing_restrictions.h - * @enum {number} - */ -print_preview.PinModeRestriction = { - UNSET: 0, - PIN: 1, - NO_PIN: 2 -}; - -/** - * Policies affecting a destination. - * @typedef {{ - * allowedColorModes: ?print_preview.ColorModeRestriction, - * allowedDuplexModes: ?print_preview.DuplexModeRestriction, - * allowedPinMode: ?print_preview.PinModeRestriction, - * defaultColorMode: ?print_preview.ColorModeRestriction, - * defaultDuplexMode: ?print_preview.DuplexModeRestriction, - * defaultPinMode: ?print_preview.PinModeRestriction, - * }} - */ -print_preview.Policies; -// </if> - -/** - * @typedef {{id: string, - * origin: print_preview.DestinationOrigin, - * account: string, - * capabilities: ?print_preview.Cdd, - * displayName: string, - * extensionId: string, - * extensionName: string}} - */ -print_preview.RecentDestination; -cr.define('print_preview', function() { - 'use strict'; + /** + * @typedef {{id: string, + * origin: print_preview.DestinationOrigin, + * account: string, + * capabilities: ?print_preview.Cdd, + * displayName: string, + * extensionId: string, + * extensionName: string}} + */ + let RecentDestination; /** * Creates a |RecentDestination| to represent |destination| in the app @@ -430,7 +428,7 @@ cr.define('print_preview', function() { * @private {print_preview.DestinationProvisionalType} */ this.provisionalType_ = (opt_params && opt_params.provisionalType) || - print_preview.DestinationProvisionalType.NONE; + DestinationProvisionalType.NONE; /** * Printer 2018 certificate status @@ -441,8 +439,7 @@ cr.define('print_preview', function() { assert( this.provisionalType_ != - print_preview.DestinationProvisionalType - .NEEDS_USB_PERMISSION || + DestinationProvisionalType.NEEDS_USB_PERMISSION || this.isExtension, 'Provisional USB destination only supprted with extension origin.'); @@ -499,17 +496,16 @@ cr.define('print_preview', function() { /** @return {boolean} Whether the destination is local or cloud-based. */ get isLocal() { - return this.origin_ == print_preview.DestinationOrigin.LOCAL || - this.origin_ == print_preview.DestinationOrigin.EXTENSION || - this.origin_ == print_preview.DestinationOrigin.CROS || - (this.origin_ == print_preview.DestinationOrigin.PRIVET && - this.connectionStatus_ != - print_preview.DestinationConnectionStatus.UNREGISTERED); + return this.origin_ == DestinationOrigin.LOCAL || + this.origin_ == DestinationOrigin.EXTENSION || + this.origin_ == DestinationOrigin.CROS || + (this.origin_ == DestinationOrigin.PRIVET && + this.connectionStatus_ != DestinationConnectionStatus.UNREGISTERED); } /** @return {boolean} Whether the destination is a Privet local printer */ get isPrivet() { - return this.origin_ == print_preview.DestinationOrigin.PRIVET; + return this.origin_ == DestinationOrigin.PRIVET; } /** @@ -517,7 +513,7 @@ cr.define('print_preview', function() { * printer. */ get isExtension() { - return this.origin_ == print_preview.DestinationOrigin.EXTENSION; + return this.origin_ == DestinationOrigin.EXTENSION; } /** @@ -671,8 +667,7 @@ cr.define('print_preview', function() { /** @return {boolean} Whether the destination is ready to be selected. */ get readyForSelection() { - return (!cr.isChromeOS || - this.origin_ != print_preview.DestinationOrigin.CROS || + return (!cr.isChromeOS || this.origin_ != DestinationOrigin.CROS || this.capabilities_ != null) && !this.isProvisional; } @@ -776,8 +771,7 @@ cr.define('print_preview', function() { * @return {boolean} */ get isProvisional() { - return this.provisionalType_ != - print_preview.DestinationProvisionalType.NONE; + return this.provisionalType_ != DestinationProvisionalType.NONE; } /** @@ -957,9 +951,28 @@ cr.define('print_preview', function() { // Export return { - Destination: Destination, - makeRecentDestination: makeRecentDestination, + CddCapabilities: CddCapabilities, + Cdd: Cdd, + CloudOrigins: CloudOrigins, + ColorMode: ColorMode, createDestinationKey: createDestinationKey, createRecentDestinationKey: createRecentDestinationKey, + DestinationCertificateStatus: DestinationCertificateStatus, + DestinationConnectionStatus: DestinationConnectionStatus, + Destination: Destination, + DestinationOrigin: DestinationOrigin, + DestinationProvisionalType: DestinationProvisionalType, + DestinationType: DestinationType, + makeRecentDestination: makeRecentDestination, + RecentDestination: RecentDestination, + VendorCapabilitySelectOption: VendorCapabilitySelectOption, + VendorCapability: VendorCapability, + + // <if expr="chromeos"> + ColorModeRestriction: ColorModeRestriction, + DuplexModeRestriction: DuplexModeRestriction, + PinModeRestriction: PinModeRestriction, + Policies: Policies, + // </if> }; }); diff --git a/chromium/chrome/browser/resources/print_preview/data/destination_store.js b/chromium/chrome/browser/resources/print_preview/data/destination_store.js index 61402a2561f..b5e767f25d9 100644 --- a/chromium/chrome/browser/resources/print_preview/data/destination_store.js +++ b/chromium/chrome/browser/resources/print_preview/data/destination_store.js @@ -2,32 +2,31 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); - -/** - * Printer search statuses used by the destination store. - * @enum {string} - */ -print_preview.DestinationStorePrinterSearchStatus = { - START: 'start', - SEARCHING: 'searching', - DONE: 'done' -}; - -/** - * Enumeration of possible destination errors. - * @enum {number} - */ -print_preview.DestinationErrorType = { - INVALID: 0, - UNSUPPORTED: 1, - // <if expr="chromeos"> - NO_DESTINATIONS: 2, - // </if> -}; - cr.define('print_preview', function() { 'use strict'; + + /** + * Printer search statuses used by the destination store. + * @enum {string} + */ + const DestinationStorePrinterSearchStatus = { + START: 'start', + SEARCHING: 'searching', + DONE: 'done' + }; + + /** + * Enumeration of possible destination errors. + * @enum {number} + */ + const DestinationErrorType = { + INVALID: 0, + UNSUPPORTED: 1, + // <if expr="chromeos"> + NO_DESTINATIONS: 2, + // </if> + }; + /** * Localizes printer capabilities. * @param {!print_preview.Cdd} capabilities Printer capabilities to @@ -191,20 +190,20 @@ cr.define('print_preview', function() { * Whether a search for destinations is in progress for each type of * printer. * @private {!Map<!print_preview.PrinterType, - * !print_preview.DestinationStorePrinterSearchStatus>} + * !DestinationStorePrinterSearchStatus>} */ this.destinationSearchStatus_ = new Map([ [ print_preview.PrinterType.EXTENSION_PRINTER, - print_preview.DestinationStorePrinterSearchStatus.START + DestinationStorePrinterSearchStatus.START ], [ print_preview.PrinterType.PRIVET_PRINTER, - print_preview.DestinationStorePrinterSearchStatus.START + DestinationStorePrinterSearchStatus.START ], [ print_preview.PrinterType.LOCAL_PRINTER, - print_preview.DestinationStorePrinterSearchStatus.START + DestinationStorePrinterSearchStatus.START ], ]); @@ -301,10 +300,7 @@ cr.define('print_preview', function() { get isPrintDestinationSearchInProgress() { const isLocalDestinationSearchInProgress = Array.from(this.destinationSearchStatus_.values()) - .some( - el => el === - print_preview.DestinationStorePrinterSearchStatus - .SEARCHING); + .some(el => el === DestinationStorePrinterSearchStatus.SEARCHING); if (isLocalDestinationSearchInProgress) { return true; } @@ -824,18 +820,18 @@ cr.define('print_preview', function() { */ startLoadDestinations_(type) { if (this.destinationSearchStatus_.get(type) === - print_preview.DestinationStorePrinterSearchStatus.DONE) { + DestinationStorePrinterSearchStatus.DONE) { return; } this.destinationSearchStatus_.set( - type, print_preview.DestinationStorePrinterSearchStatus.SEARCHING); + type, DestinationStorePrinterSearchStatus.SEARCHING); this.nativeLayer_.getPrinters(type).then( this.onDestinationSearchDone_.bind(this, type), () => { // Will be rejected by C++ for privet printers if privet printing // is disabled. assert(type === print_preview.PrinterType.PRIVET_PRINTER); this.destinationSearchStatus_.set( - type, print_preview.DestinationStorePrinterSearchStatus.DONE); + type, DestinationStorePrinterSearchStatus.DONE); }); } @@ -870,7 +866,7 @@ cr.define('print_preview', function() { // Add cloud printer to the map. this.destinationSearchStatus_.set( print_preview.PrinterType.CLOUD_PRINTER, - print_preview.DestinationStorePrinterSearchStatus.START); + DestinationStorePrinterSearchStatus.START); types.push(print_preview.PrinterType.CLOUD_PRINTER); } else { this.startLoadCloudDestinations(); @@ -1144,7 +1140,7 @@ cr.define('print_preview', function() { */ onDestinationSearchDone_(type) { this.destinationSearchStatus_.set( - type, print_preview.DestinationStorePrinterSearchStatus.DONE); + type, DestinationStorePrinterSearchStatus.DONE); this.dispatchEvent( new CustomEvent(DestinationStore.EventType.DESTINATION_SEARCH_DONE)); if (type === print_preview.PrinterType.EXTENSION_PRINTER) { @@ -1184,6 +1180,9 @@ cr.define('print_preview', function() { assert(settingsInfo.printer))); } if (dest) { + if (settingsInfo.printer && settingsInfo.printer.policies) { + dest.policies = settingsInfo.printer.policies; + } if ((origin === print_preview.DestinationOrigin.LOCAL || origin === print_preview.DestinationOrigin.CROS) && dest.capabilities) { @@ -1258,9 +1257,7 @@ cr.define('print_preview', function() { sendNoPrinterEventIfNeeded_() { const isLocalDestinationSearchNotStarted = Array.from(this.destinationSearchStatus_.values()) - .some( - el => el === - print_preview.DestinationStorePrinterSearchStatus.START); + .some(el => el === DestinationStorePrinterSearchStatus.START); if (isLocalDestinationSearchNotStarted || this.isPrintDestinationSearchInProgress || !this.selectFirstDestination_) { @@ -1554,5 +1551,8 @@ cr.define('print_preview', function() { }; // Export - return {DestinationStore: DestinationStore}; + return { + DestinationErrorType: DestinationErrorType, + DestinationStore: DestinationStore, + }; }); diff --git a/chromium/chrome/browser/resources/print_preview/data/invitation_store.js b/chromium/chrome/browser/resources/print_preview/data/invitation_store.js index 724a309540f..253e442420d 100644 --- a/chromium/chrome/browser/resources/print_preview/data/invitation_store.js +++ b/chromium/chrome/browser/resources/print_preview/data/invitation_store.js @@ -2,21 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); - -/** - * @enum {number} - * @private - */ -print_preview.InvitationStoreLoadStatus = { - IN_PROGRESS: 1, - DONE: 2, - FAILED: 3 -}; - cr.define('print_preview', function() { 'use strict'; + /** + * @enum {number} + * @private + */ + const InvitationStoreLoadStatus = { + IN_PROGRESS: 1, + DONE: 2, + FAILED: 3, + }; + class InvitationStore extends cr.EventTarget { /** Printer sharing invitations data store. */ constructor() { @@ -31,7 +29,7 @@ cr.define('print_preview', function() { /** * Maps user account to the flag whether the invitations for this account * were successfully loaded. - * @private {!Object<print_preview.InvitationStoreLoadStatus>} + * @private {!Object<InvitationStoreLoadStatus>} */ this.loadStatus_ = {}; @@ -109,16 +107,14 @@ cr.define('print_preview', function() { return; } if (this.loadStatus_.hasOwnProperty(user)) { - if (this.loadStatus_[user] == - print_preview.InvitationStoreLoadStatus.DONE) { + if (this.loadStatus_[user] == InvitationStoreLoadStatus.DONE) { this.dispatchEvent(new CustomEvent( InvitationStore.EventType.INVITATION_SEARCH_DONE)); } return; } - this.loadStatus_[user] = - print_preview.InvitationStoreLoadStatus.IN_PROGRESS; + this.loadStatus_[user] = InvitationStoreLoadStatus.IN_PROGRESS; this.cloudPrintInterface_.invites(user); } @@ -159,8 +155,7 @@ cr.define('print_preview', function() { * @private */ onCloudPrintInvitesDone_(event) { - this.loadStatus_[event.detail.user] = - print_preview.InvitationStoreLoadStatus.DONE; + this.loadStatus_[event.detail.user] = InvitationStoreLoadStatus.DONE; this.invitations_[event.detail.user] = event.detail.invitations; this.dispatchEvent( @@ -174,8 +169,7 @@ cr.define('print_preview', function() { * @private */ onCloudPrintInvitesFailed_(event) { - this.loadStatus_[event.detail] = - print_preview.InvitationStoreLoadStatus.FAILED; + this.loadStatus_[event.detail] = InvitationStoreLoadStatus.FAILED; } /** diff --git a/chromium/chrome/browser/resources/print_preview/data/margins.js b/chromium/chrome/browser/resources/print_preview/data/margins.js index 389e4e05961..3facd5a82cd 100644 --- a/chromium/chrome/browser/resources/print_preview/data/margins.js +++ b/chromium/chrome/browser/resources/print_preview/data/margins.js @@ -2,45 +2,53 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview.ticket_items'); -/** - * Enumeration of the orientations of margins. - * @enum {string} - */ -print_preview.ticket_items.CustomMarginsOrientation = { - TOP: 'top', - RIGHT: 'right', - BOTTOM: 'bottom', - LEFT: 'left' -}; +cr.define('print_preview.ticket_items', function() { + 'use strict'; + + /** + * Enumeration of the orientations of margins. + * @enum {string} + */ + const CustomMarginsOrientation = { + TOP: 'top', + RIGHT: 'right', + BOTTOM: 'bottom', + LEFT: 'left', + }; -/** - * Must be kept in sync with the C++ MarginType enum in - * printing/print_job_constants.h. - * @enum {number} - */ -print_preview.ticket_items.MarginsTypeValue = { - DEFAULT: 0, - NO_MARGINS: 1, - MINIMUM: 2, - CUSTOM: 3 -}; + /** + * Must be kept in sync with the C++ MarginType enum in + * printing/print_job_constants.h. + * @enum {number} + */ + const MarginsTypeValue = { + DEFAULT: 0, + NO_MARGINS: 1, + MINIMUM: 2, + CUSTOM: 3, + }; -/** - * Keep in sync with the C++ kSettingMargin... values in - * printing/print_job_constants.h. - * @typedef {{ - * marginTop: number, - * marginRight: number, - * marginBottom: number, - * marginLeft: number, - * }} - */ -print_preview.MarginsSetting; + return { + CustomMarginsOrientation: CustomMarginsOrientation, + MarginsTypeValue: MarginsTypeValue, + }; +}); cr.define('print_preview', function() { 'use strict'; + /** + * Keep in sync with the C++ kSettingMargin... values in + * printing/print_job_constants.h. + * @typedef {{ + * marginTop: number, + * marginRight: number, + * marginBottom: number, + * marginLeft: number, + * }} + */ + let MarginsSetting; + class Margins { /** * Creates a Margins object that holds four margin values in points. @@ -144,5 +152,8 @@ cr.define('print_preview', function() { } // Export - return {Margins: Margins}; + return { + Margins: Margins, + MarginsSetting: MarginsSetting, + }; }); diff --git a/chromium/chrome/browser/resources/print_preview/data/measurement_system.js b/chromium/chrome/browser/resources/print_preview/data/measurement_system.js index aa422f2c77f..c57e8a90e29 100644 --- a/chromium/chrome/browser/resources/print_preview/data/measurement_system.js +++ b/chromium/chrome/browser/resources/print_preview/data/measurement_system.js @@ -2,55 +2,53 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); - -/** - * Enumeration of measurement unit types. - * @enum {number} - */ -print_preview.MeasurementSystemUnitType = { - METRIC: 0, // millimeters - IMPERIAL: 1 // inches -}; - -/** - * @typedef {{precision: number, - * decimalPlaces: number, - * ptsPerUnit: number, - * unitSymbol: string}} - */ -print_preview.MeasurementSystemPrefs; - cr.define('print_preview', function() { 'use strict'; + /** + * Enumeration of measurement unit types. + * @enum {number} + */ + const MeasurementSystemUnitType = { + METRIC: 0, // millimeters + IMPERIAL: 1 // inches + }; + + /** + * @typedef {{precision: number, + * decimalPlaces: number, + * ptsPerUnit: number, + * unitSymbol: string}} + */ + let MeasurementSystemPrefs; + class MeasurementSystem { /** * Measurement system of the print preview. Used to parse and serialize * point measurements into the system's local units (e.g. millimeters, * inches). - * @param {string} thousandsDelimeter Delimeter between thousands digits. - * @param {string} decimalDelimeter Delimeter between integers and decimals. + * @param {string} thousandsDelimiter Delimiter between thousands digits. + * @param {string} decimalDelimiter Delimiter between integers and decimals. * @param {!print_preview.MeasurementSystemUnitType} unitType Measurement * unit type of the system. */ - constructor(thousandsDelimeter, decimalDelimeter, unitType) { + constructor(thousandsDelimiter, decimalDelimiter, unitType) { /** - * The thousands delimeter to use when displaying numbers. + * The thousands delimiter to use when displaying numbers. * @private {string} */ - this.thousandsDelimeter_ = thousandsDelimeter || ','; + this.thousandsDelimiter_ = thousandsDelimiter || ','; /** - * The decimal delimeter to use when displaying numbers. + * The decimal delimiter to use when displaying numbers. * @private {string} */ - this.decimalDelimeter_ = decimalDelimeter || '.'; + this.decimalDelimiter_ = decimalDelimiter || '.'; assert(measurementSystemPrefs.has(unitType)); /** * The measurement system preferences based on the unit type. - * @private {!print_preview.MeasurementSystemPrefs} + * @private {!MeasurementSystemPrefs} */ this.measurementSystemPrefs_ = measurementSystemPrefs.get(unitType); } @@ -61,19 +59,19 @@ cr.define('print_preview', function() { } /** - * @return {string} The thousands delimeter character of the measurement + * @return {string} The thousands delimiter character of the measurement * system. */ - get thousandsDelimeter() { - return this.thousandsDelimeter_; + get thousandsDelimiter() { + return this.thousandsDelimiter_; } /** - * @return {string} The decimal delimeter character of the measurement + * @return {string} The decimal delimiter character of the measurement * system. */ - get decimalDelimeter() { - return this.decimalDelimeter_; + get decimalDelimiter() { + return this.decimalDelimiter_; } /** @@ -108,11 +106,11 @@ cr.define('print_preview', function() { /** * Maximum resolution and number of decimal places for local unit values. * @private {!Map<!print_preview.MeasurementSystemUnitType, - * !print_preview.MeasurementSystemPrefs>} + * !MeasurementSystemPrefs>} */ const measurementSystemPrefs = new Map([ [ - print_preview.MeasurementSystemUnitType.METRIC, { + MeasurementSystemUnitType.METRIC, { precision: 0.5, decimalPlaces: 1, ptsPerUnit: 72.0 / 25.4, @@ -120,11 +118,14 @@ cr.define('print_preview', function() { } ], [ - print_preview.MeasurementSystemUnitType.IMPERIAL, + MeasurementSystemUnitType.IMPERIAL, {precision: 0.01, decimalPlaces: 2, ptsPerUnit: 72.0, unitSymbol: '"'} ] ]); // Export - return {MeasurementSystem: MeasurementSystem}; + return { + MeasurementSystem: MeasurementSystem, + MeasurementSystemUnitType: MeasurementSystemUnitType, + }; }); diff --git a/chromium/chrome/browser/resources/print_preview/data/model.js b/chromium/chrome/browser/resources/print_preview/data/model.js index a576e86a07b..4e5182375ae 100644 --- a/chromium/chrome/browser/resources/print_preview/data/model.js +++ b/chromium/chrome/browser/resources/print_preview/data/model.js @@ -2,117 +2,127 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); +cr.define('print_preview', function() { + /** + * |key| is the field in the serialized settings state that corresponds to the + * setting, or an empty string if the setting should not be saved in the + * serialized state. + * @typedef {{ + * value: *, + * unavailableValue: *, + * valid: boolean, + * available: boolean, + * setByPolicy: boolean, + * setFromUi: boolean, + * key: string, + * updatesPreview: boolean, + * }} + */ + let Setting; -/** - * |key| is the field in the serialized settings state that corresponds to the - * setting, or an empty string if the setting should not be saved in the - * serialized state. - * @typedef {{ - * value: *, - * unavailableValue: *, - * valid: boolean, - * available: boolean, - * setByPolicy: boolean, - * setFromUi: boolean, - * key: string, - * updatesPreview: boolean, - * }} - */ -print_preview.Setting; + /** + * @typedef {{ + * pages: !print_preview.Setting, + * copies: !print_preview.Setting, + * collate: !print_preview.Setting, + * layout: !print_preview.Setting, + * color: !print_preview.Setting, + * mediaSize: !print_preview.Setting, + * margins: !print_preview.Setting, + * dpi: !print_preview.Setting, + * fitToPage: !print_preview.Setting, + * scaling: !print_preview.Setting, + * duplex: !print_preview.Setting, + * duplexShortEdge: !print_preview.Setting, + * cssBackground: !print_preview.Setting, + * selectionOnly: !print_preview.Setting, + * headerFooter: !print_preview.Setting, + * rasterize: !print_preview.Setting, + * vendorItems: !print_preview.Setting, + * otherOptions: !print_preview.Setting, + * ranges: !print_preview.Setting, + * pagesPerSheet: !print_preview.Setting, + * pin: (print_preview.Setting|undefined), + * pinValue: (print_preview.Setting|undefined), + * }} + */ + let Settings; -/** - * @typedef {{ - * pages: !print_preview.Setting, - * copies: !print_preview.Setting, - * collate: !print_preview.Setting, - * layout: !print_preview.Setting, - * color: !print_preview.Setting, - * mediaSize: !print_preview.Setting, - * margins: !print_preview.Setting, - * dpi: !print_preview.Setting, - * fitToPage: !print_preview.Setting, - * scaling: !print_preview.Setting, - * duplex: !print_preview.Setting, - * duplexShortEdge: !print_preview.Setting, - * cssBackground: !print_preview.Setting, - * selectionOnly: !print_preview.Setting, - * headerFooter: !print_preview.Setting, - * rasterize: !print_preview.Setting, - * vendorItems: !print_preview.Setting, - * otherOptions: !print_preview.Setting, - * ranges: !print_preview.Setting, - * pagesPerSheet: !print_preview.Setting, - * pin: (print_preview.Setting|undefined), - * pinValue: (print_preview.Setting|undefined), - * }} - */ -print_preview.Settings; + /** + * @typedef {{ + * version: string, + * recentDestinations: (!Array<!print_preview.RecentDestination> | + * undefined), + * dpi: ({horizontal_dpi: number, + * vertical_dpi: number, + * is_default: (boolean | undefined)} | undefined), + * mediaSize: ({height_microns: number, + * width_microns: number, + * custom_display_name: (string | undefined), + * is_default: (boolean | undefined)} | undefined), + * marginsType: (print_preview.ticket_items.MarginsTypeValue | undefined), + * customMargins: (print_preview.MarginsSetting | undefined), + * isColorEnabled: (boolean | undefined), + * isDuplexEnabled: (boolean | undefined), + * isHeaderFooterEnabled: (boolean | undefined), + * isLandscapeEnabled: (boolean | undefined), + * isCollateEnabled: (boolean | undefined), + * isFitToPageEnabled: (boolean | undefined), + * isCssBackgroundEnabled: (boolean | undefined), + * scaling: (string | undefined), + * vendor_options: (Object | undefined), + * isPinEnabled: (boolean | undefined), + * pinValue: (string | undefined) + * }} + */ + let SerializedSettings; -/** - * @typedef {{ - * version: string, - * recentDestinations: (!Array<!print_preview.RecentDestination> | - * undefined), - * dpi: ({horizontal_dpi: number, - * vertical_dpi: number, - * is_default: (boolean | undefined)} | undefined), - * mediaSize: ({height_microns: number, - * width_microns: number, - * custom_display_name: (string | undefined), - * is_default: (boolean | undefined)} | undefined), - * marginsType: (print_preview.ticket_items.MarginsTypeValue | undefined), - * customMargins: (print_preview.MarginsSetting | undefined), - * isColorEnabled: (boolean | undefined), - * isDuplexEnabled: (boolean | undefined), - * isHeaderFooterEnabled: (boolean | undefined), - * isLandscapeEnabled: (boolean | undefined), - * isCollateEnabled: (boolean | undefined), - * isFitToPageEnabled: (boolean | undefined), - * isCssBackgroundEnabled: (boolean | undefined), - * scaling: (string | undefined), - * vendor_options: (Object | undefined), - * isPinEnabled: (boolean | undefined), - * pinValue: (string | undefined) - * }} - */ -print_preview.SerializedSettings; + /** + * @typedef {{ + * value: *, + * managed: boolean + * }} + */ + let PolicyEntry; -/** - * @typedef {{ - * value: *, - * managed: boolean - * }} - */ -print_preview.PolicyEntry; + /** + * @typedef {{ + * headerFooter: print_preview.PolicyEntry + * }} + */ + let PolicySettings; -/** - * @typedef {{ - * headerFooter: print_preview.PolicyEntry - * }} - */ -print_preview.PolicySettings; + /** + * Constant values matching printing::DuplexMode enum. + * @enum {number} + */ + const DuplexMode = { + SIMPLEX: 0, + LONG_EDGE: 1, + SHORT_EDGE: 2, + UNKNOWN_DUPLEX_MODE: -1, + }; -/** - * Constant values matching printing::DuplexMode enum. - * @enum {number} - */ -print_preview.DuplexMode = { - SIMPLEX: 0, - LONG_EDGE: 1, - SHORT_EDGE: 2, - UNKNOWN_DUPLEX_MODE: -1, -}; + /** + * Values matching the types of duplex in a CDD. + * @enum {string} + */ + const DuplexType = { + NO_DUPLEX: 'NO_DUPLEX', + LONG_EDGE: 'LONG_EDGE', + SHORT_EDGE: 'SHORT_EDGE' + }; -/** - * Values matching the types of duplex in a CDD. - * @enum {string} - */ -print_preview.DuplexType = { - NO_DUPLEX: 'NO_DUPLEX', - LONG_EDGE: 'LONG_EDGE', - SHORT_EDGE: 'SHORT_EDGE' -}; + return { + DuplexMode: DuplexMode, + DuplexType: DuplexType, + PolicyEntry: PolicyEntry, + PolicySettings: PolicySettings, + SerializedSettings: SerializedSettings, + Setting: Setting, + Settings: Settings, + }; +}); cr.define('print_preview.Model', () => { return { diff --git a/chromium/chrome/browser/resources/print_preview/native_layer.js b/chromium/chrome/browser/resources/print_preview/native_layer.js index fe78ee05149..ddf522abeb6 100644 --- a/chromium/chrome/browser/resources/print_preview/native_layer.js +++ b/chromium/chrome/browser/resources/print_preview/native_layer.js @@ -33,8 +33,8 @@ cr.define('print_preview', function() { * isInKioskAutoPrintMode: boolean, * isInAppKioskMode: boolean, * uiLocale: string, - * thousandsDelimeter: string, - * decimalDelimeter: string, + * thousandsDelimiter: string, + * decimalDelimiter: string, * unitType: !print_preview.MeasurementSystemUnitType, * previewModifiable: boolean, * documentTitle: string, diff --git a/chromium/chrome/browser/resources/print_preview/polymer3/demo.js b/chromium/chrome/browser/resources/print_preview/polymer3/demo.js index 6a59ffd92d1..39a1b1bc694 100644 --- a/chromium/chrome/browser/resources/print_preview/polymer3/demo.js +++ b/chromium/chrome/browser/resources/print_preview/polymer3/demo.js @@ -2,29 +2,152 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'chrome://resources/polymer/v3_0/paper-button/paper-button.js'; +import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; +import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; +import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; +import 'chrome://resources/cr_elements/cr_drawer/cr_drawer.m.js'; +import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; +import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; +import 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.m.js'; +import 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.m.js'; +import 'chrome://resources/cr_elements/cr_search_field/cr_search_field.m.js'; +import 'chrome://resources/cr_elements/cr_tabs/cr_tabs.m.js'; +import 'chrome://resources/cr_elements/cr_toast/cr_toast.m.js'; +import 'chrome://resources/cr_elements/cr_toggle/cr_toggle.m.js'; +import 'chrome://resources/cr_elements/icons.m.js'; +import 'chrome://resources/cr_elements/md_select_css.m.js'; +import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; class HelloPolymer3Element extends PolymerElement { static get template() { return html` - <div>Hello Polymer3 [[time]]</div> - <paper-button on-click="onClick_">Update time</paper-button> + <style include="md-select"> + cr-toggle { + display: inline-block; + } + </style> + + <cr-checkbox checked="{{checkboxChecked_}}"> + [[checkboxChecked_]] + </cr-checkbox> + + <div> + <cr-toggle checked="{{toggleChecked_}}"></cr-toggle> + <span>[[toggleChecked_]]</span> + </div> + + <select class="md-select"> + <option>JS</option> + <option>modules</option> + <option>are</option> + <option>cool</option> + </select> + + <cr-input></cr-input> + + <cr-icon-button iron-icon="cr:more-vert"></cr-icon-button> + + <div> + <cr-button on-click="onClick_">Show toast</cr-button> + <cr-toast><span>I am toasted</span></cr-toast> + </div> + + <iron-icon icon="cr:error"></iron-icon> + + <div> + <cr-radio-group id="radioGroup" selected="cr"> + <cr-radio-button name="cr">cr</cr-radio-button> + <cr-radio-button name="radio">radio</cr-radio-button> + <cr-radio-button name="buttons">buttons</cr-radio-button> + </cr-radio-group> + </div> + + <div> + <cr-button on-click="showDrawer_">Show drawer</cr-button> + <cr-drawer heading="Drawer"> + <div class="drawer-content">Content of drawer</div> + </cr-drawer> + </div> + + <div> + <cr-tabs selected="{{selectedSubpage_}}" tab-names="[[tabNames_]]"> + </cr-tabs> + <div> + <template is="dom-if" if="[[isTabASelected_(selectedSubpage_)]]"> + <span>This is Tab A</span> + </template> + <template is="dom-if" if="[[isTabBSelected_(selectedSubpage_)]]"> + <span>This is Tab B</span> + </template> + </div> + </div> + + <div> + <cr-button on-click="showDialog_">Click to open dialog</cr-button> + <cr-dialog id="dialog"> + <div slot="title">I am a dialog</div> + </cr-dialog> + </div> + + <div> + <cr-search-field label="test search field"></cr-search-field> + <div> `; } static get properties() { return { - time: { + /** @private */ + toggleChecked_: Boolean, + + /** @private */ + checkboxChecked_: Boolean, + + /** @private */ + selectedSubpage_: { type: Number, - value: Date.now(), + value: 0, + }, + + /** @private {Array<string>} */ + tabNames_: { + type: Array, + value: () => (['A', 'B']), }, }; } + /** @private */ onClick_() { - this.time = Date.now(); + this.shadowRoot.querySelector('cr-toast').show(2000); + } + + /** @private */ + showDrawer_() { + this.shadowRoot.querySelector('cr-drawer').openDrawer(); + } + + /** @private */ + showDialog_() { + this.shadowRoot.querySelector('cr-dialog').showModal(); + } + + /** + * @return {boolean} + * @private + */ + isTabASelected_() { + return this.selectedSubpage_ === 0; + } + + /** + * @return {boolean} + * @private + */ + isTabBSelected_() { + return this.selectedSubpage_ === 1; } } // class HelloPolymer3 diff --git a/chromium/chrome/browser/resources/print_preview/ui/app.js b/chromium/chrome/browser/resources/print_preview/ui/app.js index afdf54feb0f..8f30d4e6358 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/app.js +++ b/chromium/chrome/browser/resources/print_preview/ui/app.js @@ -272,7 +272,7 @@ Polymer({ this.$.model.setPolicySettings( settings.headerFooter, settings.isHeaderFooterManaged); this.measurementSystem_ = new print_preview.MeasurementSystem( - settings.thousandsDelimeter, settings.decimalDelimeter, + settings.thousandsDelimiter, settings.decimalDelimiter, settings.unitType); this.setSetting('selectionOnly', settings.shouldPrintSelectionOnly); this.$.sidebar.init( diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js index 7e5266744e8..390fad8bc1e 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js +++ b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js @@ -2,496 +2,501 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); - -/** @enum {number} */ -print_preview.DestinationState = { - INIT: 0, - SELECTED: 1, - SET: 2, - UPDATED: 3, - ERROR: 4, -}; - -(function() { -'use strict'; - -/** @type {number} Number of recent destinations to save. */ -const NUM_PERSISTED_DESTINATIONS = 3; - -Polymer({ - is: 'print-preview-destination-settings', - - behaviors: [ - I18nBehavior, - SettingsBehavior, - WebUIListenerBehavior, - ], - - properties: { - appKioskMode: Boolean, - - /** @type {cloudprint.CloudPrintInterface} */ - cloudPrintInterface: { - type: Object, - observer: 'onCloudPrintInterfaceSet_', - }, +cr.define('print_preview', function() { + 'use strict'; + + /** @enum {number} */ + const DestinationState = { + INIT: 0, + SELECTED: 1, + SET: 2, + UPDATED: 3, + ERROR: 4, + }; + + /** @type {number} Number of recent destinations to save. */ + const NUM_PERSISTED_DESTINATIONS = 3; + + Polymer({ + is: 'print-preview-destination-settings', + + behaviors: [ + I18nBehavior, + SettingsBehavior, + WebUIListenerBehavior, + ], + + properties: { + appKioskMode: Boolean, + + /** @type {cloudprint.CloudPrintInterface} */ + cloudPrintInterface: { + type: Object, + observer: 'onCloudPrintInterfaceSet_', + }, + + dark: Boolean, + + /** @type {?print_preview.Destination} */ + destination: { + type: Object, + notify: true, + value: null, + }, + + /** @private {!print_preview.DestinationState} */ + destinationState: { + type: Number, + notify: true, + value: DestinationState.INIT, + observer: 'updateDestinationSelect_', + }, + + disabled: Boolean, + + /** @type {!print_preview.Error} */ + error: { + type: Number, + notify: true, + observer: 'onErrorChanged_', + }, + + firstLoad: Boolean, + + /** @type {!print_preview.State} */ + state: Number, + + /** @private {string} */ + activeUser_: { + type: String, + observer: 'onActiveUserChanged_', + }, + + /** @private {boolean} */ + cloudPrintDisabled_: Boolean, + + /** @private {?print_preview.DestinationStore} */ + destinationStore_: { + type: Object, + value: null, + }, + + /** @private {!Array<!print_preview.RecentDestination>} */ + displayedDestinations_: Array, - dark: Boolean, + // <if expr="chromeos"> + hasPinSetting_: { + type: Boolean, + computed: 'computeHasPinSetting_(settings.pin.available)', + reflectToAttribute: true, + }, + // </if> - /** @type {?print_preview.Destination} */ - destination: { - type: Object, - notify: true, - value: null, + /** @private {?print_preview.InvitationStore} */ + invitationStore_: { + type: Object, + value: null, + }, + + /** @private {boolean} */ + isDialogOpen_: { + type: Boolean, + value: false, + }, + + /** @private {boolean} */ + noDestinations_: { + type: Boolean, + value: false, + }, + + /** @private */ + shouldHideSpinner_: { + type: Boolean, + computed: 'computeShouldHideSpinner_(destinationState, destination)', + }, + + /** @private {string} */ + statusText_: { + type: String, + computed: 'computeStatusText_(destination)', + }, + + /** @private {!Array<string>} */ + users_: Array, }, - /** @private {!print_preview.DestinationState} */ - destinationState: { - type: Number, - notify: true, - value: print_preview.DestinationState.INIT, - observer: 'updateDestinationSelect_', + /** @private {string} */ + lastUser_: '', + + /** @private {!EventTracker} */ + tracker_: new EventTracker(), + + /** @override */ + attached: function() { + this.destinationStore_ = + new print_preview.DestinationStore(this.addWebUIListener.bind(this)); + this.invitationStore_ = new print_preview.InvitationStore(); + this.tracker_.add( + this.destinationStore_, + print_preview.DestinationStore.EventType.DESTINATION_SELECT, + this.onDestinationSelect_.bind(this)); + this.tracker_.add( + this.destinationStore_, + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, + this.onDestinationCapabilitiesReady_.bind(this)); + this.tracker_.add( + this.destinationStore_, + print_preview.DestinationStore.EventType.ERROR, + this.onDestinationError_.bind(this)); + // Need to update the recent list when the destination store inserts + // destinations, in case any recent destinations have been added to the + // store. At startup, recent destinations can be in the sticky settings, + // but they should not be displayed in the dropdown until they have been + // fetched by the DestinationStore, to ensure that they still exist. + this.tracker_.add( + assert(this.destinationStore_), + print_preview.DestinationStore.EventType.DESTINATIONS_INSERTED, + this.updateDropdownDestinations_.bind(this)); }, - disabled: Boolean, + /** @override */ + detached: function() { + this.invitationStore_.resetTracker(); + this.destinationStore_.resetTracker(); + this.tracker_.removeAll(); + }, - /** @type {!print_preview.Error} */ - error: { - type: Number, - notify: true, - observer: 'onErrorChanged_', + /** @private */ + onCloudPrintInterfaceSet_: function() { + const cloudPrintInterface = assert(this.cloudPrintInterface); + this.destinationStore_.setCloudPrintInterface(cloudPrintInterface); + this.invitationStore_.setCloudPrintInterface(cloudPrintInterface); }, - firstLoad: Boolean, + /** @private */ + onActiveUserChanged_: function() { + // Re-filter the dropdown destinations for the new account. + if (!this.isDialogOpen_) { + // Don't update the destination settings UI while the dialog is open in + // front of it. + this.updateDropdownDestinations_(); + } - /** @type {!print_preview.State} */ - state: Number, + if (!this.destination || + this.destination.origin !== print_preview.DestinationOrigin.COOKIES) { + // Active user changing doesn't impact non-cookie based destinations. + return; + } - /** @private {string} */ - activeUser_: { - type: String, - observer: 'onActiveUserChanged_', - }, + if (this.destination.account === this.activeUser_) { + // If the current destination belongs to the new account and the dialog + // was waiting for sign in, update the state. + if (this.destinationState === DestinationState.SELECTED) { + this.destinationState = this.destination.capabilities ? + DestinationState.UPDATED : + DestinationState.SET; + } + return; + } - /** @private {boolean} */ - cloudPrintDisabled_: Boolean, + if (this.isDialogOpen_) { + // Do not update the selected destination if the dialog is open, as this + // will change the destination settings UI behind the dialog, and the + // user may be selecting a new destination in the dialog anyway. Wait + // for the user to select a destination or cancel. + return; + } - /** @private {?print_preview.DestinationStore} */ - destinationStore_: { - type: Object, - value: null, + // Destination belongs to a different account. Reset the destination to + // the most recent destination associated with the new account, or the + // default. + const recent = this.displayedDestinations_.find(d => { + return d.origin !== print_preview.DestinationOrigin.COOKIES || + d.account === this.activeUser_; + }); + if (recent) { + const success = this.destinationStore_.selectRecentDestinationByKey( + print_preview.createRecentDestinationKey(recent), + this.displayedDestinations_); + if (success) { + return; + } + } + this.destinationStore_.selectDefaultDestination(); }, - // <if expr="chromeos"> - hasPinSetting_: { - type: Boolean, - computed: 'computeHasPinSetting_(settings.pin.available)', - reflectToAttribute: true, + /** + * @param {string} defaultPrinter The system default printer ID. + * @param {string} serializedDefaultDestinationRulesStr String with rules + * for selecting a default destination. + * @param {?Array<string>} userAccounts The signed in user accounts. + * @param {boolean} syncAvailable Whether sync is available. Used to + * determine whether to wait for user info updates from the handler, or + * to always send requests to the Google Cloud Print server. + */ + init: function( + defaultPrinter, serializedDefaultDestinationRulesStr, userAccounts, + syncAvailable) { + this.$.userManager.initUserAccounts(userAccounts, syncAvailable); + this.destinationStore_.init( + this.appKioskMode, defaultPrinter, + serializedDefaultDestinationRulesStr, + /** @type {!Array<print_preview.RecentDestination>} */ + (this.getSettingValue('recentDestinations'))); }, - // </if> - /** @private {?print_preview.InvitationStore} */ - invitationStore_: { - type: Object, - value: null, - }, + /** @private */ + onDestinationSelect_: function() { + // If the user selected a destination in the dialog after changing the + // active user, do the UI updates that were previously deferred. + if (this.isDialogOpen_ && this.lastUser_ !== this.activeUser_) { + this.updateDropdownDestinations_(); + } - /** @private {boolean} */ - isDialogOpen_: { - type: Boolean, - value: false, + if (this.state === print_preview.State.FATAL_ERROR) { + // Don't let anything reset if there is a fatal error. + return; + } + + const destination = this.destinationStore_.selectedDestination; + if (!!this.activeUser_ || + destination.origin !== print_preview.DestinationOrigin.COOKIES) { + this.destinationState = DestinationState.SET; + } else { + this.destinationState = DestinationState.SELECTED; + } + // Notify observers that the destination is set only after updating the + // destinationState. + this.destination = destination; + this.updateRecentDestinations_(); }, - /** @private {boolean} */ - noDestinations_: { - type: Boolean, - value: false, + /** @private */ + onDestinationCapabilitiesReady_: function() { + this.notifyPath('destination.capabilities'); + this.updateRecentDestinations_(); + if (this.destinationState === DestinationState.SET) { + this.destinationState = DestinationState.UPDATED; + } }, - /** @private {!Array<!print_preview.RecentDestination>} */ - displayedDestinations_: Array, + /** + * @param {!CustomEvent<!print_preview.DestinationErrorType>} e + * @private + */ + onDestinationError_: function(e) { + let errorType = print_preview.Error.NONE; + switch (e.detail) { + case print_preview.DestinationErrorType.INVALID: + errorType = print_preview.Error.INVALID_PRINTER; + break; + case print_preview.DestinationErrorType.UNSUPPORTED: + errorType = print_preview.Error.UNSUPPORTED_PRINTER; + break; + // <if expr="chromeos"> + case print_preview.DestinationErrorType.NO_DESTINATIONS: + errorType = print_preview.Error.NO_DESTINATIONS; + this.noDestinations_ = true; + break; + // </if> + default: + break; + } + this.error = errorType; + }, /** @private */ - shouldHideSpinner_: { - type: Boolean, - computed: 'computeShouldHideSpinner_(destinationState, destination)', + onErrorChanged_: function() { + if (this.error == print_preview.Error.INVALID_PRINTER || + this.error == print_preview.Error.UNSUPPORTED_PRINTER || + this.error == print_preview.Error.NO_DESTINATIONS) { + this.destinationState = DestinationState.ERROR; + } }, - /** @private {string} */ - statusText_: { - type: String, - computed: 'computeStatusText_(destination)', + /** + * @param {!print_preview.RecentDestination} destination + * @return {boolean} Whether the destination is Save as PDF or Save to + * Drive. + */ + destinationIsDriveOrPdf_: function(destination) { + return destination.id === + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF || + destination.id === print_preview.Destination.GooglePromotedId.DOCS; }, - /** @private {!Array<string>} */ - users_: Array, - }, - - /** @private {string} */ - lastUser_: '', - - /** @private {!EventTracker} */ - tracker_: new EventTracker(), - - /** @override */ - attached: function() { - this.destinationStore_ = - new print_preview.DestinationStore(this.addWebUIListener.bind(this)); - this.invitationStore_ = new print_preview.InvitationStore(); - this.tracker_.add( - this.destinationStore_, - print_preview.DestinationStore.EventType.DESTINATION_SELECT, - this.onDestinationSelect_.bind(this)); - this.tracker_.add( - this.destinationStore_, - print_preview.DestinationStore.EventType - .SELECTED_DESTINATION_CAPABILITIES_READY, - this.onDestinationCapabilitiesReady_.bind(this)); - this.tracker_.add( - this.destinationStore_, print_preview.DestinationStore.EventType.ERROR, - this.onDestinationError_.bind(this)); - // Need to update the recent list when the destination store inserts - // destinations, in case any recent destinations have been added to the - // store. At startup, recent destinations can be in the sticky settings, - // but they should not be displayed in the dropdown until they have been - // fetched by the DestinationStore, to ensure that they still exist. - this.tracker_.add( - assert(this.destinationStore_), - print_preview.DestinationStore.EventType.DESTINATIONS_INSERTED, - this.updateDropdownDestinations_.bind(this)); - }, - - /** @override */ - detached: function() { - this.invitationStore_.resetTracker(); - this.destinationStore_.resetTracker(); - this.tracker_.removeAll(); - }, - - /** @private */ - onCloudPrintInterfaceSet_: function() { - const cloudPrintInterface = assert(this.cloudPrintInterface); - this.destinationStore_.setCloudPrintInterface(cloudPrintInterface); - this.invitationStore_.setCloudPrintInterface(cloudPrintInterface); - }, - - /** @private */ - onActiveUserChanged_: function() { - // Re-filter the dropdown destinations for the new account. - if (!this.isDialogOpen_) { - // Don't update the destination settings UI while the dialog is open in - // front of it. - this.updateDropdownDestinations_(); - } - - if (!this.destination || - this.destination.origin !== print_preview.DestinationOrigin.COOKIES) { - // Active user changing doesn't impact non-cookie based destinations. - return; - } - - if (this.destination.account === this.activeUser_) { - // If the current destination belongs to the new account and the dialog - // was waiting for sign in, update the state. - if (this.destinationState === print_preview.DestinationState.SELECTED) { - this.destinationState = this.destination.capabilities ? - print_preview.DestinationState.UPDATED : - print_preview.DestinationState.SET; + /** @private */ + updateRecentDestinations_: function() { + if (!this.destination) { + return; } - return; - } - - if (this.isDialogOpen_) { - // Do not update the selected destination if the dialog is open, as this - // will change the destination settings UI behind the dialog, and the user - // may be selecting a new destination in the dialog anyway. Wait for the - // user to select a destination or cancel. - return; - } - - // Destination belongs to a different account. Reset the destination to the - // most recent destination associated with the new account, or the default. - const recent = this.displayedDestinations_.find(d => { - return d.origin !== print_preview.DestinationOrigin.COOKIES || - d.account === this.activeUser_; - }); - if (recent) { - const success = this.destinationStore_.selectRecentDestinationByKey( - print_preview.createRecentDestinationKey(recent), - this.displayedDestinations_); - if (success) { + + // Determine if this destination is already in the recent destinations, + // and where in the array it is located. + const newDestination = + print_preview.makeRecentDestination(assert(this.destination)); + const recentDestinations = + /** @type {!Array<!print_preview.RecentDestination>} */ ( + this.getSettingValue('recentDestinations')); + let indexFound = recentDestinations.findIndex(function(recent) { + return ( + newDestination.id == recent.id && + newDestination.origin == recent.origin); + }); + + // No change + if (indexFound == 0 && + recentDestinations[0].capabilities == newDestination.capabilities) { return; } - } - this.destinationStore_.selectDefaultDestination(); - }, - - /** - * @param {string} defaultPrinter The system default printer ID. - * @param {string} serializedDefaultDestinationRulesStr String with rules for - * selecting a default destination. - * @param {?Array<string>} userAccounts The signed in user accounts. - * @param {boolean} syncAvailable Whether sync is available. Used to determine - * whether to wait for user info updates from the handler, or to always - * send requests to the Google Cloud Print server. - */ - init: function( - defaultPrinter, serializedDefaultDestinationRulesStr, userAccounts, - syncAvailable) { - this.$.userManager.initUserAccounts(userAccounts, syncAvailable); - this.destinationStore_.init( - this.appKioskMode, defaultPrinter, serializedDefaultDestinationRulesStr, - /** @type {!Array<print_preview.RecentDestination>} */ - (this.getSettingValue('recentDestinations'))); - }, - - /** @private */ - onDestinationSelect_: function() { - // If the user selected a destination in the dialog after changing the - // active user, do the UI updates that were previously deferred. - if (this.isDialogOpen_ && this.lastUser_ !== this.activeUser_) { - this.updateDropdownDestinations_(); - } - - if (this.state === print_preview.State.FATAL_ERROR) { - // Don't let anything reset if there is a fatal error. - return; - } - - const destination = this.destinationStore_.selectedDestination; - if (!!this.activeUser_ || - destination.origin !== print_preview.DestinationOrigin.COOKIES) { - this.destinationState = print_preview.DestinationState.SET; - } else { - this.destinationState = print_preview.DestinationState.SELECTED; - } - // Notify observers that the destination is set only after updating the - // destinationState. - this.destination = destination; - this.updateRecentDestinations_(); - }, - - /** @private */ - onDestinationCapabilitiesReady_: function() { - this.notifyPath('destination.capabilities'); - this.updateRecentDestinations_(); - if (this.destinationState === print_preview.DestinationState.SET) { - this.destinationState = print_preview.DestinationState.UPDATED; - } - }, - - /** - * @param {!CustomEvent<!print_preview.DestinationErrorType>} e - * @private - */ - onDestinationError_: function(e) { - let errorType = print_preview.Error.NONE; - switch (e.detail) { - case print_preview.DestinationErrorType.INVALID: - errorType = print_preview.Error.INVALID_PRINTER; - break; - case print_preview.DestinationErrorType.UNSUPPORTED: - errorType = print_preview.Error.UNSUPPORTED_PRINTER; - break; - // <if expr="chromeos"> - case print_preview.DestinationErrorType.NO_DESTINATIONS: - errorType = print_preview.Error.NO_DESTINATIONS; - this.noDestinations_ = true; - break; - // </if> - default: - break; - } - this.error = errorType; - }, - - /** @private */ - onErrorChanged_: function() { - if (this.error == print_preview.Error.INVALID_PRINTER || - this.error == print_preview.Error.UNSUPPORTED_PRINTER || - this.error == print_preview.Error.NO_DESTINATIONS) { - this.destinationState = print_preview.DestinationState.ERROR; - } - }, - - /** - * @param {!print_preview.RecentDestination} destination - * @return {boolean} Whether the destination is Save as PDF or Save to Drive. - */ - destinationIsDriveOrPdf_: function(destination) { - return destination.id === - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF || - destination.id === print_preview.Destination.GooglePromotedId.DOCS; - }, - - /** @private */ - updateRecentDestinations_: function() { - if (!this.destination) { - return; - } - - // Determine if this destination is already in the recent destinations, - // and where in the array it is located. - const newDestination = - print_preview.makeRecentDestination(assert(this.destination)); - const recentDestinations = - /** @type {!Array<!print_preview.RecentDestination>} */ ( - this.getSettingValue('recentDestinations')); - let indexFound = recentDestinations.findIndex(function(recent) { - return ( - newDestination.id == recent.id && - newDestination.origin == recent.origin); - }); - - // No change - if (indexFound == 0 && - recentDestinations[0].capabilities == newDestination.capabilities) { - return; - } - const isNew = indexFound == -1; - - // Shift the array so that the nth most recent destination is located at - // index n. - if (isNew && recentDestinations.length == NUM_PERSISTED_DESTINATIONS) { - indexFound = NUM_PERSISTED_DESTINATIONS - 1; - } - if (indexFound != -1) { - this.setSettingSplice('recentDestinations', indexFound, 1, null); - } - - // Add the most recent destination - this.setSettingSplice('recentDestinations', 0, 0, newDestination); - if (!this.destinationIsDriveOrPdf_(newDestination) && isNew) { - this.updateDropdownDestinations_(); - } - }, - - /** @private */ - updateDropdownDestinations_: function() { - this.displayedDestinations_ = - /** @type {!Array<!print_preview.RecentDestination>} */ ( - this.getSettingValue('recentDestinations')) - .filter(d => { - return !this.destinationIsDriveOrPdf_(d) && - (d.origin !== print_preview.DestinationOrigin.COOKIES || - d.account === this.activeUser_); - }); - }, - - /** - * @return {boolean} Whether the destinations dropdown should be disabled. - * @private - */ - shouldDisableDropdown_: function() { - return this.state === print_preview.State.FATAL_ERROR || - (this.destinationState === print_preview.DestinationState.UPDATED && - this.disabled && this.state !== print_preview.State.NOT_READY); - }, - - /** @private */ - computeShouldHideSpinner_: function() { - return this.destinationState === print_preview.DestinationState.ERROR || - this.destinationState === print_preview.DestinationState.UPDATED || - (this.destinationState === print_preview.DestinationState.SET && - !!this.destination && - (!!this.destination.capabilities || - this.destination.id === - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF)); - }, - - /** - * @return {string} The connection status text to display. - * @private - */ - computeStatusText_: function() { - // |destination| can be either undefined, or null here. - if (!this.destination) { - return ''; - } - - return this.destination.shouldShowInvalidCertificateError ? - this.i18n('noLongerSupportedFragment') : - this.destination.connectionStatusText; - }, - - // <if expr="chromeos"> - /** - * @return {boolean} - * @private - */ - computeHasPinSetting_: function() { - return this.getSetting('pin').available; - }, - // </if> - - /** - * @param {!CustomEvent<string>} e Event containing the key of the recent - * destination that was selected, or "seeMore". - * @private - */ - onSelectedDestinationOptionChange_: function(e) { - const value = e.detail; - if (value === 'seeMore') { - this.destinationStore_.startLoadAllDestinations(); - if (this.activeUser_) { - this.invitationStore_.startLoadingInvitations(this.activeUser_); + const isNew = indexFound == -1; + + // Shift the array so that the nth most recent destination is located at + // index n. + if (isNew && recentDestinations.length == NUM_PERSISTED_DESTINATIONS) { + indexFound = NUM_PERSISTED_DESTINATIONS - 1; + } + if (indexFound != -1) { + this.setSettingSplice('recentDestinations', indexFound, 1, null); } - this.$.destinationDialog.get().show(); - this.lastUser_ = this.activeUser_; - this.isDialogOpen_ = true; - } else { - const success = this.destinationStore_.selectRecentDestinationByKey( - value, this.displayedDestinations_); - if (!success) { - this.error = print_preview.Error.INVALID_PRINTER; + + // Add the most recent destination + this.setSettingSplice('recentDestinations', 0, 0, newDestination); + if (!this.destinationIsDriveOrPdf_(newDestination) && isNew) { + this.updateDropdownDestinations_(); } - } - }, - - /** - * @param {!CustomEvent<string>} e Event containing the new active user - * account. - * @private - */ - onAccountChange_: function(e) { - this.$.userManager.updateActiveUser(e.detail, true); - }, - - /** @private */ - onDialogClose_: function() { - // Reset the select value if the user dismissed the dialog without - // selecting a new destination. - if (this.lastUser_ != this.activeUser_) { - this.updateDropdownDestinations_(); - } - this.updateDestinationSelect_(); - this.isDialogOpen_ = false; - }, - - /** @private */ - updateDestinationSelect_: function() { + }, + + /** @private */ + updateDropdownDestinations_: function() { + this.displayedDestinations_ = + /** @type {!Array<!print_preview.RecentDestination>} */ ( + this.getSettingValue('recentDestinations')) + .filter(d => { + return !this.destinationIsDriveOrPdf_(d) && + (d.origin !== print_preview.DestinationOrigin.COOKIES || + d.account === this.activeUser_); + }); + }, + + /** + * @return {boolean} Whether the destinations dropdown should be disabled. + * @private + */ + shouldDisableDropdown_: function() { + return this.state === print_preview.State.FATAL_ERROR || + (this.destinationState === DestinationState.UPDATED && + this.disabled && this.state !== print_preview.State.NOT_READY); + }, + + /** @private */ + computeShouldHideSpinner_: function() { + return this.destinationState === DestinationState.ERROR || + this.destinationState === DestinationState.UPDATED || + (this.destinationState === DestinationState.SET && + !!this.destination && + (!!this.destination.capabilities || + this.destination.id === + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF)); + }, + + /** + * @return {string} The connection status text to display. + * @private + */ + computeStatusText_: function() { + // |destination| can be either undefined, or null here. + if (!this.destination) { + return ''; + } + + return this.destination.shouldShowInvalidCertificateError ? + this.i18n('noLongerSupportedFragment') : + this.destination.connectionStatusText; + }, + // <if expr="chromeos"> - if (this.destinationState === print_preview.DestinationState.ERROR && - !this.destination) { - return; - } + /** + * @return {boolean} + * @private + */ + computeHasPinSetting_: function() { + return this.getSetting('pin').available; + }, // </if> - if (this.destinationState === print_preview.DestinationState.INIT || - this.destinationState === print_preview.DestinationState.SELECTED) { - return; - } - - const shouldFocus = - this.destinationState !== print_preview.DestinationState.SET && - !this.firstLoad; - Polymer.RenderStatus.beforeNextRender(this.$.destinationSelect, () => { - this.$.destinationSelect.updateDestination(); - if (shouldFocus) { - this.$.destinationSelect.focus(); + /** + * @param {!CustomEvent<string>} e Event containing the key of the recent + * destination that was selected, or "seeMore". + * @private + */ + onSelectedDestinationOptionChange_: function(e) { + const value = e.detail; + if (value === 'seeMore') { + this.destinationStore_.startLoadAllDestinations(); + if (this.activeUser_) { + this.invitationStore_.startLoadingInvitations(this.activeUser_); + } + this.$.destinationDialog.get().show(); + this.lastUser_ = this.activeUser_; + this.isDialogOpen_ = true; + } else { + const success = this.destinationStore_.selectRecentDestinationByKey( + value, this.displayedDestinations_); + if (!success) { + this.error = print_preview.Error.INVALID_PRINTER; + } } - }); - }, + }, + + /** + * @param {!CustomEvent<string>} e Event containing the new active user + * account. + * @private + */ + onAccountChange_: function(e) { + this.$.userManager.updateActiveUser(e.detail, true); + }, + + /** @private */ + onDialogClose_: function() { + // Reset the select value if the user dismissed the dialog without + // selecting a new destination. + if (this.lastUser_ != this.activeUser_) { + this.updateDropdownDestinations_(); + } + this.updateDestinationSelect_(); + this.isDialogOpen_ = false; + }, + + /** @private */ + updateDestinationSelect_: function() { + // <if expr="chromeos"> + if (this.destinationState === DestinationState.ERROR && + !this.destination) { + return; + } + // </if> + + if (this.destinationState === DestinationState.INIT || + this.destinationState === DestinationState.SELECTED) { + return; + } + + const shouldFocus = + this.destinationState !== DestinationState.SET && !this.firstLoad; + Polymer.RenderStatus.beforeNextRender(this.$.destinationSelect, () => { + this.$.destinationSelect.updateDestination(); + if (shouldFocus) { + this.$.destinationSelect.focus(); + } + }); + }, + }); + + return { + DestinationState: DestinationState, + }; }); -})(); diff --git a/chromium/chrome/browser/resources/print_preview/ui/highlight_utils.js b/chromium/chrome/browser/resources/print_preview/ui/highlight_utils.js index f88c99430ed..07fc9719c2e 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/highlight_utils.js +++ b/chromium/chrome/browser/resources/print_preview/ui/highlight_utils.js @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); -/** - * @typedef {{ - * highlights: !Array<!Node>, - * bubbles: !Array<!Node> - * }} - */ -print_preview.HighlightResults; cr.define('print_preview', function() { 'use strict'; /** + * @typedef {{ + * highlights: !Array<!Node>, + * bubbles: !Array<!Node> + * }} + */ + let HighlightResults; + + /** * @param {!HTMLElement} element The element to update. Element should have a * shadow root. * @param {?RegExp} query The current search query @@ -65,6 +65,7 @@ cr.define('print_preview', function() { } return { + HighlightResults: HighlightResults, updateHighlights: updateHighlights, }; }); diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control.html b/chromium/chrome/browser/resources/print_preview/ui/margin_control.html index 4aa2d7e9dc9..2d21005cf9e 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/margin_control.html +++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control.html @@ -70,7 +70,6 @@ overflow: hidden; padding: 1px; position: absolute; - width: 60px; } @media (prefers-color-scheme: light) { @@ -136,6 +135,7 @@ #input { padding-inline-end: 0; text-align: end; + width: 44px; } #unit { diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control.js b/chromium/chrome/browser/resources/print_preview/ui/margin_control.js index d3ccb88904f..0e9dca3478f 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/margin_control.js +++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control.js @@ -180,22 +180,22 @@ Polymer({ * @private */ parseValueToPts_: function(value) { - // Removing whitespace anywhere in the string. - value = value.replace(/\s*/g, ''); + value = value.trim(); if (value.length == 0) { return null; } assert(this.measurementSystem); - const decimal = this.measurementSystem.decimalDelimeter; - const thousands = this.measurementSystem.thousandsDelimeter; - const validationRegex = new RegExp( - `^(^-?)(((\\d)(\\${thousands}\\d{3})*)(\\${decimal}\\d*)?|` + - `((\\d)?(\\${thousands}\\d{3})*)(\\${decimal}\\d*))`); + const decimal = this.measurementSystem.decimalDelimiter; + const thousands = this.measurementSystem.thousandsDelimiter; + const whole = `(?:0|[1-9]\\d*|[1-9]\\d{0,2}(?:[${thousands}]\\d{3})*)`; + const fractional = `(?:[${decimal}]\\d*)`; + const validationRegex = + new RegExp(`^-?(?:${whole}${fractional}?|${fractional})$`); if (validationRegex.test(value)) { - // Replacing decimal point with the dot symbol in order to use - // parseFloat() properly. - value = value.replace(new RegExp(`\\${decimal}{1}`), '.'); - value = value.replace(new RegExp(`\\${thousands}`, 'g'), ''); + // Removing thousands delimiters and replacing the decimal delimiter with + // the dot symbol in order to use parseFloat() properly. + value = value.replace(new RegExp(`\\${thousands}`, 'g'), '') + .replace(decimal, '.'); return this.measurementSystem.convertToPoints(parseFloat(value)); } return null; @@ -211,7 +211,9 @@ Polymer({ assert(this.measurementSystem); value = this.measurementSystem.convertFromPoints(value); value = this.measurementSystem.roundValue(value); - return value.toString(); + // Convert the dot symbol to the decimal delimiter for the locale. + return value.toString().replace( + '.', this.measurementSystem.decimalDelimiter); }, /** diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js b/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js index eb6adf25058..b507fc864bb 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js +++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js @@ -2,538 +2,546 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); - -/** - * @const {!Map<!print_preview.ticket_items.CustomMarginsOrientation, string>} - */ -print_preview.MARGIN_KEY_MAP = new Map([ - [print_preview.ticket_items.CustomMarginsOrientation.TOP, 'marginTop'], - [print_preview.ticket_items.CustomMarginsOrientation.RIGHT, 'marginRight'], - [print_preview.ticket_items.CustomMarginsOrientation.BOTTOM, 'marginBottom'], - [print_preview.ticket_items.CustomMarginsOrientation.LEFT, 'marginLeft'] -]); - -(function() { -'use strict'; - -/** @const {number} */ -const MINIMUM_DISTANCE = 72; // 1 inch - -Polymer({ - is: 'print-preview-margin-control-container', - - behaviors: [SettingsBehavior], - - properties: { - /** @type {!print_preview.Size} */ - pageSize: { - type: Object, - notify: true, - }, - /** @type {!print_preview.Margins} */ - documentMargins: { - type: Object, - notify: true, +cr.define('print_preview', function() { + 'use strict'; + + /** + * @const {!Map<!print_preview.ticket_items.CustomMarginsOrientation, string>} + */ + const MARGIN_KEY_MAP = new Map([ + [print_preview.ticket_items.CustomMarginsOrientation.TOP, 'marginTop'], + [print_preview.ticket_items.CustomMarginsOrientation.RIGHT, 'marginRight'], + [ + print_preview.ticket_items.CustomMarginsOrientation.BOTTOM, 'marginBottom' + ], + [print_preview.ticket_items.CustomMarginsOrientation.LEFT, 'marginLeft'] + ]); + + /** @const {number} */ + const MINIMUM_DISTANCE = 72; // 1 inch + + Polymer({ + is: 'print-preview-margin-control-container', + + behaviors: [SettingsBehavior], + + properties: { + /** @type {!print_preview.Size} */ + pageSize: { + type: Object, + notify: true, + }, + + /** @type {!print_preview.Margins} */ + documentMargins: { + type: Object, + notify: true, + }, + + previewLoaded: Boolean, + + /** @type {?print_preview.MeasurementSystem} */ + measurementSystem: Object, + + /** @type {!print_preview.State} */ + state: { + type: Number, + observer: 'onStateChanged_', + }, + + /** @private {number} */ + scaleTransform_: { + type: Number, + notify: true, + value: 0, + }, + + /** @private {!print_preview.Coordinate2d} */ + translateTransform_: { + type: Object, + notify: true, + value: new print_preview.Coordinate2d(0, 0), + }, + + /** @private {?print_preview.Size} */ + clipSize_: { + type: Object, + notify: true, + value: null, + }, + + /** @private {boolean} */ + available_: { + type: Boolean, + notify: true, + computed: 'computeAvailable_(previewLoaded, settings.margins.value)', + observer: 'onAvailableChange_', + }, + + /** @private {boolean} */ + invisible_: { + type: Boolean, + reflectToAttribute: true, + value: true, + }, + + /** + * @private {!Array<!print_preview.ticket_items.CustomMarginsOrientation>} + */ + marginSides_: { + type: Array, + notify: true, + value: [ + print_preview.ticket_items.CustomMarginsOrientation.TOP, + print_preview.ticket_items.CustomMarginsOrientation.RIGHT, + print_preview.ticket_items.CustomMarginsOrientation.BOTTOM, + print_preview.ticket_items.CustomMarginsOrientation.LEFT, + ], + }, + + /** + * String attribute used to set cursor appearance. Possible values: + * empty (''): No margin control is currently being dragged. + * 'dragging-horizontal': The left or right control is being dragged. + * 'dragging-vertical': The top or bottom control is being dragged. + * @private {string} + */ + dragging_: { + type: String, + reflectToAttribute: true, + value: '', + }, }, - previewLoaded: Boolean, + /** @private {boolean} */ + textboxFocused_: false, - /** @type {?print_preview.MeasurementSystem} */ - measurementSystem: Object, + observers: [ + 'onMarginSettingsChange_(settings.customMargins.value)', + 'onMediaSizeOrLayoutChange_(' + + 'settings.mediaSize.value, settings.layout.value)', + ], - /** @type {!print_preview.State} */ - state: { - type: Number, - observer: 'onStateChanged_', - }, + /** @private {!print_preview.Coordinate2d} */ + pointerStartPositionInPixels_: new print_preview.Coordinate2d(0, 0), + + /** @private {?print_preview.Coordinate2d} */ + marginStartPositionInPixels_: null, + + /** @private {?boolean} */ + resetMargins_: null, - /** @private {number} */ - scaleTransform_: { - type: Number, - notify: true, - value: 0, + /** + * @return {boolean} + * @private + */ + computeAvailable_: function() { + return this.previewLoaded && !!this.clipSize_ && + this.getSettingValue('margins') == + print_preview.ticket_items.MarginsTypeValue.CUSTOM && + !!this.pageSize; }, - /** @private {!print_preview.Coordinate2d} */ - translateTransform_: { - type: Object, - notify: true, - value: new print_preview.Coordinate2d(0, 0), + /** @private */ + onAvailableChange_: function() { + if (this.available_ && this.resetMargins_) { + // Set the custom margins values to the current document margins if the + // custom margins were reset. + const newMargins = {}; + for (const side of Object.values( + print_preview.ticket_items.CustomMarginsOrientation)) { + const key = print_preview.MARGIN_KEY_MAP.get(side); + newMargins[key] = this.documentMargins.get(side); + } + this.setSetting('customMargins', newMargins); + this.resetMargins_ = false; + } + this.invisible_ = !this.available_; }, - /** @private {?print_preview.Size} */ - clipSize_: { - type: Object, - notify: true, - value: null, + /** @private */ + onMarginSettingsChange_: function() { + const margins = this.getSettingValue('customMargins'); + if (margins.marginTop === undefined) { + // This may be called when print preview model initially sets the + // settings. It sets custom margins empty by default. + return; + } + this.shadowRoot.querySelectorAll('print-preview-margin-control') + .forEach(control => { + const key = print_preview.MARGIN_KEY_MAP.get(control.side); + const newValue = margins[key] || 0; + control.setPositionInPts(newValue); + control.setTextboxValue(newValue); + }); }, - /** @private {boolean} */ - available_: { - type: Boolean, - notify: true, - computed: 'computeAvailable_(previewLoaded, settings.margins.value)', - observer: 'onAvailableChange_', + /** @private */ + onMediaSizeOrLayoutChange_: function() { + // Reset the custom margins when the paper size changes. Don't do this if + // it is the first preview. + if (this.resetMargins_ === null) { + return; + } + + this.resetMargins_ = true; + const marginsSetting = this.getSetting('margins'); + if (marginsSetting.value == + print_preview.ticket_items.MarginsTypeValue.CUSTOM) { + // Set the margins value to default first. + this.setSetting( + 'margins', print_preview.ticket_items.MarginsTypeValue.DEFAULT); + } + // Reset custom margins so that the sticky value is not restored for the + // new paper size. + this.setSetting('customMargins', {}); }, - /** @private {boolean} */ - invisible_: { - type: Boolean, - reflectToAttribute: true, - value: true, + /** @private */ + onStateChanged_: function() { + if (this.state == print_preview.State.READY && + this.resetMargins_ === null) { + // Don't reset margins if there are sticky values. Otherwise, set them + // to the document margins when the user selects custom margins. + this.resetMargins_ = + this.getSettingValue('customMargins').marginTop === undefined; + } }, /** - * @private {!Array<!print_preview.ticket_items.CustomMarginsOrientation>} + * @return {boolean} Whether the controls should be disabled. + * @private */ - marginSides_: { - type: Array, - notify: true, - value: [ - print_preview.ticket_items.CustomMarginsOrientation.TOP, - print_preview.ticket_items.CustomMarginsOrientation.RIGHT, - print_preview.ticket_items.CustomMarginsOrientation.BOTTOM, - print_preview.ticket_items.CustomMarginsOrientation.LEFT, - ], + controlsDisabled_: function() { + return this.state !== print_preview.State.READY || this.invisible_; }, /** - * String attribute used to set cursor appearance. Possible values: - * empty (''): No margin control is currently being dragged. - * 'dragging-horizontal': The left or right control is being dragged. - * 'dragging-vertical': The top or bottom control is being dragged. - * @private {string} + * @param {!print_preview.ticket_items.CustomMarginsOrientation} orientation + * Orientation value to test. + * @return {boolean} Whether the given orientation is TOP or BOTTOM. + * @private */ - dragging_: { - type: String, - reflectToAttribute: true, - value: '', + isTopOrBottom_: function(orientation) { + return orientation == + print_preview.ticket_items.CustomMarginsOrientation.TOP || + orientation == + print_preview.ticket_items.CustomMarginsOrientation.BOTTOM; }, - }, - /** @private {boolean} */ - textboxFocused_: false, + /** + * @param {!HTMLElement} control Control being repositioned. + * @param {!print_preview.Coordinate2d} posInPixels Desired position, in + * pixels. + * @return {number} The new position for the control, in pts. Returns the + * position for the dimension that the control operates in, i.e. + * x direction for the left/right controls, y direction otherwise. + * @private + */ + posInPixelsToPts_: function(control, posInPixels) { + const side = + /** @type {print_preview.ticket_items.CustomMarginsOrientation} */ ( + control.side); + return this.clipAndRoundValue_( + side, + control.convertPixelsToPts( + this.isTopOrBottom_(side) ? posInPixels.y : posInPixels.x)); + }, - observers: [ - 'onMarginSettingsChange_(settings.customMargins.value)', - 'onMediaSizeOrLayoutChange_(' + - 'settings.mediaSize.value, settings.layout.value)', - ], + /** + * Moves the position of the given control to the desired position in pts + * within some constraint minimum and maximum. + * @param {!HTMLElement} control Control to move. + * @param {number} posInPts Desired position to move to, in pts. Position is + * 1 dimensional and represents position in the x direction if control + * is for the left or right margin, and the y direction otherwise. + * @private + */ + moveControlWithConstraints_: function(control, posInPts) { + control.setPositionInPts(posInPts); + control.setTextboxValue(posInPts); + }, - /** @private {!print_preview.Coordinate2d} */ - pointerStartPositionInPixels_: new print_preview.Coordinate2d(0, 0), + /** + * Translates the position of the margin control relative to the pointer + * position in pixels. + * @param {!print_preview.Coordinate2d} pointerPosition New position of + * the pointer. + * @return {!print_preview.Coordinate2d} New position of the margin control. + */ + translatePointerToPositionInPixels: function(pointerPosition) { + return new print_preview.Coordinate2d( + pointerPosition.x - this.pointerStartPositionInPixels_.x + + this.marginStartPositionInPixels_.x, + pointerPosition.y - this.pointerStartPositionInPixels_.y + + this.marginStartPositionInPixels_.y); + }, - /** @private {?print_preview.Coordinate2d} */ - marginStartPositionInPixels_: null, + /** + * Called when the pointer moves in the custom margins component. Moves the + * dragged margin control. + * @param {!PointerEvent} event Contains the position of the pointer. + * @private + */ + onPointerMove_: function(event) { + const control = + /** @type {!PrintPreviewMarginControlElement} */ (event.target); + const posInPts = this.posInPixelsToPts_( + control, + this.translatePointerToPositionInPixels( + new print_preview.Coordinate2d(event.x, event.y))); + this.moveControlWithConstraints_(control, posInPts); + }, - /** @private {?boolean} */ - resetMargins_: null, + /** + * Called when the pointer is released in the custom margins component. + * Releases the dragged margin control. + * @param {!PointerEvent} event Contains the position of the pointer. + * @private + */ + onPointerUp_: function(event) { + const control = + /** @type {!PrintPreviewMarginControlElement} */ (event.target); + this.dragging_ = ''; + const posInPixels = this.translatePointerToPositionInPixels( + new print_preview.Coordinate2d(event.x, event.y)); + const posInPts = this.posInPixelsToPts_(control, posInPixels); + this.moveControlWithConstraints_(control, posInPts); + this.setMargin_(control.side, posInPts); + this.updateClippingMask(this.clipSize_); + this.unlisten(control, 'pointercancel', 'onPointerUp_'); + this.unlisten(control, 'pointerup', 'onPointerUp_'); + this.unlisten(control, 'pointermove', 'onPointerMove_'); + + this.fire('margin-drag-changed', false); + }, - /** - * @return {boolean} - * @private - */ - computeAvailable_: function() { - return this.previewLoaded && !!this.clipSize_ && - this.getSettingValue('margins') == - print_preview.ticket_items.MarginsTypeValue.CUSTOM && - !!this.pageSize; - }, - - /** @private */ - onAvailableChange_: function() { - if (this.available_ && this.resetMargins_) { - // Set the custom margins values to the current document margins if the - // custom margins were reset. - const newMargins = {}; - for (const side of Object.values( - print_preview.ticket_items.CustomMarginsOrientation)) { - const key = print_preview.MARGIN_KEY_MAP.get(side); - newMargins[key] = this.documentMargins.get(side); + /** + * @param {boolean} invisible Whether the margin controls should be + * invisible. + */ + setInvisible: function(invisible) { + // Ignore changes if the margin controls are not available. + if (!this.available_) { + return; } - this.setSetting('customMargins', newMargins); - this.resetMargins_ = false; - } - this.invisible_ = !this.available_; - }, - - /** @private */ - onMarginSettingsChange_: function() { - const margins = this.getSettingValue('customMargins'); - if (margins.marginTop === undefined) { - // This may be called when print preview model initially sets the - // settings. It sets custom margins empty by default. - return; - } - this.shadowRoot.querySelectorAll('print-preview-margin-control') - .forEach(control => { - const key = print_preview.MARGIN_KEY_MAP.get(control.side); - const newValue = margins[key] || 0; - control.setPositionInPts(newValue); - control.setTextboxValue(newValue); - }); - }, - - /** @private */ - onMediaSizeOrLayoutChange_: function() { - // Reset the custom margins when the paper size changes. Don't do this if it - // is the first preview. - if (this.resetMargins_ === null) { - return; - } - - this.resetMargins_ = true; - const marginsSetting = this.getSetting('margins'); - if (marginsSetting.value == - print_preview.ticket_items.MarginsTypeValue.CUSTOM) { - // Set the margins value to default first. - this.setSetting( - 'margins', print_preview.ticket_items.MarginsTypeValue.DEFAULT); - } - // Reset custom margins so that the sticky value is not restored for the new - // paper size. - this.setSetting('customMargins', {}); - }, - - /** @private */ - onStateChanged_: function() { - if (this.state == print_preview.State.READY && - this.resetMargins_ === null) { - // Don't reset margins if there are sticky values. Otherwise, set them to - // the document margins when the user selects custom margins. - this.resetMargins_ = - this.getSettingValue('customMargins').marginTop === undefined; - } - }, - - /** - * @return {boolean} Whether the controls should be disabled. - * @private - */ - controlsDisabled_: function() { - return this.state !== print_preview.State.READY || this.invisible_; - }, - - /** - * @param {!print_preview.ticket_items.CustomMarginsOrientation} orientation - * Orientation value to test. - * @return {boolean} Whether the given orientation is TOP or BOTTOM. - * @private - */ - isTopOrBottom_: function(orientation) { - return orientation == - print_preview.ticket_items.CustomMarginsOrientation.TOP || - orientation == - print_preview.ticket_items.CustomMarginsOrientation.BOTTOM; - }, - - /** - * @param {!HTMLElement} control Control being repositioned. - * @param {!print_preview.Coordinate2d} posInPixels Desired position, in - * pixels. - * @return {number} The new position for the control, in pts. Returns the - * position for the dimension that the control operates in, i.e. - * x direction for the left/right controls, y direction otherwise. - * @private - */ - posInPixelsToPts_: function(control, posInPixels) { - const side = - /** @type {print_preview.ticket_items.CustomMarginsOrientation} */ ( - control.side); - return this.clipAndRoundValue_( - side, - control.convertPixelsToPts( - this.isTopOrBottom_(side) ? posInPixels.y : posInPixels.x)); - }, - - /** - * Moves the position of the given control to the desired position in pts - * within some constraint minimum and maximum. - * @param {!HTMLElement} control Control to move. - * @param {number} posInPts Desired position to move to, in pts. Position is - * 1 dimensional and represents position in the x direction if control is - * for the left or right margin, and the y direction otherwise. - * @private - */ - moveControlWithConstraints_: function(control, posInPts) { - control.setPositionInPts(posInPts); - control.setTextboxValue(posInPts); - }, - - /** - * Translates the position of the margin control relative to the pointer - * position in pixels. - * @param {!print_preview.Coordinate2d} pointerPosition New position of - * the pointer. - * @return {!print_preview.Coordinate2d} New position of the margin control. - */ - translatePointerToPositionInPixels: function(pointerPosition) { - return new print_preview.Coordinate2d( - pointerPosition.x - this.pointerStartPositionInPixels_.x + - this.marginStartPositionInPixels_.x, - pointerPosition.y - this.pointerStartPositionInPixels_.y + - this.marginStartPositionInPixels_.y); - }, - /** - * Called when the pointer moves in the custom margins component. Moves the - * dragged margin control. - * @param {!PointerEvent} event Contains the position of the pointer. - * @private - */ - onPointerMove_: function(event) { - const control = - /** @type {!PrintPreviewMarginControlElement} */ (event.target); - const posInPts = this.posInPixelsToPts_( - control, - this.translatePointerToPositionInPixels( - new print_preview.Coordinate2d(event.x, event.y))); - this.moveControlWithConstraints_(control, posInPts); - }, - - /** - * Called when the pointer is released in the custom margins component. - * Releases the dragged margin control. - * @param {!PointerEvent} event Contains the position of the pointer. - * @private - */ - onPointerUp_: function(event) { - const control = - /** @type {!PrintPreviewMarginControlElement} */ (event.target); - this.dragging_ = ''; - const posInPixels = this.translatePointerToPositionInPixels( - new print_preview.Coordinate2d(event.x, event.y)); - const posInPts = this.posInPixelsToPts_(control, posInPixels); - this.moveControlWithConstraints_(control, posInPts); - this.setMargin_(control.side, posInPts); - this.updateClippingMask(this.clipSize_); - this.unlisten(control, 'pointercancel', 'onPointerUp_'); - this.unlisten(control, 'pointerup', 'onPointerUp_'); - this.unlisten(control, 'pointermove', 'onPointerMove_'); - - this.fire('margin-drag-changed', false); - }, + // Do not set the controls invisible if the user is dragging or focusing + // the textbox for one of them. + if (invisible && (this.dragging_ != '' || this.textboxFocused_)) { + return; + } - /** - * @param {boolean} invisible Whether the margin controls should be - * invisible. - */ - setInvisible: function(invisible) { - // Ignore changes if the margin controls are not available. - if (!this.available_) { - return; - } + this.invisible_ = invisible; + }, - // Do not set the controls invisible if the user is dragging or focusing - // the textbox for one of them. - if (invisible && (this.dragging_ != '' || this.textboxFocused_)) { - return; - } + /** + * @param {!Event} e Contains information about what control fired the + * event. + * @private + */ + onTextFocus_: function(e) { + this.textboxFocused_ = true; + const control = + /** @type {!PrintPreviewMarginControlElement} */ (e.target); - this.invisible_ = invisible; - }, + const x = control.offsetLeft; + const y = control.offsetTop; + const isTopOrBottom = this.isTopOrBottom_( + /** @type {!print_preview.ticket_items.CustomMarginsOrientation} */ ( + control.side)); + const position = {}; + // Extra padding, in px, to ensure the full textbox will be visible and + // not just a portion of it. Can't be less than half the width or height + // of the clip area for the computations below to work. + const padding = Math.min( + Math.min(this.clipSize_.width / 2, this.clipSize_.height / 2), 50); + + // Note: clipSize_ gives the current visible area of the margin control + // container. The offsets of the controls are relative to the origin of + // this visible area. + if (isTopOrBottom) { + // For top and bottom controls, the horizontal position of the box is + // around halfway across the control's width. + position.x = Math.min(x + control.offsetWidth / 2 - padding, 0); + position.x = Math.max( + x + control.offsetWidth / 2 + padding - this.clipSize_.width, + position.x); + // For top and bottom controls, the vertical position of the box is + // nearly the same as the vertical position of the control. + position.y = Math.min(y - padding, 0); + position.y = Math.max(y - this.clipSize_.height + padding, position.y); + } else { + // For left and right controls, the horizontal position of the box is + // nearly the same as the horizontal position of the control. + position.x = Math.min(x - padding, 0); + position.x = Math.max(x - this.clipSize_.width + padding, position.x); + // For top and bottom controls, the vertical position of the box is + // around halfway up the control's height. + position.y = Math.min(y + control.offsetHeight / 2 - padding, 0); + position.y = Math.max( + y + control.offsetHeight / 2 + padding - this.clipSize_.height, + position.y); + } - /** - * @param {!Event} e Contains information about what control fired the event. - * @private - */ - onTextFocus_: function(e) { - this.textboxFocused_ = true; - const control = /** @type {!PrintPreviewMarginControlElement} */ (e.target); - - const x = control.offsetLeft; - const y = control.offsetTop; - const isTopOrBottom = this.isTopOrBottom_( - /** @type {!print_preview.ticket_items.CustomMarginsOrientation} */ ( - control.side)); - const position = {}; - // Extra padding, in px, to ensure the full textbox will be visible and not - // just a portion of it. Can't be less than half the width or height of the - // clip area for the computations below to work. - const padding = Math.min( - Math.min(this.clipSize_.width / 2, this.clipSize_.height / 2), 50); - - // Note: clipSize_ gives the current visible area of the margin control - // container. The offsets of the controls are relative to the origin of this - // visible area. - if (isTopOrBottom) { - // For top and bottom controls, the horizontal position of the box is - // around halfway across the control's width. - position.x = Math.min(x + control.offsetWidth / 2 - padding, 0); - position.x = Math.max( - x + control.offsetWidth / 2 + padding - this.clipSize_.width, - position.x); - // For top and bottom controls, the vertical position of the box is nearly - // the same as the vertical position of the control. - position.y = Math.min(y - padding, 0); - position.y = Math.max(y - this.clipSize_.height + padding, position.y); - } else { - // For left and right controls, the horizontal position of the box is - // nearly the same as the horizontal position of the control. - position.x = Math.min(x - padding, 0); - position.x = Math.max(x - this.clipSize_.width + padding, position.x); - // For top and bottom controls, the vertical position of the box is - // around halfway up the control's height. - position.y = Math.min(y + control.offsetHeight / 2 - padding, 0); - position.y = Math.max( - y + control.offsetHeight / 2 + padding - this.clipSize_.height, - position.y); - } - - this.fire('text-focus-position', position); - }, + this.fire('text-focus-position', position); + }, - /** - * @param {string} side The margin side. Must be a CustomMarginsOrientation. - * @param {number} marginValue New value for the margin in points. - * @private - */ - setMargin_: function(side, marginValue) { - const marginSide = - /** @type {!print_preview.ticket_items.CustomMarginsOrientation} */ ( - side); - const oldMargins = /** @type {print_preview.MarginsSetting} */ ( - this.getSettingValue('customMargins')); - const key = print_preview.MARGIN_KEY_MAP.get(marginSide); - if (oldMargins[key] == marginValue) { - return; - } - const newMargins = Object.assign({}, oldMargins); - newMargins[key] = marginValue; - this.setSetting('customMargins', newMargins); - }, + /** + * @param {string} side The margin side. Must be a CustomMarginsOrientation. + * @param {number} marginValue New value for the margin in points. + * @private + */ + setMargin_: function(side, marginValue) { + const marginSide = + /** @type {!print_preview.ticket_items.CustomMarginsOrientation} */ ( + side); + const oldMargins = /** @type {print_preview.MarginsSetting} */ ( + this.getSettingValue('customMargins')); + const key = print_preview.MARGIN_KEY_MAP.get(marginSide); + if (oldMargins[key] == marginValue) { + return; + } + const newMargins = Object.assign({}, oldMargins); + newMargins[key] = marginValue; + this.setSetting('customMargins', newMargins); + }, - /** - * @param {string} side The margin side. Must be a CustomMarginsOrientation. - * @param {number} value The new margin value in points. - * @return {number} The clipped margin value in points. - * @private - */ - clipAndRoundValue_: function(side, value) { - const marginSide = - /** @type {!print_preview.ticket_items.CustomMarginsOrientation} */ ( - side); - if (value < 0) { - return 0; - } - const Orientation = print_preview.ticket_items.CustomMarginsOrientation; - let limit = 0; - const margins = this.getSettingValue('customMargins'); - if (marginSide == Orientation.TOP) { - limit = this.pageSize.height - margins.marginBottom - MINIMUM_DISTANCE; - } else if (marginSide == Orientation.RIGHT) { - limit = this.pageSize.width - margins.marginLeft - MINIMUM_DISTANCE; - } else if (marginSide == Orientation.BOTTOM) { - limit = this.pageSize.height - margins.marginTop - MINIMUM_DISTANCE; - } else { - assert(marginSide == Orientation.LEFT); - limit = this.pageSize.width - margins.marginRight - MINIMUM_DISTANCE; - } - return Math.round(Math.min(value, limit)); - }, + /** + * @param {string} side The margin side. Must be a CustomMarginsOrientation. + * @param {number} value The new margin value in points. + * @return {number} The clipped margin value in points. + * @private + */ + clipAndRoundValue_: function(side, value) { + const marginSide = + /** @type {!print_preview.ticket_items.CustomMarginsOrientation} */ ( + side); + if (value < 0) { + return 0; + } + const Orientation = print_preview.ticket_items.CustomMarginsOrientation; + let limit = 0; + const margins = this.getSettingValue('customMargins'); + if (marginSide == Orientation.TOP) { + limit = this.pageSize.height - margins.marginBottom - MINIMUM_DISTANCE; + } else if (marginSide == Orientation.RIGHT) { + limit = this.pageSize.width - margins.marginLeft - MINIMUM_DISTANCE; + } else if (marginSide == Orientation.BOTTOM) { + limit = this.pageSize.height - margins.marginTop - MINIMUM_DISTANCE; + } else { + assert(marginSide == Orientation.LEFT); + limit = this.pageSize.width - margins.marginRight - MINIMUM_DISTANCE; + } + return Math.round(Math.min(value, limit)); + }, - /** - * @param {!CustomEvent<number>} e Event containing the new textbox value. - * @private - */ - onTextChange_: function(e) { - const control = - /** @type {!PrintPreviewMarginControlElement} */ (e.target); - control.invalid = false; - const clippedValue = this.clipAndRoundValue_(control.side, e.detail); - control.setPositionInPts(clippedValue); - this.setMargin_(control.side, clippedValue); - }, + /** + * @param {!CustomEvent<number>} e Event containing the new textbox value. + * @private + */ + onTextChange_: function(e) { + const control = + /** @type {!PrintPreviewMarginControlElement} */ (e.target); + control.invalid = false; + const clippedValue = this.clipAndRoundValue_(control.side, e.detail); + control.setPositionInPts(clippedValue); + this.setMargin_(control.side, clippedValue); + }, - /** - * @param {!CustomEvent<boolean>} e Event fired when a control's text field - * is blurred. Contains information about whether the control is in an - * invalid state. - * @private - */ - onTextBlur_: function(e) { - if (e.detail /* detail is true if the control is in an invalid state */) { + /** + * @param {!CustomEvent<boolean>} e Event fired when a control's text field + * is blurred. Contains information about whether the control is in an + * invalid state. + * @private + */ + onTextBlur_: function(e) { const control = /** @type {!PrintPreviewMarginControlElement} */ (e.target); control.setTextboxValue(control.getPositionInPts()); - control.invalid = false; - } - this.textboxFocused_ = false; - }, + if (e.detail /* detail is true if the control is in an invalid state */) { + control.invalid = false; + } + this.textboxFocused_ = false; + }, - /** - * @param {!PointerEvent} e Fired when pointerdown occurs on a margin control. - * @private - */ - onPointerDown_: function(e) { - const control = - /** @type {!PrintPreviewMarginControlElement} */ (e.target); - if (!control.shouldDrag(e)) { - return; - } - - this.pointerStartPositionInPixels_ = - new print_preview.Coordinate2d(e.x, e.y); - this.marginStartPositionInPixels_ = - new print_preview.Coordinate2d(control.offsetLeft, control.offsetTop); - this.dragging_ = - this.isTopOrBottom_( - /** @type {print_preview.ticket_items.CustomMarginsOrientation} */ ( - control.side)) ? - 'dragging-vertical' : - 'dragging-horizontal'; - this.listen(control, 'pointercancel', 'onPointerUp_'); - this.listen(control, 'pointerup', 'onPointerUp_'); - this.listen(control, 'pointermove', 'onPointerMove_'); - control.setPointerCapture(e.pointerId); - - this.fire('margin-drag-changed', true); - }, + /** + * @param {!PointerEvent} e Fired when pointerdown occurs on a margin + * control. + * @private + */ + onPointerDown_: function(e) { + const control = + /** @type {!PrintPreviewMarginControlElement} */ (e.target); + if (!control.shouldDrag(e)) { + return; + } - /** - * Set display:none after the opacity transition for the controls is done. - * @private - */ - onTransitionEnd_: function() { - if (this.invisible_) { - this.style.display = 'none'; - } - }, + this.pointerStartPositionInPixels_ = + new print_preview.Coordinate2d(e.x, e.y); + this.marginStartPositionInPixels_ = + new print_preview.Coordinate2d(control.offsetLeft, control.offsetTop); + this.dragging_ = + this.isTopOrBottom_( + /** @type {print_preview.ticket_items.CustomMarginsOrientation} */ + (control.side)) ? + 'dragging-vertical' : + 'dragging-horizontal'; + this.listen(control, 'pointercancel', 'onPointerUp_'); + this.listen(control, 'pointerup', 'onPointerUp_'); + this.listen(control, 'pointermove', 'onPointerMove_'); + control.setPointerCapture(e.pointerId); + + this.fire('margin-drag-changed', true); + }, - /** - * Updates the translation transformation that translates pixel values in - * the space of the HTML DOM. - * @param {print_preview.Coordinate2d} translateTransform Updated value of - * the translation transformation. - */ - updateTranslationTransform: function(translateTransform) { - if (!translateTransform.equals(this.translateTransform_)) { - this.translateTransform_ = translateTransform; - } - }, + /** + * Set display:none after the opacity transition for the controls is done. + * @private + */ + onTransitionEnd_: function() { + if (this.invisible_) { + this.style.display = 'none'; + } + }, - /** - * Updates the scaling transform that scales pixels values to point values. - * @param {number} scaleTransform Updated value of the scale transform. - */ - updateScaleTransform: function(scaleTransform) { - if (scaleTransform != this.scaleTransform_) { - this.scaleTransform_ = scaleTransform; - } - }, + /** + * Updates the translation transformation that translates pixel values in + * the space of the HTML DOM. + * @param {print_preview.Coordinate2d} translateTransform Updated value of + * the translation transformation. + */ + updateTranslationTransform: function(translateTransform) { + if (!translateTransform.equals(this.translateTransform_)) { + this.translateTransform_ = translateTransform; + } + }, - /** - * Clips margin controls to the given clip size in pixels. - * @param {print_preview.Size} clipSize Size to clip the margin controls to. - */ - updateClippingMask: function(clipSize) { - if (!clipSize) { - return; - } - this.clipSize_ = clipSize; - this.notifyPath('clipSize_'); - }, + /** + * Updates the scaling transform that scales pixels values to point values. + * @param {number} scaleTransform Updated value of the scale transform. + */ + updateScaleTransform: function(scaleTransform) { + if (scaleTransform != this.scaleTransform_) { + this.scaleTransform_ = scaleTransform; + } + }, + + /** + * Clips margin controls to the given clip size in pixels. + * @param {print_preview.Size} clipSize Size to clip the margin controls to. + */ + updateClippingMask: function(clipSize) { + if (!clipSize) { + return; + } + this.clipSize_ = clipSize; + this.notifyPath('clipSize_'); + }, + }); + + return { + MARGIN_KEY_MAP: MARGIN_KEY_MAP, + }; }); -})(); diff --git a/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js b/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js index d4e1c49cfc0..3ed597c639c 100644 --- a/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js +++ b/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js @@ -2,42 +2,41 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.exportPath('print_preview'); -/** - * @typedef {{accessibility: Function, - * documentLoadComplete: Function, - * getHeight: Function, - * getHorizontalScrollbarThickness: Function, - * getPageLocationNormalized: Function, - * getVerticalScrollbarThickness: Function, - * getWidth: Function, - * getZoomLevel: Function, - * goToPage: Function, - * grayscale: Function, - * loadPreviewPage: Function, - * onload: Function, - * onPluginSizeChanged: Function, - * onScroll: Function, - * pageXOffset: Function, - * pageYOffset: Function, - * reload: Function, - * resetPrintPreviewMode: Function, - * sendKeyEvent: Function, - * setPageNumbers: Function, - * setPageXOffset: Function, - * setPageYOffset: Function, - * setZoomLevel: Function, - * fitToHeight: Function, - * fitToWidth: Function, - * zoomIn: Function, - * zoomOut: Function}} - */ -print_preview.PDFPlugin; - cr.define('print_preview', function() { 'use strict'; /** + * @typedef {{accessibility: Function, + * documentLoadComplete: Function, + * getHeight: Function, + * getHorizontalScrollbarThickness: Function, + * getPageLocationNormalized: Function, + * getVerticalScrollbarThickness: Function, + * getWidth: Function, + * getZoomLevel: Function, + * goToPage: Function, + * grayscale: Function, + * loadPreviewPage: Function, + * onload: Function, + * onPluginSizeChanged: Function, + * onScroll: Function, + * pageXOffset: Function, + * pageYOffset: Function, + * reload: Function, + * resetPrintPreviewMode: Function, + * sendKeyEvent: Function, + * setPageNumbers: Function, + * setPageXOffset: Function, + * setPageYOffset: Function, + * setZoomLevel: Function, + * fitToHeight: Function, + * fitToWidth: Function, + * zoomIn: Function, + * zoomOut: Function}} + */ + let PDFPlugin; + + /** * An interface to the PDF plugin. */ class PluginProxy { @@ -185,5 +184,8 @@ cr.define('print_preview', function() { let instance = null; // Export - return {PluginProxy: PluginProxy}; + return { + PDFPlugin: PDFPlugin, + PluginProxy: PluginProxy, + }; }); diff --git a/chromium/chrome/browser/resources/protobufs/OWNERS b/chromium/chrome/browser/resources/protobufs/OWNERS index 27806953f99..f93bbac403b 100644 --- a/chromium/chrome/browser/resources/protobufs/OWNERS +++ b/chromium/chrome/browser/resources/protobufs/OWNERS @@ -1,2 +1,4 @@ +drubery@chromium.org meacer@chromium.org -nparker@chromium.org
\ No newline at end of file +nparker@chromium.org +vakh@chromium.org diff --git a/chromium/chrome/browser/resources/reset_password/BUILD.gn b/chromium/chrome/browser/resources/reset_password/BUILD.gn index 2a2f75f6e12..d464dd90c25 100644 --- a/chromium/chrome/browser/resources/reset_password/BUILD.gn +++ b/chromium/chrome/browser/resources/reset_password/BUILD.gn @@ -12,7 +12,7 @@ js_type_check("closure_compile") { js_library("reset_password") { deps = [ - "//chrome/browser/ui/webui/reset_password:mojo_bindings_js_externs", + "//chrome/browser/ui/webui/reset_password:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:util", ] diff --git a/chromium/chrome/browser/resources/reset_password/reset_password.js b/chromium/chrome/browser/resources/reset_password/reset_password.js index 15611b4d0e8..b08c7c32875 100644 --- a/chromium/chrome/browser/resources/reset_password/reset_password.js +++ b/chromium/chrome/browser/resources/reset_password/reset_password.js @@ -8,16 +8,16 @@ */ (function() { -/** @type {mojom.ResetPasswordHandlerProxy} */ -let uiHandler; +/** @type {mojom.ResetPasswordHandlerRemote} */ +let pageHandler; function initialize() { - uiHandler = mojom.ResetPasswordHandler.getProxy(); + pageHandler = mojom.ResetPasswordHandler.getRemote(); /** @type {?HTMLElement} */ const resetPasswordButton = $('reset-password-button'); resetPasswordButton.addEventListener('click', function() { - uiHandler.handlePasswordReset(); + pageHandler.handlePasswordReset(); }); } diff --git a/chromium/chrome/browser/resources/safety_tips/PRESUBMIT.py b/chromium/chrome/browser/resources/safety_tips/PRESUBMIT.py new file mode 100644 index 00000000000..012844a2057 --- /dev/null +++ b/chromium/chrome/browser/resources/safety_tips/PRESUBMIT.py @@ -0,0 +1,56 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Presubmit checks for Safety Tips proto for the component updater. +""" + +"""Returns true if any line in changed_contents contains the string |s|. +|changed_contents| is a tuple containing (line number, line text) pairs. +""" +def ContainsLine(changed_contents, s): + for _, line in changed_contents: + if line.strip().startswith(s): + return True + return False + +def CheckVersionUpdatedInProto(input_api, output_api): + def IsSafetyTipProto(x): + return (input_api.os_path.basename(x.LocalPath()) == + 'safety_tips.asciipb') + + safety_tips_proto = input_api.AffectedFiles(file_filter=IsSafetyTipProto) + if not safety_tips_proto: + return [] + + contents = safety_tips_proto[0].ChangedContents() + # Must not have any changes containing flagged_page: + if ContainsLine(contents, 'flagged_page:'): + return [output_api.PresubmitError( + 'Do not check in the full safety_tips.asciipb proto. ' + 'Only increment |version_id|.')] + + # This proto should not contain any actually-flagged pages. ContainsLine + # checks if any line *starts with* the given string. + if ContainsLine(contents, 'flagged_page:'): + return [output_api.PresubmitError( + 'Remove entries from Chromium safety_tips.asciipb before submitting.')] + + # It's enticing to do something fancy like checking whether the ID was in fact + # incremented or whether this is a whitespace-only or comment-only change. + # However, currently deleted lines don't show up in ChangedContents() and + # attempting to parse the asciipb file any more than we are doing above is + # likely not worth the trouble. + # + # At worst, the submitter can skip the presubmit check on upload if it isn't + # correct. + if not ContainsLine(contents, 'version_id:'): + return [output_api.PresubmitError( + 'Increment |version_id| in safety_tips.asciipb if you are ' + 'updating the file types proto.')] + + return [] + + +def CheckChangeOnUpload(input_api, output_api): + return CheckVersionUpdatedInProto(input_api, output_api) diff --git a/chromium/chrome/browser/resources/safety_tips/README.md b/chromium/chrome/browser/resources/safety_tips/README.md new file mode 100644 index 00000000000..b02c20d0730 --- /dev/null +++ b/chromium/chrome/browser/resources/safety_tips/README.md @@ -0,0 +1 @@ +See go/safety-tips-component-update for Safety Tips component update playbook. diff --git a/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py b/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py index a12e8e78eb0..e4ec99a4e3e 100755 --- a/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py +++ b/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py @@ -15,6 +15,9 @@ import sys # Subdirectory to be copied to Google Cloud Storage. Contains a copy of the # generated proto under a versioned directory. +# TODO(meacer): Remove this. Safety tips does not read the proto from a local +# resource bundle, it only uses the proto passed from component updater. It does +# not need two copies of the file. GS_COPY_DIR = "gs_copy" # Import the binary proto generator. Walks up to the root of the source tree @@ -40,11 +43,14 @@ class SafetyTipsProtoGenerator(BinaryProtoGenerator): def ValidatePb(self, opts, pb): assert pb.version_id > 0 - assert len(pb.flagged_page) > 0 for flagged_page in pb.flagged_page: - assert flagged_page.url + assert flagged_page.pattern assert flagged_page.type != safety_tips_pb2.FlaggedPage.UNKNOWN + flagged_patterns = [page.pattern for page in pb.flagged_page] + assert sorted(flagged_patterns) == flagged_patterns, ( + "Please sort flagged_page entries by pattern.") + def ProcessPb(self, opts, pb): binary_pb_str = pb.SerializeToString() outfile = os.path.join(opts.outdir, opts.outbasename) diff --git a/chromium/chrome/browser/resources/safety_tips/push_proto.py b/chromium/chrome/browser/resources/safety_tips/push_proto.py new file mode 100755 index 00000000000..2404cb96399 --- /dev/null +++ b/chromium/chrome/browser/resources/safety_tips/push_proto.py @@ -0,0 +1,89 @@ +#!/usr/bin/python +# Copyright 2018 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Build and push the {vers}/all/ssl_error_assistant.pb file to GCS so +# that the component update system will pick it up and push it to users. +# See README.md before running this. +# +# Requires ninja and gsutil to be in the user's path. + +import optparse +import os +import shutil +import subprocess +import sys + + +DEST_BUCKET = 'gs://chrome-components-safety-tips' +RESOURCE_SUBDIR = 'chrome/browser/resources/safety_tips' + +# Subdirectory to be copied to Google Cloud Storage. Contains a copy of the +# generated proto under a versioned directory. +GS_COPY_DIR = "gs_copy" + +# TODO(meacer): This is pretty much a duplicate of +# chrome/browser/safe_browsing/push_file_type_proto.py. Consider +# refactoring and reusing code. +def main(): + parser = optparse.OptionParser() + parser.add_option('-d', '--dir', + help='An up-to-date GN/Ninja build directory, ' + 'such as ./out/Debug') + + (opts, _) = parser.parse_args() + if opts.dir is None: + parser.print_help() + return 1 + + # Clear out the target dir before we build so we can be sure we've got + # the freshest version. + target_dir = os.path.join(opts.dir, "gen", RESOURCE_SUBDIR) + if os.path.isdir(target_dir): + shutil.rmtree(target_dir) + + gn_command = ['ninja', + '-C', opts.dir, + RESOURCE_SUBDIR + ':make_safety_tips_protobuf'] + print "Running the following" + print " " + (' '.join(gn_command)) + if subprocess.call(gn_command): + print "Ninja failed." + return 1 + + # Use the versioned files under the copy directory to push to the GCS bucket. + copy_dir = os.path.join(target_dir, GS_COPY_DIR) + os.chdir(copy_dir) + + # Sanity check that there is a versioned copy under the directory. + dirs = os.listdir('.') + assert len(dirs) == 1 and dirs[0].isdigit(), ( + "There must be a single versioned dir under " + copy_dir) + + # Push the files with their directories, in the form + # {vers}/{platform}/download_file_types.pb + # Don't overwrite existing files, in case we forgot to increment the + # version. + version_dir = dirs[0] + command = ['gsutil', 'cp', '-Rn', version_dir, DEST_BUCKET] + + print '\nGoing to run the following command' + print ' ', ' '.join(command) + print '\nIn directory' + print ' ', copy_dir + print '\nWhich should push the following files' + expected_files = [os.path.join(dp, f) for dp, _, fn in + os.walk(version_dir) for f in fn] + for f in expected_files: + print ' ', f + + shall = raw_input('\nAre you sure (y/N) ').lower() == 'y' + if not shall: + print 'aborting' + return 1 + return subprocess.call(command) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb b/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb index 9306e6c7a27..64b7f997870 100644 --- a/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb +++ b/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb @@ -2,16 +2,19 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -# Placeholder for list of known bad URLs. -# This file must be kept as-is and the full list must not be checked in to -# Chromium source. When you want to update it, overwrite it locally, generate -# and push the protobuffer to the storage bucket but do not check in the -# changes. +# Placeholder for list of known bad patterns. +# This file must be kept as-is except for version_id. The full list must not be +# checked in to Chromium source. When you want to update it, overwrite it +# locally, generate and push the protobuffer to the storage bucket but do not +# check in the changes. -version_id: 1 +version_id: 4 # See chrome/browser/lookalikes/safety_tips.proto for the full format. -flagged_page { - url: "http://example.test/test-path-for-safety-tips/test.html" - type: BAD_REP -} +# These entries must be sorted alphabetically by pattern. + +# Example entry: +# flagged_page { +# pattern: "example.test/test-path-for-safety-tips/test.html" +# type: BAD_REP +#} diff --git a/chromium/chrome/browser/resources/set_as_default_browser.css b/chromium/chrome/browser/resources/set_as_default_browser.css deleted file mode 100644 index 9fb82d5c72a..00000000000 --- a/chromium/chrome/browser/resources/set_as_default_browser.css +++ /dev/null @@ -1,159 +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. */ - -/* The main (outer) container. */ -#metro-setup-outer-container { - -webkit-box-align: center; - -webkit-box-orient: vertical; - -webkit-box-pack: start; - background-color: rgba(255, 255, 255, 0.75); - bottom: 0; - display: -webkit-box; - left: 0; - overflow: auto; - position: fixed; - right: 0; - top: 0; - transition: 200ms opacity; -} - -/* The page block within the outer container. */ -#metro-setup-outer-container .page { - -webkit-box-orient: vertical; - background: white; - background-color: white; - border-radius: 3px; - color: #333; - display: -webkit-box; - min-width: 40px; - padding-top: 90px; - position: relative; - user-select: none; - width: 500px; -} - -#metro-setup-outer-container .page .content-area { - -webkit-box-flex: 1; - margin: 0; - overflow: auto; - padding: 0; -} - -#metro-setup-overlay { - background-color: transparent; - margin: 0; - width: 100%; -} - -/* Page Title. */ -#metro-title-container { - display: block; - margin: 37px 44px 35px; - text-align: center; -} - -#metro-setup-outer-container .page h1 { - border-bottom: 0; - color: #323232; - font-size: 300%; - font-weight: normal; - margin: 0; - padding-bottom: 0; - padding-top: 0; - text-align: center; -} - -#metro-setup-outer-container .page h2 { - border-bottom: 0; - color: #787878; - font-size: 150%; - font-weight: normal; - margin-bottom: 84px; - margin-top: 15px; - text-align: center; -} - -#metro-setup-overlay .content-area { - padding: 10px 15px; - text-align: end; -} - -/* Action buttons. */ -#metro-action-box button { - border-radius: 2px; - display: inline-block; - font-size: 13px; - height: 32px; - line-height: 27px; - margin-inline-end: 0.4em; - margin-inline-start: 0; - margin-top: 0; - min-width: 80px; - transition: all 218ms; - user-select: none; -} - -#metro-action-box button:hover { - box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1); - transition: all 0ms; -} - -#metro-action-box button:focus { - box-shadow: inset 0 0 0 1px white; - outline: none; - z-index: 4 !important; -} - -#metro-action-box button:active, -#metro-action-box button:focus:active { - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.3); -} - -#metro-action-box button:focus:hover { - box-shadow: inset 0 0 0 1px white, 0 1px 1px rgba(0, 0, 0, 0.1); -} - -#metro-action-box button[disabled], -#metro-action-box button[disabled]:hover, -#metro-action-box button[disabled]:active { - background-color: rgb(77, 144, 254); - border: 1px solid rgb(48, 121, 237); - box-shadow: none; - color: white; - opacity: 0.5; -} - -/* Launch button has a special look-and-feel. */ -#metro-action-box #launch-button { - background-image: -webkit-linear-gradient(top, rgb(77, 144, 254), - rgb(71, 135, 237)); - border: 1px solid rgb(48, 121, 237); - color: white; - font-weight: bold; -} - -#metro-action-box #launch-button:hover { - background-image: -webkit-linear-gradient(top, rgb(77, 144, 254), - rgb(53, 122, 232)); - border-color: rgb(47, 91, 183); - color: white; -} - -#metro-action-box #launch-button:focus { - border-color: rgb(77, 144, 254); - outline: none; - z-index: 4 !important; -} - -.button-strip { - margin: 1px; - text-align: center; -} - -#chrome-logo-box { - bottom: 30px; - position: absolute; - text-align: center; - width: 100%; -} diff --git a/chromium/chrome/browser/resources/set_as_default_browser.html b/chromium/chrome/browser/resources/set_as_default_browser.html deleted file mode 100644 index 8f65526a95d..00000000000 --- a/chromium/chrome/browser/resources/set_as_default_browser.html +++ /dev/null @@ -1,39 +0,0 @@ -<!doctype html> -<!-- 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. --> -<html dir="$i18n{textdirection}" lang="$i18n{language}"> -<head> -<meta charset="utf-8"> -<title>$i18n{pageTitle}</title> -<script src="chrome://resources/js/cr.js"></script> -<script src="chrome://resources/js/util.js"></script> -<script src="chrome://resources/js/cr/event_target.js"></script> -<script src="set_as_default_browser.js"></script> -<link rel="stylesheet" href="chrome://resources/css/chrome_shared.css"> -<link rel="stylesheet" href="chrome://resources/css/widgets.css"> -<link rel="stylesheet" href="set_as_default_browser.css"> -</head> -<body> -<div id="metro-setup-outer-container"> - <div id="metro-setup-overlay" class="page"> - <div> - <div class="content-area"> - <h1>$i18n{flowTitle}</h1> - <h2>$i18n{flowDescription}</h2> - </div> - <div id="metro-action-box" class="content-area"> - <div class="button-strip"> - <button id="launch-button" class="custom-appearance"> - $i18n{flowNext} - </button> - </div> - </div> - </div> - </div> - <div id="chrome-logo-box"> - <img src="chrome-logo-faded.png" alt="$i18n{chromeLogoString}"> - </div> -</div> -</body> -</html> diff --git a/chromium/chrome/browser/resources/set_as_default_browser.js b/chromium/chrome/browser/resources/set_as_default_browser.js deleted file mode 100644 index 254704b5e74..00000000000 --- a/chromium/chrome/browser/resources/set_as_default_browser.js +++ /dev/null @@ -1,16 +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. - -(function() { -// Since all we want here is forwarding of certain commands, all can be done -// in the anonymous function's scope. - -function wireUpWindow() { - $('launch-button').addEventListener('click', function() { - chrome.send('SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow'); - }); -} - -window.addEventListener('DOMContentLoaded', wireUpWindow); -})(); diff --git a/chromium/chrome/browser/resources/settings/BUILD.gn b/chromium/chrome/browser/resources/settings/BUILD.gn index 90c81d10457..4ba0dd05e72 100644 --- a/chromium/chrome/browser/resources/settings/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/BUILD.gn @@ -106,7 +106,6 @@ group("closure_compile") { if (is_chromeos) { deps += [ "android_apps_page:closure_compile", - "app_management_page:closure_compile", "bluetooth_page:closure_compile", "chromeos:closure_compile", "crostini_page:closure_compile", diff --git a/chromium/chrome/browser/resources/settings/OWNERS b/chromium/chrome/browser/resources/settings/OWNERS index a34bf8b5f11..de56e9e6644 100644 --- a/chromium/chrome/browser/resources/settings/OWNERS +++ b/chromium/chrome/browser/resources/settings/OWNERS @@ -6,4 +6,7 @@ michaelpg@chromium.org stevenjb@chromium.org tommycli@chromium.org +# Chrome OS Settings +per-file *os_settings*=file://chrome/browser/resources/settings/chromeos/OWNERS + # COMPONENT: UI>Settings diff --git a/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn b/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn index cb0f25da20a..81f68e46981 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn @@ -52,10 +52,12 @@ js_library("manage_a11y_page") { js_library("switch_access_subpage") { deps = [ "..:route", + "../prefs:prefs_behavior", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js:load_time_data", "//ui/webui/resources/js:web_ui_listener_behavior", ] + externs_list = [ "$externs_path/settings_private.js" ] } js_library("tts_subpage") { 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 74d602e6f8e..078fc8f2161 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html +++ b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html @@ -19,43 +19,24 @@ <dom-module id="settings-a11y-page"> <template> <style include="settings-shared"></style> - <template is="dom-if" if="[[showCaptionSettings_]]"> - <cr-link-row class="hr" id="captions" label="$i18n{captionsTitle}" - on-click="onCaptionsClick_"> - </cr-link-row> - </template> <settings-animated-pages id="pages" current-route="{{currentRoute}}" section="a11y" focus-config="[[focusConfig_]]"> -<if expr="not chromeos"> <div route-path="default"> - <settings-toggle-button - id="a11yImageLabels" - hidden$="[[!showAccessibilityLabelsSetting_]]" - pref="{{prefs.settings.a11y.enable_accessibility_image_labels}}" - on-change="onToggleAccessibilityImageLabels_" - label="$i18n{accessibleImageLabelsTitle}" - sub-label="$i18n{accessibleImageLabelsSubtitle}"> - </settings-toggle-button> - <cr-link-row class="hr" label="$i18n{moreFeaturesLink}" - on-click="onMoreFeaturesLinkClick_" sub-label="$i18n{a11yWebStore}" - external> - </cr-link-row> - </div> -</if> -<if expr="chromeos or is_linux or is_win"> - <template is="dom-if" if="[[showCaptionSettings_]]"> - <template is="dom-if" route-path="/captions"> - <settings-subpage - associated-control="[[$$('#captions')]]" - page-title="$i18n{captionsTitle}"> - <settings-captions prefs="{{prefs}}"></settings-captions> - </settings-subpage> - </template> - </template> + <cr-link-row class="hr" id="captions" label="$i18n{captionsTitle}" + on-click="onCaptionsClick_" external$="[[captionSettingsOpensExternally_]]"> + </cr-link-row> +<if expr="not chromeos"> + <settings-toggle-button + id="a11yImageLabels" + hidden$="[[!showAccessibilityLabelsSetting_]]" + pref="{{prefs.settings.a11y.enable_accessibility_image_labels}}" + on-change="onToggleAccessibilityImageLabels_" + label="$i18n{accessibleImageLabelsTitle}" + sub-label="$i18n{accessibleImageLabelsSubtitle}"> + </settings-toggle-button> </if> <if expr="chromeos"> - <template is="dom-if" if="[[pageVisibility.webstoreLink]]"> - <div route-path="default"> + <template is="dom-if" if="[[pageVisibility.webstoreLink]]"> <settings-toggle-button id="a11yImageLabels" hidden$="[[!showAccessibilityLabelsSetting_]]" @@ -73,7 +54,26 @@ on-click="onManageAccessibilityFeaturesTap_" sub-label="$i18n{moreFeaturesLinkDescription}"> </cr-link-row> - </div> + </template> +</if> + <cr-link-row class="hr" label="$i18n{moreFeaturesLink}" + on-click="onMoreFeaturesLinkClick_" sub-label="$i18n{a11yWebStore}" + hidden="[[pageVisibility.webstoreLink]]" external> + </cr-link-row> + </div> +<if expr="not is_macosx"> + <template is="dom-if" if="[[showCaptionSettings_]]"> + <template is="dom-if" route-path="/captions"> + <settings-subpage + associated-control="[[$$('#captions')]]" + page-title="$i18n{captionsTitle}"> + <settings-captions prefs="{{prefs}}"></settings-captions> + </settings-subpage> + </template> + </template> +</if> +<if expr="chromeos"> + <template is="dom-if" if="[[pageVisibility.webstoreLink]]"> <template is="dom-if" route-path="/manageAccessibility"> <settings-subpage associated-control="[[$$('#subpage-trigger')]]" @@ -86,8 +86,7 @@ <settings-subpage associated-control="[[$$('#subpage-trigger')]]" page-title="$i18n{manageTtsSettings}"> - <settings-tts-subpage prefs="{{prefs}}"> - </settings-tts-subpage> + <settings-tts-subpage prefs="{{prefs}}"></settings-tts-subpage> </settings-subpage> </template> <template is="dom-if" route-path="/manageAccessibility/switchAccess"> @@ -100,12 +99,6 @@ </template> </if> </settings-animated-pages> -<if expr="chromeos"> - <cr-link-row class="hr" label="$i18n{moreFeaturesLink}" - on-click="onMoreFeaturesLinkClick_" sub-label="$i18n{a11yWebStore}" - hidden="[[pageVisibility.webstoreLink]]" external> - </cr-link-row> -</if> </template> <script src="a11y_page.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js index 6629ff75429..31045680975 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js +++ b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js @@ -67,6 +67,26 @@ Polymer({ }, }, + /** + * Whether the caption settings link opens externally. + * @private {boolean} + */ + captionSettingsOpensExternally_: { + type: Boolean, + value: function() { + let opensExternally = false; + // <if expr="is_macosx"> + opensExternally = true; + // </if> + + // <if expr="is_win"> + opensExternally = loadTimeData.getBoolean('isWindows10OrNewer'); + // </if> + + return opensExternally; + }, + }, + // <if expr="chromeos"> /** * Whether to show experimental accessibility features. diff --git a/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html index d3d305b9c42..a894a919576 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html +++ b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html @@ -7,83 +7,102 @@ <dom-module id="settings-captions"> <template> - <style include="settings-shared"></style> - <div class="settings-box"> - <div class="start settings-box-text">$i18n{captionsTextSize}</div> - <settings-dropdown-menu id="captionsTextSize" - label="$i18n{captionsTextSize}" - pref="{{prefs.accessibility.captions.text_size}}" - menu-options="[[textSizeOptions_]]"> - </settings-dropdown-menu> + <style include="settings-shared"> + .preview-box { + align-items: center; + background-image: + url(chrome://theme/IDR_ACCESSIBILITY_CAPTIONS_PREVIEW_BACKGROUND); + background-position: center; + background-size: cover; + display: flex; + height: 112px; + justify-content: center; + margin: 0 var(--cr-section-padding) var(--cr-section-padding); + text-align: center; + } + </style> + <div class="settings-box first"> + <h2 class="start">$i18n{captionsPreview}</h2> </div> - <div class="settings-box"> - <div class="start settings-box-text">$i18n{captionsTextFont}</div> - <settings-dropdown-menu id="captionsTextFont" - label="$i18n{captionsTextFont}" - pref="{{prefs.accessibility.captions.text_font}}" - menu-options="[[textFontOptions_]]"> - </settings-dropdown-menu> + <div class="preview-box"> + <span style=" + font-size:[[prefs.accessibility.captions.text_size.value]]; + font-family:[[prefs.accessibility.captions.text_font.value]]; + background-color: [[computeBackgroundColor_( + prefs.accessibility.captions.background_opacity.value, + prefs.accessibility.captions.background_color.value)]]; + color: [[computeTextColor_( + prefs.accessibility.captions.text_opacity.value, + prefs.accessibility.captions.text_color.value)]]; + text-shadow: [[prefs.accessibility.captions.text_shadow.value]]; + padding: [[computePadding_( + prefs.accessibility.captions.text_size.value)]]"> + $i18n{quickBrownFox} + </span> </div> - <div class="settings-box"> - <div class="start settings-box-text">$i18n{captionsTextColor}</div> - <settings-dropdown-menu id="captionsTextColor" - label="$i18n{captionsTextColor}" - pref="{{prefs.accessibility.captions.text_color}}" - menu-options="[[colorOptions_]]"> - </settings-dropdown-menu> - </div> - <div class="settings-box"> - <div class="start settings-box-text">$i18n{captionsTextOpacity}</div> - <settings-slider id="captionsTextOpacity" - ticks="[[textOpacityRange_]]" - label-min="$i18n{captionsOpacityMin}" - label-max="$i18n{captionsOpacityMax}" - pref="{{prefs.accessibility.captions.text_opacity}}"> - </settings-slider> - </div> - <div class="settings-box"> - <div class="start settings-box-text">$i18n{captionsTextShadow}</div> - <settings-dropdown-menu id="captionsTextShadow" - label="$i18n{captionsTextShadow}" - pref="{{prefs.accessibility.captions.text_shadow}}" - menu-options="[[textShadowOptions_]]"> - </settings-dropdown-menu> - </div> - <div class="settings-box"> - <div class="start settings-box-text">$i18n{captionsBackgroundColor}</div> - <settings-dropdown-menu id="captionsBackgroundColor" - label="$i18n{captionsBackgroundColor}" - pref="{{prefs.accessibility.captions.background_color}}" - menu-options="[[colorOptions_]]"> - </settings-dropdown-menu> - </div> - <div class="settings-box"> - <div class="start settings-box-text"> - $i18n{captionsBackgroundOpacity} - </div> - <settings-slider id="captionsBackgroundOpacity" - ticks="[[textOpacityRange_]]" - label-min="$i18n{captionsOpacityMin}" - label-max="$i18n{captionsOpacityMax}" - pref="{{prefs.accessibility.captions.background_opacity}}"> - </settings-slider> + <div class="settings-box continuation"> + <h2 class="start">$i18n{captionsSettings}</h2> </div> <div class="list-frame"> + <div class="list-item underbar first"> + <div class="start settings-box-text">$i18n{captionsTextSize}</div> + <settings-dropdown-menu id="captionsTextSize" + label="$i18n{captionsTextSize}" + pref="{{prefs.accessibility.captions.text_size}}" + menu-options="[[textSizeOptions_]]"> + </settings-dropdown-menu> + </div> + <div class="list-item underbar"> + <div class="start settings-box-text">$i18n{captionsTextFont}</div> + <settings-dropdown-menu id="captionsTextFont" + label="$i18n{captionsTextFont}" + pref="{{prefs.accessibility.captions.text_font}}" + menu-options="[[textFontOptions_]]"> + </settings-dropdown-menu> + </div> + <div class="list-item underbar"> + <div class="start settings-box-text">$i18n{captionsTextColor}</div> + <settings-dropdown-menu id="captionsTextColor" + label="$i18n{captionsTextColor}" + pref="{{prefs.accessibility.captions.text_color}}" + menu-options="[[colorOptions_]]"> + </settings-dropdown-menu> + </div> + <div class="list-item underbar"> + <div class="start settings-box-text">$i18n{captionsTextOpacity}</div> + <settings-dropdown-menu id="captionsTextOpacity" + label="$i18n{captionsTextOpacity}" + pref="{{prefs.accessibility.captions.text_opacity}}" + menu-options="[[textOpacityOptions_]]"> + </settings-dropdown-menu> + </div> + <div class="list-item underbar"> + <div class="start settings-box-text">$i18n{captionsTextShadow}</div> + <settings-dropdown-menu id="captionsTextShadow" + label="$i18n{captionsTextShadow}" + pref="{{prefs.accessibility.captions.text_shadow}}" + menu-options="[[textShadowOptions_]]"> + </settings-dropdown-menu> + </div> + <div class="list-item underbar"> + <div class="start settings-box-text"> + $i18n{captionsBackgroundColor} + </div> + <settings-dropdown-menu id="captionsBackgroundColor" + label="$i18n{captionsBackgroundColor}" + pref="{{prefs.accessibility.captions.background_color}}" + menu-options="[[colorOptions_]]"> + </settings-dropdown-menu> + </div> <div class="list-item"> - <span style=" - font-size:[[prefs.accessibility.captions.text_size.value]]; - font-family:[[prefs.accessibility.captions.text_font.value]]; - background-color: [[computeBackgroundColor_( - prefs.accessibility.captions.background_opacity.value, - prefs.accessibility.captions.background_color.value)]]; - color: [[computeTextColor_( - prefs.accessibility.captions.text_opacity.value, - prefs.accessibility.captions.text_color.value)]]; - text-shadow: [[prefs.accessibility.captions.text_shadow.value]]; - padding: [[computePadding_( - prefs.accessibility.captions.text_size.value)]]"> - $i18n{quickBrownFox} - </span> + <div class="start settings-box-text"> + $i18n{captionsBackgroundOpacity} + </div> + <settings-dropdown-menu id="captionsBackgroundOpacity" + label="$i18n{captionsBackgroundOpacity}" + pref="{{prefs.accessibility.captions.background_opacity}}" + menu-options="[[backgroundOpacityOptions_]]"> + </settings-dropdown-menu> </div> </div> </template> diff --git a/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js index df973af40cd..ca625a3be4f 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js +++ b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js @@ -9,21 +9,6 @@ (function() { 'use strict'; - -/** @type {!Array<number>} */ -const TEXT_OPACITY_RANGE = [ - 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, - 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 -]; - -/** - * @param {!Array<number>} ticks - * @return {!Array<!cr_slider.SliderTick>} - */ -function ticksWithLabels(ticks) { - return ticks.map(x => ({label: `${x}`, value: x})); -} - Polymer({ is: 'settings-captions', @@ -36,34 +21,26 @@ Polymer({ }, /** - * List of fonts populated by the fonts browser proxy. - * @private {!DropdownMenuOptionList} */ - textFontOptions_: Object, - - /** - * Reasonable, text opacity range. - * @private {!Array<!cr_slider.SliderTick>} - */ - textOpacityRange_: { - readOnly: true, - type: Array, - value: ticksWithLabels(TEXT_OPACITY_RANGE), - }, - - /** - * List of options for the text size drop-down menu. + * List of options for the background opacity drop-down menu. * @type {!DropdownMenuOptionList} */ - textSizeOptions_: { + backgroundOpacityOptions_: { readOnly: true, type: Array, value: function() { return [ - {value: '50%', name: loadTimeData.getString('verySmall')}, - {value: '75%', name: loadTimeData.getString('small')}, - {value: '', name: loadTimeData.getString('medium')}, // Default = 100% - {value: '150%', name: loadTimeData.getString('large')}, - {value: '200%', name: loadTimeData.getString('veryLarge')}, + { + value: 100, // Default + name: loadTimeData.getString('captionsOpacityOpaque') + }, + { + value: 50, + name: loadTimeData.getString('captionsOpacitySemiTransparent') + }, + { + value: 0, + name: loadTimeData.getString('captionsOpacityTransparent') + }, ]; }, }, @@ -77,18 +54,30 @@ Polymer({ type: Array, value: function() { return [ - {value: '', name: loadTimeData.getString('captionsDefaultSetting')}, - {value: '0,0,0', name: loadTimeData.getString('captionsColorBlack')}, + { + value: '', + name: loadTimeData.getString('captionsDefaultSetting') + }, + { + value: '0,0,0', + name: loadTimeData.getString('captionsColorBlack') + }, { value: '255,255,255', name: loadTimeData.getString('captionsColorWhite') }, - {value: '255,0,0', name: loadTimeData.getString('captionsColorRed')}, + { + value: '255,0,0', + name: loadTimeData.getString('captionsColorRed') + }, { value: '0,255,0', name: loadTimeData.getString('captionsColorGreen') }, - {value: '0,0,255', name: loadTimeData.getString('captionsColorBlue')}, + { + value: '0,0,255', + name: loadTimeData.getString('captionsColorBlue') + }, { value: '255,255,0', name: loadTimeData.getString('captionsColorYellow') @@ -106,6 +95,36 @@ Polymer({ }, /** + * List of fonts populated by the fonts browser proxy. + * @private {!DropdownMenuOptionList} */ + textFontOptions_: Object, + + /** + * List of options for the text opacity drop-down menu. + * @type {!DropdownMenuOptionList} + */ + textOpacityOptions_: { + readOnly: true, + type: Array, + value: function() { + return [ + { + value: 100, // Default + name: loadTimeData.getString('captionsOpacityOpaque') + }, + { + value: 50, + name: loadTimeData.getString('captionsOpacitySemiTransparent') + }, + { + value: 10, + name: loadTimeData.getString('captionsOpacityTransparent') + }, + ]; + }, + }, + + /** * List of options for the text shadow drop-down menu. * @type {!DropdownMenuOptionList} */ @@ -135,6 +154,24 @@ Polymer({ ]; }, }, + + /** + * List of options for the text size drop-down menu. + * @type {!DropdownMenuOptionList} + */ + textSizeOptions_: { + readOnly: true, + type: Array, + value: function() { + return [ + {value: '25%', name: loadTimeData.getString('verySmall')}, + {value: '50%', name: loadTimeData.getString('small')}, + {value: '', name: loadTimeData.getString('medium')}, // Default = 100% + {value: '150%', name: loadTimeData.getString('large')}, + {value: '200%', name: loadTimeData.getString('veryLarge')}, + ]; + }, + }, }, /** @private {?settings.FontsBrowserProxy} */ 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 c7f4721a974..7f290fc3df3 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 @@ -110,7 +110,8 @@ embedded></cr-link-row> <cr-link-row class="hr" label="$i18n{appearanceSettingsTitle}" on-click="onAppearanceTap_" - sub-label="$i18n{appearanceSettingsDescription}" embedded></cr-link-row> + sub-label="$i18n{appearanceSettingsDescription}" + external="[[isOSSettings_]]" embedded></cr-link-row> <h2>$i18n{keyboardAndTextInputHeading}</h2> <settings-toggle-button class="first" @@ -142,7 +143,7 @@ <iron-collapse opened="[[prefs.settings.a11y.switch_access.enabled.value]]"> <cr-link-row label="$i18n{switchAccessOptionsLabel}" - on-click="onSwitchAccessSettingsTap_" embedded external> + on-click="onSwitchAccessSettingsTap_" embedded> </cr-link-row> </iron-collapse> </template> diff --git a/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js b/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js index 88238c3061f..5365829d90f 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js +++ b/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js @@ -126,6 +126,18 @@ Polymer({ }, /** + * Whether this page shown as part of OS settings. + * TODO(crbug.com/986596): Remove this when SplitSettings is the default. + * @private + */ + isOSSettings_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('isOSSettings'); + }, + }, + + /** * |hasKeyboard_|starts undefined so observers don't trigger * until it has been populated. * @private @@ -200,7 +212,7 @@ Polymer({ /** @private */ onSwitchAccessSettingsTap_: function() { - chrome.send('showSwitchAccessSettings'); + settings.navigateTo(settings.routes.MANAGE_SWITCH_ACCESS_SETTINGS); }, /** @private */ @@ -212,9 +224,16 @@ Polymer({ /** @private */ onAppearanceTap_: function() { - settings.navigateTo( - settings.routes.APPEARANCE, - /* dynamicParams */ null, /* removeSearch */ true); + if (loadTimeData.getBoolean('isOSSettings')) { + // Open browser appearance section in a new browser tab. + window.open('chrome://settings/appearance'); + } else { + // Open browser appearance in this settings window. + // TODO(crbug.com/986596): Remove this when SplitSettings is the default. + settings.navigateTo( + settings.routes.APPEARANCE, + /* dynamicParams */ null, /* removeSearch */ true); + } }, /** @private */ diff --git a/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html index d8c101b1563..6134a743a50 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html +++ b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html @@ -6,6 +6,7 @@ <link rel="import" href="../controls/settings_slider.html"> <link rel="import" href="../controls/settings_toggle_button.html"> <link rel="import" href="../i18n_setup.html"> +<link rel="import" href="../prefs/prefs_behavior.html"> <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-switch-access-subpage"> @@ -61,7 +62,23 @@ </div> <settings-slider id="scanSpeedSlider" aria-describedby="scanSpeed" pref="{{prefs.switch_access.auto_scan.speed_ms}}" - ticks="[[autoScanSpeedValuesMs_]]" + ticks="[[autoScanSpeedRangeMs_]]" + min="[[minScanSpeedMs_]]" + max="[[maxScanSpeedMs_]]" + label-min="[[minScanSpeedLabelSec_]]" + label-max="[[maxScanSpeedLabelSec_]]"> + </settings-dropdown-menu> + </div> + <div class="settings-box continuation list-item" + hidden$="[[!showKeyboardScanSettings_( + prefs.switch_access.auto_scan.enabled.value)]]"> + <div class="start sub-item settings-box-text" id="keyboardScanSpeed"> + $i18n{switchAccessAutoScanKeyboardSpeedLabel} + </div> + <settings-slider id="keyboardScanSpeedSlider" + aria-describedby="keyboardScanSpeed" + pref="{{prefs.switch_access.auto_scan.keyboard.speed_ms}}" + ticks="[[autoScanSpeedRangeMs_]]" min="[[minScanSpeedMs_]]" max="[[maxScanSpeedMs_]]" label-min="[[minScanSpeedLabelSec_]]" diff --git a/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js index 328e60ca3d0..cd0026e9cdd 100644 --- a/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js +++ b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js @@ -3,6 +3,13 @@ // found in the LICENSE file. /** + * @fileoverview 'switch-access-subpage' is the collapsible section containing + * Switch Access settings. + */ + +(function() { + +/** * Available switch assignment values. * @enum {number} * @const @@ -13,14 +20,29 @@ const SwitchAccessAssignmentValue = { ENTER: 2, }; +/** @type {!Array<number>} */ +const AUTO_SCAN_SPEED_RANGE_MS = [ + 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, + 1700, 1800, 1900, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, + 2900, 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000 +]; + /** - * @fileoverview 'switch-access-subpage' is the collapsible section containing - * Switch Access settings. + * @param {!Array<number>} ticksInMs + * @return {!Array<!cr_slider.SliderTick>} */ +function ticksWithLabelsInSec(ticksInMs) { + // Dividing by 1000 to convert milliseconds to seconds for the label. + return ticksInMs.map(x => ({label: `${x / 1000}`, value: x})); +} + Polymer({ is: 'settings-switch-access-subpage', - behaviors: [I18nBehavior], + behaviors: [ + I18nBehavior, + PrefsBehavior, + ], properties: { /** @@ -32,15 +54,10 @@ Polymer({ }, /** @private {Array<number>} */ - autoScanSpeedValuesMs_: { + autoScanSpeedRangeMs_: { readOnly: true, type: Array, - value: [ - 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, - 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200, - 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100, - 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000 - ] + value: ticksWithLabelsInSec(AUTO_SCAN_SPEED_RANGE_MS), }, /** @private {Object} */ @@ -123,6 +140,19 @@ Polymer({ }, /** + * @return {boolean} Whether to show settings for auto-scan within the + * keyboard. + * @private + */ + showKeyboardScanSettings_: function() { + const improvedTextInputEnabled = loadTimeData.getBoolean( + 'showExperimentalAccessibilitySwitchAccessImprovedTextInput'); + const autoScanEnabled = /** @type {boolean} */ + (this.getPref('switch_access.auto_scan.enabled').value); + return improvedTextInputEnabled && autoScanEnabled; + }, + + /** * @param {string} command */ onSwitchAssigned_: function(command) { @@ -166,3 +196,4 @@ Polymer({ 'durationInSeconds', this.formatter_.format(scanSpeedValueSec)); }, }); +})(); 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 18c371cdbbe..99c0a1c19a1 100644 --- a/chromium/chrome/browser/resources/settings/about_page/about_page.html +++ b/chromium/chrome/browser/resources/settings/about_page/about_page.html @@ -23,6 +23,7 @@ <if expr="chromeos"> <link rel="import" href="detailed_build_info.html"> <link rel="import" href="update_warning_dialog.html"> +<link rel="import" href="../chromeos/os_icons.html"> <link rel="import" href="../settings_page/settings_subpage.html"> <link rel="import" href="../reset_page/powerwash_dialog.html"> </if> @@ -150,14 +151,19 @@ </span> </if> <if expr="chromeos"> - <div id="endOfLifeMessageContainer" hidden="[[!hasEndOfLife_]]"> - $i18n{endOfLifeMessage} - <a href="$i18n{endOfLifeLearnMoreURL}" target="_blank"> - $i18n{learnMore} - </a> - </div> + <div id="endOfLifeMessageContainer" hidden="[[!hasEndOfLife_]]"> + $i18n{endOfLifeMessage} + <a href="$i18n{endOfLifeLearnMoreURL}" target="_blank"> + $i18n{learnMore} + </a> + </div> </if> <div class="secondary">$i18n{aboutBrowserVersion}</div> +<if expr="chromeos"> + <div class="secondary" + inner-h-t-m-l="[[getUpdateOsSettingsLink_()]]"> + </div> +</if> </div> <div class="separator" hidden="[[!showButtonContainer_]]"></div> <span id="buttonContainer" hidden="[[!showButtonContainer_]]"> @@ -233,7 +239,7 @@ <if expr="_google_chrome"> <cr-link-row class="hr" id="reportIssue" on-click="onReportIssueTap_" hidden="[[!prefs.feedback_allowed.value]]" - label="$i18n{aboutReportAnIssue}"></cr-link-row> + label="$i18n{aboutReportAnIssue}" external></cr-link-row> </if> <if expr="chromeos"> <cr-link-row class="hr" id="detailed-build-info-trigger" 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 4899236f7b7..d4781a4d1b7 100644 --- a/chromium/chrome/browser/resources/settings/about_page/about_page.js +++ b/chromium/chrome/browser/resources/settings/about_page/about_page.js @@ -491,7 +491,7 @@ Polymer({ // If Chrome OS has reached end of life, display a special icon and // ignore UpdateStatus. if (this.hasEndOfLife_) { - return 'settings:end-of-life'; + return 'os-settings:end-of-life'; } // </if> @@ -632,6 +632,20 @@ Polymer({ this.i18nAdvanced('aboutProductOsLicense'); }, + // <if expr="chromeos"> + /** + * @return {string} + * @private + */ + getUpdateOsSettingsLink_: function() { + // Note: This string contains raw HTML and thus requires i18nAdvanced(). + // Since the i18n template syntax (e.g., $i18n{}) does not include an + // "advanced" version, it's not possible to inline this link directly in the + // HTML. + return this.i18nAdvanced('aboutUpdateOsSettingsLink'); + }, + // </if> + /** * @param {boolean} enabled True if Crostini is enabled. * @private diff --git a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html b/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html deleted file mode 100644 index cab1b4a924f..00000000000 --- a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html +++ /dev/null @@ -1,14 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="../open_window_proxy.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html"> - -<dom-module id="settings-app-management-page"> - <template> - <cr-link-row id="appManagementButton" - label="$i18n{manageYourApps}" sub-label="$i18n{manageYourAppsSublabel}" - on-click="openAppManagement_" external> - </cr-link-row> - </template> - <script src="app_management_page.js"></script> -</dom-module> diff --git a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js b/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js deleted file mode 100644 index da525757d79..00000000000 --- a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview - * 'app-management-page' is the settings page which links to App Management. - */ - -Polymer({ - is: 'settings-app-management-page', - - /** @private */ - openAppManagement_: function() { - chrome.metricsPrivate.recordUserAction('SettingsPage.OpenAppManagement'); - settings.OpenWindowProxyImpl.getInstance().openURL( - 'chrome://app-management'); - }, -}); diff --git a/chromium/chrome/browser/resources/settings/appearance_page/BUILD.gn b/chromium/chrome/browser/resources/settings/appearance_page/BUILD.gn index 7b27f61c697..a3c3d26c232 100644 --- a/chromium/chrome/browser/resources/settings/appearance_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/appearance_page/BUILD.gn @@ -12,6 +12,10 @@ js_type_check("closure_compile") { ":fonts_browser_proxy", ":home_url_input", ] + + if (is_chromeos) { + deps += [ ":wallpaper_browser_proxy" ] + } } js_library("appearance_fonts_page") { @@ -42,6 +46,7 @@ js_library("appearance_browser_proxy") { js_library("appearance_page") { deps = [ ":appearance_browser_proxy", + ":wallpaper_browser_proxy", "..:page_visibility", "..:route", "../controls:settings_dropdown_menu", @@ -75,3 +80,10 @@ js_library("home_url_input") { ] externs_list = [ "$externs_path/settings_private.js" ] } + +js_library("wallpaper_browser_proxy") { + deps = [ + "//ui/webui/resources/js:cr", + ] + externs_list = [ "$externs_path/chrome_send.js" ] +} 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 c75464dc66e..7e8bd802fc3 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,22 +17,6 @@ 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() {} - - // </if> - useDefaultTheme() {} // <if expr="is_linux and not chromeos"> @@ -70,24 +54,6 @@ cr.define('settings', function() { return loadTimeData.getBoolean('isSupervised'); } - // <if expr="chromeos"> - /** @override */ - isWallpaperSettingVisible() { - return cr.sendWithPromise('isWallpaperSettingVisible'); - } - - /** @override */ - isWallpaperPolicyControlled() { - return cr.sendWithPromise('isWallpaperPolicyControlled'); - } - - /** @override */ - openWallpaperManager() { - chrome.send('openWallpaperManager'); - } - - // </if> - /** @override */ useDefaultTheme() { chrome.send('useDefaultTheme'); 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 df9863a3a64..3a619511bed 100644 --- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html +++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html @@ -18,6 +18,10 @@ <link rel="import" href="appearance_fonts_page.html"> <link rel="import" href="home_url_input.html"> +<if expr="chromeos"> +<link rel="import" href="../appearance_page/wallpaper_browser_proxy.html"> +</if> + <dom-module id="settings-appearance-page"> <template> <style include="settings-shared md-select iron-flex"> 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 9fa3b60a182..2551cf3b191 100644 --- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js +++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.js @@ -119,7 +119,12 @@ Polymer({ }, /** @private {?settings.AppearanceBrowserProxy} */ - browserProxy_: null, + appearanceBrowserProxy_: null, + + // <if expr="chromeos"> + /** @private {?settings.WallpaperBrowserProxy} */ + wallpaperBrowserProxy_: null, + // </if> observers: [ 'defaultFontSizeChanged_(prefs.webkit.webprefs.default_font_size.value)', @@ -133,7 +138,12 @@ Polymer({ /** @override */ created: function() { - this.browserProxy_ = settings.AppearanceBrowserProxyImpl.getInstance(); + this.appearanceBrowserProxy_ = + settings.AppearanceBrowserProxyImpl.getInstance(); + // <if expr="chromeos"> + this.wallpaperBrowserProxy_ = + settings.WallpaperBrowserProxyImpl.getInstance(); + // </if> }, /** @override */ @@ -141,16 +151,16 @@ Polymer({ this.$.defaultFontSize.menuOptions = this.fontSizeOptions_; // TODO(dschuyler): Look into adding a listener for the // default zoom percent. - this.browserProxy_.getDefaultZoom().then(zoom => { + this.appearanceBrowserProxy_.getDefaultZoom().then(zoom => { this.defaultZoom_ = zoom; }); // <if expr="chromeos"> - this.browserProxy_.isWallpaperSettingVisible().then( + this.wallpaperBrowserProxy_.isWallpaperSettingVisible().then( isWallpaperSettingVisible => { assert(this.pageVisibility); this.pageVisibility.setWallpaper = isWallpaperSettingVisible; }); - this.browserProxy_.isWallpaperPolicyControlled().then( + this.wallpaperBrowserProxy_.isWallpaperPolicyControlled().then( isPolicyControlled => { this.isWallpaperPolicyControlled_ = isPolicyControlled; }); @@ -219,13 +229,13 @@ Polymer({ * @private */ openWallpaperManager_: function() { - this.browserProxy_.openWallpaperManager(); + this.wallpaperBrowserProxy_.openWallpaperManager(); }, // </if> /** @private */ onUseDefaultTap_: function() { - this.browserProxy_.useDefaultTheme(); + this.appearanceBrowserProxy_.useDefaultTheme(); }, // <if expr="is_linux and not chromeos"> @@ -254,7 +264,8 @@ Polymer({ * @private */ showUseSystem_: function(themeId, useSystemTheme) { - return (!!themeId || !useSystemTheme) && !this.browserProxy_.isSupervised(); + return (!!themeId || !useSystemTheme) && + !this.appearanceBrowserProxy_.isSupervised(); }, /** @@ -271,7 +282,7 @@ Polymer({ /** @private */ onUseSystemTap_: function() { - this.browserProxy_.useSystemTheme(); + this.appearanceBrowserProxy_.useSystemTheme(); }, // </if> @@ -288,7 +299,7 @@ Polymer({ if (themeId.length > 0 && themeId != AUTOGENERATED_THEME_ID) { assert(!useSystemTheme); - this.browserProxy_.getThemeInfo(themeId).then(info => { + this.appearanceBrowserProxy_.getThemeInfo(themeId).then(info => { this.themeSublabel_ = info.name; }); diff --git a/chromium/chrome/browser/resources/settings/appearance_page/wallpaper_browser_proxy.html b/chromium/chrome/browser/resources/settings/appearance_page/wallpaper_browser_proxy.html new file mode 100644 index 00000000000..59b04eed214 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/appearance_page/wallpaper_browser_proxy.html @@ -0,0 +1,2 @@ +<link rel="href" src="chrome://resources/html/cr.html"> +<script src="wallpaper_browser_proxy.js"></script> diff --git a/chromium/chrome/browser/resources/settings/appearance_page/wallpaper_browser_proxy.js b/chromium/chrome/browser/resources/settings/appearance_page/wallpaper_browser_proxy.js new file mode 100644 index 00000000000..90a2e4db7d9 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/appearance_page/wallpaper_browser_proxy.js @@ -0,0 +1,48 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('settings', function() { + /** @interface */ + class WallpaperBrowserProxy { + /** + * @return {!Promise<boolean>} Whether the wallpaper setting row should be + * visible. + */ + isWallpaperSettingVisible() {} + + /** + * @return {!Promise<boolean>} Whether the wallpaper is policy controlled. + */ + isWallpaperPolicyControlled() {} + + openWallpaperManager() {} + } + + /** + * @implements {settings.WallpaperBrowserProxy} + */ + class WallpaperBrowserProxyImpl { + /** @override */ + isWallpaperSettingVisible() { + return cr.sendWithPromise('isWallpaperSettingVisible'); + } + + /** @override */ + isWallpaperPolicyControlled() { + return cr.sendWithPromise('isWallpaperPolicyControlled'); + } + + /** @override */ + openWallpaperManager() { + chrome.send('openWallpaperManager'); + } + } + + cr.addSingletonGetter(WallpaperBrowserProxyImpl); + + return { + WallpaperBrowserProxy: WallpaperBrowserProxy, + WallpaperBrowserProxyImpl: WallpaperBrowserProxyImpl, + }; +}); diff --git a/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn b/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn index 84a9f949cac..1afa9c4b7ef 100644 --- a/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn @@ -117,14 +117,16 @@ js_library("passwords_section") { ":password_list_item", ":password_manager_proxy", "..:global_scroll_target_behavior", + "../people_page:sync_browser_proxy", "//third_party/polymer/v1_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer-extracted", "//third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior:iron-a11y-keys-behavior-extracted", "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu", - "//ui/webui/resources/cr_elements/cr_toast:cr_toast", + "//ui/webui/resources/cr_elements/cr_toast:cr_toast_manager", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js:list_property_update_behavior", "//ui/webui/resources/js:util", + "//ui/webui/resources/js:web_ui_listener_behavior", "//ui/webui/resources/js/cr/ui:focus_without_ink", ] externs_list = [ "$externs_path/passwords_private.js" ] diff --git a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html index 1e7b7923b1a..58e376e7433 100644 --- a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html +++ b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html @@ -3,7 +3,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/html/assert.html"> <link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html"> @@ -17,6 +17,7 @@ <link rel="import" href="../controls/extension_controlled_indicator.html"> <link rel="import" href="../global_scroll_target_behavior.html"> <link rel="import" href="../prefs/prefs.html"> +<link rel="import" href="../prefs/prefs_behavior.html"> <link rel="import" href="../settings_shared_css.html"> <link rel="import" href="../site_favicon.html"> <link rel="import" href="password_edit_dialog.html"> @@ -72,12 +73,23 @@ </extension-controlled-indicator> </div> </template> + <settings-toggle-button id="passwordsLeakDetectionCheckbox" + pref="{{prefs.profile.password_manager_leak_detection}}" + checked="[[getCheckedLeakDetection_( + userSignedIn_, prefs.profile.password_manager_leak_detection)]]" + label="$i18n{passwordsLeakDetectionLabel}" + sub-label="[[getPasswordsLeakDetectionSubLabel_( + userSignedIn_, prefs.profile.password_manager_leak_detection)]]" + hidden$="[[!passwordsLeakDetectionEnabled_]]" + disabled="[[!userSignedIn_]]"> + </settings-toggle-button> <settings-toggle-button id="autosigninCheckbox" pref="{{prefs.credentials_enable_autosignin}}" label="$i18n{passwordsAutosigninLabel}" sub-label="$i18n{passwordsAutosigninDescription}"> </settings-toggle-button> - <div id="manageLink" class="settings-box first two-line"> + <div id="manageLink" class="settings-box first two-line" + hidden$="[[hidePasswordsLink_]]"> <!-- This span lays out the url correctly, relative to the label. --> <span>$i18nRaw{managePasswordsLabel}</span> </div> @@ -163,12 +175,11 @@ </settings-password-prompt-dialog> </template> </if> - <cr-toast id="undoToast" duration="[[toastDuration_]]"> - <div id="undoLabel">$i18n{passwordDeleted}</div> - <cr-button on-click="onUndoButtonTap_"> - $i18n{undoRemovePassword} - </cr-button> - </cr-toast> + <cr-toast-manager on-undo-click="onUndoButtonTap_" + undo-label="$i18n{undoRemovePassword}" + undo-description="$i18n{undoDescription}" + duration="[[toastDuration_]]"> + </cr-toast-manager> <div class="settings-box block first"> <h2>$i18n{passwordExceptionsHeading}</h2> </div> diff --git a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js index 1f552fdf4ec..a98d69646d4 100644 --- a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js +++ b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js @@ -36,9 +36,11 @@ Polymer({ behaviors: [ I18nBehavior, + WebUIListenerBehavior, ListPropertyUpdateBehavior, Polymer.IronA11yKeysBehavior, settings.GlobalScrollTargetBehavior, + PrefsBehavior, ], properties: { @@ -94,6 +96,18 @@ Polymer({ }, /** @private */ + hidePasswordsLink_: { + type: Boolean, + computed: 'computeHidePasswordsLink_(syncPrefs_, syncStatus_)', + }, + + /** @private */ + passwordsLeakDetectionEnabled_: { + type: Boolean, + value: loadTimeData.getBoolean('passwordsLeakDetectionEnabled'), + }, + + /** @private */ showExportPasswords_: { type: Boolean, computed: 'hasPasswords_(savedPasswords.splices)', @@ -111,6 +125,23 @@ Polymer({ /** @private */ showPasswordEditDialog_: Boolean, + // <if expr="not chromeos"> + /** @private {Array<!settings.StoredAccount>} */ + storedAccounts_: Object, + // </if> + + /** @private {settings.SyncPrefs} */ + syncPrefs_: Object, + + /** @private {settings.SyncStatus} */ + syncStatus_: Object, + + /** @private */ + userSignedIn_: { + type: Boolean, + computed: 'computeUserSignedIn_(syncStatus_, storedAccounts_)', + }, + /** Filter on the saved passwords and exceptions. */ filter: { type: String, @@ -156,11 +187,14 @@ Polymer({ }, /** - * The element to return focus to, when the currently active dialog is - * closed. - * @private {?HTMLElement} + * A stack of the elements that triggered dialog to open and should therefore + * receive focus when that dialog is closed. The bottom of the stack is the + * element that triggered the earliest open dialog and top of the stack is the + * element that triggered the most recent (i.e. active) dialog. If no dialog + * is open, the stack is empty. + * @private {!Array<Element>} */ - activeDialogAnchor_: null, + activeDialogAnchorStack_: [], /** * @type {PasswordManagerProxy} @@ -210,7 +244,7 @@ Polymer({ this.tokenRequestManager_ = new settings.BlockingRequestManager(); } else { this.tokenRequestManager_ = new settings.BlockingRequestManager( - () => this.showPasswordPromptDialog_ = true); + this.openPasswordPromptDialog_.bind(this)); } // </if> @@ -226,6 +260,23 @@ Polymer({ this.notifySplices('savedPasswords', []); + const syncBrowserProxy = settings.SyncBrowserProxyImpl.getInstance(); + + const syncStatusChanged = syncStatus => this.syncStatus_ = syncStatus; + syncBrowserProxy.getSyncStatus().then(syncStatusChanged); + this.addWebUIListener('sync-status-changed', syncStatusChanged); + + // <if expr="not chromeos"> + const storedAccountsChanged = storedAccounts => this.storedAccounts_ = + storedAccounts; + syncBrowserProxy.getStoredAccounts().then(storedAccountsChanged); + this.addWebUIListener('stored-accounts-updated', storedAccountsChanged); + // </if> + + const syncPrefsChanged = syncPrefs => this.syncPrefs_ = syncPrefs; + syncBrowserProxy.sendSyncPrefsChanged(); + this.addWebUIListener('sync-prefs-changed', syncPrefsChanged); + Polymer.RenderStatus.afterNextRender(this, function() { Polymer.IronA11yAnnouncer.requestAvailability(); }); @@ -243,9 +294,8 @@ Polymer({ * @type {function(!Array<PasswordManagerProxy.ExceptionEntry>):void} */ (this.setPasswordExceptionsListener_)); - - if (this.$.undoToast.open) { - this.$.undoToast.hide(); + if (cr.toastManager.getInstance().isToastOpen) { + cr.toastManager.getInstance().hide(); } }, @@ -273,6 +323,12 @@ Polymer({ onPasswordPromptClosed_: function() { this.showPasswordPromptDialog_ = false; + cr.ui.focusWithoutInk(assert(this.activeDialogAnchorStack_.pop())); + }, + + openPasswordPromptDialog_: function() { + this.activeDialogAnchorStack_.push(getDeepActiveElement()); + this.showPasswordPromptDialog_ = true; }, // </if> @@ -290,8 +346,7 @@ Polymer({ /** @private */ onPasswordEditDialogClosed_: function() { this.showPasswordEditDialog_ = false; - cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_)); - this.activeDialogAnchor_ = null; + cr.ui.focusWithoutInk(assert(this.activeDialogAnchorStack_.pop())); // Trigger a re-evaluation of the activePassword as the visibility state of // the password might have changed. @@ -299,6 +354,33 @@ Polymer({ }, /** + * @return {boolean} + * @private + */ + computeHidePasswordsLink_: function() { + return !!this.syncStatus_ && !!this.syncStatus_.signedIn && + !!this.syncPrefs_ && !!this.syncPrefs_.encryptAllData; + }, + + /** + * @return {boolean} + * @private + */ + computeUserSignedIn_: function() { + return (!!this.syncStatus_ && !!this.syncStatus_.signedIn) || + (!!this.storedAccounts_ && this.storedAccounts_.length > 0); + }, + + /** + * @return {boolean} + * @private + */ + getCheckedLeakDetection_: function() { + return this.userSignedIn_ && + !!this.getPref('profile.password_manager_leak_detection').value; + }, + + /** * @param {string} filter * @return {!Array<!PasswordManagerProxy.UiEntryWithPassword>} * @private @@ -314,6 +396,20 @@ Polymer({ }, /** + * @return {string} + * @private + */ + getPasswordsLeakDetectionSubLabel_: function() { + if (this.userSignedIn_) { + return this.i18n('passwordsLeakDetectionSignedInDescription'); + } + if (this.getPref('profile.password_manager_leak_detection').value) { + return this.i18n('passwordsLeakDetectionSignedOutEnabledDescription'); + } + return this.i18n('passwordsLeakDetectionSignedOutDisabledDescription'); + }, + + /** * @param {string} filter * @return {function(!chrome.passwordsPrivate.ExceptionEntry): boolean} * @private @@ -330,8 +426,7 @@ Polymer({ onMenuRemovePasswordTap_: function() { this.passwordManager_.removeSavedPassword( this.activePassword.item.entry.id); - this.fire('iron-announce', {text: this.$.undoLabel.textContent}); - this.$.undoToast.show(); + cr.toastManager.getInstance().show(this.i18n('passwordDeleted'), false); /** @type {CrActionMenuElement} */ (this.$.menu).close(); }, @@ -344,7 +439,7 @@ Polymer({ const activeElement = getDeepActiveElement(); if (!activeElement || !isEditable(activeElement)) { this.passwordManager_.undoRemoveSavedPasswordOrException(); - this.$.undoToast.hide(); + cr.toastManager.getInstance().hide(); // Preventing the default is necessary to not conflict with a possible // search action. event.preventDefault(); @@ -353,7 +448,7 @@ Polymer({ onUndoButtonTap_: function() { this.passwordManager_.undoRemoveSavedPasswordOrException(); - this.$.undoToast.hide(); + cr.toastManager.getInstance().hide(); }, /** * Fires an event that should delete the password exception. @@ -376,7 +471,7 @@ Polymer({ this.activePassword = /** @type {!PasswordListItemElement} */ (event.detail.listItem); menu.showAt(target); - this.activeDialogAnchor_ = target; + this.activeDialogAnchorStack_.push(target); }, /** @@ -389,7 +484,7 @@ Polymer({ /** @type {!HTMLElement} */ (this.$$('#exportImportMenuButton')); menu.showAt(target); - this.activeDialogAnchor_ = target; + this.activeDialogAnchorStack_.push(target); }, /** @@ -413,8 +508,7 @@ Polymer({ /** @private */ onPasswordsExportDialogClosed_: function() { this.showPasswordsExportDialog_ = false; - cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_)); - this.activeDialogAnchor_ = null; + cr.ui.focusWithoutInk(assert(this.activeDialogAnchorStack_.pop())); }, /** diff --git a/chromium/chrome/browser/resources/settings/basic_page/BUILD.gn b/chromium/chrome/browser/resources/settings/basic_page/BUILD.gn index 3680ef7085f..ab89a35dd33 100644 --- a/chromium/chrome/browser/resources/settings/basic_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/basic_page/BUILD.gn @@ -18,6 +18,7 @@ js_library("basic_page") { "../android_apps_page:android_apps_browser_proxy", "../change_password_page:change_password_browser_proxy", "../chrome_cleanup_page:chrome_cleanup_proxy", + "../prefs:prefs_behavior", "../settings_page:main_page_behavior", "//ui/webui/resources/js:load_time_data", "//ui/webui/resources/js:web_ui_listener_behavior", 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 80d61cd92c3..46deb873d7d 100644 --- a/chromium/chrome/browser/resources/settings/basic_page/basic_page.html +++ b/chromium/chrome/browser/resources/settings/basic_page/basic_page.html @@ -17,7 +17,7 @@ <link rel="import" href="../settings_page_css.html"> <if expr="chromeos"> -<link rel="import" href="../app_management_page/app_management_page.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="../android_apps_page/android_apps_browser_proxy.html"> <link rel="import" href="../android_apps_page/android_apps_page.html"> <link rel="import" href="../bluetooth_page/bluetooth_page.html"> @@ -26,6 +26,7 @@ <link rel="import" href="../device_page/device_page.html"> <link rel="import" href="../internet_page/internet_page.html"> <link rel="import" href="../multidevice_page/multidevice_page.html"> +<link rel="import" href="../prefs/prefs_behavior.html"> </if> <if expr="not chromeos"> @@ -36,7 +37,7 @@ includes both the basic and advanced settings. --> <dom-module id="settings-basic-page"> <template> - <style include="settings-page-styles cr-hidden-style"> + <style include="settings-page-styles cr-hidden-style settings-shared"> :host([is-subpage-animating]) { /* Prevent an unwanted horizontal scrollbar when transitioning back from * a sub-page. */ @@ -62,13 +63,14 @@ font-weight: 600; } + #osSettingsBanner, #secondaryUserBanner { @apply --cr-card-elevation; align-items: center; background-color: white; border-radius: 2px; display: flex; - margin: 21px 0; + margin-top: 21px; } #secondaryUserIcon { @@ -85,11 +87,14 @@ #toggleContainer { align-items: center; + color: var(--cr-primary-text-color); display: flex; font: inherit; justify-content: center; margin-bottom: 0; margin-top: 0; + padding-bottom: 0; + padding-top: 0; } #toggleSpacer { @@ -108,12 +113,22 @@ </settings-reset-profile-banner> </template> <if expr="chromeos"> + <template is="dom-if" if="[[showOSSettingsBanner_]]"> + <div id="osSettingsBanner" class="settings-box"> + <div class="start" on-click="onOSSettingsBannerClick_"> + $i18nRaw{osSettingsBannerText} + </div> + <cr-icon-button class="icon-clear" + id="hideOSSettings" + aria-label="$i18n{clear}" + on-click="onOSSettingsBannerClosed_"> + </cr-icon-button> + </div> + </template> <div id="secondaryUserBanner" hidden="[[!showSecondaryUserBanner_]]"> <div id="secondaryUserIcon"></div> <div class="flex">$i18n{secondaryUserBannerText}</div> </div> -</if> -<if expr="chromeos"> <template is="dom-if" if="[[showPage_(pageVisibility.internet)]]" restamp> <settings-section page-title="$i18n{internetPageTitle}" @@ -180,21 +195,12 @@ </settings-section> </template> </if> - <template is="dom-if" if="[[showPage_(pageVisibility.search)]]" restamp> - <settings-section page-title="$i18n{searchPageTitle}" - section="search"> - <settings-search-page prefs="{{prefs}}"></settings-search-page> - </settings-section> - </template> + <settings-section page-title="$i18n{searchPageTitle}" + section="search"> + <settings-search-page prefs="{{prefs}}"></settings-search-page> + </settings-section> <if expr="chromeos"> - <template is="dom-if" if="[[showApps]]" restamp> - <settings-section page-title="$i18n{appsPageTitle}" section="apps"> - <settings-app-management-page> - </settings-app-management-page> - </settings-section> - </template> - <template is="dom-if" if="[[shouldCreateAndroidAppsSection_( - showAndroidApps, pageVisibility)]]" restamp> + <template is="dom-if" if="[[showAndroidApps]]" restamp> <settings-section page-title="$i18n{androidAppsPageTitle}" section="androidApps" hidden$="[[!shouldShowAndroidAppsSection_( androidAppsInfo)]]"> @@ -314,13 +320,10 @@ </settings-section> </template> <if expr="not chromeos"> - <template is="dom-if" if="[[showPage_(pageVisibility.system)]]" - restamp> - <settings-section page-title="$i18n{systemPageTitle}" - section="system"> - <settings-system-page prefs="{{prefs}}"></settings-system-page> - </settings-section> - </template> + <settings-section page-title="$i18n{systemPageTitle}" + section="system"> + <settings-system-page prefs="{{prefs}}"></settings-system-page> + </settings-section> </if> <template is="dom-if" if="[[showPage_(pageVisibility.reset)]]" restamp> 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 53f94adc713..f2f0131a77c 100644 --- a/chromium/chrome/browser/resources/settings/basic_page/basic_page.js +++ b/chromium/chrome/browser/resources/settings/basic_page/basic_page.js @@ -6,12 +6,33 @@ * @fileoverview * 'settings-basic-page' is the settings page containing the actual settings. */ +(function() { +'use strict'; + +// <if expr="chromeos"> +const OS_BANNER_INTERACTION_METRIC_NAME = + 'ChromeOS.Settings.OsBannerInteraction'; + +/** + * These values are persisted to logs and should not be renumbered or re-used. + * See tools/metrics/histograms/enums.xml. + * @enum {number} + */ +const CrosSettingsOsBannerInteraction = { + NotShown: 0, + Shown: 1, + Clicked: 2, + Closed: 3, +}; +// </if> + Polymer({ is: 'settings-basic-page', behaviors: [ settings.MainPageBehavior, settings.RouteObserverBehavior, + PrefsBehavior, WebUIListenerBehavior, ], @@ -23,8 +44,6 @@ Polymer({ }, // <if expr="chromeos"> - showApps: Boolean, - showAndroidApps: Boolean, showCrostini: Boolean, @@ -91,6 +110,13 @@ Polymer({ type: Boolean, computed: 'computeShowSecondaryUserBanner_(hasExpandedSection_)', }, + + /** @private */ + showOSSettingsBanner_: { + type: Boolean, + computed: 'computeShowOSSettingsBanner_(' + + 'prefs.settings.cros.show_os_banner.value, currentRoute_)', + }, // </if> /** @private {!settings.Route|undefined} */ @@ -111,6 +137,11 @@ Polymer({ */ advancedTogglingInProgress_: false, + // <if expr="chromeos"> + /** @private {boolean} */ + osBannerShowMetricRecorded_: false, + // </if> + /** @override */ attached: function() { this.currentRoute_ = settings.getCurrentRoute(); @@ -220,6 +251,58 @@ Polymer({ return !this.hasExpandedSection_ && loadTimeData.getBoolean('isSecondaryUser'); }, + + /** + * @return {boolean|undefined} + * @private + */ + computeShowOSSettingsBanner_: function() { + // this.prefs is implicitly used by this.getPref() below. + if (!this.prefs || !this.currentRoute_) { + return; + } + // Don't show the banner when SplitSettings is disabled (and hence this page + // is already showing OS settings). + if (loadTimeData.getBoolean('showOSSettings')) { + return false; + } + const showPref = /** @type {boolean} */ ( + this.getPref('settings.cros.show_os_banner').value); + + // Banner only shows on the main page because direct navigations to a + // sub-page are unlikely to be due to a user looking for an OS setting. + const show = showPref && !this.currentRoute_.isSubpage(); + + // Record the show metric once. We can't record the metric in attached() + // because prefs might not be ready yet. + if (!this.osBannerShowMetricRecorded_) { + chrome.metricsPrivate.recordEnumerationValue( + OS_BANNER_INTERACTION_METRIC_NAME, + show ? CrosSettingsOsBannerInteraction.Shown : + CrosSettingsOsBannerInteraction.NotShown, + Object.keys(CrosSettingsOsBannerInteraction).length); + this.osBannerShowMetricRecorded_ = true; + } + return show; + }, + + /** @private */ + onOSSettingsBannerClick_: function() { + // The label has a link that opens the page, so just record the metric. + chrome.metricsPrivate.recordEnumerationValue( + OS_BANNER_INTERACTION_METRIC_NAME, + CrosSettingsOsBannerInteraction.Clicked, + Object.keys(CrosSettingsOsBannerInteraction).length); + }, + + /** @private */ + onOSSettingsBannerClosed_: function() { + this.setPrefValue('settings.cros.show_os_banner', false); + chrome.metricsPrivate.recordEnumerationValue( + OS_BANNER_INTERACTION_METRIC_NAME, + CrosSettingsOsBannerInteraction.Closed, + Object.keys(CrosSettingsOsBannerInteraction).length); + }, // </if> /** @private */ @@ -236,18 +319,6 @@ Polymer({ }, /** - * Returns true in case Android apps settings needs to be created. It is not - * created in case ARC++ is not allowed for the current profile. - * @return {boolean} - * @private - */ - shouldCreateAndroidAppsSection_: function() { - const visibility = /** @type {boolean|undefined} */ ( - this.get('pageVisibility.androidApps')); - return this.showAndroidApps && this.showPage_(visibility); - }, - - /** * Returns true in case Android apps settings should be shown. It is not * shown in case we don't have the Play Store app and settings app is not * yet available. @@ -382,3 +453,4 @@ Polymer({ return bool.toString(); }, }); +})(); 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 bf85b1f8556..739b1b7b29b 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 @@ -5,6 +5,7 @@ <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="../chromeos/os_icons.html"> <link rel="import" href="../icons.html"> <link rel="import" href="../settings_shared_css.html"> diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js index ead6fe1075e..9ed885e2782 100644 --- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js +++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js @@ -132,24 +132,24 @@ Polymer({ case 'computer': return 'cr:computer'; case 'phone': - return 'settings:smartphone'; + return 'os-settings:smartphone'; case 'audio': case 'carAudio': - return 'settings:headset'; + return 'os-settings:headset'; case 'video': return 'cr:videocam'; case 'joystick': case 'gamepad': - return 'settings:gamepad'; + return 'os-settings:gamepad'; case 'keyboard': case 'keyboardMouseCombo': - return 'settings:keyboard'; + return 'os-settings:keyboard'; case 'tablet': - return 'settings:tablet'; + return 'os-settings:tablet'; case 'mouse': - return 'settings:mouse'; + return 'os-settings:mouse'; default: - return device.connected ? 'settings:bluetooth-connected' : + return device.connected ? 'os-settings:bluetooth-connected' : 'cr:bluetooth'; } }, diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html index 81f28b1245d..44dac770e3e 100644 --- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html +++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html @@ -5,8 +5,8 @@ <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> +<link rel="import" href="../chromeos/os_icons.html"> <link rel="import" href="../i18n_setup.html"> -<link rel="import" href="../icons.html"> <link rel="import" href="../prefs/prefs.html"> <link rel="import" href="../prefs/prefs_behavior.html"> <link rel="import" href="../settings_page/settings_animated_pages.html"> 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 b84118487a0..fd9aabbdf7f 100644 --- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js +++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.js @@ -172,7 +172,7 @@ Polymer({ // Don't use |this.bluetoothToggleState_| here, since it has not been // updated yet to the latest value. if (!bluetoothToggleState) { - return 'settings:bluetooth-disabled'; + return 'os-settings:bluetooth-disabled'; } return 'cr:bluetooth'; }, diff --git a/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn index e2642b28c73..37366df42de 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn @@ -28,6 +28,13 @@ if (optimize_webui) { "crisper.js", "lazy_load.crisper.js", ] + excludes = [ + "chrome://os-settings/app-management/app_management.mojom-lite.js", + "chrome://os-settings/app-management/bitmap.mojom-lite.js", + "chrome://os-settings/app-management/image_info.mojom-lite.js", + "chrome://os-settings/app-management/image.mojom-lite.js", + "chrome://os-settings/app-management/types.mojom-lite.js", + ] deps = [ ":unpak", @@ -63,6 +70,7 @@ if (optimize_webui) { group("closure_compile") { deps = [ "os_a11y_page:closure_compile", + "os_apps_page:closure_compile", "os_files_page:closure_compile", "os_languages_page:closure_compile", "os_people_page:closure_compile", diff --git a/chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/BUILD.gn index d404c63c107..b54af0ac04f 100644 --- a/chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/BUILD.gn @@ -6,13 +6,16 @@ import("//third_party/closure_compiler/compile_js.gni") js_type_check("closure_compile") { deps = [ - ":app_management_page", + ":os_apps_page", ] } -js_library("app_management_page") { +js_library("os_apps_page") { deps = [ - "..:open_window_proxy", + "../../:route", + "../../settings_page:settings_animated_pages", + "app_management_page", ] + externs_list = [ "$externs_path/metrics_private.js" ] } diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn new file mode 100644 index 00000000000..c9841d1a9d7 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn @@ -0,0 +1,230 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +js_type_check("closure_compile") { + deps = [ + ":actions", + ":api_listener", + ":app_item", + ":app_management_page", + ":app_permission_view", + ":arc_permission_view", + ":browser_proxy", + ":chrome_app_permission_view", + ":constants", + ":dom_switch", + ":fake_page_handler", + ":main_view", + ":permission_item", + ":permission_toggle", + ":pin_to_shelf_item", + ":pwa_permission_view", + ":reducers", + ":router", + ":store", + ":store_client", + ":toggle_row", + ":types", + ":uninstall_button", + ":util", + ] +} + +js_library("actions") { + deps = [ + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", + "//ui/webui/resources/js:cr", + ] +} + +js_library("api_listener") { + deps = [ + ":actions", + ":store", + ":util", + "//ui/webui/resources/js:cr", + ] +} + +js_library("app_item") { + deps = [ + ":actions", + ":store_client", + "//ui/webui/resources/js:load_time_data", + ] +} + +js_library("app_management_page") { + deps = [ + ":actions", + ":browser_proxy", + ":main_view", + ":router", + ":store", + ":store_client", + ] +} + +js_library("app_permission_view") { + deps = [ + ":arc_permission_view", + ":chrome_app_permission_view", + ":dom_switch", + ":pwa_permission_view", + ":store_client", + ] +} + +js_library("arc_permission_view") { + deps = [ + ":constants", + ":fake_page_handler", + ":permission_item", + ":pin_to_shelf_item", + ":store_client", + ] +} + +js_library("browser_proxy") { + deps = [ + ":fake_page_handler", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", + "//ui/webui/resources/js:cr", + ] +} + +js_library("chrome_app_permission_view") { + deps = [ + ":fake_page_handler", + ":pin_to_shelf_item", + ":store_client", + ] +} + +js_library("constants") { +} + +js_library("dom_switch") { +} + +js_library("fake_page_handler") { + deps = [ + ":constants", + ":types", + ":util", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", + "//ui/webui/resources/js:cr", + ] +} + +js_library("main_view") { + deps = [ + ":app_item", + ":browser_proxy", + ":constants", + ":store_client", + "//ui/webui/resources/js:load_time_data", + ] +} + +js_library("permission_item") { + deps = [ + ":fake_page_handler", + ":permission_toggle", + ":store_client", + ":util", + ] +} + +js_library("permission_toggle") { + deps = [ + ":util", + ] +} + +js_library("pin_to_shelf_item") { + deps = [ + ":browser_proxy", + ":toggle_row", + ":types", + ] +} + +js_library("pwa_permission_view") { + deps = [ + ":constants", + ":fake_page_handler", + ":permission_item", + ":pin_to_shelf_item", + ":store_client", + ] +} + +js_library("reducers") { + deps = [ + ":types", + ":util", + "//ui/webui/resources/js:cr", + ] +} + +js_library("router") { + deps = [ + ":actions", + ":constants", + ":store_client", + ] +} + +js_library("store") { + deps = [ + ":reducers", + ":util", + "//ui/webui/resources/js:cr", + "//ui/webui/resources/js/cr/ui:store", + ] +} + +js_library("store_client") { + deps = [ + ":store", + ":types", + "//ui/webui/resources/js:cr", + "//ui/webui/resources/js/cr/ui:store", + "//ui/webui/resources/js/cr/ui:store_client", + ] +} + +js_library("toggle_row") { + deps = [ + ":types", + "//ui/webui/resources/cr_elements/cr_toggle:cr_toggle", + "//ui/webui/resources/cr_elements/policy:cr_policy_indicator", + ] +} + +js_library("types") { + deps = [ + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile", + ] +} + +js_library("uninstall_button") { + deps = [ + ":store_client", + ":util", + "//ui/webui/resources/cr_elements/cr_button:cr_button", + "//ui/webui/resources/cr_elements/policy:cr_tooltip_icon", + ] +} + +js_library("util") { + deps = [ + ":constants", + ":types", + "//ui/webui/resources/js:cr", + ] +} diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn index a1b5d3d633d..38ac772a9b0 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn @@ -20,7 +20,6 @@ js_library("smb_shares_page") { js_library("os_files_page") { deps = [ - "../..:page_visibility", "../..:route", ] } diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn index 85fc4d825ac..42ff0d047c9 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn @@ -7,28 +7,27 @@ import("//third_party/closure_compiler/compile_js.gni") js_type_check("closure_compile") { deps = [ ":os_powerwash_dialog", + ":os_reset_browser_proxy", ":os_reset_page", - ":reset_os_proxy", ] } js_library("os_powerwash_dialog") { deps = [ - ":reset_os_proxy", + ":os_reset_browser_proxy", "../..:lifetime_browser_proxy", ] } js_library("os_reset_page") { deps = [ - "../..:page_visibility", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:cr", "//ui/webui/resources/js/cr/ui:focus_without_ink", ] } -js_library("reset_os_proxy") { +js_library("os_reset_browser_proxy") { deps = [ "//ui/webui/resources/js:cr", ] diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn index 397f4d3e434..3c3c14e9d3d 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn @@ -12,7 +12,6 @@ js_type_check("closure_compile") { js_library("os_settings_menu") { deps = [ - "../..:page_visibility", "../..:route", "//third_party/polymer/v1_0/components-chromium/iron-collapse:iron-collapse-extracted", "//third_party/polymer/v1_0/components-chromium/paper-ripple:paper-ripple-extracted", diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn index e34d80d6362..11525a13645 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn @@ -17,6 +17,7 @@ js_library("os_settings_page") { "../..:search_settings", "../../android_apps_page:android_apps_browser_proxy", "../../chrome_cleanup_page:chrome_cleanup_proxy", + "../../prefs:prefs_behavior", "../../settings_page:main_page_behavior", "//ui/webui/resources/js:load_time_data", "//ui/webui/resources/js:web_ui_listener_behavior", diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_ui/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_settings_ui/BUILD.gn index b098e77ce26..058863d4b69 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_ui/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_ui/BUILD.gn @@ -16,10 +16,10 @@ js_library("os_settings_ui") { "../..:page_visibility", "../../prefs", "../os_settings_main:os_settings_main", + "../os_toolbar", "//ui/webui/resources/cr_elements:cr_container_shadow_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", "//ui/webui/resources/cr_elements/cr_drawer:cr_drawer", - "//ui/webui/resources/cr_elements/cr_toolbar:cr_toolbar", "//ui/webui/resources/cr_elements/cr_toolbar:cr_toolbar_search_field", "//ui/webui/resources/cr_elements/policy:cr_policy_indicator_behavior", "//ui/webui/resources/js:find_shortcut_behavior", diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_toolbar/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_toolbar/BUILD.gn new file mode 100644 index 00000000000..3ac49b91c8f --- /dev/null +++ b/chromium/chrome/browser/resources/settings/chromeos/os_toolbar/BUILD.gn @@ -0,0 +1,18 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +js_type_check("closure_compile") { + deps = [ + ":os_toolbar", + ] +} + +js_library("os_toolbar") { + deps = [ + "//ui/webui/resources/cr_elements/cr_toolbar:cr_toolbar_search_field", + ] + externs_list = [ "$externs_path/web_animations.js" ] +} diff --git a/chromium/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn index 7e68a1627b6..ca1cedfb81c 100644 --- a/chromium/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn @@ -6,21 +6,13 @@ import("//third_party/closure_compiler/compile_js.gni") js_type_check("closure_compile") { deps = [ - ":personalization_browser_proxy", ":personalization_page", ] } -js_library("personalization_browser_proxy") { - deps = [ - "//ui/webui/resources/js:cr", - ] - externs_list = [ "$externs_path/chrome_send.js" ] -} - js_library("personalization_page") { deps = [ - ":personalization_browser_proxy", + "../../appearance_page:wallpaper_browser_proxy", "../../settings_page:settings_animated_pages", "//ui/webui/resources/js:cr", ] diff --git a/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html b/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html index d58fdddf3d8..4a0026ee454 100644 --- a/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html +++ b/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html @@ -8,19 +8,18 @@ <dom-module id="settings-password-prompt-dialog"> <template> <style include="settings-shared"> - #passwordInput { - display: inline-block; + cr-dialog::part(dialog) { + width: 320px; } - .settings-box { + #passwordPrompt { padding: 0; } </style> - <cr-dialog id="dialog" close-text="$i18n{close}"> <div slot="title">$i18n{passwordPromptTitle}</div> <div slot="body"> - <div class="settings-box first"> + <div id="passwordPrompt" class="settings-box first line-only"> [[passwordPromptText]] </div> <cr-input id="passwordInput" type="password" 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 51bbe0199f2..8db2d75dc99 100644 --- a/chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js +++ b/chromium/chrome/browser/resources/settings/controls/pref_control_behavior.js @@ -37,6 +37,10 @@ const PrefControlBehavior = { } error += ' in ' + this.domHost.tagName; console.error(error); + } else if ( + this.pref.enforcement == + chrome.settingsPrivate.Enforcement.PARENT_SUPERVISED) { + console.error('PARENT_SUPERVISED is not enforced by pref controls'); } }); }, diff --git a/chromium/chrome/browser/resources/settings/crostini_page/BUILD.gn b/chromium/chrome/browser/resources/settings/crostini_page/BUILD.gn index db0a920aee3..2e4035eae4a 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/crostini_page/BUILD.gn @@ -24,6 +24,7 @@ js_library("crostini_browser_proxy") { js_library("crostini_export_import") { deps = [ ":crostini_browser_proxy", + "//ui/webui/resources/js:web_ui_listener_behavior", ] } diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_browser_proxy.js b/chromium/chrome/browser/resources/settings/crostini_page/crostini_browser_proxy.js index 225da323ed6..f9b965ea621 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_browser_proxy.js +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_browser_proxy.js @@ -51,14 +51,26 @@ cr.define('settings', function() { */ removeCrostiniSharedPath(vmName, path) {} - /* Request chrome send a crostini-installer-status-changed event with the - current installer status */ + /** + * Request chrome send a crostini-installer-status-changed event with the + * current installer status + */ requestCrostiniInstallerStatus() {} - /* Export crostini container. */ + /** + * Request chrome send a crostini-export-import-operation-status-changed + * event with the current operation status + */ + requestCrostiniExportImportOperationStatus() {} + + /** + * Export crostini container. + */ exportCrostiniContainer() {} - /* Import crostini container. */ + /** + * Import crostini container. + */ importCrostiniContainer() {} } @@ -100,6 +112,11 @@ cr.define('settings', function() { } /** @override */ + requestCrostiniExportImportOperationStatus() { + chrome.send('requestCrostiniExportImportOperationStatus'); + } + + /** @override */ exportCrostiniContainer() { chrome.send('exportCrostiniContainer'); } diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html index 88989b88f9c..43c4d73d8da 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html @@ -2,6 +2,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> +<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="crostini_browser_proxy.html"> <link rel="import" href="crostini_import_confirmation_dialog.html"> <link rel="import" href="../i18n_setup.html"> @@ -15,18 +16,18 @@ <div id="exportCrostiniLabel" class="start secondary"> $i18n{crostiniExportLabel} </div> - <cr-button on-click="onExportClick_" - aria-labelledby="exportCrostiniLabel"> - $i18n{crostiniExport} + <cr-button on-click="onExportClick_" disabled="[[!enableButtons_]]" + aria-labelledby="exportCrostiniLabel"> + $i18n{crostiniExport} </cr-button> </div> <div id="import" class="list-item"> <div id="importCrostiniLabel" class="start secondary"> $i18n{crostiniImportLabel} </div> - <cr-button on-click="onImportClick_" - aria-labelledby="importCrostiniLabel"> - $i18n{crostiniImport} + <cr-button on-click="onImportClick_" disabled="[[!enableButtons_]]" + aria-labelledby="importCrostiniLabel"> + $i18n{crostiniImport} </cr-button> </div> </div> diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js index fa1be63a919..1cb7d34abc2 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js @@ -11,12 +11,33 @@ Polymer({ is: 'settings-crostini-export-import', + behaviors: [WebUIListenerBehavior], + properties: { /** @private */ showImportConfirmationDialog_: { type: Boolean, value: false, }, + + /** + * Whether the export import buttons should be enabled. Initially false + * until status has been confirmed. + * @private {boolean} + */ + enableButtons_: { + type: Boolean, + value: false, + }, + }, + + attached: function() { + this.addWebUIListener( + 'crostini-export-import-operation-status-changed', inProgress => { + this.enableButtons_ = !inProgress; + }); + settings.CrostiniBrowserProxyImpl.getInstance() + .requestCrostiniExportImportOperationStatus(); }, /** @private */ diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html index 1949eb2f98f..d241d5baf3a 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html @@ -43,7 +43,7 @@ <template is="dom-if" if="[[!prefs.crostini.enabled.value]]"> <div class="separator"></div> <cr-button id="enable" - disabled="[[!allowCrostini]]" + disabled$="[[disableCrostiniInstall_]]" on-click="onEnableTap_" aria-label="$i18n{crostiniPageTitle}" aria-describedby="secondaryText"> diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.js b/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.js index 1f2b08a13e9..7a74d5b5fbd 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.js +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.js @@ -12,7 +12,7 @@ Polymer({ is: 'settings-crostini-page', - behaviors: [I18nBehavior, PrefsBehavior], + behaviors: [I18nBehavior, PrefsBehavior, WebUIListenerBehavior], properties: { /** Preferences state. */ @@ -49,6 +49,27 @@ Polymer({ return map; }, }, + + /** + * Whether the install option should be enabled. + * @private {boolean} + */ + disableCrostiniInstall_: { + type: Boolean, + }, + }, + + attached: function() { + if (!loadTimeData.getBoolean('allowCrostini')) { + this.disableCrostiniInstall_ = true; + return; + } + this.addWebUIListener( + 'crostini-installer-status-changed', (installerShowing) => { + this.disableCrostiniInstall_ = installerShowing; + }); + settings.CrostiniBrowserProxyImpl.getInstance() + .requestCrostiniInstallerStatus(); }, /** diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html index 125be381c77..c77f6161ec1 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html @@ -17,14 +17,12 @@ label="$i18n{crostiniSharedPaths}" on-click="onSharedPathsClick_"> </cr-link-row> - <template is="dom-if" if="[[enableCrostiniUsbDeviceSupport_]]"> - <cr-link-row - class="hr" - label="$i18n{crostiniSharedUsbDevicesLabel}" - id="crostini-shared-usb-devices" - on-click="onSharedUsbDevicesClick_"> - </cr-link-row> - </template> + <cr-link-row + class="hr" + label="$i18n{crostiniSharedUsbDevicesLabel}" + id="crostini-shared-usb-devices" + on-click="onSharedUsbDevicesClick_"> + </cr-link-row> <template is="dom-if" if="[[showCrostiniExportImport_]]"> <cr-link-row class="hr" diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.js b/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.js index 736b8a86e4b..66d8ca13fce 100644 --- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.js +++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.js @@ -20,17 +20,6 @@ Polymer({ }, /** - * Whether CrostiniUsbSupport flag is enabled. - * @private {boolean} - */ - enableCrostiniUsbDeviceSupport_: { - type: Boolean, - value: function() { - return loadTimeData.getBoolean('enableCrostiniUsbDeviceSupport'); - }, - }, - - /** * Whether export / import UI should be displayed. * @private {boolean} */ 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 735549d7721..1575327101d 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 @@ -65,7 +65,11 @@ </settings-toggle-button> <cr-link-row class="hr" id="setDateTime" on-click="onSetDateTimeTap_" hidden$="[[!canSetDateTime_]]" - label="$i18n{setDateTime}"></cr-link-row> + label="$i18n{setDateTime}"> + <template is="dom-if" if="[[displayManagedByParentIcon_]]"> + <cr-policy-indicator indicator-type="parent"></cr-policy-indicator> + </template> + </cr-link-row> </div> <template is="dom-if" route-path="/dateTime/timeZone"> <settings-subpage data-route="DATETIME_TIMEZONE_SUBPAGE" 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 186c536e121..f5f8a8f3761 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 @@ -58,6 +58,17 @@ Polymer({ /** @private */ isChild_: {type: Boolean, value: loadTimeData.getBoolean('isChild')}, + + /** + * Whether the icon informing that this action is managed by a parent is + * displayed. + * @private + */ + displayManagedByParentIcon_: { + type: Boolean, + value: loadTimeData.getBoolean('isChild') && + loadTimeData.getBoolean('timeActionsProtectedForChild') + }, }, /** @override */ diff --git a/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.html b/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.html index 2ae2ba3226e..2ee6c254ec8 100644 --- a/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.html +++ b/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.html @@ -36,7 +36,7 @@ <settings-dropdown-menu id="timeZoneResolveMethodDropdown" pref="{{prefs.generated.resolve_timezone_by_geolocation_method_short}}" label="$i18n{selectTimeZoneResolveMethod}" - hidden="[[!prefs.generated.resolve_timezone_by_geolocation_on_off.value]]" + disabled="[[!prefs.generated.resolve_timezone_by_geolocation_on_off.value]]" menu-options="[[getTimeZoneResolveMethodsList_( prefs.generated.resolve_timezone_by_geolocation_method_short)]]"> </settings-dropdown-menu> diff --git a/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.js b/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.js index f77b53e820c..3e29c0d9f05 100644 --- a/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.js +++ b/chromium/chrome/browser/resources/settings/date_time_page/timezone_subpage.js @@ -27,22 +27,26 @@ Polymer({ */ getTimeZoneResolveMethodsList_: function() { const result = []; + const pref = + this.getPref('generated.resolve_timezone_by_geolocation_method_short'); // Make sure current value is in the list, even if it is not // user-selectable. - if (this.getPref('generated.resolve_timezone_by_geolocation_method_short') - .value == settings.TimeZoneAutoDetectMethod.DISABLED) { - result.push({ - value: settings.TimeZoneAutoDetectMethod.DISABLED, - name: loadTimeData.getString('setTimeZoneAutomaticallyDisabled') - }); + if (pref.value == settings.TimeZoneAutoDetectMethod.DISABLED) { + // If disabled by policy, show the 'Automatic timezone disabled' label. + // Otherwise, just show the default string, since the control will be + // disabled as well. + const label = pref.controlledBy ? + loadTimeData.getString('setTimeZoneAutomaticallyDisabled') : + loadTimeData.getString('setTimeZoneAutomaticallyIpOnlyDefault'); + result.push( + {value: settings.TimeZoneAutoDetectMethod.DISABLED, name: label}); } result.push({ value: settings.TimeZoneAutoDetectMethod.IP_ONLY, name: loadTimeData.getString('setTimeZoneAutomaticallyIpOnlyDefault') }); - if (this.getPref('generated.resolve_timezone_by_geolocation_method_short') - .value == + if (pref.value == settings.TimeZoneAutoDetectMethod.SEND_WIFI_ACCESS_POINTS) { result.push({ value: settings.TimeZoneAutoDetectMethod.SEND_WIFI_ACCESS_POINTS, diff --git a/chromium/chrome/browser/resources/settings/device_page/device_page.html b/chromium/chrome/browser/resources/settings/device_page/device_page.html index 1f22b1fe3e7..8eacafb0ba7 100644 --- a/chromium/chrome/browser/resources/settings/device_page/device_page.html +++ b/chromium/chrome/browser/resources/settings/device_page/device_page.html @@ -85,7 +85,7 @@ <template is="dom-if" if="[[androidEnabled_]]"> <template is="dom-if" route-path="/storage/externalStoragePreferences"> <settings-subpage - associated-control="[[$$('#externalStoragePreferencesRow')]]" + associated-control="[[$$('#storageRow')]]" page-title="$i18n{storageExternal}"> <settings-storage-external prefs="{{prefs}}"> </settings-storage-external> 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 2c8a7bf3606..13fa10e6b8a 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 @@ -78,6 +78,14 @@ settings.NoteAppLockScreenSupport = { */ settings.NoteAppInfo; +/** + * @typedef {{ + * label: string, + * uuid: string + * }} + */ +settings.ExternalStorage; + cr.define('settings', function() { /** @interface */ class DevicePageBrowserProxy { @@ -154,6 +162,16 @@ cr.define('settings', function() { * actions from the lock screen. */ setPreferredNoteTakingAppEnabledOnLockScreen(enabled) {} + + /** Requests an external storage list update. */ + updateExternalStorages() {} + + /** + * |callback| is run when the list of plugged-in external storages is + * available after |updateExternalStorages| has been called. + * @param {function(Array<!settings.ExternalStorage>):void} callback + */ + setExternalStoragesUpdatedCallback(callback) {} } /** @@ -234,6 +252,16 @@ cr.define('settings', function() { setPreferredNoteTakingAppEnabledOnLockScreen(enabled) { chrome.send('setPreferredNoteTakingAppEnabledOnLockScreen', [enabled]); } + + /** @override */ + updateExternalStorages() { + chrome.send('updateExternalStorages'); + } + + /** @override */ + setExternalStoragesUpdatedCallback(callback) { + cr.addWebUIListener('onExternalStoragesUpdated', callback); + } } cr.addSingletonGetter(DevicePageBrowserProxyImpl); 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 514f8d719b6..7fcd324f6fe 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 @@ -5,7 +5,7 @@ <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> -<link rel="import" href="../icons.html"> +<link rel="import" href="../chromeos/os_icons.html"> <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-display-overscan-dialog"> @@ -55,7 +55,7 @@ <iron-icon icon="cr:expand-less"></iron-icon> </div> <div class="layout horizontal"> - <iron-icon icon="settings:chevron-left"></iron-icon> + <iron-icon icon="os-settings:chevron-left"></iron-icon> <iron-icon icon="cr:expand-more"></iron-icon> <iron-icon icon="cr:chevron-right"></iron-icon> </div> diff --git a/chromium/chrome/browser/resources/settings/device_page/pointers.html b/chromium/chrome/browser/resources/settings/device_page/pointers.html index 95301b12bf5..fff070da29c 100644 --- a/chromium/chrome/browser/resources/settings/device_page/pointers.html +++ b/chromium/chrome/browser/resources/settings/device_page/pointers.html @@ -22,8 +22,8 @@ .subsection > settings-toggle-button, .subsection > .settings-box { - padding-left: 0; - padding-right: 0; + padding-inline-end: 0; + padding-inline-start: 0; } </style> <div id="mouse" hidden$="[[!hasMouse]]"> @@ -43,6 +43,12 @@ pref="{{prefs.settings.mouse.reverse_scroll}}" label="$i18n{mouseReverseScroll}"> </settings-toggle-button> + <template is="dom-if" if="[[allowDisableAcceleration_]]"> + <settings-toggle-button id="mouseAcceleration" + pref="{{prefs.settings.mouse.acceleration}}" + label="$i18n{pointerAccelerationLabel}"> + </settings-toggle-button> + </template> <div class="settings-box"> <div class="start" id="mouseSpeedLabel">$i18n{mouseSpeed}</div> <settings-slider pref="{{prefs.settings.mouse.sensitivity2}}" @@ -66,6 +72,12 @@ pref="{{prefs.settings.touchpad.enable_tap_dragging}}" label="$i18n{tapDraggingLabel}"> </settings-toggle-button> + <template is="dom-if" if="[[allowDisableAcceleration_]]"> + <settings-toggle-button id="touchpadAcceleration" + pref="{{prefs.settings.touchpad.acceleration}}" + label="$i18n{pointerAccelerationLabel}"> + </settings-toggle-button> + </template> <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/pointers.js b/chromium/chrome/browser/resources/settings/device_page/pointers.js index 4414214536d..1db873949f2 100644 --- a/chromium/chrome/browser/resources/settings/device_page/pointers.js +++ b/chromium/chrome/browser/resources/settings/device_page/pointers.js @@ -30,6 +30,17 @@ Polymer({ value: [1, 2, 3, 4, 5], readOnly: true, }, + + /** + * TODO(zentaro): Remove this conditional once the feature is launched. + * @private + */ + allowDisableAcceleration_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('allowDisableMouseAcceleration'); + }, + }, }, // Used to correctly identify when the mouse button has been released. diff --git a/chromium/chrome/browser/resources/settings/device_page/storage.html b/chromium/chrome/browser/resources/settings/device_page/storage.html index 701623f33f3..f0a518e2572 100644 --- a/chromium/chrome/browser/resources/settings/device_page/storage.html +++ b/chromium/chrome/browser/resources/settings/device_page/storage.html @@ -217,7 +217,7 @@ </template> <cr-link-row id="browsingDataSize" class="hr" on-click="onBrowsingDataTap_" label="$i18n{storageItemBrowsingData}" - sub-label="$i18n{storageSizeComputing}"></cr-link-row> + sub-label="$i18n{storageSizeComputing}" external></cr-link-row> <template is="dom-if" if="[[androidRunning_]]"> <cr-link-row id="androidSize" class="hr" on-click="onAndroidTap_" label="$i18n{storageItemAndroid}" diff --git a/chromium/chrome/browser/resources/settings/device_page/storage.js b/chromium/chrome/browser/resources/settings/device_page/storage.js index 211c28c7726..2717462da66 100644 --- a/chromium/chrome/browser/resources/settings/device_page/storage.js +++ b/chromium/chrome/browser/resources/settings/device_page/storage.js @@ -162,9 +162,7 @@ Polymer({ * @private */ onBrowsingDataTap_: function() { - settings.navigateTo( - settings.routes.CLEAR_BROWSER_DATA, - /* dynamicParams */ null, /* removeSearch */ true); + window.open('chrome://settings/clearBrowserData'); }, /** diff --git a/chromium/chrome/browser/resources/settings/device_page/storage_external.html b/chromium/chrome/browser/resources/settings/device_page/storage_external.html index e215e54f0d5..922c2613d1f 100644 --- a/chromium/chrome/browser/resources/settings/device_page/storage_external.html +++ b/chromium/chrome/browser/resources/settings/device_page/storage_external.html @@ -1,21 +1,32 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/html/assert.html"> +<link rel="import" href="storage_external_entry.html"> <link rel="import" href="../prefs/prefs.html"> <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-storage-external"> <template> - <style include="settings-shared"></style> + <style include="settings-shared"> + h2 { + padding-inline-start: var(--cr-section-padding); + } + + </style> <div class="settings-box first"> <span> $i18n{storageAndroidAppsExternalDrivesNote} </span> </div> - <settings-toggle-button class="hr" - pref="{{prefs.arc.has_access_to_removable_media}}" - label="$i18n{storageAndroidAppsExternalDrives}"> - </settings-toggle-button> + <h2>$i18n{storageExternalStorageListHeader}</h2> + <iron-list id="removableDevices" preserve-focus + items="[[externalStorages_]]"> + <template> + <storage-external-entry uuid="[[item.uuid]]" label="[[item.label]]" + prefs="{{prefs}}"> + </storage-external-entry> + </template> + </iron-list> </template> <script src="storage_external.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/settings/device_page/storage_external.js b/chromium/chrome/browser/resources/settings/device_page/storage_external.js index 61f54f6fdf3..b52ab99a3ae 100644 --- a/chromium/chrome/browser/resources/settings/device_page/storage_external.js +++ b/chromium/chrome/browser/resources/settings/device_page/storage_external.js @@ -10,4 +10,50 @@ Polymer({ is: 'settings-storage-external', + + behaviors: [WebUIListenerBehavior], + + properties: { + /** + * List of the plugged-in external storages. + * @private {Arrray<!settings.ExternalStorage>} + */ + externalStorages_: { + type: Array, + value: function() { + return []; + } + }, + + /** @private {!chrome.settingsPrivate.PrefObject} */ + externalStorageVisiblePref_: { + type: Object, + value: function() { + return /** @type {!chrome.settingsPrivate.PrefObject} */ ({}); + }, + }, + }, + + /** @private {?settings.DevicePageBrowserProxy} */ + browserProxy_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.DevicePageBrowserProxyImpl.getInstance(); + }, + + /** @override */ + attached: function() { + this.browserProxy_.setExternalStoragesUpdatedCallback( + this.handleExternalStoragesUpdated_.bind(this)); + this.browserProxy_.updateExternalStorages(); + }, + + /** + * @param {Array<!settings.ExternalStorage>} storages + * @private + */ + handleExternalStoragesUpdated_: function(storages) { + this.externalStorages_ = storages; + }, }); diff --git a/chromium/chrome/browser/resources/settings/device_page/storage_external_entry.html b/chromium/chrome/browser/resources/settings/device_page/storage_external_entry.html new file mode 100644 index 00000000000..c7f20266418 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/device_page/storage_external_entry.html @@ -0,0 +1,25 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/html/assert.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="storage-external-entry"> + <template> + <style include="settings-shared"> + settings-toggle-button { + margin-inline-end: var(--cr-section-padding); + margin-inline-start: var(--cr-section-indent-padding); + padding-inline-end: 0; + padding-inline-start: 0; + } + </style> + <settings-toggle-button class="hr" + pref="{{visiblePref_}}" + label="[[label]]" + on-settings-boolean-control-change="onVisibleChange_"> + </settings-toggle-button> + </template> + <script src="storage_external_entry.js"></script> +</dom-module> diff --git a/chromium/chrome/browser/resources/settings/device_page/storage_external_entry.js b/chromium/chrome/browser/resources/settings/device_page/storage_external_entry.js new file mode 100644 index 00000000000..8749afa8033 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/device_page/storage_external_entry.js @@ -0,0 +1,72 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview + * 'storage-external-entry' is the polymer element for showing a certain + * external storage device with a toggle switch. When the switch is ON, + * the storage's uuid will be saved to a preference. + */ +Polymer({ + is: 'storage-external-entry', + + behaviors: [WebUIListenerBehavior, PrefsBehavior], + + properties: { + /** + * FileSystem UUID of an external storage. + */ + uuid: String, + + /** + * Label of an external storage. + */ + label: String, + + /** @private {chrome.settingsPrivate.PrefObject} */ + visiblePref_: { + type: Object, + value: function() { + return /** @type {chrome.settingsPrivate.PrefObject} */ ({}); + }, + }, + }, + + observers: [ + 'updateVisible_(prefs.arc.visible_external_storages.*)', + ], + + /** + * Handler for when the toggle button for this entry is clicked by a user. + * @param {!Event} event + * @private + */ + onVisibleChange_: function(event) { + const visible = !!event.target.checked; + if (visible) { + this.appendPrefListItem('arc.visible_external_storages', this.uuid); + } else { + this.deletePrefListItem('arc.visible_external_storages', this.uuid); + } + chrome.metricsPrivate.recordBoolean( + 'Arc.ExternalStorage.SetVisible', visible); + }, + + /** + * Updates |visiblePref_| by reading the preference and check if it contains + * UUID of this storage. + * @private + */ + updateVisible_: function() { + const uuids = /** @type {!Array<string>} */ ( + this.getPref('arc.visible_external_storages').value); + const visible = uuids.some((id) => id === this.uuid); + const pref = { + key: '', + type: chrome.settingsPrivate.PrefType.BOOLEAN, + value: visible, + }; + this.visiblePref_ = pref; + }, +});
\ No newline at end of file diff --git a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js index a901f4e32bd..559d65184d1 100644 --- a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js +++ b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js @@ -16,7 +16,7 @@ const DspHotwordState = { * Indicates user's activity control consent status. * * Note: This should be kept in sync with ash::mojom::ConsentStatus in - * ash/public/interfaces/voice_interaction_controller.mojom + * ash/public/mojom/voice_interaction_controller.mojom * @enum {number} */ const ConsentStatus = { diff --git a/chromium/chrome/browser/resources/settings/icons.html b/chromium/chrome/browser/resources/settings/icons.html index 816bb70c3a1..ad722128231 100644 --- a/chromium/chrome/browser/resources/settings/icons.html +++ b/chromium/chrome/browser/resources/settings/icons.html @@ -4,6 +4,7 @@ <!-- List icons here rather than importing large sets of (e.g. Polymer) icons. +NOTE: Chrome OS icons go in ./chromeos/os_icons.html. --> <iron-iconset-svg name="settings20" size="20"> <svg> @@ -12,10 +13,17 @@ List icons here rather than importing large sets of (e.g. Polymer) icons. <g id="googleg"><path d="M16.58 8H9v2.75h4.47c-.24 1.2-1.42 3.27-4.47 3.27-2.72 0-4.93-2.25-4.93-5.02S6.28 3.98 9 3.98c1.54 0 2.57.66 3.17 1.22l2.19-2.12C12.97 1.79 11.16 1 9 1 4.58 1 1 4.58 1 9s3.58 8 8 8c4.62 0 7.68-3.25 7.68-7.82 0-.46-.04-.83-.1-1.18z"></path></g> <g id="location-on"><path d="M10,2 C6.95928571,2 4.5,4.504 4.5,7.6 C4.5,11.8 10,18 10,18 C10,18 15.5,11.8 15.5,7.6 C15.5,4.504 13.0407143,2 10,2 Z M10,9.5 C8.896,9.5 8,8.604 8,7.5 C8,6.396 8.896,5.5 10,5.5 C11.104,5.5 12,6.396 12,7.5 C12,8.604 11.104,9.5 10,9.5 Z"></path></g> <g id="vpn-key"><path d="M10.4727273,8 C9.87272727,6.2525 8.26181818,5 6.36363636,5 C3.95272727,5 2,7.01375 2,9.5 C2,11.98625 3.95272727,14 6.36363636,14 C8.26181818,14 9.87272727,12.7475 10.4727273,11 L13.6363636,11 L13.6363636,14 L16.5454545,14 L16.5454545,11 L18,11 L18,8 L10.4727273,8 Z M6.36363636,11 C5.56,11 4.90909091,10.32875 4.90909091,9.5 C4.90909091,8.67125 5.56,8 6.36363636,8 C7.16727273,8 7.81818182,8.67125 7.81818182,9.5 C7.81818182,10.32875 7.16727273,11 6.36363636,11 Z"></path></g> + <g id="cloud-off"><path d="M16.4732571,13.3443682 C16.8002856,12.9882746 17,12.5134184 17,11.9922 C17,10.8882 16.104,9.9922 15,9.9922 L13.494,9.9922 L13.494,9.0002 C13.494,7.0672 11.927,5.5002 9.994,5.5002 C9.5847901,5.5002 9.1930204,5.57089988 8.82954884,5.70065995 L7.33083687,4.20194798 C8.11843435,3.75577808 9.02717677,3.5002 10,3.5002 C12.71,3.5002 14.957,5.4612 15.411,8.0412 C17.424,8.2502 19,9.9312 19,12.0002 C19,13.0718701 18.5784721,14.0451601 17.8921876,14.7632987 L16.4732571,13.3443682 Z M17.8711111,17 L16.8711111,18 L14.8713111,16.0002 L6,16.0002 C3.239,16.0002 1,13.7622 1,11.0002 C1,8.58475294 2.71868905,6.59044755 4.99627833,6.12516722 L2,3.12888889 L3,2.12888889 L17.8711111,17 Z M6.86331111,7.9922 L6,7.9922 C4.343,7.9922 3,9.3352 3,10.9922 C3,12.6492 4.343,13.9922 6,13.9922 L12.8633111,13.9922 L6.86331111,7.9922 Z"></path></g> + <!-- The polygon ("+" shape) within this icon will always be filled with + the color #4285F4. Any color fills specified programmatically will + only be applied to the outer layer. --> + <g id="printer-add"><path d="M17.8734304,8.29826826 C17.2839707,8.10470383 16.6542128,8 16,8 C13.3875623,8 11.1650842,9.66961525 10.3414114,12 L7,12 L7,15 L10.0829584,15 C10.2034032,15.7179235 10.4513404,16.3926158 10.8026932,17 L5,17 L5,14 L2,14 L2,9 C2,7.8954305 2.8954305,7 4,7 L5,7 L5,3 L15,3 L15,7 L16,7 C16.8576527,7 17.5892179,7.53984453 17.8734304,8.29826826 Z M7,5 L7,7 L13,7 L13,5 L7,5 Z"></path><polygon fill="#4285F4" points="17 13 19 13 19 15 17 15 17 17 15 17 15 15 13 15 13 13 15 13 15 11 17 11"></polygon></g> </defs> </svg> </iron-iconset-svg> +<!-- NOTE: In the common case that the final icon will be 20x20, export the SVG + at 20px and place it in the section above. --> <iron-iconset-svg name="settings" size="24"> <svg> <defs> @@ -38,31 +46,6 @@ List icons here rather than importing large sets of (e.g. Polymer) icons. <path fill="none" d="M1 1h22v22H1z"></path> </g> -<if expr="chromeos"> - <!-- Icons from http://icons/ --> - <g id="play-prism"><path d="M20.18 10.88l-3.06-1.74L14.26 12l2.86 2.86 3.06-1.74c.55-.31.82-.71.82-1.12 0-.41-.27-.81-.82-1.12zM4.71 2.45l8.42 8.42 2.55-2.55-10.7-6.06c-.07-.04-.14-.07-.21-.1-.17-.07-.3.05-.15.21.03.02.06.05.09.08zm0 19.1l-.08.08c-.15.15-.02.28.15.21.07-.03.14-.06.21-.1l10.69-6.06-2.55-2.55s-7.2 7.21-8.42 8.42zM12 12L3.38 3.38c-.19-.19-.38-.07-.38.19v16.86c0 .26.19.38.38.19L12 12z"></path></g> - - <!-- Apps icon for Settings drawer --> - <g id="apps"> - <rect width="24" height="24"></rect> - <path d="M6 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6 12c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-6 0c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6 0c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-8c0 1.1.9 2 2 2s2-.9 2-2-.9-2-2-2-2 .9-2 2zm-4 2c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6 6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"></path> - </g> - - <!-- Crostini Mascot icon for Settings drawer --> - <g id="crostini-mascot" fill-rule="evenodd"> - <rect width="24" height="24" fill="none"></rect> - <path d="M6.70994751,22.1802367 C3.77039152,20.9576222 1.88689678,18.4876617 1.82270453,14.1866283 C1.52620735,14.3410271 1.18877909,14.3669908 0.800057996,14.221322 C-0.312414045,13.804436 -0.0624529958,12.4120387 0.345560769,11.1705211 C0.68346303,10.142341 1.83735671,9.39181671 2.40240955,9.23479478 C3.71763772,4.05541221 6.80346772,0 12,0 C17.2584272,0 20.3654882,3.88805047 21.6436562,9.24850027 C22.2231374,9.43172978 23.3254781,10.1695473 23.6544392,11.1705211 C24.062453,12.4120387 24.312414,13.804436 23.199942,14.221322 C22.8112853,14.3669667 22.4739044,14.3410357 22.1774428,14.186705 C22.1189307,18.5169382 20.2342349,20.9750038 17.2936622,22.1879533 C17.3379726,22.2841737 17.3614392,22.3916932 17.3614392,22.5115654 C17.3614392,23.3336051 17.750632,24 14.8965517,24 C12.813813,24 12.4581871,23.5470722 12.4180882,23.0543665 C12.2796354,22.9647547 12.14026,22.8305157 12,22.8305157 C11.8594243,22.8305157 11.7197425,22.9755283 11.5809922,23.0650454 C11.536581,23.553597 11.171131,24 9.10344828,24 C6.24936798,24 6.63856075,23.3336051 6.63856075,22.5115654 C6.63856075,22.3884786 6.66330281,22.278416 6.70994751,22.1802367 Z M12,20.3378361 C17.4851654,20.3378361 19.4630542,17.934489 19.4630542,12.6147346 C19.4630542,8.20063746 17.6641739,4.14700996 14.6790451,3.47027327 C13.7222433,3.25336374 13.052482,5.61336212 12,5.61336212 C10.947518,5.61336212 10.1820765,3.25336374 9.32095491,3.47027327 C6.32316904,4.22539115 4.53694581,8.43392639 4.53694581,12.6147346 C4.53694581,17.6346061 6.51483457,20.3378361 12,20.3378361 Z M8.27586207,9.99377535 C7.59026721,9.99377535 7.03448276,9.42257974 7.03448276,8.71797424 C7.03448276,8.01336875 7.59026721,7.44217314 8.27586207,7.44217314 C8.96145693,7.44217314 9.51724138,8.01336875 9.51724138,8.71797424 C9.51724138,9.42257974 8.96145693,9.99377535 8.27586207,9.99377535 Z M15.7241379,9.99377535 C15.0385431,9.99377535 14.4827586,9.42257974 14.4827586,8.71797424 C14.4827586,8.01336875 15.0385431,7.44217314 15.7241379,7.44217314 C16.4097328,7.44217314 16.9655172,8.01336875 16.9655172,8.71797424 C16.9655172,9.42257974 16.4097328,9.99377535 15.7241379,9.99377535 Z M12.224615,10.6827627 L13.9283449,11.4510541 C14.2234366,11.5841248 14.3564393,11.9349546 14.2254148,12.2346546 C14.1996198,12.293657 14.1645229,12.3479919 14.1215061,12.39552 L12.4275305,14.2671455 C12.2090286,14.5085621 11.8392003,14.5243719 11.6014958,14.3024578 C11.5890079,14.2907994 11.5770255,14.2785946 11.5655826,14.265878 L9.87720766,12.3895636 C9.65939502,12.1475054 9.67603268,11.771949 9.91436891,11.5507349 C9.9604013,11.5080095 10.012868,11.4730393 10.0697797,11.4471502 L11.7484004,10.6835476 C11.8998356,10.6146599 12.0729604,10.6143745 12.224615,10.6827627 Z"></path> - </g> - - <!-- Plugin VM icon for Settings drawer --> - <g id="plugin-vm"><path transform="scale(1.2)" d="M7 12v4H4V4a1 1 0 0 1 1-1h8a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H7zm0-6v3h5a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1H7z"></path></g> - - <!-- Icons for MultiDevice Settings UI --> - <g id="multidevice-better-together-suite"><path d="M17,1.01 L7,1 C5.9,1 5,1.9 5,3 L5,21 C5,22.1 5.9,23 7,23 L17,23 C18.1,23 19,22.1 19,21 L19,3 C19,1.9 18.1,1.01 17,1.01 Z M17,21 L7,21 L7,20 L17,20 L17,21 Z M17,18 L7,18 L7,6 L17,6 L17,18 Z M7,4 L7,3 L17,3 L17,4 L7,4 Z"></path></g> - <g id="multidevice-smart-lock"><path d="M18,9 L17,9 L17,7 C17,4.24 14.76,2 12,2 C9.24,2 7,4.24 7,7 L7,9 L6,9 C4.9,9 4,9.9 4,11 L4,21 C4,22.1 4.9,23 6,23 L18,23 C19.1,23 20,22.1 20,21 L20,11 C20,9.9 19.1,9 18,9 Z M9,7 C9,5.34 10.34,4 12,4 C13.66,4 15,5.34 15,7 L15,9 L9,9 L9,7 Z M18,21 L6,21 L6,11 L18,11 L18,21 Z M12,18 C13.1,18 14,17.1 14,16 C14,14.9 13.1,14 12,14 C10.9,14 10,14.9 10,16 C10,17.1 10.9,18 12,18 Z"></path></g> - <g id="multidevice-messages"><path d="M19.9593506,2 C21.0593506,2 22,2.89658203 22,3.99658203 L22,16.0036621 C22,17.1036621 21.0593506,18.0036621 19.9593506,18.0036621 L6.00878906,18.0036621 L2.00878906,22.4 L2.01878906,3.99658203 C2.01878906,2.89658203 2.90878906,2 4.00878906,2 L19.9593506,2 Z M8,8.56896973 L4.5,12 L8,15.6103516 L8,13 L14,13 L14,11 L8,11 L8,8.56896973 Z M20.5688477,7 L17,3.57207031 L17,6 L11,6 L11,8 L17,8 L17,10.5720703 L20.5688477,7 Z"></path></g> -</if> - <!-- Protected Content SVG --> <g id="protected-content"> <path d="M10,15 L6,11.1783439 L7.41,9.83121019 L10,12.2961783 L16.59,6 L18,7.3566879 L10,15 Z M21,3 L3,3 C1.89,3 1,3.89 1,5 L1,17 C1,18.1 1.89,19 3,19 L8,19 L8,21 L16,21 L16,19 L21,19 C22.1,19 22.99,18.1 22.99,17 L23,5 C23,3.89 22.1,3 21,3 Z M21,17 L3,17 L3,5 L21,5 L21,17 Z"></path> @@ -72,50 +55,21 @@ List icons here rather than importing large sets of (e.g. Polymer) icons. These icons are copied from Polymer's iron-icons and kept in sorted order. See http://goo.gl/Y1OdAq for instructions on adding additional icons. --> -<if expr="chromeos"> - <g id="access-time"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"></path></g> -</if> <g id="accessibility"><path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z"></path></g> <g id="apps"><path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z"></path></g> <g id="assignment"><path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"></path></g> -<if expr="chromeos"> - <g id="bluetooth-connected"><path d="M7 12l-2-2-2 2 2 2 2-2zm10.71-4.29L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88zM19 10l-2 2 2 2 2-2-2-2z"></path></g> - <g id="bluetooth-disabled"><path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"></path></g> - <g id="brightness-1"><circle cx="12" cy="12" r="10"></circle></g> -</if> <if expr="not chromeos"> <g id="build"><path d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"></path></g> </if> <g id="check-circle"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path></g> -<if expr="chromeos"> - <g id="chevron-left"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"</path></g> -</if> <g id="clipboard"><path d="M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z"></path></g> <g id="cloud"><path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96z"></path></g> <g id="code"><path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"></path></g> <g id="content-copy"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"></path></g> -<if expr="chromeos"> - <g id="devices-other"><path d="M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6zm10 6H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8z"></path></g> -</if> <g id="exit-to-app"><path d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"></path></g> -<if expr="chromeos"> - <g id="fingerprint"><path d="M17.81 4.47c-.08 0-.16-.02-.23-.06C15.66 3.42 14 3 12.01 3c-1.98 0-3.86.47-5.57 1.41-.24.13-.54.04-.68-.2-.13-.24-.04-.55.2-.68C7.82 2.52 9.86 2 12.01 2c2.13 0 3.99.47 6.03 1.52.25.13.34.43.21.67-.09.18-.26.28-.44.28zM3.5 9.72c-.1 0-.2-.03-.29-.09-.23-.16-.28-.47-.12-.7.99-1.4 2.25-2.5 3.75-3.27C9.98 4.04 14 4.03 17.15 5.65c1.5.77 2.76 1.86 3.75 3.25.16.22.11.54-.12.7-.23.16-.54.11-.7-.12-.9-1.26-2.04-2.25-3.39-2.94-2.87-1.47-6.54-1.47-9.4.01-1.36.7-2.5 1.7-3.4 2.96-.08.14-.23.21-.39.21zm6.25 12.07c-.13 0-.26-.05-.35-.15-.87-.87-1.34-1.43-2.01-2.64-.69-1.23-1.05-2.73-1.05-4.34 0-2.97 2.54-5.39 5.66-5.39s5.66 2.42 5.66 5.39c0 .28-.22.5-.5.5s-.5-.22-.5-.5c0-2.42-2.09-4.39-4.66-4.39-2.57 0-4.66 1.97-4.66 4.39 0 1.44.32 2.77.93 3.85.64 1.15 1.08 1.64 1.85 2.42.19.2.19.51 0 .71-.11.1-.24.15-.37.15zm7.17-1.85c-1.19 0-2.24-.3-3.1-.89-1.49-1.01-2.38-2.65-2.38-4.39 0-.28.22-.5.5-.5s.5.22.5.5c0 1.41.72 2.74 1.94 3.56.71.48 1.54.71 2.54.71.24 0 .64-.03 1.04-.1.27-.05.53.13.58.41.05.27-.13.53-.41.58-.57.11-1.07.12-1.21.12zM14.91 22c-.04 0-.09-.01-.13-.02-1.59-.44-2.63-1.03-3.72-2.1-1.4-1.39-2.17-3.24-2.17-5.22 0-1.62 1.38-2.94 3.08-2.94 1.7 0 3.08 1.32 3.08 2.94 0 1.07.93 1.94 2.08 1.94s2.08-.87 2.08-1.94c0-3.77-3.25-6.83-7.25-6.83-2.84 0-5.44 1.58-6.61 4.03-.39.81-.59 1.76-.59 2.8 0 .78.07 2.01.67 3.61.1.26-.03.55-.29.64-.26.1-.55-.04-.64-.29-.49-1.31-.73-2.61-.73-3.96 0-1.2.23-2.29.68-3.24 1.33-2.79 4.28-4.6 7.51-4.6 4.55 0 8.25 3.51 8.25 7.83 0 1.62-1.38 2.94-3.08 2.94s-3.08-1.32-3.08-2.94c0-1.07-.93-1.94-2.08-1.94s-2.08.87-2.08 1.94c0 1.71.66 3.31 1.87 4.51.95.94 1.86 1.46 3.27 1.85.27.07.42.35.35.61-.05.23-.26.38-.47.38z"></path></g> - <g id="gamepad"><path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"></path></g> - <g id="headset"><path d="M12 1c-4.97 0-9 4.03-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2c0-3.87 3.13-7 7-7s7 3.13 7 7v2h-4v8h3c1.66 0 3-1.34 3-3v-7c0-4.97-4.03-9-9-9z"></path></g> - <g id="keyboard"><path d="M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"></path></g> -</if> <g id="language"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z"></path></g> -<if expr="chromeos"> - <g id="laptop-chromebook"><path d="M22 18V3H2v15H0v2h24v-2h-2zm-8 0h-4v-1h4v1zm6-3H4V5h16v10z"></path></g> -</if> <g id="midi"><path d="M21,19.1H3V5h18V19.1z M21,3H3C1.9,3,1,3.9,1,5v14c0,1.1,0.9,2,2,2h18c1.1,0,2-0.9,2-2V5C23,3.9,22.1,3,21,3z"></path><path fill="none" d="M21,19.1H3V5h18V19.1z M21,3H3C1.9,3,1,3.9,1,5v14c0,1.1,0.9,2,2,2h18c1.1,0,2-0.9,2-2V5C23,3.9,22.1,3,21,3z"></path><path d="M14,5h3v8h-3V5z"></path><path d="M15,12h1v8h-1V12z"></path><path fill="none" d="M0,0h24v24H0V0z"></path><rect x="7" y="5" width="3" height="8"></rect><rect x="8" y="12" width="1" height="8"></rect></g> -<if expr="chromeos"> - <g id="mouse"><path d="M13 1.07V9h7c0-4.08-3.05-7.44-7-7.93zM4 15c0 4.42 3.58 8 8 8s8-3.58 8-8v-4H4v4zm7-13.93C7.05 1.56 4 4.92 4 9h7V1.07z"></path></g> -</if> <g id="music-note"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"></path></g> -<if expr="chromeos"> - <g id="network-wifi"><path fill-opacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"></path><path d="M3.53 10.95l8.46 10.54.01.01.01-.01 8.46-10.54C20.04 10.62 16.81 8 12 8c-4.81 0-8.04 2.62-8.47 2.95z"></path></g> -</if> <g id="notifications"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"></path></g> <g id="pdf"><path d="M7 11.5h1v-1H7v1zM19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9.5 8.5c0 .83-.67 1.5-1.5 1.5H7v2H5.5V9H8c.83 0 1.5.67 1.5 1.5v1zm10-1H17v1h1.5V13H17v2h-1.5V9h4v1.5zm-5 3c0 .83-.67 1.5-1.5 1.5h-2.5V9H13c.83 0 1.5.67 1.5 1.5v3zm-2.5 0h1v-3h-1v3z"></path><path fill="none" d="M0 0h24v24H0z"></path></g> <g id="palette"><path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9 8 9.67 8 10.5 7.33 12 6.5 12zm3-4C8.67 8 8 7.33 8 6.5S8.67 5 9.5 5s1.5.67 1.5 1.5S10.33 8 9.5 8zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 5 14.5 5s1.5.67 1.5 1.5S15.33 8 14.5 8zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 9 17.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"></path></g> @@ -125,29 +79,15 @@ List icons here rather than importing large sets of (e.g. Polymer) icons. <g id="protocol-handler"><path d="M21.72 11.33l-6.644-7.035a.97.97 0 0 0-1.38-.01l-1.67 1.72-1.617-1.712a.97.97 0 0 0-1.38-.01l-6.737 6.935c-.187.191-.29.447-.292.719-.002.272.099.529.28.722l6.644 7.034a.949.949 0 0 0 1.38.011l1.671-1.718 1.615 1.71a.949.949 0 0 0 1.381.01l6.74-6.935a1.054 1.054 0 0 0 .01-1.44zM6.947 12.464l3.657 3.785-.974.98-5.273-5.456 5.349-5.378.929.962-3.677 3.7a.998.998 0 0 0-.292.702 1 1 0 0 0 .28.705zm7.35 4.768l-.931-.963 3.68-3.7a1.012 1.012 0 0 0 .007-1.407l-3.656-3.784.974-.98 5.273 5.456-5.348 5.378z"></path></g> <g id="restore"><path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"></path></g> <g id="rotate-right"><path d="M15.55 5.55L11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"></path></g> + <g id="save-original"><path d="M16.058 24.876H8.002c-1.107 0-2.002-.94-2.002-2.088l.01-16.7C6.01 4.939 6.905 4 8.012 4h8.046l6.035 6.263v4.175h-2.011v-3.131h-5.03v-5.22h-7.04v16.701h4.023v2.088h4.023zm7.581-6.157l1.474 1.481-4.18 4.2-4.182-4.2 1.474-1.48 1.662 1.659V16h2.09v4.378l1.662-1.659zM26.308 28H15.557v-2.4h10.75V28z" id="a"></path></g> <g id="sensors"><path d="M10 8.5c-0.8 0-1.5 0.7-1.5 1.5s0.7 1.5 1.5 1.5s1.5-0.7 1.5-1.5S10.8 8.5 10 8.5z M7.6 5.8 C6.2 6.7 5.2 8.2 5.2 10c0 1.8 1 3.4 2.4 4.2l0.8-1.4c-1-0.6-1.6-1.6-1.6-2.8c0-1.2 0.6-2.2 1.6-2.8L7.6 5.8z M14.8 10 c0-1.8-1-3.4-2.4-4.2l-0.8 1.4c0.9 0.6 1.6 1.6 1.6 2.8c0 1.2-0.6 2.2-1.6 2.8l0.8 1.4C13.8 13.4 14.8 11.8 14.8 10z M6 3 c-2.4 1.4-4 4-4 7c0 3 1.6 5.6 4 7l0.8-1.4c-1.9-1.1-3.2-3.2-3.2-5.6c0-2.4 1.3-4.5 3.2-5.6L6 3z M13.2 4.4 c1.9 1.1 3.2 3.2 3.2 5.6c0 2.4-1.3 4.5-3.2 5.6L14 17c2.4-1.4 4-4 4-7c0-3-1.6-5.6-4-7L13.2 4.4z"></path></g> <g id="serial-port"><path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"></path></g> -<if expr="chromeos"> - <g id="alert-device-out-of-range" fill="none" fill-rule="evenodd"><path d="M-1-1h20v20H-1z"></path><path fill="#C53929" fill-rule="nonzero" d="M8.167 11.5h1.666v1.667H8.167V11.5zm0-6.667h1.666v5H8.167v-5zM8.992.667C4.392.667.667 4.4.667 9s3.725 8.333 8.325 8.333c4.608 0 8.341-3.733 8.341-8.333S13.6.667 8.992.667zm.008 15A6.665 6.665 0 0 1 2.333 9 6.665 6.665 0 0 1 9 2.333 6.665 6.665 0 0 1 15.667 9 6.665 6.665 0 0 1 9 15.667z"></path></g> - <g id="signal-cellular-0-bar"><path fill-opacity=".3" d="M2 22h20V2z"></path></g> - <g id="signal-cellular-1-bar"><path fill-opacity=".3" d="M2 22h20V2z"></path><path d="M12 12L2 22h10z"></path></g> - <g id="signal-cellular-2-bar"><path fill-opacity=".3" d="M2 22h20V2z"></path><path d="M14 10L2 22h12z"></path></g> - <g id="signal-cellular-3-bar"><path fill-opacity=".3" d="M2 22h20V2z"></path><path d="M17 7L2 22h15z"></path></g> - <g id="signal-cellular-4-bar"><path d="M2 22h20V2z"></path></g> - <g id="smartphone"><path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"></path></g> -</if> <g id="supervisor-account"><path d="M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7C15.12 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5zM9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5C7.34 5 6 6.34 6 8s1.34 3 3 3zm7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75zM9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13z"></path></g> <g id="sync-disabled"><path d="M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z"></path></g> <g id="sync-problem"><path d="M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z"></path></g> -<if expr="chromeos"> - <g id="tablet"><path d="M21 4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 1.99-.9 1.99-2L23 6c0-1.1-.9-2-2-2zm-2 14H5V6h14v12z"></path></g> -</if> <g id="usb"><path d="M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z"></path></g> <g id="volume-up"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"></path></g> <g id="bluetooth-scanning"><path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2a9.936 9.936 0 0 0 1.54-5.31c-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"></path></g> -<if expr="chromeos"> - <g id="end-of-life"><path d="M4.574 2.916H4.55l.01.01.014-.01zM2.5 4.968v.023a.18.18 0 0 1 .01-.013l-.01-.01zm14.585 10.49v-.024l-.01.013.01.01zm.223 1.817l-.933-.95-4.106-4.11L8.026 7.99 3.675 3.635l-.942-.941-.712-.713L1 3.002l1.733 1.733A9.056 9.056 0 0 0 1.05 9.98c0 1.95.628 3.748 1.683 5.22.574.8 1.274 1.501 2.074 2.075a8.918 8.918 0 0 0 5.218 1.684 8.918 8.918 0 0 0 5.218-1.684L16.991 19l1.02-1.021-.703-.704zM15.243 2.684A8.922 8.922 0 0 0 10.025 1a8.922 8.922 0 0 0-5.218 1.684c-.005.003 4.135 4.16 4.135 4.16l1.083-1.814L15.042 11h-1.846l4.11 4.214a8.939 8.939 0 0 0 .011-10.456 9.021 9.021 0 0 0-2.074-2.074zM12 15H7.012v-3.989L4.5 11l2.227-1.876L12 14.6v.4z" fill="#DB4437" fill-rule="evenodd"></path></g> -</if> <if expr="not chromeos"> <g id="web"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"></path></g> </if> diff --git a/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn b/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn index 936eea443b4..7b8a8fa0718 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn @@ -27,6 +27,7 @@ js_library("internet_page") { "../settings_page:settings_animated_pages", "//chromeos/services/network_config/public/mojom:mojom_js_library_for_compile", "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider", + "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", @@ -35,7 +36,6 @@ js_library("internet_page") { ] externs_list = [ "$externs_path/chrome_send.js", - "$externs_path/management.js", "$externs_path/networking_private.js", ] extra_sources = [ "$interfaces_path/networking_private_interface.js" ] @@ -68,7 +68,7 @@ js_library("internet_detail_page") { "..:route", "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", - "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior", + "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior_mojo", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", ] @@ -84,7 +84,7 @@ js_library("internet_known_networks_page") { "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu", - "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior", + "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior_mojo", "//ui/webui/resources/js:assert", ] externs_list = [ "$externs_path/networking_private.js" ] @@ -96,7 +96,7 @@ js_library("internet_subpage") { ":internet_page_browser_proxy", "..:route", "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", - "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior", + "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior_mojo", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js/chromeos:onc_mojo", @@ -111,9 +111,10 @@ js_library("network_proxy_section") { "../controls:settings_checkbox", "../prefs:prefs_behavior", "//ui/webui/resources/cr_components/chromeos/network:network_proxy", - "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", + "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior_mojo", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", + "//ui/webui/resources/js/chromeos:onc_mojo", "//ui/webui/resources/js/cr/ui:focus_without_ink", ] } @@ -122,7 +123,6 @@ js_library("network_summary") { deps = [ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", - "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior", "//ui/webui/resources/js:assert", "//ui/webui/resources/js/chromeos:onc_mojo", ] @@ -132,7 +132,7 @@ js_library("network_summary") { js_library("network_summary_item") { deps = [ "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", - "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior", + "//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior_mojo", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js/chromeos:onc_mojo", @@ -142,9 +142,9 @@ js_library("network_summary_item") { js_library("tether_connection_dialog") { deps = [ - "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", "//ui/webui/resources/cr_elements/cr_dialog:cr_dialog", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:i18n_behavior", + "//ui/webui/resources/js/chromeos:onc_mojo", ] } 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 a49a1d32fe9..c78ca56e50b 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 @@ -4,7 +4,7 @@ <link rel="import" href="chrome://resources/cr_components/chromeos/network/network_choose_mobile.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_components/chromeos/network/network_property_list_mojo.html"> <link rel="import" href="chrome://resources/cr_components/chromeos/network/network_siminfo.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html"> @@ -14,8 +14,9 @@ <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.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/cr_elements/policy/cr_policy_network_behavior_mojo.html"> +<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_indicator_mojo.html"> +<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> @@ -23,6 +24,7 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html"> <link rel="import" href="../controls/controlled_button.html"> <link rel="import" href="../controls/settings_toggle_button.html"> +<link rel="import" href="../i18n_setup.html"> <link rel="import" href="../prefs/prefs.html"> <link rel="import" href="../route.html"> <link rel="import" href="internet_page_browser_proxy.html"> @@ -49,7 +51,7 @@ margin-inline-start: var(--settings-control-label-spacing); } - cr-policy-network-indicator, + cr-policy-network-indicator-mojo, cr-policy-indicator, cr-policy-pref-indicator { margin-inline-start: var(--settings-controlled-by-spacing); @@ -76,72 +78,74 @@ <div class="start layout horizontal center"> <cr-network-icon show-technology-badge="[[showTechnologyBadge_]]" - network-state="[[getNetworkState_(networkProperties_)]]"> + network-state="[[getNetworkState_(managedProperties_)]]"> </cr-network-icon> <div id="networkState" class="title settings-box-text" - connected$="[[isConnectedState_(networkProperties_)]]" - error$="[[outOfRange_]]"> - [[getStateText_(networkProperties_, outOfRange_)]] + connected$="[[isConnectedState_(managedProperties_)]]" + error$="[[isConnectionErrorState_( + managedProperties_, outOfRange_)]]"> + [[getStateText_(managedProperties_, propertiesReceived_, + outOfRange_)]] </div> <template is="dom-if" - if="[[isPolicySource(networkProperties_.Source))]]"> + if="[[isPolicySource(managedProperties_.source))]]"> <cr-policy-indicator indicator-type="[[getIndicatorTypeForSource( - networkProperties_.Source)]]"> + managedProperties_.source)]]"> </cr-policy-indicator> </template> </div> <cr-button on-click="onForgetTap_" - hidden$="[[!showForget_(networkProperties_)]]" - disabled="[[disableForget_(networkProperties_, + hidden$="[[!showForget_(managedProperties_)]]" + disabled="[[disableForget_(managedProperties_, prefs.vpn_config_allowed)]]"> $i18n{networkButtonForget} </cr-button> <cr-button on-click="onViewAccountTap_" - hidden$="[[!showViewAccount_(networkProperties_)]]"> + hidden$="[[!showViewAccount_(managedProperties_)]]"> $i18n{networkButtonViewAccount} </cr-button> <cr-button on-click="onActivateTap_" - hidden$="[[!showActivate_(networkProperties_)]]"> + hidden$="[[!showActivate_(managedProperties_)]]"> $i18n{networkButtonActivate} </cr-button> <cr-button on-click="onConfigureTap_" - hidden$="[[!showConfigure_(networkProperties_, globalPolicy, + hidden$="[[!showConfigure_(managedProperties_, globalPolicy, managedNetworkAvailable)]]" - disabled="[[disableConfigure_(networkProperties_, + disabled="[[disableConfigure_(managedProperties_, prefs.vpn_config_allowed)]]"> $i18n{networkButtonConfigure} </cr-button> <!-- Use policy properties from vpn_config_allowed to indicate when that pref disables buttons in this row. --> <controlled-button id="connect" action-button on-click="onConnectTap_" - hidden$="[[!showConnect_(networkProperties_, globalPolicy, + hidden$="[[!showConnect_(managedProperties_, globalPolicy, managedNetworkAvailable)]]" - disabled="[[!enableConnect_(networkProperties_, defaultNetwork, - networkPropertiesReceived_, outOfRange_, globalPolicy, + disabled="[[!enableConnect_(managedProperties_, defaultNetwork, + propertiesReceived_, outOfRange_, globalPolicy, managedNetworkAvailable)]]" label="$i18n{networkButtonConnect}" - pref="[[getFakeVpnConfigPrefForEnforcement_(networkProperties_, + pref="[[getFakeVpnConfigPrefForEnforcement_(managedProperties_, prefs.vpn_config_allowed)]]"> </controlled-button> <controlled-button id="disconnect" action-button on-click="onDisconnectTap_" - hidden$="[[!showDisconnect_(networkProperties_)]]" + hidden$="[[!showDisconnect_(managedProperties_)]]" label="$i18n{networkButtonDisconnect}" - pref="[[getFakeVpnConfigPrefForEnforcement_(networkProperties_, + pref="[[getFakeVpnConfigPrefForEnforcement_(managedProperties_, prefs.vpn_config_allowed)]]"> </controlled-button> </div> <!-- Disabled by policy / Shared messages. --> <div class="settings-box continuation" - hidden$="[[!isBlockedByPolicy_(networkProperties_, globalPolicy, + hidden$="[[!isBlockedByPolicy_(managedProperties_, globalPolicy, managedNetworkAvailable)]]"> <iron-icon class="policy" icon="cr20:domain"></iron-icon> <div class="settings-box-text">$i18n{networkConnectNotAllowed}</div> </div> <div class="settings-box continuation settings-box-text" - hidden$="[[!showShared_(networkProperties_, globalPolicy, + hidden$="[[!showShared_(managedProperties_, globalPolicy, managedNetworkAvailable)]]"> $i18n{networkShared} </div> @@ -161,37 +165,37 @@ <template is="dom-if" if="[[!isSecondaryUser_]]"> <!-- Prefer this network. --> <template is="dom-if" - if="[[showPreferNetwork_(networkProperties_, globalPolicy, + if="[[showPreferNetwork_(managedProperties_, globalPolicy, managedNetworkAvailable)]]"> <div class="settings-box" on-click="onPreferNetworkRowClicked_" actionable$="[[!isNetworkPolicyEnforced( - networkProperties_.Priority)]]"> + managedProperties_.priority)]]"> <div id="preferNetworkToggleLabel" class="start settings-box-text"> $i18n{networkPrefer} </div> - <cr-policy-network-indicator - property="[[networkProperties_.Priority]]"> - </cr-policy-network-indicator> + <cr-policy-network-indicator-mojo + property="[[managedProperties_.priority]]"> + </cr-policy-network-indicator-mojo> <cr-toggle id="preferNetworkToggle" checked="{{preferNetwork_}}" disabled="[[isNetworkPolicyEnforced( - networkProperties_.Priority)]]" + managedProperties_.priority)]]" aria-labelledby="preferNetworkToggleLabel"> </cr-toggle> </div> </template> <!-- Autoconnect. --> <template is="dom-if" - if="[[showAutoConnect_(networkProperties_, globalPolicy, + if="[[showAutoConnect_(managedProperties_, globalPolicy, managedNetworkAvailable)]]"> <settings-toggle-button id="autoConnectToggle" - pref="{{autoConnect_}}" - label="[[getAutoConnectToggleLabel_(networkProperties_)]]"> + pref="{{autoConnectPref_}}" + label="[[getAutoConnectToggleLabel_(managedProperties_)]]"> </settings-toggle-button> <!-- Hidden Network Warning --> <template is="dom-if" - if="[[showHiddenNetworkWarning_(autoConnect_.*, - networkProperties_)]]" + if="[[showHiddenNetworkWarning_(autoConnectPref_.*, + managedProperties_)]]" restamp> <div class="warning"> <iron-icon icon="cr:warning"></iron-icon> @@ -201,47 +205,48 @@ </template> <!-- Always-on VPN. --> <template is="dom-if" - if="[[showAlwaysOnVpn_(networkProperties_)]]"> + if="[[showAlwaysOnVpn_(managedProperties_)]]"> <settings-toggle-button id="alwaysOnVpnToggle" pref="{{alwaysOnVpn_}}" label="$i18n{networkAlwaysOnVpn}"> </settings-toggle-button> </template> <!-- Data roaming (Cellular only). --> - <template is="dom-if" if="[[isCellular_(networkProperties_)]]"> + <template is="dom-if" if="[[isCellular_(managedProperties_)]]"> <settings-toggle-button id="allowDataRoaming" pref="{{prefs.cros.signed.data_roaming_enabled}}" label="$i18n{networkAllowDataRoaming}" - sub-label="[[getRoamingDetails_(networkProperties_)]]"> + sub-label="[[getRoamingDetails_(managedProperties_)]]"> </settings-toggle-button> </template> <!-- SIM Info (Cellular only). --> - <template is="dom-if" if="[[showCellularSim_(networkProperties_)]]" + <template is="dom-if" if="[[showCellularSim_(managedProperties_)]]" restamp> <div class="settings-box single-column stretch"> - <network-siminfo on-siminfo-change="onNetworkPropertyChange_"> + <network-siminfo device-state="[[deviceState_]]"> </network-siminfo> </div> </template> <!-- IP Address. --> <div class="settings-box two-line single-column stretch settings-box-text" - hidden$="[[!showIpAddress_(ipAddress_, networkProperties_)]]"> + hidden$="[[!showIpAddress_(ipAddress_, managedProperties_)]]"> <div>$i18n{networkIPAddress}</div> <div class="secondary">[[ipAddress_]]</div> </div> <!-- Properties to always show if present. --> - <template is="dom-if" if="[[hasInfoFields_(networkProperties_)]]"> + <template is="dom-if" if="[[hasInfoFields_(managedProperties_)]]"> <div class="settings-box single-column stretch"> - <network-property-list - fields="[[getInfoFields_(networkProperties_)]]" - edit-field-types="[[getInfoEditFieldTypes_(networkProperties_)]]" - property-dict="[[networkProperties_]]" + <network-property-list-mojo + fields="[[getInfoFields_(managedProperties_)]]" + edit-field-types="[[getInfoEditFieldTypes_(managedProperties_)]]" + property-dict="[[managedProperties_]]" on-property-change="onNetworkPropertyChange_"> - </network-property-list> + </network-property-list-mojo> </div> </template> - <template is="dom-if" if="[[showAdvanced_(networkProperties_)]]"> + <template is="dom-if" + if="[[showAdvanced_(managedProperties_, propertiesReceived_)]]"> <!-- Advanced toggle. --> <cr-expand-button alt="$i18n{networkSectionAdvancedA11yLabel}" @@ -253,24 +258,24 @@ <!-- Advanced section --> <iron-collapse opened="[[advancedExpanded_]]"> <div class="settings-box single-column stretch indented first" - hidden$="[[!hasAdvancedOrDeviceFields_(networkProperties_)]]"> + hidden$="[[!hasAdvancedOrDeviceFields_(managedProperties_)]]"> <!-- Advanced properties --> - <network-property-list - hidden$="[[!hasAdvancedFields_(networkProperties_)]]" - fields="[[getAdvancedFields_(networkProperties_)]]" - property-dict="[[networkProperties_]]"> - </network-property-list> + <network-property-list-mojo + hidden$="[[!hasAdvancedFields_(managedProperties_)]]" + fields="[[getAdvancedFields_(managedProperties_)]]" + property-dict="[[managedProperties_]]"> + </network-property-list-mojo> <!-- Device properties --> - <network-property-list - hidden$="[[!hasDeviceFields_(networkProperties_)]]" - fields="[[getDeviceFields_(networkProperties_)]]" - property-dict="[[networkProperties_]]"> - </network-property-list> + <network-property-list-mojo + hidden$="[[!hasDeviceFields_(managedProperties_)]]" + fields="[[getDeviceFields_(managedProperties_)]]" + property-dict="[[managedProperties_]]"> + </network-property-list-mojo> </div> </iron-collapse> </template> - <template is="dom-if" if="[[hasNetworkSection_(networkProperties_, + <template is="dom-if" if="[[hasNetworkSection_(managedProperties_, globalPolicy, managedNetworkAvailable)]]"> <!-- Network toggle --> <cr-expand-button @@ -282,7 +287,7 @@ $i18n{networkSectionNetwork} </div> <template is="dom-if" - if="[[showScanningSpinner_(networkProperties_)]]"> + if="[[showScanningSpinner_(managedProperties_, deviceState_)]]"> <paper-spinner-lite active></paper-spinner-lite> </template> </div> @@ -292,35 +297,41 @@ <div class="settings-box single-column stretch indented first"> <!-- Choose Mobile Network (Cellular only). --> <template is="dom-if" - if="[[showCellularChooseNetwork_(networkProperties_)]]"> - <network-choose-mobile - networking-private="[[networkingPrivate]]" - network-properties="[[networkProperties_]]"> + if="[[showCellularChooseNetwork_(managedProperties_)]]"> + <network-choose-mobile device-state="[[deviceState_]]" + managed-properties="[[managedProperties_]]"> </network-choose-mobile> </template> <!-- APN --> - <template is="dom-if" if="[[isCellular_(networkProperties_)]]"> - <network-apnlist on-apn-change="onNetworkPropertyChange_" - network-properties="[[networkProperties_]]"> + <template is="dom-if" if="[[isCellular_(managedProperties_)]]"> + <network-apnlist on-apn-change="onApnChange_" + managed-properties="[[managedProperties_]]"> </network-apnlist> </template> <!-- IP Config, Nameservers --> <template is="dom-if" - if="[[isRememberedOrConnected_(networkProperties_)]]"> + if="[[isRememberedOrConnected_(managedProperties_)]]"> <network-ip-config on-ip-change="onIPConfigChange_" - network-properties="[[networkProperties_]]"> + managed-properties="[[managedProperties_]]"> </network-ip-config> <network-nameservers on-nameservers-change="onIPConfigChange_" - network-properties="[[networkProperties_]]"> + managed-properties="[[managedProperties_]]"> </network-nameservers> </template> </div> + + <!-- MAC Address. --> + <div class="settings-box two-line single-column stretch indented" + hidden$="[[!deviceState_.macAddress]]"> + <div>$i18n{OncMacAddress}</div> + <div class="secondary">[[deviceState_.macAddress]]</div> + </div> </iron-collapse> </template> - <template is="dom-if" if="[[hasProxySection_(networkProperties_, + <template is="dom-if" if="[[hasProxySection_(managedProperties_, globalPolicy, managedNetworkAvailable)]]"> <!-- Proxy toggle --> <cr-expand-button @@ -333,17 +344,19 @@ <iron-collapse opened="[[proxyExpanded_]]"> <network-proxy-section prefs="{{prefs}}" on-proxy-change="onProxyChange_" - network-properties="[[networkProperties_]]"> + managed-properties="[[managedProperties_]]"> </network-proxy-section> </iron-collapse> </template> </template> - <tether-connection-dialog id="tetherDialog" - network-properties="[[networkProperties_]]" - on-tether-connect="onTetherConnect_" - out-of-range="[[outOfRange_]]"> - </tether-connection-dialog> + <template is="dom-if" if="[[isTether_(managedProperties_)]]" restamp> + <tether-connection-dialog id="tetherDialog" + managed-properties="[[managedProperties_]]" + on-tether-connect="onTetherConnect_" + out-of-range="[[outOfRange_]]"> + </tether-connection-dialog> + </template> </template> <script src="internet_detail_page.js"></script> </dom-module> 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 bf2d66f205c..3dd71d9ff20 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 @@ -17,7 +17,7 @@ Polymer({ behaviors: [ CrNetworkListenerBehavior, - CrPolicyNetworkBehavior, + CrPolicyNetworkBehaviorMojo, settings.RouteObserverBehavior, I18nBehavior, ], @@ -32,15 +32,16 @@ Polymer({ notify: true, }, - /** - * The current properties for the network matching |guid|. Note: This may - * become set to |undefined| after it is initially set if the network is no - * longer visible, so always test that it is set before accessing it. - * @private {!CrOnc.NetworkProperties|undefined} - */ - networkProperties_: { + /** @private {!chromeos.networkConfig.mojom.ManagedProperties|undefined} */ + managedProperties_: { + type: Object, + observer: 'managedPropertiesChanged_', + }, + + /** @private {?OncMojo.DeviceStateProperties} */ + deviceState_: { type: Object, - observer: 'networkPropertiesChanged_', + value: null, }, /** @@ -90,12 +91,8 @@ Polymer({ value: null, }, - /** @type {!chrome.networkingPrivate.GlobalPolicy|undefined} */ - globalPolicy: { - type: Object, - value: null, - observer: 'globalPolicyChanged_', - }, + /** @type {!chromeos.networkConfig.mojom.GlobalPolicy|undefined} */ + globalPolicy: Object, /** * Whether a managed network is available in the visible network list. @@ -116,9 +113,9 @@ Polymer({ * The network AutoConnect state as a fake preference object. * @private {!chrome.settingsPrivate.PrefObject|undefined} */ - autoConnect_: { + autoConnectPref_: { type: Object, - observer: 'autoConnectChanged_', + observer: 'autoConnectPrefChanged_', }, /** @@ -180,8 +177,11 @@ Polymer({ observers: [ 'updateAlwaysOnVpnPrefValue_(prefs.arc.vpn.always_on.*)', - 'updateAlwaysOnVpnPrefEnforcement_(prefs.vpn_config_allowed.*)', - 'autoConnectChanged_(autoConnect_.*)', 'alwaysOnVpnChanged_(alwaysOnVpn_.*)' + 'updateAlwaysOnVpnPrefEnforcement_(managedProperties_,' + + 'prefs.vpn_config_allowed.*)', + 'updateAutoConnectPref_(globalPolicy)', + 'autoConnectPrefChanged_(autoConnectPref_.*)', + 'alwaysOnVpnChanged_(alwaysOnVpn_.*)', ], /** @private {boolean} */ @@ -192,12 +192,12 @@ Polymer({ * prevents setProperties from being called when setting default properties. * @private {boolean} */ - networkPropertiesReceived_: false, + propertiesReceived_: false, /** * Set in currentRouteChanged() if the showConfigure URL query * parameter is set to true. The dialog cannot be shown until the - * network properties have been fetched in networkPropertiesChanged_(). + * network properties have been fetched in managedPropertiesChanged_(). * @private {boolean} */ shouldShowConfigureWhenNetworkLoaded_: false, @@ -209,16 +209,15 @@ Polymer({ * This UI will use both the networkingPrivate extension API and the * networkConfig mojo API until we provide all of the required functionality * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api. - * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} + * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ - networkConfigProxy_: null, + networkConfig_: null, /** @override */ created: function() { this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** @@ -241,28 +240,23 @@ Polymer({ this.shouldShowConfigureWhenNetworkLoaded_ = queryParams.get('showConfigure') == 'true'; - const type = /** @type {!chrome.networkingPrivate.NetworkType} */ ( - queryParams.get('type')) || - CrOnc.Type.WI_FI; + const type = queryParams.get('type') || 'WiFi'; const name = queryParams.get('name') || type; this.init(guid, type, name); }, /** * @param {string} guid - * @param {!chrome.networkingPrivate.NetworkType} type + * @param {string} type * @param {string} name - * @private */ init: function(guid, type, name) { this.guid = guid; - // Set basic networkProperties until they are loaded. - this.networkPropertiesReceived_ = false; - this.networkProperties_ = { - GUID: this.guid, - Type: type, - Name: {Active: name}, - }; + // Set default properties until they are loaded. + this.propertiesReceived_ = false; + this.deviceState_ = null; + this.managedProperties_ = OncMojo.getDefaultManagedProperties( + OncMojo.getNetworkTypeFromString(type), this.guid, name); this.didSetFocus_ = false; this.getNetworkDetails_(); }, @@ -281,8 +275,8 @@ Polymer({ // Clear network properties before navigating away to ensure that a future // navigation back to the details page does not show a flicker of // incorrect text. See https://crbug.com/905986. - this.networkProperties_ = undefined; - this.networkPropertiesReceived_ = false; + this.managedProperties_ = undefined; + this.propertiesReceived_ = false; settings.navigateToPreviousRoute(); }); @@ -293,64 +287,69 @@ Polymer({ * @param {!Array<OncMojo.NetworkStateProperties>} networks */ onActiveNetworksChanged: function(networks) { - if (!this.guid || !this.networkProperties_) { + if (!this.guid || !this.managedProperties_) { return; } // If the network was or is active, request an update. - if (this.networkProperties_.ConnectionState != - CrOnc.ConnectionState.NOT_CONNECTED || + if (this.managedProperties_.connectionState != + mojom.ConnectionStateType.kNotConnected || networks.find(network => network.guid == this.guid)) { this.getNetworkDetails_(); } }, + /** + * CrosNetworkConfigObserver impl + * @param {!chromeos.networkConfig.mojom.NetworkStateProperties} network + */ + onNetworkStateChanged: function(network) { + if (!this.guid || !this.managedProperties_) { + return; + } + if (network.guid == this.guid) { + this.getNetworkDetails_(); + } + }, + /** CrosNetworkConfigObserver impl */ onNetworkStateListChanged: function() { + if (!this.guid || !this.managedProperties_) { + return; + } this.checkNetworkExists_(); }, /** CrosNetworkConfigObserver impl */ onDeviceStateListChanged: function() { - if (this.guid) { - this.getNetworkDetails_(); + if (!this.guid || !this.managedProperties_) { + return; } - }, - - /** - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy - * @private - */ - globalPolicyChanged_: function(globalPolicy) { - this.updateAutoConnectPref_( - !!(this.autoConnect_ && this.autoConnect_.value), globalPolicy); + this.getDeviceState_(); + this.getNetworkDetails_(); }, /** @private */ - networkPropertiesChanged_: function() { - if (!this.networkProperties_) { + managedPropertiesChanged_: function() { + if (!this.managedProperties_) { return; } + this.updateAutoConnectPref_(); - // Update autoConnect if it has changed. Default value is false. - this.updateAutoConnectPref_( - CrOnc.getAutoConnect(this.networkProperties_), this.globalPolicy); - - // Update preferNetwork if it has changed. Default value is false. - const priority = /** @type {number} */ ( - CrOnc.getActiveValue(this.networkProperties_.Priority) || 0); - const preferNetwork = priority > 0; - if (preferNetwork != this.preferNetwork_) { - this.preferNetwork_ = preferNetwork; + const priority = this.managedProperties_.priority; + if (priority) { + const preferNetwork = priority.activeValue > 0; + if (preferNetwork != this.preferNetwork_) { + this.preferNetwork_ = preferNetwork; + } } - // Set the IPAddress property to the IPV4 Address. - const ipv4 = - CrOnc.getIPConfigForType(this.networkProperties_, CrOnc.IPType.IPV4); - this.ipAddress_ = (ipv4 && ipv4.IPAddress) || ''; + // Set the IPAddress property to the IPv4 Address. + const ipv4 = OncMojo.getIPConfigForType(this.managedProperties_, 'IPv4'); + this.ipAddress_ = (ipv4 && ipv4.ipAddress) || ''; // Update the detail page title. - this.parentNode.pageTitle = CrOnc.getNetworkName(this.networkProperties_); - + const networkName = OncMojo.getNetworkName(this.managedProperties_); + this.parentNode.pageTitle = networkName; Polymer.dom.flush(); if (!this.didSetFocus_) { @@ -364,49 +363,69 @@ Polymer({ } if (this.shouldShowConfigureWhenNetworkLoaded_ && - this.networkProperties_.Tether) { + this.managedProperties_.type == mojom.NetworkType.kTether) { // Set |this.shouldShowConfigureWhenNetworkLoaded_| back to false to // ensure that the Tether dialog is only shown once. this.shouldShowConfigureWhenNetworkLoaded_ = false; - this.showTetherDialog_(); + // Async call to ensure dialog is stamped. + setTimeout(() => this.showTetherDialog_()); } }, /** @private */ - autoConnectChanged_: function() { - if (!this.networkProperties_ || !this.guid) { + getDeviceState_: function() { + if (!this.managedProperties_) { return; } - const onc = this.getEmptyNetworkProperties_(); - CrOnc.setTypeProperty(onc, 'AutoConnect', !!this.autoConnect_.value); - this.setNetworkProperties_(onc); + const type = this.managedProperties_.type; + this.networkConfig_.getDeviceStateList().then(response => { + const devices = response.result; + this.deviceState_ = devices.find(device => device.type == type) || null; + }); + }, + + /** @private */ + autoConnectPrefChanged_: function() { + if (!this.propertiesReceived_) { + return; + } + const config = {}; + config.autoConnect = {value: !!this.autoConnectPref_.value}; + this.setMojoNetworkProperties_(config); }, /** * Updates auto-connect pref value. - * @param {boolean} value - * @param {!chrome.networkingPrivate.GlobalPolicy|undefined} globalPolicy * @private */ - updateAutoConnectPref_: function(value, globalPolicy) { + updateAutoConnectPref_: function() { + if (!this.managedProperties_) { + return; + } + const autoConnect = OncMojo.getManagedAutoConnect(this.managedProperties_); + if (!autoConnect) { + return; + } + let enforcement; let controlledBy; - - if (this.isAutoConnectEnforcedByPolicy( - this.networkProperties_, globalPolicy)) { + if (autoConnect.enforced || + (!!this.globalPolicy && + !!this.globalPolicy.allowOnlyPolicyNetworksToAutoconnect)) { enforcement = chrome.settingsPrivate.Enforcement.ENFORCED; controlledBy = chrome.settingsPrivate.ControlledBy.DEVICE_POLICY; } - if (this.autoConnect_ && this.autoConnect_.value == value && - enforcement == this.autoConnect_.enforcement && - controlledBy == this.autoConnect_.controlledBy) { + if (this.autoConnectPref_ && + this.autoConnectPref_.value == autoConnect.activeValue && + enforcement == this.autoConnectPref_.enforcement && + controlledBy == this.autoConnectPref_.controlledBy) { return; } const newPrefValue = { key: 'fakeAutoConnectPref', - value: value, + value: autoConnect.activeValue, type: chrome.settingsPrivate.PrefType.BOOLEAN, }; if (enforcement) { @@ -414,95 +433,83 @@ Polymer({ newPrefValue.controlledBy = controlledBy; } - this.autoConnect_ = newPrefValue; + this.autoConnectPref_ = newPrefValue; }, /** @private */ preferNetworkChanged_: function() { - if (!this.networkProperties_ || !this.guid) { + if (!this.propertiesReceived_) { return; } - const onc = this.getEmptyNetworkProperties_(); - onc.Priority = this.preferNetwork_ ? 1 : 0; - this.setNetworkProperties_(onc); + const config = {}; + config.priority = {value: this.preferNetwork_ ? 1 : 0}; + this.setMojoNetworkProperties_(config); }, /** @private */ checkNetworkExists_: function() { const filter = { - networkType: CrOnc.Type.ALL, - visible: true, - configured: false + filter: mojom.FilterType.kVisible, + networkType: mojom.NetworkType.kAll, + limit: mojom.kNoLimit, }; - this.networkingPrivate.getNetworks(filter, networks => { - if (networks.find(network => network.GUID == this.guid)) { + this.networkConfig_.getNetworkState(this.guid).then(response => { + if (response.result) { + // Don't update the state, a change event will trigger the update. return; } this.outOfRange_ = true; - if (this.networkProperties_) { + if (this.managedProperties_) { // Set the connection state since we won't receive an update for a non // existent network. - this.networkProperties_.ConnectionState = - CrOnc.ConnectionState.NOT_CONNECTED; + this.managedProperties_.connectionState = + mojom.ConnectionStateType.kNotConnected; } }); }, - /** - * Calls networkingPrivate.getProperties for this.guid. - * @private - */ + /** @private */ getNetworkDetails_: function() { assert(this.guid); if (this.isSecondaryUser_) { - this.networkConfigProxy_.getNetworkState(this.guid).then(response => { + this.networkConfig_.getNetworkState(this.guid).then(response => { this.getStateCallback_(response.result); }); } else { - this.networkingPrivate.getManagedProperties( - this.guid, this.getPropertiesCallback_.bind(this)); + this.networkConfig_.getManagedProperties(this.guid).then(response => { + this.getPropertiesCallback_(response.result); + }); } }, /** - * networkingPrivate.getProperties callback. - * @param {!CrOnc.NetworkProperties} properties The network properties. + * @param {?mojom.ManagedProperties} properties * @private */ getPropertiesCallback_: function(properties) { - if (chrome.runtime.lastError) { - const message = chrome.runtime.lastError.message; - if (message == 'Error.InvalidNetworkGuid') { - console.error('Details page: GUID no longer exists: ' + this.guid); - } else { - console.error( - 'Unexpected networkingPrivate.getManagedProperties error: ' + - message + ' For: ' + this.guid); - } - this.close(); - return; - } - // Details page was closed while request was in progress, ignore the result. if (!this.guid) { return; } if (!properties) { - // Edge case, may occur when disabling. Close this. + console.error('Details page: GUID no longer exists: ' + this.guid); this.close(); return; } + this.managedProperties_ = properties; // Detail page should not be shown when Arc VPN is not connected. - if (this.isArcVpn_(properties) && !this.isConnectedState_(properties)) { + if (this.isArcVpn_(this.managedProperties_) && + !this.isConnectedState_(this.managedProperties_)) { this.guid = ''; this.close(); } - - this.networkProperties_ = properties; - this.networkPropertiesReceived_ = true; + this.propertiesReceived_ = true; this.outOfRange_ = false; + if (!this.deviceState_) { + this.getDeviceState_(); + } }, /** @@ -515,57 +522,38 @@ Polymer({ this.close(); return; } - const type = /** @type {CrOnc.Type} */ ( - OncMojo.getNetworkTypeString(networkState.type)); - - let connectionState; - switch (networkState.connectionState) { - case mojom.ConnectionStateType.kOnline: - case mojom.ConnectionStateType.kConnected: - case mojom.ConnectionStateType.kPortal: - connectionState = CrOnc.ConnectionState.CONNECTED; - break; - case mojom.ConnectionStateType.kConnecting: - connectionState = CrOnc.ConnectionState.CONNECTING; - break; - case mojom.ConnectionStateType.kNotConnected: - connectionState = CrOnc.ConnectionState.NOT_CONNECTED; - break; - } - - this.networkProperties_ = { - GUID: networkState.guid, - Name: {Active: networkState.name}, - Type: type, - Connectable: networkState.connectable, - ConnectionState: connectionState, - }; - this.networkPropertiesReceived_ = true; + const managedProperties = OncMojo.getDefaultManagedProperties( + networkState.type, networkState.guid, networkState.name); + managedProperties.connectable = networkState.connectable; + managedProperties.connectionState = networkState.connectionState; + this.managedProperties_ = managedProperties; + + this.propertiesReceived_ = true; this.outOfRange_ = false; }, /** - * @param {!CrOnc.NetworkProperties} properties + * @param {!mojom.ManagedProperties} properties * @return {!OncMojo.NetworkStateProperties|undefined} */ getNetworkState_: function(properties) { - return properties ? OncMojo.oncPropertiesToNetworkState(properties) : - undefined; + if (!properties) { + return undefined; + } + return OncMojo.managedPropertiesToNetworkState(properties); }, /** - * @param {!chrome.networkingPrivate.NetworkConfigProperties} onc The ONC - * network properties. + * @param {!mojom.ConfigProperties} config * @private */ - setNetworkProperties_: function(onc) { - if (!this.networkPropertiesReceived_) { + setMojoNetworkProperties_: function(config) { + if (!this.propertiesReceived_ || !this.guid) { return; } - - assert(this.guid); - this.networkingPrivate.setProperties(this.guid, onc, () => { - if (chrome.runtime.lastError) { + this.networkConfig_.setProperties(this.guid, config).then(response => { + if (!response.success) { + console.error('Unable to set properties: ' + JSON.stringify(config)); // An error typically indicates invalid input; request the properties // to update any invalid fields. this.getNetworkDetails_(); @@ -574,279 +562,338 @@ Polymer({ }, /** - * @return {!chrome.networkingPrivate.NetworkConfigProperties} An ONC - * dictionary with just the Type property set. Used for passing properties - * to setNetworkProperties_. - * @private - */ - getEmptyNetworkProperties_: function() { - const type = this.networkProperties_ ? this.networkProperties_.Type : - CrOnc.Type.WI_FI; - return {Type: type}; - }, - - /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties + * @param {boolean} propertiesReceived * @param {boolean} outOfRange * @return {string} The text to display for the network connection state. * @private */ - getStateText_: function(networkProperties, outOfRange) { - if (!networkProperties || !networkProperties.ConnectionState) { + getStateText_: function(managedProperties, propertiesReceived, outOfRange) { + if (!managedProperties || !propertiesReceived) { return ''; } if (outOfRange) { - return networkProperties.Type == CrOnc.Type.TETHER ? + return managedProperties.type == mojom.NetworkType.kTether ? this.i18n('tetherPhoneOutOfRange') : this.i18n('networkOutOfRange'); } - return this.i18n('Onc' + networkProperties.ConnectionState); + if (managedProperties.type == mojom.NetworkType.kCellular && + !managedProperties.connectable) { + if (managedProperties.cellular.homeProvider && + managedProperties.cellular.homeProvider.name) { + return this.i18n( + 'cellularContactSpecificCarrier', + managedProperties.cellular.homeProvider.name); + } + return this.i18n('cellularContactDefaultCarrier'); + } + + return this.i18n( + OncMojo.getConnectionStateString(managedProperties.connectionState)); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {string} The text to display for auto-connect toggle label. * @private */ - getAutoConnectToggleLabel_: function(networkProperties) { - return this.isCellular_(networkProperties) ? + getAutoConnectToggleLabel_: function(managedProperties) { + return this.isCellular_(managedProperties) ? this.i18n('networkAutoConnectCellular') : this.i18n('networkAutoConnect'); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {string} The text to display with roaming details. * @private */ - getRoamingDetails_: function(networkProperties) { - if (!networkProperties.Cellular.AllowRoaming) { + getRoamingDetails_: function(managedProperties) { + if (!this.isCellular_(managedProperties)) { + return ''; + } + if (!managedProperties.cellular.allowRoaming) { return this.i18n('networkAllowDataRoamingDisabled'); } - return networkProperties.Cellular.RoamingState === - CrOnc.RoamingState.ROAMING ? + return managedProperties.cellular.roamingState == 'Roaming' ? this.i18n('networkAllowDataRoamingEnabledRoaming') : this.i18n('networkAllowDataRoamingEnabledHome'); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties|undefined} managedProperties * @return {boolean} True if the network is connected. * @private */ - isConnectedState_: function(networkProperties) { - return !!networkProperties && - networkProperties.ConnectionState == CrOnc.ConnectionState.CONNECTED; + isConnectedState_: function(managedProperties) { + return !!managedProperties && + OncMojo.connectionStateIsConnected(managedProperties.connectionState); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties|undefined} managedProperties + * @param {boolean} outOfRange + * @return {boolean} True if the network shown cannot initiate a connection. + * @private + */ + isConnectionErrorState_: function(managedProperties, outOfRange) { + if (outOfRange) { + return true; + } + + if (!managedProperties) { + return false; + } + + // It's still possible to initiate a connection to a network if it is not + // connectable as long as the network has an associated configuration flow. + // Cellular networks do not have a configuration flow, so a Cellular network + // that is not connectable represents an error state. + return managedProperties.type == mojom.NetworkType.kCellular && + !managedProperties.connectable; + }, + + /** + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - isRemembered_: function(networkProperties) { - const source = networkProperties ? networkProperties.Source : null; - return !!source && source != CrOnc.Source.NONE; + isRemembered_: function(managedProperties) { + return !!managedProperties && + managedProperties.source != mojom.OncSource.kNone; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - isRememberedOrConnected_: function(networkProperties) { - return this.isRemembered_(networkProperties) || - this.isConnectedState_(networkProperties); + isRememberedOrConnected_: function(managedProperties) { + return this.isRemembered_(managedProperties) || + this.isConnectedState_(managedProperties); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - isCellular_: function(networkProperties) { - return !!networkProperties && - networkProperties.Type == CrOnc.Type.CELLULAR && - !!networkProperties.Cellular; + isCellular_: function(managedProperties) { + return !!managedProperties && + managedProperties.type == mojom.NetworkType.kCellular; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @return {boolean} + * @private + */ + isTether_: function(managedProperties) { + return !!managedProperties && + managedProperties.type == mojom.NetworkType.kTether; + }, + + /** + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy|undefined} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} * @private */ isBlockedByPolicy_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - if (!networkProperties || networkProperties.Type != CrOnc.Type.WI_FI || - this.isPolicySource(networkProperties.Source) || !globalPolicy) { + managedProperties, globalPolicy, managedNetworkAvailable) { + if (!managedProperties || !globalPolicy || + managedProperties.type != mojom.NetworkType.kWiFi || + this.isPolicySource(managedProperties.source)) { return false; } - return !!globalPolicy.AllowOnlyPolicyNetworksToConnect || - (!!globalPolicy.AllowOnlyPolicyNetworksToConnectIfAvailable && + const hexSsid = OncMojo.getActiveString(managedProperties.wifi.hexSsid); + return !!globalPolicy.allowOnlyPolicyNetworksToConnect || + (!!globalPolicy.allowOnlyPolicyNetworksToConnectIfAvailable && !!managedNetworkAvailable) || - (!!networkProperties.WiFi && !!networkProperties.WiFi.HexSSID && - !!globalPolicy.BlacklistedHexSSIDs && - globalPolicy.BlacklistedHexSSIDs.includes( - CrOnc.getStateOrActiveString(networkProperties.WiFi.HexSSID))); + (!!hexSsid && !!globalPolicy.blockedHexSsids && + globalPolicy.blockedHexSsids.includes(hexSsid)); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} * @private */ showConnect_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - if (!networkProperties) { + managedProperties, globalPolicy, managedNetworkAvailable) { + if (!managedProperties) { return false; } if (this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable)) { + managedProperties, globalPolicy, managedNetworkAvailable)) { return false; } + // TODO(lgcheng@) support connect Arc VPN from UI once Android support API // to initiate a VPN session. - if (this.isArcVpn_(networkProperties)) { + if (this.isArcVpn_(managedProperties)) { return false; } - - return networkProperties.Type != CrOnc.Type.ETHERNET && - networkProperties.ConnectionState == - CrOnc.ConnectionState.NOT_CONNECTED; + if (managedProperties.connectionState != + mojom.ConnectionStateType.kNotConnected) { + return false; + } + // Cellular is not configurable, so we always show the connect button, and + // disable it if 'connectable' is false. + if (managedProperties.type == mojom.NetworkType.kCellular) { + return true; + } + // If 'connectable' is false we show the configure button. + return managedProperties.connectable && + managedProperties.type != mojom.NetworkType.kEthernet; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showDisconnect_: function(networkProperties) { - return !!networkProperties && - networkProperties.Type != CrOnc.Type.ETHERNET && - CrOnc.isConnectingOrConnected(networkProperties); + showDisconnect_: function(managedProperties) { + if (!managedProperties || + managedProperties.type == mojom.NetworkType.kEthernet) { + return false; + } + return managedProperties.connectionState != + mojom.ConnectionStateType.kNotConnected; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showForget_: function(networkProperties) { - if (this.isSecondaryUser_ || !networkProperties) { + showForget_: function(managedProperties) { + if (!managedProperties || this.isSecondaryUser_) { return false; } - const type = networkProperties.Type; - if (type != CrOnc.Type.WI_FI && type != CrOnc.Type.VPN) { + const type = managedProperties.type; + if (type != mojom.NetworkType.kWiFi && type != mojom.NetworkType.kVPN) { return false; } - if (this.isArcVpn_(networkProperties)) { + if (this.isArcVpn_(managedProperties)) { return false; } - return !this.isPolicySource(networkProperties.Source) && - this.isRemembered_(networkProperties); + return !this.isPolicySource(managedProperties.source) && + this.isRemembered_(managedProperties); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showActivate_: function(networkProperties) { - if (this.isSecondaryUser_) { + showActivate_: function(managedProperties) { + if (!managedProperties || this.isSecondaryUser_) { return false; } - if (!this.isCellular_(networkProperties)) { + if (!this.isCellular_(managedProperties)) { return false; } - const activation = networkProperties.Cellular.ActivationState; - return activation == CrOnc.ActivationState.NOT_ACTIVATED || - activation == CrOnc.ActivationState.PARTIALLY_ACTIVATED; + const activation = managedProperties.cellular.activationState; + return activation == mojom.ActivationStateType.kNotActivated || + activation == mojom.ActivationStateType.kPartiallyActivated; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} * @private */ showConfigure_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - if (this.isSecondaryUser_ || !networkProperties) { + managedProperties, globalPolicy, managedNetworkAvailable) { + if (!managedProperties || this.isSecondaryUser_) { return false; } if (this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable)) { + managedProperties, globalPolicy, managedNetworkAvailable)) { return false; } - const type = networkProperties.Type; - if (type == CrOnc.Type.CELLULAR || type == CrOnc.Type.TETHER) { + const type = managedProperties.type; + if (type == mojom.NetworkType.kCellular || + type == mojom.NetworkType.kTether) { return false; } - if (type == CrOnc.Type.WI_FI) { - const security = networkProperties.WiFi && - CrOnc.getActiveValue(networkProperties.WiFi.Security); - if (!security || security == CrOnc.Security.NONE) { - return false; - } + if (type == mojom.NetworkType.kWiFi && + managedProperties.wifi.security == mojom.SecurityType.kNone) { + return false; } - if ((type == CrOnc.Type.WI_FI || type == CrOnc.Type.WI_MAX) && - CrOnc.isConnectingOrConnected(networkProperties)) { + if (type == mojom.NetworkType.kWiFi && + (managedProperties.connectionState != + mojom.ConnectionStateType.kNotConnected)) { return false; } - if (this.isArcVpn_(networkProperties) && - !this.isConnectedState_(networkProperties)) { + if (this.isArcVpn_(managedProperties) && + !this.isConnectedState_(managedProperties)) { return false; } return true; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.settingsPrivate.PrefObject} vpn_config_allowed + * @param {!mojom.ManagedProperties} managedProperties + * @param {!chrome.settingsPrivate.PrefObject} vpnConfigAllowed * @return {boolean} * @private */ - disableForget_: function(networkProperties, vpn_config_allowed) { - return this.isVpn_(networkProperties) && vpn_config_allowed && - !vpn_config_allowed.value; + disableForget_: function(managedProperties, vpnConfigAllowed) { + if (!managedProperties) { + return true; + } + return managedProperties.type == mojom.NetworkType.kVPN && + vpnConfigAllowed && !vpnConfigAllowed.value; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.settingsPrivate.PrefObject} vpn_config_allowed + * @param {!mojom.ManagedProperties} managedProperties + * @param {!chrome.settingsPrivate.PrefObject} vpnConfigAllowed * @return {boolean} * @private */ - disableConfigure_: function(networkProperties, vpn_config_allowed) { - if (!networkProperties || - (this.isVpn_(networkProperties) && vpn_config_allowed && - !vpn_config_allowed.value)) { + disableConfigure_: function(managedProperties, vpnConfigAllowed) { + if (!managedProperties) { return true; } - return this.isPolicySource(networkProperties.Source) && - !this.hasRecommendedFields_(networkProperties); + if (managedProperties.type == mojom.NetworkType.kVPN && vpnConfigAllowed && + !vpnConfigAllowed.value) { + return true; + } + return this.isPolicySource(managedProperties.source) && + !this.hasRecommendedFields_(managedProperties); }, /** - * @param {!Object} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} */ - hasRecommendedFields_: function(networkProperties) { - for (const property in networkProperties) { - const propertyValue = networkProperties[property]; - if (this.isNetworkPolicyRecommended(propertyValue) || - (typeof propertyValue == 'object' && - this.hasRecommendedFields_(propertyValue))) { + hasRecommendedFields_: function(managedProperties) { + if (!managedProperties) { + return false; + } + for (const key of Object.keys(managedProperties)) { + const value = managedProperties[key]; + if (typeof value != 'object' || value === null) { + continue; + } + if ('activeValue' in value) { + if (this.isNetworkPolicyRecommended(value)) { + return true; + } + } else if (this.hasRecommendedFields_(value)) { return true; } } @@ -854,34 +901,33 @@ Polymer({ }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showViewAccount_: function(networkProperties) { - if (this.isSecondaryUser_) { + showViewAccount_: function(managedProperties) { + if (!managedProperties || this.isSecondaryUser_) { return false; } // Show either the 'Activate' or the 'View Account' button (Cellular only). - if (!this.isCellular_(networkProperties) || - this.showActivate_(networkProperties)) { + if (!this.isCellular_(managedProperties) || + this.showActivate_(managedProperties)) { return false; } - const paymentPortal = networkProperties.Cellular.PaymentPortal; - if (!paymentPortal || !paymentPortal.Url) { + const paymentPortal = managedProperties.cellular.paymentPortal; + if (!paymentPortal || !paymentPortal.url) { return false; } // Only show for connected networks or LTE networks with a valid MDN. - if (!this.isConnectedState_(networkProperties)) { - const technology = networkProperties.Cellular.NetworkTechnology; - if (technology != CrOnc.NetworkTechnology.LTE && - technology != CrOnc.NetworkTechnology.LTE_ADVANCED) { + if (!this.isConnectedState_(managedProperties)) { + const technology = managedProperties.cellular.networkTechnology; + if (technology != 'LTE' && technology != 'LTEAdvanced') { return false; } - if (!networkProperties.Cellular.MDN) { + if (!managedProperties.cellular.mdn) { return false; } } @@ -890,49 +936,37 @@ Polymer({ }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @param {?OncMojo.NetworkStateProperties} defaultNetwork - * @param {boolean} networkPropertiesReceived + * @param {boolean} propertiesReceived * @param {boolean} outOfRange - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} Whether or not to enable the network connect button. * @private */ enableConnect_: function( - networkProperties, defaultNetwork, networkPropertiesReceived, outOfRange, + managedProperties, defaultNetwork, propertiesReceived, outOfRange, globalPolicy, managedNetworkAvailable) { if (!this.showConnect_( - networkProperties, globalPolicy, managedNetworkAvailable)) { + managedProperties, globalPolicy, managedNetworkAvailable)) { return false; } - if (!networkPropertiesReceived || outOfRange) { + if (!propertiesReceived || outOfRange) { return false; } - if (this.isSecondaryUser_ && - this.networkProperties_.Connectable === false) { + // Cellular networks are not configurable, so we show a disabled 'Connect' + // button when not connectable. + if (managedProperties.type == mojom.NetworkType.kCellular && + !managedProperties.connectable) { return false; } - if ((networkProperties.Type == CrOnc.Type.CELLULAR) && - (CrOnc.isSimLocked(networkProperties) || - this.get('Cellular.Scanning', networkProperties))) { - return false; - } - if (networkProperties.Type == CrOnc.Type.VPN && !defaultNetwork) { + if (managedProperties.type == mojom.NetworkType.kVPN && !defaultNetwork) { return false; } return true; }, - /** - * @param {!CrOnc.NetworkProperties=} networkProperties - * @return {boolean} Whether or not we are looking at VPN configuration. - * @private - */ - isVpn_: function(networkProperties) { - return !!networkProperties && networkProperties.Type == CrOnc.Type.VPN; - }, - /** @private */ updateAlwaysOnVpnPrefValue_: function() { this.alwaysOnVpn_.value = this.prefs.arc && this.prefs.arc.vpn && @@ -953,14 +987,14 @@ Polymer({ // Only mark VPN networks as enforced. This fake pref also controls the // policy indicator on the connect/disconnect buttons, so it shouldn't be // shown on non-VPN networks. - if (this.isVpn_(this.networkProperties_) && this.prefs && + if (this.managedProperties_ && + this.managedProperties_.type == mojom.NetworkType.kVPN && this.prefs && this.prefs.vpn_config_allowed && !this.prefs.vpn_config_allowed.value) { fakeAlwaysOnVpnEnforcementPref.enforcement = chrome.settingsPrivate.Enforcement.ENFORCED; fakeAlwaysOnVpnEnforcementPref.controlledBy = this.prefs.vpn_config_allowed.controlledBy; } - return fakeAlwaysOnVpnEnforcementPref; }, @@ -976,15 +1010,14 @@ Polymer({ * @private */ getTetherDialog_: function() { - return /** @type {!TetherConnectionDialogElement} */ (this.$.tetherDialog); + return /** @type {!TetherConnectionDialogElement} */ ( + this.$$('#tetherDialog')); }, /** @private */ onConnectTap_: function() { - // For Tether networks that have not connected to a host, show a dialog. - if (this.networkProperties_.Type == CrOnc.Type.TETHER && - (!this.networkProperties_.Tether || - !this.networkProperties_.Tether.HasConnectedToHost)) { + if (this.managedProperties_.type == mojom.NetworkType.kTether && + (!this.managedProperties_.tether.hasConnectedToHost)) { this.showTetherDialog_(); return; } @@ -1002,9 +1035,9 @@ Polymer({ * @private */ fireNetworkConnect_: function(bypassDialog) { - assert(this.networkProperties_); + assert(this.managedProperties_); const networkState = - OncMojo.oncPropertiesToNetworkState(this.networkProperties_); + OncMojo.managedPropertiesToNetworkState(this.managedProperties_); this.fire( 'network-connect', {networkState: networkState, bypassConnectionDialog: bypassDialog}); @@ -1012,7 +1045,11 @@ Polymer({ /** @private */ onDisconnectTap_: function() { - this.networkingPrivate.startDisconnect(this.guid); + this.networkConfig_.startDisconnect(this.guid).then(response => { + if (!response.success) { + console.error('Disconnect failed for: ' + this.guid); + } + }); }, /** @private */ @@ -1024,29 +1061,29 @@ Polymer({ /** @private */ onActivateTap_: function() { - this.networkingPrivate.startActivate(this.guid); + this.browserProxy_.showCellularSetupUI(this.guid); }, /** @private */ onConfigureTap_: function() { - if (this.networkProperties_ && - (this.isThirdPartyVpn_(this.networkProperties_) || - this.isArcVpn_(this.networkProperties_))) { + if (this.managedProperties_ && + (this.isThirdPartyVpn_(this.managedProperties_) || + this.isArcVpn_(this.managedProperties_))) { this.browserProxy_.configureThirdPartyVpn(this.guid); return; } this.fire('show-config', { - guid: this.networkProperties_.GUID, - type: this.networkProperties_.Type, - name: CrOnc.getNetworkName(this.networkProperties_) + guid: this.guid, + type: OncMojo.getNetworkTypeString(this.managedProperties_.type), + name: OncMojo.getNetworkName(this.managedProperties_) }); }, /** @private */ onViewAccountTap_: function() { - // startActivate() will show the account page for activated networks. - this.networkingPrivate.startActivate(this.guid); + // Currently 'Account Details' is the same as the activation UI. + this.browserProxy_.showCellularSetupUI(this.guid); }, /** @type {string} */ @@ -1063,218 +1100,133 @@ Polymer({ */ showHiddenNetworkWarning_: function() { return loadTimeData.getBoolean('showHiddenNetworkWarning') && - !!this.autoConnect_ && !!this.autoConnect_.value && - !!this.networkProperties_ && !!this.networkProperties_.WiFi && - !!CrOnc.getActiveValue(this.networkProperties_.WiFi.HiddenSSID); + !!this.autoConnectPref_ && !!this.autoConnectPref_.value && + !!this.managedProperties_ && + !!this.managedProperties_.type == mojom.NetworkType.kWiFi && + !!OncMojo.getActiveValue(this.managedProperties_.wifi.hiddenSsid); }, /** * Event triggered for elements associated with network properties. * @param {!CustomEvent<!{ * field: string, - * value: !CrOnc.NetworkPropertyType + * value: (string|number|boolean|!Array<string>) * }>} e * @private */ onNetworkPropertyChange_: function(e) { - if (!this.networkProperties_) { + if (!this.propertiesReceived_) { return; } const field = e.detail.field; const value = e.detail.value; - const onc = this.getEmptyNetworkProperties_(); - if (field == 'APN') { - CrOnc.setTypeProperty(onc, 'APN', value); - } else if (field == 'SIMLockStatus') { - CrOnc.setTypeProperty(onc, 'SIMLockStatus', value); - } else { - const valueType = typeof value; - if (valueType == 'string' || valueType == 'number' || - valueType == 'boolean' || Array.isArray(value)) { - CrOnc.setProperty(onc, field, value); - // Ensure any required configuration properties are also set. - if (field.match(/^VPN/)) { - const vpnType = - CrOnc.getActiveValue(this.networkProperties_.VPN.Type); - assert(vpnType); - CrOnc.setProperty(onc, 'VPN.Type', vpnType); - } - } else { - console.error( - 'Unexpected property change event, Key: ' + field + - ' Value: ' + JSON.stringify(value)); - return; - } + const config = {}; + const valueType = typeof value; + if (valueType != 'string' && valueType != 'number' && + valueType != 'boolean' && !Array.isArray(value)) { + console.error( + 'Unexpected property change event, Key: ' + field + + ' Value: ' + JSON.stringify(value)); + return; } - this.setNetworkProperties_(onc); + OncMojo.setConfigProperty(config, field, value); + // Ensure any required configuration properties are also set. + if (this.managedProperties_.vpn && config.vpn && + config.vpn.type === undefined) { + config.vpn.type = this.managedProperties_.vpn.type; + } + this.setMojoNetworkProperties_(config); }, /** + * @param {!CustomEvent<!mojom.ApnProperties>} event + * @private + */ + onApnChange_: function(event) { + if (!this.propertiesReceived_) { + return; + } + const apn = event.detail; + const config = {cellular: {apn: apn}}; + this.setMojoNetworkProperties_(config); + }, + + + /** * Event triggered when the IP Config or NameServers element changes. * @param {!CustomEvent<!{ * field: string, - * value: (string|!CrOnc.IPConfigProperties| !Array<string>) + * value: (string|!mojom.IPConfigProperties|!Array<string>) * }>} event The network-ip-config or network-nameservers change event. * @private */ onIPConfigChange_: function(event) { - if (!this.networkProperties_) { + if (!this.managedProperties_) { return; } - const field = event.detail.field; - const value = event.detail.value; - // Get an empty ONC dictionary and set just the IP Config properties that - // need to change. - const onc = this.getEmptyNetworkProperties_(); - const ipConfigType = - /** @type {chrome.networkingPrivate.IPConfigType|undefined} */ ( - CrOnc.getActiveValue(this.networkProperties_.IPAddressConfigType)); - if (field == 'IPAddressConfigType') { - const newIpConfigType = - /** @type {chrome.networkingPrivate.IPConfigType} */ (value); - if (newIpConfigType == ipConfigType) { - return; - } - onc.IPAddressConfigType = newIpConfigType; - } else if (field == 'NameServersConfigType') { - const nsConfigType = - /** @type {chrome.networkingPrivate.IPConfigType|undefined} */ ( - CrOnc.getActiveValue( - this.networkProperties_.NameServersConfigType)); - const newNsConfigType = - /** @type {chrome.networkingPrivate.IPConfigType} */ (value); - if (newNsConfigType == nsConfigType) { - return; - } - onc.NameServersConfigType = newNsConfigType; - } else if (field == 'StaticIPConfig') { - if (ipConfigType == CrOnc.IPConfigType.STATIC) { - const staticIpConfig = this.networkProperties_.StaticIPConfig; - const ipConfigValue = /** @type {!Object} */ (value); - if (staticIpConfig && - this.allPropertiesMatch_(staticIpConfig, ipConfigValue)) { - return; - } - } - onc.IPAddressConfigType = CrOnc.IPConfigType.STATIC; - if (!onc.StaticIPConfig) { - onc.StaticIPConfig = - /** @type {!chrome.networkingPrivate.IPConfigProperties} */ ({}); - } - // Only copy Static IP properties. - const keysToCopy = ['Type', 'IPAddress', 'RoutingPrefix', 'Gateway']; - for (let i = 0; i < keysToCopy.length; ++i) { - const key = keysToCopy[i]; - if (key in value) { - onc.StaticIPConfig[key] = value[key]; - } - } - } else if (field == 'NameServers') { - // If a StaticIPConfig property is specified and its NameServers value - // matches the new value, no need to set anything. - const nameServers = /** @type {!Array<string>} */ (value); - if (onc.NameServersConfigType == CrOnc.IPConfigType.STATIC && - onc.StaticIPConfig && onc.StaticIPConfig.NameServers == nameServers) { - return; - } - onc.NameServersConfigType = CrOnc.IPConfigType.STATIC; - if (!onc.StaticIPConfig) { - onc.StaticIPConfig = - /** @type {!chrome.networkingPrivate.IPConfigProperties} */ ({}); - } - onc.StaticIPConfig.NameServers = nameServers; - } else { - console.error('Unexpected change field: ' + field); - return; + const config = OncMojo.getUpdatedIPConfigProperties( + this.managedProperties_, event.detail.field, event.detail.value); + if (config) { + this.setMojoNetworkProperties_(config); } - // setValidStaticIPConfig will fill in any other properties from - // networkProperties. This is necessary since we update IP Address and - // NameServers independently. - CrOnc.setValidStaticIPConfig(onc, this.networkProperties_); - this.setNetworkProperties_(onc); }, /** * Event triggered when the Proxy configuration element changes. - * @param {!CustomEvent<!{field: string, value: !CrOnc.ProxySettings}>} event - * The network-proxy change event. + * @param {!CustomEvent<!mojom.ProxySettings>} event * @private */ onProxyChange_: function(event) { - if (!this.networkProperties_) { - return; - } - const field = event.detail.field; - const value = event.detail.value; - if (field != 'ProxySettings') { + if (!this.propertiesReceived_) { return; } - const onc = this.getEmptyNetworkProperties_(); - CrOnc.setProperty(onc, 'ProxySettings', /** @type {!Object} */ (value)); - this.setNetworkProperties_(onc); + this.setMojoNetworkProperties_({proxySettings: event.detail}); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} True if the shared message should be shown. * @private */ showShared_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - return !!networkProperties && - (networkProperties.Source == 'Device' || - networkProperties.Source == 'DevicePolicy') && + managedProperties, globalPolicy, managedNetworkAvailable) { + return !!managedProperties && + (managedProperties.source == mojom.OncSource.kDevice || + managedProperties.source == mojom.OncSource.kDevicePolicy) && !this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable); + managedProperties, globalPolicy, managedNetworkAvailable); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} True if the AutoConnect checkbox should be shown. * @private */ showAutoConnect_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - return !!networkProperties && - networkProperties.Type != CrOnc.Type.ETHERNET && - this.isRemembered_(networkProperties) && - !this.isArcVpn_(networkProperties) && + managedProperties, globalPolicy, managedNetworkAvailable) { + return !!managedProperties && + managedProperties.type != mojom.NetworkType.kEthernet && + this.isRemembered_(managedProperties) && + !this.isArcVpn_(managedProperties) && !this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable); + managedProperties, globalPolicy, managedNetworkAvailable); }, /** - * @param {!CrOnc.NetworkProperties=} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy=} globalPolicy - * @return {boolean} - * @private - */ - isAutoConnectEnforcedByPolicy: function(networkProperties, globalPolicy) { - if (!networkProperties || networkProperties.Type != CrOnc.Type.WI_FI) { - return false; - } - if (this.isPolicySource(networkProperties.Source)) { - return !this.isEditable(CrOnc.getManagedAutoConnect(networkProperties)); - } - return !!globalPolicy && - !!globalPolicy.AllowOnlyPolicyNetworksToAutoconnect; - }, - - /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} Whether the toggle for the Always-on VPN feature is * displayed. * @private */ - showAlwaysOnVpn_: function(networkProperties) { - return this.isArcVpn_(networkProperties) && this.prefs.arc && + showAlwaysOnVpn_: function(managedProperties) { + return this.isArcVpn_(managedProperties) && this.prefs.arc && this.prefs.arc.vpn && this.prefs.arc.vpn.always_on && this.prefs.arc.vpn.always_on.vpn_package && - networkProperties.VPN.Host.Active === + OncMojo.getActiveValue(managedProperties.vpn.host) === this.prefs.arc.vpn.always_on.vpn_package.value; }, @@ -1289,27 +1241,28 @@ Polymer({ }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} True if the prefer network checkbox should be shown. * @private */ showPreferNetwork_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - if (!networkProperties) { + managedProperties, globalPolicy, managedNetworkAvailable) { + if (!managedProperties) { return false; } - const type = networkProperties.Type; - if (type == CrOnc.Type.ETHERNET || type == CrOnc.Type.CELLULAR || - this.isArcVpn_(networkProperties)) { + const type = managedProperties.type; + if (type == mojom.NetworkType.kEthernet || + type == mojom.NetworkType.kCellular || + this.isArcVpn_(managedProperties)) { return false; } - return this.isRemembered_(networkProperties) && + return this.isRemembered_(managedProperties) && !this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable); + managedProperties, globalPolicy, managedNetworkAvailable); }, /** @@ -1336,7 +1289,7 @@ Polymer({ */ hasVisibleFields_: function(fields) { for (let i = 0; i < fields.length; ++i) { - const value = this.get(fields[i], this.networkProperties_); + const value = this.get(fields[i], this.managedProperties_); if (value !== undefined && value !== '') { return true; } @@ -1358,65 +1311,70 @@ Polymer({ * @private */ getInfoFields_: function() { - if (!this.networkProperties_) { + if (!this.managedProperties_) { return []; } /** @type {!Array<string>} */ const fields = []; - const type = this.networkProperties_.Type; - if (type == CrOnc.Type.CELLULAR && !!this.networkProperties_.Cellular) { - fields.push( - 'Cellular.ActivationState', 'RestrictedConnectivity', - 'Cellular.ServingOperator.Name'); - } else if (type == CrOnc.Type.TETHER && !!this.networkProperties_.Tether) { + const type = this.managedProperties_.type; + if (type == mojom.NetworkType.kCellular) { + fields.push('cellular.activationState', 'cellular.servingOperator.name'); + if (this.managedProperties_.restrictedConnectivity) { + fields.push('restrictedConnectivity'); + } + } else if (type == mojom.NetworkType.kTether) { fields.push( - 'Tether.BatteryPercentage', 'Tether.SignalStrength', - 'Tether.Carrier'); - } else if (type == CrOnc.Type.VPN && !!this.networkProperties_.VPN) { - const vpnType = CrOnc.getActiveValue(this.networkProperties_.VPN.Type); + 'tether.batteryPercentage', 'tether.signalStrength', + 'tether.carrier'); + } else if (type == mojom.NetworkType.kVPN) { + const vpnType = this.managedProperties_.vpn.type; switch (vpnType) { - case CrOnc.VPNType.THIRD_PARTY_VPN: - fields.push('VPN.ThirdPartyVPN.ProviderName'); + case mojom.VpnType.kExtension: + fields.push('vpn.providerName'); break; - case CrOnc.VPNType.ARCVPN: - fields.push('VPN.Type'); + case mojom.VpnType.kArc: + fields.push('vpn.type'); + fields.push('vpn.providerName'); break; - case CrOnc.VPNType.OPEN_VPN: + case mojom.VpnType.kOpenVPN: fields.push( - 'VPN.Type', 'VPN.Host', 'VPN.OpenVPN.Username', - 'VPN.OpenVPN.ExtraHosts'); + 'vpn.type', 'vpn.host', 'vpn.openVpn.username', + 'vpn.openVpn.extraHosts'); break; - case CrOnc.VPNType.L2TP_IPSEC: - fields.push('VPN.Type', 'VPN.Host', 'VPN.L2TP.Username'); + case mojom.VpnType.kL2TPIPsec: + fields.push('vpn.type', 'vpn.host', 'vpn.l2tp.username'); break; } - } else if (type == CrOnc.Type.WI_FI) { - fields.push('RestrictedConnectivity'); - } else if (type == CrOnc.Type.WI_MAX) { - fields.push('RestrictedConnectivity', 'WiMAX.EAP.Identity'); + } else if (type == mojom.NetworkType.kWiFi) { + if (this.managedProperties_.restrictedConnectivity) { + fields.push('restrictedConnectivity'); + } } return fields; }, /** + * Provides the list of editable fields to <network-property-list>. + * NOTE: Entries added to this list must be reflected in ConfigProperties in + * chromeos.network_config.mojom and handled in the service implementation. * @return {!Object} A dictionary of editable fields in the info section. * @private */ getInfoEditFieldTypes_: function() { - if (!this.networkProperties_) { + if (!this.managedProperties_) { return []; } /** @dict */ const editFields = {}; - const type = this.networkProperties_.Type; - if (type == CrOnc.Type.VPN && !!this.networkProperties_.VPN) { - const vpnType = CrOnc.getActiveValue(this.networkProperties_.VPN.Type); - if (vpnType != CrOnc.VPNType.THIRD_PARTY_VPN) { - editFields['VPN.Host'] = 'String'; + const type = this.managedProperties_.type; + if (type == mojom.NetworkType.kVPN) { + const vpnType = this.managedProperties_.vpn.type; + if (vpnType != mojom.VpnType.kExtension) { + editFields['vpn.host'] = 'String'; } - if (vpnType == CrOnc.VPNType.OPEN_VPN) { - editFields['VPN.OpenVPN.Username'] = 'String'; - editFields['VPN.OpenVPN.ExtraHosts'] = 'StringArray'; + if (vpnType == mojom.VpnType.kOpenVPN) { + editFields['vpn.openVpn.username'] = 'String'; + editFields['vpn.openVpn.extraHosts'] = 'StringArray'; } } return editFields; @@ -1427,26 +1385,21 @@ Polymer({ * @private */ getAdvancedFields_: function() { - if (!this.networkProperties_) { + if (!this.managedProperties_) { return []; } /** @type {!Array<string>} */ const fields = []; - const type = this.networkProperties_.Type; - if (type != CrOnc.Type.TETHER) { - fields.push('MacAddress'); - } - if (type == CrOnc.Type.CELLULAR && !!this.networkProperties_.Cellular) { + const type = this.managedProperties_.type; + if (type == mojom.NetworkType.kCellular) { fields.push( - 'Cellular.Family', 'Cellular.NetworkTechnology', - 'Cellular.ServingOperator.Code'); - } else if (type == CrOnc.Type.WI_FI) { + 'cellular.family', 'cellular.networkTechnology', + 'cellular.servingOperator.code'); + } else if (type == mojom.NetworkType.kWiFi) { fields.push( - 'WiFi.SSID', 'WiFi.BSSID', 'WiFi.SignalStrength', 'WiFi.Security', - 'WiFi.EAP.Outer', 'WiFi.EAP.Inner', 'WiFi.EAP.SubjectMatch', - 'WiFi.EAP.Identity', 'WiFi.EAP.AnonymousIdentity', 'WiFi.Frequency'); - } else if (type == CrOnc.Type.WI_MAX) { - fields.push('WiFi.SignalStrength'); + 'wifi.ssid', 'wifi.bssid', 'wifi.signalStrength', 'wifi.security', + 'wifi.eap.outer', 'wifi.eap.inner', 'wifi.eap.subjectMatch', + 'wifi.eap.identity', 'wifi.eap.anonymousIdentity', 'wifi.frequency'); } return fields; }, @@ -1456,34 +1409,36 @@ Polymer({ * @private */ getDeviceFields_: function() { - if (!this.networkProperties_ || - this.networkProperties_.Type !== CrOnc.Type.CELLULAR) { + if (!this.managedProperties_ || + this.managedProperties_.type !== mojom.NetworkType.kCellular) { return []; } return [ - 'Cellular.HomeProvider.Name', 'Cellular.HomeProvider.Country', - 'Cellular.HomeProvider.Code', 'Cellular.Manufacturer', 'Cellular.ModelID', - 'Cellular.FirmwareRevision', 'Cellular.HardwareRevision', 'Cellular.ESN', - 'Cellular.ICCID', 'Cellular.IMEI', 'Cellular.IMSI', 'Cellular.MDN', - 'Cellular.MEID', 'Cellular.MIN', 'Cellular.PRLVersion' + 'cellular.homeProvider.name', 'cellular.homeProvider.country', + 'cellular.homeProvider.code', 'cellular.manufacturer', 'cellular.modelId', + 'cellular.firmwareRevision', 'cellular.hardwareRevision', 'cellular.esn', + 'cellular.iccid', 'cellular.imei', 'cellular.imsi', 'cellular.mdn', + 'cellular.meid', 'cellular.min' ]; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties + * @param {boolean} propertiesReceived * @return {boolean} * @private */ - showAdvanced_: function(networkProperties) { - if (!networkProperties || networkProperties.Type == CrOnc.Type.TETHER) { + showAdvanced_: function(managedProperties, propertiesReceived) { + if (!managedProperties || !propertiesReceived) { + return false; + } + if (managedProperties.type == mojom.NetworkType.kTether) { // These settings apply to the underlying WiFi network, not the Tether // network. return false; } - return this.hasAdvancedFields_() || this.hasDeviceFields_() || - (networkProperties.Type != CrOnc.Type.VPN && - this.isRememberedOrConnected_(networkProperties)); + return this.hasAdvancedFields_() || this.hasDeviceFields_(); }, /** @@ -1511,125 +1466,129 @@ Polymer({ }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} * @private */ hasNetworkSection_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - if (!networkProperties || networkProperties.Type == CrOnc.Type.TETHER) { + managedProperties, globalPolicy, managedNetworkAvailable) { + if (!managedProperties || + managedProperties.type == mojom.NetworkType.kTether) { // These settings apply to the underlying WiFi network, not the Tether // network. return false; } if (this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable)) { + managedProperties, globalPolicy, managedNetworkAvailable)) { return false; } - if (networkProperties.Type == CrOnc.Type.CELLULAR) { + if (managedProperties.type == mojom.NetworkType.kCellular) { return true; } - return this.isRememberedOrConnected_(networkProperties); + return this.isRememberedOrConnected_(managedProperties); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.ManagedProperties} managedProperties + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} * @private */ hasProxySection_: function( - networkProperties, globalPolicy, managedNetworkAvailable) { - if (!networkProperties || networkProperties.Type == CrOnc.Type.TETHER) { + managedProperties, globalPolicy, managedNetworkAvailable) { + if (!managedProperties || + managedProperties.type == mojom.NetworkType.kTether) { // Proxy settings apply to the underlying WiFi network, not the Tether // network. return false; } if (this.isBlockedByPolicy_( - networkProperties, globalPolicy, managedNetworkAvailable)) { + managedProperties, globalPolicy, managedNetworkAvailable)) { return false; } - return this.isRememberedOrConnected_(networkProperties); + return this.isRememberedOrConnected_(managedProperties); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showCellularChooseNetwork_: function(networkProperties) { - return !!networkProperties && - networkProperties.Type == CrOnc.Type.CELLULAR && - !!this.get('Cellular.SupportNetworkScan', this.networkProperties_); + showCellularChooseNetwork_: function(managedProperties) { + return !!managedProperties && + managedProperties.type == mojom.NetworkType.kCellular && + managedProperties.cellular.supportNetworkScan; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties * @return {boolean} * @private */ - showScanningSpinner_: function(networkProperties) { - return !!this.get('Cellular.Scanning', networkProperties); + showScanningSpinner_: function() { + if (!this.managedProperties_ || + this.managedProperties_.type != mojom.NetworkType.kCellular) { + return false; + } + return !!this.deviceState_ && this.deviceState_.scanning; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showCellularSim_: function(networkProperties) { - return !!networkProperties && - networkProperties.Type == CrOnc.Type.CELLULAR && - !!networkProperties.Cellular && - networkProperties.Cellular.Family != 'CDMA'; + showCellularSim_: function(managedProperties) { + return !!managedProperties && + managedProperties.type == mojom.NetworkType.kCellular && + managedProperties.cellular.family != 'CDMA'; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties|undefined} managedProperties * @return {boolean} * @private */ - isArcVpn_: function(networkProperties) { - return !!networkProperties && !!networkProperties.VPN && - CrOnc.getActiveValue(networkProperties.VPN.Type) == - CrOnc.VPNType.ARCVPN; + isArcVpn_: function(managedProperties) { + return !!managedProperties && + managedProperties.type == mojom.NetworkType.kVPN && + managedProperties.vpn.type == mojom.VpnType.kArc; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties|undefined} managedProperties * @return {boolean} * @private */ - isThirdPartyVpn_: function(networkProperties) { - return !!networkProperties && !!networkProperties.VPN && - CrOnc.getActiveValue(networkProperties.VPN.Type) == - CrOnc.VPNType.THIRD_PARTY_VPN; + isThirdPartyVpn_: function(managedProperties) { + return !!managedProperties && + managedProperties.type == mojom.NetworkType.kVPN && + managedProperties.vpn.type == mojom.VpnType.kExtension; }, /** * @param {string} ipAddress - * @param {!CrOnc.NetworkProperties} networkProperties + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - showIpAddress_: function(ipAddress, networkProperties) { + showIpAddress_: function(ipAddress, managedProperties) { // Arc Vpn does not currently pass IP configuration to ChromeOS. IP address // property holds an internal IP address Android uses to talk to ChromeOS. // TODO(lgcheng@) Show correct IP address when we implement IP configuration // correctly. - if (this.isArcVpn_(networkProperties)) { + if (this.isArcVpn_(managedProperties)) { return false; } // Cellular IP addresses are shown under the network details section. - if (this.isCellular_(networkProperties)) { + if (this.isCellular_(managedProperties)) { return false; } - return !!ipAddress && this.isConnectedState_(networkProperties); + return !!ipAddress && this.isConnectedState_(managedProperties); }, /** 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 42dcf86aa71..b0d29715c33 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 @@ -5,7 +5,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> -<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html"> +<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior_mojo.html"> <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-internet-known-networks-page"> @@ -36,10 +36,9 @@ <div class="list-item"> <cr-link-row embedded label="[[getNetworkDisplayName_(item)]]" on-click="fireShowDetails_"> - <template is="dom-if" if="[[isPolicySourceMojo(item.source))]]"> + <template is="dom-if" if="[[isPolicySource(item.source))]]"> <cr-policy-indicator on-click="doNothing_" - indicator-type="[[getIndicatorTypeForSourceMojo( - item.source)]]"> + indicator-type="[[getIndicatorTypeForSource(item.source)]]"> </cr-policy-indicator> </template> </cr-link-row> @@ -61,10 +60,9 @@ <div class="list-item"> <cr-link-row embedded label="[[getNetworkDisplayName_(item)]]" on-click="fireShowDetails_"> - <template is="dom-if" if="[[isPolicySourceMojo(item.source))]]"> + <template is="dom-if" if="[[isPolicySource(item.source))]]"> <cr-policy-indicator on-click="doNothing_" - indicator-type="[[getIndicatorTypeForSourceMojo( - item.source)]]"> + indicator-type="[[getIndicatorTypeForSource(item.source)]]"> </cr-policy-indicator> </template> </cr-link-row> diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js index 6d613efeda5..2e42c952c87 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 @@ -12,7 +12,7 @@ Polymer({ behaviors: [ CrNetworkListenerBehavior, - CrPolicyNetworkBehavior, + CrPolicyNetworkBehaviorMojo, ], properties: { @@ -64,15 +64,14 @@ Polymer({ * This UI will use both the networkingPrivate extension API and the * networkConfig mojo API until we provide all of the required functionality * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api. - * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} + * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ - networkConfigProxy_: null, + networkConfig_: null, /** @override */ created: function() { - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** CrosNetworkConfigObserver impl */ @@ -99,7 +98,7 @@ Polymer({ limit: chromeos.networkConfig.mojom.kNoLimit, networkType: OncMojo.getNetworkTypeFromString(this.networkType), }; - this.networkConfigProxy_.getNetworkStateList(filter).then(response => { + this.networkConfig_.getNetworkStateList(filter).then(response => { this.networkStateList_ = response.result; }); }, @@ -147,7 +146,7 @@ Polymer({ * @private */ getNetworkDisplayName_: function(networkState) { - return OncMojo.getNetworkDisplayName(networkState); + return OncMojo.getNetworkStateDisplayName(networkState); }, /** @@ -162,14 +161,15 @@ Polymer({ // We need to make a round trip to Chrome in order to retrieve the managed // properties for the network. The delay is not noticeable (~5ms) and is // preferable to initiating a query for every known network at load time. - this.networkingPrivate.getManagedProperties( - this.selectedGuid_, properties => { - if (chrome.runtime.lastError || !properties) { - console.error( - 'Unexpected error: ' + chrome.runtime.lastError.message); + this.networkConfig_.getManagedProperties(this.selectedGuid_) + .then(response => { + const properties = response.result; + if (!properties) { + console.error('Properties not found for: ' + this.selectedGuid_); return; } - if (this.isNetworkPolicyEnforced(properties.Priority)) { + if (properties.priority && + this.isNetworkPolicyEnforced(properties.priority)) { this.showAddPreferred_ = false; this.showRemovePreferred_ = false; } else { @@ -177,22 +177,37 @@ Polymer({ this.showAddPreferred_ = !preferred; this.showRemovePreferred_ = preferred; } - this.enableForget_ = !this.isPolicySource(properties.Source); + this.enableForget_ = !this.isPolicySource(networkState.source); /** @type {!CrActionMenuElement} */ (this.$.dotsMenu) .showAt(/** @type {!Element} */ (button)); }); event.stopPropagation(); }, + /** + * @param {!chromeos.networkConfig.mojom.ConfigProperties} config + * @private + */ + setProperties_: function(config) { + this.networkConfig_.setProperties(this.selectedGuid_, config) + .then(response => { + if (!response.success) { + console.error( + 'Unable to set properties for: ' + this.selectedGuid_ + ': ' + + JSON.stringify(config)); + } + }); + }, + /** @private */ onRemovePreferredTap_: function() { - this.networkingPrivate.setProperties(this.selectedGuid_, {Priority: 0}); + this.setProperties_({priority: {value: 0}}); /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close(); }, /** @private */ onAddPreferredTap_: function() { - this.networkingPrivate.setProperties(this.selectedGuid_, {Priority: 1}); + this.setProperties_({priority: {value: 1}}); /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close(); }, diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_page.html b/chromium/chrome/browser/resources/settings/internet_page/internet_page.html index 3727b4dad9a..10eeff05b0a 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/internet_page.html +++ b/chromium/chrome/browser/resources/settings/internet_page/internet_page.html @@ -9,6 +9,7 @@ <link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="../i18n_setup.html"> <link rel="import" href="../prefs/prefs.html"> <link rel="import" href="../route.html"> <link rel="import" href="../settings_page/settings_animated_pages.html"> @@ -65,7 +66,7 @@ <cr-icon-button class$="[[getAddNetworkClass_('VPN')]]" aria-label="$i18n{internetAddVPN}"></cr-icon-button> </div> - <template is="dom-repeat" items="[[thirdPartyVpnProviders_]]"> + <template is="dom-repeat" items="[[vpnProviders_]]"> <div actionable class="list-item" on-click="onAddThirdPartyVpnTap_"> <div class="start settings-box-text"> @@ -76,16 +77,6 @@ </cr-icon-button> </div> </template> - <template is="dom-if" if="[[arcVpnProviders_.length]]"> - <div actionable class="list-item" id="addArcVpn" - on-click="onAddArcVpnTap_"> - <div class="setting-box-text"> - $i18n{internetAddArcVPN} - </div> - <cr-icon-button class="icon-external" - aria-label$="$i18n{internetAddArcVPN}"></cr-icon-button> - </div> - </template> </div> </template> </template> @@ -129,8 +120,7 @@ device-state="[[getDeviceState_(subpageType_, deviceStates)]]" tether-device-state="[[getTetherDeviceState_(deviceStates)]]" global-policy="[[globalPolicy_]]" - third-party-vpn-providers="[[thirdPartyVpnProviders_]]" - arc-vpn-providers="[[arcVpnProviders_]]" + vpn-providers="[[vpnProviders_]]" show-spinner="{{showSpinner_}}"> </settings-internet-subpage> </settings-subpage> diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_page.js index bb18ded6ab7..1737c822b40 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/internet_page.js +++ b/chromium/chrome/browser/resources/settings/internet_page/internet_page.js @@ -15,6 +15,7 @@ Polymer({ is: 'settings-internet-page', behaviors: [ + CrNetworkListenerBehavior, I18nBehavior, settings.RouteObserverBehavior, WebUIListenerBehavior, @@ -84,11 +85,8 @@ Polymer({ value: false, }, - /** @private {!chrome.networkingPrivate.GlobalPolicy|undefined} */ - globalPolicy_: { - type: Object, - value: null, - }, + /** @private {!chromeos.networkConfig.mojom.GlobalPolicy|undefined} */ + globalPolicy_: Object, /** * Whether a managed network is available in the visible network list. @@ -100,23 +98,11 @@ Polymer({ }, /** - * List of third party VPN providers. - * @type {!Array<!chrome.networkingPrivate.ThirdPartyVPNProperties>} - * @private - */ - thirdPartyVpnProviders_: { - type: Array, - value: function() { - return []; - } - }, - - /** - * List of Arc VPN providers. - * @type {!Array<!settings.ArcVpnProvider>} + * List of third party (Extension + Arc) VPN providers. + * @type {!Array<!chromeos.networkConfig.mojom.VpnProvider>} * @private */ - arcVpnProviders_: { + vpnProviders_: { type: Array, value: function() { return []; @@ -145,16 +131,6 @@ Polymer({ 'show-networks': 'onShowNetworks_', }, - // chrome.management listeners - /** @private {Function} */ - onExtensionAddedListener_: null, - - /** @private {Function} */ - onExtensionRemovedListener_: null, - - /** @private {Function} */ - onExtensionDisabledListener_: null, - /** @private {?settings.InternetPageBrowserProxy} */ browserProxy_: null, @@ -162,58 +138,23 @@ Polymer({ * This UI will use both the networkingPrivate extension API and the * networkConfig mojo API until we provide all of the required functionality * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api. - * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} + * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ - networkConfigProxy_: null, + networkConfig_: null, /** @override */ created: function() { this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); - }, - - /** @override */ - ready: function() { - this.browserProxy_.setUpdateArcVpnProvidersCallback( - this.onArcVpnProvidersReceived_.bind(this)); - this.browserProxy_.requestArcVpnProviders(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** @override */ attached: function() { - this.onExtensionAddedListener_ = - this.onExtensionAddedListener_ || this.onExtensionAdded_.bind(this); - chrome.management.onInstalled.addListener(this.onExtensionAddedListener_); - chrome.management.onEnabled.addListener(this.onExtensionAddedListener_); - - this.onExtensionRemovedListener_ = - this.onExtensionRemovedListener_ || this.onExtensionRemoved_.bind(this); - chrome.management.onUninstalled.addListener( - this.onExtensionRemovedListener_); - - this.onExtensionDisabledListener_ = this.onExtensionDisabledListener_ || - this.onExtensionDisabled_.bind(this); - chrome.management.onDisabled.addListener(this.onExtensionDisabledListener_); - - chrome.management.getAll(this.onGetAllExtensions_.bind(this)); - - this.networkingPrivate.getGlobalPolicy(policy => { - this.globalPolicy_ = policy; + this.networkConfig_.getGlobalPolicy().then(response => { + this.globalPolicy_ = response.result; }); - }, - - /** @override */ - detached: function() { - chrome.management.onInstalled.removeListener( - assert(this.onExtensionAddedListener_)); - chrome.management.onEnabled.removeListener( - assert(this.onExtensionAddedListener_)); - chrome.management.onUninstalled.removeListener( - assert(this.onExtensionRemovedListener_)); - chrome.management.onDisabled.removeListener( - assert(this.onExtensionDisabledListener_)); + this.onVpnProvidersChanged(); }, /** @@ -278,6 +219,15 @@ Polymer({ } }, + /** CrosNetworkConfigObserver impl */ + onVpnProvidersChanged: function() { + this.networkConfig_.getVpnProviders().then(response => { + const providers = response.providers; + providers.sort(this.compareVpnProviders_); + this.vpnProviders_ = providers; + }); + }, + /** * Event triggered by a device state enabled toggle. * @param {!CustomEvent<!{ @@ -287,7 +237,7 @@ Polymer({ * @private */ onDeviceEnabledToggled_: function(event) { - this.networkConfigProxy_.setNetworkTypeEnabledState( + this.networkConfig_.setNetworkTypeEnabledState( event.detail.type, event.detail.enabled); }, @@ -336,7 +286,7 @@ Polymer({ const params = new URLSearchParams; params.append('guid', networkState.guid); params.append('type', oncType); - params.append('name', OncMojo.getNetworkDisplayName(networkState)); + params.append('name', OncMojo.getNetworkStateDisplayName(networkState)); settings.navigateTo(settings.routes.NETWORK_DETAIL, params); }, @@ -454,19 +404,12 @@ Polymer({ }, /** - * @param {!{model: - * !{item: !chrome.networkingPrivate.ThirdPartyVPNProperties}, - * }} event + * @param {!{model: !{item: !mojom.VpnProvider}}} event * @private */ onAddThirdPartyVpnTap_: function(event) { const provider = event.model.item; - this.browserProxy_.addThirdPartyVpn(provider.ExtensionID); - }, - - /** @private */ - onAddArcVpnTap_: function() { - this.showNetworksSubpage_(mojom.NetworkType.kVPN); + this.browserProxy_.addThirdPartyVpn(provider.appId); }, /** @@ -483,101 +426,31 @@ Polymer({ }, /** - * chrome.management.getAll callback. - * @param {!Array<!chrome.management.ExtensionInfo>} extensions - * @private + * @param {!mojom.VpnProvider} vpnProvider1 + * @param {!mojom.VpnProvider} vpnProvider2 + * @return {number} */ - onGetAllExtensions_: function(extensions) { - const vpnProviders = []; - for (let i = 0; i < extensions.length; ++i) { - this.addVpnProvider_(vpnProviders, extensions[i]); - } - this.thirdPartyVpnProviders_ = vpnProviders; - }, - - /** - * If |extension| is a third-party VPN provider, add it to |vpnProviders|. - * @param {!Array<!chrome.networkingPrivate.ThirdPartyVPNProperties>} - * vpnProviders - * @param {!chrome.management.ExtensionInfo} extension - * @private - */ - addVpnProvider_: function(vpnProviders, extension) { - if (!extension.enabled || - extension.permissions.indexOf('vpnProvider') == -1) { - return; - } - if (vpnProviders.find(function(provider) { - return provider.ExtensionID == extension.id; - })) { - return; + compareVpnProviders_: function(vpnProvider1, vpnProvider2) { + // Show Extension VPNs before Arc VPNs. + if (vpnProvider1.type < vpnProvider2.type) { + return -1; } - const newProvider = { - ExtensionID: extension.id, - ProviderName: extension.name, - }; - vpnProviders.push(newProvider); - }, - - /** - * chrome.management.onInstalled or onEnabled event. - * @param {!chrome.management.ExtensionInfo} extension - * @private - */ - onExtensionAdded_: function(extension) { - this.addVpnProvider_(this.thirdPartyVpnProviders_, extension); - }, - - /** - * chrome.management.onUninstalled event. - * @param {string} extensionId - * @private - */ - onExtensionRemoved_: function(extensionId) { - for (let i = 0; i < this.thirdPartyVpnProviders_.length; ++i) { - const provider = this.thirdPartyVpnProviders_[i]; - if (provider.ExtensionID == extensionId) { - this.splice('thirdPartyVpnProviders_', i, 1); - break; - } + if (vpnProvider1.type > vpnProvider2.type) { + return 1; } - }, - - /** - * Compares Arc VPN Providers based on LastlauchTime - * @param {!settings.ArcVpnProvider} arcVpnProvider1 - * @param {!settings.ArcVpnProvider} arcVpnProvider2 - * @private - */ - compareArcVpnProviders_: function(arcVpnProvider1, arcVpnProvider2) { - if (arcVpnProvider1.LastLaunchTime > arcVpnProvider2.LastLaunchTime) { + // Show VPNs of the same type by lastLaunchTime. + if (vpnProvider1.lastLaunchTime.internalValue > + vpnProvider2.lastLaunchTime.internalValue) { return -1; } - if (arcVpnProvider1.LastLaunchTime < arcVpnProvider2.LastLaunchTime) { + if (vpnProvider1.lastLaunchTime.internalValue < + vpnProvider2.lastLaunchTime.internalValue) { return 1; } return 0; }, /** - * @param {?Array<!settings.ArcVpnProvider>} arcVpnProviders - * @private - */ - onArcVpnProvidersReceived_: function(arcVpnProviders) { - arcVpnProviders.sort(this.compareArcVpnProviders_); - this.arcVpnProviders_ = arcVpnProviders; - }, - - /** - * chrome.management.onDisabled event. - * @param {{id: string}} extension - * @private - */ - onExtensionDisabled_: function(extension) { - this.onExtensionRemoved_(extension.id); - }, - - /** * @param {!Array<!OncMojo.DeviceStateProperties>} deviceStates * @param {string} type * @return {boolean} @@ -591,7 +464,7 @@ Polymer({ }, /** - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.GlobalPolicy} globalPolicy * @param {boolean} managedNetworkAvailable * @return {boolean} */ @@ -600,17 +473,17 @@ Polymer({ return true; } - return !globalPolicy.AllowOnlyPolicyNetworksToConnect && - (!globalPolicy.AllowOnlyPolicyNetworksToConnectIfAvailable || + return !globalPolicy.allowOnlyPolicyNetworksToConnect && + (!globalPolicy.allowOnlyPolicyNetworksToConnectIfAvailable || !managedNetworkAvailable); }, /** - * @param {!chrome.networkingPrivate.ThirdPartyVPNProperties} provider + * @param {!mojom.VpnProvider} provider * @return {string} */ getAddThirdPartyVpnLabel_: function(provider) { - return this.i18n('internetAddThirdPartyVPN', provider.ProviderName || ''); + return this.i18n('internetAddThirdPartyVPN', provider.providerName || ''); }, /** @@ -625,7 +498,7 @@ Polymer({ onNetworkConnect_: function(event) { const networkState = event.detail.networkState; const oncType = OncMojo.getNetworkTypeString(networkState.type); - const displayName = OncMojo.getNetworkDisplayName(networkState); + const displayName = OncMojo.getNetworkStateDisplayName(networkState); if (!event.detail.bypassConnectionDialog && networkState.type == mojom.NetworkType.kTether && @@ -647,24 +520,32 @@ Polymer({ return; } - this.networkingPrivate.startConnect(networkState.guid, () => { - if (chrome.runtime.lastError) { - const message = chrome.runtime.lastError.message; - if (message == 'connecting' || message == 'connect-canceled' || - message == 'connected' || message == 'Error.InvalidNetworkGuid') { + this.networkConfig_.startConnect(networkState.guid).then(response => { + switch (response.result) { + case mojom.StartConnectResult.kSuccess: + return; + case mojom.StartConnectResult.kInvalidGuid: + case mojom.StartConnectResult.kInvalidState: + case mojom.StartConnectResult.kCanceled: + // TODO(stevenjb/khorimoto): Consider handling these cases. + return; + case mojom.StartConnectResult.kNotConfigured: + if (!isMobile) { + this.showConfig_( + true /* configAndConnect */, oncType, networkState.guid, + displayName); + } + return; + case mojom.StartConnectResult.kBlocked: + // This shouldn't happen, the UI should prevent this, fall through and + // show the error. + case mojom.StartConnectResult.kUnknown: + console.error( + 'startConnect failed for: ' + networkState.guid + + ' Error: ' + response.message); return; - } - console.error( - 'networkingPrivate.startConnect error: ' + message + - ' For: ' + networkState.guid); - - // There is no configuration flow for Mobile Networks. - if (!isMobile) { - this.showConfig_( - true /* configAndConnect */, oncType, networkState.guid, - displayName); - } } + assertNotReached(); }); }, }); diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js b/chromium/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js index 42473ab988b..f39bf9141c8 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js +++ b/chromium/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js @@ -5,20 +5,16 @@ /** @fileoverview A helper object used for Internet page. */ cr.exportPath('settings'); -/** - * @typedef {{ - * PackageName: string, - * ProviderName: string, - * AppID: string, - * LastLaunchTime: number, - * }} - */ -settings.ArcVpnProvider; - cr.define('settings', function() { /** @interface */ class InternetPageBrowserProxy { /** + * Shows the Cellular activation UI. + * @param {string} guid + */ + showCellularSetupUI(guid) {} + + /** * Shows configuration for external VPNs. Includes ThirdParty (extension * configured) VPNs, and Arc VPNs. * @param {string} guid @@ -33,18 +29,6 @@ cr.define('settings', function() { addThirdPartyVpn(appId) {} /** - * Requests Chrome to send list of Arc VPN providers. - */ - requestArcVpnProviders() {} - - /** - * |callback| is run when there is update of Arc VPN providers. - * Available after |requestArcVpnProviders| has been called. - * @param {function(?Array<settings.ArcVpnProvider>):void} callback - */ - setUpdateArcVpnProvidersCallback(callback) {} - - /** * Requests that Chrome send the list of devices whose "Google Play * Services" notifications are disabled (these notifications must be enabled * to utilize Instant Tethering). The names will be provided via @@ -67,6 +51,11 @@ cr.define('settings', function() { */ class InternetPageBrowserProxyImpl { /** @override */ + showCellularSetupUI(guid) { + chrome.send('showCellularSetupUI', [guid]); + } + + /** @override */ configureThirdPartyVpn(guid) { chrome.send('configureThirdPartyVpn', [guid]); } @@ -77,16 +66,6 @@ cr.define('settings', function() { } /** @override */ - requestArcVpnProviders() { - chrome.send('requestArcVpnProviders'); - } - - /** @override */ - setUpdateArcVpnProvidersCallback(callback) { - cr.addWebUIListener('sendArcVpnProviders', callback); - } - - /** @override */ requestGmsCoreNotificationsDisabledDeviceNames() { chrome.send('requestGmsCoreNotificationsDisabledDeviceNames'); } 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 3516ce9f4de..3307caa6c8e 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html +++ b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html @@ -5,12 +5,15 @@ <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> +<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior_mojo.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> <link rel="import" href="internet_page_browser_proxy.html"> +<link rel="import" href="../i18n_setup.html"> +<link rel="import" href="../route.html"> <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-internet-subpage"> @@ -154,16 +157,17 @@ <!-- Text shown if no networks exist. --> <div hidden="[[shouldShowNetworkList_(networkStateList_)]]" inner-h-t-m-l= - "[[getNoNetworksString_(deviceState, tetherDeviceState)]]" + "[[getNoNetworksInnerHtml_(deviceState, tetherDeviceState)]]" class="no-networks"> </div> <template is="dom-if" if="[[matchesType_('VPN', deviceState)]]"> <!-- Third party VPNs. --> - <template is="dom-repeat" items="[[thirdPartyVpnProviders]]"> - <div id="[[item.ProviderName]]" + <template is="dom-repeat" + items="[[getVpnProviders_(vpnProviders, thirdPartyVpns_)]]"> + <div id="[[item.providerName]]" class="vpn-header layout horizontal center"> - <div class="flex settings-box-text">[[item.ProviderName]]</div> + <div class="flex settings-box-text">[[item.providerName]]</div> <cr-icon-button class="icon-add-circle" aria-label$="[[getAddThirdPartyVpnA11yString_(item)]]" on-click="onAddThirdPartyVpnTap_" tabindex$="[[tabindex]]"> @@ -179,26 +183,6 @@ $i18n{internetNoNetworks} </div> </template> - <!-- Arc VPNs. --> - <template is="dom-repeat" items="[[arcVpnProviders]]"> - <div id="[[item.ProviderName]]" - class="vpn-header layout horizontal center"> - <div class="flex settings-box-text">[[item.ProviderName]]</div> - <cr-icon-button class="icon-add-circle" - aria-label$="[[getAddArcVpnAllyString_(item)]]" - on-click="onAddArcVpnTap_" tabindex$="[[tabindex]]"> - </cr-icon-button> - </div> - <cr-network-list show-buttons - hidden$="[[!haveArcVpnNetwork_(arcVpns_, item)]]" - networks="[[getArcVpnNetworks_(arcVpns_, item)]]" - on-selected="onNetworkSelected_"> - </cr-network-list> - <div hidden$="[[haveArcVpnNetwork_(arcVpns_, item)]]" - class="no-networks"> - $i18n{internetNoNetworks} - </div> - </template> </template> </div> 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 0b5b7863c2f..9996d3b6538 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js +++ b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js @@ -4,7 +4,7 @@ /** * @fileoverview Polymer element for displaying information about WiFi, - * WiMAX, or virtual networks. + * Cellular, or virtual networks. */ (function() { @@ -16,7 +16,7 @@ Polymer({ behaviors: [ CrNetworkListenerBehavior, - CrPolicyNetworkBehavior, + CrPolicyNetworkBehaviorMojo, settings.RouteObserverBehavior, I18nBehavior, ], @@ -44,21 +44,14 @@ Polymer({ */ tetherDeviceState: Object, - /** @type {!chrome.networkingPrivate.GlobalPolicy|undefined} */ + /** @type {!chromeos.networkConfig.mojom.GlobalPolicy|undefined} */ globalPolicy: Object, /** - * List of third party VPN providers. - * @type - * {!Array<!chrome.networkingPrivate.ThirdPartyVPNProperties>|undefined} + * List of third party (Extension + Arc) VPN providers. + * @type {!Array<!chromeos.networkConfig.mojom.VpnProvider>} */ - thirdPartyVpnProviders: Array, - - /** - * List of Arc VPN providers. - * @type {!Array<!settings.ArcVpnProvider>|undefined} - */ - arcVpnProviders: Array, + vpnProviders: Array, showSpinner: { type: Boolean, @@ -89,17 +82,6 @@ Polymer({ }, /** - * Dictionary of lists of network states for Arc VPNs. - * @private {!Object<!Array<!OncMojo.NetworkStateProperties>>} - */ - arcVpns_: { - type: Object, - value: function() { - return {}; - } - }, - - /** * List of potential Tether hosts whose "Google Play Services" notifications * are disabled (these notifications are required to use Instant Tethering). * @private {!Array<string>} @@ -122,6 +104,12 @@ Polymer({ loadTimeData.getBoolean('showTechnologyBadge'); } }, + + /** @private */ + hasCompletedScanSinceLastEnabled_: { + type: Boolean, + value: false, + }, }, observers: ['deviceStateChanged_(deviceState)'], @@ -136,16 +124,15 @@ Polymer({ * This UI will use both the networkingPrivate extension API and the * networkConfig mojo API until we provide all of the required functionality * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api. - * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} + * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ - networkConfigProxy_: null, + networkConfig_: null, /** @override */ created: function() { this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** @override */ @@ -170,32 +157,52 @@ Polymer({ this.stopScanning_(); return; } + this.init(); + }, + + init: function() { // Clear any stale data. this.networkStateList_ = []; this.thirdPartyVpns_ = {}; - this.arcVpns_ = {}; + this.hasCompletedScanSinceLastEnabled_ = false; + this.showSpinner = false; + // Request the list of networks and start scanning if necessary. this.getNetworkStateList_(); this.updateScanning_(); }, /** - * CrosNetworkConfigObserver impl + * CrNetworkListenerBehavior override * @param {!Array<OncMojo.NetworkStateProperties>} networks */ onActiveNetworksChanged: function(networks) { this.getNetworkStateList_(); }, - /** CrosNetworkConfigObserver impl */ + /** CrNetworkListenerBehavior override */ onNetworkStateListChanged: function() { this.getNetworkStateList_(); }, + /** CrNetworkListenerBehavior override */ + onVpnProvidersChanged: function() { + if (this.deviceState.type != mojom.NetworkType.kVPN) { + return; + } + this.getNetworkStateList_(); + }, + /** @private */ deviceStateChanged_: function() { - this.showSpinner = - this.deviceState !== undefined && !!this.deviceState.scanning; + if (this.deviceState !== undefined) { + // A scan has completed if the spinner was active (i.e., scanning was + // active) and the device is no longer scanning. + this.hasCompletedScanSinceLastEnabled_ = this.showSpinner && + !this.deviceState.scanning && + this.deviceState.deviceState == mojom.DeviceStateType.kEnabled; + this.showSpinner = !!this.deviceState.scanning; + } // Scans should only be triggered by the "networks" subpage. if (settings.getCurrentRoute() != settings.routes.INTERNET_NETWORKS) { @@ -246,9 +253,9 @@ Polymer({ return; } const INTERVAL_MS = 10 * 1000; - this.networkConfigProxy_.requestNetworkScan(this.deviceState.type); + this.networkConfig_.requestNetworkScan(this.deviceState.type); this.scanIntervalId_ = window.setInterval(() => { - this.networkConfigProxy_.requestNetworkScan(this.deviceState.type); + this.networkConfig_.requestNetworkScan(this.deviceState.type); }, INTERVAL_MS); }, @@ -271,7 +278,7 @@ Polymer({ limit: chromeos.networkConfig.mojom.kNoLimit, networkType: this.deviceState.type, }; - this.networkConfigProxy_.getNetworkStateList(filter).then(response => { + this.networkConfig_.getNetworkStateList(filter).then(response => { this.onGetNetworks_(response.result); }); }, @@ -294,48 +301,84 @@ Polymer({ limit: chromeos.networkConfig.mojom.kNoLimit, networkType: mojom.NetworkType.kTether, }; - this.networkConfigProxy_.getNetworkStateList(filter).then(response => { + this.networkConfig_.getNetworkStateList(filter).then(response => { const tetherNetworkStates = response.result; this.networkStateList_ = networkStates.concat(tetherNetworkStates); }); return; } - // For VPNs, separate out third party VPNs and Arc VPNs. + // For VPNs, separate out third party (Extension + Arc) VPNs. if (this.deviceState.type == mojom.NetworkType.kVPN) { const builtinNetworkStates = []; const thirdPartyVpns = {}; - const arcVpns = {}; networkStates.forEach(state => { assert(state.type == mojom.NetworkType.kVPN); switch (state.vpn.type) { - case mojom.VPNType.kL2TPIPsec: - case mojom.VPNType.kOpenVPN: + case mojom.VpnType.kL2TPIPsec: + case mojom.VpnType.kOpenVPN: builtinNetworkStates.push(state); break; - case mojom.VPNType.kThirdPartyVPN: - const providerName = state.vpn.providerName; - thirdPartyVpns[providerName] = thirdPartyVpns[providerName] || []; - thirdPartyVpns[providerName].push(state); - break; - case mojom.VPNType.kArcVPN: - const arcProviderName = this.get('VPN.Host', state); - if (OncMojo.connectionStateIsConnected(state.connectionState)) { - arcVpns[arcProviderName] = arcVpns[arcProviderName] || []; - arcVpns[arcProviderName].push(state); + case mojom.VpnType.kArc: + // Only show connected Arc VPNs. + if (!OncMojo.connectionStateIsConnected(state.connectionState)) { + break; } + // Otherwise Arc VPNs are treated the same as Extension VPNs. + case mojom.VpnType.kExtension: + const providerId = state.vpn.providerId; + thirdPartyVpns[providerId] = thirdPartyVpns[providerId] || []; + thirdPartyVpns[providerId].push(state); break; } }); networkStates = builtinNetworkStates; this.thirdPartyVpns_ = thirdPartyVpns; - this.arcVpns_ = arcVpns; } this.networkStateList_ = networkStates; }, /** + * Returns an ordered list of VPN providers for all third party VPNs and any + * other known providers. + * @param {!Array<!chromeos.networkConfig.mojom.VpnProvider>} vpnProviders + * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} thirdPartyVpns + * @return {!Array<!chromeos.networkConfig.mojom.VpnProvider>} + * @private + */ + getVpnProviders_(vpnProviders, thirdPartyVpns) { + // First add providers for configured thirdPartyVpns. This list will + // generally be empty or small. + const configuredProviders = []; + for (const vpnList of Object.values(thirdPartyVpns)) { + assert(vpnList.length > 0); + // All vpns in the list will have the same type and provider id. + const vpn = vpnList[0].vpn; + const provider = { + type: vpn.type, + providerId: vpn.providerId, + providerName: vpn.providerName || vpn.providerId, + appId: '', + lastLaunchTime: {internalValue: 0} + }; + configuredProviders.push(provider); + } + // Next update or append known third party providers. + const unconfiguredProviders = []; + for (const provider of vpnProviders) { + const idx = configuredProviders.findIndex( + p => p.providerId == provider.providerId); + if (idx >= 0) { + configuredProviders[idx] = provider; + } else { + unconfiguredProviders.push(provider); + } + } + return configuredProviders.concat(unconfiguredProviders); + }, + + /** * @param {!Array<string>} notificationsDisabledDeviceNames * @private */ @@ -402,43 +445,32 @@ Polymer({ return this.i18n('internetToggleMobileA11yLabel'); case mojom.NetworkType.kWiFi: return this.i18n('internetToggleWiFiA11yLabel'); - case mojom.NetworkType.kWiMAX: - return this.i18n('internetToggleWiMAXA11yLabel'); } assertNotReached(); return ''; }, /** - * @param {!chrome.networkingPrivate.ThirdPartyVPNProperties} vpnState - * @return {string} - * @private - */ - getAddThirdPartyVpnA11yString_: function(vpnState) { - return this.i18n('internetAddThirdPartyVPN', vpnState.ProviderName || ''); - }, - - /** - * @param {!settings.ArcVpnProvider} arcVpn + * @param {!mojom.VpnProvider} provider * @return {string} * @private */ - getAddArcVpnAllyString_: function(arcVpn) { - return this.i18n('internetAddArcVPNProvider', arcVpn.ProviderName); + getAddThirdPartyVpnA11yString_: function(provider) { + return this.i18n('internetAddThirdPartyVPN', provider.providerName || ''); }, /** - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.GlobalPolicy} globalPolicy * @return {boolean} * @private */ allowAddConnection_: function(globalPolicy) { - return globalPolicy && !globalPolicy.AllowOnlyPolicyNetworksToConnect; + return globalPolicy && !globalPolicy.allowOnlyPolicyNetworksToConnect; }, /** * @param {!OncMojo.DeviceStateProperties|undefined} deviceState - * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy + * @param {!mojom.GlobalPolicy} globalPolicy * @return {boolean} * @private */ @@ -461,22 +493,12 @@ Polymer({ }, /** - * @param {!{model: !{item: - * !chrome.networkingPrivate.ThirdPartyVPNProperties}}} event + * @param {!{model: !{item: !mojom.VpnProvider}}} event * @private */ onAddThirdPartyVpnTap_: function(event) { const provider = event.model.item; - this.browserProxy_.addThirdPartyVpn(provider.ExtensionID); - }, - - /** - * @param {!{model: !{item: !settings.ArcVpnProvider}}} event - * @private - */ - onAddArcVpnTap_: function(event) { - const provider = event.model.item; - this.browserProxy_.addThirdPartyVpn(provider.AppID); + this.browserProxy_.addThirdPartyVpn(provider.appId); }, /** @@ -512,43 +534,22 @@ Polymer({ /** * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} thirdPartyVpns - * @param {!chrome.networkingPrivate.ThirdPartyVPNProperties} vpnState + * @param {!mojom.VpnProvider} provider * @return {!Array<!OncMojo.NetworkStateProperties>} * @private */ - getThirdPartyVpnNetworks_: function(thirdPartyVpns, vpnState) { - return thirdPartyVpns[vpnState.ProviderName] || []; + getThirdPartyVpnNetworks_: function(thirdPartyVpns, provider) { + return thirdPartyVpns[provider.providerId] || []; }, /** * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} thirdPartyVpns - * @param {!chrome.networkingPrivate.ThirdPartyVPNProperties} vpnState + * @param {!mojom.VpnProvider} provider * @return {boolean} * @private */ - haveThirdPartyVpnNetwork_: function(thirdPartyVpns, vpnState) { - const list = this.getThirdPartyVpnNetworks_(thirdPartyVpns, vpnState); - return !!list.length; - }, - - /** - * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} arcVpns - * @param {!settings.ArcVpnProvider} arcVpnProvider - * @return {!Array<!OncMojo.NetworkStateProperties>} - * @private - */ - getArcVpnNetworks_: function(arcVpns, arcVpnProvider) { - return arcVpns[arcVpnProvider.PackageName] || []; - }, - - /** - * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} arcVpns - * @param {!settings.ArcVpnProvider} arcVpnProvider - * @return {boolean} - * @private - */ - haveArcVpnNetwork_: function(arcVpns, arcVpnProvider) { - const list = this.getArcVpnNetworks_(arcVpns, arcVpnProvider); + haveThirdPartyVpnNetwork_: function(thirdPartyVpns, provider) { + const list = this.getThirdPartyVpnNetworks_(thirdPartyVpns, provider); return !!list.length; }, @@ -562,7 +563,7 @@ Polymer({ assert(this.defaultNetwork !== undefined); const networkState = e.detail; e.target.blur(); - if (this.canConnect_(networkState)) { + if (this.canAttemptConnection_(networkState)) { this.fire('network-connect', {networkState: networkState}); return; } @@ -576,22 +577,24 @@ Polymer({ */ isBlockedByPolicy_: function(state) { if (state.type != mojom.NetworkType.kWiFi || - this.isPolicySourceMojo(state.source) || !this.globalPolicy) { + this.isPolicySource(state.source) || !this.globalPolicy) { return false; } - return !!this.globalPolicy.AllowOnlyPolicyNetworksToConnect || - (!!this.globalPolicy.AllowOnlyPolicyNetworksToConnectIfAvailable && + return !!this.globalPolicy.allowOnlyPolicyNetworksToConnect || + (!!this.globalPolicy.allowOnlyPolicyNetworksToConnectIfAvailable && !!this.deviceState && !!this.deviceState.managedNetworkAvailable) || - (!!this.globalPolicy.BlacklistedHexSSIDs && - this.globalPolicy.BlacklistedHexSSIDs.includes(state.wifi.hexSsid)); + (!!this.globalPolicy.blockedHexSsids && + this.globalPolicy.blockedHexSsids.includes(state.wifi.hexSsid)); }, /** - * Determines whether or not a network state can be connected to. + * Determines whether or not it is possible to attempt a connection to the + * provided network (e.g., whether it's possible to connect or configure the + * network for connection). * @param {!OncMojo.NetworkStateProperties} state The network state. * @private */ - canConnect_: function(state) { + canAttemptConnection_: function(state) { if (state.connectionState != mojom.ConnectionStateType.kNotConnected) { return false; } @@ -604,6 +607,11 @@ Polymer({ this.defaultNetwork.connectionState))) { return false; } + // Cellular networks do not have a configuration flow, so it's not possible + // to attempt a connection if the network is not conncetable. + if (state.type == mojom.NetworkType.kCellular && !state.connectable) { + return false; + } return true; }, @@ -669,14 +677,27 @@ Polymer({ * @return {string} * @private */ - getNoNetworksString_: function(deviceState, tetherDeviceState) { + getNoNetworksInnerHtml_: function(deviceState, tetherDeviceState) { const type = deviceState.type; if (type == mojom.NetworkType.kTether || (type == mojom.NetworkType.kCellular && this.tetherDeviceState)) { return this.i18nAdvanced('internetNoNetworksMobileData'); } - return this.i18n('internetNoNetworks'); + if (type == mojom.NetworkType.kVPN) { + return this.i18n('internetNoNetworks'); + } + + // If a scan has not yet completed since the device was last enabled, it may + // be the case that scan results are still in the process of arriving, so + // display a message stating that scanning is in progress. If a scan has + // already completed and there are still no networks present, this implies + // that there has been sufficient time to find a network, so display a + // messages stating that there are no networks. See https://crbug.com/974169 + // for more details. + return this.hasCompletedScanSinceLastEnabled_ ? + this.i18n('internetNoNetworks') : + this.i18n('networkScanningLabel'); }, /** diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html index c1e7309b691..a061a6e92ab 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html +++ b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html @@ -5,8 +5,8 @@ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> -<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html"> -<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_indicator.html"> +<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior_mojo.html"> +<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_indicator_mojo.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"> @@ -22,7 +22,7 @@ <template> <style include="internet-shared cr-hidden-style iron-flex iron-flex-alignment"> - cr-policy-network-indicator { + cr-policy-network-indicator-mojo { margin-inline-end: 10px; } @@ -38,19 +38,19 @@ <!-- Policy indicator. Only one dom-if below will be shown. --> <template is="dom-if" - if="[[shouldShowNetworkPolicyIndicator_(networkProperties)]]"> + if="[[shouldShowNetworkPolicyIndicator_(managedProperties)]]"> <div class="settings-box"> <div class="layout horizontal center"> - <cr-policy-network-indicator - property="[[networkProperties.ProxySettings.Type]]" + <cr-policy-network-indicator-mojo + property="[[managedProperties.proxySettings.type]]" no-extension-indicator> - </cr-policy-network-indicator> + </cr-policy-network-indicator-mojo> <div>$i18n{networkProxyEnforcedPolicy}</div> </div> </div> </template> <template is="dom-if" - if="[[shouldShowExtensionIndicator_(networkProperties)]]"> + if="[[shouldShowExtensionIndicator_(managedProperties)]]"> <div class="settings-box"> <extension-controlled-indicator extension-id="[[prefs.proxy.extensionId]]" @@ -62,8 +62,7 @@ <!-- Allow shared proxies --> <settings-toggle-button id="allowShared" class="continuation indented" - hidden$="[[!shouldShowAllowShared_( - networkProperties.ProxySettings.Type)]]" + hidden$="[[!shouldShowAllowShared_(managedProperties.source)]]" pref="{{prefs.settings.use_shared_proxies}}" label="$i18n{networkProxyAllowShared}" on-settings-boolean-control-change="onAllowSharedProxiesChange_" @@ -72,7 +71,7 @@ <div class="settings-box single-column stretch continuation indented"> <network-proxy editable - network-properties="[[networkProperties]]" + managed-properties="[[managedProperties]]" use-shared-proxies="[[useSharedProxies_]]"> </network-proxy> </div> 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 index ce61e4f85c9..3827c8cbf37 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.js +++ b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.js @@ -7,23 +7,24 @@ * detail page. This element is responsible for setting 'Allow proxies for * shared networks'. */ +(function() { +'use strict'; + +const mojom = chromeos.networkConfig.mojom; + Polymer({ is: 'network-proxy-section', behaviors: [ - CrPolicyNetworkBehavior, + CrPolicyNetworkBehaviorMojo, I18nBehavior, PrefsBehavior, settings.RouteObserverBehavior, ], properties: { - /** - * The network properties dictionary containing the proxy properties to - * display and modify. - * @type {!CrOnc.NetworkProperties|undefined} - */ - networkProperties: Object, + /** @private {!chromeos.networkConfig.mojom.ManagedProperties|undefined} */ + managedProperties: Object, /** * Reflects prefs.settings.use_shared_proxies for data binding. @@ -54,17 +55,17 @@ Polymer({ * @private */ isShared_: function() { - return this.networkProperties.Source == 'Device' || - this.networkProperties.Source == 'DevicePolicy'; + return this.managedProperties.source == mojom.OncSource.kDevice || + this.managedProperties.source == mojom.OncSource.kDevicePolicy; }, /** - * @return {!CrOnc.ManagedProperty|undefined} + * @return {!OncMojo.ManagedProperty|undefined} * @private */ getProxySettingsTypeProperty_: function() { - return /** @type {!CrOnc.ManagedProperty|undefined} */ ( - this.get('ProxySettings.Type', this.networkProperties)); + return /** @type {!OncMojo.ManagedProperty|undefined} */ ( + this.get('proxySettings.type', this.managedProperties)); }, /** @@ -98,7 +99,7 @@ Polymer({ }, /** - * @param {!CrOnc.ManagedProperty} property + * @param {!OncMojo.ManagedProperty} property * @return {boolean} * @private */ @@ -148,3 +149,4 @@ Polymer({ this.$.allowShared.focus(); }, }); +})(); diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary.html b/chromium/chrome/browser/resources/settings/internet_page/network_summary.html index 1dfcd0bccaf..2ceba972978 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/network_summary.html +++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary.html @@ -1,7 +1,6 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html"> -<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html"> <link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html"> <link rel="import" href="network_summary_item.html"> 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 70b08bde47c..ac6a45c2d31 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/network_summary.js +++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary.js @@ -4,7 +4,7 @@ /** * @fileoverview Polymer element for displaying a summary of network states - * by type: Ethernet, WiFi, Cellular, WiMAX, and VPN. + * by type: Ethernet, WiFi, Cellular, and VPN. */ (function() { @@ -16,7 +16,6 @@ Polymer({ behaviors: [ CrNetworkListenerBehavior, - CrPolicyNetworkBehavior, ], properties: { @@ -76,8 +75,8 @@ Polymer({ }, }, - /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */ - networkConfigProxy_: null, + /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ + networkConfig_: null, /** * Set of GUIDs identifying active networks, one for each type. @@ -87,9 +86,8 @@ Polymer({ /** @override */ created: function() { - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** @override */ @@ -135,7 +133,7 @@ Polymer({ */ getNetworkLists_: function() { // First get the device states. - this.networkConfigProxy_.getDeviceStateList().then(response => { + this.networkConfig_.getDeviceStateList().then(response => { // Second get the network states. this.getNetworkStates_(response.result); }); @@ -154,7 +152,7 @@ Polymer({ limit: chromeos.networkConfig.mojom.kNoLimit, networkType: mojom.NetworkType.kAll, }; - this.networkConfigProxy_.getNetworkStateList(filter).then(response => { + this.networkConfig_.getNetworkStateList(filter).then(response => { this.updateNetworkStates_(response.result, deviceStateList); }); }, @@ -177,7 +175,6 @@ Polymer({ mojom.NetworkType.kWiFi, mojom.NetworkType.kCellular, mojom.NetworkType.kTether, - mojom.NetworkType.kWiMAX, mojom.NetworkType.kVPN, ]; @@ -223,8 +220,8 @@ Polymer({ for (const type of orderedNetworkTypes) { const device = newDeviceStates[type]; if (!device) { - continue; - } // The technology for this device type is unavailable. + continue; // The technology for this device type is unavailable. + } // If both 'Tether' and 'Cellular' technologies exist, merge the network // lists and do not add an active network for 'Tether' so that there is @@ -241,7 +238,7 @@ Polymer({ // types are enabled but no Cellular network exists (edge case). const networkState = this.getActiveStateForType_(activeNetworkStatesByType, type); - if (networkState.source === undefined && + if (networkState.source == mojom.OncSource.kNone && device.deviceState == mojom.DeviceStateType.kProhibited) { // Prohibited technologies are enforced by the device policy. networkState.source = diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html index 7e6f3f9fbce..5b26c96577a 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html +++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html @@ -6,6 +6,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> <link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html"> +<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior_mojo.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> @@ -29,15 +30,9 @@ flex: auto; } - #networkTitleText { - color: #333; - font-weight: 500; - } - #networkState { color: var(--cr-secondary-text-color); font-size: inherit; - font-weight: 400; } </style> <div id="outerBox" class="settings-box two-line"> @@ -60,12 +55,12 @@ </div> <template is="dom-if" if="[[showSimInfo_(deviceState)]]" restamp> - <network-siminfo on-click="doNothing_"> + <network-siminfo device-state="[[deviceState]]" on-click="doNothing_"> </network-siminfo> </template> <template is="dom-if" if="[[showPolicyIndicator_(activeNetworkState)]]"> - <cr-policy-indicator indicator-type="[[getIndicatorTypeForSourceMojo( + <cr-policy-indicator indicator-type="[[getIndicatorTypeForSource( activeNetworkState.source)]]" on-click="doNothing_"> </cr-policy-indicator> </template> diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js index 326cf06dfa1..09cbcd3965e 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 @@ -16,7 +16,10 @@ const mojom = chromeos.networkConfig.mojom; Polymer({ is: 'network-summary-item', - behaviors: [CrPolicyNetworkBehavior, I18nBehavior], + behaviors: [ + CrPolicyNetworkBehaviorMojo, + I18nBehavior, + ], properties: { /** @@ -24,7 +27,10 @@ Polymer({ * a device becomes unavailable. * @type {!OncMojo.DeviceStateProperties|undefined} */ - deviceState: Object, + deviceState: { + type: Object, + notify: true, + }, /** * If both Cellular and Tether technologies exist, we combine the @@ -120,12 +126,11 @@ Polymer({ * @private */ getConnectionStateText_: function(networkState, deviceState) { - if (!networkState) { + if (!networkState || !networkState.guid) { return ''; } const connectionState = networkState.connectionState; - const name = - networkState ? OncMojo.getNetworkDisplayName(networkState) : ''; + const name = OncMojo.getNetworkStateDisplayName(networkState); if (OncMojo.connectionStateIsConnected(connectionState)) { return name; } @@ -150,7 +155,7 @@ Polymer({ return (activeNetworkState !== undefined && OncMojo.connectionStateIsConnected( activeNetworkState.connectionState)) || - this.isPolicySourceMojo(activeNetworkState.source); + this.isPolicySource(activeNetworkState.source); }, /** @@ -181,8 +186,7 @@ Polymer({ return true; } const simLockType = deviceState.simLockStatus.lockType; - return simLockType == CrOnc.LockType.PIN || - simLockType == CrOnc.LockType.PUK; + return simLockType == 'sim-pin' || simLockType == 'sim-puk'; }, /** @@ -211,7 +215,6 @@ Polymer({ case mojom.NetworkType.kTether: return true; case mojom.NetworkType.kWiFi: - case mojom.NetworkType.kWiMAX: return deviceState.deviceState != mojom.DeviceStateType.kUninitialized; case mojom.NetworkType.kCellular: return deviceState.deviceState != @@ -248,8 +251,6 @@ Polymer({ return this.i18n('internetToggleMobileA11yLabel'); case mojom.NetworkType.kWiFi: return this.i18n('internetToggleWiFiA11yLabel'); - case mojom.NetworkType.kWiMAX: - return this.i18n('internetToggleWiMAXA11yLabel'); } assertNotReached(); return ''; @@ -324,9 +325,10 @@ Polymer({ activeNetworkState, deviceState, networkStateList) { if (!this.shouldShowSubpage_(deviceState, networkStateList)) { if (activeNetworkState.guid) { - return OncMojo.getNetworkDisplayName(activeNetworkState); - } else if (networkStateList.length > 0) { - return OncMojo.getNetworkDisplayName(networkStateList[0]); + return OncMojo.getNetworkStateDisplayName(activeNetworkState); + } + if (networkStateList.length > 0) { + return OncMojo.getNetworkStateDisplayName(networkStateList[0]); } } return this.getNetworkTypeString_(deviceState.type); diff --git a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html index 8e8b914c2e6..22d07f9ecb5 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html +++ b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html @@ -1,12 +1,11 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html"> -<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> -<link rel="import" href="../icons.html"> +<link rel="import" href="../chromeos/os_icons.html"> <link rel="import" href="../route.html"> <link rel="import" href="../settings_shared_css.html"> @@ -75,35 +74,36 @@ </span> <div id="host-device-container"> <!-- TODO(hsuregan): Add an a11y label. --> - <iron-icon icon="[[getSignalStrengthIconName_(networkProperties)]]"> + <iron-icon icon="[[getSignalStrengthIconName_(managedProperties)]]"> </iron-icon> <div id="host-device-text-container"> <span id="host-device-text-name"> - [[getDeviceName_(networkProperties)]] + [[getDeviceName_(managedProperties)]] </span> <span id="host-device-text-battery" class="secondary"> - [[getBatteryPercentageString_(networkProperties)]] + [[getBatteryPercentageString_(managedProperties)]] </span> </div> <div class="flex"></div> <div id="host-device-lost-container" hidden$="[[!outOfRange]]"> - <iron-icon icon="settings:alert-device-out-of-range"></iron-icon> + <iron-icon icon="os-settings:alert-device-out-of-range"> + </iron-icon> $i18n{tetherPhoneOutOfRange} </div> </div> <div id="tether-explanation"> - [[getExplanation_(networkProperties)]] + [[getExplanation_(managedProperties)]] </div> <div id="tether-carrier-warning"> $i18n{tetherConnectionCarrierWarning} </div> <div id="tether-description-title"> - [[getDescriptionTitle_(networkProperties)]] + [[getDescriptionTitle_(managedProperties)]] </div> <ul id="tether-description-list"> <li>$i18n{tetherConnectionDescriptionMobileData}</li> - <li>[[getBatteryDescription_(networkProperties)]]</li> - <li hidden$="[[!shouldShowDisconnectFromWifi_(networkProperties)]]"> + <li>[[getBatteryDescription_(managedProperties)]]</li> + <li hidden$="[[!shouldShowDisconnectFromWifi_(managedProperties)]]"> $i18n{tetherConnectionDescriptionWiFi} </li> </ul> diff --git a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js index 775051fab29..5a7c6beff6f 100644 --- a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js +++ b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js @@ -2,15 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * @typedef {{ - * tetherHostDeviceName: string, - * batteryPercentage: number, - * connectionStrength: number, - * isTetherHostCurrentlyOnWifi: boolean - * }} - */ -let TetherConnectionData; +(function() { +'use strict'; + +const mojom = chromeos.networkConfig.mojom; Polymer({ is: 'tether-connection-dialog', @@ -18,13 +13,8 @@ Polymer({ behaviors: [I18nBehavior], properties: { - /** - * The current properties for the network matching |guid|. - * @type {!CrOnc.NetworkProperties|undefined} - */ - networkProperties: { - type: Object, - }, + /** @private {!chromeos.networkConfig.mojom.ManagedProperties|undefined} */ + managedProperties: Object, /** * Whether the network has been lost (e.g., has gone out of range). @@ -71,12 +61,11 @@ Polymer({ }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network - * properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {boolean} * @private */ - shouldShowDisconnectFromWifi_: function(networkProperties) { + shouldShowDisconnectFromWifi_: function(managedProperties) { // TODO(khorimoto): Pipe through a new network property which describes // whether the tether host is currently connected to a Wi-Fi network. Return // whether it is here. @@ -84,13 +73,13 @@ Polymer({ }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} The battery percentage integer value converted to a * string. Note that this will not return a string with a "%" suffix. * @private */ - getBatteryPercentageAsString_: function(networkProperties) { - const percentage = this.get('Tether.BatteryPercentage', networkProperties); + getBatteryPercentageAsString_: function(managedProperties) { + const percentage = this.get('tether.batteryPercentage', managedProperties); if (percentage === undefined) { return ''; } @@ -102,69 +91,70 @@ Polymer({ * Custom icons are used here instead of a <cr-network-icon> because this * dialog uses a special color scheme. * - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} The name of the icon to be used to represent the network's * signal strength. */ - getSignalStrengthIconName_: function(networkProperties) { - let signalStrength = this.get('Tether.SignalStrength', networkProperties); + getSignalStrengthIconName_: function(managedProperties) { + let signalStrength = this.get('tether.signalStrength', managedProperties); if (signalStrength === undefined) { signalStrength = 4; } - return 'settings:signal-cellular-' + + return 'os-settings:signal-cellular-' + Math.min(4, Math.max(signalStrength, 0)) + '-bar'; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} * @private */ - getDeviceName_: function(networkProperties) { - return CrOnc.getNetworkName(networkProperties); + getDeviceName_: function(managedProperties) { + return managedProperties ? OncMojo.getNetworkName(managedProperties) : ''; }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} * @private */ - getBatteryPercentageString_: function(networkProperties) { + getBatteryPercentageString_: function(managedProperties) { return this.i18n( 'tetherConnectionBatteryPercentage', - this.getBatteryPercentageAsString_(networkProperties)); + this.getBatteryPercentageAsString_(managedProperties)); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} * @private */ - getExplanation_: function(networkProperties) { + getExplanation_: function(managedProperties) { return this.i18n( 'tetherConnectionExplanation', - CrOnc.getEscapedNetworkName(networkProperties)); + HTMLEscape(OncMojo.getNetworkName(managedProperties))); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} * @private */ - getDescriptionTitle_: function(networkProperties) { + getDescriptionTitle_: function(managedProperties) { return this.i18n( 'tetherConnectionDescriptionTitle', - CrOnc.getEscapedNetworkName(networkProperties)); + HTMLEscape(OncMojo.getNetworkName(managedProperties))); }, /** - * @param {!CrOnc.NetworkProperties} networkProperties The network properties. + * @param {!mojom.ManagedProperties} managedProperties * @return {string} * @private */ - getBatteryDescription_: function(networkProperties) { + getBatteryDescription_: function(managedProperties) { return this.i18n( 'tetherConnectionDescriptionBattery', - this.getBatteryPercentageAsString_(networkProperties)); + this.getBatteryPercentageAsString_(managedProperties)); }, }); +})(); 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 a69c59b8e0c..657239a5971 100644 --- a/chromium/chrome/browser/resources/settings/languages_page/languages_page.js +++ b/chromium/chrome/browser/resources/settings/languages_page/languages_page.js @@ -117,6 +117,16 @@ Polymer({ * @type {!LanguagesPageVisibility} */ pageVisibility: Object, + + // <if expr="chromeos"> + /** @private */ + isGuest_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('isGuest'); + }, + }, + // </if> }, // <if expr="not is_macosx"> @@ -185,6 +195,11 @@ Polymer({ * @private */ shouldShowDialogSeparator_: function() { + // <if expr="chromeos"> + if (this.isGuest_) { + return false; + } + // </if> return this.languages != undefined && this.languages.enabled.length > 1; }, @@ -268,7 +283,7 @@ Polymer({ } // The UI language choice doesn't persist for guests. - if (loadTimeData.getBoolean('isGuest')) { + if (this.isGuest_) { menu.querySelector('#uiLanguageItem').hidden = true; } }, @@ -346,6 +361,7 @@ Polymer({ }); return inputMethod ? inputMethod.displayName : ''; }, + // </if> // <if expr="chromeos or is_win"> diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.html index 12a3bc36e31..adc498c1f7d 100644 --- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.html +++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.html @@ -1,5 +1,7 @@ <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> +<!-- Anyone using this behavior might be using the referenced icons. --> +<link rel="import" href="../chromeos/os_icons.html"> <link rel="import" href="../i18n_setup.html"> <link rel="import" href="multidevice_constants.html"> <script src="multidevice_feature_behavior.js"></script> diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.js b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.js index d4468ab27e9..727822ca512 100644 --- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.js +++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_behavior.js @@ -116,11 +116,11 @@ const MultiDeviceFeatureBehaviorImpl = { getIconName: function(feature) { switch (feature) { case settings.MultiDeviceFeature.BETTER_TOGETHER_SUITE: - return 'settings:multidevice-better-together-suite'; + return 'os-settings:multidevice-better-together-suite'; case settings.MultiDeviceFeature.MESSAGES: - return 'settings:multidevice-messages'; + return 'os-settings:multidevice-messages'; case settings.MultiDeviceFeature.SMART_LOCK: - return 'settings:multidevice-smart-lock'; + return 'os-settings:multidevice-smart-lock'; default: return ''; } diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.js b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.js index f0e57fa3a19..1b8b003a81c 100644 --- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.js +++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.js @@ -57,6 +57,11 @@ Polymer({ return; } - settings.navigateTo(this.subpageRoute, this.subpageRouteUrlSearchParams); + // Remove the search term when navigating to avoid potentially having any + // visible search term reappear at a later time. See + // https://crbug.com/989119. + settings.navigateTo( + this.subpageRoute, this.subpageRouteUrlSearchParams, + true /* opt_removeSearch */); }, }); diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js index 8dc4cf217eb..fe69ece9bc2 100644 --- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js +++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js @@ -56,14 +56,13 @@ Polymer({ }, }, - /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */ - networkConfigProxy_: null, + /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ + networkConfig_: null, /** @override */ created: function() { - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** @override */ @@ -87,7 +86,7 @@ Polymer({ if (!networks.find(network => network.guid == guid)) { return; } - this.networkConfigProxy_.getNetworkState(guid).then(response => { + this.networkConfig_.getNetworkState(guid).then(response => { if (response.result) { this.activeNetworkState_ = response.result; } @@ -113,7 +112,7 @@ Polymer({ * @private */ updateTetherDeviceState_: function() { - this.networkConfigProxy_.getDeviceStateList().then(response => { + this.networkConfig_.getDeviceStateList().then(response => { const kTether = chromeos.networkConfig.mojom.NetworkType.kTether; const deviceStates = response.result; const deviceState = @@ -143,7 +142,7 @@ Polymer({ limit: 1, networkType: kTether, }; - this.networkConfigProxy_.getNetworkStateList(filter).then(response => { + this.networkConfig_.getNetworkStateList(filter).then(response => { const networks = response.result; this.activeNetworkState_ = networks[0] || OncMojo.getDefaultNetworkState(kTether); diff --git a/chromium/chrome/browser/resources/settings/os_settings_resources.grd b/chromium/chrome/browser/resources/settings/os_settings_resources.grd index 8ad9dd094f8..8338d49eb90 100644 --- a/chromium/chrome/browser/resources/settings/os_settings_resources.grd +++ b/chromium/chrome/browser/resources/settings/os_settings_resources.grd @@ -19,6 +19,159 @@ file="chromeos/os_a11y_page/os_a11y_page.html" type="chrome_html" allowexternalscript="true" /> + <structure name="IDR_OS_SETTINGS_APPS_PAGE_JS" + file="chromeos/os_apps_page/os_apps_page.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APPS_PAGE_HTML" + file="chromeos/os_apps_page/os_apps_page.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_JS" + file="chromeos/os_apps_page/app_management_page/app_management_page.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_HTML" + file="chromeos/os_apps_page/app_management_page/app_management_page.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_CONSTANTS_JS" + file="chromeos/os_apps_page/app_management_page/constants.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_CONSTANTS_HTML" + file="chromeos/os_apps_page/app_management_page/constants.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_STORE_CLIENT_JS" + file="chromeos/os_apps_page/app_management_page/store_client.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_STORE_CLIENT_HTML" + file="chromeos/os_apps_page/app_management_page/store_client.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_STORE_JS" + file="chromeos/os_apps_page/app_management_page/store.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_STORE_HTML" + file="chromeos/os_apps_page/app_management_page/store.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ACTIONS_JS" + file="chromeos/os_apps_page/app_management_page/actions.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ACTIONS_HTML" + file="chromeos/os_apps_page/app_management_page/actions.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_APP_ITEM_JS" + file="chromeos/os_apps_page/app_management_page/app_item.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_APP_ITEM_HTML" + file="chromeos/os_apps_page/app_management_page/app_item.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_BROWSER_PROXY_JS" + file="chromeos/os_apps_page/app_management_page/browser_proxy.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_BROWSER_PROXY_HTML" + file="chromeos/os_apps_page/app_management_page/browser_proxy.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_FAKE_PAGE_HANDLER_JS" + file="chromeos/os_apps_page/app_management_page/fake_page_handler.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_MAIN_VIEW_JS" + file="chromeos/os_apps_page/app_management_page/main_view.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_MAIN_VIEW_HTML" + file="chromeos/os_apps_page/app_management_page/main_view.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_TYPES_JS" + file="chromeos/os_apps_page/app_management_page/types.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_UTIL_JS" + file="chromeos/os_apps_page/app_management_page/util.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_UTIL_HTML" + file="chromeos/os_apps_page/app_management_page/util.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_SHARED_STYLE_HTML" + file="chromeos/os_apps_page/app_management_page/shared_style.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_SHARED_VARS_HTML" + file="chromeos/os_apps_page/app_management_page/shared_vars.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_REDUCERS_JS" + file="chromeos/os_apps_page/app_management_page/reducers.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_REDUCERS_HTML" + file="chromeos/os_apps_page/app_management_page/reducers.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_API_LISTENER_JS" + file="chromeos/os_apps_page/app_management_page/api_listener.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_API_LISTENER_HTML" + file="chromeos/os_apps_page/app_management_page/api_listener.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_DOM_SWITCH_JS" + file="chromeos/os_apps_page/app_management_page/dom_switch.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_DOM_SWITCH_HTML" + file="chromeos/os_apps_page/app_management_page/dom_switch.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PWA_PERMISSION_VIEW_JS" + file="chromeos/os_apps_page/app_management_page/pwa_permission_view.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PWA_PERMISSION_VIEW_HTML" + file="chromeos/os_apps_page/app_management_page/pwa_permission_view.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_ITEM_JS" + file="chromeos/os_apps_page/app_management_page/permission_item.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_ITEM_HTML" + file="chromeos/os_apps_page/app_management_page/permission_item.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_TOGGLE_JS" + file="chromeos/os_apps_page/app_management_page/permission_toggle.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_TOGGLE_HTML" + file="chromeos/os_apps_page/app_management_page/permission_toggle.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PIN_TO_SHELF_ITEM_JS" + file="chromeos/os_apps_page/app_management_page/pin_to_shelf_item.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PIN_TO_SHELF_ITEM_HTML" + file="chromeos/os_apps_page/app_management_page/pin_to_shelf_item.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_TOGGLE_ROW_JS" + file="chromeos/os_apps_page/app_management_page/toggle_row.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_TOGGLE_ROW_HTML" + file="chromeos/os_apps_page/app_management_page/toggle_row.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_APP_PERMISSION_VIEW_JS" + file="chromeos/os_apps_page/app_management_page/app_permission_view.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_APP_PERMISSION_VIEW_HTML" + file="chromeos/os_apps_page/app_management_page/app_permission_view.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ARC_PERMISSION_VIEW_JS" + file="chromeos/os_apps_page/app_management_page/arc_permission_view.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ARC_PERMISSION_VIEW_HTML" + file="chromeos/os_apps_page/app_management_page/arc_permission_view.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_CHROME_APP_PERMISSION_VIEW_JS" + file="chromeos/os_apps_page/app_management_page/chrome_app_permission_view.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_CHROME_APP_PERMISSION_VIEW_HTML" + file="chromeos/os_apps_page/app_management_page/chrome_app_permission_view.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ROUTER_JS" + file="chromeos/os_apps_page/app_management_page/router.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ROUTER_HTML" + file="chromeos/os_apps_page/app_management_page/router.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ICONS_HTML" + file="chromeos/os_apps_page/app_management_page/icons.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_UNINSTALL_BUTTON_JS" + file="chromeos/os_apps_page/app_management_page/uninstall_button.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_APP_UNINSTALL_BUTTON_HTML" + file="chromeos/os_apps_page/app_management_page/uninstall_button.html" + type="chrome_html" /> <structure name="IDR_OS_SETTINGS_MANAGE_A11Y_PAGE_JS" file="a11y_page/manage_a11y_page.js" type="chrome_html" /> @@ -125,12 +278,6 @@ file="settings_page/settings_animated_pages.js" type="chrome_html" preprocess="true" /> - <structure name="IDR_OS_SETTINGS_PERSONALIZATION_BROWSER_PROXY_HTML" - file="chromeos/personalization_page/personalization_browser_proxy.html" - type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_PERSONALIZATION_BROWSER_PROXY_JS" - file="chromeos/personalization_page/personalization_browser_proxy.js" - type="chrome_html" /> <structure name="IDR_OS_SETTINGS_PERSONALIZATION_PAGE_HTML" file="chromeos/personalization_page/personalization_page.html" type="chrome_html" @@ -394,6 +541,12 @@ <structure name="IDR_OS_SETTINGS_DEVICE_STORAGE_JS" file="device_page/storage.js" type="chrome_html" /> + <structure name="IDR_SETTINGS_DEVICE_STORAGE_EXTERNAL_ENTRY_HTML" + file="device_page/storage_external_entry.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_DEVICE_STORAGE_EXTERNAL_ENTRY_JS" + file="device_page/storage_external_entry.js" + type="chrome_html" /> <structure name="IDR_SETTINGS_DEVICE_STORAGE_EXTERNAL_HTML" file="device_page/storage_external.html" type="chrome_html" /> @@ -456,6 +609,10 @@ file="icons.html" type="chrome_html" preprocess="true" /> + <structure name="IDR_OS_SETTINGS_OS_ICONS" + file="chromeos/os_icons.html" + type="chrome_html" + preprocess="true" /> <structure name="IDR_OS_SETTINGS_POWERWASH_DIALOG_HTML" file="chromeos/os_reset_page/os_powerwash_dialog.html" type="chrome_html" /> @@ -468,11 +625,11 @@ <structure name="IDR_OS_SETTINGS_RESET_PAGE_JS" file="chromeos/os_reset_page/os_reset_page.js" type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_RESET_OS_PROXY_JS" - file="chromeos/os_reset_page/reset_os_proxy.js" + <structure name="IDR_OS_SETTINGS_RESET_BROWSER_PROXY_JS" + file="chromeos/os_reset_page/os_reset_browser_proxy.js" type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_RESET_OS_PROXY_HTML" - file="chromeos/os_reset_page/reset_os_proxy.html" + <structure name="IDR_OS_SETTINGS_RESET_BROWSER_PROXY_HTML" + file="chromeos/os_reset_page/os_reset_browser_proxy.html" type="chrome_html" /> <structure name="IDR_OS_SETTINGS_LANGUAGES_HTML" file="languages_page/languages.html" @@ -523,6 +680,12 @@ <structure name="IDR_OS_SETTINGS_MEDIA_PICKER_JS" file="site_settings/media_picker.js" type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_OS_TOOLBAR_JS" + file="chromeos/os_toolbar/os_toolbar.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_OS_TOOLBAR_HTML" + file="chromeos/os_toolbar/os_toolbar.html" + type="chrome_html" /> <structure name="IDR_OS_SETTINGS_PEOPLE_PAGE_HTML" file="chromeos/os_people_page/os_people_page.html" type="chrome_html" @@ -950,12 +1113,6 @@ <structure name="IDR_OS_SETTINGS_ZOOM_LEVELS_JS" file="site_settings/zoom_levels.js" type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_HTML" - file="app_management_page/app_management_page.html" - type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_JS" - file="app_management_page/app_management_page.js" - type="chrome_html" /> <structure name="IDR_OS_SETTINGS_ANDROID_APPS_PAGE_HTML" file="android_apps_page/android_apps_page.html" type="chrome_html" /> @@ -1347,6 +1504,12 @@ type="chrome_html" preprocess="true" allowexternalscript="true" /> + <structure name="IDR_OS_SETTINGS_WALLPAPER_BROWSER_PROXY_HTML" + file="appearance_page/wallpaper_browser_proxy.html" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_WALLPAPER_BROWSER_PROXY_JS" + file="appearance_page/wallpaper_browser_proxy.js" + type="chrome_html" /> </structures> </release> </grit> diff --git a/chromium/chrome/browser/resources/settings/page_visibility.js b/chromium/chrome/browser/resources/settings/page_visibility.js index fc8d51f2e10..6096033fafd 100644 --- a/chromium/chrome/browser/resources/settings/page_visibility.js +++ b/chromium/chrome/browser/resources/settings/page_visibility.js @@ -37,6 +37,7 @@ let PageVisibility; let A11yPageVisibility; /** + * TODO(crbug.com/950007): Remove setWallpaper after SplitSettings launch. * @typedef {{ * bookmarksBar: boolean, * homeButton: boolean, @@ -98,6 +99,11 @@ cr.define('settings', function() { let pageVisibility; const showOSSettings = loadTimeData.getBoolean('showOSSettings'); + const isAccountManagerEnabled = + loadTimeData.valueExists('isAccountManagerEnabled') && + loadTimeData.getBoolean('isAccountManagerEnabled'); + const isKerberosEnabled = loadTimeData.valueExists('isKerberosEnabled') && + loadTimeData.getBoolean('isKerberosEnabled'); if (loadTimeData.getBoolean('isGuest')) { // "if not chromeos" and "if chromeos" in two completely separate blocks @@ -167,8 +173,8 @@ cr.define('settings', function() { autofill: true, people: { lockScreen: showOSSettings, - kerberosAccounts: showOSSettings, - googleAccounts: showOSSettings, + kerberosAccounts: showOSSettings && isKerberosEnabled, + googleAccounts: showOSSettings && isAccountManagerEnabled, manageUsers: showOSSettings, }, onStartup: true, diff --git a/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html index 960c4f9f0db..3a55afc70c6 100644 --- a/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html +++ b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html @@ -15,10 +15,6 @@ <dom-module id="settings-parental-controls-page"> <template> <style include="settings-shared"> - #parental-controls-setup-section { - padding-inline-start: 20px; - } - cr-link-row { --cr-section-padding: 0; } @@ -28,16 +24,12 @@ <cr-link-row on-click="handleFamilyLinkButtonClick_" label="$i18n{parentalControlsPageTitle}" sub-label="$i18n{parentalControlsPageViewSettingsLabel}" - start-icon="cr20:kite" external> + <iron-icon icon="cr20:kite" aria-hidden="true"></iron-icon> </cr-link-row> </template> <template is="dom-if" if="[[!isChild_]]"> - <div> - <iron-icon icon="cr20:kite"></iron-icon> - </div> - <div id="parental-controls-setup-section" - class="start settings-box-text"> + <div class="start settings-box-text"> <div> $i18n{parentalControlsPageTitle} </div> diff --git a/chromium/chrome/browser/resources/settings/people_page/BUILD.gn b/chromium/chrome/browser/resources/settings/people_page/BUILD.gn index 799bbfa9a5d..05645882e1b 100644 --- a/chromium/chrome/browser/resources/settings/people_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/people_page/BUILD.gn @@ -222,7 +222,8 @@ js_library("profile_info_browser_proxy") { js_library("setup_fingerprint_dialog") { deps = [ ":fingerprint_browser_proxy", - "//ui/webui/resources/cr_elements/chromeos/fingerprint:cr_fingerprint_progress_arc", + "//ui/webui/resources/cr_elements/chromeos/cr_lottie:cr_lottie", + "//ui/webui/resources/cr_elements/cr_fingerprint:cr_fingerprint_progress_arc", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js:web_ui_listener_behavior", ] diff --git a/chromium/chrome/browser/resources/settings/people_page/account_manager.html b/chromium/chrome/browser/resources/settings/people_page/account_manager.html index b4687fedb68..3addbf6027c 100644 --- a/chromium/chrome/browser/resources/settings/people_page/account_manager.html +++ b/chromium/chrome/browser/resources/settings/people_page/account_manager.html @@ -17,6 +17,10 @@ <dom-module id="settings-account-manager"> <template> <style include="settings-shared iron-flex iron-flex-alignment"> + :host { + --add-account-margin-top: 16px; + } + .profile-icon { background: center / cover no-repeat; border-radius: 20px; @@ -40,16 +44,17 @@ margin-inline-start: 60px; } - cr-policy-indicator { - margin-inline-end: 1em; - } - #account-list-header { padding-bottom: 8px; } + cr-policy-indicator { + margin-inline-end: 1em; + margin-top: var(--add-account-margin-top); + } + #add-account-button { - margin-top: 16px; + margin-top: var(--add-account-margin-top); } #add-account-icon { diff --git a/chromium/chrome/browser/resources/settings/people_page/account_manager.js b/chromium/chrome/browser/resources/settings/people_page/account_manager.js index c4364f4ea11..8613c1262a3 100644 --- a/chromium/chrome/browser/resources/settings/people_page/account_manager.js +++ b/chromium/chrome/browser/resources/settings/people_page/account_manager.js @@ -169,8 +169,7 @@ Polymer({ * @private */ refreshAccounts_: function() { - const includeImages = true; - this.browserProxy_.getAccounts(includeImages).then(accounts => { + this.browserProxy_.getAccounts().then(accounts => { this.set('accounts_', accounts); }); }, diff --git a/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js b/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js index 87826f732a5..b08b02268b5 100644 --- a/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js +++ b/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js @@ -19,7 +19,7 @@ cr.exportPath('settings'); * unmigrated: boolean, * fullName: string, * email: string, - * pic: (string|undefined), + * pic: string, * organization: (string|undefined), * }} */ @@ -30,11 +30,9 @@ cr.define('settings', function() { class AccountManagerBrowserProxy { /** * Returns a Promise for the list of GAIA accounts held in AccountManager. - * @param {boolean} includeImages Include the profile icon images in - * settings.Account.pic field, which increases IPC data from the browser. * @return {!Promise<!Array<settings.Account>>} */ - getAccounts(includeImages) {} + getAccounts() {} /** * Triggers the 'Add account' flow. @@ -72,8 +70,8 @@ cr.define('settings', function() { */ class AccountManagerBrowserProxyImpl { /** @override */ - getAccounts(includeImages) { - return cr.sendWithPromise('getAccounts', includeImages); + getAccounts() { + return cr.sendWithPromise('getAccounts'); } /** @override */ 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 92cfb70ecef..657e219e3dd 100644 --- a/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js +++ b/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.js @@ -117,9 +117,10 @@ Polymer({ // Flash the background. listItem.animate( - { - backgroundColor: ['var(--google-grey-300)', 'white'], - }, + [ + {backgroundColor: ['var(--google-grey-300)']}, + {backgroundColor: ['white']} + ], FLASH_DURATION_MS); }); }, diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html index da29870c4e8..66f41e87954 100644 --- a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html +++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html @@ -169,11 +169,9 @@ </cr-action-menu> </div> - <cr-toast id="account-removed-toast" duration="3000"> + <cr-toast id="account-toast" duration="3000"> <!-- Gets displayed with black font without div and id :-/ --> - <div id="account-removed-toast-label"> - $i18n{kerberosAccountsAccountRemovedTip} - </div> + <div id="account-toast-label">[[accountToastText_]]</div> </cr-toast> <template is="dom-if" if="[[showAddAccountDialog_]]" restamp> diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js index aec55ed61e7..4f45f060ed1 100644 --- a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js +++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js @@ -46,6 +46,12 @@ Polymer({ return loadTimeData.getBoolean('kerberosAddAccountsAllowed'); }, }, + + /** @private */ + accountToastText_: { + type: String, + value: '', + }, }, /** @private {?settings.KerberosAccountsBrowserProxy} */ @@ -106,7 +112,12 @@ Polymer({ /** @private */ onAddAccountDialogClosed_: function() { + if (this.$$('kerberos-add-account-dialog').accountWasRefreshed) { + this.showToast_('kerberosAccountsAccountRefreshedTip'); + } + this.showAddAccountDialog_ = false; + // In case it was opened by the 'Refresh now' action menu. this.closeActionMenu_(); }, @@ -152,7 +163,7 @@ Polymer({ /** @type {!settings.KerberosAccount} */ (this.selectedAccount_)) .then(error => { if (error == settings.KerberosErrorType.kNone) { - this.$$('#account-removed-toast').show(); + this.showToast_('kerberosAccountsAccountRemovedTip'); } else { console.error('Unexpected error removing account: ' + error); } @@ -176,5 +187,15 @@ Polymer({ */ onRefreshNowClick_: function() { this.showAddAccountDialog_ = true; + }, + + /** + * Pops up a toast with localized text |label|. + * @param {string} label Name of the localized label string. + * @private + */ + showToast_: function(label) { + this.accountToastText_ = this.i18n(label); + this.$$('#account-toast').show(); } }); diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html index b6f3fd769cd..45f8f74a85a 100644 --- a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html +++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html @@ -28,15 +28,21 @@ margin-inline-start: 1em; } + #credentials { + margin-top: 16px; + } + #credentials > *:not(:last-child) { margin-bottom: var(--cr-form-field-bottom-spacing); } #general-error-container { + display: flex; height: 56px; } #config-error-container { + display: flex; height: 40px; margin-top: 16px; } @@ -46,10 +52,6 @@ color: var(--settings-error-color); } - .inner-error-container { - display: flex; - } - iron-icon[icon='cr:error'] { fill: var(--settings-error-color); margin-inline-end: 8px; @@ -74,13 +76,12 @@ $i18n{addKerberosAccountDescription} </h2> - <div id="general-error-container"> - <div class="inner-error-container" - hidden="[[!showError_(generalErrorText_)]]"> - <iron-icon id="error-icon" icon="cr:error"></iron-icon> - <div id="general-error-message">[[generalErrorText_]]</div> - </div> + <div id="general-error-container" + hidden="[[!showError_(generalErrorText_)]]"> + <iron-icon id="error-icon" icon="cr:error"></iron-icon> + <div id="general-error-message">[[generalErrorText_]]</div> </div> + <div id="credentials"> <cr-input id="username" label="$i18n{kerberosUsername}" value="{{username_}}" invalid="[[showError_(usernameErrorText_)]]" @@ -143,12 +144,10 @@ spellcheck="false" disabled="[[isManaged_]]"> </settings-textarea> - <div id="config-error-container"> - <div class="inner-error-container" - hidden="[[!showError_(configErrorText_)]]"> - <iron-icon id="error-icon" icon="cr:error"></iron-icon> - <div id="config-error-message">[[configErrorText_]]</div> - </div> + <div id="config-error-container" + hidden="[[!showError_(configErrorText_)]]"> + <iron-icon id="error-icon" icon="cr:error"></iron-icon> + <div id="config-error-message">[[configErrorText_]]</div> </div> </div> diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js index 295a14d087a..5bb16f8daf9 100644 --- a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js +++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js @@ -20,6 +20,15 @@ Polymer({ */ presetAccount: Object, + /** + * Whether an existing |presetAccount| was successfully authenticated. + * Always false if |presetAccount| is null (new accounts). + */ + accountWasRefreshed: { + type: Boolean, + value: false, + }, + /** @private */ username_: { type: String, @@ -170,7 +179,11 @@ Polymer({ onAdd_: function() { assert(!this.inProgress_); this.inProgress_ = true; - this.updateErrorMessages_(settings.KerberosErrorType.kNone); + + // Keep the general error, wiping it might cause the error to disappear and + // immediately reappear, causing 2 resizings of the dialog. + this.usernameErrorText_ = ''; + this.passwordErrorText_ = ''; // An empty password triggers the Kerberos daemon to use the remembered one. const passwordToSubmit = this.useRememberedPassword_ ? '' : this.password_; @@ -187,6 +200,7 @@ Polymer({ // Success case. Close dialog. if (error == settings.KerberosErrorType.kNone) { + this.accountWasRefreshed = this.presetAccount != null; this.$.addDialog.close(); return; } @@ -331,8 +345,8 @@ Polymer({ /** * @param {!settings.KerberosConfigErrorCode} code Error code - * @param {!string} errorLine Line where the error occurred - * @return {!string} Localized error string that corresponds to code + * @param {string} errorLine Line where the error occurred + * @return {string} Localized error string that corresponds to code * @private */ getConfigErrorString_: function(code, errorLine) { @@ -363,8 +377,8 @@ Polymer({ /** * Selects a line in a text area and scrolls to it. * @param {!Element} textArea A textarea element - * @param {!number} lineIndex 0-based index of the line to select - * @return {!string} The line at lineIndex. + * @param {number} lineIndex 0-based index of the line to select + * @return {string} The line at lineIndex. * @private */ selectAndScrollTo_: function(textArea, lineIndex) { 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 a2ce568a87d..56fa177dc1d 100644 --- a/chromium/chrome/browser/resources/settings/people_page/lock_screen.html +++ b/chromium/chrome/browser/resources/settings/people_page/lock_screen.html @@ -66,12 +66,6 @@ label="$i18n{enableScreenlock}"> </settings-toggle-button> - <settings-toggle-button id="enableLockScreenMediaKeys" - hidden="[[!lockScreenMediaKeysPreferenceEnabled_]]" - pref="{{prefs.ash.lock_screen_media_keys_enabled}}" - label="$i18n{lockScreenMediaKeys}"> - </settings-toggle-button> - <template is="dom-if" if="[[quickUnlockEnabled_]]"> <div id="lockOptionsDiv"> <div class="settings-box"> 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 6780493980f..f0584fee7e4 100644 --- a/chromium/chrome/browser/resources/settings/people_page/lock_screen.js +++ b/chromium/chrome/browser/resources/settings/people_page/lock_screen.js @@ -130,19 +130,6 @@ Polymer({ readOnly: true, }, - /** - * Whether the lock screen media keys preference is enabled by the - * feature flag. - * @private - */ - lockScreenMediaKeysPreferenceEnabled_: { - type: Boolean, - value: function() { - return loadTimeData.getBoolean('lockScreenMediaKeysEnabled'); - }, - readOnly: true, - }, - /** @private */ showPasswordPromptDialog_: Boolean, diff --git a/chromium/chrome/browser/resources/settings/people_page/people_page.html b/chromium/chrome/browser/resources/settings/people_page/people_page.html index f2a605bb946..d6891e8da93 100644 --- a/chromium/chrome/browser/resources/settings/people_page/people_page.html +++ b/chromium/chrome/browser/resources/settings/people_page/people_page.html @@ -28,6 +28,7 @@ <if expr="chromeos"> <link rel="import" href="account_manager.html"> +<link rel="import" href="account_manager_browser_proxy.html"> <link rel="import" href="change_picture.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/cr_picture/cr_png_behavior.html"> <link rel="import" href="fingerprint_list.html"> @@ -52,6 +53,11 @@ margin-inline-start: 20px; } + .sync-row { + align-items: center; + flex: auto; + } + #profile-icon { background: center / cover no-repeat; border-radius: 20px; @@ -60,29 +66,29 @@ width: 40px; } - iron-icon[icon='cr:sync'] { - --iron-icon-fill-color: var(--google-green-refresh-700); + #sync-status.no-error { + --cr-link-row-start-icon-color: var(--google-green-refresh-700); } @media (prefers-color-scheme: dark) { - iron-icon[icon='cr:sync'] { - --iron-icon-fill-color: var(--google-green-refresh-300); + #sync-status.no-error { + --cr-link-row-start-icon-color: var(--google-green-refresh-300); } } - #sync-status[actionable] iron-icon[icon='settings:sync-problem'] { - --iron-icon-fill-color: var(--settings-error-color); + #sync-setup { + --cr-secondary-text: { + color: var(--settings-error-color); + } } - #sync-status[actionable].auth-error - iron-icon[icon='settings:sync-disabled'] { - --iron-icon-fill-color: var(--google-blue-500); + #sync-status[actionable].auth-error { + --cr-link-row-start-icon-color: var(--google-blue-500); } @media (prefers-color-scheme: dark) { - #sync-status[actionable].auth-error - iron-icon[icon='settings:sync-disabled'] { - --iron-icon-fill-color: var(--google-blue-refresh-300); + #sync-status[actionable].auth-error { + --cr-link-row-start-icon-color: var(--google-blue-refresh-300); } } @@ -95,8 +101,11 @@ border-top: var(--cr-separator-line); } - .settings-box[actionable].sync-error #syncSecondary { - color: var(--settings-error-color); + #sync-status[actionable].sync-error { + --cr-link-row-start-icon-color: var(--settings-error-color); + --cr-secondary-text: { + color: var(--settings-error-color); + } } .icon-container { @@ -151,12 +160,15 @@ </if> <div id="picture-subpage-trigger" class="settings-box first two-line"> <template is="dom-if" if="[[syncStatus]]"> - <div id="profile-icon" on-click="onProfileTap_" actionable + <div id="profile-icon" on-click="onProfileTap_" + actionable$="[[isProfileActionable_]]" style="background-image: [[getIconImageSet_( profileIconUrl_)]]"> </div> - <div class="middle two-line no-min-width" on-click="onProfileTap_" - actionable> + <div class="middle two-line no-min-width" + id="profile-row" + on-click="onProfileTap_" + actionable$="[[isProfileActionable_]]"> <div class="flex text-elide settings-box-text"> <span id="profile-name">[[profileName_]]</span> <div class="secondary" hidden="[[!syncStatus.signedIn]]"> @@ -169,8 +181,10 @@ aria-describedby="profile-name"></cr-icon-button> </if> <if expr="chromeos"> - <cr-icon-button class="subpage-arrow" - aria-label="$i18n{changePictureTitle}" + <cr-icon-button class$="[[profileRowIconClass_]]" + id="profile-subpage-arrow" + hidden="[[!isProfileActionable_]]" + aria-label$="[[profileRowIconAriaLabel_]]" aria-describedby="profile-name"></cr-icon-button> </if> </div> @@ -217,29 +231,21 @@ <template is="dom-if" if="[[isPreUnifiedConsentAdvancedSyncSettingsVisible_( syncStatus, unifiedConsentEnabled_)]]"> - <div class$="settings-box two-line - [[getSyncStatusClass_(syncStatus)]]" - on-click="onSyncTap_" id="sync-status" + <cr-link-row id="sync-status" + class$="[[getSyncStatusClass_(syncStatus)]]" + label="$i18n{syncAndNonPersonalizedServices}" + sub-label="[[getSyncAndGoogleServicesSubtext_(syncStatus)]]" + on-click="onSyncTap_" start-icon="[[getSyncIcon_(syncStatus)]]" actionable$="[[isSyncStatusActionable_(syncStatus)]]"> - <div class="icon-container"> - <iron-icon id="sync-icon" icon$="[[getSyncIcon_(syncStatus)]]"> - </iron-icon> - </div> - <div class="middle settings-box-text"> - $i18n{sync} - <div class="secondary" id="syncSecondary"> - [[syncStatus.statusText]] - </div> - </div> - <cr-icon-button class="subpage-arrow" aria-label="$i18n{sync}" - aria-describedby="syncSecondary"></cr-icon-button> - </div> + </cr-link-row> </template> <template is="dom-if" if="[[unifiedConsentEnabled_]]"> <cr-link-row id="sync-setup" label="$i18n{syncAndNonPersonalizedServices}" - on-click="onSyncTap_"></cr-link-row> + sub-label="[[getSyncAndGoogleServicesSubtext_(syncStatus)]]" + on-click="onSyncTap_"> + </cr-link-row> </template> <if expr="not chromeos"> @@ -268,8 +274,7 @@ prefs.settings.enable_screen_lock.value)]]" hidden="[[!pageVisibility.people.lockScreen]]"></cr-link-row> - <template is="dom-if" if="[[shouldShowAccountManager_( - isAccountManagerEnabled_, pageVisibility.people.googleAccounts)]]"> + <template is="dom-if" if="[[pageVisibility.people.googleAccounts]]"> <cr-link-row id="account-manager-subpage-trigger" class="hr" on-click="onAccountManagerTap_" label="$i18n{accountManagerSubMenuLabel}"></cr-link-row> @@ -283,8 +288,7 @@ hidden="[[!pageVisibility.people.manageUsers]]"> </cr-link-row> - <template is="dom-if" if="[[shouldShowKerberos_( - isKerberosEnabled_, pageVisibility.people.kerberosAccounts)]]"> + <template is="dom-if" if="[[pageVisibility.people.kerberosAccounts]]"> <cr-link-row id="kerberos-accounts-subpage-trigger" class="hr" on-click="onKerberosAccountsTap_" label="$i18n{kerberosAccountsSubMenuLabel}"> @@ -371,8 +375,7 @@ <settings-change-picture></settings-change-picture> </settings-subpage> </template> - <template is="dom-if" if="[[shouldShowAccountManager_( - isAccountManagerEnabled_, pageVisibility.people.googleAccounts)]]"> + <template is="dom-if" if="[[pageVisibility.people.googleAccounts]]"> <template is="dom-if" route-path="/accountManager"> <settings-subpage associated-control="[[$$('#account-manager-subpage-trigger')]]" @@ -381,8 +384,7 @@ </settings-subpage> </template> </template> - <template is="dom-if" if="[[shouldShowKerberos_( - isKerberosEnabled_, pageVisibility.people.kerberosAccounts)]]"> + <template is="dom-if" if="[[pageVisibility.people.kerberosAccounts]]"> <template is="dom-if" route-path="/kerberosAccounts"> <settings-subpage associated-control="[[$$('#kerberos-accounts-subpage-trigger')]]" 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 cce39871d20..ec7591d62f6 100644 --- a/chromium/chrome/browser/resources/settings/people_page/people_page.js +++ b/chromium/chrome/browser/resources/settings/people_page/people_page.js @@ -91,11 +91,67 @@ Polymer({ profileIconUrl_: String, /** + * Whether the profile row is clickable. The behavior depends on the + * platform. + * @private + */ + isProfileActionable_: { + type: Boolean, + value: function() { + if (!cr.isChromeOS) { + // Opens profile manager. + return true; + } + if (loadTimeData.getBoolean('showOSSettings')) { + // Pre-SplitSettings opens change picture. + return true; + } + // Post-SplitSettings links out to account manager if it is available. + return loadTimeData.getBoolean('isAccountManagerEnabled'); + }, + readOnly: true, + }, + + /** * The current profile name. * @private */ profileName_: String, + // <if expr="chromeos"> + /** @private {string} */ + profileRowIconClass_: { + type: String, + value: function() { + if (loadTimeData.getBoolean('showOSSettings')) { + // Pre-SplitSettings links internally to the change picture subpage. + return 'subpage-arrow'; + } else { + // Post-SplitSettings links externally to account manager. If account + // manager isn't available the icon will be hidden. + return 'icon-external'; + } + }, + readOnly: true, + }, + + /** @private {string} */ + profileRowIconAriaLabel_: { + type: String, + value: function() { + if (loadTimeData.getBoolean('showOSSettings')) { + // Pre-SplitSettings. + return this.i18n('changePictureTitle'); + } else { + // Post-SplitSettings. If account manager isn't available the icon + // will be hidden so the label doesn't matter. + return this.i18n('accountManagerSubMenuLabel'); + } + }, + readOnly: true, + }, + // </if> + // <if expr="not chromeos"> /** @private {boolean} */ shouldShowGoogleAccount_: { @@ -128,30 +184,6 @@ Polymer({ readOnly: true, }, - /** - * True if Chrome OS Account Manager is enabled. - * @private - */ - isAccountManagerEnabled_: { - type: Boolean, - value: function() { - return loadTimeData.getBoolean('isAccountManagerEnabled'); - }, - readOnly: true, - }, - - /** - * True if Chrome OS Kerberos support is enabled. - * @private - */ - isKerberosEnabled_: { - type: Boolean, - value: function() { - return loadTimeData.getBoolean('isKerberosEnabled'); - }, - readOnly: true, - }, - /** @private */ showParentalControls_: { type: Boolean, @@ -219,10 +251,24 @@ Polymer({ /** @override */ attached: function() { - const profileInfoProxy = settings.ProfileInfoBrowserProxyImpl.getInstance(); - profileInfoProxy.getProfileInfo().then(this.handleProfileInfo_.bind(this)); - this.addWebUIListener( - 'profile-info-changed', this.handleProfileInfo_.bind(this)); + let useProfileNameAndIcon = true; + // <if expr="chromeos"> + if (!loadTimeData.getBoolean('showOSSettings') && + loadTimeData.getBoolean('isAccountManagerEnabled')) { + // If this is SplitSettings and we have the Google Account manager, + // prefer the GAIA name and icon. + useProfileNameAndIcon = false; + this.addWebUIListener( + 'accounts-changed', this.updateAccounts_.bind(this)); + this.updateAccounts_(); + } + // </if> + if (useProfileNameAndIcon) { + settings.ProfileInfoBrowserProxyImpl.getInstance().getProfileInfo().then( + this.handleProfileInfo_.bind(this)); + this.addWebUIListener( + 'profile-info-changed', this.handleProfileInfo_.bind(this)); + } this.syncBrowserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); this.syncBrowserProxy_.getSyncStatus().then( @@ -283,6 +329,18 @@ Polymer({ // </if> /** + * @return {string} + * @private + */ + getSyncAndGoogleServicesSubtext_: function() { + if (this.syncStatus && this.syncStatus.hasError && + this.syncStatus.statusText) { + return this.syncStatus.statusText; + } + return ''; + }, + + /** * Handler for when the profile's icon and name is updated. * @private * @param {!settings.ProfileInfo} info @@ -304,6 +362,27 @@ Polymer({ this.profileIconUrl_ = info.iconUrl; }, + // <if expr="chromeos"> + /** + * @private + * @suppress {checkTypes} The types only exists in Chrome OS builds, but + * Closure doesn't understand the <if> above. + */ + updateAccounts_: async function() { + const /** @type {!Array<{settings.Account}>} */ accounts = + await settings.AccountManagerBrowserProxyImpl.getInstance() + .getAccounts(); + // The user might not have any GAIA accounts (e.g. guest mode, Kerberos, + // Active Directory). In these cases the profile row is hidden, so there's + // nothing to do. + if (accounts.length == 0) { + return; + } + this.profileName_ = accounts[0].fullName; + this.profileIconUrl_ = accounts[0].pic; + }, + // </if> + /** * Handler for when the sync state is pushed from the browser. * @param {?settings.SyncStatus} syncStatus @@ -342,7 +421,14 @@ Polymer({ /** @private */ onProfileTap_: function() { // <if expr="chromeos"> - settings.navigateTo(settings.routes.CHANGE_PICTURE); + if (loadTimeData.getBoolean('showOSSettings')) { + // Pre-SplitSettings. + settings.navigateTo(settings.routes.CHANGE_PICTURE); + } else if (loadTimeData.getBoolean('isAccountManagerEnabled')) { + // Post-SplitSettings. The browser C++ code loads OS settings in a window. + // Don't use window.open() because that creates an extra empty tab. + window.location.href = 'chrome://os-settings/accountManager'; + } // </if> // <if expr="not chromeos"> settings.navigateTo(settings.routes.MANAGE_PROFILE); @@ -459,18 +545,6 @@ Polymer({ onManageOtherPeople_: function() { settings.navigateTo(settings.routes.ACCOUNTS); }, - - /** @private */ - shouldShowAccountManager_: function() { - return this.isAccountManagerEnabled_ && - this.pageVisibility.people.googleAccounts; - }, - - /** @private */ - shouldShowKerberos_: function() { - return this.isKerberosEnabled_ && - this.pageVisibility.people.kerberosAccounts; - }, // </if> // <if expr="not chromeos"> @@ -590,7 +664,7 @@ Polymer({ 'sync-error'; } - return ''; + return 'no-error'; }, /** 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 6636a96d3eb..298e790f814 100644 --- a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html +++ b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html @@ -1,6 +1,7 @@ <link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="chrome://resources/cr_elements/chromeos/fingerprint/cr_fingerprint_progress_arc.html"> +<link rel="import" href="chrome://resources/cr_elements/chromeos/cr_lottie/cr_lottie.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> @@ -21,11 +22,6 @@ width: 500px; } - .fingerprint-scanner-tablet-power-button { - background: - url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_POWER_BUTTON_ANIMATION); - } - .fingerprint-scanner-laptop-bottom-right { background: url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_BOTTOM_RIGHT_ANIMATION); @@ -43,6 +39,11 @@ height: 240px; } + #scannerLocationLottie { + height: 220px; + padding: 10px 0; + } + #messageDiv { height: 20px; } @@ -67,11 +68,21 @@ aria-live="polite"> <span>[[getInstructionMessage_(step_, problemMessage_)]]</span> </div> - <div id="scannerLocation" hidden="[[!showScannerLocation_(step_)]]" - class$="[[fingerprintScannerAnimationClass_]]" - aria-label="$i18n{configureFingerprintScannerStepAriaLabel}" - aria-live="polite" > - </div> + <template is="dom-if" if="[[shouldUseLottieAnimation_]]"> + <div id="scannerLocationLottie" + hidden="[[!showScannerLocation_(step_)]]" aria-live="polite" + aria-label="$i18n{configureFingerprintScannerStepAriaLabel}"> + <cr-lottie animation-url="finger_print.json" autoplay> + </cr-lottie> + </div> + </template> + <template is="dom-if" if="[[!shouldUseLottieAnimation_]]"> + <div id="scannerLocation" hidden="[[!showScannerLocation_(step_)]]" + class$="[[fingerprintScannerAnimationClass_]]" + aria-label="$i18n{configureFingerprintScannerStepAriaLabel}" + aria-live="polite" > + </div> + </template> <cr-fingerprint-progress-arc id="arc" circle-radius="100" hidden="[[!showArc_(step_)]]"> </cr-fingerprint-progress-arc> 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 57168253b54..d0d6d0ec42b 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 @@ -101,7 +101,7 @@ Polymer({ loadTimeData.getInteger('fingerprintReaderLocation'); switch (fingerprintLocation) { case settings.FingerprintLocation.TABLET_POWER_BUTTON: - return 'fingerprint-scanner-tablet-power-button'; + return ''; case settings.FingerprintLocation.KEYBOARD_TOP_RIGHT: return 'fingerprint-scanner-laptop-top-right'; case settings.FingerprintLocation.KEYBOARD_BOTTOM_RIGHT: @@ -111,6 +111,28 @@ Polymer({ }, readOnly: true, }, + + /** + * True lottie animation file should be used instead of a png animation + * image sequence. + * @private {boolean} + */ + shouldUseLottieAnimation_: { + type: Boolean, + value: function() { + if (!loadTimeData.getBoolean('fingerprintUnlockEnabled')) { + return false; + } + + const fingerprintLocation = + loadTimeData.getInteger('fingerprintReaderLocation'); + const isTabletPowerButton = + settings.FingerprintLocation.TABLET_POWER_BUTTON == + fingerprintLocation; + return isTabletPowerButton; + }, + readOnly: true, + } }, /** @@ -344,6 +366,5 @@ Polymer({ this.$.arc.setProgress(oldValue, newValue, newValue === 100); }, - }); })(); diff --git a/chromium/chrome/browser/resources/settings/people_page/sync_browser_proxy.js b/chromium/chrome/browser/resources/settings/people_page/sync_browser_proxy.js index 1b17c57b2ec..340398c2a47 100644 --- a/chromium/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +++ b/chromium/chrome/browser/resources/settings/people_page/sync_browser_proxy.js @@ -96,6 +96,9 @@ settings.StatusAction = { * typedUrlsEnforced: boolean, * typedUrlsRegistered: boolean, * typedUrlsSynced: boolean, + * wifiConfigurationsEnforced: boolean, + * wifiConfigurationsRegistered: boolean, + * wifiConfigurationsSynced: boolean, * }} */ settings.SyncPrefs; @@ -211,6 +214,13 @@ cr.define('settings', function() { * Opens the Google Activity Controls url in a new tab. */ openActivityControlsUrl() {} + + /** + * Function to dispatch event sync-prefs-changed even without a change. + * This is used to decide whether we should show the link to password + * manager in passwords section on page load. + */ + sendSyncPrefsChanged() {} } /** @@ -298,6 +308,11 @@ cr.define('settings', function() { chrome.metricsPrivate.recordUserAction( 'Signin_AccountSettings_GoogleActivityControlsClicked'); } + + /** @override */ + sendSyncPrefsChanged() { + chrome.send('SyncPrefsDispatch'); + } } cr.addSingletonGetter(SyncBrowserProxyImpl); diff --git a/chromium/chrome/browser/resources/settings/people_page/sync_controls.html b/chromium/chrome/browser/resources/settings/people_page/sync_controls.html index 29466647fec..85151dcf0e4 100644 --- a/chromium/chrome/browser/resources/settings/people_page/sync_controls.html +++ b/chromium/chrome/browser/resources/settings/people_page/sync_controls.html @@ -135,6 +135,22 @@ </cr-toggle> </div> +<if expr="chromeos"> + <div class="list-item" + hidden="[[!syncPrefs.wifiConfigurationsRegistered]]"> + <div id="wifiConfigurationsCheckboxLabel"> + $i18n{wifiConfigurationsCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.wifiConfigurationsSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, + syncPrefs.wifiConfigurationsEnforced)]]" + aria-labelledby="wifiConfigurationsCheckboxLabel"> + </cr-toggle> + </div> +</if> + <div class="list-item" hidden="[[!syncPrefs.autofillRegistered]]"> <div id="autofillCheckboxLabel"> $i18n{autofillCheckboxLabel} 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 47c03a09a34..3b94c83970a 100644 --- a/chromium/chrome/browser/resources/settings/people_page/users_page.html +++ b/chromium/chrome/browser/resources/settings/people_page/users_page.html @@ -55,19 +55,19 @@ disabled="[[isEditingDisabled_(isOwner_, isWhitelistManaged_)]]" inverted> </settings-toggle-button> - <div class="list-frame"> - <settings-user-list prefs="[[prefs]]" - disabled="[[isEditingUsersDisabled_(isOwner_, isWhitelistManaged_, - prefs.cros.accounts.allowGuest.value)]]"> - </settings-user-list> - <div id="add-user-button" class="list-item" - hidden="[[isEditingUsersDisabled_(isOwner_, isWhitelistManaged_, - prefs.cros.accounts.allowGuest.value)]]"> - <a is="action-link" class="list-button" on-click="openAddUserDialog_"> - $i18n{addUsers} - </a> + <template is="dom-if" + if="[[isEditingUsersEnabled_(isOwner_, isWhitelistManaged_, + prefs.cros.accounts.allowGuest.value, isChild_)]]"> + <div class="list-frame" > + <settings-user-list prefs="[[prefs]]"> + </settings-user-list> + <div id="add-user-button" class="list-item"> + <a is="action-link" class="list-button" on-click="openAddUserDialog_"> + $i18n{addUsers} + </a> + </div> </div> - </div> + </template> <settings-users-add-user-dialog id="addUserDialog" on-close="onAddUserDialogClose_"> </settings-users-add-user-dialog> 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 f8f19f31ff6..4a3ff206056 100644 --- a/chromium/chrome/browser/resources/settings/people_page/users_page.js +++ b/chromium/chrome/browser/resources/settings/people_page/users_page.js @@ -30,6 +30,14 @@ Polymer({ type: Boolean, value: false, }, + + /** @private */ + isChild_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('isSupervised'); + }, + }, }, /** @override */ @@ -71,11 +79,13 @@ Polymer({ * @param {boolean} isOwner * @param {boolean} isWhitelistManaged * @param {boolean} allowGuest + * @param {boolean} isChild * @private * @return {boolean} */ - isEditingUsersDisabled_: function(isOwner, isWhitelistManaged, allowGuest) { - return !isOwner || isWhitelistManaged || allowGuest; + isEditingUsersEnabled_: function( + isOwner, isWhitelistManaged, allowGuest, isChild) { + return isOwner && !isWhitelistManaged && !allowGuest && !isChild; }, /** @return {boolean} */ diff --git a/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn b/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn index 0f0acd7af8e..e7619959244 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn @@ -103,6 +103,7 @@ if (is_chromeos) { ":cups_nearby_printers", ":cups_printers_browser_proxy", ":cups_saved_printers", + "..:route", "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider", "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/cr_toast:cr_toast", diff --git a/chromium/chrome/browser/resources/settings/printing_page/OWNERS b/chromium/chrome/browser/resources/settings/printing_page/OWNERS new file mode 100644 index 00000000000..1100e9746d7 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/printing_page/OWNERS @@ -0,0 +1,2 @@ +khorimoto@chromium.org +stevenjb@chromium.org 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 55b32a67b00..7c9a314bf87 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 @@ -139,7 +139,8 @@ </cr-button> <cr-button id="addPrinterButton" class="action-button" on-click="addPressed_" - disabled="[[!canAddPrinter_(newPrinter.*, inProgress_)]]"> + disabled="[[!canAddPrinter_(newPrinter.*, + addPrinterInProgress_)]]"> $i18n{addPrinterButtonText} </cr-button> </div> @@ -216,7 +217,8 @@ <cr-button class="action-button" id="addPrinterButton" disabled="[[!canAddPrinter_(activePrinter.ppdManufacturer, activePrinter.ppdModel, - activePrinter.printerPPDPath)]]" + activePrinter.printerPPDPath, + addPrinterInProgress_)]]" on-click="addPrinter_"> $i18n{addPrinterButtonText} </cr-button> 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 c63057baedb..74f6940dfbb 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 @@ -387,6 +387,12 @@ Polymer({ value: '', }, + /** @private */ + addPrinterInProgress_: { + type: Boolean, + value: false, + }, + /** * The error text to be displayed on the dialog. * @private @@ -431,6 +437,7 @@ Polymer({ * @private * */ onPrinterAddedFailed_: function(result) { + this.addPrinterInProgress_ = false; this.errorText_ = settings.printing.getErrorText( /** @type {PrinterSetupResult} */ (result)); }, @@ -548,6 +555,7 @@ Polymer({ /** @private */ addPrinter_: function() { + this.addPrinterInProgress_ = true; settings.CupsPrintersBrowserProxyImpl.getInstance() .addCupsPrinter(this.activePrinter) .then( @@ -563,8 +571,9 @@ Polymer({ * @private */ canAddPrinter_: function(ppdManufacturer, ppdModel, printerPPDPath) { - return settings.printing.isPPDInfoValid( - ppdManufacturer, ppdModel, printerPPDPath); + return !this.addPrinterInProgress_ && + settings.printing.isPPDInfoValid( + ppdManufacturer, ppdModel, printerPPDPath); }, }); 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 793770fd6dc..ab4137cfd86 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 @@ -59,22 +59,26 @@ on-change="onProtocolChange_" disabled="[[!protocolSelectEnabled(isOnline_, networkProtocolActive_)]]"> - <option value="ipp" disabled="[[!networkProtocolActive_]]"> + <option value="ipp"> $i18n{printerProtocolIpp} </option> - <option value="ipps" disabled="[[!networkProtocolActive_]]"> + <option value="ipps"> $i18n{printerProtocolIpps} </option> - <option value="http" disabled="[[!networkProtocolActive_]]"> + <option value="http" + disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]"> $i18n{printerProtocolHttp} </option> - <option value="https" disabled="[[!networkProtocolActive_]]"> + <option value="https" + disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]"> $i18n{printerProtocolHttps} </option> - <option value="socket" disabled="[[!networkProtocolActive_]]"> + <option value="socket" + disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]"> $i18n{printerProtocolAppSocket} </option> - <option value="lpd" disabled="[[!networkProtocolActive_]]"> + <option value="lpd" + disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]"> $i18n{printerProtocolLpd} </option> <option value="usb" disabled="[[networkProtocolActive_]]"> @@ -101,42 +105,45 @@ value="[[getPrinterURI_(pendingPrinter_)]]"> </cr-input> </div> - <div class="settings-box two-line"> - <cr-searchable-drop-down items="[[manufacturerList]]" - id="printerPPDManufacturer" - label="$i18n{printerManufacturer}" - value="{{pendingPrinter_.ppdManufacturer}}" - readonly="[[!isOnline_]]"> - </cr-searchable-drop-down> - </div> - <div class="settings-box two-line"> - <cr-searchable-drop-down items="[[modelList]]" - id="printerPPDModel" - label="$i18n{printerModel}" - value="{{pendingPrinter_.ppdModel}}" - readonly="[[!isOnline_]]"> - </cr-searchable-drop-down> - </div> - <div id="ppdLabel" class="cr-form-field-label"> - <span>$i18n{selectDriver}</span> - <a href="$i18n{printingCUPSPrintPpdLearnMoreUrl}" target="_blank"> - $i18n{learnMore} - </a> - </div> - <div class="settings-box two-line"> - <cr-input class="browse-file-input" readonly tabindex="-1" - value="[[userPPD_]]" aria-labelledby="ppdLabel" - error-message="$i18n{selectDriverErrorMessage}" - invalid="[[invalidPPD_]]"> - </cr-input> - <cr-button class="browse-button" on-click="onBrowseFile_" - disabled="[[!isOnline_]]"> - $i18n{selectDriverButtonText} - </cr-button> - </div> - <div class="eula" id="eulaUrl" hidden="[[!eulaUrl_]]"> - <a href="[[eulaUrl_]]" target="_blank">$i18n{printerEulaNotice}</a> - </div> + <template id="makeAndModelSection" is="dom-if" + if="[[!isAutoconfPrinter_(pendingPrinter_.*)]]"> + <div class="settings-box two-line"> + <cr-searchable-drop-down items="[[manufacturerList]]" + id="printerPPDManufacturer" + label="$i18n{printerManufacturer}" + value="{{pendingPrinter_.ppdManufacturer}}" + readonly="[[!isOnline_]]"> + </cr-searchable-drop-down> + </div> + <div class="settings-box two-line"> + <cr-searchable-drop-down items="[[modelList]]" + id="printerPPDModel" + label="$i18n{printerModel}" + value="{{pendingPrinter_.ppdModel}}" + readonly="[[!isOnline_]]"> + </cr-searchable-drop-down> + </div> + <div id="ppdLabel" class="cr-form-field-label"> + <span>$i18n{selectDriver}</span> + <a href="$i18n{printingCUPSPrintPpdLearnMoreUrl}" target="_blank"> + $i18n{learnMore} + </a> + </div> + <div class="settings-box two-line"> + <cr-input class="browse-file-input" readonly tabindex="-1" + value="[[userPPD_]]" aria-labelledby="ppdLabel" + error-message="$i18n{selectDriverErrorMessage}" + invalid="[[invalidPPD_]]"> + </cr-input> + <cr-button class="browse-button" on-click="onBrowseFile_" + disabled="[[!isOnline_]]"> + $i18n{selectDriverButtonText} + </cr-button> + </div> + <div class="eula" id="eulaUrl" hidden="[[!eulaUrl_]]"> + <a href="[[eulaUrl_]]" target="_blank">$i18n{printerEulaNotice}</a> + </div> + </template> </div> <div slot="dialog-buttons"> <cr-button class="cancel-button" on-click="onCancelTap_"> diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js index 2832048cf28..7f78d1dfb77 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js @@ -125,14 +125,13 @@ Polymer({ 'onModelChanged_(pendingPrinter_.ppdModel)', ], - /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */ - networkConfigProxy_: null, + /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ + networkConfig_: null, /** @override */ created: function() { - this.networkConfigProxy_ = - network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceRemote(); }, /** @override */ @@ -291,12 +290,20 @@ Polymer({ }, /** + * @return {boolean} Whether the current printer was auto configured. + * @private + */ + isAutoconfPrinter_: function() { + return this.pendingPrinter_.printerPpdReference.autoconf; + }, + + /** * @return {boolean} Whether the Save button is enabled. * @private */ canSavePrinter_: function() { return this.printerInfoChanged_ && - (this.isPrinterValid() || !this.isOnline_); + (this.isPrinterConfigured_() || !this.isOnline_); }, /** @@ -397,17 +404,20 @@ Polymer({ }, /** - * Returns true if the printer has valid name, address, and PPD. + * Returns true if the printer has valid name, address, and valid PPD or was + * auto-configured. * @return {boolean} + * @private */ - isPrinterValid: function() { + isPrinterConfigured_: function() { return settings.printing.isNameAndAddressValid(this.pendingPrinter_) && - settings.printing.isPPDInfoValid( - this.pendingPrinter_.ppdManufacturer, this.pendingPrinter_.ppdModel, - this.pendingPrinter_.printerPPDPath); + (this.isAutoconfPrinter_() || + settings.printing.isPPDInfoValid( + this.pendingPrinter_.ppdManufacturer, + this.pendingPrinter_.ppdModel, + this.pendingPrinter_.printerPPDPath)); }, - /** * Helper function to copy over modified fields to activePrinter. * @private @@ -431,7 +441,7 @@ Polymer({ * @private */ refreshNetworks_: function() { - this.networkConfigProxy_ + this.networkConfig_ .getNetworkStateList({ filter: chromeos.networkConfig.mojom.FilterType.kActive, networkType: chromeos.networkConfig.mojom.NetworkType.kAll, diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html index 428055b1b0f..7d6bf1824d2 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html @@ -8,10 +8,20 @@ <dom-module id="settings-cups-nearby-printers"> <template> - <style include="settings-shared"></style> + <style include="settings-shared"> + #noPrinterMessage { + margin-inline-start: 60px; + margin-top: 20px; + } + </style> <settings-cups-printers-entry-list printers="[[nearbyPrinters_]]" search-term="[[searchTerm]]"> </settings-cups-printers-entry-list> + <div class="secondary" id="noPrinterMessage" + hidden="[[!shouldShowNoNearbyPrinterMessage_(searchTerm, + nearbyPrinters_)]]"> + $i18n{noPrinterNearbyMessage} + </div> </template> <script src="cups_nearby_printers.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js index 76652d815cd..aa4912c4010 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js @@ -93,8 +93,10 @@ Polymer({ settings.CupsPrintersBrowserProxyImpl.getInstance() .addDiscoveredPrinter(item.printerInfo.printerId) - .then(this.onAddNearbyPrintersSucceeded_.bind(this, - item.printerInfo.printerName)); + .then( + this.onAddNearbyPrintersSucceeded_.bind(this, + item.printerInfo.printerName), + this.onAddNearbyPrinterFailed_.bind(this)); }, /** @@ -114,7 +116,7 @@ Polymer({ }, /** - * Handler for addDiscoveredPrinter. + * Handler for addDiscoveredPrinter success. * @param {string} printerName * @param {!PrinterSetupResult} result * @private @@ -123,5 +125,25 @@ Polymer({ this.fire( 'show-cups-printer-toast', {resultCode: result, printerName: printerName}); + }, + + /** + * Handler for addDiscoveredPrinter failure. + * @param {*} printer + * @private + */ + onAddNearbyPrinterFailed_: function(printer) { + this.fire( + 'show-cups-printer-toast', + {resultCode: PrinterSetupResult.PRINTER_UNREACHABLE, + printerName: printer.printerName}); + }, + + /** + * @return {boolean} Returns true if noPrinterMessage should be visible. + * @private + */ + shouldShowNoNearbyPrinterMessage_: function() { + return !this.searchTerm && !this.nearbyPrinters_.length; } });
\ No newline at end of file diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js index 1d8487bf254..d2367b61c3b 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js @@ -15,6 +15,8 @@ let PrinterListEntry; * These values correspond to the different types of printers available. Refer * to cups_printer_management.md for more information about the different * categories of printers. + * + * The types are numbered in desired sorting order for display. */ const PrinterType = { SAVED: 0, diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html index 7f23152c39a..6777282b161 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html @@ -3,6 +3,7 @@ <link rel="import" href="chrome://resources/cr_components/chromeos/network/mojo_interface_provider.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html"> <link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html"> <link rel="import" href="chrome://resources/html/action_link.html"> @@ -10,20 +11,22 @@ <link rel="import" href="chrome://resources/html/assert.html"> <link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html"> <link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> <link rel="import" href="cups_add_printer_dialog.html"> <link rel="import" href="cups_edit_printer_dialog.html"> <link rel="import" href="cups_printer_shared_css.html"> <link rel="import" href="cups_printers_list.html"> <link rel="import" href="cups_saved_printers.html"> <link rel="import" href="cups_nearby_printers.html"> +<link rel="import" href="../route.html"> <dom-module id="settings-cups-printers"> <template> - <style include="cups-printer-shared action-link"> + <style include="cups-printer-shared action-link iron-flex + iron-flex-alignment"> .custom-list-item { - align-items: center; border-bottom: var(--cr-separator-line); - display: flex; min-height: var(--settings-row-min-height); } @@ -42,6 +45,25 @@ flex: 1; } + #addManualPrinterIcon { + --iron-icon-fill-color: rgb(138, 180, 248); + --cr-icon-button-margin-end: 0; + } + + #cloudOffIcon { + --iron-icon-fill-color: rgb(95, 99, 104); + margin-top: 10px; + } + + #connectionMessage { + padding-inline-start: 20px; + } + + #noConnectivityContentContainer { + border-bottom: var(--cr-separator-line); + padding-inline-start: 20px; + } + #noSearchResultsMessage { color: var(--md-loading-message-color); font-size: 16px; @@ -49,6 +71,16 @@ margin-top: 80px; text-align: center; } + + #savedPrintersContainer { + border-bottom: var(--cr-separator-line); + } + + :host(:not([can-add-printer])) #addPrinterSection, + :host(:not([can-add-printer])) #nearbyPrinters { + opacity: var(--cr-disabled-opacity); + pointer-events: none; + } </style> <template is="dom-if" if="[[!enableUpdatedUi_]]"> @@ -58,11 +90,11 @@ <a href="$i18n{printingCUPSPrintLearnMoreUrl}" target="_blank"> $i18n{learnMore} </a> - <div class="secondary" hidden="[[canAddPrinter_]]"> + <div class="secondary" hidden="[[canAddPrinter]]"> $i18n{requireNetworkMessage} </div> </div> - <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter_, + <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter, prefs.native_printing.user_native_printers_allowed.value)]]"> <cr-policy-pref-indicator pref="[[prefs.native_printing.user_native_printers_allowed]]" @@ -71,7 +103,7 @@ </template> <cr-button class="action-button" id="addPrinter" on-click="onAddPrinterTap_" - disabled="[[!addPrinterButtonActive_(canAddPrinter_, + disabled="[[!addPrinterButtonActive_(canAddPrinter, prefs.native_printing.user_native_printers_allowed.value)]]"> $i18n{addCupsPrinter} </cr-button> @@ -80,32 +112,52 @@ active-printer="{{activePrinter}}" search-term="[[searchTerm]]"> </settings-cups-printers-list> + + <div id="noSearchResultsMessage" + hidden="[[!showNoSearchResultsMessage_(searchTerm)]]"> + $i18n{noSearchResults} + </div> </template> <template is="dom-if" if="[[enableUpdatedUi_]]"> - <div class="settings-box first"> - <div class="start"> - <span>$i18n{savedPrintersTitle}</span> + <template is="dom-if" if="[[!canAddPrinter]]"> + <div id="noConnectivityContentContainer" + class="layout horizontal padded"> + <iron-icon id="cloudOffIcon" icon="settings20:cloud-off"></iron-icon> + <div id="connectionMessage" class="layout vertical"> + <div>$i18n{noInternetConnection}</div> + <div class="secondary">$i18n{checkNetworkAndTryAgain}</div> + </div> </div> - </div> + </template> + + <template is="dom-if" + if="[[doesAccountHaveSavedPrinters_(savedPrinters_)]]" restamp> + <div id="savedPrintersContainer"> + <div class="settings-box first"> + <div class="start"> + <span>$i18n{savedPrintersTitle}</span> + </div> + </div> - <settings-cups-saved-printers id="savedPrinters" - active-printer="{{activePrinter}}" - search-term="[[searchTerm]]"> - </settings-cups-saved-printers> + <settings-cups-saved-printers id="savedPrinters" + active-printer="{{activePrinter}}" + saved-printers="[[savedPrinters_]]" + search-term="[[searchTerm]]"> + </settings-cups-saved-printers> + </div> + </template> <div class="padded first" id="nearbyPrinters"> <div>$i18n{nearbyPrintersListTitle}</div> <span class="secondary"> $i18n{nearbyPrintersListDescription} </span> - <a href="$i18n{printingCUPSPrintLearnMoreUrl}" target="_blank"> + <a href="$i18n{printingCUPSPrintLearnMoreUrl}" + target="_blank"> $i18n{learnMore} </a> - <div class="secondary" hidden="[[canAddPrinter_]]"> - $i18n{requireNetworkMessage} - </div> - <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter_, + <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter, prefs.native_printing.user_native_printers_allowed.value)]]"> <cr-policy-pref-indicator pref="[[prefs.native_printing.user_native_printers_allowed]]" @@ -115,20 +167,22 @@ </div> <div id="addPrinterSection"> - <div class="custom-list-item"> + <div class="layout horizontal center custom-list-item"> <div id="addPrinterText">$i18n{addCupsPrinter}</div> - <cr-button class="action-button" id="addPrinter" + <cr-icon-button class="action-button" id="addManualPrinterIcon" + iron-icon="settings20:printer-add" on-click="onAddPrinterTap_" - disabled="[[!addPrinterButtonActive_(canAddPrinter_, - prefs.native_printing.user_native_printers_allowed.value)]]"> - $i18n{addCupsPrinter} - </cr-button> + disabled="[[!addPrinterButtonActive_(canAddPrinter, + prefs.native_printing.user_native_printers_allowed.value)]]" + title="$i18n{addCupsPrinter}"> + </cr-icon-button> </div> </div> - - <settings-cups-nearby-printers search-term="[[searchTerm]]" - active-printer="{{activePrinter}}"> - </settings-cups-nearby-printers> + <template is="dom-if" if="[[canAddPrinter]]" restamp> + <settings-cups-nearby-printers search-term="[[searchTerm]]" + active-printer="{{activePrinter}}"> + </settings-cups-nearby-printers> + </template> </template> <settings-cups-add-printer-dialog id="addPrinterDialog" @@ -143,11 +197,6 @@ </settings-cups-edit-printer-dialog> </template> - <div id="noSearchResultsMessage" - hidden="[[!showNoSearchResultsMessage_(searchTerm)]]"> - $i18n{noSearchResults} - </div> - <cr-toast id="errorToast" duration="3000"> <div class="error-message" id="addPrinterDoneMessage"> [[addPrinterResultText_]] 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 7e41ed47507..21109350ab6 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js @@ -14,6 +14,7 @@ Polymer({ behaviors: [ CrNetworkListenerBehavior, + settings.RouteObserverBehavior, WebUIListenerBehavior, ], @@ -36,8 +37,20 @@ Polymer({ type: String, }, - /** @private */ - canAddPrinter_: Boolean, + /** This is also used as an attribute for css styling. */ + canAddPrinter: { + type: Boolean, + reflectToAttribute: true, + }, + + /** + * @type {!Array<!PrinterListEntry>} + * @private + */ + savedPrinters_: { + type: Array, + value: () => [], + }, /** @private */ showCupsEditPrinterDialog_: Boolean, @@ -65,19 +78,19 @@ Polymer({ 'openManufacturerModelDialogForSpecifiedPrinter_', }, - /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */ - networkConfigProxy_: null, + /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */ + networkConfig_: null, /** @override */ created: function() { - this.networkConfigProxy_ = + this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance() - .getMojoServiceProxy(); + .getMojoServiceRemote(); }, /** @override */ attached: function() { - this.networkConfigProxy_ + this.networkConfig_ .getNetworkStateList({ filter: chromeos.networkConfig.mojom.FilterType.kActive, networkType: chromeos.networkConfig.mojom.NetworkType.kAll, @@ -90,9 +103,6 @@ Polymer({ if (this.enableUpdatedUi_) { return; } - - this.addWebUIListener( - 'on-printers-changed', this.printersChanged_.bind(this)); }, /** @override */ @@ -100,6 +110,21 @@ Polymer({ this.updateCupsPrintersList_(); }, + + /** + * settings.RouteObserverBehavior + * @param {!settings.Route} route + * @protected + */ + currentRouteChanged: function(route) { + if (route != settings.routes.CUPS_PRINTERS) { + cr.removeWebUIListener('on-printers-changed'); + return; + } + cr.addWebUIListener( + 'on-printers-changed', this.onPrintersChanged_.bind(this)); + }, + /** * CrosNetworkConfigObserver impl * @param {!Array<chromeos.networkConfig.mojom.NetworkStateProperties>} @@ -107,8 +132,12 @@ Polymer({ * @private */ onActiveNetworksChanged: function(networks) { - this.canAddPrinter_ = networks.some(function(network) { - return OncMojo.connectionStateIsConnected(network.connectionState); + this.canAddPrinter = networks.some(function(network) { + // Note: Check for kOnline rather than using + // OncMojo.connectionStateIsConnected() since the latter could return true + // for networks without connectivity (e.g., captive portals). + return network.connectionState == + chromeos.networkConfig.mojom.ConnectionStateType.kOnline; }); }, @@ -123,25 +152,23 @@ Polymer({ const printerName = event.detail.printerName; switch (event.detail.resultCode) { case PrinterSetupResult.SUCCESS: - if (this.enableUpdatedUi_) { - this.$$('#savedPrinters').updateSavedPrintersList(); - } else { - this.updateCupsPrintersList_(); - } + this.updateCupsPrintersList_(); this.addPrinterResultText_ = loadTimeData.getStringF('printerAddedSuccessfulMessage', printerName); break; case PrinterSetupResult.EDIT_SUCCESS: - if (this.enableUpdatedUi_) { - this.$$('#savedPrinters').updateSavedPrintersList(); - } else { - this.updateCupsPrintersList_(); - } + this.updateCupsPrintersList_(); this.addPrinterResultText_ = loadTimeData.getStringF('printerEditedSuccessfulMessage', printerName); break; + case PrinterSetupResult.PRINTER_UNREACHABLE: + if (this.enableUpdatedUi_) { + this.addPrinterResultText_ = + loadTimeData.getStringF('printerUnavailableMessage', printerName); + break; + } default: assertNotReached(); } @@ -163,15 +190,22 @@ Polymer({ updateCupsPrintersList_: function() { settings.CupsPrintersBrowserProxyImpl.getInstance() .getCupsPrintersList() - .then(this.printersChanged_.bind(this)); + .then(this.onPrintersChanged_.bind(this)); }, /** * @param {!CupsPrintersList} cupsPrintersList * @private */ - printersChanged_: function(cupsPrintersList) { - this.printers = cupsPrintersList.printerList; + onPrintersChanged_: function(cupsPrintersList) { + if (this.enableUpdatedUi_) { + this.savedPrinters_ = cupsPrintersList.printerList.map( + printer => /** @type {!PrinterListEntry} */({ + printerInfo: printer, + printerType: PrinterType.SAVED})); + } else { + this.printers = cupsPrintersList.printerList; + } }, /** @private */ @@ -181,7 +215,9 @@ Polymer({ /** @private */ onAddPrinterDialogClose_: function() { - cr.ui.focusWithoutInk(assert(this.$$('#addPrinter'))); + cr.ui.focusWithoutInk(assert( + this.enableUpdatedUi_ ? this.$$('#addManualPrinterIcon') + : this.$$('#addPrinter'))); }, /** @private */ @@ -220,5 +256,13 @@ Polymer({ addPrinterButtonActive_: function( connectedToNetwork, userNativePrintersAllowed) { return connectedToNetwork && userNativePrintersAllowed; + }, + + /** + * @return {boolean} Whether |savedPrinters_| is empty. + * @private + */ + doesAccountHaveSavedPrinters_: function() { + return !!this.savedPrinters_.length; } }); diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html index 164a8c5e637..c8df839a0ee 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html @@ -1,7 +1,6 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="cups_printer_types.html"> <link rel="import" href="cups_printers_browser_proxy.html"> <link rel="import" href="../settings_shared_css.html"> @@ -29,17 +28,16 @@ </template> <template is="dom-if" if="[[isDiscoveredPrinter_(printerEntry.printerType)]]"> - <cr-button class="action-button" + <cr-button id="setupPrinterButton" on-click="onOpenManufacturerModelDialogTap_"> - $i18n{configurePrinter} + $i18n{setupPrinter} </cr-button> </template> <template is="dom-if" if="[[isAutomaticPrinter_(printerEntry.printerType)]]"> - <cr-icon-button class="icon-add-circle" - on-click="onAddAutomaticPrinterTap_" - title="$i18n{moreActions}"> - </cr-icon-button> + <cr-button id="savePrinterButton" on-click="onAddAutomaticPrinterTap_"> + $i18n{savePrinter} + </cr-button> </template> </div> </template> diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html index fdb85be62b1..bf9fbaf1f9f 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html @@ -19,6 +19,12 @@ iron-list { flex: 1 1 auto; } + + #no-search-results { + margin-top: 20px; + text-align: center; + } + </style> <iron-list class="list-frame vertical-list" id="printerEntryList" items="[[filteredPrinters_]]"> @@ -27,6 +33,10 @@ </settings-cups-printers-entry> </template> </iron-list> + <div id="no-search-results" + hidden="[[!showNoSearchResultsMessage_]]"> + $i18n{noSearchResults} + </div> </template> <script src="cups_printers_entry_list.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js index 6037c31aecc..3fe5f69bd12 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js @@ -37,7 +37,20 @@ Polymer({ * Search term for filtering |printers|. * @type {string} */ - searchTerm: String, + searchTerm: { + type: String, + value: '', + }, + + /** + * Whether to show the no search results message. + * @type {boolean} + * @private + */ + showNoSearchResultsMessage_: { + type: Boolean, + value: false, + }, }, observers: [ @@ -59,13 +72,30 @@ Polymer({ item =>this.matchesSearchTerm_(item.printerInfo,this.searchTerm)) : this.printers.slice(); - updatedPrinters.sort((first, second) => { - return settings.printing.alphabeticalSort( - first.printerInfo, second.printerInfo); - }); + updatedPrinters.sort(this.sortPrinters_); this.updateList('filteredPrinters_', printer => printer.printerInfo, updatedPrinters); + + this.showNoSearchResultsMessage_ = + !!this.searchTerm && !this.filteredPrinters_.length; + }, + + + /** + * @param {!PrinterListEntry} first + * @param {!PrinterListEntry} second + * @return {number} + * @private + */ + sortPrinters_: function(first, second) { + if (first.printerType == second.printerType) { + return settings.printing.alphabeticalSort( + first.printerInfo, second.printerInfo); + } + + // PrinterType sort order maintained in cups_printer_types.js + return first.printerType - second.printerType; }, /** diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html index b343992525d..1bb09c08fc0 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html @@ -19,7 +19,7 @@ </cr-action-menu> <style include="settings-shared"></style> - <settings-cups-printers-entry-list printers="[[savedPrinters_]]" + <settings-cups-printers-entry-list printers="[[savedPrinters]]" search-term="[[searchTerm]]"> </settings-cups-printers-entry-list> </template> diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js index a44b197232f..85ef694f1ec 100644 --- a/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js +++ b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js @@ -14,17 +14,13 @@ Polymer({ ], properties: { - /** - * @type {!Array<!PrinterListEntry>} - * @private - */ - savedPrinters_: { + /** @type {!Array<!PrinterListEntry>} */ + savedPrinters: { type: Array, - value: () => [], }, /** - * Search term for filtering |savedPrinters_|. + * Search term for filtering |savedPrinters|. * @type {string} */ searchTerm: { @@ -60,35 +56,6 @@ Polymer({ this.browserProxy_ = settings.CupsPrintersBrowserProxyImpl.getInstance(); }, - /** @override */ - ready: function() { - this.addWebUIListener( - 'on-printers-changed', this.printersChanged_.bind(this)); - this.updateSavedPrintersList(); - }, - - /** Public function to update the printer list. */ - updateSavedPrintersList: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance() - .getCupsPrintersList() - .then(this.printersChanged_.bind(this)); - }, - - /** - * @param {!CupsPrintersList} cupsPrintersList - * @private - */ - printersChanged_: function(cupsPrintersList) { - if (!cupsPrintersList) { - return; - } - - this.savedPrinters_ = cupsPrintersList.printerList.map( - printer => /** @type {!PrinterListEntry} */({ - printerInfo: printer, - printerType: PrinterType.SAVED})); - }, - /** * @param {!CustomEvent<{target: !HTMLElement, item: !PrinterListEntry}>} e * @private @@ -96,10 +63,10 @@ Polymer({ onOpenActionMenu_: function(e) { const item = /** @type {!PrinterListEntry} */(e.detail.item); this.activePrinterListEntryIndex_ = - this.savedPrinters_.findIndex( + this.savedPrinters.findIndex( printer => printer.printerInfo == item.printerInfo); this.activePrinter = - this.get(['savedPrinters_', this.activePrinterListEntryIndex_]) + this.get(['savedPrinters', this.activePrinterListEntryIndex_]) .printerInfo; const target = /** @type {!HTMLElement} */ (e.detail.target); @@ -115,7 +82,6 @@ Polymer({ /** @private */ onRemoveTap_: function() { - this.splice('savedPrinters_', this.activePrinterListEntryIndex_, 1); this.browserProxy_.removeCupsPrinter( this.activePrinter.printerId, this.activePrinter.printerName); this.activePrinter = null; diff --git a/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn b/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn index a77c34ad919..028266d95fb 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn +++ b/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn @@ -9,6 +9,7 @@ js_type_check("closure_compile") { ":personalization_options", ":privacy_page", ":privacy_page_browser_proxy", + ":security_keys_bio_enroll_dialog", ":security_keys_credential_management_dialog", ":security_keys_reset_dialog", ":security_keys_set_pin_dialog", @@ -76,6 +77,7 @@ js_library("security_keys_subpage") { js_library("security_keys_set_pin_dialog") { deps = [ ":security_keys_browser_proxy", + "//third_party/polymer/v1_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer-extracted", "//ui/webui/resources/js:i18n_behavior", ] externs_list = [ "$externs_path/settings_private.js" ] @@ -103,3 +105,13 @@ js_library("security_keys_reset_dialog") { ] externs_list = [ "$externs_path/settings_private.js" ] } + +js_library("security_keys_bio_enroll_dialog") { + deps = [ + ":security_keys_browser_proxy", + ":security_keys_pin_field", + "//ui/webui/resources/cr_elements/cr_fingerprint:cr_fingerprint_progress_arc", + "//ui/webui/resources/js:i18n_behavior", + ] + externs_list = [ "$externs_path/settings_private.js" ] +} 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 283cfb4c790..1ad29354d5c 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html @@ -396,23 +396,21 @@ </category-setting-exceptions> </settings-subpage> </template> - <template is="dom-if" if="[[enableSensorsContentSetting_]]" no-search> - <template is="dom-if" route-path="/content/sensors" no-search> - <settings-subpage page-title="$i18n{siteSettingsSensors}" - search-label="$i18n{siteSettingsAllSitesSearch}" - search-term="{{searchFilter_}}"> - <category-default-setting - toggle-off-label="$i18n{siteSettingsSensorsBlock}" - toggle-on-label="$i18n{siteSettingsSensorsAllow}" - category="{{ContentSettingsTypes.SENSORS}}"> - </category-default-setting> - <category-setting-exceptions - category="{{ContentSettingsTypes.SENSORS}}" read-only-list - block-header="$i18n{siteSettingsBlock}" - search-filter="[[searchFilter_]]"> - </category-setting-exceptions> - </settings-subpage> - </template> + <template is="dom-if" route-path="/content/sensors" no-search> + <settings-subpage page-title="$i18n{siteSettingsSensors}" + search-label="$i18n{siteSettingsAllSitesSearch}" + search-term="{{searchFilter_}}"> + <category-default-setting + toggle-off-label="$i18n{siteSettingsSensorsBlock}" + toggle-on-label="$i18n{siteSettingsSensorsAllow}" + category="{{ContentSettingsTypes.SENSORS}}"> + </category-default-setting> + <category-setting-exceptions + category="{{ContentSettingsTypes.SENSORS}}" read-only-list + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> + </category-setting-exceptions> + </settings-subpage> </template> <template is="dom-if" route-path="/content/notifications" no-search> <settings-subpage page-title="$i18n{siteSettingsCategoryNotifications}" @@ -557,6 +555,25 @@ </settings-subpage> </template> </template> + <template is="dom-if" if="[[enableNativeFileSystemWriteContentSetting_]]"> + <template is="dom-if" route-path="/content/filesystem" no-search> + <settings-subpage + page-title="$i18n{siteSettingsNativeFileSystemWrite}"> + <category-default-setting + toggle-off-label="$i18n{siteSettingsNativeFileSystemWriteBlock}" + toggle-on-label= + "$i18n{siteSettingsNativeFileSystemWriteAskRecommended}" + category="{{ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE}}"> + </category-default-setting> + <category-setting-exceptions + category="{{ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE}}" + read-only-list + block-header="$i18n{siteSettingsBlock}" + search-filter="[[searchFilter_]]"> + </category-setting-exceptions> + </settings-subpage> + </template> + </template> <template is="dom-if" route-path="/content/siteDetails" no-search> <settings-subpage page-title="[[pageTitle]]"> <site-details 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 49ea7f9dae2..57b42d06dee 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js +++ b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js @@ -119,15 +119,6 @@ Polymer({ }, /** @private */ - enableSensorsContentSetting_: { - type: Boolean, - readOnly: true, - value: function() { - return loadTimeData.getBoolean('enableSensorsContentSetting'); - } - }, - - /** @private */ enableExperimentalWebPlatformFeatures_: { type: Boolean, value: function() { @@ -152,6 +143,15 @@ Polymer({ } }, + /** @private */ + enableNativeFileSystemWriteContentSetting_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean( + 'enableNativeFileSystemWriteContentSetting'); + } + }, + /** @private {!Map<string, string>} */ focusConfig_: { type: Object, diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html new file mode 100644 index 00000000000..7569eead29a --- /dev/null +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html @@ -0,0 +1,118 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/html/assert.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> +<link rel="import" href="chrome://resources/html/i18n_behavior.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html"> +<link rel="import" href="../i18n_setup.html"> +<link rel="import" href="../settings_shared_css.html"> +<link rel="import" href="../site_favicon.html"> +<link rel="import" href="security_keys_browser_proxy.html"> +<link rel="import" href="security_keys_pin_field.html"> + +<dom-module id="settings-security-keys-bio-enroll-dialog"> + <template> + <style include="settings-shared"> + #header { + display: flex; + } + + iron-icon { + padding-inline-end: 12px; + } + + .name { + flex: 3; + } + + #dialog::part(body-container) { + overflow-y: hidden; + } + </style> + + <cr-dialog id="dialog" close-text="$i18n{cancel}" ignore-popstate + on-close="onDialogClosed_"> + <div slot="title">$i18n{securityKeysBioEnrollmentDialogTitle}</div> + + <div slot="body"> + <iron-pages attr-for-selected="id" selected="[[dialogPage_]]" + on-iron-select="onIronSelect_"> + <div id="initial"> + <p>$i18n{securityKeysBioEnrollmentTouch}</p> + <paper-spinner-lite style="padding-bottom: 16px;" active> + </paper-spinner-lite> + </div> + + <div id="pinPrompt"> + <p>$i18n{securityKeysBioEnrollmentPinPrompt}</p> + <settings-security-keys-pin-field id="pin"> + </settings-security-keys-pin-field> + </div> + + <div id="enrollments"> + <div class="settings-box first"> + <p class="start" hidden="[[hasSome_(enrollments_)]]"> + $i18n{securityKeysBioEnrollmentNoEnrollments}</p> + <p class="start" hidden="[[!hasSome_(enrollments_)]]"> + $i18n{securityKeysBioEnrollmentLabel}</p> + <cr-button id="addButton" on-click="addButtonClick_" + hidden="[[!addButtonVisible_]]" + class="secondary-button header-aligned-button"> + $i18n{add} + </cr-button> + </div> + <div id="container"> + <iron-list id="enrollmentList" items="[[enrollments_]]" + class="cr-separators"> + <template> + <div class="list-item"> + <iron-icon icon="cr-fingerprint-icon:enrollment-done"> + </iron-icon> + <div class="name" aria-label="[[item.name]]"> + [[item.name]] + </div> + <cr-icon-button class="icon-clear" + aria-label="i18n{securityKeysBioEnrollmentDelete}" + on-click="deleteEnrollment_" + disabled="[[deleteInProgress_]]"> + </cr-icon-button> + </div> + </template> + </iron-list> + </div> + </div> + + <div id="enroll"> + <p>$i18n{securityKeysBioEnrollmentEnrollingLabel}</p> + <cr-fingerprint-progress-arc id="arc"></cr-fingerprint-progress-arc> + </div> + + <div id="error">[[errorMsg_]]</div> + </iron-pages> + </div> + + <div slot="button-container"> + <cr-button id="cancelButton" class="cancel-button" + on-click="cancel_" hidden="[[!cancelButtonVisible_]]"> + $i18n{cancel} + </cr-button> + <cr-button id="okButton" class="action-button" + on-click="okButtonClick_" hidden="[[!okButtonVisible_]]"> + $i18n{ok} + </cr-button> + <cr-button id="doneButton" class="action-button" + on-click="done_" hidden="[[!doneButtonVisible_]]"> + $i18n{done} + </cr-button> + </div> + </cr-dialog> + + </template> + <script src="security_keys_bio_enroll_dialog.js"></script> +</dom-module> diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.js new file mode 100644 index 00000000000..1f251c65aa4 --- /dev/null +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.js @@ -0,0 +1,273 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(function() { +'use strict'; + +/** + * @fileoverview 'settings-security-keys-bio-enroll-dialog' is a dialog for + * listing, adding, renaming, and deleting biometric enrollments stored on a + * security key. + */ +Polymer({ + is: 'settings-security-keys-bio-enroll-dialog', + + behaviors: [ + I18nBehavior, + WebUIListenerBehavior, + ], + + properties: { + /** @private */ + addButtonVisible_: Boolean, + + /** @private */ + cancelButtonVisible_: Boolean, + + /** @private */ + deleteInProgress_: Boolean, + + /** + * The ID of the element currently shown in the dialog. + * @private + */ + dialogPage_: { + type: String, + value: 'initial', + observer: 'dialogPageChanged_', + }, + + /** @private */ + doneButtonVisible_: Boolean, + + /** + * The list of enrollments displayed. + * @private {!Array<!Enrollment>} + */ + enrollments_: Array, + + /** @private */ + okButtonVisible_: Boolean, + }, + + /** @private {?settings.SecurityKeysBioEnrollProxyImpl} */ + browserProxy_: null, + + /** @private */ + maxSamples_: Number, + + /** @override */ + attached: function() { + this.$.dialog.showModal(); + this.addWebUIListener( + 'security-keys-bio-enroll-error', this.onError_.bind(this)); + this.addWebUIListener( + 'security-keys-bio-enroll-status', this.onEnrolling_.bind(this)); + this.browserProxy_ = settings.SecurityKeysBioEnrollProxyImpl.getInstance(); + this.browserProxy_.startBioEnroll().then( + this.collectPIN_.bind(this), () => {}); + }, + + /** @private */ + collectPIN_: function() { + this.dialogPage_ = 'pinPrompt'; + this.$.pin.focus(); + }, + + /** + * @private + * @param {string} error + */ + onError_: function(error) { + this.errorMsg_ = error; + this.dialogPage_ = 'error'; + }, + + /** @private */ + submitPIN_: function() { + if (!this.$.pin.validate()) { + return; + } + this.browserProxy_.providePIN(this.$.pin.value).then((retries) => { + if (retries != null) { + this.$.pin.showIncorrectPINError(retries); + return; + } + + this.browserProxy_.enumerateEnrollments().then( + this.onEnrollments_.bind(this)); + }, () => {}); + }, + + /** + * @private + * @param {!Array<!Enrollment>} enrollments + */ + onEnrollments_: function(enrollments) { + this.enrollments_ = enrollments; + this.$.enrollmentList.fire('iron-resize'); + this.dialogPage_ = 'enrollments'; + }, + + /** @private */ + dialogPageChanged_: function() { + switch (this.dialogPage_) { + case 'initial': + this.addButtonVisible_ = false; + this.cancelButtonVisible_ = true; + this.okButtonVisible_ = false; + this.doneButtonVisible_ = false; + break; + case 'pinPrompt': + this.addButtonVisible_ = false; + this.cancelButtonVisible_ = true; + this.okButtonVisible_ = true; + this.doneButtonVisible_ = false; + break; + case 'enrollments': + this.addButtonVisible_ = true; + this.cancelButtonVisible_ = false; + this.okButtonVisible_ = false; + this.doneButtonVisible_ = true; + break; + case 'enroll': + this.addButtonVisible_ = false; + this.cancelButtonVisible_ = true; + this.okButtonVisible_ = false; + this.doneButtonVisible_ = false; + break; + case 'error': + this.addButtonVisible_ = false; + this.cancelButtonVisible_ = false; + this.okButtonVisible_ = false; + this.doneButtonVisible_ = true; + break; + default: + assertNotReached(); + } + this.fire('bio-enroll-dialog-ready-for-testing'); + }, + + /** @private */ + addButtonClick_: function() { + assert(this.dialogPage_ == 'enrollments'); + + this.maxSamples_ = -1; // Reset maxSamples_ before enrolling starts. + this.$.arc.reset(); + this.cancelButtonVisible_ = true; + this.okButtonVisible_ = false; + + this.dialogPage_ = 'enroll'; + this.browserProxy_.startEnrolling().then( + this.onEnrolling_.bind(this), () => {}); + }, + + /** + * @private + * @param {!EnrollmentStatus} response + */ + onEnrolling_: function(response) { + if (this.maxSamples_ == -1 && response.status != null) { + if (response.status == 0) { + // If the first sample is valid, remaining is one less than max samples + // required. + this.maxSamples_ = response.remaining + 1; + } else { + // If the first sample failed for any reason (timed out, key full, etc), + // the remaining number of samples is the max samples required. + this.maxSamples_ = response.remaining; + } + } + // If 0 samples remain, the enrollment has finished in some state. + // Currently not checking response['code'] for an error. + this.$.arc.setProgress( + 100 - (100 * (response.remaining + 1) / this.maxSamples_), + 100 - (100 * response.remaining / this.maxSamples_), + response.remaining == 0); + if (response.remaining == 0) { + this.cancelButtonVisible_ = false; + this.okButtonVisible_ = true; + } + this.fire('bio-enroll-dialog-ready-for-testing'); + }, + + /** @private */ + okButtonClick_: function() { + switch (this.dialogPage_) { + case 'pinPrompt': + this.submitPIN_(); + break; + case 'enroll': + this.browserProxy_.enumerateEnrollments().then( + this.onEnrollments_.bind(this), () => {}); + break; + default: + assertNotReached(); + } + }, + + /** @private */ + cancel_: function() { + if (this.dialogPage_ == 'enroll') { + this.browserProxy_.cancelEnrollment().then( + this.cancelEnroll_.bind(this), () => {}); + } else { + this.done_(); + } + }, + + /** @private */ + cancelEnroll_: function() { + // Cancelling from the enrolling screen redirects to the enrollments + // list, so request another enumeration to display. + this.browserProxy_.enumerateEnrollments().then( + this.onEnrollments_.bind(this), () => {}); + }, + + /** @private */ + done_: function() { + this.$.dialog.close(); + }, + + /** @private */ + onDialogClosed_: function() { + this.browserProxy_.close(); + }, + + /** + * @private + * @param {!Event} e + */ + onIronSelect_: function(e) { + // Prevent this event from bubbling since it is unnecessarily triggering the + // listener within settings-animated-pages. + e.stopPropagation(); + }, + + /** + * @private + * @param {?Array} list + * @return {boolean} true if the list exists and has items. + */ + hasSome_: function(list) { + return !!(list && list.length); + }, + + /** + * @private + * @param {!DomRepeatEvent} event + */ + deleteEnrollment_: function(event) { + if (this.deleteInProgress_) { + return; + } + this.deleteInProgress_ = true; + const enrollment = this.enrollments_[event.model.index]; + this.browserProxy_.deleteEnrollment(enrollment.id).then(enrollments => { + this.deleteInProgress_ = false; + this.onEnrollments_(enrollments); + }); + } +}); +})(); diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js index 0d6f5fb4ce3..00a55d9f52d 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js @@ -26,6 +26,31 @@ cr.exportPath('settings'); */ let Credential; +/** + * EnrollmentStatus represents the current status of an enrollment suboperation, + * where 'remaining' indicates the number of samples left, 'status' indicates + * the last enrollment status, and 'code' indicates the CtapDeviceResponseCode. + * For each enrollment sample, 'status' is set - when the enrollment operation + * reaches an end state, 'code' is set. A 'code' of CtapDeviceResponseCode 0 + * indicates successful enrollment. + * + * @typedef {{status: ?number, + * code: ?number, + * remaining: number}} + * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc + */ +let EnrollmentStatus; + +/** + * Enrollment represents a valid fingerprint template stored on a security key, + * which can be used in a user verification request. + * + * @typedef {{name: string, + * id: string}} + * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc + */ +let Enrollment; + cr.define('settings', function() { /** @interface */ class SecurityKeysPINBrowserProxy { @@ -118,6 +143,78 @@ cr.define('settings', function() { close() {} } + /** @interface */ + class SecurityKeysBioEnrollProxy { + /** + * Starts a biometric enrollment operation. + * + * Callers must listen to errors that can occur during this operation via a + * 'security-keys-bio-enrollment-error' WebUIListener. Values received via + * this listener are localized error strings. The WebListener may fire at + * any point during the operation (enrolling, deleting, etc) and when it + * fires, the operation must be considered terminated. + * + * @return {!Promise} resolves when the handler is ready for the + * authentcation PIN to be provided. + */ + startBioEnroll() {} + + /** + * Provides a PIN for a biometric enrollment operation. The startBioEnroll() + * Promise must have resolved before this method may be called. + * + * @return {!Promise<?number>} resolves with null if the PIN was correct, + * the number of retries remaining otherwise. + */ + providePIN(pin) {} + + /** + * Enumerates enrollments on the authenticator. A correct PIN must have + * previously been supplied via bioEnrollProvidePIN() before this method may + * be called. + * + * @return {!Promise<!Array<!Enrollment>>} + */ + enumerateEnrollments() {} + + /** + * Move the operation into enrolling mode, which instructs the authenticator + * to start sampling for touches. + * + * Callers must listen to status updates that will occur during this + * suboperation via a 'security-keys-bio-enroll-status' WebListener. Values + * received via this listener are DictionaryValues with two elements (see + * below). When the WebListener fires, the authenticator has either timed + * out waiting for a touch, or has successfully processed a touch. Any + * errors will fire the 'security-keys-bio-enrollment-error' WebListener. + * + * @return {!Promise<!EnrollmentStatus>} resolves when the enrollment + * operation is finished successfully. + */ + startEnrolling() {} + + /** + * Cancel an ongoing enrollment suboperation. This can safely be called at + * any time and only has an impact when the authenticator is currently + * sampling. + * + * @return {!Promise} resolves when the ongoing enrollment suboperation has + * been cancelled. + */ + cancelEnrollment() {} + + /** + * Deletes the enrollment with the given ID. + * + * @param {string} id + * @return {!Promise<!Array<!Enrollment>>} The remaining enrollments. + */ + deleteEnrollment(id) {} + + /** Cancels all outstanding operations. */ + close() {} + } + /** @implements {settings.SecurityKeysPINBrowserProxy} */ class SecurityKeysPINBrowserProxyImpl { /** @override */ @@ -182,11 +279,50 @@ cr.define('settings', function() { } } + /** @implements {settings.SecurityKeysBioEnrollProxy} */ + class SecurityKeysBioEnrollProxyImpl { + /** @override */ + startBioEnroll() { + return cr.sendWithPromise('securityKeyBioEnrollStart'); + } + + /** @override */ + providePIN(pin) { + return cr.sendWithPromise('securityKeyBioEnrollProvidePIN', pin); + } + + /** @override */ + enumerateEnrollments() { + return cr.sendWithPromise('securityKeyBioEnrollEnumerate'); + } + + /** @override */ + startEnrolling() { + return cr.sendWithPromise('securityKeyBioEnrollStartEnrolling'); + } + + /** @override */ + cancelEnrollment() { + return cr.sendWithPromise('securityKeyBioEnrollCancel'); + } + + /** @override */ + deleteEnrollment(id) { + return cr.sendWithPromise('securityKeyBioEnrollDelete', id); + } + + /** @override */ + close() { + return chrome.send('securityKeyBioEnrollClose'); + } + } + // The singleton instance_ is replaced with a test version of this wrapper // during testing. cr.addSingletonGetter(SecurityKeysPINBrowserProxyImpl); cr.addSingletonGetter(SecurityKeysCredentialBrowserProxyImpl); cr.addSingletonGetter(SecurityKeysResetBrowserProxyImpl); + cr.addSingletonGetter(SecurityKeysBioEnrollProxyImpl); return { SecurityKeysPINBrowserProxy: SecurityKeysPINBrowserProxy, @@ -196,5 +332,7 @@ cr.define('settings', function() { SecurityKeysCredentialBrowserProxyImpl, SecurityKeysResetBrowserProxy: SecurityKeysResetBrowserProxy, SecurityKeysResetBrowserProxyImpl: SecurityKeysResetBrowserProxyImpl, + SecurityKeysBioEnrollProxy: SecurityKeysBioEnrollProxy, + SecurityKeysBioEnrollProxyImpl: SecurityKeysBioEnrollProxyImpl, }; }); diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html index a67ac0a89bc..0045f54d6a2 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html @@ -1,5 +1,6 @@ <link rel="import" href="chrome://resources/html/polymer.html"> +<link rel="import" href="chrome://resources/html/assert.html"> <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html"> <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js index ce300e509eb..146f22674b3 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js @@ -166,6 +166,8 @@ Polymer({ this.confirmButtonVisible_ = false; this.closeButtonVisible_ = true; break; + default: + assertNotReached(); } this.fire('credential-management-dialog-ready-for-testing'); }, diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html index 2e6c0a4942f..94f201d1cf2 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html @@ -6,6 +6,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> <link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-announcer/iron-a11y-announcer.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html"> <link rel="import" href="../i18n_setup.html"> diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js index 4cadbca4e28..813d93e51d5 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js @@ -149,6 +149,10 @@ Polymer({ this.browserProxy_ = settings.SecurityKeysPINBrowserProxyImpl.getInstance(); this.$.dialog.showModal(); + Polymer.RenderStatus.afterNextRender(this, function() { + Polymer.IronA11yAnnouncer.requestAvailability(); + }); + this.browserProxy_.startSetPIN().then(([success, errorCode]) => { if (success) { // Operation is complete. errorCode is a CTAP error code. See @@ -335,6 +339,7 @@ Polymer({ this.currentPINError_ = this.isValidPIN_(this.currentPIN_); if (this.currentPINError_ != '') { this.focusOn_(this.$.currentPIN); + this.fire('iron-announce', {text: this.currentPINError_}); this.fire('ui-ready'); // for test synchronization. return; } @@ -343,6 +348,7 @@ Polymer({ this.newPINError_ = this.isValidPIN_(this.newPIN_); if (this.newPINError_ != '') { this.focusOn_(this.$.newPIN); + this.fire('iron-announce', {text: this.newPINError_}); this.fire('ui-ready'); // for test synchronization. return; } @@ -350,6 +356,7 @@ Polymer({ if (this.newPIN_ != this.confirmPIN_) { this.confirmPINError_ = this.i18n('securityKeysPINMismatch'); this.focusOn_(this.$.confirmPIN); + this.fire('iron-announce', {text: this.confirmPINError_}); this.fire('ui-ready'); // for test synchronization. return; } @@ -374,6 +381,7 @@ Polymer({ this.currentPINError_ = this.mismatchError_(this.retries_); this.setPINButtonValid_ = true; this.focusOn_(this.$.currentPIN); + this.fire('iron-announce', {text: this.currentPINError_}); this.fire('ui-ready'); // for test synchronization. } else { // Unknown error. diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html index e1d58b335fd..8f242c43a58 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html @@ -6,6 +6,7 @@ <link rel="import" href="../settings_shared_css.html"> <link rel="import" href="security_keys_credential_management_dialog.html"> +<link rel="import" href="security_keys_bio_enroll_dialog.html"> <link rel="import" href="security_keys_set_pin_dialog.html"> <link rel="import" href="security_keys_reset_dialog.html"> @@ -32,6 +33,14 @@ label="$i18n{securityKeysReset}" sub-label="$i18n{securityKeysResetDesc}" on-click="onReset_"></cr-link-row> + <template is="dom-if" if="[[enableBioEnrollment_]]"> + <cr-link-row + id="bioEnrollButton" + class="hr" + label="$i18n{securityKeysBioEnrollmentDialogTitle}" + sub-label="$i18n{securityKeysBioEnrollmentSubpageDescription}" + on-click="onBioEnroll_"></cr-link-row> + </template> <template is="dom-if" if="[[showSetPINDialog_]]" restamp> <settings-security-keys-set-pin-dialog on-close="onSetPINDialogClosed_"> @@ -49,6 +58,12 @@ </settings-security-keys-reset-dialog> </template> + <template is="dom-if" if="[[showBioEnrollDialog_]]" restamp> + <settings-security-keys-bio-enroll-dialog + on-close="onBioEnrollDialogClosed_"> + </settings-security-keys-bio-enroll-dialog> + </template> + </template> <script src="security_keys_subpage.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js index b0eee4155a2..414f10740ec 100644 --- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js +++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js @@ -21,6 +21,15 @@ Polymer({ }, /** @private */ + enableBioEnrollment_: { + type: Boolean, + readOnly: true, + value: function() { + return loadTimeData.getBoolean('enableSecurityKeysBioEnrollment'); + } + }, + + /** @private */ showSetPINDialog_: { type: Boolean, value: false, @@ -35,6 +44,11 @@ Polymer({ type: Boolean, value: false, }, + /** @private */ + showBioEnrollDialog_: { + type: Boolean, + value: false, + }, }, /** @private */ @@ -56,7 +70,7 @@ Polymer({ /** @private */ onCredentialManagementDialogClosed_: function() { this.showCredentialManagementDialog_ = false; - cr.ui.focusWithoutInk(this.$.credentialManagementButton); + cr.ui.focusWithoutInk(assert(this.$$('#credentialManagementButton'))); }, /** @private */ @@ -69,4 +83,15 @@ Polymer({ this.showResetDialog_ = false; cr.ui.focusWithoutInk(this.$.resetButton); }, + + /** @private */ + onBioEnroll_: function() { + this.showBioEnrollDialog_ = true; + }, + + /** @private */ + onBioEnrollDialogClosed_: function() { + this.showBioEnrollDialog_ = false; + cr.ui.focusWithoutInk(assert(this.$$('#bioEnrollButton'))); + }, }); diff --git a/chromium/chrome/browser/resources/settings/route.js b/chromium/chrome/browser/resources/settings/route.js index 808fc7775c4..244cb3be580 100644 --- a/chromium/chrome/browser/resources/settings/route.js +++ b/chromium/chrome/browser/resources/settings/route.js @@ -101,6 +101,7 @@ * SITE_SETTINGS_LOCATION: (undefined|!settings.Route), * SITE_SETTINGS_MICROPHONE: (undefined|!settings.Route), * SITE_SETTINGS_MIDI_DEVICES: (undefined|!settings.Route), + * SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE: (undefined|!settings.Route), * SITE_SETTINGS_NOTIFICATIONS: (undefined|!settings.Route), * SITE_SETTINGS_PAYMENT_HANDLER: (undefined|!settings.Route), * SITE_SETTINGS_PDF_DOCUMENTS: (undefined|!settings.Route), @@ -224,12 +225,10 @@ cr.define('settings', function() { } /** - * Computes and return all available routes based on settings.pageVisibility. - * @return {!SettingsRoutes} + * @return {!SettingsRoutes} Routes that are shared between browser and OS + * settings under the same conditions (e.g. in guest mode). */ - const computeAvailableRoutes = function() { - const pageVisibility = settings.pageVisibility || {}; - + function computeCommonRoutes() { /** @type {!SettingsRoutes} */ const r = {}; @@ -237,27 +236,33 @@ cr.define('settings', function() { r.BASIC = new Route('/'); r.ABOUT = new Route('/help'); - // Navigable dialogs. These are the only non-section children of root - // pages. These are disfavored. If we add anymore, we should add explicit - // support. - r.IMPORT_DATA = r.BASIC.createChild('/importData'); - r.IMPORT_DATA.isNavigableDialog = true; r.SIGN_OUT = r.BASIC.createChild('/signOut'); r.SIGN_OUT.isNavigableDialog = true; - // <if expr="chromeos"> - r.INTERNET = r.BASIC.createSection('/internet', 'internet'); - r.INTERNET_NETWORKS = r.INTERNET.createChild('/networks'); - r.NETWORK_DETAIL = r.INTERNET.createChild('/networkDetail'); - r.KNOWN_NETWORKS = r.INTERNET.createChild('/knownNetworks'); - r.BLUETOOTH = r.BASIC.createSection('/bluetooth', 'bluetooth'); - r.BLUETOOTH_DEVICES = r.BLUETOOTH.createChild('/bluetoothDevices'); + r.SEARCH = r.BASIC.createSection('/search', 'search'); + if (!loadTimeData.getBoolean('isGuest')) { + r.PEOPLE = r.BASIC.createSection('/people', 'people'); + r.SYNC = r.PEOPLE.createChild('/syncSetup'); + r.SYNC_ADVANCED = r.SYNC.createChild('/syncSetup/advanced'); + } + + return r; + } - r.MULTIDEVICE = r.BASIC.createSection('/multidevice', 'multidevice'); - r.MULTIDEVICE_FEATURES = r.MULTIDEVICE.createChild('/multidevice/features'); - r.SMART_LOCK = - r.MULTIDEVICE_FEATURES.createChild('/multidevice/features/smartLock'); + /** + * Adds Route objects for each path corresponding to browser-only content. + * @param {!SettingsRoutes} r Routes to include browser-only content. + */ + function addBrowserSettingsRoutes(r) { + const pageVisibility = settings.pageVisibility || {}; + + // <if expr="not chromeos"> + r.IMPORT_DATA = r.BASIC.createChild('/importData'); + r.IMPORT_DATA.isNavigableDialog = true; + if (pageVisibility.people !== false) { + r.MANAGE_PROFILE = r.PEOPLE.createChild('/manageProfile'); + } // </if> if (pageVisibility.appearance !== false) { @@ -277,84 +282,13 @@ cr.define('settings', function() { r.BASIC.createSection('/defaultBrowser', 'defaultBrowser'); } - r.SEARCH = r.BASIC.createSection('/search', 'search'); r.SEARCH_ENGINES = r.SEARCH.createChild('/searchEngines'); - // <if expr="chromeos"> - if (loadTimeData.valueExists('assistantEnabled') && - loadTimeData.getBoolean('assistantEnabled')) { - r.GOOGLE_ASSISTANT = r.SEARCH.createChild('/googleAssistant'); - } - - if (loadTimeData.valueExists('showApps') && - loadTimeData.getBoolean('showApps')) { - r.APPS = r.BASIC.createSection('/apps', 'apps'); - } - - r.ANDROID_APPS = r.BASIC.createSection('/androidApps', 'androidApps'); - r.ANDROID_APPS_DETAILS = r.ANDROID_APPS.createChild('/androidApps/details'); - - if (loadTimeData.valueExists('showCrostini') && - loadTimeData.getBoolean('showCrostini')) { - r.CROSTINI = r.BASIC.createSection('/crostini', 'crostini'); - r.CROSTINI_DETAILS = r.CROSTINI.createChild('/crostini/details'); - r.CROSTINI_EXPORT_IMPORT = - r.CROSTINI_DETAILS.createChild('/crostini/exportImport'); - r.CROSTINI_SHARED_PATHS = - r.CROSTINI_DETAILS.createChild('/crostini/sharedPaths'); - r.CROSTINI_SHARED_USB_DEVICES = - r.CROSTINI_DETAILS.createChild('/crostini/sharedUsbDevices'); - } - - if (loadTimeData.valueExists('showPluginVm') && - loadTimeData.getBoolean('showPluginVm')) { - r.PLUGIN_VM = r.BASIC.createSection('/pluginVm', 'pluginVm'); - r.PLUGIN_VM_DETAILS = r.PLUGIN_VM.createChild('/pluginVm/details'); - r.PLUGIN_VM_SHARED_PATHS = - r.PLUGIN_VM.createChild('/pluginVm/sharedPaths'); - } - // </if> if (pageVisibility.onStartup !== false) { r.ON_STARTUP = r.BASIC.createSection('/onStartup', 'onStartup'); r.STARTUP_PAGES = r.ON_STARTUP.createChild('/startupPages'); } - if (pageVisibility.people !== false) { - r.PEOPLE = r.BASIC.createSection('/people', 'people'); - r.SYNC = r.PEOPLE.createChild('/syncSetup'); - r.SYNC_ADVANCED = r.SYNC.createChild('/syncSetup/advanced'); - // <if expr="not chromeos"> - r.MANAGE_PROFILE = r.PEOPLE.createChild('/manageProfile'); - // </if> - // <if expr="chromeos"> - // TODO(crbug.com/950007): Remove when SplitSettings is the default. - if (loadTimeData.getBoolean('isOSSettings')) { - r.PERSONALIZATION = - r.BASIC.createSection('/personalization', 'personalization'); - r.CHANGE_PICTURE = r.PERSONALIZATION.createChild('/changePicture'); - } else { - r.CHANGE_PICTURE = r.PEOPLE.createChild('/changePicture'); - } - r.ACCOUNTS = r.PEOPLE.createChild('/accounts'); - r.ACCOUNT_MANAGER = r.PEOPLE.createChild('/accountManager'); - r.KERBEROS_ACCOUNTS = r.PEOPLE.createChild('/kerberosAccounts'); - r.LOCK_SCREEN = r.PEOPLE.createChild('/lockScreen'); - r.FINGERPRINT = r.LOCK_SCREEN.createChild('/lockScreen/fingerprint'); - // </if> - } - - // <if expr="chromeos"> - r.DEVICE = r.BASIC.createSection('/device', 'device'); - r.POINTERS = r.DEVICE.createChild('/pointer-overlay'); - r.KEYBOARD = r.DEVICE.createChild('/keyboard-overlay'); - r.STYLUS = r.DEVICE.createChild('/stylus'); - r.DISPLAY = r.DEVICE.createChild('/display'); - r.STORAGE = r.DEVICE.createChild('/storage'); - r.EXTERNAL_STORAGE_PREFERENCES = - r.DEVICE.createChild('/storage/externalStoragePreferences'); - r.POWER = r.DEVICE.createChild('/power'); - // </if> - // Advanced Routes if (pageVisibility.advancedSettings !== false) { r.ADVANCED = new Route('/advanced'); @@ -422,48 +356,23 @@ cr.define('settings', function() { r.SITE_SETTINGS_BLUETOOTH_SCANNING = r.SITE_SETTINGS.createChild('bluetoothScanning'); } - - // <if expr="chromeos"> - if (pageVisibility.dateTime !== false) { - r.DATETIME = r.ADVANCED.createSection('/dateTime', 'dateTime'); - r.DATETIME_TIMEZONE_SUBPAGE = - r.DATETIME.createChild('/dateTime/timeZone'); + if (loadTimeData.getBoolean( + 'enableNativeFileSystemWriteContentSetting')) { + r.SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE = + r.SITE_SETTINGS.createChild('filesystem'); } - // </if> r.LANGUAGES = r.ADVANCED.createSection('/languages', 'languages'); - // <if expr="chromeos"> - if (loadTimeData.getBoolean('isOSSettings')) { - r.LANGUAGES_DETAILS = r.LANGUAGES.createChild('/languages/details'); - r.INPUT_METHODS = - r.LANGUAGES_DETAILS.createChild('/languages/inputMethods'); - } else { - r.INPUT_METHODS = r.LANGUAGES.createChild('/inputMethods'); - } - // </if> // <if expr="not is_macosx"> r.EDIT_DICTIONARY = r.LANGUAGES.createChild('/editDictionary'); // </if> if (pageVisibility.downloads !== false) { r.DOWNLOADS = r.ADVANCED.createSection('/downloads', 'downloads'); - // <if expr="chromeos"> - // TODO(crbug.com/950007): Make unconditional and remove 'else' block - // when SplitSettings is the default. - if (loadTimeData.getBoolean('isOSSettings')) { - r.FILES = r.ADVANCED.createSection('/files', 'files'); - r.SMB_SHARES = r.FILES.createChild('/smbShares'); - } else { - r.SMB_SHARES = r.DOWNLOADS.createChild('/smbShares'); - } - // </if> } r.PRINTING = r.ADVANCED.createSection('/printing', 'printing'); r.CLOUD_PRINTERS = r.PRINTING.createChild('/cloudPrinters'); - // <if expr="chromeos"> - r.CUPS_PRINTERS = r.PRINTING.createChild('/cupsPrinters'); - // </if> r.ACCESSIBILITY = r.ADVANCED.createSection('/accessibility', 'a11y'); @@ -480,19 +389,9 @@ cr.define('settings', function() { } // </if> - // <if expr="chromeos"> - r.MANAGE_ACCESSIBILITY = - r.ACCESSIBILITY.createChild('/manageAccessibility'); - if (loadTimeData.getBoolean( - 'showExperimentalAccessibilitySwitchAccess')) { - r.MANAGE_SWITCH_ACCESS_SETTINGS = r.MANAGE_ACCESSIBILITY.createChild( - '/manageAccessibility/switchAccess'); - } - r.MANAGE_TTS_SETTINGS = - r.MANAGE_ACCESSIBILITY.createChild('/manageAccessibility/tts'); - // </if> - + // <if expr="not chromeos"> r.SYSTEM = r.ADVANCED.createSection('/system', 'system'); + // </if> if (pageVisibility.reset !== false) { r.RESET = r.ADVANCED.createSection('/reset', 'reset'); @@ -510,28 +409,182 @@ cr.define('settings', function() { // </if> } } + } + + // <if expr="chromeos"> + /** + * Adds Route objects for each path corresponding to CrOS-only content. + * @param {!SettingsRoutes} r Routes to include CrOS-only content. + */ + function addOSSettingsRoutes(r) { + r.INTERNET = r.BASIC.createSection('/internet', 'internet'); + r.INTERNET_NETWORKS = r.INTERNET.createChild('/networks'); + r.NETWORK_DETAIL = r.INTERNET.createChild('/networkDetail'); + r.KNOWN_NETWORKS = r.INTERNET.createChild('/knownNetworks'); + r.BLUETOOTH = r.BASIC.createSection('/bluetooth', 'bluetooth'); + r.BLUETOOTH_DEVICES = r.BLUETOOTH.createChild('/bluetoothDevices'); + + r.DEVICE = r.BASIC.createSection('/device', 'device'); + r.POINTERS = r.DEVICE.createChild('/pointer-overlay'); + r.KEYBOARD = r.DEVICE.createChild('/keyboard-overlay'); + r.STYLUS = r.DEVICE.createChild('/stylus'); + r.DISPLAY = r.DEVICE.createChild('/display'); + r.STORAGE = r.DEVICE.createChild('/storage'); + r.EXTERNAL_STORAGE_PREFERENCES = + r.DEVICE.createChild('/storage/externalStoragePreferences'); + r.POWER = r.DEVICE.createChild('/power'); - // <if expr="chromeos"> // "About" is the only section in About, but we still need to create the // route in order to show the subpage on Chrome OS. r.ABOUT_ABOUT = r.ABOUT.createSection('/help/about', 'about'); - // TODO(aee): Remove once this file is forked. - if (loadTimeData.getBoolean('showOSSettings')) { - r.DETAILED_BUILD_INFO = r.ABOUT_ABOUT.createChild('/help/details'); + r.DETAILED_BUILD_INFO = r.ABOUT_ABOUT.createChild('/help/details'); + + if (!loadTimeData.getBoolean('isGuest')) { + r.MULTIDEVICE = r.BASIC.createSection('/multidevice', 'multidevice'); + r.MULTIDEVICE_FEATURES = + r.MULTIDEVICE.createChild('/multidevice/features'); + r.SMART_LOCK = + r.MULTIDEVICE_FEATURES.createChild('/multidevice/features/smartLock'); + + r.ACCOUNTS = r.PEOPLE.createChild('/accounts'); + r.ACCOUNT_MANAGER = r.PEOPLE.createChild('/accountManager'); + r.KERBEROS_ACCOUNTS = r.PEOPLE.createChild('/kerberosAccounts'); + r.LOCK_SCREEN = r.PEOPLE.createChild('/lockScreen'); + r.FINGERPRINT = r.LOCK_SCREEN.createChild('/lockScreen/fingerprint'); } - // </if> - return r; - }; + if (loadTimeData.valueExists('androidAppsVisible') && + loadTimeData.getBoolean('androidAppsVisible')) { + r.ANDROID_APPS = r.BASIC.createSection('/androidApps', 'androidApps'); + r.ANDROID_APPS_DETAILS = + r.ANDROID_APPS.createChild('/androidApps/details'); + } + + if (loadTimeData.valueExists('showCrostini') && + loadTimeData.getBoolean('showCrostini')) { + r.CROSTINI = r.BASIC.createSection('/crostini', 'crostini'); + r.CROSTINI_DETAILS = r.CROSTINI.createChild('/crostini/details'); + if (loadTimeData.valueExists('showCrostiniExportImport') && + loadTimeData.getBoolean('showCrostiniExportImport')) { + r.CROSTINI_EXPORT_IMPORT = + r.CROSTINI_DETAILS.createChild('/crostini/exportImport'); + } + r.CROSTINI_SHARED_PATHS = + r.CROSTINI_DETAILS.createChild('/crostini/sharedPaths'); + r.CROSTINI_SHARED_USB_DEVICES = + r.CROSTINI_DETAILS.createChild('/crostini/sharedUsbDevices'); + } + + if (loadTimeData.valueExists('showPluginVm') && + loadTimeData.getBoolean('showPluginVm')) { + r.PLUGIN_VM = r.BASIC.createSection('/pluginVm', 'pluginVm'); + r.PLUGIN_VM_DETAILS = r.PLUGIN_VM.createChild('/pluginVm/details'); + r.PLUGIN_VM_SHARED_PATHS = + r.PLUGIN_VM.createChild('/pluginVm/sharedPaths'); + } + + r.GOOGLE_ASSISTANT = r.SEARCH.createChild('/googleAssistant'); + + // This if/else accounts for sections that were added or refactored in + // the settings split (crbug.com/950007) and some routes that were created + // in browser settings conditioned on the pageVisibility constant, which is + // being decoupled from OS Settings in the split. The 'else' block provides + // a section-by-section comparison. + // TODO (crbug.com/967861): Make 'if' block unconditional. Remove 'else' + // block. + if (loadTimeData.getBoolean('isOSSettings')) { + r.ADVANCED = new Route('/advanced'); + + r.PRIVACY = r.ADVANCED.createSection('/privacy', 'privacy'); + + // Languages and input + r.LANGUAGES = r.ADVANCED.createSection('/languages', 'languages'); + r.LANGUAGES_DETAILS = r.LANGUAGES.createChild('/languages/details'); + r.INPUT_METHODS = + r.LANGUAGES_DETAILS.createChild('/languages/inputMethods'); + + r.PRINTING = r.ADVANCED.createSection('/printing', 'printing'); + + r.ACCESSIBILITY = r.ADVANCED.createSection('/accessibility', 'a11y'); + + if (!loadTimeData.getBoolean('isGuest')) { + // Personalization + r.PERSONALIZATION = + r.BASIC.createSection('/personalization', 'personalization'); + r.CHANGE_PICTURE = r.PERSONALIZATION.createChild('/changePicture'); + + // Files (analogous to Downloads) + r.FILES = r.ADVANCED.createSection('/files', 'files'); + r.SMB_SHARES = r.FILES.createChild('/smbShares'); + } + + // Reset + if (loadTimeData.valueExists('allowPowerwash') && + loadTimeData.getBoolean('allowPowerwash')) { + r.RESET = r.ADVANCED.createSection('/reset', 'reset'); + } + + // Apps + if (loadTimeData.valueExists('showApps') && + loadTimeData.getBoolean('showApps')) { + r.APPS = r.BASIC.createSection('/apps', 'apps'); + r.APP_MANAGEMENT = r.APPS.createChild('/app-management'); + r.APP_MANAGEMENT_DETAIL = + r.APP_MANAGEMENT.createChild('/app-management/detail'); + } + } else { + assert(r.ADVANCED, 'ADVANCED route should exist'); + + assert(r.PRIVACY, 'PRIVACY route should exist'); + + // Languages and input + assert(r.LANGUAGES, 'LANGUAGES route should exist'); + r.INPUT_METHODS = r.LANGUAGES.createChild('/inputMethods'); + + assert(r.PRINTING, 'PRINTING route should exist'); + + assert(r.ACCESSIBILITY, 'ACCESSIBILITY route should exist'); + + if (!loadTimeData.getBoolean('isGuest')) { + // People + r.CHANGE_PICTURE = r.PEOPLE.createChild('/changePicture'); + + // Downloads (analogous to Files) + assert(r.DOWNLOADS, 'DOWNLOADS route should exist'); + r.SMB_SHARES = r.DOWNLOADS.createChild('/smbShares'); + + // Reset + assert(r.RESET, 'RESET route should exist'); + } + + assert(!r.APPS, 'APPS route should not exist'); + } + + r.DATETIME = r.ADVANCED.createSection('/dateTime', 'dateTime'); + r.DATETIME_TIMEZONE_SUBPAGE = r.DATETIME.createChild('/dateTime/timeZone'); + + r.CUPS_PRINTERS = r.PRINTING.createChild('/cupsPrinters'); + + r.MANAGE_ACCESSIBILITY = + r.ACCESSIBILITY.createChild('/manageAccessibility'); + if (loadTimeData.getBoolean('showExperimentalAccessibilitySwitchAccess')) { + r.MANAGE_SWITCH_ACCESS_SETTINGS = r.MANAGE_ACCESSIBILITY.createChild( + '/manageAccessibility/switchAccess'); + } + r.MANAGE_TTS_SETTINGS = + r.MANAGE_ACCESSIBILITY.createChild('/manageAccessibility/tts'); + } + // </if> class Router { - constructor() { + /** @param {!SettingsRoutes} availableRoutes */ + constructor(availableRoutes) { /** * List of available routes. This is populated taking into account current * state (like guest mode). * @private {!SettingsRoutes} */ - this.routes_ = computeAvailableRoutes(); + this.routes_ = availableRoutes; /** * The current active route. This updated is only by settings.navigateTo @@ -710,7 +763,31 @@ cr.define('settings', function() { } } - const routerInstance = new Router(); + /** + * @return {!settings.Router} A router with at least those routes common to OS + * and browser settings. If the window is not in OS settings (based on + * loadTimeData) then browser specific routes are added. If the window is + * OS settings or if Chrome OS is using a consolidated settings page for + * OS and browser settings then OS specific routes are added. + */ + function buildRouter() { + const availableRoutes = computeCommonRoutes(); + const isOSSettings = loadTimeData.valueExists('isOSSettings') && + loadTimeData.getBoolean('isOSSettings'); + if (!isOSSettings) { + addBrowserSettingsRoutes(availableRoutes); + } + + // <if expr="chromeos"> + const showOSSettings = loadTimeData.valueExists('showOSSettings') && + loadTimeData.getBoolean('showOSSettings'); + if (isOSSettings || showOSSettings) { + addOSSettingsRoutes(availableRoutes); + } + // </if> + return new Router(availableRoutes); + } + const routerInstance = buildRouter(); const routeObservers = new Set(); @@ -780,6 +857,7 @@ cr.define('settings', function() { Route: Route, // The Route class definition. Router: Router, // The Router class definition. router: routerInstance, // the singleton. + buildRouterForTesting: buildRouter, routes: routes, RouteObserverBehavior: RouteObserverBehavior, getRouteForPath: getRouteForPath, 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 43fcdba764a..fac0773366c 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 @@ -25,7 +25,7 @@ </style> <div class="list-item" focus-row-container> <div class="name-column"> - <site-favicon url="[[engine.iconURL]]"></site-favicon> + <site-favicon favicon-url="[[engine.iconURL]]"></site-favicon> <span>[[engine.displayName]]</span> </div> <div class="keyword-column">[[engine.keyword]]</div> 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 9715c76b469..83d8b346ed4 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 @@ -41,7 +41,7 @@ <div class="list-item" focus-row-container> <div id="name-column"> - <site-favicon url="[[engine.iconURL]]"></site-favicon> + <site-favicon favicon-url="[[engine.iconURL]]"></site-favicon> <div>[[engine.displayName]]</div> </div> <div id="keyword-column"><div>[[engine.keyword]]</div></div> diff --git a/chromium/chrome/browser/resources/settings/search_settings.js b/chromium/chrome/browser/resources/settings/search_settings.js index 98d79796f44..a98f501303f 100644 --- a/chromium/chrome/browser/resources/settings/search_settings.js +++ b/chromium/chrome/browser/resources/settings/search_settings.js @@ -153,7 +153,7 @@ cr.define('settings', function() { parent = parent.nodeType == Node.DOCUMENT_FRAGMENT_NODE ? parent.host : parent.parentNode; - if (parent.nodeName == 'SETTINGS-SUBPAGE') { + if (parent && parent.nodeName == 'SETTINGS-SUBPAGE') { // TODO(dpapad): Cast to SettingsSubpageElement here. associatedControl = assert( parent.associatedControl, 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 d75f667d3c3..b005a754146 100644 --- a/chromium/chrome/browser/resources/settings/settings_main/settings_main.html +++ b/chromium/chrome/browser/resources/settings/settings_main/settings_main.html @@ -63,7 +63,6 @@ <template is="dom-if" if="[[showPages_.settings]]"> <settings-basic-page prefs="{{prefs}}" page-visibility="[[pageVisibility]]" - show-apps="[[showApps]]" show-android-apps="[[showAndroidApps]]" show-crostini="[[showCrostini]]" show-parental-controls="[[showParentalControls]]" 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 9369f5f5517..4dabc3f833b 100644 --- a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html +++ b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html @@ -10,6 +10,11 @@ <link rel="import" href="../route.html"> <link rel="import" href="../settings_shared_css.html"> +<if expr="chromeos"> +<!-- TODO(crbug.com/986596): Remove OS icons when SplitSettings is complete. --> +<link rel="import" href="../chromeos/os_icons.html"> +</if> + <dom-module id="settings-menu"> <template> <style include="settings-shared"> @@ -107,7 +112,7 @@ role="navigation" on-click="onLinkClick_"> <if expr="chromeos"> <a href="/internet" hidden="[[!pageVisibility.internet]]"> - <iron-icon icon="settings:network-wifi"></iron-icon> + <iron-icon icon="os-settings:network-wifi"></iron-icon> $i18n{internetPageTitle} </a> <a href="/bluetooth" hidden="[[!pageVisibility.bluetooth]]"> @@ -116,7 +121,7 @@ </a> <a id="multidevice" href="/multidevice" hidden="[[!pageVisibility.multidevice]]"> - <iron-icon icon="settings:multidevice-better-together-suite"> + <iron-icon icon="os-settings:multidevice-better-together-suite"> </iron-icon> $i18n{multidevicePageTitle} </a> @@ -137,7 +142,7 @@ </a> <if expr="chromeos"> <a href="/device" hidden="[[!pageVisibility.device]]"> - <iron-icon icon="settings:laptop-chromebook"></iron-icon> + <iron-icon icon="os-settings:laptop-chromebook"></iron-icon> $i18n{devicePageTitle} </a> </if> @@ -146,20 +151,16 @@ $i18n{searchPageTitle} </a> <if expr="chromeos"> - <a href="/apps" hidden="[[!showApps]]"> - <iron-icon icon="settings:apps"></iron-icon> - $i18n{appsPageTitle} - </a> <a href="/androidApps" hidden="[[!showAndroidApps]]"> - <iron-icon icon="settings:play-prism"></iron-icon> + <iron-icon icon="os-settings:play-prism"></iron-icon> $i18n{androidAppsPageTitle} </a> <a href="/crostini" hidden="[[!showCrostini]]"> - <iron-icon icon="settings:crostini-mascot"></iron-icon> + <iron-icon icon="os-settings:crostini-mascot"></iron-icon> $i18n{crostiniPageTitle} </a> <a href="/pluginVm" hidden="[[!showPluginVm]]"> - <iron-icon icon="settings:plugin-vm"></iron-icon> + <iron-icon icon="os-settings:plugin-vm"></iron-icon> $i18n{pluginVmPageTitle} </a> </if> @@ -187,7 +188,7 @@ role="navigation" on-click="onLinkClick_"> <if expr="chromeos"> <a href="/dateTime" hidden="[[!pageVisibility.dateTime]]"> - <iron-icon icon="settings:access-time"></iron-icon> + <iron-icon icon="os-settings:access-time"></iron-icon> $i18n{dateTimePageTitle} </a> </if> 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 4989fb87e41..c48064bcaf2 100644 --- a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html +++ b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html @@ -45,6 +45,13 @@ width: var(--cr-icon-ripple-size); } + #title-icon { + height: 36px; + margin-inline-end: 12px; + margin-inline-start: 2px; + width: 36px; + } + cr-icon-button { /* Centers the ripple on the icon with appropriate margin on right. */ margin-inline-end: 10px; @@ -67,6 +74,9 @@ <div class="settings-box first" id="headerLine"> <cr-icon-button class="icon-arrow-back" id="closeButton" on-click="onTapBack_" aria-label="$i18n{back}"></cr-icon-button> + <template is="dom-if" if="[[titleIcon]]"> + <img id="title-icon" src="[[titleIcon]]"> + </template> <h1 class="cr-title-text">[[pageTitle]]</h1> <slot name="subpage-title-extra"></slot> <template is="dom-if" if="[[learnMoreUrl]]"> diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js index b33ba416d65..bea0032426f 100644 --- a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js +++ b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js @@ -20,6 +20,8 @@ Polymer({ properties: { pageTitle: String, + titleIcon: String, + learnMoreUrl: String, /** Setting a |searchLabel| will enable search. */ diff --git a/chromium/chrome/browser/resources/settings/settings_resources.grd b/chromium/chrome/browser/resources/settings/settings_resources.grd index f9f460935ef..14f631a9af7 100644 --- a/chromium/chrome/browser/resources/settings/settings_resources.grd +++ b/chromium/chrome/browser/resources/settings/settings_resources.grd @@ -151,6 +151,14 @@ file="appearance_page/appearance_browser_proxy.js" type="chrome_html" preprocess="true" /> + <if expr="chromeos"> + <structure name="IDR_SETTINGS_WALLPAPER_BROWSER_PROXY_HTML" + file="appearance_page/wallpaper_browser_proxy.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_WALLPAPER_BROWSER_PROXY_JS" + file="appearance_page/wallpaper_browser_proxy.js" + type="chrome_html" /> + </if> <structure name="IDR_SETTINGS_APPEARANCE_FONTS_PAGE_HTML" file="appearance_page/appearance_fonts_page.html" type="chrome_html" @@ -416,6 +424,12 @@ <structure name="IDR_SETTINGS_SECURITY_KEYS_RESET_DIALOG_JS" file="privacy_page/security_keys_reset_dialog.js" type="chrome_html"/> + <structure name="IDR_SETTINGS_SECURITY_KEYS_BIO_ENROLL_DIALOG_HTML" + file="privacy_page/security_keys_bio_enroll_dialog.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_SECURITY_KEYS_BIO_ENROLL_DIALOG_JS" + file="privacy_page/security_keys_bio_enroll_dialog.js" + type="chrome_html" /> <structure name="IDR_SETTINGS_SECURITY_KEYS_DIALOG_BROWSER_PROXY_HTML" file="privacy_page/security_keys_browser_proxy.html" type="chrome_html" /> @@ -573,6 +587,12 @@ <structure name="IDR_SETTINGS_DEVICE_STORAGE_JS" file="device_page/storage.js" type="chrome_html" /> + <structure name="IDR_SETTINGS_DEVICE_STORAGE_EXTERNAL_ENTRY_HTML" + file="device_page/storage_external_entry.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_DEVICE_STORAGE_EXTERNAL_ENTRY_JS" + file="device_page/storage_external_entry.js" + type="chrome_html" /> <structure name="IDR_SETTINGS_DEVICE_STORAGE_EXTERNAL_HTML" file="device_page/storage_external.html" type="chrome_html" /> @@ -647,6 +667,14 @@ file="icons.html" type="chrome_html" preprocess="true" /> + <if expr="chromeos"> + <!-- TODO(crbug.com/986596): Remove OS icons when SplitSettings + is complete. --> + <structure name="IDR_SETTINGS_CHROMEOS_OS_ICONS" + file="chromeos/os_icons.html" + type="chrome_html" + preprocess="true" /> + </if> <structure name="IDR_SETTINGS_POWERWASH_DIALOG_HTML" file="reset_page/powerwash_dialog.html" type="chrome_html" /> @@ -1300,12 +1328,6 @@ file="site_settings/zoom_levels.js" type="chrome_html" /> <if expr="chromeos"> - <structure name="IDR_SETTINGS_APP_MANAGEMENT_PAGE_HTML" - file="app_management_page/app_management_page.html" - type="chrome_html" /> - <structure name="IDR_SETTINGS_APP_MANAGEMENT_PAGE_JS" - file="app_management_page/app_management_page.js" - type="chrome_html" /> <structure name="IDR_SETTINGS_ANDROID_APPS_PAGE_HTML" file="android_apps_page/android_apps_page.html" type="chrome_html" /> diff --git a/chromium/chrome/browser/resources/settings/settings_shared_css.html b/chromium/chrome/browser/resources/settings/settings_shared_css.html index bc22b45af3c..f91bdedd09b 100644 --- a/chromium/chrome/browser/resources/settings/settings_shared_css.html +++ b/chromium/chrome/browser/resources/settings/settings_shared_css.html @@ -186,6 +186,13 @@ min-height: inherit; } + /* Link buttons use FocusOutlineManager to only show outlines when focus + * was triggered by keyboard. */ + :host-context(html:not(.focus-outline-visible)) + .list-button[is='action-link'] { + outline: none; + } + /* A row with two lines of text. Often the lower line will be .secondary. */ .two-line { 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 9d42840497d..286257d15ea 100644 --- a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html +++ b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html @@ -43,7 +43,6 @@ cr-toolbar { @apply --layout-center; min-height: 56px; - z-index: 2; --cr-toolbar-left-spacer-width: var(--settings-menu-width); --cr-toolbar-center-basis: var(--settings-main-basis); } @@ -126,7 +125,6 @@ <div class="drawer-content"> <template is="dom-if" id="drawerTemplate"> <settings-menu page-visibility="[[pageVisibility_]]" - show-apps="[[showApps_]]" show-android-apps="[[showAndroidApps_]]" show-crostini="[[showCrostini_]]" show-parental-controls="[[showParentalControls_]]" @@ -141,7 +139,6 @@ <div id="container" class="no-outline"> <div id="left"> <settings-menu page-visibility="[[pageVisibility_]]" - show-apps="[[showApps_]]" show-android-apps="[[showAndroidApps_]]" show-crostini="[[showCrostini_]]" show-parental-controls="[[showParentalControls_]]" 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 f3868ee260e..fdbbef286d5 100644 --- a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js +++ b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js @@ -66,9 +66,6 @@ Polymer({ pageVisibility_: {type: Object, value: settings.pageVisibility}, /** @private */ - showApps_: Boolean, - - /** @private */ showAndroidApps_: Boolean, /** @private */ @@ -147,7 +144,6 @@ Polymer({ OncTypeTether: loadTimeData.getString('OncTypeTether'), OncTypeVPN: loadTimeData.getString('OncTypeVPN'), OncTypeWiFi: loadTimeData.getString('OncTypeWiFi'), - OncTypeWiMAX: loadTimeData.getString('OncTypeWiMAX'), networkListItemConnected: loadTimeData.getString('networkListItemConnected'), networkListItemConnecting: @@ -169,8 +165,6 @@ Polymer({ // The SplitSettings feature hides OS settings in the browser settings page. // https://crbug.com/950007 const showOSSettings = loadTimeData.getBoolean('showOSSettings'); - this.showApps_ = showOSSettings && loadTimeData.valueExists('showApps') && - loadTimeData.getBoolean('showApps'); this.showAndroidApps_ = showOSSettings && loadTimeData.valueExists('androidAppsVisible') && loadTimeData.getBoolean('androidAppsVisible'); diff --git a/chromium/chrome/browser/resources/settings/site_favicon.html b/chromium/chrome/browser/resources/settings/site_favicon.html index 7ff3ca780bd..0b99dc90c3e 100644 --- a/chromium/chrome/browser/resources/settings/site_favicon.html +++ b/chromium/chrome/browser/resources/settings/site_favicon.html @@ -5,7 +5,7 @@ <dom-module id="site-favicon"> <template> <style> - :host { + #favicon { background-repeat: no-repeat; background-size: contain; display: block; @@ -13,6 +13,10 @@ width: 16px; } </style> + <div + id="favicon" + style="background-image: [[getBackgroundImage_(faviconUrl, url)]]"> + </div> </template> <script src="site_favicon.js"></script> </dom-module> diff --git a/chromium/chrome/browser/resources/settings/site_favicon.js b/chromium/chrome/browser/resources/settings/site_favicon.js index 09f30efc673..e905bd54e35 100644 --- a/chromium/chrome/browser/resources/settings/site_favicon.js +++ b/chromium/chrome/browser/resources/settings/site_favicon.js @@ -11,18 +11,22 @@ Polymer({ is: 'site-favicon', properties: { - url: { - type: String, - value: '', - observer: 'urlChanged_', - } + faviconUrl: String, + url: String, }, /** @private */ - urlChanged_: function() { - let url = this.removePatternWildcard_(this.url); - url = this.ensureUrlHasScheme_(url); - this.style.backgroundImage = cr.icon.getFavicon(url || '', false); + getBackgroundImage_: function() { + let backgroundImage = 'none'; + if (this.faviconUrl) { + const url = this.ensureUrlHasScheme_(this.faviconUrl); + backgroundImage = cr.icon.getFavicon(url); + } else if (this.url) { + let url = this.removePatternWildcard_(this.url); + url = this.ensureUrlHasScheme_(url); + backgroundImage = cr.icon.getFaviconForPageURL(url || '', false); + } + return backgroundImage; }, /** 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 12f8c830dbc..554bc6992dc 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 @@ -126,6 +126,7 @@ Polymer({ case settings.ContentSettingsTypes.USB_DEVICES: case settings.ContentSettingsTypes.SERIAL_PORTS: case settings.ContentSettingsTypes.BLUETOOTH_SCANNING: + case settings.ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE: // "Ask" vs "Blocked". this.browserProxy.setDefaultValueForContentType( this.category, diff --git a/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html b/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html index 5164f1ceb8d..01d7cb15355 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html +++ b/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.html @@ -10,7 +10,8 @@ category-subtype="[[ContentSetting.BLOCK]]" category-header="[[blockHeader]]" read-only-list="[[readOnlyList]]" - search-filter="[[searchFilter]]"> + search-filter="[[searchFilter]]" + hidden$="[[!showBlockSiteList_]]"> </site-list> <site-list category="[[category]]" @@ -24,7 +25,8 @@ category-subtype="[[ContentSetting.ALLOW]]" category-header="$i18n{siteSettingsAllow}" read-only-list="[[readOnlyList]]" - search-filter="[[searchFilter]]"> + search-filter="[[searchFilter]]" + hidden$="[[!showAllowSiteList_]]"> </site-list> </template> <script src="category_setting_exceptions.js"></script> diff --git a/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js b/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js index bff5aae0f21..212204450a9 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js +++ b/chromium/chrome/browser/resources/settings/site_settings/category_setting_exceptions.js @@ -11,6 +11,14 @@ Polymer({ is: 'category-setting-exceptions', properties: { + + /** + * The string ID of the category that this element is displaying data for. + * See site_settings/constants.js for possible values. + * @type {!settings.ContentSettingsTypes} + */ + category: String, + /** * Some content types (like Location) do not allow the user to manually * edit the exception list from within Settings. @@ -27,10 +35,38 @@ Polymer({ blockHeader: String, searchFilter: String, + + /** + * If true, displays the Allow site list. Defaults to true. + * @private + */ + showAllowSiteList_: { + type: Boolean, + computed: 'computeShowAllowSiteList_(category)', + }, + + /** + * If true, displays the Block site list. Defaults to true. + */ + showBlockSiteList_: { + type: Boolean, + value: true, + }, }, /** @override */ ready: function() { this.ContentSetting = settings.ContentSetting; }, + + /** + * Hides particular category subtypes if |this.category| does not support the + * content setting of that type. + * @return {boolean} + * @private + */ + computeShowAllowSiteList_: function() { + return this.category != + settings.ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE; + }, }); diff --git a/chromium/chrome/browser/resources/settings/site_settings/constants.js b/chromium/chrome/browser/resources/settings/site_settings/constants.js index 909b06ff3b4..a7cf78b84ad 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/constants.js +++ b/chromium/chrome/browser/resources/settings/site_settings/constants.js @@ -37,6 +37,7 @@ settings.ContentSettingsTypes = { SENSORS: 'sensors', PAYMENT_HANDLER: 'payment-handler', BLUETOOTH_SCANNING: 'bluetooth-scanning', + NATIVE_FILE_SYSTEM_WRITE: 'native-file-system-write', }; /** diff --git a/chromium/chrome/browser/resources/settings/site_settings/cookie_info.js b/chromium/chrome/browser/resources/settings/site_settings/cookie_info.js index d4aec05be80..91289e40b9e 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/cookie_info.js +++ b/chromium/chrome/browser/resources/settings/site_settings/cookie_info.js @@ -53,10 +53,6 @@ const cookieInfo = { ['origin', 'fileSystemOrigin'], ['persistent', 'fileSystemPersistentUsage'], ['temporary', 'fileSystemTemporaryUsage'] ], - 'channel_id': [ - ['serverId', 'channelIdServerId'], ['certType', 'channelIdType'], - ['created', 'channelIdCreated'] - ], 'service_worker': [['origin', 'serviceWorkerOrigin'], ['size', 'serviceWorkerSize']], 'shared_worker': diff --git a/chromium/chrome/browser/resources/settings/site_settings/local_data_browser_proxy.js b/chromium/chrome/browser/resources/settings/site_settings/local_data_browser_proxy.js index dee64f793b3..56112da2884 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/local_data_browser_proxy.js +++ b/chromium/chrome/browser/resources/settings/site_settings/local_data_browser_proxy.js @@ -97,6 +97,14 @@ cr.define('settings', function() { * @param {string} path The path to the parent cookie. */ removeCookie(path) {} + + /** + * Removes all SameSite=None cookies, as well as storage available in + * third-party contexts. + * Note: on-tree-item-removed will not be sent. + * @return {!Promise} To signal completion. + */ + removeAllThirdPartyCookies() {} } /** @@ -142,6 +150,11 @@ cr.define('settings', function() { removeCookie(path) { chrome.send('localData.removeCookie', [path]); } + + /** @override */ + removeAllThirdPartyCookies() { + return cr.sendWithPromise('localData.removeThirdPartyCookies'); + } } // The singleton instance_ is replaced with a test version of this wrapper 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 b3c8d9bf131..9fc485db610 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_data.html +++ b/chromium/chrome/browser/resources/settings/site_settings/site_data.html @@ -42,6 +42,11 @@ on-click="onRemoveShowingSitesTap_" hidden$="[[!sites.length]]"> [[computeRemoveLabel_(filter)]] </cr-button> + <cr-button disabled$="[[isLoading_]]" id="removeThirdPartyCookies" + on-click="onRemoveThirdPartyCookiesTap_" + hidden$="[[!enableRemovingAllThirdPartyCookies_]]"> + $i18n{siteSettingsCookieRemoveAllThirdParty} + </cr-button> </div> <iron-list id="list" items="[[sites]]" preserve-focus scroll-target="[[subpageScrollTarget]]" class="cr-separators"> @@ -71,6 +76,26 @@ </cr-button> </div> </cr-dialog> + + <!-- Confirm Delete Third Party Cookies dialog --> + <cr-dialog id="confirmDeleteThirdPartyDialog" close-text="$i18n{close}" + on-close="onConfirmDeleteThirdPartyDialogClosed_"> + <div slot="title"> + $i18n{siteSettingsCookieRemoveThirdPartyDialogTitle} + </div> + <div slot="body"> + $i18n{siteSettingsCookieRemoveThirdPartyConfirmation} + </div> + <div slot="button-container"> + <cr-button class="cancel-button" on-click="onCloseThirdPartyDialog_"> + $i18n{cancel} + </cr-button> + <cr-button class="action-button" on-click="onConfirmThirdPartyDelete_"> + $i18n{siteSettingsCookiesClearThirdParty} + </cr-button> + </div> + </cr-dialog> + </template> <script src="site_data.js"></script> </dom-module> 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 06c8e742b30..644aedc4ac0 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_data.js +++ b/chromium/chrome/browser/resources/settings/site_settings/site_data.js @@ -75,6 +75,15 @@ Polymer({ /** @private */ listBlurred_: Boolean, + + /** @private */ + enableRemovingAllThirdPartyCookies_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('enableRemovingAllThirdPartyCookies') && + (this.sites.length > 0); + } + }, }, /** @private {settings.LocalDataBrowserProxy} */ @@ -201,10 +210,20 @@ Polymer({ }, /** @private */ + onCloseThirdPartyDialog_: function() { + this.$.confirmDeleteThirdPartyDialog.close(); + }, + + /** @private */ onConfirmDeleteDialogClosed_: function() { cr.ui.focusWithoutInk(assert(this.$.removeShowingSites)); }, + /** @private */ + onConfirmDeleteThirdPartyDialogClosed_: function() { + cr.ui.focusWithoutInk(assert(this.$.removeAllThirdPartyCookies)); + }, + /** * Shows a dialog to confirm the deletion of multiple sites. * @param {!Event} e @@ -216,6 +235,16 @@ Polymer({ }, /** + * Shows a dialog to confirm the deletion of cookies available + * in third-party contexts and associated site data. + * @private + */ + onRemoveThirdPartyCookiesTap_: function(e) { + e.preventDefault(); + this.$.confirmDeleteThirdPartyDialog.showModal(); + }, + + /** * Called when deletion for all showing sites has been confirmed. * @private */ @@ -233,6 +262,18 @@ Polymer({ }, /** + * Called when deletion of all third-party cookies and site data has been + * confirmed. + * @private + */ + onConfirmThirdPartyDelete_: function() { + this.$.confirmDeleteThirdPartyDialog.close(); + this.browserProxy_.removeAllThirdPartyCookies().then(() => { + this.updateSiteList_(); + }); + }, + + /** * @param {!{model: !{item: CookieDataSummaryItem, index: number}}} event * @private */ diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js b/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js index f862bba40e6..37ca12214f4 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js +++ b/chromium/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js @@ -8,7 +8,6 @@ const categoryLabels = { app_cache: loadTimeData.getString('cookieAppCache'), cache_storage: loadTimeData.getString('cookieCacheStorage'), - channel_id: loadTimeData.getString('cookieChannelId'), database: loadTimeData.getString('cookieDatabaseStorage'), file_system: loadTimeData.getString('cookieFileSystem'), flash_lso: loadTimeData.getString('cookieFlashLso'), 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 5b373ff071c..1472652cc9e 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_details.html +++ b/chromium/chrome/browser/resources/settings/site_settings/site_details.html @@ -178,6 +178,13 @@ label="$i18n{siteSettingsSerialPorts}"> </site-details-permission> </template> + <template is="dom-if" if="[[enableNativeFileSystemWriteContentSetting_]]"> + <site-details-permission + category="{{ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE}}" + icon="settings:save-original" id="nativeFileSystemWrite" + label="$i18n{siteSettingsNativeFileSystemWrite}"> + </site-details-permission> + </template> <site-details-permission category="{{ContentSettingsTypes.UNSANDBOXED_PLUGINS}}" icon="cr:extension" id="unsandboxedPlugins" 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 da034ee588f..875533a5f19 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_details.js +++ b/chromium/chrome/browser/resources/settings/site_settings/site_details.js @@ -69,6 +69,15 @@ Polymer({ return loadTimeData.getBoolean('enableBluetoothScanningContentSetting'); } }, + + /** @private */ + enableNativeFileSystemWriteContentSetting_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean( + 'enableNativeFileSystemWriteContentSetting'); + } + }, }, listeners: { 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 88b55c9ce59..76f870645d2 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 @@ -230,7 +230,8 @@ Polymer({ return !( category == settings.ContentSettingsTypes.SERIAL_PORTS || category == settings.ContentSettingsTypes.USB_DEVICES || - category == settings.ContentSettingsTypes.BLUETOOTH_SCANNING); + category == settings.ContentSettingsTypes.BLUETOOTH_SCANNING || + category == settings.ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE); }, /** @@ -248,8 +249,10 @@ Polymer({ return true; } - // For Bluetooth scanning permission 'ask' takes the place of 'allow'. - if (category == settings.ContentSettingsTypes.BLUETOOTH_SCANNING) { + // For Bluetooth scanning permission and Native File System write permission + // 'ask' takes the place of 'allow'. + if (category == settings.ContentSettingsTypes.BLUETOOTH_SCANNING || + category == settings.ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE) { return true; } 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 a07b8c00068..de095c0574e 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_list.html +++ b/chromium/chrome/browser/resources/settings/site_settings/site_list.html @@ -33,7 +33,7 @@ <div class="settings-box first"> <h2 class="start">[[categoryHeader]]</h2> <cr-button id="addSite" class="header-aligned-button" - hidden="[[readOnlyList]]" on-click="onAddSiteTap_"> + hidden$="[[!showAddSiteButton_]]" on-click="onAddSiteTap_"> $i18n{add} </cr-button> </div> 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 5e9cbba9943..bdc541bd8a9 100644 --- a/chromium/chrome/browser/resources/settings/site_settings/site_list.js +++ b/chromium/chrome/browser/resources/settings/site_settings/site_list.js @@ -65,6 +65,16 @@ Polymer({ /** @private */ hasIncognito_: Boolean, + /** + * Whether to show the Add button next to the header. + * @private + */ + showAddSiteButton_: { + type: Boolean, + computed: 'computeShowAddSiteButton_(readOnlyList, category, ' + + 'categorySubtype)', + }, + /** @private */ showAddSiteDialog_: Boolean, @@ -222,6 +232,20 @@ Polymer({ }, /** + * Whether the Add Site button is shown in the header for the current category + * and category subtype. + * @return {boolean} + * @private + */ + computeShowAddSiteButton_: function() { + return !( + this.readOnlyList || + (this.category == + settings.ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE && + this.categorySubtype == settings.ContentSetting.ALLOW)); + }, + + /** * @return {boolean} * @private */ 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 9b3234d09ff..af45a352e33 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 @@ -193,8 +193,6 @@ const SiteSettingsBehaviorImpl = { }; // These categories are gated behind flags. addOrRemoveSettingWithFlag( - settings.ContentSettingsTypes.SENSORS, 'enableSensorsContentSetting'); - addOrRemoveSettingWithFlag( settings.ContentSettingsTypes.SERIAL_PORTS, 'enableExperimentalWebPlatformFeatures'); addOrRemoveSettingWithFlag( @@ -206,6 +204,9 @@ const SiteSettingsBehaviorImpl = { addOrRemoveSettingWithFlag( settings.ContentSettingsTypes.BLUETOOTH_SCANNING, 'enableBluetoothScanningContentSetting'); + addOrRemoveSettingWithFlag( + settings.ContentSettingsTypes.NATIVE_FILE_SYSTEM_WRITE, + 'enableNativeFileSystemWriteContentSetting'); return this.contentTypes_.slice(0); }, diff --git a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html index f2b5e48bdc7..a2adc7f829b 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 @@ -66,15 +66,13 @@ '$i18nPolymer{siteSettingsAskBeforeAccessing}', '$i18nPolymer{siteSettingsBlocked}')]]"></cr-link-row> - <template is="dom-if" if="[[enableSensorsContentSetting_]]"> - <cr-link-row class="hr two-line" data-route="SITE_SETTINGS_SENSORS" - id="sensors" label="$i18n{siteSettingsSensors}" - on-click="onTapNavigate_" start-icon="settings:sensors" - sub-label="[[defaultSettingLabel_( - default_.sensors, - '$i18nPolymer{siteSettingsSensorsAllow}', - '$i18nPolymer{siteSettingsSensorsBlock}')]]"></cr-link-row> - </template> + <cr-link-row class="hr two-line" data-route="SITE_SETTINGS_SENSORS" + id="sensors" label="$i18n{siteSettingsSensors}" + on-click="onTapNavigate_" start-icon="settings:sensors" + sub-label="[[defaultSettingLabel_( + default_.sensors, + '$i18nPolymer{siteSettingsSensorsAllow}', + '$i18nPolymer{siteSettingsSensorsBlock}')]]"></cr-link-row> <cr-link-row class="hr two-line" data-route="SITE_SETTINGS_NOTIFICATIONS" id="notifications" label="$i18n{siteSettingsNotifications}" @@ -207,6 +205,19 @@ </cr-link-row> </template> + <template is="dom-if" if="[[enableNativeFileSystemWriteContentSetting_]]"> + <cr-link-row class="hr two-line" + data-route="SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE" + icon-class="subpage-arrow" id="native-file-system-write" + label="$i18n{siteSettingsNativeFileSystemWrite}" + on-click="onTapNavigate_" start-icon="settings:save-original" + sub-label="[[defaultSettingLabel_( + default_.filesystem, + '$i18nPolymer{siteSettingsNativeFileSystemWriteAsk}', + '$i18nPolymer{siteSettingsNativeFileSystemWriteBlock}')]]"> + </cr-link-row> + </template> + <cr-link-row class="hr" data-route="SITE_SETTINGS_PDF_DOCUMENTS" id="pdf-documents" label="$i18n{siteSettingsPdfDocuments}" on-click="onTapNavigate_" start-icon="settings:pdf"></cr-link-row> 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 85c0349ce7d..25bee399e1c 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 @@ -44,15 +44,6 @@ Polymer({ }, /** @private */ - enableSensorsContentSetting_: { - type: Boolean, - readOnly: true, - value: function() { - return loadTimeData.getBoolean('enableSensorsContentSetting'); - } - }, - - /** @private */ enableExperimentalWebPlatformFeatures_: { type: Boolean, value: function() { @@ -76,6 +67,15 @@ Polymer({ } }, + /** @private */ + enableNativeFileSystemWriteContentSetting_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean( + 'enableNativeFileSystemWriteContentSetting'); + } + }, + /** @type {!Map<string, (string|Function)>} */ focusConfig: { type: Object, @@ -134,6 +134,12 @@ Polymer({ pairs.push([R.SITE_SETTINGS_BLUETOOTH_SCANNING, 'bluetooth-scanning']); } + if (this.enableNativeFileSystemWriteContentSetting_) { + pairs.push([ + R.SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE, 'native-file-system-write' + ]); + } + pairs.forEach(([route, id]) => { this.focusConfig.set(route.path, () => this.async(() => { cr.ui.focusWithoutInk(assert(this.$$(`#${id}`))); diff --git a/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js b/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js index d3d057d16a6..99270fb3301 100644 --- a/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js +++ b/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js @@ -4,7 +4,7 @@ 'use strict'; -/** @type {snippetsInternals.mojom.PageHandlerProxy} */ +/** @type {snippetsInternals.mojom.PageHandlerRemote} */ let pageHandler = null; /** @type {snippetsInternals.mojom.PageInterface} */ @@ -245,6 +245,17 @@ function setupEventListeners() { /* Represents the js-side of the IPC link. Backend talks to this. */ /** @implements {snippetsInternals.mojom.PageInterface} */ class SnippetsInternalsPageImpl { + constructor() { + this.receiver_ = new snippetsInternals.mojom.PageReceiver(this); + } + + /** + * @return {!snippetsInternals.mojom.PageRemote} + */ + bindNewPipeAndPassRemote() { + return this.receiver_.$.bindNewPipeAndPassRemote(); + } + /* Callback for when suggestions change on the backend. */ onSuggestionsChanged() { getSuggestionsByCategory(); @@ -254,25 +265,24 @@ class SnippetsInternalsPageImpl { /* Main entry point. */ document.addEventListener('DOMContentLoaded', function() { // Setup frontend mojo. - page = new SnippetsInternalsPageImpl; + page = new SnippetsInternalsPageImpl(); // Setup backend mojo. const pageHandlerFactory = - snippetsInternals.mojom.PageHandlerFactory.getProxy(); + snippetsInternals.mojom.PageHandlerFactory.getRemote(); // Give backend mojo a reference to frontend mojo. - const client = new snippetsInternals.mojom.Page(page).$.createProxy(); - pageHandlerFactory.createPageHandler(client).then((response) => { + pageHandlerFactory.createPageHandler(page.bindNewPipeAndPassRemote()) + .then((response) => { + pageHandler = response.handler; - pageHandler = response.handler; - - // Populate value fields. - refreshContent(); - getSuggestionsByCategory(); - setInterval(refreshContent, 2000); + // Populate value fields. + refreshContent(); + getSuggestionsByCategory(); + setInterval(refreshContent, 2000); - // Setup events. - setupEventListeners(); - }); + // Setup events. + setupEventListeners(); + }); }); }()); diff --git a/chromium/chrome/browser/resources/supervised_user_error_page_resources.grdp b/chromium/chrome/browser/resources/supervised_user_error_page_resources.grdp new file mode 100644 index 00000000000..efdd213ea9f --- /dev/null +++ b/chromium/chrome/browser/resources/supervised_user_error_page_resources.grdp @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<grit-part> + <include name="IDR_SUPERVISED_USER_BLOCK_INTERSTITIAL_HTML" file="supervised_user/supervised_user_error_page/resources/supervised_user_block_interstitial.html" flattenhtml="true" type="BINDATA" /> +</grit-part> diff --git a/chromium/chrome/browser/resources/tab_strip/BUILD.gn b/chromium/chrome/browser/resources/tab_strip/BUILD.gn new file mode 100644 index 00000000000..ece86c1ad36 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") + +js_type_check("closure_compile") { + deps = [ + ":custom_element", + ":tab", + ":tab_list", + ":tabs_api_proxy", + ] +} + +js_library("custom_element") { +} + +js_library("tabs_api_proxy") { + deps = [ + "//ui/webui/resources/js:cr.m", + ] + externs_list = [ "$externs_path/chrome_extensions.js" ] +} + +js_library("tab") { + deps = [ + "//ui/webui/resources/js:icon.m", + ] + externs_list = [ "$externs_path/chrome.js" ] +} + +js_library("tab_list") { + deps = [ + ":types", + ] + externs_list = [ "$externs_path/chrome.js" ] +} + +js_library("types") { +} + +group("tab_strip_modules") { + deps = [ + ":tab_list_module", + ":tab_module", + ] +} + +polymer_modulizer("tab") { + js_file = "tab.js" + html_file = "tab.html" + html_type = "v3-ready" +} + +polymer_modulizer("tab_list") { + js_file = "tab_list.js" + html_file = "tab_list.html" + html_type = "v3-ready" +} diff --git a/chromium/chrome/browser/resources/tab_strip/OWNERS b/chromium/chrome/browser/resources/tab_strip/OWNERS new file mode 100644 index 00000000000..c4454dd4ad5 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/OWNERS @@ -0,0 +1,2 @@ +dpapad@chromium.org +johntlee@chromium.org diff --git a/chromium/chrome/browser/resources/tab_strip/custom_element.js b/chromium/chrome/browser/resources/tab_strip/custom_element.js new file mode 100644 index 00000000000..2d8e4e91937 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/custom_element.js @@ -0,0 +1,17 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Super class for all custom elements defined in the tab strip. + */ +export class CustomElement extends HTMLElement { + constructor() { + super(); + + this.attachShadow({mode: 'open'}); + const template = document.createElement('template'); + template.innerHTML = this.constructor.template || ''; + this.shadowRoot.appendChild(template.content.cloneNode(true)); + } +} diff --git a/chromium/chrome/browser/resources/tab_strip/tab.html b/chromium/chrome/browser/resources/tab_strip/tab.html new file mode 100644 index 00000000000..1e715432804 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tab.html @@ -0,0 +1,109 @@ +<style> + :host { + border-radius: var(--tabstrip-card-border-radius); + box-shadow: var(--tabstrip-elevation-box-shadow); + cursor: pointer; + display: flex; + flex-direction: column; + height: 230px; + overflow: hidden; + width: 280px; + } + + :host([active]) { + box-shadow: 0 0 0 2px var(--tabstrip-focus-color); + outline: none; + } + + #title { + align-items: center; + background: var(--tabstrip-card-background-color); + border-block-end: 1px solid var(--tabstrip-separator-color); + box-sizing: border-box; + display: flex; + height: 40px; + justify-content: center; + margin: 0; + padding-inline-end: 4px; + padding-inline-start: 12px; + } + + #favicon { + flex-shrink: 0; + height: 16px; + margin-inline-end: 8px; + width: 16px; + } + + #titleText { + font-size: 100%; + font-weight: normal; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + #close { + -webkit-appearance: none; + align-items: center; + background-color: transparent; + border: 0; + display: flex; + flex-shrink: 0; + height: 32px; + justify-content: center; + margin-inline-start: auto; + padding: 0; + position: relative; + width: 32px; + } + + #closeIcon { + background: + url(chrome://resources/images/icon_clear.svg) center/contain no-repeat; + display: block; + height: 24px; + position: relative; + width: 24px; + } + + #thumbnail { + background: var(--tabstrip-card-background-color); + flex: 1; + } + + #thumbnailImg { + height: 100%; + object-fit: contain; + width: 100%; + } + + /* Pinned tab styles */ + :host([pinned]) { + height: 50px; + width: 50px; + } + + :host([pinned]) #title { + border-block-end: 0; + height: 100%; + } + + :host([pinned]) #titleText, + :host([pinned]) #close, + :host([pinned]) #thumbnail { + display: none; + } +</style> + +<header id="title"> + <span id="favicon"></span> + <h2 id="titleText"></h2> + <button id="close"> + <span id="closeIcon"></span> + </button> +</header> + +<div id="thumbnail"> + <img id="thumbnailImg"> +</div> diff --git a/chromium/chrome/browser/resources/tab_strip/tab.js b/chromium/chrome/browser/resources/tab_strip/tab.js new file mode 100644 index 00000000000..0b16488f0ca --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tab.js @@ -0,0 +1,153 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {getFavicon, getFaviconForPageURL} from 'chrome://resources/js/icon.m.js'; + +import {CustomElement} from './custom_element.js'; +import {TabsApiProxy} from './tabs_api_proxy.js'; + +export const DEFAULT_ANIMATION_DURATION = 125; + +export class TabElement extends CustomElement { + static get template() { + return `{__html_template__}`; + } + + constructor() { + super(); + + /** @private {!HTMLElement} */ + this.closeButtonEl_ = + /** @type {!HTMLElement} */ (this.shadowRoot.querySelector('#close')); + + /** @private {!HTMLElement} */ + this.faviconEl_ = + /** @type {!HTMLElement} */ (this.shadowRoot.querySelector('#favicon')); + + /** @private {!HTMLElement} */ + this.thumbnailContainer_ = + /** @type {!HTMLElement} */ ( + this.shadowRoot.querySelector('#thumbnail')); + + /** @private {!Image} */ + this.thumbnail_ = + /** @type {!Image} */ (this.shadowRoot.querySelector('#thumbnailImg')); + + /** @private {!Tab} */ + this.tab_; + + /** @private {!TabsApiProxy} */ + this.tabsApi_ = TabsApiProxy.getInstance(); + + /** @private {!HTMLElement} */ + this.titleTextEl_ = /** @type {!HTMLElement} */ ( + this.shadowRoot.querySelector('#titleText')); + + this.addEventListener('click', this.onClick_.bind(this)); + this.closeButtonEl_.addEventListener('click', this.onClose_.bind(this)); + } + + /** @return {!Tab} */ + get tab() { + return this.tab_; + } + + /** @param {!Tab} tab */ + set tab(tab) { + this.toggleAttribute('active', tab.active); + this.toggleAttribute('pinned', tab.pinned); + + if (!this.tab_ || this.tab_.title !== tab.title) { + this.titleTextEl_.textContent = tab.title; + } + + if (tab.favIconUrl && + (!this.tab_ || this.tab_.favIconUrl !== tab.favIconUrl)) { + this.faviconEl_.style.backgroundImage = getFavicon(tab.favIconUrl); + } else if (!this.tab_ || this.tab_.url !== tab.url) { + this.faviconEl_.style.backgroundImage = + getFaviconForPageURL(tab.url, false); + } + + // Expose the ID to an attribute to allow easy querySelector use + this.setAttribute('data-tab-id', tab.id); + + if (!this.tab_ || this.tab_.id !== tab.id) { + // Request thumbnail updates + chrome.send('addTrackedTab', [tab.id]); + } + + this.tab_ = Object.freeze(tab); + } + + /** + * @param {string} imgData + */ + updateThumbnail(imgData) { + this.thumbnail_.src = imgData; + } + + /** @private */ + onClick_() { + if (!this.tab_) { + return; + } + + this.tabsApi_.activateTab(this.tab_.id); + } + + /** + * @param {!Event} event + * @private + */ + onClose_(event) { + if (!this.tab_) { + return; + } + + event.stopPropagation(); + this.tabsApi_.closeTab(this.tab_.id); + } + + /** + * @return {!Promise} + */ + slideIn() { + return new Promise(resolve => { + const animation = this.animate( + [ + {maxWidth: 0, opacity: 0}, + {maxWidth: '280px', opacity: 1}, + ], + { + duration: DEFAULT_ANIMATION_DURATION, + fill: 'forwards', + }); + animation.onfinish = resolve; + }); + } + + /** + * @return {!Promise} + */ + slideOut() { + return new Promise(resolve => { + const animation = this.animate( + [ + {maxWidth: '280px', opacity: 1}, + {maxWidth: 0, opacity: 0}, + ], + { + duration: DEFAULT_ANIMATION_DURATION, + fill: 'forwards', + }); + animation.onfinish = () => { + this.remove(); + resolve(); + }; + }); + } +} + +customElements.define('tabstrip-tab', TabElement); diff --git a/chromium/chrome/browser/resources/tab_strip/tab_list.html b/chromium/chrome/browser/resources/tab_strip/tab_list.html new file mode 100644 index 00000000000..680c562aa68 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tab_list.html @@ -0,0 +1,51 @@ +<style> + :host { + display: flex; + padding: 16px; + width: fit-content; + } + + #pinnedTabsContainer { + display: grid; + grid-auto-columns: 50px; + grid-auto-flow: column; + grid-gap: 10px; + grid-template-rows: repeat(4, 50px); + margin-inline-end: 16px; + } + + #pinnedTabsContainer[empty] { + display: none; + } + + .ghost-pinned-tab { + background: var(--tabstrip-card-background-color); + border-radius: var(--tabstrip-card-border-radius); + box-shadow: var(--tabstrip-elevation-box-shadow); + opacity: 0.5; + } + + /* The #pinnedTabsContainer can only fit a maximum of 4 pinned tabs. The + * ghost-pinned-tab elements are meant to add as placeholders if there + * are not enough actual pinned tabs to fill an entire column. Therefore, + * all ghost-pinned-tabs after the 4 * nth element should be hidden. */ + .ghost-pinned-tab:nth-child(4n + 1), + .ghost-pinned-tab:nth-child(4n + 1) ~ .ghost-pinned-tab { + display: none; + } + + #tabsContainer { + display: flex; + } + + #tabsContainer tabstrip-tab:not(:last-child) { + margin-inline-end: 16px; + } +</style> + +<div id="pinnedTabsContainer" empty> + <div class="ghost-pinned-tab"></div> + <div class="ghost-pinned-tab"></div> + <div class="ghost-pinned-tab"></div> +</div> +<div id="tabsContainer"></div> diff --git a/chromium/chrome/browser/resources/tab_strip/tab_list.js b/chromium/chrome/browser/resources/tab_strip/tab_list.js new file mode 100644 index 00000000000..dd72aec77bd --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tab_list.js @@ -0,0 +1,249 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import './tab.js'; + +import {addWebUIListener} from 'chrome://resources/js/cr.m.js'; +import {CustomElement} from './custom_element.js'; +import {TabElement} from './tab.js'; +import {TabsApiProxy} from './tabs_api_proxy.js'; + +const GHOST_PINNED_TAB_COUNT = 3; + +class TabListElement extends CustomElement { + static get template() { + return `{__html_template__}`; + } + + constructor() { + super(); + + /** + * A chain of promises that the tab list needs to keep track of. The chain + * is useful in cases when the list needs to wait for all animations to + * finish in order to get accurate pixels (such as getting the position of a + * tab) or accurate element counts. + * @type {!Promise} + */ + this.animationPromises = Promise.resolve(); + + /** @private {!Element} */ + this.pinnedTabsContainerElement_ = + /** @type {!Element} */ ( + this.shadowRoot.querySelector('#pinnedTabsContainer')); + + /** @private {!TabsApiProxy} */ + this.tabsApi_ = TabsApiProxy.getInstance(); + + /** @private {!Object} */ + this.tabsApiHandler_ = this.tabsApi_.callbackRouter; + + /** @private {!Element} */ + this.tabsContainerElement_ = + /** @type {!Element} */ ( + this.shadowRoot.querySelector('#tabsContainer')); + + /** @private {number} */ + this.windowId_; + + addWebUIListener( + 'tab-thumbnail-updated', this.tabThumbnailUpdated_.bind(this)); + } + + /** + * @param {!Promise} promise + * @private + */ + addAnimationPromise_(promise) { + this.animationPromises = this.animationPromises.then(() => promise); + } + + connectedCallback() { + this.tabsApi_.getCurrentWindow().then((currentWindow) => { + this.windowId_ = currentWindow.id; + + // TODO(johntlee): currentWindow.tabs is guaranteed to be defined because + // `populate: true` is passed in as part of the arguments to the API. + // Once the closure compiler is able to type `assert` to return a truthy + // type even when being used with modules, the conditionals should be + // replaced with `assert` (b/138729777). + if (currentWindow.tabs) { + for (const tab of currentWindow.tabs) { + if (tab) { + this.onTabCreated_(tab); + } + } + } + + this.tabsApiHandler_.onActivated.addListener( + this.onTabActivated_.bind(this)); + this.tabsApiHandler_.onCreated.addListener(this.onTabCreated_.bind(this)); + this.tabsApiHandler_.onMoved.addListener(this.onTabMoved_.bind(this)); + this.tabsApiHandler_.onRemoved.addListener(this.onTabRemoved_.bind(this)); + this.tabsApiHandler_.onUpdated.addListener(this.onTabUpdated_.bind(this)); + }); + } + + /** + * @param {!Tab} tab + * @return {!TabElement} + * @private + */ + createTabElement_(tab) { + const tabElement = new TabElement(); + tabElement.tab = tab; + return tabElement; + } + + /** + * @param {number} tabId + * @return {?TabElement} + * @private + */ + findTabElement_(tabId) { + return /** @type {?TabElement} */ ( + this.shadowRoot.querySelector(`tabstrip-tab[data-tab-id="${tabId}"]`)); + } + + /** + * @param {!TabElement} tabElement + * @param {number} index + * @private + */ + insertTabOrMoveTo_(tabElement, index) { + // Remove the tabElement if it already exists in the DOM + tabElement.remove(); + + if (tabElement.tab && tabElement.tab.pinned) { + this.pinnedTabsContainerElement_.insertBefore( + tabElement, this.pinnedTabsContainerElement_.childNodes[index]); + } else { + // Pinned tabs are in their own container, so the index of non-pinned + // tabs need to be offset by the number of pinned tabs + const offsetIndex = index - + (this.pinnedTabsContainerElement_.childElementCount - + GHOST_PINNED_TAB_COUNT); + this.tabsContainerElement_.insertBefore( + tabElement, this.tabsContainerElement_.childNodes[offsetIndex]); + } + + this.updatePinnedTabsState_(); + } + + /** + * @param {!TabActivatedInfo} activeInfo + * @private + */ + onTabActivated_(activeInfo) { + if (activeInfo.windowId !== this.windowId_) { + return; + } + + const previouslyActiveTab = + this.shadowRoot.querySelector('tabstrip-tab[active]'); + if (previouslyActiveTab) { + previouslyActiveTab.tab = /** @type {!Tab} */ ( + Object.assign({}, previouslyActiveTab.tab, {active: false})); + } + + const newlyActiveTab = this.findTabElement_(activeInfo.tabId); + newlyActiveTab.tab = /** @type {!Tab} */ ( + Object.assign({}, newlyActiveTab.tab, {active: true})); + } + + /** + * @param {!Tab} tab + * @private + */ + onTabCreated_(tab) { + if (tab.windowId !== this.windowId_) { + return; + } + + const tabElement = this.createTabElement_(tab); + this.insertTabOrMoveTo_(tabElement, tab.index); + this.addAnimationPromise_(tabElement.slideIn()); + } + + /** + * @param {number} tabId + * @param {!TabMovedInfo} moveInfo + * @private + */ + onTabMoved_(tabId, moveInfo) { + if (moveInfo.windowId !== this.windowId_) { + return; + } + + const movedTab = this.findTabElement_(tabId); + if (movedTab) { + this.insertTabOrMoveTo_(movedTab, moveInfo.toIndex); + } + } + + /** + * @param {number} tabId + * @param {!WindowRemoveInfo} removeInfo + * @private + */ + onTabRemoved_(tabId, removeInfo) { + if (removeInfo.windowId !== this.windowId_) { + return; + } + + const tabElement = this.findTabElement_(tabId); + if (tabElement) { + this.addAnimationPromise_(new Promise(async resolve => { + await tabElement.slideOut(); + this.updatePinnedTabsState_(); + resolve(); + })); + } + } + + /** + * @param {number} tabId + * @param {!Tab} changeInfo + * @param {!Tab} tab + * @private + */ + onTabUpdated_(tabId, changeInfo, tab) { + if (tab.windowId !== this.windowId_) { + return; + } + + const tabElement = this.findTabElement_(tabId); + if (tabElement) { + tabElement.tab = tab; + + if (changeInfo.pinned !== undefined) { + // If the tab is being pinned or unpinned, we need to move it to its new + // location + this.insertTabOrMoveTo_(tabElement, tab.index); + } + } + } + + /** + * @param {number} tabId + * @param {string} imgData + * @private + */ + tabThumbnailUpdated_(tabId, imgData) { + const tab = this.findTabElement_(tabId); + if (tab) { + tab.updateThumbnail(imgData); + } + } + + /** @private */ + updatePinnedTabsState_() { + this.pinnedTabsContainerElement_.toggleAttribute( + 'empty', + this.pinnedTabsContainerElement_.childElementCount === + GHOST_PINNED_TAB_COUNT); + } +} + +customElements.define('tabstrip-tab-list', TabListElement); diff --git a/chromium/chrome/browser/resources/tab_strip/tab_strip.html b/chromium/chrome/browser/resources/tab_strip/tab_strip.html new file mode 100644 index 00000000000..088f0ea0097 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tab_strip.html @@ -0,0 +1,53 @@ +<!doctype html> +<html dir="$i18n{textdirection}" lang="$i18n{language}"> + <head> + <meta charset="utf-8"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> + <style> + html { + --google-grey-50-rgb: 248, 249, 250; + --google-grey-200-rgb: 232, 234, 237; + --google-grey-300-rgb: 218, 220, 224; + --google-grey-800-rgb: 60, 64, 67; + --google-grey-900-rgb: 32, 33, 36; + --google-blue-300-rgb: 138, 180, 248; + --google-blue-500-rgb: 66, 133, 244; + + --tabstrip-background-color: rgb(var(--google-grey-50-rgb)); + --tabstrip-card-background-color: white; + --tabstrip-card-border-radius: 8px; + --tabstrip-elevation-box-shadow: + 0 0 0 1px rgb(var(--google-grey-300-rgb)); + --tabstrip-focus-color: rgb(var(--google-blue-500-rgb)); + --tabstrip-primary-text-color: rgb(var(--google-grey-900-rgb)); + --tabstrip-separator-color: rgb(var(--google-grey-300-rgb)); + } + + @media (prefers-color-scheme: dark) { + html { + --tabstrip-background-color: rgba(var(--google-grey-900-rgb)); + --tabstrip-card-background-color: rgba(255, 255, 255, 0.04); + --tabstrip-elevation-box-shadow: none; + --tabstrip-focus-color: rgb(var(--google-blue-300-rgb)); + --tabstrip-primary-text-color: rgb(var(--google-grey-200-rgb)); + --tabstrip-separator-color: rgb(255, 255, 255, 0.1); + } + } + + body { + background: var(--tabstrip-background-color); + color: var(--tabstrip-primary-text-color); + margin: 0; + padding: 0; + } + + ::-webkit-scrollbar { + display: none; + } + </style> + </head> + <body> + <tabstrip-tab-list></tabstrip-tab-list> + <script src="tab_list.js" type="module"></script> + </body> +</html> diff --git a/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd b/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd new file mode 100644 index 00000000000..72257fd7930 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> + <outputs> + <output filename="grit/tab_strip_resources.h" type="rc_header"> + <emit emit_type='prepend'></emit> + </output> + <output filename="grit/tab_strip_resources_map.cc" + type="resource_file_map_source" /> + <output filename="grit/tab_strip_resources_map.h" + type="resource_map_header" /> + <output filename="tab_strip_resources.pak" type="data_package" /> + </outputs> + <release seq="1"> + <structures> + <structure + name="IDR_TAB_STRIP_HTML" + file="tab_strip.html" + type="chrome_html" + compress="gzip"/> + <structure + name="IDR_TAB_STRIP_TABS_API_PROXY_JS" + file="tabs_api_proxy.js" + type="chrome_html" + compress="gzip"/> + <structure + name="IDR_TAB_STRIP_CUSTOM_ELEMENT_JS" + file="custom_element.js" + type="chrome_html" + compress="gzip"/> + <structure + name="IDR_TAB_STRIP_TAB_LIST_JS" + file="${root_gen_dir}/chrome/browser/resources/tab_strip/tab_list.js" + use_base_dir="false" + type="chrome_html" + compress="gzip"/> + <structure + name="IDR_TAB_STRIP_TAB_JS" + file="${root_gen_dir}/chrome/browser/resources/tab_strip/tab.js" + use_base_dir="false" + type="chrome_html" + compress="gzip"/> + </structures> + </release> +</grit> diff --git a/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js b/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js new file mode 100644 index 00000000000..9ce6ad61f28 --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js @@ -0,0 +1,68 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {addSingletonGetter} from 'chrome://resources/js/cr.m.js'; + +export class TabsApiProxy { + constructor() { + /** @type {!Object<string, !ChromeEvent>} */ + this.callbackRouter = { + onActivated: chrome.tabs.onActivated, + onCreated: chrome.tabs.onCreated, + onMoved: chrome.tabs.onMoved, + onRemoved: chrome.tabs.onRemoved, + onUpdated: chrome.tabs.onUpdated, + }; + } + + /** + * @param {number} tabId + * @return {!Promise<!Tab>} + */ + activateTab(tabId) { + return new Promise(resolve => { + chrome.tabs.update(tabId, {active: true}, resolve); + }); + } + + /** + * @return {!Promise<!ChromeWindow>} + */ + getCurrentWindow() { + const options = { + populate: true, // populate window data with tabs data + windowTypes: ['normal'], // prevent devtools from being returned + }; + return new Promise(resolve => { + chrome.windows.getCurrent(options, currentWindow => { + resolve(currentWindow); + }); + }); + } + + /** + * @param {number} tabId + * @return {!Promise} + */ + closeTab(tabId) { + return new Promise(resolve => { + chrome.tabs.remove(tabId, resolve); + }); + } + + /** + * @param {number} tabId + * @param {number} newIndex + * @return {!Promise<!Tab>} + */ + moveTab(tabId, newIndex) { + return new Promise(resolve => { + chrome.tabs.move(tabId, {index: newIndex}, tab => { + resolve(tab); + }); + }); + } +} + +addSingletonGetter(TabsApiProxy); diff --git a/chromium/chrome/browser/resources/tab_strip/types.js b/chromium/chrome/browser/resources/tab_strip/types.js new file mode 100644 index 00000000000..6496711a0da --- /dev/null +++ b/chromium/chrome/browser/resources/tab_strip/types.js @@ -0,0 +1,32 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Closure typedefs for Tab Strip. + */ + +/** + * @typedef {{ + * tabId: number, + * windowId: number, + * }} + */ +let TabActivatedInfo; + +/** + * @typedef {{ + * fromIndex: number, + * toIndex: number, + * windowId: number, + * }} + */ +let TabMovedInfo; + +/** + * @typedef {{ + * isWindowClosing: boolean, + * windowId: number, + * }} + */ +let WindowRemoveInfo; diff --git a/chromium/chrome/browser/resources/usb_internals/BUILD.gn b/chromium/chrome/browser/resources/usb_internals/BUILD.gn index 28ec89bb179..d4d21445df1 100644 --- a/chromium/chrome/browser/resources/usb_internals/BUILD.gn +++ b/chromium/chrome/browser/resources/usb_internals/BUILD.gn @@ -7,26 +7,33 @@ import("//third_party/closure_compiler/compile_js.gni") js_type_check("closure_compile") { deps = [ ":descriptor_panel", - ":device_page", + ":devices_page", ":usb_internals", ] } js_library("usb_internals") { deps = [ - ":device_page", + ":devices_page", "//chrome/browser/ui/webui/usb_internals:mojo_bindings_js_library_for_compile", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:util", "//ui/webui/resources/js/cr/ui:tabs", + "//ui/webui/resources/js/cr/ui:tree", ] } js_library("devices_page") { deps = [ ":descriptor_panel", + "//chrome/browser/ui/webui/usb_internals:mojo_bindings_js_library_for_compile", + "//ui/webui/resources/js:cr", ] } js_library("descriptor_panel") { + deps = [ + "//chrome/browser/ui/webui/usb_internals:mojo_bindings_js_library_for_compile", + "//ui/webui/resources/js:cr", + ] } diff --git a/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js b/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js index 62d2910203f..6c0bfa8271c 100644 --- a/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js +++ b/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js @@ -125,10 +125,10 @@ cr.define('descriptor_panel', function() { /** * Adds the reference of the string descriptor panel of the device for * string descriptor functionality. - * @param {!DescriptorPanel} stringDescriptorPanel + * @param {!descriptor_panel.DescriptorPanel} stringDescriptorPanel */ setStringDescriptorPanel(stringDescriptorPanel) { - /** @type {!DescriptorPanel} */ + /** @type {!descriptor_panel.DescriptorPanel} */ this.stringDescriptorPanel_ = stringDescriptorPanel; } @@ -166,7 +166,7 @@ cr.define('descriptor_panel', function() { this.stringDescriptorPanel_.stringDescriptorIndexes.add(index); } - const buttonTemplate = document.querySelector('#raw-data-tree-button'); + const buttonTemplate = queryRequiredElement('#raw-data-tree-button'); const button = document.importNode(buttonTemplate.content, true) .querySelector('button'); item.labelElement.appendChild(button); @@ -200,7 +200,7 @@ cr.define('descriptor_panel', function() { renderUrlDescriptorIndexItem_(rawData, offset, item, fieldLabel) { const index = rawData[offset]; if (index > 0) { - const buttonTemplate = document.querySelector('#raw-data-tree-button'); + const buttonTemplate = queryRequiredElement('#raw-data-tree-button'); const button = document.importNode(buttonTemplate.content, true) .querySelector('button'); item.labelElement.appendChild(button); @@ -238,7 +238,7 @@ cr.define('descriptor_panel', function() { const msOs20DescriptorSetLength = data.getUint16(MS_OS_20_SET_TOTAL_LENGTH_OFFSET, true); - const buttonTemplate = document.querySelector('#raw-data-tree-button'); + const buttonTemplate = queryRequiredElement('#raw-data-tree-button'); const button = document.importNode(buttonTemplate.content, true) .querySelector('button'); item.labelElement.appendChild(button); @@ -277,7 +277,7 @@ cr.define('descriptor_panel', function() { if (altEnumCode !== 0) { const vendorCode = rawData[offset + MS_OS_20_VENDOR_CODE_ITEM_OFFSET]; - const buttonTemplate = document.querySelector('#raw-data-tree-button'); + const buttonTemplate = queryRequiredElement('#raw-data-tree-button'); const button = document.importNode(buttonTemplate.content, true) .querySelector('button'); item.labelElement.appendChild(button); @@ -451,14 +451,13 @@ cr.define('descriptor_panel', function() { */ async getDeviceDescriptor() { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.STANDARD; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - usbControlTransferParams.request = GET_DESCRIPTOR_REQUEST; - usbControlTransferParams.value = (DEVICE_DESCRIPTOR_TYPE << 8); - usbControlTransferParams.index = 0; + const usbControlTransferParams = { + type: device.mojom.UsbControlTransferType.STANDARD, + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + request: GET_DESCRIPTOR_REQUEST, + value: DEVICE_DESCRIPTOR_TYPE << 8, + index: 0, + }; try { await this.usbDeviceProxy_.open(); @@ -577,14 +576,13 @@ cr.define('descriptor_panel', function() { */ async getConfigurationDescriptor() { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.STANDARD; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - usbControlTransferParams.request = GET_DESCRIPTOR_REQUEST; - usbControlTransferParams.value = (CONFIGURATION_DESCRIPTOR_TYPE << 8); - usbControlTransferParams.index = 0; + const usbControlTransferParams = { + type: device.mojom.UsbControlTransferType.STANDARD, + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + request: GET_DESCRIPTOR_REQUEST, + value: CONFIGURATION_DESCRIPTOR_TYPE << 8, + index: 0, + }; try { await this.usbDeviceProxy_.open(); @@ -683,7 +681,7 @@ cr.define('descriptor_panel', function() { * @param {number} offset The start offset of the interface * descriptor. * @param {number} indexInterface - * @return {!Array<number>} + * @return {!cr.ui.TreeItem} * @private */ renderInterfaceDescriptor_( @@ -752,13 +750,12 @@ cr.define('descriptor_panel', function() { /** * Renders a tree item to display endpoint descriptor at index * indexEndpoint. - * @param {!cr.ui.Tree} rawDataTreeRoot + * @param {!cr.ui.Tree|!cr.ui.TreeItem} rawDataTreeRoot * @param {!HTMLElement} rawDataByteElement * @param {!Uint8Array} rawData * @param {number} offset The start offset of the endpoint * descriptor. * @param {number} indexEndpoint - * @return {number} * @private */ renderEndpointDescriptor_( @@ -814,7 +811,6 @@ cr.define('descriptor_panel', function() { * @param {!Uint8Array} rawData * @param {number} originalOffset The start offset of the this descriptor. * @param {number} indexUnknown - * @return {number} * @private */ renderUnknownDescriptor_( @@ -856,18 +852,17 @@ cr.define('descriptor_panel', function() { * Gets all the supported language codes of this device, and adds them as * autocompletions for the language code input area in the string descriptor * panel. - * @return {!Array<string>} + * @return {!Promise<!Array<number>>} */ async getAllLanguageCodes() { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.STANDARD; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - usbControlTransferParams.request = GET_DESCRIPTOR_REQUEST; - usbControlTransferParams.value = (STRING_DESCRIPTOR_TYPE << 8); - usbControlTransferParams.index = 0; + const usbControlTransferParams = { + type: device.mojom.UsbControlTransferType.STANDARD, + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + request: GET_DESCRIPTOR_REQUEST, + value: STRING_DESCRIPTOR_TYPE << 8, + index: 0, + }; let response; try { @@ -886,7 +881,7 @@ cr.define('descriptor_panel', function() { showError(e.message, this.rootElement_); // Stop rendering autocomplete datalist if failed to read the string // descriptor. - return new Uint8Array(); + return []; } finally { await this.usbDeviceProxy_.close(); } @@ -920,20 +915,18 @@ cr.define('descriptor_panel', function() { * @param {number} index * @param {number} languageCode * @param {!cr.ui.TreeItem=} treeItem - * @return {{languageCode:string,rawData:!Uint8Array}} * @private */ async getStringDescriptorForLanguageCode_( index, languageCode, treeItem = undefined) { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.STANDARD; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - usbControlTransferParams.request = GET_DESCRIPTOR_REQUEST; - usbControlTransferParams.index = languageCode; - usbControlTransferParams.value = (STRING_DESCRIPTOR_TYPE << 8) | index; + const usbControlTransferParams = { + type: device.mojom.UsbControlTransferType.STANDARD, + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + request: GET_DESCRIPTOR_REQUEST, + index: languageCode, + value: (STRING_DESCRIPTOR_TYPE << 8) | index, + }; try { await this.usbDeviceProxy_.open(); @@ -1025,18 +1018,18 @@ cr.define('descriptor_panel', function() { this.indexInput_.value = index; - /** @type {!Array<number>|undefined} */ + /** @type {!Array<number>} */ const languageCodesList = await this.getAllLanguageCodes(); for (const languageCode of languageCodesList) { await this.getStringDescriptorForLanguageCode_( - index, languageCode, treeItem); + index, languageCode, assert(treeItem)); } } /** * Initializes the string descriptor panel for autocomplete functionality. - * @param {number} tabId + * @param {string} tabId */ initialStringDescriptorPanel(tabId) { // Binds the input area and datalist use each tab's unique id. @@ -1046,21 +1039,22 @@ cr.define('descriptor_panel', function() { .forEach(el => el.id = `${el.id}-${tabId}`); /** @type {!HTMLElement} */ - const button = this.rootElement_.querySelector('button'); + const button = queryRequiredElement('button', this.rootElement_); /** @type {!HTMLElement} */ - this.indexInput_ = this.rootElement_.querySelector('#index-input'); + this.indexInput_ = + queryRequiredElement('#index-input', this.rootElement_); /** @type {!HTMLElement} */ const languageCodeInput = - this.rootElement_.querySelector('#language-code-input'); + queryRequiredElement('#language-code-input', this.rootElement_); button.addEventListener('click', async () => { this.clearView(); - const index = Number.parseInt(this.indexInput_.value); + const index = Number.parseInt(this.indexInput_.value, 10); if (this.checkParamValid_(index, 'Index', 1, 255)) { if (languageCodeInput.value === 'All') { await this.getStringDescriptorForAllLanguages_(index); } else { - const languageCode = Number.parseInt(languageCodeInput.value); + const languageCode = Number.parseInt(languageCodeInput.value, 10); if (this.checkParamValid_( languageCode, 'Language Code', 0, 65535)) { await this.getStringDescriptorForLanguageCode_( @@ -1074,10 +1068,10 @@ cr.define('descriptor_panel', function() { this.stringDescriptorIndexes = new Set(); /** @type {!HTMLElement} */ this.indexesListElement = - this.rootElement_.querySelector(`#indexes-${tabId}`); + queryRequiredElement(`#indexes-${tabId}`, this.rootElement_); /** @type {!HTMLElement} */ this.languageCodesListElement_ = - this.rootElement_.querySelector(`#languages-${tabId}`); + queryRequiredElement(`#languages-${tabId}`, this.rootElement_); } /** @@ -1087,14 +1081,13 @@ cr.define('descriptor_panel', function() { */ async getBosDescriptor() { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.STANDARD; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - usbControlTransferParams.request = GET_DESCRIPTOR_REQUEST; - usbControlTransferParams.value = (BOS_DESCRIPTOR_TYPE << 8); - usbControlTransferParams.index = 0; + const usbControlTransferParams = { + type: device.mojom.UsbControlTransferType.STANDARD, + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + request: GET_DESCRIPTOR_REQUEST, + value: BOS_DESCRIPTOR_TYPE << 8, + index: 0, + }; try { await this.usbDeviceProxy_.open(); @@ -1183,13 +1176,13 @@ cr.define('descriptor_panel', function() { break; } else if (isSameUuid( rawData, offset, MS_OS_20_PLATFORM_CAPABILITY_UUID)) { - offset = this.renderMsOs20PlatformDescriptor_( + this.renderMsOs20PlatformDescriptor_( rawDataTreeRoot, rawDataByteElement, rawData, offset, indexDevCapability); break; } default: - offset = this.renderUnknownBosDescriptor_( + this.renderUnknownBosDescriptor_( rawDataTreeRoot, rawDataByteElement, rawData, offset, indexDevCapability); } @@ -1326,7 +1319,7 @@ cr.define('descriptor_panel', function() { /** * Renders a tree item to display Microsoft OS 2.0 descriptor set * information at index indexMsOs20DescriptorSetInfo. - * @param {!cr.ui.Tree} rawDataTreeRoot + * @param {!cr.ui.Tree|!cr.ui.TreeItem} rawDataTreeRoot * @param {!HTMLElement} rawDataByteElement * @param {!Uint8Array} rawData * @param {number} offset The start offset of the Microsoft OS 2.0 @@ -1451,16 +1444,15 @@ cr.define('descriptor_panel', function() { const urlIndex = rawData[offset + WEB_USB_URL_DESCRIPTOR_INDEX_OFFSET]; /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - // These constants are defined by the WebUSB specification: - // http://wicg.github.io/webusb/ - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.VENDOR; - usbControlTransferParams.request = vendorCode; - usbControlTransferParams.value = urlIndex; - usbControlTransferParams.index = GET_URL_REQUEST; + const usbControlTransferParams = { + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + // These constants are defined by the WebUSB specification: + // http://wicg.github.io/webusb/ + type: device.mojom.UsbControlTransferType.VENDOR, + request: vendorCode, + value: urlIndex, + index: GET_URL_REQUEST, + }; try { await this.usbDeviceProxy_.open(); @@ -1509,21 +1501,20 @@ cr.define('descriptor_panel', function() { /** * Gets the Microsoft OS 2.0 Descriptor vendor-specific descriptor. * @param {number} vendorCode - * @return {!Uint8Array} + * @return {!Promise<!Uint8Array>} * @private */ async getMsOs20DescriptorSet_(vendorCode, msOs20DescriptorSetLength) { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - // These constants are defined by Microsoft OS 2.0 Descriptors - // Specification (July, 2018). - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.VENDOR; - usbControlTransferParams.request = vendorCode; - usbControlTransferParams.value = 0; - usbControlTransferParams.index = MS_OS_20_DESCRIPTOR_INDEX; + const usbControlTransferParams = { + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + // These constants are defined by Microsoft OS 2.0 Descriptors + // Specification (July, 2018). + type: device.mojom.UsbControlTransferType.VENDOR, + request: vendorCode, + value: 0, + index: MS_OS_20_DESCRIPTOR_INDEX, + }; let response; try { @@ -1541,7 +1532,7 @@ cr.define('descriptor_panel', function() { showError(e.message, this.rootElement_); // Returns an empty array if failed to read the Microsoft OS 2.0 // descriptor set. - return new Uint8Array(); + return new Uint8Array(0); } finally { await this.usbDeviceProxy_.close(); } @@ -1557,16 +1548,15 @@ cr.define('descriptor_panel', function() { */ async sendMsOs20DescriptorSetAltEnumCommand_(vendorCode, altEnumCode) { /** @type {!device.mojom.UsbControlTransferParams} */ - const usbControlTransferParams = {}; - usbControlTransferParams.recipient = - device.mojom.UsbControlTransferRecipient.DEVICE; - // These constants are defined by Microsoft OS 2.0 Descriptors - // Specification (July, 2018). - usbControlTransferParams.type = - device.mojom.UsbControlTransferType.VENDOR; - usbControlTransferParams.request = vendorCode; - usbControlTransferParams.value = altEnumCode; - usbControlTransferParams.index = MS_OS_20_SET_ALT_ENUMERATION; + const usbControlTransferParams = { + recipient: device.mojom.UsbControlTransferRecipient.DEVICE, + // These constants are defined by Microsoft OS 2.0 Descriptors + // Specification (July, 2018). + type: device.mojom.UsbControlTransferType.VENDOR, + request: vendorCode, + value: altEnumCode, + index: MS_OS_20_SET_ALT_ENUMERATION, + }; try { await this.usbDeviceProxy_.open(); @@ -2311,7 +2301,7 @@ cr.define('descriptor_panel', function() { * Gets response of the given request. * @param {!device.mojom.UsbControlTransferParams} usbControlTransferParams * @param {number} length - * @param {number} direction + * @param {string} direction * @private */ async sendTestingRequest_(usbControlTransferParams, length, direction) { @@ -2333,8 +2323,7 @@ cr.define('descriptor_panel', function() { } const response = await this.usbDeviceProxy_.controlTransferOut( - usbControlTransferParams, new Uint8Array(data), - CONTROL_TRANSFER_TIMEOUT_MS); + usbControlTransferParams, data, CONTROL_TRANSFER_TIMEOUT_MS); checkTransferSuccess( response.status, 'Failed to send request.', this.rootElement_); } @@ -2387,17 +2376,20 @@ cr.define('descriptor_panel', function() { this.clearView(); const index = testingToolPanelInputTypeSelector.selectedIndex; inputTableRows.forEach(row => row.hidden = true); - inputTableRows[index].hidden = false; + const rowAtIndex = assertInstanceof(inputTableRows[index], HTMLElement); + rowAtIndex.hidden = false; - const direction = getRequestTypeDirection(inputTableRows[index], index); - const length = getRequestLength(inputTableRows[index], index); + const direction = getRequestTypeDirection(rowAtIndex, index); + const length = getRequestLength(rowAtIndex, index); this.rootElement_.querySelector('#data-input-area').hidden = (direction !== 'Host-to-Device'); dataInputArea.value = '00'.repeat(length); dataInputArea.maxLength = length * 2; }); - for (const [i, inputTableRow] of inputTableRows.entries()) { + + inputTableRows.forEach((el, i) => { + const inputTableRow = assertInstanceof(el, HTMLElement); let directionInputElement; switch (i) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: @@ -2420,19 +2412,20 @@ cr.define('descriptor_panel', function() { dataInputArea.value = '00'.repeat(length); dataInputArea.maxLength = length * 2; }); - } + }); - for (const [i, button] of buttons.entries()) { + buttons.forEach((button, i) => { button.addEventListener('click', () => { this.clearView(); - const direction = getRequestTypeDirection(inputTableRows[i], i); - const type = getRequestType(inputTableRows[i], i); - const recipient = getRequestTypeRecipient(inputTableRows[i], i); - const request = getRequestCode(inputTableRows[i], i); - const value = getRequestValue(inputTableRows[i], i); - const index = getRequestIndex(inputTableRows[i], i); - const dataLength = getRequestLength(inputTableRows[i], i); + const row = assertInstanceof(inputTableRows[i], HTMLElement); + const direction = getRequestTypeDirection(row, i); + const type = getRequestType(row, i); + const recipient = getRequestTypeRecipient(row, i); + const request = getRequestCode(row, i); + const value = getRequestValue(row, i); + const index = getRequestIndex(row, i); + const dataLength = getRequestLength(row, i); if (this.checkEnumParamValid_( type, 'Transfer Type', device.mojom.UsbControlTransferType) && @@ -2455,7 +2448,7 @@ cr.define('descriptor_panel', function() { usbControlTransferParams, dataLength, direction); } }); - } + }); } /** @@ -2501,10 +2494,10 @@ cr.define('descriptor_panel', function() { function getRequestType(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return inputRow.querySelector('#transfer-type').value; + return queryRequiredElement('#transfer-type', inputRow).value; case INPUT_TYPE_HEX_BYTE: const value = Number.parseInt( - inputRow.querySelector('#query-request-type').value, 16); + queryRequiredElement('#query-request-type', inputRow).value, 16); switch (value >> 5 & 0x03) { case 0: return 'STANDARD'; @@ -2527,10 +2520,10 @@ cr.define('descriptor_panel', function() { function getRequestTypeRecipient(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return inputRow.querySelector('#transfer-recipient').value; + return queryRequiredElement('#transfer-recipient', inputRow).value; case INPUT_TYPE_HEX_BYTE: const value = Number.parseInt( - inputRow.querySelector('#query-request-type').value, 16); + queryRequiredElement('#query-request-type', inputRow).value, 16); switch (value & 0x1F) { case 0: return 'DEVICE'; @@ -2551,15 +2544,15 @@ cr.define('descriptor_panel', function() { * host-to-device. * @param {!HTMLElement} inputRow * @param {number} inputType - * @return {number} + * @return {string} */ function getRequestTypeDirection(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return inputRow.querySelector('#transfer-direction').value; + return queryRequiredElement('#transfer-direction', inputRow).value; case INPUT_TYPE_HEX_BYTE: const value = Number.parseInt( - inputRow.querySelector('#query-request-type').value, 16); + queryRequiredElement('#query-request-type', inputRow).value, 16); switch (value >> 7) { case CONTROL_TRANSFER_DIRECTION_HOST_TO_DEVICE: return 'Host-to-Device'; @@ -2580,10 +2573,11 @@ cr.define('descriptor_panel', function() { function getRequestCode(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return Number.parseInt(inputRow.querySelector('#query-request').value); + return Number.parseInt( + queryRequiredElement('#query-request', inputRow).value, 10); case INPUT_TYPE_HEX_BYTE: return Number.parseInt( - inputRow.querySelector('#query-request').value, 16); + queryRequiredElement('#query-request', inputRow).value, 16); default: return Number.NaN; } @@ -2598,10 +2592,11 @@ cr.define('descriptor_panel', function() { function getRequestValue(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return Number.parseInt(inputRow.querySelector('#query-value').value); + return Number.parseInt( + queryRequiredElement('#query-value', inputRow).value, 10); case INPUT_TYPE_HEX_BYTE: return Number.parseInt( - inputRow.querySelector('#query-value').value, 16); + queryRequiredElement('#query-value', inputRow).value, 16); default: return Number.NaN; } @@ -2616,10 +2611,11 @@ cr.define('descriptor_panel', function() { function getRequestIndex(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return Number.parseInt(inputRow.querySelector('#query-index').value); + return Number.parseInt( + queryRequiredElement('#query-index', inputRow).value, 10); case INPUT_TYPE_HEX_BYTE: return Number.parseInt( - inputRow.querySelector('#query-index').value, 16); + queryRequiredElement('#query-index', inputRow).value, 16); default: return Number.NaN; } @@ -2634,10 +2630,11 @@ cr.define('descriptor_panel', function() { function getRequestLength(inputRow, inputType) { switch (inputType) { case INPUT_TYPE_DECIMAL_WITH_DROPDOWN: - return Number.parseInt(inputRow.querySelector('#query-length').value); + return Number.parseInt( + queryRequiredElement('#query-length', inputRow).value, 10); case INPUT_TYPE_HEX_BYTE: return Number.parseInt( - inputRow.querySelector('#query-length').value, 16); + queryRequiredElement('#query-length', inputRow).value, 16); default: return Number.NaN; } @@ -2652,23 +2649,24 @@ cr.define('descriptor_panel', function() { function addNewDescriptorDisplayElement( rootElement, descriptorPanelTitle = undefined) { const descriptorPanelTemplate = - document.querySelector('#descriptor-panel-template'); - const descriptorPanelClone = - document.importNode(descriptorPanelTemplate.content, true); + queryRequiredElement('#descriptor-panel-template'); + + const descriptorPanelClone = /** @type {!HTMLElement} */ + (document.importNode(descriptorPanelTemplate.content, true)); /** @type {!HTMLElement} */ const rawDataTreeRoot = - descriptorPanelClone.querySelector('.raw-data-tree-view'); + queryRequiredElement('.raw-data-tree-view', descriptorPanelClone); /** @type {!HTMLElement} */ const rawDataByteElement = - descriptorPanelClone.querySelector('.raw-data-byte-view'); + queryRequiredElement('.raw-data-byte-view', descriptorPanelClone); cr.ui.decorate(rawDataTreeRoot, cr.ui.Tree); rawDataTreeRoot.detail = {payload: {}, children: {}}; if (descriptorPanelTitle) { const descriptorPanelTitleTemplate = - document.querySelector('#descriptor-panel-title'); + queryRequiredElement('#descriptor-panel-title'); const clone = document.importNode(descriptorPanelTitleTemplate.content, true) .querySelector('descriptorpaneltitle'); @@ -2774,7 +2772,8 @@ cr.define('descriptor_panel', function() { el.addEventListener('pointerenter', () => { rawDataByteElement.querySelectorAll(`.${fieldOffsetClass}`) .forEach((el) => el.classList.add('hovered-field')); - const el = rawDataTreeRoot.querySelector(`.${fieldOffsetClass}`); + const el = + queryRequiredElement(`.${fieldOffsetClass}`, rawDataTreeRoot); if (el) { el.classList.add('hover'); } @@ -2783,14 +2782,16 @@ cr.define('descriptor_panel', function() { el.addEventListener('pointerleave', () => { rawDataByteElement.querySelectorAll(`.${fieldOffsetClass}`) .forEach((el) => el.classList.remove('hovered-field')); - const el = rawDataTreeRoot.querySelector(`.${fieldOffsetClass}`); + const el = + queryRequiredElement(`.${fieldOffsetClass}`, rawDataTreeRoot); if (el) { el.classList.remove('hover'); } }); el.addEventListener('click', () => { - const el = rawDataTreeRoot.querySelector(`.${fieldOffsetClass}`); + const el = + queryRequiredElement(`.${fieldOffsetClass}`, rawDataTreeRoot); if (el) { el.click(); } @@ -2857,19 +2858,17 @@ cr.define('descriptor_panel', function() { */ function renderRawDataBytes(rawDataByteElement, rawData) { const rawDataByteContainerTemplate = - document.querySelector('#raw-data-byte-container-template'); + queryRequiredElement('#raw-data-byte-container-template'); const rawDataByteContainerClone = document.importNode(rawDataByteContainerTemplate.content, true); const rawDataByteContainerElement = rawDataByteContainerClone.querySelector('div'); - const rawDataByteTemplate = - document.querySelector('#raw-data-byte-template'); + const rawDataByteTemplate = queryRequiredElement('#raw-data-byte-template'); for (const value of rawData) { const rawDataByteClone = document.importNode(rawDataByteTemplate.content, true); const rawDataByteElement = rawDataByteClone.querySelector('span'); - rawDataByteElement.textContent = toHex(value, 2); rawDataByteContainerElement.appendChild(rawDataByteElement); } diff --git a/chromium/chrome/browser/resources/usb_internals/devices_page.js b/chromium/chrome/browser/resources/usb_internals/devices_page.js index e7743ac9062..2589e5eb286 100644 --- a/chromium/chrome/browser/resources/usb_internals/devices_page.js +++ b/chromium/chrome/browser/resources/usb_internals/devices_page.js @@ -8,17 +8,17 @@ */ cr.define('devices_page', function() { - const UsbDeviceProxy = device.mojom.UsbDeviceProxy; + const UsbDeviceRemote = device.mojom.UsbDeviceRemote; /** * Page that contains a tab header and a tab panel displaying devices table. */ class DevicesPage { /** - * @param {!device.mojom.UsbDeviceManagerProxy} usbManager + * @param {!device.mojom.UsbDeviceManagerRemote} usbManager */ constructor(usbManager) { - /** @private {device.mojom.UsbDeviceManagerProxy} */ + /** @private {!device.mojom.UsbDeviceManagerRemote} */ this.usbManager_ = usbManager; this.renderDeviceList_(); } @@ -28,7 +28,7 @@ cr.define('devices_page', function() { * @private */ async renderDeviceList_() { - const response = await this.usbManager_.getDevices(); + const response = await this.usbManager_.getDevices(null); /** @type {!Array<!device.mojom.UsbDeviceInfo>} */ const devices = response.results; @@ -39,6 +39,7 @@ cr.define('devices_page', function() { const rowTemplate = document.querySelector('#device-row'); for (const device of devices) { + /** @type {DocumentFragment|Node} */ const clone = document.importNode(rowTemplate.content, true); const td = clone.querySelectorAll('td'); @@ -48,13 +49,13 @@ cr.define('devices_page', function() { td[2].textContent = toHex(device.vendorId); td[3].textContent = toHex(device.productId); if (device.manufacturerName) { - td[4].textContent = decodeString16(device.manufacturerName.data); + td[4].textContent = decodeString16(device.manufacturerName); } if (device.productName) { - td[5].textContent = decodeString16(device.productName.data); + td[5].textContent = decodeString16(device.productName); } if (device.serialNumber) { - td[6].textContent = decodeString16(device.serialNumber.data); + td[6].textContent = decodeString16(device.serialNumber); } const inspectButton = clone.querySelector('button'); @@ -90,11 +91,10 @@ cr.define('devices_page', function() { */ class DevicePage { /** - * @param {!device.mojom.UsbDeviceManagerProxy} usbManager + * @param {!device.mojom.UsbDeviceManagerRemote} usbManager * @param {!device.mojom.UsbDeviceInfo} device */ constructor(usbManager, device) { - /** @private {device.mojom.UsbDeviceManagerProxy} */ this.usbManager_ = usbManager; this.renderTab_(device); } @@ -105,14 +105,15 @@ cr.define('devices_page', function() { * @private */ renderTab_(device) { - const tabs = document.querySelector('tabs'); + const tabs = queryRequiredElement('tabs'); - const tabTemplate = document.querySelector('#tab-template'); + const tabTemplate = queryRequiredElement('#tab-template'); + /** @type {DocumentFragment|Node} */ const tabClone = document.importNode(tabTemplate.content, true); const tab = tabClone.querySelector('tab'); if (device.productName) { - tab.textContent = decodeString16(device.productName.data); + tab.textContent = decodeString16(device.productName); } else { const vendorId = toHex(device.vendorId).slice(2); const productId = toHex(device.productId).slice(2); @@ -123,23 +124,25 @@ cr.define('devices_page', function() { tabs.appendChild(tabClone); cr.ui.decorate('tab', cr.ui.Tab); - const tabPanels = document.querySelector('tabpanels'); + const tabPanels = queryRequiredElement('tabpanels'); const tabPanelTemplate = - document.querySelector('#device-tabpanel-template'); + queryRequiredElement('#device-tabpanel-template'); + /** @type {DocumentFragment|Node} */ const tabPanelClone = document.importNode(tabPanelTemplate.content, true); /** * Root of the WebContents tree of current device. - * @type {?cr.ui.Tree} */ - const treeViewRoot = tabPanelClone.querySelector('.tree-view'); + const treeViewRoot = assertInstanceof( + tabPanelClone.querySelector('.tree-view'), HTMLElement); cr.ui.decorate(treeViewRoot, cr.ui.Tree); treeViewRoot.detail = {payload: {}, children: {}}; // Clear the tree first before populating it with the new content. treeViewRoot.innerText = ''; renderDeviceTree(device, treeViewRoot); - const tabPanel = tabPanelClone.querySelector('tabpanel'); + const tabPanel = assertInstanceof( + tabPanelClone.querySelector('tabpanel'), HTMLElement); this.initializeDescriptorPanels_(tabPanel, device.guid); tabPanels.appendChild(tabPanelClone); @@ -153,24 +156,25 @@ cr.define('devices_page', function() { * @private */ async initializeDescriptorPanels_(tabPanel, guid) { - const usbDeviceProxy = new UsbDeviceProxy; - await this.usbManager_.getDevice(guid, usbDeviceProxy.$.createRequest()); + const usbDevice = new UsbDeviceRemote; + await this.usbManager_.getDevice( + guid, usbDevice.$.bindNewPipeAndPassReceiver(), null); - const deviceDescriptorPanel = initialInspectorPanel( - tabPanel, 'device-descriptor', usbDeviceProxy, guid); + const deviceDescriptorPanel = + initialInspectorPanel(tabPanel, 'device-descriptor', usbDevice, guid); const configurationDescriptorPanel = initialInspectorPanel( - tabPanel, 'configuration-descriptor', usbDeviceProxy, guid); + tabPanel, 'configuration-descriptor', usbDevice, guid); - const stringDescriptorPanel = initialInspectorPanel( - tabPanel, 'string-descriptor', usbDeviceProxy, guid); + const stringDescriptorPanel = + initialInspectorPanel(tabPanel, 'string-descriptor', usbDevice, guid); deviceDescriptorPanel.setStringDescriptorPanel(stringDescriptorPanel); configurationDescriptorPanel.setStringDescriptorPanel( stringDescriptorPanel); - initialInspectorPanel(tabPanel, 'bos-descriptor', usbDeviceProxy, guid); + initialInspectorPanel(tabPanel, 'bos-descriptor', usbDevice, guid); - initialInspectorPanel(tabPanel, 'testing-tool', usbDeviceProxy, guid); + initialInspectorPanel(tabPanel, 'testing-tool', usbDevice, guid); // window.deviceTabInitializedFn() provides a hook for the test suite to // perform test actions after the device tab query descriptors actions are @@ -204,18 +208,18 @@ cr.define('devices_page', function() { device.deviceVersionMinor}.${device.deviceVersionSubminor}`)); if (device.manufacturerName) { - root.add(customTreeItem(`Manufacturer Name: ${ - decodeString16(device.manufacturerName.data)}`)); + root.add(customTreeItem( + `Manufacturer Name: ${decodeString16(device.manufacturerName)}`)); } if (device.productName) { root.add(customTreeItem( - `Product Name: ${decodeString16(device.productName.data)}`)); + `Product Name: ${decodeString16(device.productName)}`)); } if (device.serialNumber) { root.add(customTreeItem( - `Serial Number: ${decodeString16(device.serialNumber.data)}`)); + `Serial Number: ${decodeString16(device.serialNumber)}`)); } if (device.webusbLandingPage) { @@ -239,7 +243,7 @@ cr.define('devices_page', function() { /** * Renders a tree item to display the device's configuration information. * @param {!Array<!device.mojom.UsbConfigurationInfo>} configurationsArray - * @param {!cr.ui.TreeItem} root + * @param {!cr.ui.Tree} root */ function renderConfigurationTreeItem(configurationsArray, root) { for (const configuration of configurationsArray) { @@ -248,7 +252,7 @@ cr.define('devices_page', function() { if (configuration.configurationName) { configurationItem.add(customTreeItem(`Configuration Name: ${ - decodeString16(configuration.configurationName.data)}`)); + decodeString16(configuration.configurationName)}`)); } const interfacesArray = configuration.interfaces; @@ -296,7 +300,7 @@ cr.define('devices_page', function() { if (alternate.interfaceName) { alternateItem.add(customTreeItem( - `Interface Name: ${decodeString16(alternate.interfaceName.data)}`)); + `Interface Name: ${decodeString16(alternate.interfaceName)}`)); } const endpointsArray = alternate.endpoints; @@ -356,15 +360,16 @@ cr.define('devices_page', function() { * Initialize a descriptor panel. * @param {!HTMLElement} tabPanel * @param {string} panelType - * @param {!device.mojom.UsbDeviceInterface} usbDeviceProxy + * @param {!device.mojom.UsbDeviceRemote} usbDevice * @param {string} guid * @return {!descriptor_panel.DescriptorPanel} */ - function initialInspectorPanel(tabPanel, panelType, usbDeviceProxy, guid) { - const button = tabPanel.querySelector(`.${panelType}-button`); - const displayElement = tabPanel.querySelector(`.${panelType}-panel`); + function initialInspectorPanel(tabPanel, panelType, usbDevice, guid) { + const button = queryRequiredElement(`.${panelType}-button`, tabPanel); + const displayElement = + queryRequiredElement(`.${panelType}-panel`, tabPanel); const descriptorPanel = - new descriptor_panel.DescriptorPanel(usbDeviceProxy, displayElement); + new descriptor_panel.DescriptorPanel(usbDevice, displayElement); switch (panelType) { case 'string-descriptor': descriptorPanel.initialStringDescriptorPanel(guid); @@ -405,7 +410,7 @@ cr.define('devices_page', function() { * @return {string} */ function decodeString16(arr) { - return arr.map(ch => String.fromCodePoint(ch)).join(''); + return arr.data.map(ch => String.fromCodePoint(ch)).join(''); } /** @@ -424,7 +429,7 @@ cr.define('devices_page', function() { * @private */ function customTreeItem(itemLabel) { - return item = new cr.ui.TreeItem({ + return new cr.ui.TreeItem({ label: itemLabel, icon: '', }); @@ -437,4 +442,4 @@ cr.define('devices_page', function() { window.deviceListCompleteFn = window.deviceListCompleteFn || function() {}; -window.deviceTabInitializedFn = window.deviceTabInitializedFn || function() {};
\ No newline at end of file +window.deviceTabInitializedFn = window.deviceTabInitializedFn || function() {}; diff --git a/chromium/chrome/browser/resources/usb_internals/usb_internals.js b/chromium/chrome/browser/resources/usb_internals/usb_internals.js index ff0683482ef..45bce591f47 100644 --- a/chromium/chrome/browser/resources/usb_internals/usb_internals.js +++ b/chromium/chrome/browser/resources/usb_internals/usb_internals.js @@ -14,20 +14,20 @@ cr.define('usb_internals', function() { // actions after the page is loaded but before any script is run. await window.setupFn(); - const pageHandler = mojom.UsbInternalsPageHandler.getProxy(); + const pageHandler = mojom.UsbInternalsPageHandler.getRemote(); // Connection to the UsbInternalsPageHandler instance running in the // browser process. - /** @type {device.mojom.UsbDeviceManagerProxy} */ - const usbManager = new device.mojom.UsbDeviceManagerProxy; + /** @type {device.mojom.UsbDeviceManagerRemote} */ + const usbManager = new device.mojom.UsbDeviceManagerRemote; await pageHandler.bindUsbDeviceManagerInterface( usbManager.$.createRequest()); /** @private {devices_page.DevicesPage} */ this.devicesPage_ = new devices_page.DevicesPage(usbManager); - /** @private {device.mojom.UsbDeviceManagerTestProxy} */ - this.usbManagerTest_ = new device.mojom.UsbDeviceManagerTestProxy; + /** @private {device.mojom.UsbDeviceManagerTestRemote} */ + this.usbManagerTest_ = new device.mojom.UsbDeviceManagerTestRemote; await pageHandler.bindTestInterface( this.usbManagerTest_.$.createRequest()); @@ -93,4 +93,4 @@ window.setupFn = window.setupFn || function() { document.addEventListener('DOMContentLoaded', () => { const usbInternalsPage = new usb_internals.UsbInternals(); usbInternalsPage.initializeViews(); -});
\ No newline at end of file +}); diff --git a/chromium/chrome/browser/resources/web_footer_experiment/index.html b/chromium/chrome/browser/resources/web_footer_experiment/index.html new file mode 100644 index 00000000000..ea952773de5 --- /dev/null +++ b/chromium/chrome/browser/resources/web_footer_experiment/index.html @@ -0,0 +1,10 @@ +<!DOCTYPE HTML> +<html> +<head> + <style> + body { + background-color: #9e9e9e; + } + </style> +</head> +</html> diff --git a/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html b/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html index a5d31e14e95..fd03465f37a 100644 --- a/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html +++ b/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html @@ -143,38 +143,38 @@ /* App Icons */ .gmail { content: -webkit-image-set( - url(chrome://theme/IDS_ONBOARDING_WELCOME_GMAIL@1x) 1x, - url(chrome://theme/IDS_ONBOARDING_WELCOME_GMAIL@2x) 2x); + url(chrome://theme/IDS_WELCOME_GMAIL@1x) 1x, + url(chrome://theme/IDS_WELCOME_GMAIL@2x) 2x); } .youtube { content: -webkit-image-set( - url(chrome://theme/IDS_ONBOARDING_WELCOME_YOUTUBE@1x) 1x, - url(chrome://theme/IDS_ONBOARDING_WELCOME_YOUTUBE@2x) 2x); + url(chrome://theme/IDS_WELCOME_YOUTUBE@1x) 1x, + url(chrome://theme/IDS_WELCOME_YOUTUBE@2x) 2x); } .maps { content: -webkit-image-set( - url(chrome://theme/IDS_ONBOARDING_WELCOME_MAPS@1x) 1x, - url(chrome://theme/IDS_ONBOARDING_WELCOME_MAPS@2x) 2x); + url(chrome://theme/IDS_WELCOME_MAPS@1x) 1x, + url(chrome://theme/IDS_WELCOME_MAPS@2x) 2x); } .translate { content: -webkit-image-set( - url(chrome://theme/IDS_ONBOARDING_WELCOME_TRANSLATE@1x) 1x, - url(chrome://theme/IDS_ONBOARDING_WELCOME_TRANSLATE@2x) 2x); + url(chrome://theme/IDS_WELCOME_TRANSLATE@1x) 1x, + url(chrome://theme/IDS_WELCOME_TRANSLATE@2x) 2x); } .news { content: -webkit-image-set( - url(chrome://theme/IDS_ONBOARDING_WELCOME_NEWS@1x) 1x, - url(chrome://theme/IDS_ONBOARDING_WELCOME_NEWS@2x) 2x); + url(chrome://theme/IDS_WELCOME_NEWS@1x) 1x, + url(chrome://theme/IDS_WELCOME_NEWS@2x) 2x); } .search { content: -webkit-image-set( - url(chrome://theme/IDS_ONBOARDING_WELCOME_SEARCH@1x) 1x, - url(chrome://theme/IDS_ONBOARDING_WELCOME_SEARCH@2x) 2x); + url(chrome://theme/IDS_WELCOME_SEARCH@1x) 1x, + url(chrome://theme/IDS_WELCOME_SEARCH@2x) 2x); } </style> <div class="apps-ask"> diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome_resources.grd b/chromium/chrome/browser/resources/welcome/welcome_resources.grd index 011b9b184a4..cc67d33b906 100644 --- a/chromium/chrome/browser/resources/welcome/onboarding_welcome_resources.grd +++ b/chromium/chrome/browser/resources/welcome/welcome_resources.grd @@ -1,199 +1,199 @@ <?xml version="1.0" encoding="UTF-8"?> <grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> <outputs> - <output filename="grit/onboarding_welcome_resources.h" + <output filename="grit/welcome_resources.h" type="rc_header"> <emit emit_type='prepend'></emit> </output> - <output filename="grit/onboarding_welcome_resources_map.cc" + <output filename="grit/welcome_resources_map.cc" type="resource_file_map_source" /> - <output filename="grit/onboarding_welcome_resources_map.h" + <output filename="grit/welcome_resources_map.h" type="resource_map_header" /> - <output filename="onboarding_welcome_resources.pak" + <output filename="welcome_resources.pak" type="data_package" /> </outputs> <release seq="1"> <includes> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_BLUE_CIRCLE_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_BLUE_CIRCLE_SVG" file="images/background_svgs/blue_circle.svg" compress="gzip" type="BINDATA" /> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_GREEN_RECTANGLE_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_GREEN_RECTANGLE_SVG" file="images/background_svgs/green_rectangle.svg" compress="gzip" type="BINDATA" /> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_GREY_OVAL_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_GREY_OVAL_SVG" file="images/background_svgs/grey_oval.svg" compress="gzip" type="BINDATA" /> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_GREY_ROUNDED_RECTANGLE_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_GREY_ROUNDED_RECTANGLE_SVG" file="images/background_svgs/grey_rounded_rectangle.svg" compress="gzip" type="BINDATA" /> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_RED_TRIANGLE_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_RED_TRIANGLE_SVG" file="images/background_svgs/red_triangle.svg" compress="gzip" type="BINDATA" /> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_YELLOW_DOTS_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_YELLOW_DOTS_SVG" file="images/background_svgs/yellow_dots.svg" compress="gzip" type="BINDATA" /> - <include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_YELLOW_SEMICIRCLE_SVG" + <include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_YELLOW_SEMICIRCLE_SVG" file="images/background_svgs/yellow_semicircle.svg" compress="gzip" type="BINDATA" /> </includes> <structures> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_LANDING_VIEW_HTML" + <structure name="IDR_WELCOME_LANDING_VIEW_HTML" file="landing_view.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_LANDING_VIEW_JS" + <structure name="IDR_WELCOME_LANDING_VIEW_JS" file="landing_view.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_LANDING_VIEW_PROXY_HTML" + <structure name="IDR_WELCOME_LANDING_VIEW_PROXY_HTML" file="landing_view_proxy.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_LANDING_VIEW_PROXY_JS" + <structure name="IDR_WELCOME_LANDING_VIEW_PROXY_JS" file="landing_view_proxy.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_NAVIGATION_BEHAVIOR_HTML" + <structure name="IDR_WELCOME_NAVIGATION_BEHAVIOR_HTML" file="navigation_behavior.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_NAVIGATION_BEHAVIOR_JS" + <structure name="IDR_WELCOME_NAVIGATION_BEHAVIOR_JS" file="navigation_behavior.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_ACTION_LINK_STYLE_JS" + <structure name="IDR_WELCOME_SHARED_ACTION_LINK_STYLE_JS" file="shared/action_link_style.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_ACTION_LINK_STYLE_CSS_HTML" + <structure name="IDR_WELCOME_SHARED_ACTION_LINK_STYLE_CSS_HTML" file="shared/action_link_style_css.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_ANIMATIONS_CSS" + <structure name="IDR_WELCOME_SHARED_ANIMATIONS_CSS" file="shared/animations_css.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_BOOKMARK_PROXY_HTML" + <structure name="IDR_WELCOME_SHARED_BOOKMARK_PROXY_HTML" file="shared/bookmark_proxy.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_BOOKMARK_PROXY_JS" + <structure name="IDR_WELCOME_SHARED_BOOKMARK_PROXY_JS" file="shared/bookmark_proxy.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_CHOOSER_SHARED_CSS" + <structure name="IDR_WELCOME_SHARED_CHOOSER_SHARED_CSS" file="shared/chooser_shared_css.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_I18N_SETUP_HTML" + <structure name="IDR_WELCOME_SHARED_I18N_SETUP_HTML" file="shared/i18n_setup.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_MODULE_METRICS_PROXY_HTML" + <structure name="IDR_WELCOME_SHARED_MODULE_METRICS_PROXY_HTML" file="shared/module_metrics_proxy.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_MODULE_METRICS_PROXY_JS" + <structure name="IDR_WELCOME_SHARED_MODULE_METRICS_PROXY_JS" file="shared/module_metrics_proxy.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_NAVI_COLORS_CSS" + <structure name="IDR_WELCOME_SHARED_NAVI_COLORS_CSS" file="shared/navi_colors_css.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_ONBOARDING_BACKGROUND_HTML" + <structure name="IDR_WELCOME_SHARED_ONBOARDING_BACKGROUND_HTML" file="shared/onboarding_background.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_ONBOARDING_BACKGROUND_JS" + <structure name="IDR_WELCOME_SHARED_ONBOARDING_BACKGROUND_JS" file="shared/onboarding_background.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_STEP_INDICATOR_HTML" + <structure name="IDR_WELCOME_SHARED_STEP_INDICATOR_HTML" file="shared/step_indicator.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_STEP_INDICATOR_JS" + <structure name="IDR_WELCOME_SHARED_STEP_INDICATOR_JS" file="shared/step_indicator.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_SPLASH_PAGES_SHARED_CSS" + <structure name="IDR_WELCOME_SHARED_SPLASH_PAGES_SHARED_CSS" file="shared/splash_pages_shared_css.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SIGNIN_VIEW_HTML" + <structure name="IDR_WELCOME_SIGNIN_VIEW_HTML" file="signin_view.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SIGNIN_VIEW_JS" + <structure name="IDR_WELCOME_SIGNIN_VIEW_JS" file="signin_view.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SIGNIN_VIEW_PROXY_HTML" + <structure name="IDR_WELCOME_SIGNIN_VIEW_PROXY_HTML" file="signin_view_proxy.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SIGNIN_VIEW_PROXY_JS" + <structure name="IDR_WELCOME_SIGNIN_VIEW_PROXY_JS" file="signin_view_proxy.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_APP_HTML" + <structure name="IDR_WELCOME_APP_HTML" file="welcome_app.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_APP_JS" + <structure name="IDR_WELCOME_APP_JS" file="welcome_app.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_BROWSER_PROXY_HTML" + <structure name="IDR_WELCOME_BROWSER_PROXY_HTML" file="welcome_browser_proxy.html" compress="gzip" type="chrome_html"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_BROWSER_PROXY_JS" + <structure name="IDR_WELCOME_BROWSER_PROXY_JS" file="welcome_browser_proxy.js" compress="gzip" type="chrome_html"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_CSS" + <structure name="IDR_WELCOME_CSS" file="welcome.css" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_HTML" + <structure name="IDR_WELCOME_HTML" file="welcome.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_JS" + <structure name="IDR_WELCOME_JS" file="welcome.js" type="chrome_html" compress="gzip" preprocess="true"/> - <!-- NUX Google apps--> - <structure name="IDR_NUX_GOOGLE_APPS_HTML" + <!-- Google apps--> + <structure name="IDR_GOOGLE_APPS_HTML" file="google_apps/nux_google_apps.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_GOOGLE_APPS_JS" + <structure name="IDR_GOOGLE_APPS_JS" file="google_apps/nux_google_apps.js" compress="gzip" type="chrome_html" /> @@ -205,21 +205,21 @@ file="google_apps/google_app_proxy.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_SET_AS_DEFAULT_HTML" + <structure name="IDR_SET_AS_DEFAULT_HTML" file="set_as_default/nux_set_as_default.html" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_NUX_SET_AS_DEFAULT_JS" + <structure name="IDR_SET_AS_DEFAULT_JS" file="set_as_default/nux_set_as_default.js" type="chrome_html" compress="gzip" preprocess="true"/> - <structure name="IDR_NUX_SET_AS_DEFAULT_PROXY_HTML" + <structure name="IDR_SET_AS_DEFAULT_PROXY_HTML" file="set_as_default/nux_set_as_default_proxy.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_SET_AS_DEFAULT_PROXY_JS" + <structure name="IDR_SET_AS_DEFAULT_PROXY_JS" file="set_as_default/nux_set_as_default_proxy.js" compress="gzip" type="chrome_html" /> @@ -232,28 +232,28 @@ compress="gzip" type="chrome_html" /> - <!-- NUX NTP background--> - <structure name="IDR_NUX_NTP_BACKGROUND_HTML" + <!-- NTP background--> + <structure name="IDR_NTP_BACKGROUND_HTML" file="ntp_background/nux_ntp_background.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_NTP_BACKGROUND_JS" + <structure name="IDR_NTP_BACKGROUND_JS" file="ntp_background/nux_ntp_background.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_NTP_BACKGROUND_PROXY_HTML" + <structure name="IDR_NTP_BACKGROUND_PROXY_HTML" file="ntp_background/ntp_background_proxy.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_NTP_BACKGROUND_PROXY_JS" + <structure name="IDR_NTP_BACKGROUND_PROXY_JS" file="ntp_background/ntp_background_proxy.js" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_NTP_BACKGROUND_METRICS_PROXY_HTML" + <structure name="IDR_NTP_BACKGROUND_METRICS_PROXY_HTML" file="ntp_background/ntp_background_metrics_proxy.html" compress="gzip" type="chrome_html" /> - <structure name="IDR_NUX_NTP_BACKGROUND_METRICS_PROXY_JS" + <structure name="IDR_NTP_BACKGROUND_METRICS_PROXY_JS" file="ntp_background/ntp_background_metrics_proxy.js" compress="gzip" type="chrome_html" /> diff --git a/chromium/chrome/browser/safe_browsing/BUILD.gn b/chromium/chrome/browser/safe_browsing/BUILD.gn index 2be129ce18a..3599895eb5c 100644 --- a/chromium/chrome/browser/safe_browsing/BUILD.gn +++ b/chromium/chrome/browser/safe_browsing/BUILD.gn @@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/jumbo.gni") +import("//components/safe_browsing/buildflags.gni") import("//extensions/buildflags/buildflags.gni") jumbo_static_library("safe_browsing") { @@ -27,6 +28,7 @@ jumbo_static_library("safe_browsing") { "//components/password_manager/core/browser:hash_password_manager", "//components/pref_registry", "//components/resources:components_resources_grit", + "//components/safe_browsing:buildflags", "//components/safe_browsing:features", "//components/safe_browsing:ping_manager", "//components/safe_browsing/browser:referrer_chain_provider", @@ -71,6 +73,8 @@ jumbo_static_library("safe_browsing") { "certificate_reporting_service.h", "certificate_reporting_service_factory.cc", "certificate_reporting_service_factory.h", + "chrome_password_protection_service.cc", + "chrome_password_protection_service.h", "safe_browsing_blocking_page.cc", "safe_browsing_blocking_page.h", "safe_browsing_navigation_observer.cc", @@ -81,6 +85,9 @@ jumbo_static_library("safe_browsing") { "safe_browsing_navigation_throttle.h", "safe_browsing_service.cc", "safe_browsing_service.h", + "safe_browsing_subresource_tab_helper.cc", + "safe_browsing_subresource_tab_helper.h", + "services_delegate.cc", "services_delegate.h", "telemetry/telemetry_service.cc", "telemetry/telemetry_service.h", @@ -95,6 +102,12 @@ jumbo_static_library("safe_browsing") { "//chrome/common/safe_browsing:proto", "//components/safe_browsing:csd_proto", "//components/safe_browsing:safe_browsing", + + # TODO(crbug/996380): This is needed because the DownloadProtectionService + # is being built on Android. Since we don't actually use any + # DownloadProtectionService features on Android, we should fix that + # dependency and move this to the 'safe_browsing_mode == 1' section. + "//components/safe_browsing:webprotect_proto", "//components/safe_browsing/browser", "//components/safe_browsing/common", "//components/safe_browsing/common:safe_browsing_prefs", @@ -118,22 +131,28 @@ jumbo_static_library("safe_browsing") { "browser_feature_extractor.h", "browser_features.cc", "browser_features.h", - "chrome_password_protection_service.cc", - "chrome_password_protection_service.h", "client_side_detection_host.cc", "client_side_detection_host.h", "client_side_detection_service.cc", "client_side_detection_service.h", "client_side_model_loader.cc", "client_side_model_loader.h", + "download_protection/binary_fcm_service.cc", + "download_protection/binary_fcm_service.h", "download_protection/binary_upload_service.cc", "download_protection/binary_upload_service.h", "download_protection/check_client_download_request.cc", "download_protection/check_client_download_request.h", + "download_protection/check_client_download_request_base.cc", + "download_protection/check_client_download_request_base.h", + "download_protection/check_native_file_system_write_request.cc", + "download_protection/check_native_file_system_write_request.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_item_request.cc", + "download_protection/download_item_request.h", "download_protection/download_protection_service.cc", "download_protection/download_protection_service.h", "download_protection/download_protection_util.cc", @@ -212,7 +231,6 @@ jumbo_static_library("safe_browsing") { "//components/content_settings/core/browser", "//components/language/core/common", "//components/prefs", - "//components/safe_browsing:webprotect_proto", "//components/safe_browsing/db", "//components/security_interstitials/content:security_interstitial_page", "//content/public/browser", @@ -231,6 +249,7 @@ jumbo_static_library("safe_browsing") { ] deps += [ "//chrome/android:jni_headers", + "//components/safe_browsing:buildflags", "//components/safe_browsing/android:safe_browsing_mobile", ] } else if (safe_browsing_mode == 3) { @@ -277,6 +296,7 @@ source_set("test_support") { deps = [ ":safe_browsing", "//chrome/common/safe_browsing:proto", + "//components/safe_browsing:buildflags", "//components/safe_browsing/db:database_manager", "//components/safe_browsing/db:test_database_manager", "//components/safe_browsing/db:v4_protocol_manager_util", diff --git a/chromium/chrome/browser/search/BUILD.gn b/chromium/chrome/browser/search/BUILD.gn index 338bfa87e33..c610750bd07 100644 --- a/chromium/chrome/browser/search/BUILD.gn +++ b/chromium/chrome/browser/search/BUILD.gn @@ -8,6 +8,7 @@ action("local_ntp_code_generate") { script = "tools/generate_integrity_header.py" header_path = "$target_gen_dir/local_ntp_js_integrity.h" animations_js = local_ntp_resources + "/animations.js" + assert_js = "//ui/webui/resources/js/assert.js" customize_js = local_ntp_resources + "/customize.js" doodles_js = local_ntp_resources + "/doodles.js" local_ntp_js = local_ntp_resources + "/local_ntp.js" @@ -16,6 +17,7 @@ action("local_ntp_code_generate") { inputs = [ animations_js, + assert_js, customize_js, doodles_js, local_ntp_js, @@ -30,6 +32,7 @@ action("local_ntp_code_generate") { args = [ "--output_path=" + rebase_path(header_path, root_build_dir), rebase_path(animations_js, root_build_dir), + rebase_path(assert_js, root_build_dir), rebase_path(customize_js, root_build_dir), rebase_path(doodles_js, root_build_dir), rebase_path(local_ntp_js, root_build_dir), diff --git a/chromium/chrome/browser/sharing/proto/BUILD.gn b/chromium/chrome/browser/sharing/proto/BUILD.gn index 832182ad6d2..4eb18a56522 100644 --- a/chromium/chrome/browser/sharing/proto/BUILD.gn +++ b/chromium/chrome/browser/sharing/proto/BUILD.gn @@ -14,6 +14,7 @@ group("proto_lite") { proto_library("proto") { sources = [ "click_to_call_message.proto", + "shared_clipboard_message.proto", "sharing_message.proto", ] } diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc index 2a8968b4ee2..44f7af39615 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc +++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc @@ -5,6 +5,7 @@ #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" #include "base/bind.h" +#include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h" #include "chrome/browser/spellchecker/spellcheck_factory.h" @@ -13,25 +14,45 @@ #include "components/spellcheck/browser/spellcheck_platform.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/strong_binding.h" +#include "content/public/browser/render_process_host.h" +#include "mojo/public/cpp/bindings/self_owned_receiver.h" #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) #include "chrome/browser/spellchecker/spelling_request.h" #endif -SpellCheckHostChromeImpl::SpellCheckHostChromeImpl( - const service_manager::Identity& renderer_identity) - : renderer_identity_(renderer_identity) {} +namespace { + +SpellCheckHostChromeImpl::Binder& GetSpellCheckHostBinderOverride() { + static base::NoDestructor<SpellCheckHostChromeImpl::Binder> binder; + return *binder; +} + +} // namespace + +SpellCheckHostChromeImpl::SpellCheckHostChromeImpl(int render_process_id) + : render_process_id_(render_process_id) {} SpellCheckHostChromeImpl::~SpellCheckHostChromeImpl() = default; // static void SpellCheckHostChromeImpl::Create( - spellcheck::mojom::SpellCheckHostRequest request, - const service_manager::BindSourceInfo& source_info) { - mojo::MakeStrongBinding( - std::make_unique<SpellCheckHostChromeImpl>(source_info.identity), - std::move(request)); + int render_process_id, + mojo::PendingReceiver<spellcheck::mojom::SpellCheckHost> receiver) { + auto& binder = GetSpellCheckHostBinderOverride(); + if (binder) { + binder.Run(render_process_id, std::move(receiver)); + return; + } + + mojo::MakeSelfOwnedReceiver( + std::make_unique<SpellCheckHostChromeImpl>(render_process_id), + std::move(receiver)); +} + +// static +void SpellCheckHostChromeImpl::OverrideBinderForTesting(Binder binder) { + GetSpellCheckHostBinderOverride() = std::move(binder); } void SpellCheckHostChromeImpl::RequestDictionary() { @@ -47,7 +68,9 @@ void SpellCheckHostChromeImpl::RequestDictionary() { // The spellchecker initialization already started and finished; just // send it to the renderer. - spellcheck->InitForRenderer(renderer_identity_); + auto* host = content::RenderProcessHost::FromID(render_process_id_); + if (host) + spellcheck->InitForRenderer(host); // TODO(rlp): Ensure that we do not initialize the hunspell dictionary // more than once if we get requests from different renderers. @@ -80,11 +103,13 @@ void SpellCheckHostChromeImpl::CallSpellingService( // service if a user enables the "Use enhanced spell check" option. When // a response is received (including an error) from the remote Spelling // service, calls CallSpellingServiceDone. - content::BrowserContext* context = - content::BrowserContext::GetBrowserContextForServiceInstanceGroup( - renderer_identity_.instance_group()); + auto* host = content::RenderProcessHost::FromID(render_process_id_); + if (!host) { + std::move(callback).Run(false, std::vector<SpellCheckResult>()); + return; + } client_.RequestTextCheck( - context, SpellingServiceClient::SPELLCHECK, text, + host->GetBrowserContext(), SpellingServiceClient::SPELLCHECK, text, base::BindOnce(&SpellCheckHostChromeImpl::CallSpellingServiceDone, weak_factory_.GetWeakPtr(), std::move(callback))); } @@ -158,7 +183,7 @@ void SpellCheckHostChromeImpl::RequestTextCheck( // |SpellingRequest| self-destructs on completion. // OK to store unretained |this| in a |SpellingRequest| owned by |this|. requests_.insert(std::make_unique<SpellingRequest>( - &client_, text, renderer_identity_, route_id, std::move(callback), + &client_, text, render_process_id_, route_id, std::move(callback), base::BindOnce(&SpellCheckHostChromeImpl::OnRequestFinished, base::Unretained(this)))); } @@ -193,5 +218,8 @@ void SpellCheckHostChromeImpl::RetireDocumentTag(int route_id) { #endif // defined(OS_MACOSX) SpellcheckService* SpellCheckHostChromeImpl::GetSpellcheckService() const { - return SpellcheckServiceFactory::GetForRenderer(renderer_identity_); + auto* host = content::RenderProcessHost::FromID(render_process_id_); + if (!host) + return nullptr; + return SpellcheckServiceFactory::GetForContext(host->GetBrowserContext()); } diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h index dd3af7f8d09..bacbb71fab1 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h +++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h @@ -5,11 +5,12 @@ #ifndef CHROME_BROWSER_SPELLCHECKER_SPELL_CHECK_HOST_CHROME_IMPL_H_ #define CHROME_BROWSER_SPELLCHECKER_SPELL_CHECK_HOST_CHROME_IMPL_H_ +#include "base/callback.h" #include "base/containers/unique_ptr_adapters.h" #include "build/build_config.h" #include "components/spellcheck/browser/spell_check_host_impl.h" #include "components/spellcheck/browser/spelling_service_client.h" -#include "services/service_manager/public/cpp/bind_source_info.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" class SpellcheckCustomDictionary; class SpellcheckService; @@ -20,12 +21,19 @@ struct SpellCheckResult; // Implementation of SpellCheckHost involving Chrome-only features. class SpellCheckHostChromeImpl : public SpellCheckHostImpl { public: - explicit SpellCheckHostChromeImpl( - const service_manager::Identity& renderer_identity); + explicit SpellCheckHostChromeImpl(int render_process_id); ~SpellCheckHostChromeImpl() override; - static void Create(spellcheck::mojom::SpellCheckHostRequest request, - const service_manager::BindSourceInfo& source_info); + static void Create( + int render_process_id, + mojo::PendingReceiver<spellcheck::mojom::SpellCheckHost> receiver); + + // Allows tests to override how |Create()| is implemented to bind a process + // hosts's SpellCheckHost receiver. + using Binder = base::RepeatingCallback<void( + int /* render_process_id */, + mojo::PendingReceiver<spellcheck::mojom::SpellCheckHost>)>; + static void OverrideBinderForTesting(Binder binder); private: friend class TestSpellCheckHostChromeImpl; @@ -90,8 +98,8 @@ class SpellCheckHostChromeImpl : public SpellCheckHostImpl { // is null if the render process is being shut down. virtual SpellcheckService* GetSpellcheckService() const; - // The identity of the renderer service. - const service_manager::Identity renderer_identity_; + // The process ID of the renderer. + const int render_process_id_; // A JSON-RPC client that calls the remote Spelling service. SpellingServiceClient client_; diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac_browsertest.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac_browsertest.cc index 461ee3c709d..f78aa4f7593 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac_browsertest.cc +++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac_browsertest.cc @@ -18,11 +18,8 @@ class SpellCheckHostChromeImplMacBrowserTest : public InProcessBrowserTest { void SetUpOnMainThread() override { content::BrowserContext* context = browser()->profile(); renderer_.reset(new content::MockRenderProcessHost(context)); - - service_manager::BindSourceInfo source_info; - source_info.identity = renderer_->GetChildIdentity(); - SpellCheckHostChromeImpl::Create(mojo::MakeRequest(&spell_check_host_), - source_info); + SpellCheckHostChromeImpl::Create(renderer_->GetID(), + mojo::MakeRequest(&spell_check_host_)); } void TearDownOnMainThread() override { renderer_.reset(); } diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc index 83cf0cb522c..ca5f66fb20f 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc +++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc @@ -11,7 +11,7 @@ #include "chrome/browser/spellchecker/spellcheck_service.h" #include "chrome/test/base/testing_profile.h" #include "components/spellcheck/common/spellcheck_result.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" #if !BUILDFLAG(USE_RENDERER_SPELLCHECKER) @@ -38,7 +38,7 @@ class TestSpellCheckHostChromeImpl { } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile testing_profile_; std::unique_ptr<SpellcheckService> spellcheck_; diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc index f1c65ad82a7..9ceeb4deedc 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc +++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc @@ -23,14 +23,11 @@ class SpellCheckHostChromeImplWinBrowserTest : public InProcessBrowserTest { content::BrowserContext* context = browser()->profile(); renderer_.reset(new content::MockRenderProcessHost(context)); - service_manager::BindSourceInfo source_info; - source_info.identity = renderer_->GetChildIdentity(); - base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker); - SpellCheckHostChromeImpl::Create(mojo::MakeRequest(&spell_check_host_), - source_info); + SpellCheckHostChromeImpl::Create(renderer_->GetID(), + mojo::MakeRequest(&spell_check_host_)); } void TearDownOnMainThread() override { renderer_.reset(); } diff --git a/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.cc b/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.cc index 5c0e4230dd5..4218ae0c3f9 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.cc +++ b/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.cc @@ -5,9 +5,19 @@ #include "chrome/browser/spellchecker/spell_check_panel_host_impl.h" #include "base/bind.h" +#include "base/no_destructor.h" #include "components/spellcheck/browser/spellcheck_platform.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/strong_binding.h" +#include "mojo/public/cpp/bindings/self_owned_receiver.h" + +namespace { + +SpellCheckPanelHostImpl::Binder& GetPanelHostBinderOverride() { + static base::NoDestructor<SpellCheckPanelHostImpl::Binder> binder; + return *binder; +} + +} // namespace SpellCheckPanelHostImpl::SpellCheckPanelHostImpl() = default; @@ -15,9 +25,21 @@ SpellCheckPanelHostImpl::~SpellCheckPanelHostImpl() = default; // static void SpellCheckPanelHostImpl::Create( - spellcheck::mojom::SpellCheckPanelHostRequest request) { - mojo::MakeStrongBinding(std::make_unique<SpellCheckPanelHostImpl>(), - std::move(request)); + int render_process_id, + mojo::PendingReceiver<spellcheck::mojom::SpellCheckPanelHost> receiver) { + auto& binder = GetPanelHostBinderOverride(); + if (binder) { + binder.Run(render_process_id, std::move(receiver)); + return; + } + + mojo::MakeSelfOwnedReceiver(std::make_unique<SpellCheckPanelHostImpl>(), + std::move(receiver)); +} + +// static +void SpellCheckPanelHostImpl::OverrideBinderForTesting(Binder binder) { + GetPanelHostBinderOverride() = std::move(binder); } void SpellCheckPanelHostImpl::ShowSpellingPanel(bool show) { diff --git a/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.h b/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.h index 07e738bc57d..68ed9657715 100644 --- a/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.h +++ b/chromium/chrome/browser/spellchecker/spell_check_panel_host_impl.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_SPELLCHECKER_SPELL_CHECK_PANEL_HOST_IMPL_H_ #define CHROME_BROWSER_SPELLCHECKER_SPELL_CHECK_PANEL_HOST_IMPL_H_ +#include "base/callback.h" #include "base/macros.h" #include "components/spellcheck/common/spellcheck_panel.mojom.h" #include "components/spellcheck/spellcheck_buildflags.h" @@ -18,7 +19,16 @@ class SpellCheckPanelHostImpl : public spellcheck::mojom::SpellCheckPanelHost { SpellCheckPanelHostImpl(); ~SpellCheckPanelHostImpl() override; - static void Create(spellcheck::mojom::SpellCheckPanelHostRequest request); + static void Create( + int render_process_id, + mojo::PendingReceiver<spellcheck::mojom::SpellCheckPanelHost> receiver); + + // Allows tests to override how |Create()| is implemented to bind a process + // hosts's SpellCheckPanelHost receiver. + using Binder = base::RepeatingCallback<void( + int /* render_process_id */, + mojo::PendingReceiver<spellcheck::mojom::SpellCheckPanelHost>)>; + static void OverrideBinderForTesting(Binder binder); private: // spellcheck::mojom::SpellCheckPanelHost: diff --git a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc index 31619d7e7ae..0decf90b820 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc @@ -222,8 +222,8 @@ int SpellcheckCustomDictionary::Change::Sanitize( SpellcheckCustomDictionary::SpellcheckCustomDictionary( const base::FilePath& dictionary_directory_name) - : task_runner_( - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})), + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})), custom_dictionary_path_( dictionary_directory_name.Append(chrome::kCustomDictionaryFileName)), is_loaded_(false) {} @@ -452,7 +452,7 @@ void SpellcheckCustomDictionary::OnLoaded( fix_invalid_file_.Reset( base::BindOnce(&SpellcheckCustomDictionary::FixInvalidFile, weak_ptr_factory_.GetWeakPtr(), std::move(result))); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT}, fix_invalid_file_.callback()); diff --git a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary_unittest.cc b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary_unittest.cc index cc3e9acc818..1b75004b2f1 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary_unittest.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary_unittest.cc @@ -30,7 +30,7 @@ #include "components/sync/model/sync_error_factory.h" #include "components/sync/model/sync_error_factory_mock.h" #include "components/sync/protocol/sync.pb.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "net/test/embedded_test_server/default_handlers.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -68,7 +68,7 @@ static std::unique_ptr<KeyedService> BuildSpellcheckService( class SpellcheckCustomDictionaryTest : public testing::Test { public: SpellcheckCustomDictionaryTest() - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {} + : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP) {} protected: void SetUp() override { @@ -115,7 +115,7 @@ class SpellcheckCustomDictionaryTest : public testing::Test { return dictionary.Apply(change); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; diff --git a/chromium/chrome/browser/spellchecker/spellcheck_factory.cc b/chromium/chrome/browser/spellchecker/spellcheck_factory.cc index 8f070a23c6d..5253d1f48e1 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_factory.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_factory.cc @@ -14,7 +14,6 @@ #include "components/user_prefs/user_prefs.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_process_host.h" -#include "services/service_manager/public/cpp/identity.h" #include "ui/base/l10n/l10n_util.h" // static @@ -25,17 +24,6 @@ SpellcheckService* SpellcheckServiceFactory::GetForContext( } // static -SpellcheckService* SpellcheckServiceFactory::GetForRenderer( - const service_manager::Identity& renderer_identity) { - content::BrowserContext* context = - content::BrowserContext::GetBrowserContextForServiceInstanceGroup( - renderer_identity.instance_group()); - if (!context) - return nullptr; - return GetForContext(context); -} - -// static SpellcheckServiceFactory* SpellcheckServiceFactory::GetInstance() { return base::Singleton<SpellcheckServiceFactory>::get(); } diff --git a/chromium/chrome/browser/spellchecker/spellcheck_factory.h b/chromium/chrome/browser/spellchecker/spellcheck_factory.h index fd4e6643725..7adf9db4f84 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_factory.h +++ b/chromium/chrome/browser/spellchecker/spellcheck_factory.h @@ -12,10 +12,6 @@ class SpellcheckService; -namespace service_manager { -class Identity; -} - // Entry into the SpellCheck system. // // Internally, this owns all SpellcheckService objects. @@ -25,9 +21,6 @@ class SpellcheckServiceFactory : public BrowserContextKeyedServiceFactory { // if it does not already exist. This can return NULL. static SpellcheckService* GetForContext(content::BrowserContext* context); - static SpellcheckService* GetForRenderer( - const service_manager::Identity& renderer_identity); - static SpellcheckServiceFactory* GetInstance(); private: diff --git a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc index d4ac62ef820..78432896094 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc @@ -110,8 +110,8 @@ SpellcheckHunspellDictionary::SpellcheckHunspellDictionary( const std::string& language, content::BrowserContext* browser_context, SpellcheckService* spellcheck_service) - : task_runner_( - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})), + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})), language_(language), use_browser_spellchecker_(false), browser_context_(browser_context), @@ -303,8 +303,7 @@ void SpellcheckHunspellDictionary::DownloadDictionary(GURL url) { auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = url; - resource_request->load_flags = - net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); network::mojom::URLLoaderFactory* loader_factory = diff --git a/chromium/chrome/browser/spellchecker/spellcheck_mac_view_browsertest.mm b/chromium/chrome/browser/spellchecker/spellcheck_mac_view_browsertest.mm index ac1a4e5aceb..4ab4943a317 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_mac_view_browsertest.mm +++ b/chromium/chrome/browser/spellchecker/spellcheck_mac_view_browsertest.mm @@ -12,7 +12,7 @@ #include "content/public/browser/web_contents.h" #if BUILDFLAG(ENABLE_SPELLCHECK) -#include "chrome/browser/spellchecker/test/spellcheck_content_browser_client.h" +#include "chrome/browser/spellchecker/test/spellcheck_panel_browsertest_helper.h" #endif namespace { @@ -24,9 +24,7 @@ class SpellCheckMacViewBrowserTest : public InProcessBrowserTest { #if BUILDFLAG(ENABLE_SPELLCHECK) IN_PROC_BROWSER_TEST_F(SpellCheckMacViewBrowserTest, SpellCheckPanelVisible) { - spellcheck::SpellCheckContentBrowserClient browser_client; - content::ContentBrowserClient* old_browser_client = - content::SetBrowserClientForTesting(&browser_client); + spellcheck::SpellCheckPanelBrowserTestHelper test_helper; ASSERT_TRUE(embedded_test_server()->Start()); auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -36,12 +34,11 @@ IN_PROC_BROWSER_TEST_F(SpellCheckMacViewBrowserTest, SpellCheckPanelVisible) { SEL show_guess_panel = NSSelectorFromString(@"showGuessPanel:"); [web_contents->GetRenderWidgetHostView()->GetNativeView().GetNativeNSView() performSelector:show_guess_panel]; - browser_client.RunUntilBind(); + test_helper.RunUntilBind(); spellcheck::SpellCheckMockPanelHost* host = - browser_client.GetSpellCheckMockPanelHostForProcess( + test_helper.GetSpellCheckMockPanelHostForProcess( web_contents->GetMainFrame()->GetProcess()); EXPECT_TRUE(host->SpellingPanelVisible()); - content::SetBrowserClientForTesting(old_browser_client); } #endif diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service.cc b/chromium/chrome/browser/spellchecker/spellcheck_service.cc index c408235b3c4..f5b38b4f18a 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_service.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_service.cc @@ -10,16 +10,15 @@ #include "base/bind.h" #include "base/logging.h" +#include "base/no_destructor.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/supports_user_data.h" #include "base/synchronization/waitable_event.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/browser/chrome_service.h" #include "chrome/browser/spellchecker/spellcheck_factory.h" #include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h" -#include "chrome/common/constants.mojom.h" #include "chrome/common/pref_names.h" #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_member.h" @@ -39,10 +38,19 @@ #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/storage_partition.h" -#include "services/service_manager/public/cpp/connector.h" +#include "mojo/public/cpp/bindings/remote.h" using content::BrowserThread; +namespace { + +SpellcheckService::SpellCheckerBinder& GetSpellCheckerBinderOverride() { + static base::NoDestructor<SpellcheckService::SpellCheckerBinder> binder; + return *binder; +} + +} // namespace + // TODO(rlp): I do not like globals, but keeping these for now during // transition. // An event used by browser tests to receive status events from this class and @@ -187,13 +195,10 @@ void SpellcheckService::StartRecordingMetrics(bool spellcheck_enabled) { #endif // defined(OS_WIN) } -void SpellcheckService::InitForRenderer( - const service_manager::Identity& renderer_identity) { +void SpellcheckService::InitForRenderer(content::RenderProcessHost* host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - content::BrowserContext* context = - content::BrowserContext::GetBrowserContextForServiceInstanceGroup( - renderer_identity.instance_group()); + content::BrowserContext* context = host->GetBrowserContext(); if (SpellcheckServiceFactory::GetForContext(context) != this) return; @@ -215,13 +220,8 @@ void SpellcheckService::InitForRenderer( custom_dictionary_->GetWords().end()); } - spellcheck::mojom::SpellCheckerPtr spellchecker; - ChromeService::GetInstance()->connector()->BindInterface( - service_manager::ServiceFilter::ByNameWithIdInGroup( - chrome::mojom::kRendererServiceName, renderer_identity.instance_id(), - renderer_identity.instance_group()), - &spellchecker); - spellchecker->Initialize(std::move(dictionaries), custom_words, enable); + GetSpellCheckerForProcess(host)->Initialize(std::move(dictionaries), + custom_words, enable); } SpellCheckHostMetrics* SpellcheckService::GetMetrics() const { @@ -296,9 +296,7 @@ void SpellcheckService::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(content::NOTIFICATION_RENDERER_PROCESS_CREATED, type); - InitForRenderer(content::Source<content::RenderProcessHost>(source) - .ptr() - ->GetChildIdentity()); + InitForRenderer(content::Source<content::RenderProcessHost>(source).ptr()); } void SpellcheckService::OnCustomDictionaryLoaded() { @@ -319,16 +317,8 @@ void SpellcheckService::OnCustomDictionaryChanged( content::RenderProcessHost* process = it.GetCurrentValue(); if (!process->IsInitializedAndNotDead()) continue; - - service_manager::Identity renderer_identity = process->GetChildIdentity(); - spellcheck::mojom::SpellCheckerPtr spellchecker; - ChromeService::GetInstance()->connector()->BindInterface( - service_manager::ServiceFilter::ByNameWithIdInGroup( - chrome::mojom::kRendererServiceName, - renderer_identity.instance_id(), - renderer_identity.instance_group()), - &spellchecker); - spellchecker->CustomDictionaryChanged(additions, deletions); + GetSpellCheckerForProcess(process)->CustomDictionaryChanged(additions, + deletions); } } @@ -350,6 +340,11 @@ void SpellcheckService::OnHunspellDictionaryDownloadFailure( } // static +void SpellcheckService::OverrideBinderForTesting(SpellCheckerBinder binder) { + GetSpellCheckerBinderOverride() = std::move(binder); +} + +// static void SpellcheckService::AttachStatusEvent(base::WaitableEvent* status_event) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -362,6 +357,18 @@ SpellcheckService::EventType SpellcheckService::GetStatusEvent() { return g_status_type; } +mojo::Remote<spellcheck::mojom::SpellChecker> +SpellcheckService::GetSpellCheckerForProcess(content::RenderProcessHost* host) { + mojo::Remote<spellcheck::mojom::SpellChecker> spellchecker; + auto receiver = spellchecker.BindNewPipeAndPassReceiver(); + auto binder = GetSpellCheckerBinderOverride(); + if (binder) + binder.Run(std::move(receiver)); + else + host->BindReceiver(std::move(receiver)); + return spellchecker; +} + void SpellcheckService::InitForAllRenderers() { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (content::RenderProcessHost::iterator i( @@ -369,7 +376,7 @@ void SpellcheckService::InitForAllRenderers() { !i.IsAtEnd(); i.Advance()) { content::RenderProcessHost* process = i.GetCurrentValue(); if (process && process->GetProcess().Handle()) - InitForRenderer(process->GetChildIdentity()); + InitForRenderer(process); } } diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service.h b/chromium/chrome/browser/spellchecker/spellcheck_service.h index 39a29325264..d5af9d5829c 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_service.h +++ b/chromium/chrome/browser/spellchecker/spellcheck_service.h @@ -11,6 +11,7 @@ #include <string> #include <vector> +#include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -19,8 +20,10 @@ #include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h" #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" +#include "components/spellcheck/common/spellcheck.mojom.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "mojo/public/cpp/bindings/remote.h" class SpellCheckHostMetrics; @@ -33,10 +36,7 @@ namespace content { class BrowserContext; class NotificationDetails; class NotificationSource; -} - -namespace service_manager { -class Identity; +class RenderProcessHost; } // Encapsulates the browser side spellcheck service. There is one of these per @@ -98,7 +98,7 @@ class SpellcheckService : public KeyedService, // Pass the renderer some basic initialization information. Note that the // renderer will not load Hunspell until it needs to. - void InitForRenderer(const service_manager::Identity& renderer_identity); + void InitForRenderer(content::RenderProcessHost* host); // Returns a metrics counter associated with this object, // or null when metrics recording is disabled. @@ -143,6 +143,12 @@ class SpellcheckService : public KeyedService, void OnHunspellDictionaryDownloadFailure( const std::string& language) override; + // Allows tests to override how SpellcheckService binds its interface + // receiver, instead of going through a RenderProcessHost by default. + using SpellCheckerBinder = base::RepeatingCallback<void( + mojo::PendingReceiver<spellcheck::mojom::SpellChecker>)>; + static void OverrideBinderForTesting(SpellCheckerBinder binder); + private: FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceBrowserTest, DeleteCorruptedBDICT); @@ -152,6 +158,9 @@ class SpellcheckService : public KeyedService, // Returns the status event type. static EventType GetStatusEvent(); + mojo::Remote<spellcheck::mojom::SpellChecker> GetSpellCheckerForProcess( + content::RenderProcessHost* host); + // Pass all renderers some basic initialization information. void InitForAllRenderers(); diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc b/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc index 38b52079c0f..ec0665d4487 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc @@ -19,13 +19,11 @@ #include "base/test/metrics/histogram_tester.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" -#include "chrome/browser/chrome_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" #include "chrome/browser/spellchecker/spellcheck_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" -#include "chrome/common/constants.mojom.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/browser_sync/browser_sync_switches.h" #include "components/language/core/browser/pref_names.h" @@ -38,8 +36,8 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_utils.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "services/service_manager/public/cpp/connector.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver.h" using content::BrowserContext; using content::RenderProcessHost; @@ -47,7 +45,7 @@ using content::RenderProcessHost; class SpellcheckServiceBrowserTest : public InProcessBrowserTest, public spellcheck::mojom::SpellChecker { public: - SpellcheckServiceBrowserTest() : binding_(this) {} + SpellcheckServiceBrowserTest() = default; void SetUpOnMainThread() override { renderer_.reset(new content::MockRenderProcessHost(GetContext())); @@ -63,10 +61,13 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest, // forever if the service already existed). So disable sync of the custom // dictionary for these tests. command_line->AppendSwitchASCII(switches::kDisableSyncTypes, "Dictionary"); + SpellcheckService::OverrideBinderForTesting(base::BindRepeating( + &SpellcheckServiceBrowserTest::Bind, base::Unretained(this))); } void TearDownOnMainThread() override { - binding_.Close(); + SpellcheckService::OverrideBinderForTesting(base::NullCallback()); + receiver_.reset(); prefs_ = nullptr; renderer_.reset(); } @@ -91,21 +92,9 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest, base::SPLIT_WANT_NONEMPTY)); prefs_->Set(spellcheck::prefs::kSpellCheckDictionaries, dictionaries_value); - service_manager::Identity renderer_identity = renderer_->GetChildIdentity(); SpellcheckService* spellcheck = - SpellcheckServiceFactory::GetForRenderer(renderer_identity); + SpellcheckServiceFactory::GetForContext(renderer_->GetBrowserContext()); ASSERT_NE(nullptr, spellcheck); - - // Override requests for the spellcheck::mojom::SpellChecker interface so we - // can test the SpellChecker request flow. - ChromeService::GetInstance()->connector()->OverrideBinderForTesting( - service_manager::ServiceFilter::ByNameWithIdInGroup( - chrome::mojom::kRendererServiceName, - renderer_identity.instance_id(), - renderer_identity.instance_group()), - spellcheck::mojom::SpellChecker::Name_, - base::BindRepeating(&SpellcheckServiceBrowserTest::Bind, - base::Unretained(this))); } void EnableSpellcheck(bool enable_spellcheck) { @@ -114,7 +103,7 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest, void ChangeCustomDictionary() { SpellcheckService* spellcheck = - SpellcheckServiceFactory::GetForRenderer(renderer_->GetChildIdentity()); + SpellcheckServiceFactory::GetForContext(renderer_->GetBrowserContext()); ASSERT_NE(nullptr, spellcheck); SpellcheckCustomDictionary::Change change; @@ -181,9 +170,10 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest, } // Binds requests for the SpellChecker interface. - void Bind(mojo::ScopedMessagePipeHandle handle) { - binding_.Bind(spellcheck::mojom::SpellCheckerRequest(std::move(handle))); - binding_.set_connection_error_handler( + void Bind(mojo::PendingReceiver<spellcheck::mojom::SpellChecker> receiver) { + receiver_.reset(); + receiver_.Bind(std::move(receiver)); + receiver_.set_disconnect_handler( base::BindOnce(&SpellcheckServiceBrowserTest::BoundConnectionClosed, base::Unretained(this))); } @@ -191,7 +181,7 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest, // The requester closes (disconnects) when done. void BoundConnectionClosed() { bound_connection_closed_ = true; - binding_.Close(); + receiver_.reset(); if (quit_) std::move(quit_).Run(); } @@ -225,7 +215,7 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest, PrefService* prefs_; // Binding to receive the SpellChecker request flow. - mojo::Binding<spellcheck::mojom::SpellChecker> binding_; + mojo::Receiver<spellcheck::mojom::SpellChecker> receiver_{this}; // Used to verify the SpellChecker request flow. bool bound_connection_closed_; @@ -276,9 +266,8 @@ class SpellcheckServiceHostBrowserTest : public SpellcheckServiceBrowserTest { private: void RequestSpellCheckHost(spellcheck::mojom::SpellCheckHostPtr* interface) { - service_manager::BindSourceInfo source_info; - source_info.identity = GetRenderer()->GetChildIdentity(); - SpellCheckHostChromeImpl::Create(mojo::MakeRequest(interface), source_info); + SpellCheckHostChromeImpl::Create(GetRenderer()->GetID(), + mojo::MakeRequest(interface)); } void SpellingServiceDone(bool success, diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc b/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc index c2cab605889..3a4fa901884 100644 --- a/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc +++ b/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc @@ -19,7 +19,7 @@ #include "components/prefs/testing_pref_service.h" #include "components/spellcheck/browser/pref_names.h" #include "components/user_prefs/user_prefs.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" struct TestCase { @@ -103,7 +103,7 @@ class SpellcheckServiceUnitTest : public testing::TestWithParam<TestCase> { struct : public base::SupportsUserData { } context_; TestingPrefServiceSimple prefs_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; DISALLOW_COPY_AND_ASSIGN(SpellcheckServiceUnitTest); }; diff --git a/chromium/chrome/browser/spellchecker/spelling_request.cc b/chromium/chrome/browser/spellchecker/spelling_request.cc index 7453651013c..73a1f30e9a3 100644 --- a/chromium/chrome/browser/spellchecker/spelling_request.cc +++ b/chromium/chrome/browser/spellchecker/spelling_request.cc @@ -15,7 +15,7 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/strong_binding.h" +#include "content/public/browser/render_process_host.h" namespace { @@ -25,25 +25,23 @@ bool CompareLocation(const SpellCheckResult& r1, const SpellCheckResult& r2) { } // namespace -SpellingRequest::SpellingRequest( - SpellingServiceClient* client, - const base::string16& text, - const service_manager::Identity& renderer_identity, - int document_tag, - RequestTextCheckCallback callback, - DestructionCallback destruction_callback) +SpellingRequest::SpellingRequest(SpellingServiceClient* client, + const base::string16& text, + int render_process_id, + int document_tag, + RequestTextCheckCallback callback, + DestructionCallback destruction_callback) : remote_success_(false), text_(text), callback_(std::move(callback)), - destruction_callback_(std::move(destruction_callback)), - weak_factory_(this) { + destruction_callback_(std::move(destruction_callback)) { DCHECK(!text_.empty()); DCHECK_CURRENTLY_ON(content::BrowserThread::UI); completion_barrier_ = BarrierClosure(2, base::BindOnce(&SpellingRequest::OnCheckCompleted, weak_factory_.GetWeakPtr())); - RequestRemoteCheck(client, renderer_identity); + RequestRemoteCheck(client, render_process_id); RequestLocalCheck(document_tag); } @@ -75,16 +73,15 @@ void SpellingRequest::CombineResults( } } -void SpellingRequest::RequestRemoteCheck( - SpellingServiceClient* client, - const service_manager::Identity& renderer_identity) { - content::BrowserContext* context = - content::BrowserContext::GetBrowserContextForServiceInstanceGroup( - renderer_identity.instance_group()); +void SpellingRequest::RequestRemoteCheck(SpellingServiceClient* client, + int render_process_id) { + auto* host = content::RenderProcessHost::FromID(render_process_id); + if (!host) + return; // |this| may be gone at callback invocation if the owner has been removed. client->RequestTextCheck( - context, SpellingServiceClient::SPELLCHECK, text_, + host->GetBrowserContext(), SpellingServiceClient::SPELLCHECK, text_, base::BindOnce(&SpellingRequest::OnRemoteCheckCompleted, weak_factory_.GetWeakPtr())); } @@ -130,10 +127,9 @@ void SpellingRequest::OnLocalCheckCompletedOnAnyThread( base::WeakPtr<SpellingRequest> request, const std::vector<SpellCheckResult>& results) { // Local checking can happen on any thread - don't DCHECK thread. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&SpellingRequest::OnLocalCheckCompleted, request, - results)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&SpellingRequest::OnLocalCheckCompleted, + request, results)); } void SpellingRequest::OnLocalCheckCompleted( diff --git a/chromium/chrome/browser/spellchecker/spelling_request.h b/chromium/chrome/browser/spellchecker/spelling_request.h index 7877e93591b..be895a4751a 100644 --- a/chromium/chrome/browser/spellchecker/spelling_request.h +++ b/chromium/chrome/browser/spellchecker/spelling_request.h @@ -8,7 +8,6 @@ #include "base/containers/unique_ptr_adapters.h" #include "components/spellcheck/browser/spell_check_host_impl.h" #include "components/spellcheck/browser/spelling_service_client.h" -#include "services/service_manager/public/cpp/bind_source_info.h" class SpellingRequest; @@ -23,7 +22,7 @@ class SpellingRequest { SpellingRequest(SpellingServiceClient* client, const base::string16& text, - const service_manager::Identity& renderer_identity, + int render_process_id, int document_tag, RequestTextCheckCallback callback, DestructionCallback destruction_callback); @@ -37,8 +36,7 @@ class SpellingRequest { private: // Request server-side checking for |text_|. - void RequestRemoteCheck(SpellingServiceClient* client, - const service_manager::Identity& renderer_identity); + void RequestRemoteCheck(SpellingServiceClient* client, int render_process_id); // Request a check for |text_| from local spell checker. void RequestLocalCheck(int document_tag); @@ -75,7 +73,7 @@ class SpellingRequest { // Callback to delete |this|. Called on |this| after everything is done. DestructionCallback destruction_callback_; - base::WeakPtrFactory<SpellingRequest> weak_factory_; + base::WeakPtrFactory<SpellingRequest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SpellingRequest); }; diff --git a/chromium/chrome/browser/spellchecker/spelling_service_client_unittest.cc b/chromium/chrome/browser/spellchecker/spelling_service_client_unittest.cc index c94a5e21601..5441a4be28d 100644 --- a/chromium/chrome/browser/spellchecker/spelling_service_client_unittest.cc +++ b/chromium/chrome/browser/spellchecker/spelling_service_client_unittest.cc @@ -23,7 +23,7 @@ #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_features.h" #include "components/spellcheck/common/spellcheck_result.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "net/base/load_flags.h" #include "net/http/http_util.h" #include "services/network/public/cpp/resource_response.h" @@ -127,7 +127,7 @@ class SpellingServiceClientTest return false; } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingSpellingServiceClient client_; TestingProfile profile_; base::test::ScopedFeatureList scoped_feature_list_; @@ -157,6 +157,9 @@ TEST_P(SpellingServiceClientTest, RequestTextCheck) { if (is_rest) { scoped_feature_list_.InitAndEnableFeature( spellcheck::kSpellingServiceRestApi); + } else { + scoped_feature_list_.InitAndDisableFeature( + spellcheck::kSpellingServiceRestApi); } PrefService* pref = profile_.GetPrefs(); @@ -204,7 +207,7 @@ TEST_P(SpellingServiceClientTest, RequestTextCheck) { base::WideToUTF16(test_case.request_text), base::BindOnce(&SpellingServiceClientTest::OnTextCheckComplete, base::Unretained(this), 0)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); // Verify that the expected endpoint was hit (REST vs RPC). ASSERT_EQ(requested_url.path(), expected_request_url.path()); diff --git a/chromium/chrome/browser/supervised_user/supervised_user_error_page/BUILD.gn b/chromium/chrome/browser/supervised_user/supervised_user_error_page/BUILD.gn new file mode 100644 index 00000000000..f6a564d99e3 --- /dev/null +++ b/chromium/chrome/browser/supervised_user/supervised_user_error_page/BUILD.gn @@ -0,0 +1,46 @@ +# 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. + +if (is_android) { + import("//build/config/android/rules.gni") +} + +static_library("supervised_user_error_page") { + sources = [ + "supervised_user_error_page.cc", + "supervised_user_error_page.h", + ] + + deps = [ + "//base", + "//chrome/app:generated_resources", + "//chrome/browser:resources_grit", + "//ui/base", + ] +} + +if (is_android) { + java_cpp_enum("enums_srcjar") { + sources = [ + "supervised_user_error_page.h", + ] + } +} + +source_set("unit_tests") { + testonly = true + sources = [ + "supervised_user_error_page_unittest.cc", + ] + deps = [ + ":supervised_user_error_page", + "//base", + "//base/test:test_support", + "//chrome/app:generated_resources", + "//chrome/browser:resources_grit", + "//testing/gmock", + "//testing/gtest", + "//ui/base", + ] +} diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn index 3ec0ed426c7..1826b714b2e 100644 --- a/chromium/chrome/browser/ui/BUILD.gn +++ b/chromium/chrome/browser/ui/BUILD.gn @@ -26,10 +26,6 @@ import("//third_party/protobuf/proto_library.gni") import("//ui/base/ui_features.gni") import("//ui/views/features.gni") -if (is_chromeos) { - import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni") -} - # Use a static library here because many test binaries depend on this but don't # require many files from it. This makes linking more efficient. jumbo_split_static_library("ui") { @@ -121,7 +117,7 @@ jumbo_split_static_library("ui") { "interventions/intervention_delegate.h", "interventions/intervention_infobar_delegate.cc", "interventions/intervention_infobar_delegate.h", - "javascript_dialogs/chrome_javascript_native_dialog_factory.h", + "javascript_dialogs/chrome_javascript_native_app_modal_dialog_factory.h", "javascript_dialogs/javascript_dialog.h", "javascript_dialogs/javascript_dialog_tab_helper.cc", "javascript_dialogs/javascript_dialog_tab_helper.h", @@ -129,6 +125,8 @@ jumbo_split_static_library("ui") { "login/login_handler.h", "login/login_interstitial_delegate.cc", "login/login_interstitial_delegate.h", + "login/login_navigation_throttle.cc", + "login/login_navigation_throttle.h", "login/login_tab_helper.cc", "login/login_tab_helper.h", "navigation_correction_tab_observer.cc", @@ -139,6 +137,8 @@ jumbo_split_static_library("ui") { "page_info/page_info_ui.h", "passwords/account_avatar_fetcher.cc", "passwords/account_avatar_fetcher.h", + "passwords/credential_leak_dialog_utils.cc", + "passwords/credential_leak_dialog_utils.h", "passwords/manage_passwords_state.cc", "passwords/manage_passwords_state.h", "passwords/manage_passwords_view_utils.cc", @@ -215,8 +215,12 @@ jumbo_split_static_library("ui") { "webauthn/authenticator_request_dialog.h", "webui/about_ui.cc", "webui/about_ui.h", - "webui/autofill_internals_ui.cc", - "webui/autofill_internals_ui.h", + "webui/autofill_and_password_manager_internals/autofill_internals_ui.cc", + "webui/autofill_and_password_manager_internals/autofill_internals_ui.h", + "webui/autofill_and_password_manager_internals/internals_ui_handler.cc", + "webui/autofill_and_password_manager_internals/internals_ui_handler.h", + "webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc", + "webui/autofill_and_password_manager_internals/password_manager_internals_ui.h", "webui/chrome_web_ui_controller_factory.cc", "webui/chrome_web_ui_controller_factory.h", "webui/components_ui.cc", @@ -283,8 +287,6 @@ jumbo_split_static_library("ui") { "webui/omnibox/omnibox_page_handler.h", "webui/omnibox/omnibox_ui.cc", "webui/omnibox/omnibox_ui.h", - "webui/password_manager_internals/password_manager_internals_ui.cc", - "webui/password_manager_internals/password_manager_internals_ui.h", "webui/policy_ui.cc", "webui/policy_ui.h", "webui/policy_ui_handler.cc", @@ -375,6 +377,7 @@ jumbo_split_static_library("ui") { # browser, then we can clean up these dependencies. public_deps = [ "//components/dom_distiller/core", + "//components/safe_browsing:buildflags", "//components/sync", "//components/sync_user_events", "//components/translate/content/browser", @@ -442,7 +445,7 @@ jumbo_split_static_library("ui") { "//components/feedback", "//components/flags_ui", "//components/gcm_driver", - "//components/google/core/browser", + "//components/google/core/common", "//components/heap_profiling", "//components/history/content/browser", "//components/history/core/browser", @@ -479,12 +482,14 @@ jumbo_split_static_library("ui") { "//components/rappor", "//components/renderer_context_menu", "//components/resources", + "//components/safe_browsing:csd_proto", "//components/safe_browsing:features", "//components/safe_browsing/common", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:database_manager", "//components/safe_browsing/db:util", "//components/safe_browsing/password_protection", + "//components/safe_browsing/password_protection:password_protection_metrics_util", "//components/safe_browsing/triggers:ad_popup_trigger", "//components/safe_browsing/triggers:ad_redirect_trigger", "//components/safe_browsing/web_ui", @@ -505,7 +510,6 @@ jumbo_split_static_library("ui") { "//components/strings", "//components/subresource_filter/content/browser", "//components/subresource_filter/core/browser", - "//components/supervised_user_error_page", "//components/sync", "//components/sync_preferences", "//components/sync_sessions", @@ -520,13 +524,14 @@ jumbo_split_static_library("ui") { "//components/update_client", "//components/upload_list", "//components/url_formatter", - "//components/url_formatter/top_domains:common", + "//components/url_formatter/spoof_checks/top_domains:common", "//components/user_manager", "//components/user_prefs", "//components/variations", "//components/variations/service", "//components/vector_icons", "//components/version_ui", + "//components/viz/host", "//components/web_cache/browser", "//components/web_resource", "//components/webrtc_logging/browser", @@ -683,8 +688,6 @@ jumbo_split_static_library("ui") { "android/infobars/near_oom_infobar.h", "android/infobars/near_oom_reduction_infobar.cc", "android/infobars/near_oom_reduction_infobar.h", - "android/infobars/permission_infobar.cc", - "android/infobars/permission_infobar.h", "android/infobars/previews_lite_page_infobar.cc", "android/infobars/previews_lite_page_infobar.h", "android/infobars/reader_mode_infobar.cc", @@ -717,15 +720,21 @@ jumbo_split_static_library("ui") { "android/page_info/connection_info_popup_android.h", "android/page_info/page_info_controller_android.cc", "android/page_info/page_info_controller_android.h", + "android/passwords/credential_leak_dialog_view_android.cc", + "android/passwords/credential_leak_dialog_view_android.h", "android/passwords/manual_filling_view_android.cc", "android/passwords/manual_filling_view_android.h", + "android/passwords/onboarding_dialog_view.cc", + "android/passwords/onboarding_dialog_view.h", "android/passwords/password_generation_dialog_view_android.cc", "android/passwords/password_generation_dialog_view_android.h", "android/passwords/password_generation_editing_popup_view_android.cc", "android/passwords/password_generation_editing_popup_view_android.h", "android/simple_message_box_android.cc", - "android/sms_dialog_android.cc", - "android/sms_dialog_android.h", + "android/sms/sms_infobar.cc", + "android/sms/sms_infobar.h", + "android/sms/sms_infobar_delegate.cc", + "android/sms/sms_infobar_delegate.h", "android/snackbars/auto_signin_prompt_controller.cc", "android/snackbars/auto_signin_prompt_controller.h", "android/ssl_client_certificate_request.cc", @@ -734,7 +743,6 @@ jumbo_split_static_library("ui") { "android/tab_contents/chrome_web_contents_view_delegate_android.h", "android/tab_model/android_live_tab_context.cc", "android/tab_model/android_live_tab_context.h", - "android/tab_model/single_tab_model.cc", "android/tab_model/tab_model.cc", "android/tab_model/tab_model.h", "android/tab_model/tab_model_jni_bridge.cc", @@ -779,6 +787,8 @@ jumbo_split_static_library("ui") { } deps += [ "//chrome/android:jni_headers", + "//chrome/android/features/dev_ui:buildflags", + "//chrome/browser/android/thin_webview:thin_webview", "//components/embedder_support/android:web_contents_delegate", "//components/navigation_interception", "//components/subresource_filter/core/browser", @@ -918,10 +928,8 @@ jumbo_split_static_library("ui") { "global_error/global_error_service.h", "global_error/global_error_service_factory.cc", "global_error/global_error_service_factory.h", - "global_media_controls/media_dialog_controller.cc", - "global_media_controls/media_dialog_controller.h", - "global_media_controls/media_dialog_controller_delegate.cc", - "global_media_controls/media_dialog_controller_delegate.h", + "global_media_controls/media_dialog_delegate.cc", + "global_media_controls/media_dialog_delegate.h", "global_media_controls/media_toolbar_button_controller.cc", "global_media_controls/media_toolbar_button_controller.h", "global_media_controls/media_toolbar_button_controller_delegate.cc", @@ -940,6 +948,10 @@ jumbo_split_static_library("ui") { "hung_renderer/hung_renderer_core.h", "in_product_help/active_tab_tracker.cc", "in_product_help/active_tab_tracker.h", + "in_product_help/global_media_controls_in_product_help.cc", + "in_product_help/global_media_controls_in_product_help.h", + "in_product_help/global_media_controls_in_product_help_factory.cc", + "in_product_help/global_media_controls_in_product_help_factory.h", "in_product_help/in_product_help.h", "in_product_help/reopen_tab_in_product_help.cc", "in_product_help/reopen_tab_in_product_help.h", @@ -949,8 +961,6 @@ jumbo_split_static_library("ui") { "in_product_help/reopen_tab_in_product_help_trigger.h", "intent_picker_tab_helper.cc", "intent_picker_tab_helper.h", - "javascript_dialogs/javascript_dialog_views.cc", - "javascript_dialogs/javascript_dialog_views.h", "layout_constants.cc", "layout_constants.h", "location_bar/location_bar.cc", @@ -1003,6 +1013,12 @@ jumbo_split_static_library("ui") { "page_info/page_info_infobar_delegate.h", "page_info/permission_menu_model.cc", "page_info/permission_menu_model.h", + "passwords/credential_leak_dialog_controller.h", + "passwords/credential_leak_dialog_controller_impl.cc", + "passwords/credential_leak_dialog_controller_impl.h", + "passwords/credential_manager_dialog_controller.h", + "passwords/credential_manager_dialog_controller_impl.cc", + "passwords/credential_manager_dialog_controller_impl.h", "passwords/google_password_manager_navigation_throttle.cc", "passwords/google_password_manager_navigation_throttle.h", "passwords/manage_passwords_bubble_model.cc", @@ -1010,12 +1026,11 @@ jumbo_split_static_library("ui") { "passwords/manage_passwords_icon_view.h", "passwords/manage_passwords_ui_controller.cc", "passwords/manage_passwords_ui_controller.h", - "passwords/password_dialog_controller.h", - "passwords/password_dialog_controller_impl.cc", - "passwords/password_dialog_controller_impl.h", + "passwords/password_base_dialog_controller.h", "passwords/password_dialog_prompts.h", "passwords/passwords_client_ui_delegate.cc", "passwords/passwords_client_ui_delegate.h", + "passwords/passwords_leak_dialog_delegate.h", "passwords/passwords_model_delegate.cc", "passwords/passwords_model_delegate.h", "pdf/adobe_reader_info_win.cc", @@ -1096,10 +1111,10 @@ jumbo_split_static_library("ui") { "tabs/pinned_tab_service_factory.cc", "tabs/pinned_tab_service_factory.h", "tabs/tab_change_type.h", - "tabs/tab_group_data.cc", - "tabs/tab_group_data.h", "tabs/tab_group_id.cc", "tabs/tab_group_id.h", + "tabs/tab_group_visual_data.cc", + "tabs/tab_group_visual_data.h", "tabs/tab_menu_model.cc", "tabs/tab_menu_model.h", "tabs/tab_network_state.cc", @@ -1118,6 +1133,7 @@ jumbo_split_static_library("ui") { "tabs/tab_style.h", "tabs/tab_switch_event_latency_recorder.cc", "tabs/tab_switch_event_latency_recorder.h", + "tabs/tab_types.h", "tabs/tab_utils.cc", "tabs/tab_utils.h", "task_manager/task_manager_columns.cc", @@ -1185,6 +1201,8 @@ jumbo_split_static_library("ui") { "webui/constrained_web_dialog_delegate_base.h", "webui/devtools_ui.cc", "webui/devtools_ui.h", + "webui/devtools_ui_data_source.cc", + "webui/devtools_ui_data_source.h", "webui/downloads/downloads_dom_handler.cc", "webui/downloads/downloads_dom_handler.h", "webui/downloads/downloads_list_tracker.cc", @@ -1214,6 +1232,8 @@ jumbo_split_static_library("ui") { "webui/management_ui.h", "webui/management_ui_handler.cc", "webui/management_ui_handler.h", + "webui/management_ui_handler_chromeos.cc", + "webui/management_ui_handler_chromeos.h", "webui/media_router/media_router_internals_ui.cc", "webui/media_router/media_router_internals_ui.h", "webui/media_router/media_router_internals_webui_message_handler.cc", @@ -1241,8 +1261,6 @@ jumbo_split_static_library("ui") { "webui/policy_indicator_localized_strings_provider.h", "webui/profile_info_watcher.cc", "webui/profile_info_watcher.h", - "webui/set_as_default_browser_ui_win.cc", - "webui/set_as_default_browser_ui_win.h", "webui/settings/about_handler.cc", "webui/settings/about_handler.h", "webui/settings/accessibility_main_handler.cc", @@ -1323,6 +1341,8 @@ jumbo_split_static_library("ui") { "webui/theme_handler.h", "webui/theme_source.cc", "webui/theme_source.h", + "webui/web_footer_experiment_ui.cc", + "webui/web_footer_experiment_ui.h", "window_sizer/window_sizer.cc", "window_sizer/window_sizer.h", "zoom/chrome_zoom_level_otr_delegate.cc", @@ -1358,6 +1378,7 @@ jumbo_split_static_library("ui") { "//device/fido", "//services/device/public/mojom", "//services/metrics/public/cpp:metrics_cpp", + "//third_party/blink/public/common:headers", "//third_party/libaddressinput", "//third_party/libaddressinput:strings", "//ui/events", @@ -1388,14 +1409,6 @@ jumbo_split_static_library("ui") { } } - # TODO(crbug.com/980869): Remove the section below. - if (enable_supervised_users && !is_android && !is_chromeos) { - sources += [ - "startup/supervised_users_deprecated_infobar_delegate.cc", - "startup/supervised_users_deprecated_infobar_delegate.h", - ] - } - if (enable_supervised_users) { sources += [ "webui/supervised_user_internals_message_handler.cc", @@ -1403,6 +1416,7 @@ jumbo_split_static_library("ui") { "webui/supervised_user_internals_ui.cc", "webui/supervised_user_internals_ui.h", ] + deps += [ "//chrome/browser/supervised_user/supervised_user_error_page" ] } if (is_chromeos) { @@ -1431,6 +1445,8 @@ jumbo_split_static_library("ui") { "ash/ambient/photo_controller_impl.h", "ash/arc_chrome_actions_client.cc", "ash/arc_chrome_actions_client.h", + "ash/arc_custom_tab_modal_dialog_host.cc", + "ash/arc_custom_tab_modal_dialog_host.h", "ash/ash_shell_init.cc", "ash/ash_shell_init.h", "ash/ash_util.cc", @@ -1536,9 +1552,8 @@ jumbo_split_static_library("ui") { "ash/system_tray_client.h", "ash/tab_scrubber.cc", "ash/tab_scrubber.h", - "ash/tablet_mode_client.cc", - "ash/tablet_mode_client.h", - "ash/tablet_mode_client_observer.h", + "ash/tablet_mode_page_behavior.cc", + "ash/tablet_mode_page_behavior.h", "ash/test_ime_controller.cc", "ash/test_ime_controller.h", "ash/vpn_list_forwarder.cc", @@ -1599,6 +1614,8 @@ jumbo_split_static_library("ui") { "webui/chromeos/add_supervision/add_supervision_handler.h", "webui/chromeos/add_supervision/add_supervision_handler_utils.cc", "webui/chromeos/add_supervision/add_supervision_handler_utils.h", + "webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc", + "webui/chromeos/add_supervision/add_supervision_metrics_recorder.h", "webui/chromeos/add_supervision/add_supervision_ui.cc", "webui/chromeos/add_supervision/add_supervision_ui.h", "webui/chromeos/add_supervision/confirm_signout_dialog.cc", @@ -1645,6 +1662,8 @@ jumbo_split_static_library("ui") { "webui/chromeos/image_source.h", "webui/chromeos/in_session_password_change/confirm_password_change_handler.cc", "webui/chromeos/in_session_password_change/confirm_password_change_handler.h", + "webui/chromeos/in_session_password_change/password_change_dialogs.cc", + "webui/chromeos/in_session_password_change/password_change_dialogs.h", "webui/chromeos/in_session_password_change/password_change_handler.cc", "webui/chromeos/in_session_password_change/password_change_handler.h", "webui/chromeos/in_session_password_change/password_change_ui.cc", @@ -1821,6 +1840,8 @@ jumbo_split_static_library("ui") { "webui/settings/chromeos/account_manager_handler.h", "webui/settings/chromeos/android_apps_handler.cc", "webui/settings/chromeos/android_apps_handler.h", + "webui/settings/chromeos/app_management/app_management_page_handler_factory.cc", + "webui/settings/chromeos/app_management/app_management_page_handler_factory.h", "webui/settings/chromeos/change_picture_handler.cc", "webui/settings/chromeos/change_picture_handler.h", "webui/settings/chromeos/crostini_handler.cc", @@ -1855,6 +1876,8 @@ jumbo_split_static_library("ui") { "webui/settings/chromeos/parental_controls_handler.h", "webui/settings/chromeos/plugin_vm_handler.cc", "webui/settings/chromeos/plugin_vm_handler.h", + "webui/settings/chromeos/wallpaper_handler.cc", + "webui/settings/chromeos/wallpaper_handler.h", "webui/settings/tts_handler.cc", "webui/settings/tts_handler.h", "webui/signin/inline_login_handler_chromeos.cc", @@ -1875,7 +1898,9 @@ jumbo_split_static_library("ui") { "//ash/public/cpp/resources:ash_public_unscaled_resources", "//ash/public/cpp/vector_icons", "//chrome/browser/chromeos", + "//chrome/browser/chromeos:backdrop_wallpaper_proto", "//chrome/browser/resources/chromeos:camera_resources", + "//chrome/browser/ui/webui/app_management:mojo_bindings", "//chrome/browser/ui/webui/chromeos/add_supervision:mojo_bindings", "//chrome/browser/ui/webui/chromeos/machine_learning:mojo_bindings", "//chrome/services/file_util/public/cpp", @@ -1898,6 +1923,7 @@ jumbo_split_static_library("ui") { "//chromeos/dbus/power", "//chromeos/dbus/session_manager", "//chromeos/dbus/system_clock", + "//chromeos/disks", "//chromeos/login/auth", "//chromeos/login/login_state", "//chromeos/login/session", @@ -1906,6 +1932,7 @@ jumbo_split_static_library("ui") { "//chromeos/services/assistant/public:feature_flags", "//chromeos/services/assistant/public/mojom", "//chromeos/services/assistant/public/proto:proto", + "//chromeos/services/cellular_setup", "//chromeos/services/cellular_setup/public/mojom", "//chromeos/services/machine_learning/public/cpp", "//chromeos/services/multidevice_setup/public/cpp", @@ -1949,16 +1976,17 @@ jumbo_split_static_library("ui") { if (use_cras) { defines += [ "USE_CRAS" ] } - - if (enable_kiosk_next) { - defines += [ "KIOSK_NEXT" ] - } } if (is_win || is_mac || is_desktop_linux || is_chromeos) { sources += [ + "autofill/payments/webauthn_offer_dialog.h", + "autofill/payments/webauthn_offer_dialog_controller.cc", + "autofill/payments/webauthn_offer_dialog_controller.h", "frame/window_frame_util.cc", "frame/window_frame_util.h", + "views/autofill/payments/webauthn_offer_dialog_view.cc", + "views/autofill/payments/webauthn_offer_dialog_view.h", "views/close_bubble_on_tab_activation_helper.cc", "views/close_bubble_on_tab_activation_helper.h", "views/hats/hats_bubble_view.cc", @@ -2003,14 +2031,10 @@ jumbo_split_static_library("ui") { "user_manager.h", "views/external_protocol_dialog.cc", "views/external_protocol_dialog.h", - "views/message_center/popups_only_ui_delegate.cc", - "views/message_center/popups_only_ui_delegate.h", "views/profiles/badged_profile_photo.cc", "views/profiles/badged_profile_photo.h", - "views/profiles/dice_accounts_menu.cc", - "views/profiles/dice_accounts_menu.h", - "views/profiles/profile_chooser_view.cc", - "views/profiles/profile_chooser_view.h", + "views/profiles/profile_menu_view.cc", + "views/profiles/profile_menu_view.h", "views/profiles/signin_view_controller_delegate_views.cc", "views/profiles/signin_view_controller_delegate_views.h", "views/profiles/user_manager_view.cc", @@ -2051,22 +2075,20 @@ jumbo_split_static_library("ui") { "webui/signin/user_manager_screen_handler.h", "webui/signin/user_manager_ui.cc", "webui/signin/user_manager_ui.h", - "webui/welcome/nux/bookmark_handler.cc", - "webui/welcome/nux/bookmark_handler.h", - "webui/welcome/nux/bookmark_item.cc", - "webui/welcome/nux/bookmark_item.h", - "webui/welcome/nux/constants.cc", - "webui/welcome/nux/constants.h", - "webui/welcome/nux/google_apps_handler.cc", - "webui/welcome/nux/google_apps_handler.h", - "webui/welcome/nux/ntp_background_fetcher.cc", - "webui/welcome/nux/ntp_background_fetcher.h", - "webui/welcome/nux/ntp_background_handler.cc", - "webui/welcome/nux/ntp_background_handler.h", - "webui/welcome/nux/set_as_default_handler.cc", - "webui/welcome/nux/set_as_default_handler.h", - "webui/welcome/nux_helper.cc", - "webui/welcome/nux_helper.h", + "webui/welcome/bookmark_handler.cc", + "webui/welcome/bookmark_handler.h", + "webui/welcome/bookmark_item.cc", + "webui/welcome/bookmark_item.h", + "webui/welcome/google_apps_handler.cc", + "webui/welcome/google_apps_handler.h", + "webui/welcome/helpers.cc", + "webui/welcome/helpers.h", + "webui/welcome/ntp_background_fetcher.cc", + "webui/welcome/ntp_background_fetcher.h", + "webui/welcome/ntp_background_handler.cc", + "webui/welcome/ntp_background_handler.h", + "webui/welcome/set_as_default_handler.cc", + "webui/welcome/set_as_default_handler.h", "webui/welcome/welcome_handler.cc", "webui/welcome/welcome_handler.h", "webui/welcome/welcome_ui.cc", @@ -2232,6 +2254,8 @@ jumbo_split_static_library("ui") { "cocoa/tab_contents/chrome_web_contents_view_delegate_mac.mm", "cocoa/tab_contents/web_drag_bookmark_handler_mac.h", "cocoa/tab_contents/web_drag_bookmark_handler_mac.mm", + "cocoa/tab_menu_bridge.h", + "cocoa/tab_menu_bridge.mm", "cocoa/task_manager_mac.h", "cocoa/task_manager_mac.mm", "cocoa/touchbar/browser_window_default_touch_bar.h", @@ -2294,7 +2318,6 @@ jumbo_split_static_library("ui") { "startup/credential_provider_signin_dialog_win.h", "startup/credential_provider_signin_info_fetcher_win.cc", "startup/credential_provider_signin_info_fetcher_win.h", - "startup/default_browser_prompt_win.cc", "views/certificate_viewer_win.cc", "views/chrome_cleaner_dialog_win.cc", "views/chrome_cleaner_dialog_win.h", @@ -2403,6 +2426,8 @@ jumbo_split_static_library("ui") { "views/first_run_dialog.cc", "views/first_run_dialog.h", "views/frame/browser_desktop_window_tree_host.h", + "views/frame/desktop_browser_frame_aura_linux.cc", + "views/frame/desktop_browser_frame_aura_linux.h", "views/status_icons/status_icon_linux_wrapper.cc", "views/status_icons/status_icon_linux_wrapper.h", "webui/help/version_updater_basic.cc", @@ -2432,8 +2457,6 @@ jumbo_split_static_library("ui") { sources += [ "views/frame/browser_desktop_window_tree_host_x11.cc", "views/frame/browser_desktop_window_tree_host_x11.h", - "views/frame/desktop_browser_frame_aurax11.cc", - "views/frame/desktop_browser_frame_aurax11.h", "views/frame/global_menu_bar_registrar_x11.cc", "views/frame/global_menu_bar_registrar_x11.h", "views/frame/global_menu_bar_x11.cc", @@ -2448,6 +2471,7 @@ jumbo_split_static_library("ui") { ] configs += [ "//build/config/linux:x11" ] deps += [ + "//components/dbus/menu", "//ui/events/devices", "//ui/events/devices/x11", "//ui/events/platform/x11", @@ -2459,6 +2483,7 @@ jumbo_split_static_library("ui") { "views/frame/browser_desktop_window_tree_host_platform.h", "views/frame/native_browser_frame_factory_ozone.cc", ] + deps += [ "//ui/platform_window" ] } if (use_gtk) { # This is the only component that can interact with gtk. @@ -2505,11 +2530,15 @@ jumbo_split_static_library("ui") { "autofill/payments/local_card_migration_dialog_state.h", "autofill/payments/manage_migration_ui_controller.cc", "autofill/payments/manage_migration_ui_controller.h", + "autofill/payments/save_card_bubble_controller.h", "autofill/payments/save_card_bubble_controller_impl.cc", "autofill/payments/save_card_bubble_controller_impl.h", "autofill/payments/save_card_bubble_view.h", "autofill/payments/save_card_ui.h", "bubble_anchor_util.h", + "cookie_controls/cookie_controls_controller.cc", + "cookie_controls/cookie_controls_controller.h", + "cookie_controls/cookie_controls_view.h", "manifest_web_app_browser_controller.cc", "manifest_web_app_browser_controller.h", "send_tab_to_self/send_tab_to_self_bubble_controller.cc", @@ -2631,6 +2660,8 @@ jumbo_split_static_library("ui") { "views/desktop_capture/desktop_media_tab_list.h", "views/device_chooser_content_view.cc", "views/device_chooser_content_view.h", + "views/devtools_process_observer.cc", + "views/devtools_process_observer.h", "views/download/download_danger_prompt_views.cc", "views/download/download_in_progress_dialog_view.cc", "views/download/download_in_progress_dialog_view.h", @@ -2653,6 +2684,8 @@ jumbo_split_static_library("ui") { "views/extensions/bookmark_app_confirmation_view.h", "views/extensions/chooser_dialog_view.cc", "views/extensions/chooser_dialog_view.h", + "views/extensions/extension_context_menu_controller.cc", + "views/extensions/extension_context_menu_controller.h", "views/extensions/extension_install_dialog_view.cc", "views/extensions/extension_install_dialog_view.h", "views/extensions/extension_installed_bubble_view.cc", @@ -2662,6 +2695,8 @@ jumbo_split_static_library("ui") { "views/extensions/extension_uninstall_dialog_view.cc", "views/extensions/extensions_menu_button.cc", "views/extensions/extensions_menu_button.h", + "views/extensions/extensions_menu_item_view.cc", + "views/extensions/extensions_menu_item_view.h", "views/extensions/extensions_menu_view.cc", "views/extensions/extensions_menu_view.h", "views/extensions/extensions_toolbar_button.cc", @@ -2676,6 +2711,8 @@ jumbo_split_static_library("ui") { "views/feature_promos/feature_promo_bubble_timeout.h", "views/feature_promos/feature_promo_bubble_view.cc", "views/feature_promos/feature_promo_bubble_view.h", + "views/feature_promos/global_media_controls_promo_controller.cc", + "views/feature_promos/global_media_controls_promo_controller.h", "views/feature_promos/reopen_tab_promo_controller.cc", "views/feature_promos/reopen_tab_promo_controller.h", "views/find_bar_host.cc", @@ -2725,6 +2762,8 @@ jumbo_split_static_library("ui") { "views/frame/system_menu_model_delegate.h", "views/frame/tab_strip_region_view.cc", "views/frame/tab_strip_region_view.h", + "views/frame/terminal_system_app_menu_button_chromeos.cc", + "views/frame/terminal_system_app_menu_button_chromeos.h", "views/frame/toolbar_button_provider.h", "views/frame/top_container_view.cc", "views/frame/top_container_view.h", @@ -2732,6 +2771,10 @@ jumbo_split_static_library("ui") { "views/frame/web_contents_close_handler.cc", "views/frame/web_contents_close_handler.h", "views/frame/web_contents_close_handler_delegate.h", + "views/frame/web_footer_experiment_view.cc", + "views/frame/web_footer_experiment_view.h", + "views/front_eliding_title_label.cc", + "views/front_eliding_title_label.h", "views/fullscreen_control/fullscreen_control_host.cc", "views/fullscreen_control/fullscreen_control_host.h", "views/fullscreen_control/fullscreen_control_popup.cc", @@ -2750,6 +2793,8 @@ jumbo_split_static_library("ui") { "views/global_media_controls/media_toolbar_button_view.h", "views/hover_button.cc", "views/hover_button.h", + "views/hover_button_controller.cc", + "views/hover_button_controller.h", "views/hung_renderer_view.cc", "views/hung_renderer_view.h", "views/ime/ime_warning_bubble_view.cc", @@ -2764,10 +2809,20 @@ jumbo_split_static_library("ui") { "views/infobars/infobar_container_view.h", "views/infobars/infobar_view.cc", "views/infobars/infobar_view.h", + "views/javascript_dialog_views.cc", + "views/javascript_dialog_views.h", + "views/layout/animating_layout_manager.cc", + "views/layout/animating_layout_manager.h", + "views/layout/interpolating_layout_manager.cc", + "views/layout/interpolating_layout_manager.h", "views/load_complete_listener.cc", "views/load_complete_listener.h", "views/location_bar/content_setting_image_view.cc", "views/location_bar/content_setting_image_view.h", + "views/location_bar/cookie_controls_bubble_view.cc", + "views/location_bar/cookie_controls_bubble_view.h", + "views/location_bar/cookie_controls_icon_view.cc", + "views/location_bar/cookie_controls_icon_view.h", "views/location_bar/custom_tab_bar_view.cc", "views/location_bar/custom_tab_bar_view.h", "views/location_bar/find_bar_icon.cc", @@ -2793,8 +2848,6 @@ jumbo_split_static_library("ui") { "views/login_handler_views.cc", "views/login_view.cc", "views/login_view.h", - "views/material_refresh_layout_provider.cc", - "views/material_refresh_layout_provider.h", "views/md_text_button_with_down_arrow.cc", "views/md_text_button_with_down_arrow.h", "views/media_router/cast_dialog_helper.cc", @@ -2856,8 +2909,6 @@ jumbo_split_static_library("ui") { "views/overlay/back_to_tab_image_button.h", "views/overlay/close_image_button.cc", "views/overlay/close_image_button.h", - "views/overlay/mute_image_button.cc", - "views/overlay/mute_image_button.h", "views/overlay/overlay_window_views.cc", "views/overlay/overlay_window_views.h", "views/overlay/playback_image_button.cc", @@ -2888,10 +2939,14 @@ jumbo_split_static_library("ui") { "views/page_info/permission_selector_row.cc", "views/page_info/permission_selector_row.h", "views/page_info/permission_selector_row_observer.h", + "views/page_info/safety_tip_page_info_bubble_view.cc", + "views/page_info/safety_tip_page_info_bubble_view.h", "views/passwords/account_chooser_dialog_view.cc", "views/passwords/account_chooser_dialog_view.h", "views/passwords/auto_signin_first_run_dialog_view.cc", "views/passwords/auto_signin_first_run_dialog_view.h", + "views/passwords/credential_leak_dialog_view.cc", + "views/passwords/credential_leak_dialog_view.h", "views/passwords/credentials_item_view.cc", "views/passwords/credentials_item_view.h", "views/passwords/manage_passwords_icon_views.cc", @@ -2987,10 +3042,10 @@ jumbo_split_static_library("ui") { "views/send_tab_to_self/send_tab_to_self_icon_view.h", "views/session_crashed_bubble_view.cc", "views/session_crashed_bubble_view.h", - "views/sharing/click_to_call/click_to_call_dialog_view.cc", - "views/sharing/click_to_call/click_to_call_dialog_view.h", - "views/sharing/click_to_call/click_to_call_icon_view.cc", - "views/sharing/click_to_call/click_to_call_icon_view.h", + "views/sharing/sharing_dialog_view.cc", + "views/sharing/sharing_dialog_view.h", + "views/sharing/sharing_icon_view.cc", + "views/sharing/sharing_icon_view.h", "views/simple_message_box_views.cc", "views/simple_message_box_views.h", "views/status_bubble_views.cc", @@ -3013,6 +3068,8 @@ jumbo_split_static_library("ui") { "views/tabs/alert_indicator.h", "views/tabs/browser_tab_strip_controller.cc", "views/tabs/browser_tab_strip_controller.h", + "views/tabs/color_picker_view.cc", + "views/tabs/color_picker_view.h", "views/tabs/glow_hover_controller.cc", "views/tabs/glow_hover_controller.h", "views/tabs/new_tab_button.cc", @@ -3031,6 +3088,8 @@ jumbo_split_static_library("ui") { "views/tabs/tab_drag_context.h", "views/tabs/tab_drag_controller.cc", "views/tabs/tab_drag_controller.h", + "views/tabs/tab_group_editor_bubble_view.cc", + "views/tabs/tab_group_editor_bubble_view.h", "views/tabs/tab_group_header.cc", "views/tabs/tab_group_header.h", "views/tabs/tab_hover_card_bubble_view.cc", @@ -3039,17 +3098,19 @@ jumbo_split_static_library("ui") { "views/tabs/tab_icon.h", "views/tabs/tab_renderer_data.cc", "views/tabs/tab_renderer_data.h", + "views/tabs/tab_slot_view.h", "views/tabs/tab_strip.cc", "views/tabs/tab_strip.h", - "views/tabs/tab_strip_animator.cc", - "views/tabs/tab_strip_animator.h", "views/tabs/tab_strip_controller.h", "views/tabs/tab_strip_layout.cc", "views/tabs/tab_strip_layout.h", "views/tabs/tab_strip_layout_helper.cc", "views/tabs/tab_strip_layout_helper.h", + "views/tabs/tab_strip_layout_types.h", "views/tabs/tab_style_views.cc", "views/tabs/tab_style_views.h", + "views/tabs/tab_width_constraints.cc", + "views/tabs/tab_width_constraints.h", "views/tabs/window_finder.h", "views/task_manager_view.cc", "views/task_manager_view.h", @@ -3166,8 +3227,6 @@ jumbo_split_static_library("ui") { if (is_linux) { sources += [ - "views/frame/browser_command_handler_linux.cc", - "views/frame/browser_command_handler_linux.h", "views/process_singleton_dialog_linux.cc", "views/status_icons/status_tray_linux.cc", "views/status_icons/status_tray_linux.h", @@ -3402,8 +3461,14 @@ jumbo_split_static_library("ui") { "app_list/search/arc/arc_playstore_search_result.h", "app_list/search/chrome_search_result.cc", "app_list/search/chrome_search_result.h", + "app_list/search/common/file_icon_util.cc", + "app_list/search/common/file_icon_util.h", "app_list/search/common/url_icon_source.cc", "app_list/search/common/url_icon_source.h", + "app_list/search/drive_quick_access_provider.cc", + "app_list/search/drive_quick_access_provider.h", + "app_list/search/drive_quick_access_result.cc", + "app_list/search/drive_quick_access_result.h", "app_list/search/extension_app_result.cc", "app_list/search/extension_app_result.h", "app_list/search/logging/search_ranking_event_logger.cc", @@ -3426,6 +3491,8 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/app_launch_data.h", "app_list/search/search_result_ranker/app_launch_event_logger.cc", "app_list/search/search_result_ranker/app_launch_event_logger.h", + "app_list/search/search_result_ranker/app_launch_event_logger_helper.cc", + "app_list/search/search_result_ranker/app_launch_event_logger_helper.h", "app_list/search/search_result_ranker/app_launch_predictor.cc", "app_list/search/search_result_ranker/app_launch_predictor.h", "app_list/search/search_result_ranker/app_list_launch_metrics_provider.cc", @@ -3440,6 +3507,8 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/frecency_store.h", "app_list/search/search_result_ranker/histogram_util.cc", "app_list/search/search_result_ranker/histogram_util.h", + "app_list/search/search_result_ranker/ml_app_rank_provider.cc", + "app_list/search/search_result_ranker/ml_app_rank_provider.h", "app_list/search/search_result_ranker/ranking_item_util.cc", "app_list/search/search_result_ranker/ranking_item_util.h", "app_list/search/search_result_ranker/recurrence_predictor.cc", @@ -3450,12 +3519,18 @@ jumbo_split_static_library("ui") { "app_list/search/search_result_ranker/recurrence_ranker_util.h", "app_list/search/search_result_ranker/search_result_ranker.cc", "app_list/search/search_result_ranker/search_result_ranker.h", + "app_list/search/search_utils/sequence_matcher.cc", + "app_list/search/search_utils/sequence_matcher.h", "app_list/search/settings_shortcut/settings_shortcut_metadata.cc", "app_list/search/settings_shortcut/settings_shortcut_metadata.h", "app_list/search/settings_shortcut/settings_shortcut_provider.cc", "app_list/search/settings_shortcut/settings_shortcut_provider.h", "app_list/search/settings_shortcut/settings_shortcut_result.cc", "app_list/search/settings_shortcut/settings_shortcut_result.h", + "app_list/search/zero_state_file_provider.cc", + "app_list/search/zero_state_file_provider.h", + "app_list/search/zero_state_file_result.cc", + "app_list/search/zero_state_file_result.h", ] deps += [ # TODO(wutao): Put new icons resources to ash/public/cpp/vector_icons/ @@ -3468,11 +3543,16 @@ jumbo_split_static_library("ui") { "//chrome/browser/ui/app_list/search/search_result_ranker:app_launch_predictor_proto", "//chrome/browser/ui/app_list/search/search_result_ranker:app_list_launch_recorder_proto", "//chrome/browser/ui/app_list/search/search_result_ranker:recurrence_ranker_proto", + "//components/assist_ranker", + "//components/assist_ranker/proto", + "//ui/file_manager:file_manager", ] if (is_chromeos) { sources += [ "app_icon_loader_delegate.h", + "app_list/app_service_app_icon_loader.cc", + "app_list/app_service_app_icon_loader.h", "app_list/app_service_app_item.cc", "app_list/app_service_app_item.h", "app_list/app_service_app_model_builder.cc", @@ -3579,6 +3659,8 @@ jumbo_split_static_library("ui") { "ash/launcher/internal_app_shelf_context_menu.h", "ash/launcher/internal_app_window_shelf_controller.cc", "ash/launcher/internal_app_window_shelf_controller.h", + "ash/launcher/launcher_app_service_app_updater.cc", + "ash/launcher/launcher_app_service_app_updater.h", "ash/launcher/launcher_arc_app_updater.cc", "ash/launcher/launcher_arc_app_updater.h", "ash/launcher/launcher_crostini_app_updater.cc", @@ -3607,6 +3689,7 @@ jumbo_split_static_library("ui") { deps += [ "//chrome/services/app_service/public/cpp:app_update", "//chrome/services/app_service/public/cpp:icon_loader", + "//components/services/app_service/public/cpp:app_file_handling", ] } } @@ -3616,6 +3699,12 @@ jumbo_split_static_library("ui") { "//ash/public/cpp", "//chromeos/services/assistant:lib", "//chromeos/services/assistant/public/mojom", + "//chromeos/services/network_config/public/mojom", + "//services/audio/public/mojom", + "//services/device/public/mojom", + "//services/identity/public/mojom", + "//services/media_session/public/mojom", + "//services/preferences/public/mojom", ] sources += [ @@ -3625,10 +3714,16 @@ jumbo_split_static_library("ui") { "ash/assistant/assistant_context_util.h", "ash/assistant/assistant_image_downloader.cc", "ash/assistant/assistant_image_downloader.h", + "ash/assistant/assistant_service_connection.cc", + "ash/assistant/assistant_service_connection.h", "ash/assistant/assistant_setup.cc", "ash/assistant/assistant_setup.h", "ash/assistant/device_actions.cc", "ash/assistant/device_actions.h", + "ash/assistant/proactive_suggestions_client_impl.cc", + "ash/assistant/proactive_suggestions_client_impl.h", + "ash/assistant/proactive_suggestions_loader.cc", + "ash/assistant/proactive_suggestions_loader.h", ] } @@ -3680,14 +3775,14 @@ jumbo_split_static_library("ui") { "extensions/extensions_container.h", "extensions/hosted_app_browser_controller.cc", "extensions/hosted_app_browser_controller.h", - "extensions/hosted_app_menu_model.cc", - "extensions/hosted_app_menu_model.h", "extensions/icon_with_badge_image_source.cc", "extensions/icon_with_badge_image_source.h", "extensions/installation_error_infobar_delegate.cc", "extensions/installation_error_infobar_delegate.h", "extensions/settings_api_bubble_helpers.cc", "extensions/settings_api_bubble_helpers.h", + "extensions/terminal_system_app_menu_model_chromeos.cc", + "extensions/terminal_system_app_menu_model_chromeos.h", "views/extensions/browser_action_drag_data.cc", "views/extensions/browser_action_drag_data.h", "views/extensions/extension_action_platform_delegate_views.cc", @@ -3706,14 +3801,20 @@ jumbo_split_static_library("ui") { "views/extensions/media_gallery_checkbox_view.h", "web_applications/app_browser_controller.cc", "web_applications/app_browser_controller.h", - "web_applications/system_web_app_ui_utils_chromeos.cc", - "web_applications/system_web_app_ui_utils_chromeos.h", + "web_applications/system_web_app_ui_utils.cc", + "web_applications/system_web_app_ui_utils.h", + "web_applications/web_app_browser_controller.cc", + "web_applications/web_app_browser_controller.h", "web_applications/web_app_dialog_manager.cc", "web_applications/web_app_dialog_manager.h", "web_applications/web_app_dialog_utils.cc", "web_applications/web_app_dialog_utils.h", "web_applications/web_app_launch_manager.cc", "web_applications/web_app_launch_manager.h", + "web_applications/web_app_launch_utils.cc", + "web_applications/web_app_launch_utils.h", + "web_applications/web_app_menu_model.cc", + "web_applications/web_app_menu_model.h", "web_applications/web_app_metrics.cc", "web_applications/web_app_metrics.h", "web_applications/web_app_metrics_factory.cc", @@ -3839,10 +3940,6 @@ jumbo_split_static_library("ui") { deps += [ "//dbus" ] } - if (use_gio) { - configs += [ "//build/linux:gio_config" ] - } - if (use_nss_certs) { sources += [ "crypto_module_delegate_nss.cc", @@ -3874,6 +3971,19 @@ jumbo_split_static_library("ui") { "//components/offline_pages/core/prefetch", ] } + + if (enable_webui_tab_strip) { + deps += [ "//chrome/browser/resources:tab_strip_resources" ] + + sources += [ + "views/frame/webui_tab_strip_container_view.cc", + "views/frame/webui_tab_strip_container_view.h", + "webui/tab_strip/tab_strip_ui.cc", + "webui/tab_strip/tab_strip_ui.h", + "webui/tab_strip/thumbnail_tracker.cc", + "webui/tab_strip/thumbnail_tracker.h", + ] + } } # In GYP this is part of test_support_common. @@ -3955,10 +4065,12 @@ static_library("test_support") { "exclusive_access/fullscreen_controller_test.h", "global_error/global_error_waiter.cc", "global_error/global_error_waiter.h", + "passwords/credential_manager_dialog_controller_mock.cc", + "passwords/credential_manager_dialog_controller_mock.h", "passwords/manage_passwords_ui_controller_mock.cc", "passwords/manage_passwords_ui_controller_mock.h", - "passwords/password_dialog_controller_mock.cc", - "passwords/password_dialog_controller_mock.h", + "passwords/passwords_leak_dialog_delegate_mock.cc", + "passwords/passwords_leak_dialog_delegate_mock.h", "passwords/passwords_model_delegate_mock.cc", "passwords/passwords_model_delegate_mock.h", "tabs/tab_ukm_test_helper.cc", @@ -3980,8 +4092,6 @@ static_library("test_support") { sources += [ "ash/ash_test_util.cc", "ash/ash_test_util.h", - "ash/fake_tablet_mode_controller.cc", - "ash/fake_tablet_mode_controller.h", "ash/test_login_screen.cc", "ash/test_login_screen.h", "ash/test_login_screen_model.cc", diff --git a/chromium/chrome/browser/ui/android/widget/BUILD.gn b/chromium/chrome/browser/ui/android/widget/BUILD.gn new file mode 100644 index 00000000000..13fa251ecb6 --- /dev/null +++ b/chromium/chrome/browser/ui/android/widget/BUILD.gn @@ -0,0 +1,102 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/android/rules.gni") + +android_library("java") { + java_files = [ + "java/src/org/chromium/chrome/browser/ui/widget/CompositeTouchDelegate.java", + "java/src/org/chromium/chrome/browser/ui/widget/FadingShadow.java", + "java/src/org/chromium/chrome/browser/ui/widget/FadingShadowView.java", + "java/src/org/chromium/chrome/browser/ui/widget/ListMenuButton.java", + "java/src/org/chromium/chrome/browser/ui/widget/text/TextViewWithCompoundDrawables.java", + ] + + deps = [ + ":ui_widget_java_resources", + "//base:base_java", + "//third_party/android_deps:android_support_v7_appcompat_java", + "//third_party/android_deps:com_android_support_design_java", + "//ui/android:ui_java", + ] +} + +android_resources("ui_widget_java_resources") { + custom_package = "org.chromium.chrome.browser.ui.widget" + resource_dirs = [ "java/res" ] + deps = [ + ":ui_widget_strings_grd", + "//ui/android:ui_java_resources", + ] +} + +java_strings_grd("ui_widget_strings_grd") { + grd_file = "java/strings/android_ui_widget_strings.grd" + outputs = [ + "values/android_ui_widget_strings.xml", + "values-am/android_ui_widget_strings.xml", + "values-ar/android_ui_widget_strings.xml", + "values-bg/android_ui_widget_strings.xml", + "values-bn/android_ui_widget_strings.xml", + "values-ca/android_ui_widget_strings.xml", + "values-cs/android_ui_widget_strings.xml", + "values-da/android_ui_widget_strings.xml", + "values-de/android_ui_widget_strings.xml", + "values-el/android_ui_widget_strings.xml", + "values-en-rGB/android_ui_widget_strings.xml", + "values-es/android_ui_widget_strings.xml", + "values-es-rUS/android_ui_widget_strings.xml", + "values-et/android_ui_widget_strings.xml", + "values-fa/android_ui_widget_strings.xml", + "values-fi/android_ui_widget_strings.xml", + "values-fr/android_ui_widget_strings.xml", + "values-gu/android_ui_widget_strings.xml", + "values-hi/android_ui_widget_strings.xml", + "values-hr/android_ui_widget_strings.xml", + "values-hu/android_ui_widget_strings.xml", + "values-in/android_ui_widget_strings.xml", + "values-it/android_ui_widget_strings.xml", + "values-iw/android_ui_widget_strings.xml", + "values-ja/android_ui_widget_strings.xml", + "values-kn/android_ui_widget_strings.xml", + "values-ko/android_ui_widget_strings.xml", + "values-lt/android_ui_widget_strings.xml", + "values-lv/android_ui_widget_strings.xml", + "values-ml/android_ui_widget_strings.xml", + "values-mr/android_ui_widget_strings.xml", + "values-ms/android_ui_widget_strings.xml", + "values-nb/android_ui_widget_strings.xml", + "values-nl/android_ui_widget_strings.xml", + "values-pl/android_ui_widget_strings.xml", + "values-pt-rBR/android_ui_widget_strings.xml", + "values-pt-rPT/android_ui_widget_strings.xml", + "values-ro/android_ui_widget_strings.xml", + "values-ru/android_ui_widget_strings.xml", + "values-sk/android_ui_widget_strings.xml", + "values-sl/android_ui_widget_strings.xml", + "values-sr/android_ui_widget_strings.xml", + "values-sv/android_ui_widget_strings.xml", + "values-sw/android_ui_widget_strings.xml", + "values-ta/android_ui_widget_strings.xml", + "values-te/android_ui_widget_strings.xml", + "values-th/android_ui_widget_strings.xml", + "values-tl/android_ui_widget_strings.xml", + "values-tr/android_ui_widget_strings.xml", + "values-uk/android_ui_widget_strings.xml", + "values-vi/android_ui_widget_strings.xml", + "values-zh-rCN/android_ui_widget_strings.xml", + "values-zh-rTW/android_ui_widget_strings.xml", + ] +} + +junit_binary("ui_widget_junit_tests") { + java_files = [ "junit/src/org/chromium/chrome//browser/ui/widget/CompositeTouchDelegateTest.java" ] + deps = [ + ":java", + "//base:base_java", + "//base:base_java_test_support", + "//base:base_junit_test_support", + "//base/test:test_support_java", + ] +} diff --git a/chromium/chrome/browser/ui/android/widget/java/strings/android_ui_widget_strings.grd b/chromium/chrome/browser/ui/android/widget/java/strings/android_ui_widget_strings.grd new file mode 100644 index 00000000000..258217f9954 --- /dev/null +++ b/chromium/chrome/browser/ui/android/widget/java/strings/android_ui_widget_strings.grd @@ -0,0 +1,119 @@ +<?xml version="1.0" encoding="UTF-8"?> +<grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> + <outputs> + <output filename="values-am/android_ui_widget_strings.xml" lang="am" type="android" /> + <output filename="values-ar/android_ui_widget_strings.xml" lang="ar" type="android" /> + <output filename="values-bg/android_ui_widget_strings.xml" lang="bg" type="android" /> + <output filename="values-bn/android_ui_widget_strings.xml" lang="bn" type="android" /> + <output filename="values-ca/android_ui_widget_strings.xml" lang="ca" type="android" /> + <output filename="values-cs/android_ui_widget_strings.xml" lang="cs" type="android" /> + <output filename="values-da/android_ui_widget_strings.xml" lang="da" type="android" /> + <output filename="values-de/android_ui_widget_strings.xml" lang="de" type="android" /> + <output filename="values-el/android_ui_widget_strings.xml" lang="el" type="android" /> + <output filename="values/android_ui_widget_strings.xml" lang="en" type="android" /> + <output filename="values-en-rGB/android_ui_widget_strings.xml" lang="en-GB" type="android" /> + <output filename="values-es/android_ui_widget_strings.xml" lang="es" type="android" /> + <output filename="values-es-rUS/android_ui_widget_strings.xml" lang="es-419" type="android" /> + <output filename="values-et/android_ui_widget_strings.xml" lang="et" type="android" /> + <output filename="values-fa/android_ui_widget_strings.xml" lang="fa" type="android" /> + <output filename="values-fi/android_ui_widget_strings.xml" lang="fi" type="android" /> + <output filename="values-tl/android_ui_widget_strings.xml" lang="fil" type="android" /> + <output filename="values-fr/android_ui_widget_strings.xml" lang="fr" type="android" /> + <output filename="values-gu/android_ui_widget_strings.xml" lang="gu" type="android" /> + <output filename="values-hi/android_ui_widget_strings.xml" lang="hi" type="android" /> + <output filename="values-hr/android_ui_widget_strings.xml" lang="hr" type="android" /> + <output filename="values-hu/android_ui_widget_strings.xml" lang="hu" type="android" /> + <output filename="values-in/android_ui_widget_strings.xml" lang="id" type="android" /> + <output filename="values-it/android_ui_widget_strings.xml" lang="it" type="android" /> + <output filename="values-iw/android_ui_widget_strings.xml" lang="iw" type="android" /> + <output filename="values-ja/android_ui_widget_strings.xml" lang="ja" type="android" /> + <output filename="values-kn/android_ui_widget_strings.xml" lang="kn" type="android" /> + <output filename="values-ko/android_ui_widget_strings.xml" lang="ko" type="android" /> + <output filename="values-lt/android_ui_widget_strings.xml" lang="lt" type="android" /> + <output filename="values-lv/android_ui_widget_strings.xml" lang="lv" type="android" /> + <output filename="values-ml/android_ui_widget_strings.xml" lang="ml" type="android" /> + <output filename="values-mr/android_ui_widget_strings.xml" lang="mr" type="android" /> + <output filename="values-ms/android_ui_widget_strings.xml" lang="ms" type="android" /> + <output filename="values-nl/android_ui_widget_strings.xml" lang="nl" type="android" /> + <output filename="values-nb/android_ui_widget_strings.xml" lang="no" type="android" /> + <output filename="values-pl/android_ui_widget_strings.xml" lang="pl" type="android" /> + <output filename="values-pt-rBR/android_ui_widget_strings.xml" lang="pt-BR" type="android" /> + <output filename="values-pt-rPT/android_ui_widget_strings.xml" lang="pt-PT" type="android" /> + <output filename="values-ro/android_ui_widget_strings.xml" lang="ro" type="android" /> + <output filename="values-ru/android_ui_widget_strings.xml" lang="ru" type="android" /> + <output filename="values-sk/android_ui_widget_strings.xml" lang="sk" type="android" /> + <output filename="values-sl/android_ui_widget_strings.xml" lang="sl" type="android" /> + <output filename="values-sr/android_ui_widget_strings.xml" lang="sr" type="android" /> + <output filename="values-sv/android_ui_widget_strings.xml" lang="sv" type="android" /> + <output filename="values-sw/android_ui_widget_strings.xml" lang="sw" type="android" /> + <output filename="values-ta/android_ui_widget_strings.xml" lang="ta" type="android" /> + <output filename="values-te/android_ui_widget_strings.xml" lang="te" type="android" /> + <output filename="values-th/android_ui_widget_strings.xml" lang="th" type="android" /> + <output filename="values-tr/android_ui_widget_strings.xml" lang="tr" type="android" /> + <output filename="values-uk/android_ui_widget_strings.xml" lang="uk" type="android" /> + <output filename="values-vi/android_ui_widget_strings.xml" lang="vi" type="android" /> + <output filename="values-zh-rCN/android_ui_widget_strings.xml" lang="zh-CN" type="android" /> + <output filename="values-zh-rTW/android_ui_widget_strings.xml" lang="zh-TW" type="android" /> + </outputs> + <translations> + <file lang="am" path="translations/android_ui_widget_strings_am.xtb" /> + <file lang="ar" path="translations/android_ui_widget_strings_ar.xtb" /> + <file lang="bg" path="translations/android_ui_widget_strings_bg.xtb" /> + <file lang="bn" path="translations/android_ui_widget_strings_bn.xtb" /> + <file lang="ca" path="translations/android_ui_widget_strings_ca.xtb" /> + <file lang="cs" path="translations/android_ui_widget_strings_cs.xtb" /> + <file lang="da" path="translations/android_ui_widget_strings_da.xtb" /> + <file lang="de" path="translations/android_ui_widget_strings_de.xtb" /> + <file lang="el" path="translations/android_ui_widget_strings_el.xtb" /> + <file lang="en-GB" path="translations/android_ui_widget_strings_en-GB.xtb" /> + <file lang="es" path="translations/android_ui_widget_strings_es.xtb" /> + <file lang="es-419" path="translations/android_ui_widget_strings_es-419.xtb" /> + <file lang="et" path="translations/android_ui_widget_strings_et.xtb" /> + <file lang="fa" path="translations/android_ui_widget_strings_fa.xtb" /> + <file lang="fi" path="translations/android_ui_widget_strings_fi.xtb" /> + <file lang="fil" path="translations/android_ui_widget_strings_fil.xtb" /> + <file lang="fr" path="translations/android_ui_widget_strings_fr.xtb" /> + <file lang="gu" path="translations/android_ui_widget_strings_gu.xtb" /> + <file lang="hi" path="translations/android_ui_widget_strings_hi.xtb" /> + <file lang="hr" path="translations/android_ui_widget_strings_hr.xtb" /> + <file lang="hu" path="translations/android_ui_widget_strings_hu.xtb" /> + <file lang="id" path="translations/android_ui_widget_strings_id.xtb" /> + <file lang="it" path="translations/android_ui_widget_strings_it.xtb" /> + <file lang="iw" path="translations/android_ui_widget_strings_iw.xtb" /> + <file lang="ja" path="translations/android_ui_widget_strings_ja.xtb" /> + <file lang="ko" path="translations/android_ui_widget_strings_ko.xtb" /> + <file lang="kn" path="translations/android_ui_widget_strings_kn.xtb" /> + <file lang="lt" path="translations/android_ui_widget_strings_lt.xtb" /> + <file lang="lv" path="translations/android_ui_widget_strings_lv.xtb" /> + <file lang="ml" path="translations/android_ui_widget_strings_ml.xtb" /> + <file lang="mr" path="translations/android_ui_widget_strings_mr.xtb" /> + <file lang="ms" path="translations/android_ui_widget_strings_ms.xtb" /> + <file lang="nl" path="translations/android_ui_widget_strings_nl.xtb" /> + <file lang="no" path="translations/android_ui_widget_strings_no.xtb" /> + <file lang="pl" path="translations/android_ui_widget_strings_pl.xtb" /> + <file lang="pt-BR" path="translations/android_ui_widget_strings_pt-BR.xtb" /> + <file lang="pt-PT" path="translations/android_ui_widget_strings_pt-PT.xtb" /> + <file lang="ro" path="translations/android_ui_widget_strings_ro.xtb" /> + <file lang="ru" path="translations/android_ui_widget_strings_ru.xtb" /> + <file lang="sk" path="translations/android_ui_widget_strings_sk.xtb" /> + <file lang="sl" path="translations/android_ui_widget_strings_sl.xtb" /> + <file lang="sr" path="translations/android_ui_widget_strings_sr.xtb" /> + <file lang="sv" path="translations/android_ui_widget_strings_sv.xtb" /> + <file lang="sw" path="translations/android_ui_widget_strings_sw.xtb" /> + <file lang="ta" path="translations/android_ui_widget_strings_ta.xtb" /> + <file lang="te" path="translations/android_ui_widget_strings_te.xtb" /> + <file lang="th" path="translations/android_ui_widget_strings_th.xtb" /> + <file lang="tr" path="translations/android_ui_widget_strings_tr.xtb" /> + <file lang="uk" path="translations/android_ui_widget_strings_uk.xtb" /> + <file lang="vi" path="translations/android_ui_widget_strings_vi.xtb" /> + <file lang="zh-CN" path="translations/android_ui_widget_strings_zh-CN.xtb" /> + <file lang="zh-TW" path="translations/android_ui_widget_strings_zh-TW.xtb" /> + </translations> + <release allow_pseudo="false" seq="1"> + <messages fallback_to_english="true"> + <message name="IDS_ACCESSIBILITY_LIST_MENU_BUTTON" desc="Content description for the button that shows option menu for a list item."> + <ph name="NAME_OF_LIST_ITEM">%1$s<ex>Movie Title</ex></ph> Options + </message> + </messages> + </release> +</grit> diff --git a/chromium/chrome/browser/ui/libgtkui/BUILD.gn b/chromium/chrome/browser/ui/libgtkui/BUILD.gn index ced5ef6d9e7..7895f25952d 100644 --- a/chromium/chrome/browser/ui/libgtkui/BUILD.gn +++ b/chromium/chrome/browser/ui/libgtkui/BUILD.gn @@ -17,8 +17,6 @@ jumbo_component("libgtkui") { "app_indicator_icon_menu.h", "gtk_background_painter.cc", "gtk_background_painter.h", - "gtk_event_loop.cc", - "gtk_event_loop.h", "gtk_key_bindings_handler.cc", "gtk_key_bindings_handler.h", "gtk_ui.cc", @@ -48,8 +46,6 @@ jumbo_component("libgtkui") { "skia_utils_gtk.h", "unity_service.cc", "unity_service.h", - "x11_input_method_context_impl_gtk.cc", - "x11_input_method_context_impl_gtk.h", ] if (gtk_version <= 3) { @@ -112,10 +108,8 @@ jumbo_component("libgtkui") { "//ui/events:dom_keyboard_layout", "//ui/events:dom_keycode_converter", "//ui/events:events_base", - "//ui/events/platform/x11", "//ui/gfx", "//ui/gfx/geometry", - "//ui/gfx/x", "//ui/native_theme", "//ui/resources", "//ui/shell_dialogs", @@ -125,4 +119,18 @@ jumbo_component("libgtkui") { public_deps = [ "//chrome/browser:theme_properties", ] + + if (use_x11) { + sources += [ + "gtk_event_loop_x11.cc", + "gtk_event_loop_x11.h", + "x11_input_method_context_impl_gtk.cc", + "x11_input_method_context_impl_gtk.h", + ] + + deps += [ + "//ui/events/platform/x11", + "//ui/gfx/x", + ] + } } diff --git a/chromium/chrome/browser/ui/views/BUILD.gn b/chromium/chrome/browser/ui/views/BUILD.gn index 6862437bcc8..0241896ec54 100644 --- a/chromium/chrome/browser/ui/views/BUILD.gn +++ b/chromium/chrome/browser/ui/views/BUILD.gn @@ -27,6 +27,7 @@ component("views") { "//base", "//build:branding_buildflags", "//chrome/app:command_ids", + "//chrome/app:generated_resources", "//components/keep_alive_registry", "//components/vector_icons", "//content/public/browser", diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc index d4cff184227..8637fe302a0 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.cc +++ b/chromium/chrome/browser/ui/webui/about_ui.cc @@ -203,27 +203,35 @@ class ChromeOSTermsHandler DCHECK_CURRENTLY_ON(BrowserThread::UI); if (path_ == chrome::kOemEulaURLPath) { // Load local OEM EULA from the disk. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadOemEulaFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } else if (path_ == chrome::kArcTermsURLPath) { // Load ARC++ terms from the file. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadArcTermsFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } else if (path_ == chrome::kArcPrivacyPolicyURLPath) { // Load ARC++ privacy policy from the file. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadArcPrivacyPolicyFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } else { // Load local ChromeOS terms from the file. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ChromeOSTermsHandler::LoadEulaFileAsync, this), base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this)); } @@ -383,8 +391,9 @@ class ChromeOSCreditsHandler return; } // Load local Chrome OS credits from the disk. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&ChromeOSCreditsHandler::LoadCreditsFileAsync, this), base::Bind(&ChromeOSCreditsHandler::ResponseOnUIThread, this)); } @@ -450,8 +459,9 @@ class LinuxCreditsHandler return; } // Load local Linux credits from the disk. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&LinuxCreditsHandler::LoadLinuxCreditsFileAsync, this), base::Bind(&LinuxCreditsHandler::ResponseOnUIThread, this)); } @@ -586,7 +596,7 @@ std::string AboutUIHTMLSource::GetSource() { void AboutUIHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { std::string response; // Add your data source here, in alphabetical order. diff --git a/chromium/chrome/browser/ui/webui/about_ui.h b/chromium/chrome/browser/ui/webui/about_ui.h index 6860148d33b..0f2ae712871 100644 --- a/chromium/chrome/browser/ui/webui/about_ui.h +++ b/chromium/chrome/browser/ui/webui/about_ui.h @@ -26,7 +26,7 @@ class AboutUIHTMLSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; bool ShouldAddContentSecurityPolicy() override; diff --git a/chromium/chrome/browser/ui/webui/about_ui_unittest.cc b/chromium/chrome/browser/ui/webui/about_ui_unittest.cc index 301e1940431..66904b301b3 100644 --- a/chromium/chrome/browser/ui/webui/about_ui_unittest.cc +++ b/chromium/chrome/browser/ui/webui/about_ui_unittest.cc @@ -29,8 +29,7 @@ #include "chromeos/system/fake_statistics_provider.h" #include "chromeos/system/statistics_provider.h" #include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -123,12 +122,12 @@ class ChromeOSTermsTest : public testing::Test { // Starts data request with the |request_url|. void StartRequest(const std::string& request_url, TestDataReceiver* data_receiver) { - content::ResourceRequestInfo::WebContentsGetter wc_getter; + content::WebContents::Getter wc_getter; tested_html_source_->StartDataRequest( request_url, std::move(wc_getter), base::BindRepeating(&TestDataReceiver::OnDataReceived, base::Unretained(data_receiver))); - test_browser_thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); } const base::FilePath& PreinstalledOfflineResourcesPath() { @@ -139,7 +138,7 @@ class ChromeOSTermsTest : public testing::Test { base::ScopedTempDir preinstalled_offline_resources_dir_; base::FilePath arc_tos_dir_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; chromeos::system::ScopedFakeStatisticsProvider statistics_provider_; diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc new file mode 100644 index 00000000000..9fd69a5ea1e --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.cc @@ -0,0 +1,85 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/values.h" +#include "chrome/browser/android/dev_ui/dev_ui_module_provider.h" + +DevUiLoaderMessageHandler::DevUiLoaderMessageHandler() = default; + +DevUiLoaderMessageHandler::~DevUiLoaderMessageHandler() = default; + +void DevUiLoaderMessageHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "getDevUiDfmState", + base::BindRepeating(&DevUiLoaderMessageHandler::HandleGetDevUiDfmState, + weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "installAndLoadDevUiDfm", + base::BindRepeating( + &DevUiLoaderMessageHandler::HandleInstallAndLoadDevUiDfm, + weak_ptr_factory_.GetWeakPtr())); +} + +void DevUiLoaderMessageHandler::HandleGetDevUiDfmState( + const base::ListValue* args) { + const base::Value* callback_id = nullptr; + CHECK(args->Get(0, &callback_id)); + const char* response = "ready"; + if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleInstalled()) + response = "not-installed"; + else if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleLoaded()) + response = "not-loaded"; + AllowJavascript(); + ResolveJavascriptCallback(*callback_id, base::Value(response)); +} + +void DevUiLoaderMessageHandler::ReplyToJavaScript( + const base::Value& callback_id, + const char* return_value) { + AllowJavascript(); + base::ListValue response; + response.GetList().emplace_back(base::Value(return_value)); + ResolveJavascriptCallback(callback_id, response); +} + +void DevUiLoaderMessageHandler::HandleInstallAndLoadDevUiDfm( + const base::ListValue* args) { + const base::Value* callback_id = nullptr; + CHECK(args->Get(0, &callback_id)); + + if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleInstalled()) { + dev_ui::DevUiModuleProvider::GetInstance().InstallModule(base::BindOnce( + &DevUiLoaderMessageHandler::OnDevUiDfmInstallWithStatus, + weak_ptr_factory_.GetWeakPtr(), callback_id->GetString())); + + } else if (!dev_ui::DevUiModuleProvider::GetInstance().ModuleLoaded()) { + dev_ui::DevUiModuleProvider::GetInstance().LoadModule(base::BindOnce( + &DevUiLoaderMessageHandler::OnDevUiResourceLoaded, + weak_ptr_factory_.GetWeakPtr(), callback_id->GetString())); + + } else { + ReplyToJavaScript(*callback_id, "noop"); + } +} + +void DevUiLoaderMessageHandler::OnDevUiDfmInstallWithStatus( + std::string callback_id_string, + bool success) { + if (success) { + dev_ui::DevUiModuleProvider::GetInstance().LoadModule( + base::BindOnce(&DevUiLoaderMessageHandler::OnDevUiResourceLoaded, + weak_ptr_factory_.GetWeakPtr(), callback_id_string)); + } else { + ReplyToJavaScript(base::Value(callback_id_string), "failure"); + } +} + +void DevUiLoaderMessageHandler::OnDevUiResourceLoaded( + std::string callback_id_string) { + ReplyToJavaScript(base::Value(callback_id_string), "success"); +} diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h new file mode 100644 index 00000000000..04921022d9a --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h @@ -0,0 +1,65 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_MESSAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_MESSAGE_HANDLER_H_ + +#include <string> + +#include "base/memory/weak_ptr.h" +#include "build/build_config.h" +#include "chrome/android/features/dev_ui/buildflags.h" +#include "content/public/browser/web_ui_message_handler.h" + +#if !defined(OS_ANDROID) || !BUILDFLAG(DFMIFY_DEV_UI) +#error Unsupported platform. +#endif + +namespace base { +class ListValue; +class Value; +} // namespace base + +class DevUiLoaderMessageHandler : public content::WebUIMessageHandler { + public: + DevUiLoaderMessageHandler(); + ~DevUiLoaderMessageHandler() override; + + private: + DevUiLoaderMessageHandler(const DevUiLoaderMessageHandler&) = delete; + void operator=(const DevUiLoaderMessageHandler&) = delete; + + // WebUIMessageHandler + void RegisterMessages() override; + + // Called from JavaScript. |args| specifies id for callback, which receives + // one of the following responses: + // * "not-installed" if the DevUI DFM is not installed. + // * "not-loaded" if the DevUI DFM is installed, but not loaded. + // * "ready" if the DevUI DFM is installed and loaded. + void HandleGetDevUiDfmState(const base::ListValue* args); + + // Helper for HandleInstallAndLoadDevUiDfm(). + void ReplyToJavaScript(const base::Value& callback_id, + const char* return_value); + + // Called from JavaScript. |args| specifies id for callback, which receives + // one of the following responses: + // * "noop" if the DevUI DFM is already installed and loaded. + // * "success" if DevUI DFM install / load takes place, and succeeds. + // * "failure" if DevUI DFM install / load takes place, but fails. + void HandleInstallAndLoadDevUiDfm(const base::ListValue* args); + + // Callback for dev_ui::DevUiModuleProvider::InstallModule(). + void OnDevUiDfmInstallWithStatus(std::string callback_id_string, + bool success); + + // Callback for dev_ui::DevUiModuleProvider::LoadModule(). + void OnDevUiResourceLoaded(std::string callback_id_string); + + // Factory for creating references in callbacks. + base::WeakPtrFactory<DevUiLoaderMessageHandler> weak_ptr_factory_{this}; +}; + +#endif // CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_MESSAGE_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc new file mode 100644 index 00000000000..52622ee0b68 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.cc @@ -0,0 +1,30 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h" + +#include <memory> +#include <utility> + +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_message_handler.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_ui_data_source.h" +#include "url/gurl.h" + +DevUiLoaderUI::DevUiLoaderUI(content::WebUI* web_ui_in, const GURL& url) + : WebUIController(web_ui_in) { + std::unique_ptr<content::WebUIDataSource> html_source; + html_source.reset(content::WebUIDataSource::Create(url.host())); + html_source->SetDefaultResource(IDR_DEV_UI_LOADER_HTML); + html_source->AddResourcePath("dev_ui_loader.html", IDR_DEV_UI_LOADER_HTML); + html_source->AddResourcePath("dev_ui_loader.js", IDR_DEV_UI_LOADER_JS); + html_source->AddResourcePath("dev_ui_loader.css", IDR_DEV_UI_LOADER_CSS); + + Profile* profile = Profile::FromWebUI(web_ui()); + content::WebUIDataSource::Add(profile, html_source.release()); + web_ui()->AddMessageHandler(std::make_unique<DevUiLoaderMessageHandler>()); +} + +DevUiLoaderUI::~DevUiLoaderUI() = default; diff --git a/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h new file mode 100644 index 00000000000..d8b70e71615 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h @@ -0,0 +1,32 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_UI_H_ + +#include "base/memory/weak_ptr.h" +#include "build/build_config.h" +#include "chrome/android/features/dev_ui/buildflags.h" +#include "content/public/browser/web_ui_controller.h" + +#if !defined(OS_ANDROID) || !BUILDFLAG(DFMIFY_DEV_UI) +#error Unsupported platform. +#endif + +class GURL; + +class DevUiLoaderUI : public content::WebUIController { + public: + DevUiLoaderUI(content::WebUI* web_ui_in, const GURL& url); + ~DevUiLoaderUI() override; + + private: + DevUiLoaderUI(const DevUiLoaderUI&) = delete; + void operator=(const DevUiLoaderUI&) = delete; + + // Factory for creating references in callbacks. + base::WeakPtrFactory<DevUiLoaderUI> weak_ptr_factory_{this}; +}; + +#endif // CHROME_BROWSER_UI_WEBUI_ANDROID_DEV_UI_LOADER_DEV_UI_LOADER_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc index 4b44c8cfcf5..9dfbd2f390b 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc @@ -80,10 +80,10 @@ AppLauncherLoginHandler::AppLauncherLoginHandler() {} AppLauncherLoginHandler::~AppLauncherLoginHandler() {} void AppLauncherLoginHandler::RegisterMessages() { - profile_info_watcher_.reset(new ProfileInfoWatcher( + profile_info_watcher_ = std::make_unique<ProfileInfoWatcher>( Profile::FromWebUI(web_ui()), base::Bind(&AppLauncherLoginHandler::UpdateLogin, - base::Unretained(this)))); + base::Unretained(this))); web_ui()->RegisterMessageCallback( "initializeSyncLogin", 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 7005dd6a16a..521d94e93d8 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc +++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc @@ -100,7 +100,7 @@ std::string AppLauncherPageUI::HTMLSource::GetSource() { void AppLauncherPageUI::HTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); diff --git a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h index 0b632d6adb4..b5ad2e116e8 100644 --- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h +++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h @@ -40,7 +40,7 @@ class AppLauncherPageUI : public content::WebUIController { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool ShouldReplaceExistingSource() override; diff --git a/chromium/chrome/browser/ui/webui/app_management/OWNERS b/chromium/chrome/browser/ui/webui/app_management/OWNERS index 4829e5de205..3b255369827 100644 --- a/chromium/chrome/browser/ui/webui/app_management/OWNERS +++ b/chromium/chrome/browser/ui/webui/app_management/OWNERS @@ -1,6 +1,5 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS -calamity@chromium.org dominickn@chromium.org -ericwilligers@chromium.org +jshikaram@chromium.org diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc index 8df423bb254..35c327bb3b8 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc @@ -22,10 +22,20 @@ #include "extensions/common/permissions/permission_message.h" #include "extensions/common/permissions/permissions_data.h" +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/arc/arc_util.h" +#include "components/arc/arc_prefs.h" +#endif + using apps::mojom::OptionalBool; namespace { +#if defined(OS_CHROMEOS) +constexpr char kArcFrameworkPackage[] = "android"; +constexpr int kMinAndroidFrameworkVersion = 28; // Android P +#endif + constexpr char const* kAppIdsWithHiddenMoreSettings[] = { extension_misc::kFilesManagerAppId, extensions::kWebStoreAppId, @@ -60,12 +70,13 @@ bool ShouldHidePinToShelf(const std::string app_id) { AppManagementPageHandler::AppManagementPageHandler( app_management::mojom::PageHandlerRequest request, app_management::mojom::PagePtr page, - content::WebUI* web_ui) + Profile* profile) : binding_(this, std::move(request)), page_(std::move(page)), - profile_(Profile::FromWebUI(web_ui)) + profile_(profile) #if defined(OS_CHROMEOS) , + arc_app_list_prefs_observer_(this), shelf_delegate_(this) #endif { @@ -78,6 +89,12 @@ AppManagementPageHandler::AppManagementPageHandler( return; Observe(&proxy->AppRegistryCache()); + +#if defined(OS_CHROMEOS) + if (arc::IsArcAllowedForProfile(profile_)) { + arc_app_list_prefs_observer_.Add(ArcAppListPrefs::Get(profile_)); + } +#endif // OS_CHROMEOS } AppManagementPageHandler::~AppManagementPageHandler() {} @@ -247,11 +264,36 @@ void AppManagementPageHandler::OnAppUpdate(const apps::AppUpdate& update) { } } -void AppManagementPageHandler::OnArcSupportChanged(bool supported) { - page_->OnArcSupportChanged(supported); -} - void AppManagementPageHandler::OnAppRegistryCacheWillBeDestroyed( apps::AppRegistryCache* cache) { Observe(nullptr); } + +#if defined(OS_CHROMEOS) +// static +bool AppManagementPageHandler::IsCurrentArcVersionSupported(Profile* profile) { + if (arc::IsArcAllowedForProfile(profile)) { + auto package = + ArcAppListPrefs::Get(profile)->GetPackage(kArcFrameworkPackage); + return package && (package->package_version >= kMinAndroidFrameworkVersion); + } + return false; +} + +void AppManagementPageHandler::OnArcVersionChanged(int androidVersion) { + page_->OnArcSupportChanged(androidVersion >= kMinAndroidFrameworkVersion); +} + +void AppManagementPageHandler::OnPackageInstalled( + const arc::mojom::ArcPackageInfo& package_info) { + OnPackageModified(package_info); +} + +void AppManagementPageHandler::OnPackageModified( + const arc::mojom::ArcPackageInfo& package_info) { + if (package_info.package_name != kArcFrameworkPackage) { + return; + } + OnArcVersionChanged(package_info.package_version); +} +#endif // OS_CHROMEOS diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h index 25f0a826171..baeef297ebd 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h @@ -6,27 +6,39 @@ #define CHROME_BROWSER_UI_WEBUI_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_H_ #include "base/macros.h" +#include "base/scoped_observer.h" #include "chrome/browser/ui/webui/app_management/app_management.mojom.h" #include "chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h" #include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "mojo/public/cpp/bindings/binding.h" -namespace content { -class WebUI; -} +#if defined(OS_CHROMEOS) +#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" +#endif class Profile; class AppManagementPageHandler : public app_management::mojom::PageHandler, - public apps::AppRegistryCache::Observer { + public apps::AppRegistryCache::Observer +#if defined(OS_CHROMEOS) + , + public ArcAppListPrefs::Observer +#endif // OS_CHROMEOS +{ public: AppManagementPageHandler(app_management::mojom::PageHandlerRequest request, app_management::mojom::PagePtr page, - content::WebUI* web_ui); + Profile* profile); ~AppManagementPageHandler() override; +#if defined(OS_CHROMEOS) + static bool IsCurrentArcVersionSupported(Profile* profile); +#endif // OS_CHROMEOS + void OnPinnedChanged(const std::string& app_id, bool pinned); - void OnArcSupportChanged(bool supported); +#if defined(OS_CHROMEOS) + void OnArcVersionChanged(int androidVersion); +#endif // OS_CHROMEOS // app_management::mojom::PageHandler: void GetApps(GetAppsCallback callback) override; @@ -48,6 +60,14 @@ class AppManagementPageHandler : public app_management::mojom::PageHandler, void OnAppRegistryCacheWillBeDestroyed( apps::AppRegistryCache* cache) override; +#if defined(OS_CHROMEOS) + // ArcAppListPrefs::Observer: + void OnPackageInstalled( + const arc::mojom::ArcPackageInfo& package_info) override; + void OnPackageModified( + const arc::mojom::ArcPackageInfo& package_info) override; +#endif // OS_CHROMEOS + mojo::Binding<app_management::mojom::PageHandler> binding_; app_management::mojom::PagePtr page_; @@ -55,8 +75,10 @@ class AppManagementPageHandler : public app_management::mojom::PageHandler, Profile* profile_; #if defined(OS_CHROMEOS) + ScopedObserver<ArcAppListPrefs, AppManagementPageHandler> + arc_app_list_prefs_observer_; AppManagementShelfDelegate shelf_delegate_; -#endif +#endif // OS_CHROMEOS DISALLOW_COPY_AND_ASSIGN(AppManagementPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc index d59a0bd6351..5d3ce3e4657 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc @@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/feature_list.h" -#include "chrome/browser/apps/app_service/app_icon_source.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/app_management/app_management_page_handler.h" #include "chrome/browser/ui/webui/localized_string.h" @@ -20,24 +19,12 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" -#include "content/public/browser/url_data_source.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "ui/base/resource/resource_bundle.h" -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/arc/arc_util.h" -#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" -#include "components/arc/arc_prefs.h" -#endif - namespace { -#if defined(OS_CHROMEOS) -constexpr char kArcFrameworkPackage[] = "android"; -constexpr int kMinAndroidFrameworkVersion = 28; // Android P -#endif - content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIAppManagementHost); @@ -68,14 +55,15 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { {"storage", IDS_APP_MANAGEMENT_STORAGE}, {"thisAppCan", IDS_APP_MANAGEMENT_THIS_APP_CAN}, {"title", IDS_APP_MANAGEMENT_TITLE}, - {"uninstall", IDS_APP_MANAGEMENT_UNINSTALL}, + {"uninstall", IDS_APP_MANAGEMENT_UNINSTALL_APP}, {"version", IDS_APP_MANAGEMENT_VERSION}, }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); #if defined(OS_CHROMEOS) - source->AddBoolean("isSupportedArcVersion", - AppManagementUI::IsCurrentArcVersionSupported(profile)); + source->AddBoolean( + "isSupportedArcVersion", + AppManagementPageHandler::IsCurrentArcVersionSupported(profile)); #endif // OS_CHROMEOS source->AddResourcePath("app_management.mojom-lite.js", @@ -89,96 +77,15 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) { source->AddResourcePath("image_info.mojom-lite.js", IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); - source->AddResourcePath("actions.html", IDR_APP_MANAGEMENT_ACTIONS_HTML); - source->AddResourcePath("actions.js", IDR_APP_MANAGEMENT_ACTIONS_JS); - source->AddResourcePath("api_listener.html", - IDR_APP_MANAGEMENT_API_LISTENER_HTML); - source->AddResourcePath("api_listener.js", - IDR_APP_MANAGEMENT_API_LISTENER_JS); - source->AddResourcePath("app_item.html", IDR_APP_MANAGEMENT_APP_ITEM_HTML); - source->AddResourcePath("app_item.js", IDR_APP_MANAGEMENT_APP_ITEM_JS); source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML); source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS); - source->AddResourcePath("arc_permission_view.html", - IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_HTML); - source->AddResourcePath("arc_permission_view.js", - IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_JS); - source->AddResourcePath("browser_proxy.html", - IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML); - source->AddResourcePath("browser_proxy.js", - IDR_APP_MANAGEMENT_BROWSER_PROXY_JS); - source->AddResourcePath("chrome_app_permission_view.html", - IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_HTML); - source->AddResourcePath("chrome_app_permission_view.js", - IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS); - source->AddResourcePath("constants.html", IDR_APP_MANAGEMENT_CONSTANTS_HTML); - source->AddResourcePath("constants.js", IDR_APP_MANAGEMENT_CONSTANTS_JS); - source->AddResourcePath("dom_switch.html", - IDR_APP_MANAGEMENT_DOM_SWITCH_HTML); - source->AddResourcePath("dom_switch.js", IDR_APP_MANAGEMENT_DOM_SWITCH_JS); source->AddResourcePath("expandable_app_list.html", IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_HTML); source->AddResourcePath("expandable_app_list.js", IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_JS); - source->AddResourcePath("fake_page_handler.js", - IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS); - source->AddResourcePath("icons.html", IDR_APP_MANAGEMENT_ICONS_HTML); - source->AddResourcePath("main_view.html", IDR_APP_MANAGEMENT_MAIN_VIEW_HTML); - source->AddResourcePath("main_view.js", IDR_APP_MANAGEMENT_MAIN_VIEW_JS); - source->AddResourcePath("metadata_view.html", - IDR_APP_MANAGEMENT_METADATA_VIEW_HTML); - source->AddResourcePath("metadata_view.js", - IDR_APP_MANAGEMENT_METADATA_VIEW_JS); - source->AddResourcePath("notifications_view.html", - IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_HTML); - source->AddResourcePath("notifications_view.js", - IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_JS); - source->AddResourcePath("permission_item.html", - IDR_APP_MANAGEMENT_PERMISSION_ITEM_HTML); - source->AddResourcePath("permission_item.js", - IDR_APP_MANAGEMENT_PERMISSION_ITEM_JS); - source->AddResourcePath("permission_toggle.html", - IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_HTML); - source->AddResourcePath("permission_toggle.js", - IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_JS); - source->AddResourcePath("permission_view_header.html", - IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML); - source->AddResourcePath("permission_view_header.js", - IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS); - source->AddResourcePath("pin_to_shelf_item.html", - IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML); - source->AddResourcePath("pin_to_shelf_item.js", - IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS); - source->AddResourcePath("pwa_permission_view.html", - IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML); - source->AddResourcePath("pwa_permission_view.js", - IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_JS); - source->AddResourcePath("reducers.html", IDR_APP_MANAGEMENT_REDUCERS_HTML); - source->AddResourcePath("reducers.js", IDR_APP_MANAGEMENT_REDUCERS_JS); - source->AddResourcePath("router.html", IDR_APP_MANAGEMENT_ROUTER_HTML); - source->AddResourcePath("router.js", IDR_APP_MANAGEMENT_ROUTER_JS); - source->AddResourcePath("search_view.html", - IDR_APP_MANAGEMENT_SEARCH_VIEW_HTML); - source->AddResourcePath("search_view.js", IDR_APP_MANAGEMENT_SEARCH_VIEW_JS); - source->AddResourcePath("shared_style.html", - IDR_APP_MANAGEMENT_SHARED_STYLE_HTML); - source->AddResourcePath("shared_vars.html", - IDR_APP_MANAGEMENT_SHARED_VARS_HTML); - source->AddResourcePath("store_client.html", - IDR_APP_MANAGEMENT_STORE_CLIENT_HTML); - source->AddResourcePath("store_client.js", - IDR_APP_MANAGEMENT_STORE_CLIENT_JS); - source->AddResourcePath("store.html", IDR_APP_MANAGEMENT_STORE_HTML); - source->AddResourcePath("store.js", IDR_APP_MANAGEMENT_STORE_JS); - source->AddResourcePath("toggle_row.html", - IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML); - source->AddResourcePath("toggle_row.js", IDR_APP_MANAGEMENT_TOGGLE_ROW_JS); - source->AddResourcePath("types.js", IDR_APP_MANAGEMENT_TYPES_JS); - source->AddResourcePath("util.html", IDR_APP_MANAGEMENT_UTIL_HTML); - source->AddResourcePath("util.js", IDR_APP_MANAGEMENT_UTIL_JS); source->SetDefaultResource(IDR_APP_MANAGEMENT_INDEX_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } @@ -202,22 +109,10 @@ AppManagementUI::AppManagementUI(content::WebUI* web_ui) AddHandlerToRegistry(base::BindRepeating( &AppManagementUI::BindPageHandlerFactory, base::Unretained(this))); - // Make the chrome://app-icon/ resource available. - if (profile) { - content::URLDataSource::Add(profile, - std::make_unique<apps::AppIconSource>(profile)); - } - auto plural_string_handler = std::make_unique<PluralStringHandler>(); plural_string_handler->AddLocalizedString( "appListPreview", IDS_APP_MANAGEMENT_APP_LIST_PREVIEW); web_ui->AddMessageHandler(std::move(plural_string_handler)); - -#if defined(OS_CHROMEOS) - if (arc::IsArcAllowedForProfile(profile)) { - ArcAppListPrefs::Get(profile)->AddObserver(this); - } -#endif } AppManagementUI::~AppManagementUI() = default; @@ -241,40 +136,5 @@ void AppManagementUI::CreatePageHandler( DCHECK(page); page_handler_ = std::make_unique<AppManagementPageHandler>( - std::move(request), std::move(page), web_ui()); + std::move(request), std::move(page), Profile::FromWebUI(web_ui())); } - -#if defined(OS_CHROMEOS) -bool AppManagementUI::IsCurrentArcVersionSupported(Profile* profile) { - if (arc::IsArcAllowedForProfile(profile)) { - auto package = - ArcAppListPrefs::Get(profile)->GetPackage(kArcFrameworkPackage); - return package && (package->package_version >= kMinAndroidFrameworkVersion); - } - return false; -} - -void AppManagementUI::NotifyAndroidVersionChange(int androidVersion) { - if (!page_handler_) { - return; - } - const bool supported = androidVersion >= kMinAndroidFrameworkVersion; - page_handler_->OnArcSupportChanged(supported); -} - -void AppManagementUI::OnPackageInstalled( - const arc::mojom::ArcPackageInfo& package_info) { - if (package_info.package_name != kArcFrameworkPackage) { - return; - } - NotifyAndroidVersionChange(package_info.package_version); -} - -void AppManagementUI::OnPackageModified( - const arc::mojom::ArcPackageInfo& package_info) { - if (package_info.package_name != kArcFrameworkPackage) { - return; - } - NotifyAndroidVersionChange(package_info.package_version); -} -#endif // OS_CHROMEOS diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h index 56caea216f0..a0187ee104e 100644 --- a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h +++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h @@ -12,31 +12,17 @@ #include "mojo/public/cpp/bindings/binding.h" #include "ui/webui/mojo_web_ui_controller.h" -#if defined(OS_CHROMEOS) -#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" -#endif - class AppManagementPageHandler; -class Profile; class AppManagementUI : public ui::MojoWebUIController, - public app_management::mojom::PageHandlerFactory -#if defined(OS_CHROMEOS) - , - public ArcAppListPrefs::Observer -#endif // OS_CHROMEOS -{ + public app_management::mojom::PageHandlerFactory { public: explicit AppManagementUI(content::WebUI* web_ui); ~AppManagementUI() override; static bool IsEnabled(); -#if defined(OS_CHROMEOS) - static bool IsCurrentArcVersionSupported(Profile* profile); -#endif // OS_CHROMEOS private: - void NotifyAndroidVersionChange(int androidVersion); void BindPageHandlerFactory( app_management::mojom::PageHandlerFactoryRequest request); @@ -49,14 +35,6 @@ class AppManagementUI : public ui::MojoWebUIController, mojo::Binding<app_management::mojom::PageHandlerFactory> page_factory_binding_; -#if defined(OS_CHROMEOS) - // ArcAppListPrefs::Observer: - void OnPackageInstalled( - const arc::mojom::ArcPackageInfo& package_info) override; - void OnPackageModified( - const arc::mojom::ArcPackageInfo& package_info) override; -#endif - DISALLOW_COPY_AND_ASSIGN(AppManagementUI); }; diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/OWNERS b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/OWNERS index 034df867c1c..85ef92a8da9 100644 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/OWNERS +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/OWNERS @@ -1,3 +1,4 @@ +battre@chromium.org dvadym@chromium.org # COMPONENT: UI>Browser>Passwords diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.cc new file mode 100644 index 00000000000..a6231ff0fc2 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.cc @@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h" + +#include "base/bind.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h" +#include "chrome/common/url_constants.h" +#include "components/autofill/content/browser/autofill_log_router_factory.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +AutofillInternalsUI::AutofillInternalsUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource::Add(profile, + autofill::CreateInternalsHTMLSource( + chrome::kChromeUIAutofillInternalsHost)); + web_ui->AddMessageHandler(std::make_unique<autofill::InternalsUIHandler>( + "setUpAutofillInternals", + base::BindRepeating( + &autofill::AutofillLogRouterFactory::GetForBrowserContext))); +} + +AutofillInternalsUI::~AutofillInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/autofill_internals_ui.h b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h index 3a22afcb067..c38a6d9b7da 100644 --- a/chromium/chrome/browser/ui/webui/autofill_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_AUTOFILL_INTERNALS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_INTERNALS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_AUTOFILL_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_AUTOFILL_INTERNALS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui.h" @@ -18,4 +18,4 @@ class AutofillInternalsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(AutofillInternalsUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_INTERNALS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_AUTOFILL_INTERNALS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.cc new file mode 100644 index 00000000000..1c242488832 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.cc @@ -0,0 +1,108 @@ +// 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/autofill_and_password_manager_internals/internals_ui_handler.h" + +#include "base/values.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_content_browser_client.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/channel_info.h" +#include "components/autofill/core/browser/logging/log_router.h" +#include "components/grit/components_resources.h" +#include "components/version_info/version_info.h" +#include "components/version_ui/version_handler_helper.h" +#include "components/version_ui/version_ui_constants.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +using autofill::LogRouter; + +namespace autofill { + +content::WebUIDataSource* CreateInternalsHTMLSource( + const std::string& source_name) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(source_name); + source->AddResourcePath("autofill_and_password_manager_internals.js", + IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_JS); + source->AddResourcePath("autofill_and_password_manager_internals.css", + IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_CSS); + source->SetDefaultResource(IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_HTML); + // Data strings: + source->AddString(version_ui::kVersion, version_info::GetVersionNumber()); + source->AddString(version_ui::kOfficial, version_info::IsOfficialBuild() + ? "official" + : "Developer build"); + source->AddString(version_ui::kVersionModifier, chrome::GetChannelName()); + source->AddString(version_ui::kCL, version_info::GetLastChange()); + source->AddString(version_ui::kUserAgent, GetUserAgent()); + source->AddString("app_locale", g_browser_process->GetApplicationLocale()); + return source; +} + +InternalsUIHandler::InternalsUIHandler( + std::string call_on_load, + GetLogRouterFunction get_log_router_function) + : call_on_load_(std::move(call_on_load)), + get_log_router_function_(std::move(get_log_router_function)) {} + +InternalsUIHandler::~InternalsUIHandler() { + EndSubscription(); +} + +void InternalsUIHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "loaded", base::BindRepeating(&InternalsUIHandler::OnLoaded, + base::Unretained(this))); +} + +void InternalsUIHandler::OnJavascriptAllowed() { + StartSubscription(); +} + +void InternalsUIHandler::OnJavascriptDisallowed() { + EndSubscription(); +} + +void InternalsUIHandler::OnLoaded(const base::ListValue* args) { + AllowJavascript(); + CallJavascriptFunction(call_on_load_); + CallJavascriptFunction( + "notifyAboutIncognito", + base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile())); + CallJavascriptFunction("notifyAboutVariations", + *version_ui::GetVariationsList()); +} + +void InternalsUIHandler::StartSubscription() { + LogRouter* log_router = + get_log_router_function_.Run(Profile::FromWebUI(web_ui())); + if (!log_router) + return; + + registered_with_log_router_ = true; + + const auto& past_logs = log_router->RegisterReceiver(this); + for (const auto& entry : past_logs) + LogEntry(entry); +} + +void InternalsUIHandler::EndSubscription() { + if (!registered_with_log_router_) + return; + registered_with_log_router_ = false; + LogRouter* log_router = + get_log_router_function_.Run(Profile::FromWebUI(web_ui())); + if (log_router) + log_router->UnregisterReceiver(this); +} + +void InternalsUIHandler::LogEntry(const base::Value& entry) { + if (!registered_with_log_router_ || entry.is_none()) + return; + CallJavascriptFunction("addRawLog", entry); +} + +} // namespace autofill diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h new file mode 100644 index 00000000000..8a6594fd352 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h @@ -0,0 +1,70 @@ +// 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_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_INTERNALS_UI_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_INTERNALS_UI_HANDLER_H_ + +#include <string> + +#include "base/bind.h" +#include "base/macros.h" +#include "components/autofill/core/browser/logging/log_receiver.h" +#include "content/public/browser/web_ui_message_handler.h" + +namespace autofill { +class LogRouter; +} + +namespace content { +class BrowserContext; +class WebUIDataSource; +} // namespace content + +namespace autofill { +content::WebUIDataSource* CreateInternalsHTMLSource( + const std::string& source_name); + +// UI handler for chrome://password-manager-internals and +// chrome://autofill-internals that takes care of subscribing to the autofill +// logging instance. +class InternalsUIHandler : public content::WebUIMessageHandler, + public autofill::LogReceiver { + public: + using GetLogRouterFunction = + base::RepeatingCallback<autofill::LogRouter*(content::BrowserContext*)>; + + InternalsUIHandler(std::string call_on_load, + GetLogRouterFunction get_log_router_function); + ~InternalsUIHandler() override; + + private: + // content::WebUIMessageHandler: + void RegisterMessages() override; + + // Implements content::WebUIMessageHandler. + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + // LogReceiver implementation. + void LogEntry(const base::Value& entry) override; + + void StartSubscription(); + void EndSubscription(); + + // JavaScript call handler. + void OnLoaded(const base::ListValue* args); + + // JavaScript function to be called on load. + std::string call_on_load_; + GetLogRouterFunction get_log_router_function_; + + // Whether |this| is registered as a log receiver with the LogRouter. + bool registered_with_log_router_ = false; + + DISALLOW_COPY_AND_ASSIGN(InternalsUIHandler); +}; + +} // namespace autofill + +#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_INTERNALS_UI_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc new file mode 100644 index 00000000000..a43a8d42ef4 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.cc @@ -0,0 +1,27 @@ +// 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/autofill_and_password_manager_internals/password_manager_internals_ui.h" + +#include "base/bind.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/internals_ui_handler.h" +#include "chrome/common/url_constants.h" +#include "components/password_manager/content/browser/password_manager_log_router_factory.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +PasswordManagerInternalsUI::PasswordManagerInternalsUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource::Add( + profile, autofill::CreateInternalsHTMLSource( + chrome::kChromeUIPasswordManagerInternalsHost)); + web_ui->AddMessageHandler(std::make_unique<autofill::InternalsUIHandler>( + "setUpPasswordManagerInternals", + base::BindRepeating(&password_manager::PasswordManagerLogRouterFactory:: + GetForBrowserContext))); +} + +PasswordManagerInternalsUI::~PasswordManagerInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h index 586ce8e2940..19d8ed9f3f2 100644 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ #include "base/macros.h" #include "content/public/browser/web_ui.h" @@ -18,4 +18,4 @@ class PasswordManagerInternalsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(PasswordManagerInternalsUI); }; -#endif // CHROME_BROWSER_UI_WEBUI_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ +#endif // CHROME_BROWSER_UI_WEBUI_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui_browsertest.cc index 5d84d3044ff..0a50d409f8c 100644 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui_browsertest.cc @@ -5,7 +5,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/base/web_ui_browser_test.h" @@ -31,15 +31,14 @@ class PasswordManagerInternalsWebUIBrowserTest : public WebUIBrowserTest { WindowOpenDisposition disposition); private: - PasswordManagerInternalsUI* controller_; + PasswordManagerInternalsUI* controller_ = nullptr; }; PasswordManagerInternalsWebUIBrowserTest:: - PasswordManagerInternalsWebUIBrowserTest() - : controller_(NULL) {} + PasswordManagerInternalsWebUIBrowserTest() = default; PasswordManagerInternalsWebUIBrowserTest:: - ~PasswordManagerInternalsWebUIBrowserTest() {} + ~PasswordManagerInternalsWebUIBrowserTest() = default; void PasswordManagerInternalsWebUIBrowserTest::SetUpOnMainThread() { WebUIBrowserTest::SetUpOnMainThread(); @@ -64,9 +63,7 @@ void PasswordManagerInternalsWebUIBrowserTest::OpenInternalsPageWithBrowser( std::string url_string("chrome://"); url_string += chrome::kChromeUIPasswordManagerInternalsHost; ui_test_utils::NavigateToURLWithDisposition( - browser, - GURL(url_string), - disposition, + browser, GURL(url_string), disposition, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); controller_ = static_cast<PasswordManagerInternalsUI*>( GetWebContents()->GetWebUI()->GetController()); diff --git a/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc deleted file mode 100644 index 489a5d65bd6..00000000000 --- a/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/autofill_internals_ui.h" - -#include <string> - -#include "base/bind.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "components/autofill/content/browser/autofill_log_router_factory.h" -#include "components/autofill/core/browser/logging/log_receiver.h" -#include "components/autofill/core/browser/logging/log_router.h" -#include "components/grit/components_resources.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/browser/web_ui_message_handler.h" - -using autofill::AutofillLogRouterFactory; -using autofill::LogRouter; - -namespace { - -content::WebUIDataSource* CreateAutofillInternalsHTMLSource() { - content::WebUIDataSource* source = - content::WebUIDataSource::Create(chrome::kChromeUIAutofillInternalsHost); - source->AddResourcePath("autofill_and_password_manager_internals.js", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_JS); - source->AddResourcePath("autofill_and_password_manager_internals.css", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_CSS); - source->SetDefaultResource(IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_HTML); - return source; -} - -// Message handler for AutofillInternalsLoggingImpl. The purpose of this class -// is to enable safe calls to JavaScript, while the renderer is fully loaded. -class AutofillInternalsUIHandler : public content::WebUIMessageHandler, - public autofill::LogReceiver { - public: - AutofillInternalsUIHandler() = default; - ~AutofillInternalsUIHandler() override; - - private: - // content::WebUIMessageHandler: - void RegisterMessages() override; - - // Implements content::WebUIMessageHandler. - void OnJavascriptAllowed() override; - void OnJavascriptDisallowed() override; - - // LogReceiver implementation. - void LogEntry(const base::Value& entry) override; - - void StartSubscription(); - void EndSubscription(); - - // JavaScript call handler. - void OnLoaded(const base::ListValue* args); - - // Whether |this| is registered as a log receiver with the LogRouter. - bool registered_with_log_router_ = false; - - DISALLOW_COPY_AND_ASSIGN(AutofillInternalsUIHandler); -}; - -AutofillInternalsUIHandler::~AutofillInternalsUIHandler() { - EndSubscription(); -} - -void AutofillInternalsUIHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "loaded", base::BindRepeating(&AutofillInternalsUIHandler::OnLoaded, - base::Unretained(this))); -} - -void AutofillInternalsUIHandler::OnJavascriptAllowed() { - StartSubscription(); -} - -void AutofillInternalsUIHandler::OnJavascriptDisallowed() { - EndSubscription(); -} - -void AutofillInternalsUIHandler::OnLoaded(const base::ListValue* args) { - AllowJavascript(); - CallJavascriptFunction("setUpAutofillInternals"); - CallJavascriptFunction( - "notifyAboutIncognito", - base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile())); -} - -void AutofillInternalsUIHandler::LogEntry(const base::Value& entry) { - if (!registered_with_log_router_ || entry.is_none()) - return; - CallJavascriptFunction("addRawLog", entry); -} - -void AutofillInternalsUIHandler::StartSubscription() { - LogRouter* log_router = AutofillLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - - if (!log_router) - return; - - registered_with_log_router_ = true; - - const auto& past_logs = log_router->RegisterReceiver(this); - for (const auto& entry : past_logs) - LogEntry(entry); -} - -void AutofillInternalsUIHandler::EndSubscription() { - if (!registered_with_log_router_) - return; - registered_with_log_router_ = false; - LogRouter* log_router = AutofillLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - if (log_router) - log_router->UnregisterReceiver(this); -} - -} // namespace - -AutofillInternalsUI::AutofillInternalsUI(content::WebUI* web_ui) - : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - content::WebUIDataSource::Add(profile, CreateAutofillInternalsHTMLSource()); - web_ui->AddMessageHandler(std::make_unique<AutofillInternalsUIHandler>()); -} - -AutofillInternalsUI::~AutofillInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn index c50c38a1ffc..0f0f0aaad80 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn @@ -18,6 +18,7 @@ source_set("bluetooth_internals") { deps = [ ":mojo_bindings", + "//chrome/browser/resources/bluetooth_internals:resources", "//chrome/common", "//content/public/browser", "//device/bluetooth", @@ -33,7 +34,4 @@ mojom("mojo_bindings") { deps = [ "//device/bluetooth/public/mojom:deprecated_experimental_interfaces", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc index 513a4d8208a..d51387baaee 100644 --- a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.cc @@ -8,7 +8,8 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h" #include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" +#include "chrome/grit/bluetooth_internals_resources.h" +#include "chrome/grit/bluetooth_internals_resources_map.h" #include "content/public/browser/web_ui_data_source.h" BluetoothInternalsUI::BluetoothInternalsUI(content::WebUI* web_ui) @@ -19,48 +20,17 @@ BluetoothInternalsUI::BluetoothInternalsUI(content::WebUI* web_ui) // Add required resources. html_source->AddResourcePath("adapter.mojom-lite.js", - IDR_BLUETOOTH_ADAPTER_MOJO_JS); - html_source->AddResourcePath("adapter_broker.js", - IDR_BLUETOOTH_INTERNALS_ADAPTER_BROKER_JS); - html_source->AddResourcePath("adapter_page.js", - IDR_BLUETOOTH_INTERNALS_ADAPTER_PAGE_JS); - html_source->AddResourcePath("bluetooth_internals.css", - IDR_BLUETOOTH_INTERNALS_CSS); - html_source->AddResourcePath("bluetooth_internals.js", - IDR_BLUETOOTH_INTERNALS_JS); + IDR_BLUETOOTH_INTERNALS_ADAPTER_MOJO_JS); + html_source->AddResourcePath("device.mojom-lite.js", + IDR_BLUETOOTH_INTERNALS_DEVICE_MOJO_JS); html_source->AddResourcePath("bluetooth_internals.mojom-lite.js", IDR_BLUETOOTH_INTERNALS_MOJO_JS); - html_source->AddResourcePath("characteristic_list.js", - IDR_BLUETOOTH_INTERNALS_CHARACTERISTIC_LIST_JS); - html_source->AddResourcePath("descriptor_list.js", - IDR_BLUETOOTH_INTERNALS_DESCRIPTOR_LIST_JS); - html_source->AddResourcePath("device.mojom-lite.js", - IDR_BLUETOOTH_DEVICE_MOJO_JS); - html_source->AddResourcePath("device_broker.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_BROKER_JS); - html_source->AddResourcePath("device_collection.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_COLLECTION_JS); - html_source->AddResourcePath("device_details_page.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_DETAILS_PAGE_JS); - html_source->AddResourcePath("device_table.js", - IDR_BLUETOOTH_INTERNALS_DEVICE_TABLE_JS); - html_source->AddResourcePath("devices_page.js", - IDR_BLUETOOTH_INTERNALS_DEVICES_PAGE_JS); - html_source->AddResourcePath("expandable_list.js", - IDR_BLUETOOTH_INTERNALS_EXPANDABLE_LIST_JS); - html_source->AddResourcePath("object_fieldset.js", - IDR_BLUETOOTH_INTERNALS_OBJECT_FIELDSET_JS); - html_source->AddResourcePath("service_list.js", - IDR_BLUETOOTH_INTERNALS_SERVICE_LIST_JS); - html_source->AddResourcePath("sidebar.js", - IDR_BLUETOOTH_INTERNALS_SIDEBAR_JS); - html_source->AddResourcePath("snackbar.js", - IDR_BLUETOOTH_INTERNALS_SNACKBAR_JS); html_source->AddResourcePath("uuid.mojom-lite.js", - IDR_BLUETOOTH_UUID_MOJO_JS); - html_source->AddResourcePath("value_control.js", - IDR_BLUETOOTH_INTERNALS_VALUE_CONTROL_JS); - + IDR_BLUETOOTH_INTERNALS_UUID_MOJO_JS); + for (size_t i = 0; i < kBluetoothInternalsResourcesSize; i++) { + html_source->AddResourcePath(kBluetoothInternalsResources[i].name, + kBluetoothInternalsResources[i].value); + } html_source->SetDefaultResource(IDR_BLUETOOTH_INTERNALS_HTML); Profile* profile = Profile::FromWebUI(web_ui); @@ -74,5 +44,6 @@ BluetoothInternalsUI::~BluetoothInternalsUI() {} void BluetoothInternalsUI::BindBluetoothInternalsHandler( mojom::BluetoothInternalsHandlerRequest request) { - page_handler_.reset(new BluetoothInternalsHandler(std::move(request))); + page_handler_ = + std::make_unique<BluetoothInternalsHandler>(std::move(request)); } diff --git a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc index 483ef599b63..2e4f5d89ed3 100644 --- a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc @@ -60,7 +60,7 @@ void BookmarksBrowserTest::SetupExtensionAPITest() { node->SetString("name", "Managed Bookmark"); node->SetString("url", "http://www.chromium.org"); list.Append(std::move(node)); - node.reset(new base::DictionaryValue()); + node = std::make_unique<base::DictionaryValue>(); node->SetString("name", "Managed Folder"); node->Set("children", std::make_unique<base::ListValue>()); list.Append(std::move(node)); diff --git a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc index dc7678bab36..094a943ac95 100644 --- a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc +++ b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc @@ -52,7 +52,7 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { // definitions from JS to C++. ui::Accelerator undoAccelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); source->AddString("undoDescription", l10n_util::GetStringFUTF16( - IDS_BOOKMARK_BAR_UNDO_DESCRIPTION, + IDS_UNDO_DESCRIPTION, undoAccelerator.GetShortcutText())); // Localized strings (alphabetical order). @@ -73,7 +73,10 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { {"listAxLabel", IDS_BOOKMARK_MANAGER_LIST_AX_LABEL}, {"menuAddBookmark", IDS_BOOKMARK_MANAGER_MENU_ADD_BOOKMARK}, {"menuAddFolder", IDS_BOOKMARK_MANAGER_MENU_ADD_FOLDER}, + {"menuCut", IDS_BOOKMARK_MANAGER_MENU_CUT}, + {"menuCopy", IDS_BOOKMARK_MANAGER_MENU_COPY}, {"menuCopyURL", IDS_BOOKMARK_MANAGER_MENU_COPY_URL}, + {"menuPaste", IDS_BOOKMARK_MANAGER_MENU_PASTE}, {"menuDelete", IDS_DELETE}, {"menuEdit", IDS_EDIT}, {"menuExport", IDS_BOOKMARK_MANAGER_MENU_EXPORT}, @@ -90,6 +93,8 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { {"menuSort", IDS_BOOKMARK_MANAGER_MENU_SORT}, {"moreActionsButtonTitle", IDS_BOOKMARK_MANAGER_MORE_ACTIONS}, {"moreActionsButtonAxLabel", IDS_BOOKMARK_MANAGER_MORE_ACTIONS_AX_LABEL}, + {"moreActionsMultiButtonAxLabel", + IDS_BOOKMARK_MANAGER_MORE_ACTIONS_MULTI_AX_LABEL}, {"noSearchResults", IDS_SEARCH_NO_RESULTS}, {"openDialogBody", IDS_BOOKMARK_BAR_SHOULD_OPEN_ALL}, {"openDialogConfirm", IDS_BOOKMARK_MANAGER_OPEN_DIALOG_CONFIRM}, @@ -167,7 +172,7 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) { source->SetDefaultResource(IDR_BOOKMARKS_BOOKMARKS_HTML); #endif - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc index 89a24827fde..f21dc8923c5 100644 --- a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc +++ b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc @@ -148,7 +148,7 @@ content::WebUIDataSource* CreateBrowserSwitchUIHTMLSource( source->AddResourcePath("internals/", IDR_BROWSER_SWITCH_INTERNALS_HTML); source->AddResourcePath("internals", IDR_BROWSER_SWITCH_INTERNALS_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc index 389bc5d5767..95e30eecb7c 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc @@ -245,6 +245,8 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue( result->SetInteger("hostFilteringBehavior", host_filtering_behavior); result->SetBoolean("blockedVisit", is_blocked_visit); result->SetBoolean("isUrlInRemoteUserData", IsEntryInRemoteUserData(entry)); + result->SetString("remoteIconUrlForUma", + entry.remote_icon_url_for_uma.spec()); return result; } 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 0eb7e9de200..f65dda6c020 100644 --- a/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/browsing_history_handler_unittest.cc @@ -80,7 +80,7 @@ class BrowsingHistoryHandlerTest : public ChromeRenderViewHostTestHarness { WebHistoryServiceFactory::GetForProfile(profile())); ASSERT_TRUE(web_history_service_); - web_ui_.reset(new content::TestWebUI); + web_ui_ = std::make_unique<content::TestWebUI>(); web_ui_->set_web_contents(web_contents()); } @@ -89,14 +89,15 @@ class BrowsingHistoryHandlerTest : public ChromeRenderViewHostTestHarness { ChromeRenderViewHostTestHarness::TearDown(); } - content::BrowserContext* CreateBrowserContext() override { - TestingProfile::Builder builder; - builder.AddTestingFactory(ProfileSyncServiceFactory::GetInstance(), - base::BindRepeating(&BuildTestSyncService)); - builder.AddTestingFactory(WebHistoryServiceFactory::GetInstance(), - base::BindRepeating(&BuildFakeWebHistoryService)); - return builder.Build().release(); + TestingProfile::TestingFactories GetTestingFactories() const override { + return { + {ProfileSyncServiceFactory::GetInstance(), + base::BindRepeating(&BuildTestSyncService)}, + {WebHistoryServiceFactory::GetInstance(), + base::BindRepeating(&BuildFakeWebHistoryService)}, + }; } + syncer::TestSyncService* sync_service() { return sync_service_; } history::WebHistoryService* web_history_service() { return web_history_service_; diff --git a/chromium/chrome/browser/ui/webui/cast/OWNERS b/chromium/chrome/browser/ui/webui/cast/OWNERS index 5b34f4712ed..1de9e6bb6d7 100644 --- a/chromium/chrome/browser/ui/webui/cast/OWNERS +++ b/chromium/chrome/browser/ui/webui/cast/OWNERS @@ -1 +1 @@ -sheretov@chromium.org +# Component: Chromecast diff --git a/chromium/chrome/browser/ui/webui/cast/cast_ui.cc b/chromium/chrome/browser/ui/webui/cast/cast_ui.cc index 68f113bf2ae..1c27f5122b3 100644 --- a/chromium/chrome/browser/ui/webui/cast/cast_ui.cc +++ b/chromium/chrome/browser/ui/webui/cast/cast_ui.cc @@ -13,6 +13,8 @@ #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" +// TODO: Figure out a way to self-navigate the WebUI in C++ on instantiation, +// and replace the navigation in cast.js with that. CastUI::CastUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { // Retrieve the ID of the component extension. @@ -26,13 +28,10 @@ CastUI::CastUI(content::WebUI* web_ui) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUICastHost); - html_source->AddResourcePath("cast.css", IDR_CAST_CSS); html_source->AddResourcePath("cast.js", IDR_CAST_JS); - html_source->AddResourcePath("cast_favicon.ico", IDR_CAST_FAVICON); html_source->AddString("extensionId", extension_id); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->SetDefaultResource(IDR_CAST_HTML); - html_source->OverrideContentSecurityPolicyObjectSrc("object-src * chrome:;"); content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), html_source); } diff --git a/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc b/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc index 468aaacacb4..995c3fefa64 100644 --- a/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc +++ b/chromium/chrome/browser/ui/webui/certificate_viewer_ui.cc @@ -46,7 +46,7 @@ content::WebUIDataSource* GetWebUIDataSource(const std::string& host) { }; AddLocalizedStringsBulk(html_source, kStrings, base::size(kStrings)); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add required resources. html_source->AddResourcePath("certificate_viewer.js", diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc index 78dd1df58d1..02077494954 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.cc +++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc @@ -57,6 +57,7 @@ static const char kCertificatesHandlerObjSignField[] = "objSign"; static const char kCertificatesHandlerPolicyInstalledField[] = "policy"; static const char kCertificatesHandlerWebTrustAnchorField[] = "webTrustAnchor"; static const char kCertificatesHandlerCanBeDeletedField[] = "canBeDeleted"; +static const char kCertificatesHandlerCanBeEditedField[] = "canBeEdited"; static const char kCertificatesHandlerSslField[] = "ssl"; static const char kCertificatesHandlerSubnodesField[] = "subnodes"; static const char kCertificatesHandlerContainsPolicyCertsField[] = @@ -78,19 +79,6 @@ enum { IMPORT_CA_FILE_SELECTED, }; -#if defined(OS_CHROMEOS) -// Enumeration of certificate management permissions which corresponds to -// values of policy ClientCertificateManagementAllowed. -enum class CertificateManagementPermission : int { - // Allow users to manage all certificates - kAll = 0, - // Allow users to manage user certificates - kUserOnly = 1, - // Disallow users from managing certificates - kNone = 2 -}; -#endif - std::string OrgNameToId(const std::string& org) { return "org-" + org; } @@ -236,8 +224,8 @@ base::CancelableTaskTracker::TaskId FileAccessProvider::StartRead( std::string* data = new std::string(); // Post task to a background sequence to read file. - auto task_runner = base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + auto task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}); return tracker->PostTaskAndReply( task_runner.get(), FROM_HERE, base::BindOnce(&FileAccessProvider::DoRead, this, path, saved_errno, @@ -255,8 +243,8 @@ base::CancelableTaskTracker::TaskId FileAccessProvider::StartWrite( int* bytes_written = new int(0); // This task blocks shutdown because it saves critical user data. - auto task_runner = base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + auto task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); return tracker->PostTaskAndReply( task_runner.get(), FROM_HERE, @@ -457,6 +445,15 @@ void CertificatesHandler::HandleEditCATrust(const base::ListValue* args) { if (!cert_info) return; + if (!CanEditCertificate(cert_info)) { + RejectCallbackWithError( + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_SET_TRUST_ERROR_TITLE), + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_ERROR_NOT_ALLOWED)); + return; + } + bool trust_ssl = false; bool trust_email = false; bool trust_obj_sign = false; @@ -571,15 +568,19 @@ void CertificatesHandler::ExportPersonalFileWritten(const int* write_errno, } void CertificatesHandler::HandleImportPersonal(const base::ListValue* args) { +#if defined(OS_CHROMEOS) + // When policy changes while user on the certificate manager page, the UI + // doesn't update without page refresh and user can still see and use import + // button. Because of this 'return' the button will do nothing. + if (!IsClientCertificateManagementAllowedPolicy(Slot::kUser)) { + return; + } +#endif + CHECK_EQ(2U, args->GetSize()); AssignWebUICallbackId(args); CHECK(args->GetBoolean(1, &use_hardware_backed_)); -#if defined(OS_CHROMEOS) - CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser)) - << "Importing certificates not allowed by policy"; -#endif - ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("p12")); @@ -740,11 +741,6 @@ void CertificatesHandler::HandleImportServer(const base::ListValue* args) { CHECK_EQ(1U, args->GetSize()); AssignWebUICallbackId(args); -#if defined(OS_CHROMEOS) - CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser)) - << "Importing certificates not allowed by policy"; -#endif - select_file_dialog_ = ui::SelectFileDialog::Create( this, std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents())); @@ -809,6 +805,15 @@ void CertificatesHandler::ImportServerFileRead(const int* read_errno, } void CertificatesHandler::HandleImportCA(const base::ListValue* args) { +#if defined(OS_CHROMEOS) + // When policy changes while user on the certificate manager page, the UI + // doesn't update without page refresh and user can still see and use import + // button. Because of this 'return' the button will do nothing. + if (!IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)) { + return; + } +#endif // defined(OS_CHROMEOS) + CHECK_EQ(1U, args->GetSize()); AssignWebUICallbackId(args); @@ -924,6 +929,15 @@ void CertificatesHandler::HandleDeleteCertificate(const base::ListValue* args) { if (!cert_info) return; + if (!CanDeleteCertificate(cert_info)) { + RejectCallbackWithError( + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_DELETE_CERT_ERROR_TITLE), + l10n_util::GetStringUTF8( + IDS_SETTINGS_CERTIFICATE_MANAGER_ERROR_NOT_ALLOWED)); + return; + } + bool result = certificate_manager_model_->Delete(cert_info->cert()); if (!result) { // TODO(mattm): better error messages? @@ -945,13 +959,18 @@ void CertificatesHandler::OnCertificateManagerModelCreated( void CertificatesHandler::CertificateManagerModelReady() { bool client_import_allowed = true; + bool ca_import_allowed = true; #if defined(OS_CHROMEOS) client_import_allowed = IsClientCertificateManagementAllowedPolicy(Slot::kUser); -#endif + ca_import_allowed = + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported); +#endif // defined(OS_CHROMEOS) if (IsJavascriptAllowed()) { - FireWebUIListener("certificates-model-ready", + FireWebUIListener("client-import-allowed-changed", base::Value(client_import_allowed)); + FireWebUIListener("ca-import-allowed-changed", + base::Value(ca_import_allowed)); } certificate_manager_model_->Refresh(); } @@ -1019,6 +1038,8 @@ void CertificatesHandler::PopulateTree(const std::string& tab_name, base::Value(cert_info->name())); cert_dict.SetKey(kCertificatesHandlerCanBeDeletedField, base::Value(CanDeleteCertificate(cert_info))); + cert_dict.SetKey(kCertificatesHandlerCanBeEditedField, + base::Value(CanEditCertificate(cert_info))); cert_dict.SetKey(kCertificatesHandlerUntrustedField, base::Value(cert_info->untrusted())); cert_dict.SetKey( @@ -1136,18 +1157,33 @@ bool CertificatesHandler::IsClientCertificateManagementAllowedPolicy( Slot slot) const { Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); - auto policy_value = static_cast<CertificateManagementPermission>( + auto policy_value = static_cast<ClientCertificateManagementPermission>( prefs->GetInteger(prefs::kClientCertificateManagementAllowed)); if (slot == Slot::kUser) { - return policy_value != CertificateManagementPermission::kNone; + return policy_value != ClientCertificateManagementPermission::kNone; + } + return policy_value == ClientCertificateManagementPermission::kAll; +} + +bool CertificatesHandler::IsCACertificateManagementAllowedPolicy( + CertificateSource source) const { + Profile* profile = Profile::FromWebUI(web_ui()); + PrefService* prefs = profile->GetPrefs(); + auto policy_value = static_cast<CACertificateManagementPermission>( + prefs->GetInteger(prefs::kCACertificateManagementAllowed)); + + switch (source) { + case CertificateSource::kBuiltIn: + return policy_value == CACertificateManagementPermission::kAll; + case CertificateSource::kImported: + return policy_value != CACertificateManagementPermission::kNone; } - return policy_value == CertificateManagementPermission::kAll; } #endif // defined(OS_CHROMEOS) bool CertificatesHandler::CanDeleteCertificate( - const CertificateManagerModel::CertInfo* cert_info) { + const CertificateManagerModel::CertInfo* cert_info) const { if (!cert_info->can_be_deleted() || cert_info->source() == CertificateManagerModel::CertInfo::Source::kPolicy) { @@ -1155,22 +1191,50 @@ bool CertificatesHandler::CanDeleteCertificate( } #if defined(OS_CHROMEOS) - return cert_info->type() == net::CertType::USER_CERT && - IsClientCertificateManagementAllowedPolicy( - cert_info->device_wide() ? Slot::kSystem : Slot::kUser); -#else + if (cert_info->type() == net::CertType::USER_CERT) { + return IsClientCertificateManagementAllowedPolicy( + cert_info->device_wide() ? Slot::kSystem : Slot::kUser); + } + if (cert_info->type() == net::CertType::CA_CERT) { + CertificateSource source = cert_info->can_be_deleted() + ? CertificateSource::kImported + : CertificateSource::kBuiltIn; + return IsCACertificateManagementAllowedPolicy(source); + } +#endif // defined(OS_CHROMEOS) + return true; +} + +bool CertificatesHandler::CanEditCertificate( + const CertificateManagerModel::CertInfo* cert_info) const { + if ((cert_info->type() != net::CertType::CA_CERT) || + (cert_info->source() == + CertificateManagerModel::CertInfo::Source::kPolicy)) { + return false; + } +#if defined(OS_CHROMEOS) + CertificateSource source = cert_info->can_be_deleted() + ? CertificateSource::kImported + : CertificateSource::kBuiltIn; + return IsCACertificateManagementAllowedPolicy(source); +#endif // defined(OS_CHROMEOS) return true; -#endif } #if defined(OS_CHROMEOS) void CertificatesHandler::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { - // Allow users to manage all certificates by default. This can be overridden - // by enterprise policy. + // Allow users to manage all client certificates by default. This can be + // overridden by enterprise policy. registry->RegisterIntegerPref( prefs::kClientCertificateManagementAllowed, - static_cast<int>(CertificateManagementPermission::kAll)); + static_cast<int>(ClientCertificateManagementPermission::kAll)); + + // Allow users to manage all CA certificates by default. This can be + // overridden by enterprise policy. + registry->RegisterIntegerPref( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); } #endif // defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.h b/chromium/chrome/browser/ui/webui/certificates_handler.h index 76ff163b1e7..e346efa177e 100644 --- a/chromium/chrome/browser/ui/webui/certificates_handler.h +++ b/chromium/chrome/browser/ui/webui/certificates_handler.h @@ -25,7 +25,32 @@ class PrefRegistrySyncable; #if defined(OS_CHROMEOS) enum class Slot { kUser, kSystem }; -#endif +enum class CertificateSource { kBuiltIn, kImported }; + +// Enumeration of certificate management permissions which corresponds to +// values of policy ClientCertificateManagementAllowed. +// Underlying type is int because values are casting to/from prefs values. +enum class ClientCertificateManagementPermission : int { + // Allow users to manage all certificates + kAll = 0, + // Allow users to manage user certificates + kUserOnly = 1, + // Disallow users from managing certificates + kNone = 2 +}; + +// Enumeration of certificate management permissions which corresponds to +// values of policy CACertificateManagementAllowed. +// Underlying type is int because values are casting to/from prefs values. +enum class CACertificateManagementPermission : int { + // Allow users to manage all certificates + kAll = 0, + // Allow users to manage user certificates + kUserOnly = 1, + // Disallow users from managing certificates + kNone = 2 +}; +#endif // defined(OS_CHROMEOS) namespace certificate_manager { @@ -178,14 +203,21 @@ class CertificatesHandler : public content::WebUIMessageHandler, #if defined(OS_CHROMEOS) // Returns true if the user may manage certificates on |slot| according - // ClientCertificateManagementAllowed to policy. + // to ClientCertificateManagementAllowed policy. bool IsClientCertificateManagementAllowedPolicy(Slot slot) const; -#endif + + // Returns true if the user may manage certificates according + // to CACertificateManagementAllowed policy. + bool IsCACertificateManagementAllowedPolicy(CertificateSource source) const; +#endif // defined(OS_CHROMEOS) // Returns true if the certificate represented by |cert_info| can be deleted. - // Evaluates the certificate attributes and, on Chrome OS devices, the - // enterprise policy ClientCertificateManagementAllowed. - bool CanDeleteCertificate(const CertificateManagerModel::CertInfo* cert_info); + bool CanDeleteCertificate( + const CertificateManagerModel::CertInfo* cert_info) const; + + // Returns true if the certificate represented by |cert_info| can be edited. + bool CanEditCertificate( + const CertificateManagerModel::CertInfo* cert_info) const; // The Certificates Manager model bool requested_certificate_manager_model_; @@ -215,6 +247,7 @@ class CertificatesHandler : public content::WebUIMessageHandler, base::WeakPtrFactory<CertificatesHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CertificatesHandler); + friend class ::CertificateHandlerTest; }; } // namespace certificate_manager diff --git a/chromium/chrome/browser/ui/webui/certificates_handler_unittest.cc b/chromium/chrome/browser/ui/webui/certificates_handler_unittest.cc new file mode 100644 index 00000000000..6977fd0295c --- /dev/null +++ b/chromium/chrome/browser/ui/webui/certificates_handler_unittest.cc @@ -0,0 +1,354 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/certificates_handler.h" + +#include "base/logging.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/testing_profile.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "content/public/test/test_web_ui.h" +#include "testing/gtest/include/gtest/gtest.h" + +class CertificateHandlerTest : public ChromeRenderViewHostTestHarness { + public: + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); + + web_ui_.set_web_contents(web_contents()); + cert_handler_.set_web_ui(&web_ui_); + pref_service_ = profile()->GetTestingPrefService(); + } + +#if defined(OS_CHROMEOS) + bool IsCACertificateManagementAllowedPolicy(CertificateSource source) const { + return cert_handler_.IsCACertificateManagementAllowedPolicy(source); + } +#endif // defined(OS_CHROMEOS) + + bool CanDeleteCertificate( + const CertificateManagerModel::CertInfo* cert_info) const { + return cert_handler_.CanDeleteCertificate(cert_info); + } + + bool CanEditCertificate( + const CertificateManagerModel::CertInfo* cert_info) const { + return cert_handler_.CanEditCertificate(cert_info); + } + + protected: + content::TestWebUI web_ui_; + certificate_manager::CertificatesHandler cert_handler_; + sync_preferences::TestingPrefServiceSyncable* pref_service_ = nullptr; +}; + +#if defined(OS_CHROMEOS) +TEST_F(CertificateHandlerTest, IsCACertificateManagementAllowedPolicyTest) { + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); + + EXPECT_TRUE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)); + EXPECT_TRUE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kBuiltIn)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kUserOnly)); + + EXPECT_TRUE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)); + EXPECT_FALSE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kBuiltIn)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kNone)); + + EXPECT_FALSE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kImported)); + EXPECT_FALSE( + IsCACertificateManagementAllowedPolicy(CertificateSource::kBuiltIn)); + } +} +#endif // defined(OS_CHROMEOS) + +TEST_F(CertificateHandlerTest, CanDeleteCertificateCommonTest) { + CertificateManagerModel::CertInfo default_cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + false /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kPolicy, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + + { + auto cert_info = + CertificateManagerModel::CertInfo::Clone(&default_cert_info); + cert_info->type_ = net::CertType::USER_CERT; + cert_info->can_be_deleted_ = false; + cert_info->source_ = CertificateManagerModel::CertInfo::Source::kExtension; + + // Deletion of |!can_be_deleted_| certificates is not allowed. + EXPECT_FALSE(CanDeleteCertificate(cert_info.get())); + } + + { + auto cert_info = + CertificateManagerModel::CertInfo::Clone(&default_cert_info); + cert_info->type_ = net::CertType::USER_CERT; + cert_info->can_be_deleted_ = true; + cert_info->source_ = CertificateManagerModel::CertInfo::Source::kPolicy; + + // Deletion of policy certificates is not allowed. + EXPECT_FALSE(CanDeleteCertificate(cert_info.get())); + } +} + +TEST_F(CertificateHandlerTest, CanDeleteUserCertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.device_wide_ = false; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kAll)); + + cert_info.device_wide_ = false; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kUserOnly)); + + cert_info.device_wide_ = false; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kNone)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} + +TEST_F(CertificateHandlerTest, CanDeleteCACertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::CA_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kUserOnly)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanDeleteCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kNone)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + cert_info.can_be_deleted_ = true; + EXPECT_FALSE(CanDeleteCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} + +TEST_F(CertificateHandlerTest, CanEditCertificateCommonTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kExtension; + cert_info.type_ = net::CertType::USER_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kExtension; + cert_info.type_ = net::CertType::SERVER_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kExtension; + cert_info.type_ = net::CertType::OTHER_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.source_ = CertificateManagerModel::CertInfo::Source::kPolicy; + cert_info.type_ = net::CertType::CA_CERT; + EXPECT_FALSE(CanEditCertificate(&cert_info)); +} + +// Edit of user certificates is not allowed in any case. +TEST_F(CertificateHandlerTest, CanEditUserCertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::USER_CERT, {} /* cert_name */, + true /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kAll)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kUserOnly)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kClientCertificateManagementAllowed, + static_cast<int>(ClientCertificateManagementPermission::kNone)); + + cert_info.device_wide_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.device_wide_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} + +TEST_F(CertificateHandlerTest, CanEditCACertificateTest) { + CertificateManagerModel::CertInfo cert_info( + {} /* cert */, net::CertType::CA_CERT, {} /* cert_name */, + false /* can_be_deleted */, false /* untrusted */, + CertificateManagerModel::CertInfo::Source::kExtension, + true /* web_trust_anchor */, false /* hardware_backed */, + false /* device_wide */); + { + cert_info.can_be_deleted_ = false; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + } + +#if defined(OS_CHROMEOS) + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kAll)); + + cert_info.can_be_deleted_ = false; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kUserOnly)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_TRUE(CanEditCertificate(&cert_info)); + } + + { + pref_service_->SetInteger( + prefs::kCACertificateManagementAllowed, + static_cast<int>(CACertificateManagementPermission::kNone)); + + cert_info.can_be_deleted_ = false; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + + cert_info.can_be_deleted_ = true; + EXPECT_FALSE(CanEditCertificate(&cert_info)); + } +#endif // defined(OS_CHROMEOS) +} diff --git a/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc b/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc index 8d2a5e65217..1b97ae66d5b 100644 --- a/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc +++ b/chromium/chrome/browser/ui/webui/chrome_web_contents_handler.cc @@ -43,7 +43,7 @@ WebContents* ChromeWebContentsHandler::OpenURLFromTab( // TODO(erg): OpenURLParams should pass a user_gesture flag, pass it to // CreateParams, and pass the real value to nav_params below. browser = - new Browser(Browser::CreateParams(Browser::TYPE_TABBED, profile, true)); + new Browser(Browser::CreateParams(Browser::TYPE_NORMAL, profile, true)); } NavigateParams nav_params(browser, params.url, params.transition); nav_params.referrer = params.referrer; @@ -88,7 +88,7 @@ void ChromeWebContentsHandler::AddNewContents( const bool browser_created = !browser; if (!browser) { browser = new Browser( - Browser::CreateParams(Browser::TYPE_TABBED, profile, user_gesture)); + Browser::CreateParams(Browser::TYPE_NORMAL, profile, user_gesture)); } NavigateParams params(browser, std::move(new_contents)); params.source_contents = source; 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 8f6d49bfdb3..afb648955a1 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 @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" #include <stddef.h> +#include <utility> #include "base/bind.h" #include "base/feature_list.h" @@ -22,7 +23,8 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search/suggestions/suggestions_ui.h" #include "chrome/browser/ui/webui/about_ui.h" -#include "chrome/browser/ui/webui/autofill_internals_ui.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/autofill_internals_ui.h" +#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" #include "chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h" #include "chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h" @@ -51,7 +53,6 @@ #include "chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h" #include "chrome/browser/ui/webui/ntp_tiles_internals_ui.h" #include "chrome/browser/ui/webui/omnibox/omnibox_ui.h" -#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h" #include "chrome/browser/ui/webui/policy_ui.h" #include "chrome/browser/ui/webui/predictors/predictors_ui.h" #include "chrome/browser/ui/webui/quota_internals/quota_internals_ui.h" @@ -81,6 +82,7 @@ #include "components/history/core/browser/history_types.h" #include "components/nacl/common/buildflags.h" #include "components/prefs/pref_service.h" +#include "components/safe_browsing/buildflags.h" #include "components/safe_browsing/web_ui/constants.h" #include "components/safe_browsing/web_ui/safe_browsing_ui.h" #include "components/security_interstitials/content/connection_help_ui.h" @@ -106,17 +108,23 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #endif +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) +#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui.h" +#endif + #if !defined(OS_ANDROID) #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/ui/webui/app_management/app_management_ui.h" #include "chrome/browser/ui/webui/management_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_internals_ui.h" +#include "chrome/browser/ui/webui/web_footer_experiment_ui.h" #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/cast/cast_ui.h" #endif #if defined(OS_ANDROID) +#include "chrome/android/features/dev_ui/buildflags.h" #include "chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.h" #include "chrome/browser/ui/webui/offline/offline_internals_ui.h" #include "chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.h" @@ -126,7 +134,10 @@ #if BUILDFLAG(ENABLE_FEED_IN_CHROME) #include "chrome/browser/ui/webui/feed_internals/feed_internals_ui.h" #endif // BUILDFLAG(ENABLE_FEED_IN_CHROME) -#else +#if BUILDFLAG(DFMIFY_DEV_UI) +#include "chrome/browser/ui/webui/android/dev_ui_loader/dev_ui_loader_ui.h" +#endif // BUILDFLAG(DFMIFY_DEV_UI) +#else // defined(OS_ANDROID) #include "chrome/browser/ui/webui/bookmarks/bookmarks_ui.h" #include "chrome/browser/ui/webui/devtools_ui.h" #include "chrome/browser/ui/webui/downloads/downloads_ui.h" @@ -137,7 +148,7 @@ #include "chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.h" #include "chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.h" #include "chrome/browser/ui/webui/system_info_ui.h" -#endif +#endif // defined(OS_ANDROID) #if defined(OS_CHROMEOS) #include "base/system/sys_info.h" @@ -175,7 +186,6 @@ #include "chromeos/components/multidevice/debug_webui/url_constants.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" -#include "components/arc/arc_features.h" #endif #if defined(OS_CHROMEOS) && !defined(OFFICIAL_BUILD) @@ -194,13 +204,12 @@ #include "chrome/browser/ui/webui/signin/signin_error_ui.h" #include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h" #include "chrome/browser/ui/webui/signin/user_manager_ui.h" -#include "chrome/browser/ui/webui/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" #include "chrome/browser/ui/webui/welcome/welcome_ui.h" #endif #if defined(OS_WIN) #include "chrome/browser/ui/webui/conflicts/conflicts_ui.h" -#include "chrome/browser/ui/webui/set_as_default_browser_ui_win.h" #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) @@ -231,7 +240,7 @@ #include "extensions/common/manifest.h" #endif -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) #include "chrome/browser/ui/webui/reset_password/reset_password_ui.h" #endif @@ -246,16 +255,25 @@ using ui::WebDialogUI; namespace { // A function for creating a new WebUI. The caller owns the return value, which -// may be NULL (for example, if the URL refers to an non-existent extension). +// may be nullptr (for example, if the URL refers to an non-existent extension). typedef WebUIController* (*WebUIFactoryFunction)(WebUI* web_ui, const GURL& url); // Template for defining WebUIFactoryFunction. -template<class T> +template <class T> WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new T(web_ui); } +#if defined(OS_ANDROID) +#if BUILDFLAG(DFMIFY_DEV_UI) +template <> +WebUIController* NewWebUI<DevUiLoaderUI>(WebUI* web_ui, const GURL& url) { + return new DevUiLoaderUI(web_ui, url); +} +#endif // BUILDFLAG(DFMIFY_DEV_UI) +#endif // defined(OS_ANDROID) + #if !defined(OS_ANDROID) template <> WebUIController* NewWebUI<PageNotAvailableForGuestUI>(WebUI* web_ui, @@ -265,13 +283,13 @@ WebUIController* NewWebUI<PageNotAvailableForGuestUI>(WebUI* web_ui, #endif // Special case for older about: handlers. -template<> +template <> WebUIController* NewWebUI<AboutUI>(WebUI* web_ui, const GURL& url) { return new AboutUI(web_ui, url.host()); } #if defined(OS_CHROMEOS) -template<> +template <> WebUIController* NewWebUI<chromeos::OobeUI>(WebUI* web_ui, const GURL& url) { return new chromeos::OobeUI(web_ui, url); } @@ -293,7 +311,7 @@ WebUIController* NewWebUI<chromeos::multidevice::ProximityAuthUI>( #endif // Special cases for DOM distiller. -template<> +template <> WebUIController* NewWebUI<dom_distiller::DomDistillerUi>(WebUI* web_ui, const GURL& url) { // The DomDistillerUi can not depend on components/dom_distiller/content, @@ -303,8 +321,8 @@ WebUIController* NewWebUI<dom_distiller::DomDistillerUi>(WebUI* web_ui, dom_distiller::DomDistillerService* service = dom_distiller::DomDistillerServiceFactory::GetForBrowserContext( browser_context); - return new dom_distiller::DomDistillerUi( - web_ui, service, dom_distiller::kDomDistillerScheme); + return new dom_distiller::DomDistillerUi(web_ui, service, + dom_distiller::kDomDistillerScheme); } #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) @@ -327,12 +345,12 @@ bool IsAboutUI(const GURL& url) { || url.host_piece() == chrome::kChromeUIOSCreditsHost || url.host_piece() == chrome::kChromeUILinuxCreditsHost #endif - ); // NOLINT + ); // NOLINT } // Returns a function that can be used to create the right type of WebUI for a -// tab, based on its URL. Returns NULL if the URL doesn't have WebUI associated -// with it. +// tab, based on its URL. Returns nullptr if the URL doesn't have WebUI +// associated with it. WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, Profile* profile, const GURL& url) { @@ -340,13 +358,19 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, // schemes to filter out most URLs. if (!url.SchemeIs(content::kChromeDevToolsScheme) && !url.SchemeIs(content::kChromeUIScheme)) { - return NULL; + return nullptr; } - /**************************************************************************** - * Please keep this in alphabetical order. If #ifs or special logics are - * required, add it below in the appropriate section. - ***************************************************************************/ +#if defined(OS_ANDROID) +#if BUILDFLAG(DFMIFY_DEV_UI) + if (url.host_piece() == chrome::kChromeUIDevUiLoaderHost) + return &NewWebUI<DevUiLoaderUI>; +#endif // BUILDFLAG(DFMIFY_DEV_UI) +#endif // defined(OS_ANDROID) + + // Please keep this in alphabetical order. If #ifs or special logics are + // required, add it below in the appropriate section. + // // We must compare hosts only since some of the Web UIs append extra stuff // after the host name. // All platform builds of Chrome will need to have a cloud printing @@ -370,6 +394,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<DomainReliabilityInternalsUI>; if (url.host_piece() == chrome::kChromeUIDownloadInternalsHost) return &NewWebUI<DownloadInternalsUI>; + if (url.host_piece() == chrome::kChromeUIFlagsHost && + FlagsDeprecatedUI::IsDeprecatedUrl(url)) + return &NewWebUI<FlagsDeprecatedUI>; if (url.host_piece() == chrome::kChromeUIFlagsHost) return &NewWebUI<FlagsUI>; if (url.host_piece() == chrome::kChromeUIGCMInternalsHost) @@ -421,9 +448,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUIVersionHost) return &NewWebUI<VersionUI>; - /**************************************************************************** - * OS Specific #defines - ***************************************************************************/ #if !defined(OS_ANDROID) if (AppManagementUI::IsEnabled() && url.host_piece() == chrome::kChromeUIAppManagementHost && profile && @@ -469,6 +493,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<SyncFileSystemInternalsUI>; if (url.host_piece() == chrome::kChromeUISystemInfoHost) return &NewWebUI<SystemInfoUI>; + if (url.host_piece() == chrome::kChromeUIWebFooterExperimentHost) + return &NewWebUI<WebFooterExperimentUI>; // Inline login UI is available on all platforms except Android. if (url.host_piece() == chrome::kChromeUIChromeSigninHost) return &NewWebUI<InlineLoginUI>; @@ -476,8 +502,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, #if defined(OS_WIN) if (url.host_piece() == chrome::kChromeUIConflictsHost) return &NewWebUI<ConflictsUI>; - if (url.host_piece() == chrome::kChromeUIMetroFlowHost) - return &NewWebUI<SetAsDefaultBrowserUI>; #endif #if defined(OS_CHROMEOS) if (url.host_piece() == chrome::kChromeUIPasswordChangeHost) { @@ -506,7 +530,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<chromeos::AccountManagerWelcomeUI>; if (url.host_piece() == chrome::kChromeUIAccountMigrationWelcomeHost) return &NewWebUI<chromeos::AccountMigrationWelcomeUI>; - if (chromeos::switches::IsParentalControlsSettingsEnabled()) { + if (chromeos::features::IsParentalControlsSettingsEnabled()) { if (url.host_piece() == chrome::kChromeUIAddSupervisionHost) return &NewWebUI<chromeos::AddSupervisionUI>; } @@ -566,11 +590,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<chromeos::CameraUI>; } - if (url.host_piece() == chrome::kChromeUIArcGraphicsTracingHost) { - if (!base::FeatureList::IsEnabled(arc::kGraphicBuffersVisualizationTool)) - return nullptr; + if (url.host_piece() == chrome::kChromeUIArcGraphicsTracingHost) return &NewWebUI<chromeos::ArcGraphicsTracingUI>; - } + #if !defined(OFFICIAL_BUILD) if (!base::SysInfo::IsRunningOnChromeOS()) { if (url.host_piece() == chrome::kChromeUIDeviceEmulatorHost) @@ -624,13 +646,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, !profile->IsOffTheRecord()) return &NewWebUI<SigninEmailConfirmationUI>; if (url.host_piece() == chrome::kChromeUIWelcomeHost && - nux::IsNuxOnboardingEnabled(profile)) + welcome::IsEnabled(profile)) return &NewWebUI<WelcomeUI>; #endif - /**************************************************************************** - * Other #defines and special logics. - ***************************************************************************/ #if BUILDFLAG(ENABLE_NACL) if (url.host_piece() == chrome::kChromeUINaClHost) return &NewWebUI<NaClUI>; @@ -662,6 +681,13 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<LocalDiscoveryUI>; } #endif + +#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) + if (url.host_piece() == chrome::kChromeUITabStripHost) { + return &NewWebUI<TabStripUI>; + } +#endif + if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) return &NewWebUI<WebRtcLogsUI>; #if !defined(OS_ANDROID) @@ -698,7 +724,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<security_interstitials::ConnectionHelpUI>; } - if (dom_distiller::IsEnableDomDistillerSet() && + if (dom_distiller::IsDomDistillerEnabled() && url.host_piece() == dom_distiller::kChromeUIDomDistillerHost) { return &NewWebUI<dom_distiller::DomDistillerUi>; } @@ -713,7 +739,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<MediaEngagementUI>; } -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) if (url.host_piece() == chrome::kChromeUIResetPasswordHost) { return &NewWebUI<ResetPasswordUI>; } @@ -724,7 +750,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI<SupervisedUserInternalsUI>; #endif - return NULL; + return nullptr; } } // namespace @@ -733,7 +759,8 @@ WebUI::TypeID ChromeWebUIControllerFactory::GetWebUIType( content::BrowserContext* browser_context, const GURL& url) { Profile* profile = Profile::FromBrowserContext(browser_context); - WebUIFactoryFunction function = GetWebUIFactoryFunction(NULL, profile, url); + WebUIFactoryFunction function = + GetWebUIFactoryFunction(nullptr, profile, url); return function ? reinterpret_cast<WebUI::TypeID>(function) : WebUI::kNoWebUI; } @@ -801,8 +828,8 @@ void ChromeWebUIControllerFactory::GetFaviconForURL( gfx::Size(candidate_edge_size, candidate_edge_size)); } std::vector<size_t> selected_indices; - SelectFaviconFrameIndices( - candidate_sizes, desired_sizes_in_pixel, &selected_indices, NULL); + SelectFaviconFrameIndices(candidate_sizes, desired_sizes_in_pixel, + &selected_indices, nullptr); for (size_t i = 0; i < selected_indices.size(); ++i) { size_t selected_index = selected_indices[i]; ui::ScaleFactor selected_resource_scale = @@ -850,24 +877,23 @@ bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests( origin.host() == chrome::kChromeUIDownloadsHost; } -ChromeWebUIControllerFactory::ChromeWebUIControllerFactory() { -} +ChromeWebUIControllerFactory::ChromeWebUIControllerFactory() {} -ChromeWebUIControllerFactory::~ChromeWebUIControllerFactory() { -} +ChromeWebUIControllerFactory::~ChromeWebUIControllerFactory() {} base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( - const GURL& page_url, ui::ScaleFactor scale_factor) const { + const GURL& page_url, + ui::ScaleFactor scale_factor) const { #if !defined(OS_ANDROID) // The extension scheme is handled in GetFaviconForURL. if (page_url.SchemeIs(extensions::kExtensionScheme)) { NOTREACHED(); - return NULL; + return nullptr; } #endif if (!content::HasWebUIScheme(page_url)) - return NULL; + return nullptr; if (page_url.host_piece() == chrome::kChromeUIComponentsHost) return ComponentsUI::GetFaviconResourceBytes(scale_factor); @@ -921,5 +947,10 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( #endif // BUILDFLAG(ENABLE_EXTENSIONS) #endif // !defined(OS_ANDROID) - return NULL; +#if defined(OS_CHROMEOS) + if (page_url.host_piece() == chrome::kChromeUIOSSettingsHost) + return settings_utils::GetFaviconResourceBytes(scale_factor); +#endif // defined(OS_CHROMEOS) + + return nullptr; } diff --git a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h index 92245af05e9..ada994e360c 100644 --- a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h +++ b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h @@ -67,7 +67,8 @@ class ChromeWebUIControllerFactory : public content::WebUIControllerFactory { // |gfx::kFaviconSize| x |gfx::kFaviconSize| DIP. GetFaviconForURL() should // be updated if this changes. base::RefCountedMemory* GetFaviconResourceBytes( - const GURL& page_url, ui::ScaleFactor scale_factor) const; + const GURL& page_url, + ui::ScaleFactor scale_factor) const; DISALLOW_COPY_AND_ASSIGN(ChromeWebUIControllerFactory); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc index d678bfe3343..0ffa1c7c75a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc @@ -67,7 +67,6 @@ bool AccountManagerWelcomeDialog::ShowIfRequired() { void AccountManagerWelcomeDialog::AdjustWidgetInitParams( views::Widget::InitParams* params) { params->z_order = ui::ZOrderLevel::kNormal; - params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS; params->shadow_type = views::Widget::InitParams::ShadowType::SHADOW_TYPE_DROP; params->shadow_elevation = wm::kShadowElevationActiveWindow; } @@ -92,4 +91,8 @@ bool AccountManagerWelcomeDialog::ShouldShowDialogTitle() const { return false; } +bool AccountManagerWelcomeDialog::ShouldShowCloseButton() const { + return false; +} + } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h index efed08c5331..67fea954e98 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h @@ -29,6 +29,7 @@ class AccountManagerWelcomeDialog : public SystemWebDialogDelegate { void GetDialogSize(gfx::Size* size) const override; std::string GetDialogArgs() const override; bool ShouldShowDialogTitle() const override; + bool ShouldShowCloseButton() const override; private: DISALLOW_COPY_AND_ASSIGN(AccountManagerWelcomeDialog); diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc index 67d228af18c..16a69c1d232 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc @@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" +#include "build/branding_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" @@ -18,7 +19,7 @@ namespace chromeos { AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui) - : ui::WebDialogUI(web_ui), weak_factory_(this) { + : ui::WebDialogUI(web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create( chrome::kChromeUIAccountManagerWelcomeHost); @@ -26,7 +27,7 @@ AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui) "closeDialog", base::BindRepeating(&WebDialogUI::CloseDialog, weak_factory_.GetWeakPtr())); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add localized strings. html_source->AddLocalizedString("welcomeTitle", @@ -44,7 +45,7 @@ AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui) IDR_ACCOUNT_MANAGER_SHARED_CSS); html_source->AddResourcePath("account_manager_welcome.js", IDR_ACCOUNT_MANAGER_WELCOME_JS); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) html_source->AddResourcePath("account_manager_welcome_1x.png", IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG); html_source->AddResourcePath("account_manager_welcome_2x.png", diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h index 6f66e183f84..ded176fe6df 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h @@ -18,7 +18,7 @@ class AccountManagerWelcomeUI : public ui::WebDialogUI { ~AccountManagerWelcomeUI() override; private: - base::WeakPtrFactory<AccountManagerWelcomeUI> weak_factory_; + base::WeakPtrFactory<AccountManagerWelcomeUI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccountManagerWelcomeUI); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc index 33407733834..5144af68c27 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc @@ -64,7 +64,6 @@ AccountMigrationWelcomeDialog* AccountMigrationWelcomeDialog::Show( void AccountMigrationWelcomeDialog::AdjustWidgetInitParams( views::Widget::InitParams* params) { params->z_order = ui::ZOrderLevel::kNormal; - params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS; params->shadow_type = views::Widget::InitParams::ShadowType::SHADOW_TYPE_DROP; params->shadow_elevation = wm::kShadowElevationActiveWindow; } @@ -89,6 +88,10 @@ bool AccountMigrationWelcomeDialog::ShouldShowDialogTitle() const { return false; } +bool AccountMigrationWelcomeDialog::ShouldShowCloseButton() const { + return false; +} + const std::string& AccountMigrationWelcomeDialog::Id() { return id_; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h index c12c22906fc..96670974836 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h @@ -28,6 +28,7 @@ class AccountMigrationWelcomeDialog : public SystemWebDialogDelegate { void GetDialogSize(gfx::Size* size) const override; std::string GetDialogArgs() const override; bool ShouldShowDialogTitle() const override; + bool ShouldShowCloseButton() const override; const std::string& Id() override; std::string GetUserEmail() const; diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc index 78f338045ea..3c486f344a0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc @@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/strings/utf_string_conversions.h" +#include "build/branding_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h" #include "chrome/common/url_constants.h" @@ -71,11 +72,11 @@ class MigrationMessageHandler : public content::WebUIMessageHandler { } // namespace AccountMigrationWelcomeUI::AccountMigrationWelcomeUI(content::WebUI* web_ui) - : ui::WebDialogUI(web_ui), weak_factory_(this) { + : ui::WebDialogUI(web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create( chrome::kChromeUIAccountMigrationWelcomeHost); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add localized strings. html_source->AddLocalizedString("welcomePageTitle", @@ -99,7 +100,7 @@ AccountMigrationWelcomeUI::AccountMigrationWelcomeUI(content::WebUI* web_ui) IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_HTML); html_source->AddResourcePath("account_migration_browser_proxy.js", IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_JS); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) html_source->AddResourcePath("account_manager_welcome_1x.png", IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG); html_source->AddResourcePath("account_manager_welcome_2x.png", diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h index 90dee7f3a6f..24a0c7dd8be 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h @@ -19,7 +19,7 @@ class AccountMigrationWelcomeUI : public ui::WebDialogUI { ~AccountMigrationWelcomeUI() override; private: - base::WeakPtrFactory<AccountMigrationWelcomeUI> weak_factory_; + base::WeakPtrFactory<AccountMigrationWelcomeUI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccountMigrationWelcomeUI); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn index 2829e6d376d..54b63f6b00a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn @@ -8,7 +8,4 @@ mojom("mojo_bindings") { sources = [ "add_supervision.mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc index 0acab1a5249..e418a046414 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc @@ -11,17 +11,19 @@ #include "base/stl_util.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" -#include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" #include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "components/signin/public/identity_manager/access_token_fetcher.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/identity_manager.h" +#include "components/user_manager/user_manager.h" #include "content/public/browser/web_ui.h" #include "google_apis/gaia/gaia_constants.h" @@ -50,6 +52,18 @@ void AddSupervisionHandler::GetInstalledArcApps( apps::AppServiceProxy* proxy = apps::AppServiceProxyFactory::GetForProfile(profile); + if (arc::ArcSessionManager::Get() == nullptr) { + DLOG(WARNING) << "No ArcSessionManager available"; + std::move(callback).Run({}); + return; + } + if (arc::ArcSessionManager::Get()->state() != + arc::ArcSessionManager::State::ACTIVE) { + DLOG(WARNING) << "ArcSessionManager is not active"; + std::move(callback).Run({}); + return; + } + std::vector<std::string> installed_arc_apps; proxy->AppRegistryCache().ForEachApp( @@ -75,6 +89,8 @@ void AddSupervisionHandler::GetOAuthToken(GetOAuthTokenCallback callback) { scopes.insert(GaiaConstants::kKidsSupervisionSetupChildOAuth2Scope); scopes.insert(GaiaConstants::kPeopleApiReadOnlyOAuth2Scope); scopes.insert(GaiaConstants::kAccountsReauthOAuth2Scope); + scopes.insert(GaiaConstants::kAuditRecordingOAuth2Scope); + scopes.insert(GaiaConstants::kClearCutOAuth2Scope); oauth2_access_token_fetcher_ = identity_manager_->CreateAccessTokenFetcherForAccount( @@ -85,14 +101,23 @@ void AddSupervisionHandler::GetOAuthToken(GetOAuthTokenCallback callback) { } void AddSupervisionHandler::LogOut() { - chrome::AttemptUserExit(); + LogOutHelper(); } void AddSupervisionHandler::NotifySupervisionEnabled() { SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile(Profile::FromWebUI(web_ui_)); - service->set_signout_required_after_supervision_enabled(); + + // Force full sign-in the next time the user is at the login screen. + // Gellerization can only be triggered by the primary user. + user_manager::UserManager* manager = user_manager::UserManager::Get(); + manager->SaveForceOnlineSignin(manager->GetPrimaryUser()->GetAccountId(), + true /* force signin */); + + // Record UMA metric that user has completed Add Supervision process. + AddSupervisionMetricsRecorder::GetInstance()->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kCompleted); } void AddSupervisionHandler::OnAccessTokenFetchComplete( diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc index c5775d23ff0..0c7a610df3e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc @@ -4,6 +4,11 @@ #include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/supervised_user/supervised_user_service.h" +#include "chrome/browser/supervised_user/supervised_user_service_factory.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" #include "chrome/services/app_service/public/cpp/app_update.h" #include "chrome/services/app_service/public/mojom/types.mojom.h" @@ -13,3 +18,23 @@ bool ShouldIncludeAppUpdate(const apps::AppUpdate& app_update) { return app_update.AppType() == apps::mojom::AppType::kArc; } + +void LogOutHelper() { + // Record UMA metric that the user clicked "Sign out". + if (EnrollmentCompleted()) { + AddSupervisionMetricsRecorder::GetInstance() + ->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kSignedOut); + } else { + AddSupervisionMetricsRecorder::GetInstance() + ->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kSwitchedAccounts); + } + chrome::AttemptUserExit(); +} + +bool EnrollmentCompleted() { + SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile( + ProfileManager::GetPrimaryUserProfile()); + return service->signout_required_after_supervision_enabled(); +} diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h index 9f8c8383fc8..6cb4741673d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h @@ -17,4 +17,10 @@ class AppUpdate; // returned to clients or uninstalled. bool ShouldIncludeAppUpdate(const apps::AppUpdate& app_update); +// Records UMA metric and signs out the user. +void LogOutHelper(); + +// Checks if the user has completed enrollment in supervision. +bool EnrollmentCompleted(); + #endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_HANDLER_UTILS_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc new file mode 100644 index 00000000000..3681eee93fe --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.cc @@ -0,0 +1,79 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" + +#include "base/logging.h" +#include "base/metrics/histogram_functions.h" +#include "base/metrics/user_metrics.h" +#include "base/time/default_tick_clock.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" + +// static +AddSupervisionMetricsRecorder* AddSupervisionMetricsRecorder::GetInstance() { + static base::NoDestructor<AddSupervisionMetricsRecorder> instance_; + return instance_.get(); +} + +void AddSupervisionMetricsRecorder::RecordAddSupervisionEnrollment( + EnrollmentState action) { + base::UmaHistogramEnumeration("AddSupervisionDialog.Enrollment", action); + switch (action) { + case EnrollmentState::kInitiated: + DCHECK(!EnrollmentCompleted()) + << "The user should not be enrolled in supervision at the start of " + "the Add Supervision process."; + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_Launched")); + start_time_ = clock_->NowTicks(); + break; + case EnrollmentState::kCompleted: + DCHECK(EnrollmentCompleted()) + << "Add Supervision enrollment should be completed before recording " + "kCompleted UMA metric."; + RecordUserTime("AddSupervisionDialog.EnrollmentCompletedUserTime"); + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_EnrollmentCompleted")); + break; + case EnrollmentState::kSignedOut: + DCHECK(EnrollmentCompleted()) + << "There should be no way for the user to attempt sign out from " + "within the Add Supervision dialog without completing supervision " + "enrollment."; + RecordUserTime("AddSupervisionDialog.SignoutCompletedUserTime"); + base::RecordAction(base::UserMetricsAction( + "AddSupervisionDialog_AttemptedSignoutAfterEnrollment")); + break; + case EnrollmentState::kClosed: + DCHECK(!EnrollmentCompleted()) + << "There should be no way to close the Add Supervision dialog " + "without signing out after supervision enrollment has completed."; + RecordUserTime("AddSupervisionDialog.EnrollmentNotCompletedUserTime"); + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_Closed")); + break; + case EnrollmentState::kSwitchedAccounts: + DCHECK(!EnrollmentCompleted()) << "The only way for the user to switch " + "accounts is before enrollment"; + RecordUserTime("AddSupervisionDialog.EnrollmentNotCompletedUserTime"); + base::RecordAction( + base::UserMetricsAction("AddSupervisionDialog_SwitchedAccounts")); + break; + } +} + +void AddSupervisionMetricsRecorder::SetClockForTesting( + const base::TickClock* tick_clock) { + clock_ = tick_clock; +} + +AddSupervisionMetricsRecorder::AddSupervisionMetricsRecorder() + : clock_(base::DefaultTickClock::GetInstance()) {} + +void AddSupervisionMetricsRecorder::RecordUserTime( + const char* metric_name) const { + DCHECK(!start_time_.is_null()) << "start_time_ has not been initialized."; + base::TimeDelta duration = clock_->NowTicks() - start_time_; + base::UmaHistogramLongTimes(metric_name, duration); +} diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h new file mode 100644 index 00000000000..600f4b87324 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h @@ -0,0 +1,66 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_METRICS_RECORDER_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_METRICS_RECORDER_H_ + +#include "base/no_destructor.h" +#include "base/time/time.h" + +namespace base { +class TickClock; +} + +// Records UMA metrics for users going through the Add Supervision process. +class AddSupervisionMetricsRecorder { + public: + // These enum values represent the state that the user has attained while + // going through the Add Supervision dialog. + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum class EnrollmentState { + // Recorded when user opens Add Supervision dialog. + kInitiated = 0, + // Recorded when user successfully enrolls in supervision. + kCompleted = 1, + // Recorded when user clicks "Sign out" after enrollment in the dialog. + kSignedOut = 2, + // Recorded when user closes the dialog without enrollment, excluding sign + // out. + kClosed = 3, + // Recorded when user signs out to switch accounts. + kSwitchedAccounts = 4, + // Add future entries above this comment, in sync with enums.xml. + // Update kMaxValue to the last value. + kMaxValue = kSwitchedAccounts + }; + + static AddSupervisionMetricsRecorder* GetInstance(); + + // Records UMA metrics for users going through the Add Supervision process. + void RecordAddSupervisionEnrollment(EnrollmentState action); + + // Method intended for testing purposes only. + // Set clock used for timing to enable manipulation during tests. + void SetClockForTesting(const base::TickClock* tick_clock); + + private: + friend class base::NoDestructor<AddSupervisionMetricsRecorder>; + + AddSupervisionMetricsRecorder(); + + // Records UMA metric of how long the user spends in the Add Supervision + // process in milliseconds. + void RecordUserTime(const char* metric_name) const; + + // Points to the base::DefaultTickClock by default. + const base::TickClock* clock_; + + // Records when the user initiates the Add Supervision process. + base::TimeTicks start_time_; + + DISALLOW_COPY_AND_ASSIGN(AddSupervisionMetricsRecorder); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_METRICS_RECORDER_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder_browsertest.cc new file mode 100644 index 00000000000..3071dacac19 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder_browsertest.cc @@ -0,0 +1,294 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/metrics/histogram_tester.h" +#include "base/test/metrics/user_action_tester.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_mock_time_task_runner.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/constants/chromeos_features.h" +#include "content/public/test/test_web_ui.h" + +namespace chromeos { + +// This browser test class is for the Add Supervision metrics recorder. +class AddSupervisionMetricsRecorderTest : public InProcessBrowserTest { + public: + AddSupervisionMetricsRecorderTest() = default; + ~AddSupervisionMetricsRecorderTest() override = default; + + void SetUp() override { + feature_list_.InitAndEnableFeature( + chromeos::features::kParentalControlsSettings); + InProcessBrowserTest::SetUp(); + } + + void SetUpOnMainThread() override { + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + test_web_ui_.set_web_contents(web_contents); + } + + void ShowAddSupervisionDialog() { + content::WebContents* web_contents = test_web_ui_.GetWebContents(); + AddSupervisionDialog::Show(web_contents->GetTopLevelNativeWindow()); + } + + void CloseNowForTesting() { + AddSupervisionDialog* instance = + static_cast<AddSupervisionDialog*>(AddSupervisionDialog::GetInstance()); + instance->CloseNowForTesting(); + } + + void CloseAddSupervisionDialog() { + bool out_close_dialog = + AddSupervisionDialog::GetInstance()->OnDialogCloseRequested(); + EXPECT_TRUE(out_close_dialog); + CloseNowForTesting(); + } + + void NotifySupervisionEnabled() { + add_supervision::mojom::AddSupervisionHandlerRequest request; + AddSupervisionUI add_supervision_ui(&test_web_ui_); + AddSupervisionHandler add_supervision_handler( + std::move(request), &test_web_ui_, &add_supervision_ui); + add_supervision_handler.NotifySupervisionEnabled(); + } + + void LogOutAndClose() { + LogOutHelper(); + CloseNowForTesting(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(AddSupervisionMetricsRecorderTest); + + base::test::ScopedFeatureList feature_list_; + content::TestWebUI test_web_ui_; +}; + +IN_PROC_BROWSER_TEST_F(AddSupervisionMetricsRecorderTest, HistogramTest) { + base::HistogramTester histogram_tester; + + // Should see 0 Add Supervision enrollment metrics at first. + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 0); + + // Simulate the user opening the Add Supervision dialog and closing it. + ShowAddSupervisionDialog(); + + // Should see 1 Add Supervision process initiated. + histogram_tester.ExpectUniqueSample( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 1); + + CloseAddSupervisionDialog(); + + // Should see 1 Add Supervision process closed. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kClosed, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 2); + + // Simulate the user opening the Add Supervision dialog and signing out to + // switch accounts. + ShowAddSupervisionDialog(); + + // Should see 2 Add Supervision processes initiated. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated, 2); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 3); + + LogOutAndClose(); + + // Should see 1 switch accounts attempt. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kSwitchedAccounts, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 4); + + // Simulate the user opening the Add Supervision dialog, enrolling in + // supervision and signing out. + ShowAddSupervisionDialog(); + + // Should see 3 Add Supervision processes initiated. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated, 3); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 5); + + NotifySupervisionEnabled(); + + // Should see 1 Add Supervision process completed. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kCompleted, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 6); + + LogOutAndClose(); + + // Should see 1 sign out attempt. + histogram_tester.ExpectBucketCount( + "AddSupervisionDialog.Enrollment", + AddSupervisionMetricsRecorder::EnrollmentState::kSignedOut, 1); + histogram_tester.ExpectTotalCount("AddSupervisionDialog.Enrollment", 7); +} + +IN_PROC_BROWSER_TEST_F(AddSupervisionMetricsRecorderTest, UserActionTest) { + base::UserActionTester user_action_tester; + // Should see 0 user actions at first. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 0); + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Closed"), + 0); + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_AttemptedSignoutAfterEnrollment"), + 0); + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_EnrollmentCompleted"), + 0); + + // Simulate the user opening the Add Supervision dialog and closing it. + ShowAddSupervisionDialog(); + + // Should see 1 Launched action. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 1); + + CloseAddSupervisionDialog(); + + // Should see 1 Closed action. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Closed"), + 1); + + // Simulate the user opening the Add Supervision dialog and signing out to + // switch accounts. + ShowAddSupervisionDialog(); + + // Should see 2 Launched actions. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 2); + + LogOutAndClose(); + + // Should see 1 switch accounts attempt. + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_SwitchedAccounts"), + 1); + + // Simulate the user opening the Add Supervision dialog, enrolling in + // supervision and signing out. + ShowAddSupervisionDialog(); + + // Should see 3 Launched actions. + EXPECT_EQ(user_action_tester.GetActionCount("AddSupervisionDialog_Launched"), + 3); + + NotifySupervisionEnabled(); + + // Should see 1 EnrollmentCompleted action. + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_EnrollmentCompleted"), + 1); + + LogOutAndClose(); + + // Should see 1 AttemptedSignoutAfterEnrollment action. + EXPECT_EQ(user_action_tester.GetActionCount( + "AddSupervisionDialog_AttemptedSignoutAfterEnrollment"), + 1); +} + +// This browser test class is for the Add Supervision timing metrics. +class AddSupervisionMetricsRecorderTimeTest + : public AddSupervisionMetricsRecorderTest, + public testing::WithParamInterface<int> {}; + +INSTANTIATE_TEST_SUITE_P(AddSupervisionDialogUserTimeInSeconds, + AddSupervisionMetricsRecorderTimeTest, + ::testing::Values(0, 11, 120, 1800)); + +IN_PROC_BROWSER_TEST_P(AddSupervisionMetricsRecorderTimeTest, UserTimingTest) { + base::HistogramTester histogram_tester; + + // Should see 0 Add Supervision timing metrics at first. + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 0); + + // Simulate the user opening the Add Supervision dialog and closing it + // after GetParam() seconds. + scoped_refptr<base::TestMockTimeTaskRunner> task_runner_ = + base::MakeRefCounted<base::TestMockTimeTaskRunner>(); + AddSupervisionMetricsRecorder::GetInstance()->SetClockForTesting( + task_runner_->GetMockTickClock()); + base::TimeDelta duration(base::TimeDelta::FromSeconds(GetParam())); + + // We need to start at some non-zero point in time or else + // DCHECK(!start_time_.is_null()) throws. + task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1)); + ShowAddSupervisionDialog(); + task_runner_->FastForwardBy(duration); + CloseAddSupervisionDialog(); + + // Should see 1 new EnrollmentNotCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", duration, 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 0); + + // Simulate the user opening the Add Supervision dialog and signing out to + // switch accounts after GetParam() seconds. + ShowAddSupervisionDialog(); + task_runner_->FastForwardBy(duration); + LogOutAndClose(); + + // Should see 1 new EnrollmentNotCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", duration, 2); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 2); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 0); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 0); + + // Simulate the user opening the Add Supervision dialog, enrolling in + // supervision after GetParam() seconds and signing out after GetParam() + // seconds. + ShowAddSupervisionDialog(); + task_runner_->FastForwardBy(duration); + NotifySupervisionEnabled(); + task_runner_->FastForwardBy(duration); + LogOutAndClose(); + + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentNotCompletedUserTime", 2); + // Should see 1 new EnrollmentCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", duration, 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.EnrollmentCompletedUserTime", 1); + // Should see 1 new SignoutCompletedUserTime timing. + histogram_tester.ExpectTimeBucketCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 2 * duration, 1); + histogram_tester.ExpectTotalCount( + "AddSupervisionDialog.SignoutCompletedUserTime", 1); +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc index b0dcfb1cfef..c0c3fb9b98f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc @@ -8,14 +8,13 @@ #include <utility> #include "base/bind.h" -#include "base/no_destructor.h" #include "base/system/sys_info.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/views/chrome_web_dialog_view.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h" #include "chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" @@ -34,19 +33,12 @@ namespace { constexpr int kDialogHeightPx = 608; constexpr int kDialogWidthPx = 768; -// Id of System Dialog used to show the Add Supervision flow. -std::string& GetDialogId() { - static base::NoDestructor<std::string> dialog_id; - return *dialog_id; -} // Shows the dialog indicating that user has to sign out if supervision has been // enabled for their account. Returns a boolean indicating whether the // ConfirmSignoutDialog is being shown. bool MaybeShowConfirmSignoutDialog() { - SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile( - ProfileManager::GetPrimaryUserProfile()); - if (service->signout_required_after_supervision_enabled()) { + if (EnrollmentCompleted()) { ConfirmSignoutDialog::Show(); return true; } @@ -94,10 +86,18 @@ void AddSupervisionDialog::Show(gfx::NativeView parent) { // SystemWebDialogDelegate::OnDialogClosed() is called. current_instance = new AddSupervisionDialog(); - GetDialogId() = current_instance->Id(); - current_instance->ShowSystemDialogForBrowserContext( ProfileManager::GetPrimaryUserProfile(), parent); + + // Record UMA metric that user has initiated the Add Supervision process. + AddSupervisionMetricsRecorder::GetInstance()->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kInitiated); +} + +// static +SystemWebDialogDelegate* AddSupervisionDialog::GetInstance() { + return SystemWebDialogDelegate::FindInstance( + chrome::kChromeUIAddSupervisionURL); } // static @@ -105,7 +105,14 @@ void AddSupervisionDialog::Close() { SystemWebDialogDelegate* current_instance = GetInstance(); if (current_instance) { current_instance->Close(); - GetDialogId() = std::string(); + } +} + +void AddSupervisionDialog::CloseNowForTesting() { + SystemWebDialogDelegate* current_instance = GetInstance(); + if (current_instance) { + DCHECK(dialog_window()) << "No dialog window instance currently set."; + views::Widget::GetWidgetForNativeWindow(dialog_window())->CloseNow(); } } @@ -117,20 +124,16 @@ void AddSupervisionDialog::GetDialogSize(gfx::Size* size) const { size->SetSize(kDialogWidthPx, kDialogHeightPx); } -bool AddSupervisionDialog::OnDialogCloseRequested() { +bool AddSupervisionDialog::CanCloseDialog() const { bool showing_confirm_dialog = MaybeShowConfirmSignoutDialog(); return !showing_confirm_dialog; } -void AddSupervisionDialog::OnCloseContents(content::WebContents* source, - bool* out_close_dialog) { - // This code gets called by a different path that OnDialogCloseRequested(), - // and actually masks the call to OnDialogCloseRequested() the first time the - // user clicks on the [x]. Because the first [x] click comes here, we need to - // show the confirmation dialog here and signal the caller to possibly close - // the dialog. Subsequent clicks on [x] during the lifetime of the dialog - // will result in calls to OnDialogCloseRequested(). - *out_close_dialog = OnDialogCloseRequested(); +bool AddSupervisionDialog::OnDialogCloseRequested() { + // Record UMA metric that user has closed the Add Supervision dialog. + AddSupervisionMetricsRecorder::GetInstance()->RecordAddSupervisionEnrollment( + AddSupervisionMetricsRecorder::EnrollmentState::kClosed); + return true; } AddSupervisionDialog::AddSupervisionDialog() @@ -139,11 +142,6 @@ AddSupervisionDialog::AddSupervisionDialog() AddSupervisionDialog::~AddSupervisionDialog() = default; -// static -SystemWebDialogDelegate* AddSupervisionDialog::GetInstance() { - return SystemWebDialogDelegate::FindInstance(GetDialogId()); -} - // AddSupervisionUI implementations. AddSupervisionUI::AddSupervisionUI(content::WebUI* web_ui) @@ -188,7 +186,7 @@ void AddSupervisionUI::SetupResources() { "add_supervision.mojom-lite.js", IDR_ADD_SUPERVISION_MOJOM_LITE_JS); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_ADD_SUPERVISION_HTML); source->AddString("webviewUrl", supervision_url_.spec()); source->AddString("eventOriginFilter", supervision_url_.GetOrigin().spec()); diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h index 25a2c1b2068..02afc8e1d8e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h @@ -27,24 +27,30 @@ class AddSupervisionDialog : public SystemWebDialogDelegate { // no-op. static void Show(gfx::NativeView parent); - // Closes the dialog, if the dialog doesn't exist, this function is a + static SystemWebDialogDelegate* GetInstance(); + + // Closes the dialog; if the dialog doesn't exist, this function is a // no-op. + // This is only called when the user clicks "Cancel", not the "x" in the top + // right. static void Close(); + // Deletes this dialog window. + // Currently only used by AddSupervisionMetricsRecorderTest browser test to + // simulate closing the dialog cleanly. + void CloseNowForTesting(); + // ui::WebDialogDelegate: ui::ModalType GetDialogModalType() const override; void GetDialogSize(gfx::Size* size) const override; + bool CanCloseDialog() const override; bool OnDialogCloseRequested() override; - void OnCloseContents(content::WebContents* source, - bool* out_close_dialog) override; protected: AddSupervisionDialog(); ~AddSupervisionDialog() override; private: - static SystemWebDialogDelegate* GetInstance(); - DISALLOW_COPY_AND_ASSIGN(AddSupervisionDialog); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc index 9ee08568e9b..b0754f4a57b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc @@ -7,11 +7,10 @@ #include <memory> #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/ui/browser_dialogs.h" +#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" -#include "components/user_manager/user_manager.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/resources/grit/ui_resources.h" @@ -35,15 +34,12 @@ ConfirmSignoutDialog::ConfirmSignoutDialog() { views::LayoutProvider::Get()->GetDialogInsetsForContentType( views::DialogContentType::TEXT, views::DialogContentType::TEXT))); - base::string16 given_name = - user_manager::UserManager::Get()->GetPrimaryUser()->GetGivenName(); - - // |body_| will be owned by the views system. + // |body| will be owned by the views system. views::Label* body = new views::Label; body->SetHorizontalAlignment(gfx::ALIGN_LEFT); body->SetMultiLine(true); - body->SetText(l10n_util::GetStringFUTF16(IDS_ADD_SUPERVISION_EXIT_DIALOG_BODY, - given_name)); + body->SetText( + l10n_util::GetStringUTF16(IDS_ADD_SUPERVISION_EXIT_DIALOG_BODY)); body->SizeToFit(kDialogBodyTextWidth); AddChildView(body); } @@ -59,7 +55,7 @@ base::string16 ConfirmSignoutDialog::GetWindowTitle() const { } bool ConfirmSignoutDialog::Accept() { - chrome::AttemptUserExit(); + LogOutHelper(); return true; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc index de20b5eedd0..3c918789930 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc @@ -16,6 +16,7 @@ #include "base/json/json_writer.h" #include "base/linux_util.h" #include "base/memory/ref_counted_memory.h" +#include "base/metrics/histogram_macros.h" #include "base/process/process_iterator.h" #include "base/strings/string_split.h" #include "base/strings/string_tokenizer.h" @@ -55,9 +56,24 @@ constexpr char kKeyTasks[] = "tasks"; constexpr char kLastTracingModelName[] = "last_tracing_model.json"; +enum class Action { + kShown = 0, + kBuildSucceeded = 1, + kBuildFailed = 2, + kInitialLoadSucceeded = 3, + kInitialLoadFailed = 4, + kLoadSucceeded = 5, + kLoadFailed = 6, + kMaxValue = kLoadFailed, +}; + +void UpdateStatistics(Action action) { + UMA_HISTOGRAM_ENUMERATION("Arc.Tracing.Tool", action); +} + // Maximum interval to display. constexpr base::TimeDelta kMaxIntervalToDisplay = - base::TimeDelta::FromSecondsD(3.0); + base::TimeDelta::FromSecondsD(5.0); base::FilePath GetLastTracingModelPath(Profile* profile) { DCHECK(profile); @@ -78,9 +94,12 @@ std::pair<base::Value, std::string> MaybeLoadLastGraphicsModel( arc::ArcTracingGraphicsModel graphics_model; base::DictionaryValue* dictionary = nullptr; model->GetAsDictionary(&dictionary); - if (!graphics_model.LoadFromValue(*dictionary)) + if (!graphics_model.LoadFromValue(*dictionary)) { + UpdateStatistics(Action::kInitialLoadFailed); return std::make_pair(base::Value(), "Failed to load last tracing model"); + } + UpdateStatistics(Action::kInitialLoadSucceeded); return std::make_pair(std::move(*model), "Loaded last tracing model"); } @@ -168,15 +187,19 @@ std::pair<base::Value, std::string> BuildGraphicsModel( (time_min_clamped - base::TimeTicks()).InMicroseconds(), (time_max - base::TimeTicks()).InMicroseconds()); - if (!common_model.Build(data)) + if (!common_model.Build(data)) { + UpdateStatistics(Action::kBuildFailed); return std::make_pair(base::Value(), "Failed to process tracing data"); + } system_stat_collector->Flush(time_min, time_max, &common_model.system_model()); arc::ArcTracingGraphicsModel graphics_model; - if (!graphics_model.Build(common_model)) + if (!graphics_model.Build(common_model)) { + UpdateStatistics(Action::kBuildFailed); return std::make_pair(base::Value(), "Failed to build tracing model"); + } UpdateThreads(&graphics_model.system_model().thread_map()); @@ -194,16 +217,20 @@ std::pair<base::Value, std::string> BuildGraphicsModel( << "."; } + UpdateStatistics(Action::kBuildSucceeded); return std::make_pair(std::move(*model), "Tracing model is ready"); } std::pair<base::Value, std::string> LoadGraphicsModel( const std::string& json_text) { arc::ArcTracingGraphicsModel graphics_model; - if (!graphics_model.LoadFromJson(json_text)) + if (!graphics_model.LoadFromJson(json_text)) { + UpdateStatistics(Action::kLoadFailed); return std::make_pair(base::Value(), "Failed to load tracing model"); + } std::unique_ptr<base::DictionaryValue> model = graphics_model.Serialize(); + UpdateStatistics(Action::kLoadSucceeded); return std::make_pair(std::move(*model), "Tracing model is loaded"); } @@ -211,8 +238,7 @@ std::pair<base::Value, std::string> LoadGraphicsModel( ArcGraphicsTracingHandler::ArcGraphicsTracingHandler() : wm_helper_(exo::WMHelper::HasInstance() ? exo::WMHelper::GetInstance() - : nullptr), - weak_ptr_factory_(this) { + : nullptr) { DCHECK(wm_helper_); aura::Window* const current_active = wm_helper_->GetActiveWindow(); @@ -221,6 +247,8 @@ ArcGraphicsTracingHandler::ArcGraphicsTracingHandler() current_active, nullptr); } wm_helper_->AddActivationObserver(this); + + UpdateStatistics(Action::kShown); } ArcGraphicsTracingHandler::~ArcGraphicsTracingHandler() { @@ -428,8 +456,9 @@ void ArcGraphicsTracingHandler::OnTracingStopped( base::RefCountedString* trace_data) { std::string string_data; string_data.swap(trace_data->data()); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&BuildGraphicsModel, std::move(string_data), std::move(tasks_info_), std::move(system_stat_colletor_), tracing_time_min_, tracing_time_max_, @@ -450,8 +479,9 @@ void ArcGraphicsTracingHandler::OnGraphicsModelReady( } void ArcGraphicsTracingHandler::HandleReady(const base::ListValue* args) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&MaybeLoadLastGraphicsModel, GetLastTracingModelPath(Profile::FromWebUI(web_ui()))), base::BindOnce(&ArcGraphicsTracingHandler::OnGraphicsModelReady, @@ -476,8 +506,9 @@ void ArcGraphicsTracingHandler::HandleLoadFromText( return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&LoadGraphicsModel, std::move(args->GetList()[0].GetString())), base::BindOnce(&ArcGraphicsTracingHandler::OnGraphicsModelReady, diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h index 4f613c1a1a7..bd774e39149 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h @@ -119,7 +119,7 @@ class ArcGraphicsTracingHandler : public content::WebUIMessageHandler, // Information about tasks, title and icon. base::DictionaryValue tasks_info_; - base::WeakPtrFactory<ArcGraphicsTracingHandler> weak_ptr_factory_; + base::WeakPtrFactory<ArcGraphicsTracingHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ArcGraphicsTracingHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc index f144257e56f..9610dee0f41 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc @@ -25,7 +25,7 @@ constexpr char kArcGraphicsTracingCssPath[] = "arc_graphics_tracing.css"; content::WebUIDataSource* CreateDataSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIArcGraphicsTracingHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_ARC_GRAPHICS_TRACING_HTML); source->AddResourcePath(kArcGraphicsTracingJsPath, IDR_ARC_GRAPHICS_TRACING_JS); diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc index 2e65bdfe483..03a052c6863 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc @@ -8,7 +8,7 @@ #include <string> #include <utility> -#include "ash/public/interfaces/voice_interaction_controller.mojom.h" +#include "ash/public/mojom/voice_interaction_controller.mojom.h" #include "base/bind.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" @@ -20,7 +20,6 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" -#include "components/arc/arc_prefs.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "content/public/browser/host_zoom_map.h" @@ -29,7 +28,9 @@ #include "content/public/browser/web_ui_data_source.h" #include "content/public/common/content_features.h" #include "net/base/url_util.h" +#include "ui/chromeos/resources/grit/ui_chromeos_resources.h" #include "ui/views/widget/widget.h" +#include "ui/wm/core/window_animations.h" namespace chromeos { @@ -76,11 +77,14 @@ AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui) base::DictionaryValue localized_strings; assistant_handler_ptr_->GetLocalizedStrings(&localized_strings); source->AddLocalizedStrings(localized_strings); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("assistant_optin.js", IDR_ASSISTANT_OPTIN_JS); source->AddResourcePath("assistant_logo.png", IDR_ASSISTANT_LOGO_PNG); source->AddBoolean("hotwordDspAvailable", chromeos::IsHotwordDspAvailable()); source->SetDefaultResource(IDR_ASSISTANT_OPTIN_HTML); + source->AddResourcePath("voice_match_animation.json", + IDR_ASSISTANT_VOICE_MATCH_ANIMATION); + source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';"); content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); // Do not zoom for Assistant opt-in web contents. @@ -135,6 +139,17 @@ void AssistantOptInDialog::Show( g_dialog->ShowSystemDialog(); } +// static +bool AssistantOptInDialog::BounceIfActive() { + if (!g_dialog) + return false; + + g_dialog->Focus(); + wm::AnimateWindow(g_dialog->dialog_window(), + wm::WINDOW_ANIMATION_TYPE_BOUNCE); + return true; +} + AssistantOptInDialog::AssistantOptInDialog( ash::FlowType type, ash::AssistantSetup::StartAssistantOptInFlowCallback callback) @@ -172,7 +187,7 @@ void AssistantOptInDialog::OnDialogClosed(const std::string& json_retval) { PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); const bool completed = - prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled) && + prefs->GetBoolean(chromeos::assistant::prefs::kAssistantEnabled) && (prefs->GetInteger(assistant::prefs::kAssistantConsentStatus) == assistant::prefs::ConsentStatus::kActivityControlAccepted); std::move(callback_).Run(completed); diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h index d4b7b6b90e0..a93c2483e26 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h @@ -48,6 +48,9 @@ class AssistantOptInDialog : public SystemWebDialogDelegate { ash::AssistantSetup::StartAssistantOptInFlowCallback callback = base::DoNothing()); + // Returns true and bounces the window if the dialog is active. + static bool BounceIfActive(); + protected: AssistantOptInDialog( ash::FlowType type, diff --git a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc index 4287e686189..96f8106a00d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc @@ -13,6 +13,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "chromeos/audio/cras_audio_handler.h" +#include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/services/assistant/public/features.h" #include "components/arc/arc_prefs.h" #include "components/consent_auditor/consent_auditor.h" @@ -39,12 +40,12 @@ bool IsPreferenceDefaultEnabled(const PrefService* prefs, bool IsScreenContextDefaultEnabled(PrefService* prefs) { return IsPreferenceDefaultEnabled( - prefs, arc::prefs::kVoiceInteractionContextEnabled); + prefs, chromeos::assistant::prefs::kAssistantContextEnabled); } bool IsScreenContextToggleDisabled(PrefService* prefs) { return prefs->IsManagedPreference( - arc::prefs::kVoiceInteractionContextEnabled); + chromeos::assistant::prefs::kAssistantContextEnabled); } } // namespace @@ -244,8 +245,8 @@ bool IsVoiceMatchEnforcedOff(const PrefService* prefs) { // If the hotword preference is managed to always disabled, then we should not // show Voice Match flow. return prefs->IsManagedPreference( - arc::prefs::kVoiceInteractionHotwordEnabled) && - !prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled); + assistant::prefs::kAssistantHotwordEnabled) && + !prefs->GetBoolean(assistant::prefs::kAssistantHotwordEnabled); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc index 326632a3125..b65490702e4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc @@ -103,7 +103,7 @@ BluetoothPairingDialogUI::BluetoothPairingDialogUI(content::WebUI* web_ui) AddBluetoothStrings(source); source->AddLocalizedString("title", IDS_SETTINGS_BLUETOOTH_PAIR_DEVICE_TITLE); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->SetDefaultResource(IDR_BLUETOOTH_PAIRING_DIALOG_VULCANIZED_HTML); source->AddResourcePath("crisper.js", diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h index 3fd8630b818..3a39cb5c7ab 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h +++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog_browsertest-inl.h @@ -54,9 +54,10 @@ void BluetoothPairingDialogTest::ShowDialog() { const bool kNotPaired = false; const bool kNotConnected = false; - mock_device_.reset(new testing::NiceMock<device::MockBluetoothDevice>( - nullptr, 0, "Bluetooth 2.0 Mouse", "28:CF:DA:00:00:00", kNotPaired, - kNotConnected)); + mock_device_ = + std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>( + nullptr, 0, "Bluetooth 2.0 Mouse", "28:CF:DA:00:00:00", kNotPaired, + kNotConnected); EXPECT_CALL(*mock_adapter_, GetDevice(testing::_)) .WillRepeatedly(testing::Return(mock_device_.get())); diff --git a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc index c6110b2fde4..8a40f0cbdba 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc @@ -45,15 +45,15 @@ content::WebUIDataSource* CreateCameraUIHTMLSource() { IDR_CAMERA_CAMERA_METADATA_MOJOM_LITE_JS); source->AddResourcePath("src/js/mojo/camera_metadata_tags.mojom-lite.js", IDR_CAMERA_CAMERA_METADATA_TAGS_MOJOM_LITE_JS); - source->AddResourcePath("src/js/mojo/cros_image_capture.mojom-lite.js", - IDR_CAMERA_CROS_IMAGE_CAPTURE_MOJOM_LITE_JS); + source->AddResourcePath("src/js/mojo/camera_app.mojom-lite.js", + IDR_CAMERA_APP_MOJOM_LITE_JS); source->AddResourcePath("src/js/mojo/mojo_bindings_lite.js", IDR_MOJO_MOJO_BINDINGS_LITE_JS); // Add System Web App resources. source->AddResourcePath("pwa.html", IDR_PWA_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/DEPS b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/DEPS new file mode 100644 index 00000000000..55ca2bd3041 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+chromeos/services/cellular_setup", +] diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc index 4243362e1fc..60d1b64de38 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog.h" #include "base/bind.h" +#include "base/supports_user_data.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" @@ -12,9 +13,10 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/cellular_setup_resources.h" #include "chrome/grit/cellular_setup_resources_map.h" -#include "chromeos/services/cellular_setup/public/mojom/constants.mojom.h" +#include "chromeos/services/cellular_setup/cellular_setup_base.h" +#include "chromeos/services/cellular_setup/cellular_setup_impl.h" #include "content/public/browser/web_ui_data_source.h" -#include "services/service_manager/public/cpp/connector.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/aura/window.h" namespace chromeos { @@ -30,6 +32,37 @@ constexpr int kDialogWidthPx = 650; CellularSetupDialog* dialog_instance = nullptr; +// Used to attach an instance of the CellularSetup service to a BrowserContext. +class CellularSetupServiceHolder : public base::SupportsUserData::Data { + public: + CellularSetupServiceHolder() = default; + ~CellularSetupServiceHolder() override = default; + + void BindReceiver(mojo::PendingReceiver<mojom::CellularSetup> receiver) { + service_.BindRequest(std::move(receiver)); + } + + private: + CellularSetupImpl service_; + + DISALLOW_COPY_AND_ASSIGN(CellularSetupServiceHolder); +}; + +const char kCellularSetupServiceHolderKey[] = "cellular_setup_service_holder"; + +CellularSetupServiceHolder* GetOrCreateServiceHolder( + content::BrowserContext* browser_context) { + auto* holder = static_cast<CellularSetupServiceHolder*>( + browser_context->GetUserData(kCellularSetupServiceHolderKey)); + if (!holder) { + auto new_holder = std::make_unique<CellularSetupServiceHolder>(); + holder = new_holder.get(); + browser_context->SetUserData(kCellularSetupServiceHolderKey, + std::move(new_holder)); + } + return holder; +} + } // namespace // static @@ -78,7 +111,7 @@ CellularSetupDialogUI::CellularSetupDialogUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUICellularSetupHost); chromeos::cellular_setup::AddLocalizedStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_CELLULAR_SETUP_CELLULAR_SETUP_DIALOG_HTML); // Note: The |kCellularSetupResourcesSize| and |kCellularSetupResources| @@ -100,10 +133,8 @@ CellularSetupDialogUI::~CellularSetupDialogUI() = default; void CellularSetupDialogUI::BindCellularSetup( mojom::CellularSetupRequest request) { - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()); - connector->BindInterface(mojom::kServiceName, std::move(request)); + GetOrCreateServiceHolder(web_ui()->GetWebContents()->GetBrowserContext()) + ->BindReceiver(std::move(request)); } } // namespace cellular_setup diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc index 981076b2c11..994d31c045b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc @@ -23,7 +23,17 @@ constexpr LocalizedString kLocalizedStringsWithoutPlaceholders[] = { {"finish", IDS_CELLULAR_SETUP_FINISH_LABEL}, {"tryAgain", IDS_CELLULAR_SETUP_TRY_AGAIN_LABEL}, {"simDetectPageTitle", IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_TITLE}, - {"provisioningPageTitle", IDS_CELLULAR_SETUP_PROVISIONING_PAGE_TITLE}, + {"simDetectPageErrorTitle", IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_ERROR_TITLE}, + {"simDetectPageErrorMessage", + IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_ERROR_MESSAGE}, + {"provisioningPageLoadingTitle", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_LOADING_TITLE}, + {"provisioningPageActiveTitle", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_ACTIVE_TITLE}, + {"provisioningPageErrorTitle", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_ERROR_TITLE}, + {"provisioningPageErrorMessage", + IDS_CELLULAR_SETUP_PROVISIONING_PAGE_ERROR_MESSAGE}, {"finalPageTitle", IDS_CELLULAR_SETUP_FINAL_PAGE_TITLE}, {"finalPageMessage", IDS_CELLULAR_SETUP_FINAL_PAGE_MESSAGE}, {"finalPageErrorTitle", IDS_CELLULAR_SETUP_FINAL_PAGE_ERROR_TITLE}, diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc index 5eaf0f3a48c..6ac7d19882b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc @@ -178,7 +178,7 @@ class MobileSetupUIHTMLSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override { return "text/html"; } bool ShouldAddContentSecurityPolicy() override { return false; } @@ -189,7 +189,7 @@ class MobileSetupUIHTMLSource : public content::URLDataSource { } private: - base::WeakPtrFactory<MobileSetupUIHTMLSource> weak_ptr_factory_; + base::WeakPtrFactory<MobileSetupUIHTMLSource> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MobileSetupUIHTMLSource); }; @@ -251,7 +251,7 @@ class MobileSetupHandler : public content::WebUIMessageHandler, // connection state. This value is reflected in portal webui for lte networks. // Initial value is true. bool lte_portal_reachable_; - base::WeakPtrFactory<MobileSetupHandler> weak_ptr_factory_; + base::WeakPtrFactory<MobileSetupHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MobileSetupHandler); }; @@ -262,7 +262,7 @@ class MobileSetupHandler : public content::WebUIMessageHandler, // //////////////////////////////////////////////////////////////////////////////// -MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() : weak_ptr_factory_(this) {} +MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() {} std::string MobileSetupUIHTMLSource::GetSource() { return chrome::kChromeUIMobileSetupHost; @@ -270,7 +270,7 @@ std::string MobileSetupUIHTMLSource::GetSource() { void MobileSetupUIHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // Sanity checks that activation was requested for an appropriate network. const NetworkState* network = @@ -362,10 +362,7 @@ void MobileSetupUIHTMLSource::StartDataRequest( // //////////////////////////////////////////////////////////////////////////////// MobileSetupHandler::MobileSetupHandler() - : type_(TYPE_UNDETERMINED), - active_(false), - lte_portal_reachable_(true), - weak_ptr_factory_(this) {} + : type_(TYPE_UNDETERMINED), active_(false), lte_portal_reachable_(true) {} MobileSetupHandler::~MobileSetupHandler() { Reset(); 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 e3c74610424..36919052a60 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 @@ -55,7 +55,7 @@ CertificateManagerDialogUI::CertificateManagerDialogUI(content::WebUI* web_ui) user_manager::UserManager::Get()->IsLoggedInAsKioskApp() || user_manager::UserManager::Get()->IsLoggedInAsArcKioskApp()); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_CERT_MANAGER_DIALOG_HTML); source->DisableContentSecurityPolicy(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc index a2b95c06332..52894b68f0e 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc @@ -18,7 +18,7 @@ using content::BrowserThread; namespace chromeos { -CryptohomeWebUIHandler::CryptohomeWebUIHandler() : weak_ptr_factory_(this) {} +CryptohomeWebUIHandler::CryptohomeWebUIHandler() {} CryptohomeWebUIHandler::~CryptohomeWebUIHandler() {} @@ -40,7 +40,7 @@ void CryptohomeWebUIHandler::OnPageLoaded(const base::ListValue* args) { cryptohome_client->Pkcs11IsTpmTokenReady( GetCryptohomeBoolCallback("pkcs11-is-tpm-token-ready")); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::IO}, base::Bind(&crypto::IsTPMTokenReady, base::Closure()), base::Bind(&CryptohomeWebUIHandler::DidGetNSSUtilInfoOnUIThread, diff --git a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h index b470724610c..890066643bb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h @@ -49,7 +49,7 @@ class CryptohomeWebUIHandler : public content::WebUIMessageHandler { void SetCryptohomeProperty(const std::string& destination_id, const base::Value& value); - base::WeakPtrFactory<CryptohomeWebUIHandler> weak_ptr_factory_; + base::WeakPtrFactory<CryptohomeWebUIHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CryptohomeWebUIHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc index cce737b51cf..686d55faf55 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc @@ -34,6 +34,7 @@ #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/drive/drive_notification_manager_factory.h" +#include "chrome/browser/file_util_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -53,7 +54,6 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" -#include "content/public/browser/system_connector.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" @@ -297,8 +297,7 @@ void ZipLogs(Profile* profile, // Class to handle messages from chrome://drive-internals. class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { public: - DriveInternalsWebUIHandler() - : last_sent_event_id_(-1), weak_ptr_factory_(this) {} + DriveInternalsWebUIHandler() : last_sent_event_id_(-1) {} ~DriveInternalsWebUIHandler() override {} @@ -694,8 +693,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { // Propagate the amount of local free space in bytes. base::FilePath home_path; if (base::PathService::Get(base::DIR_HOME, &home_path)) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&base::SysInfo::AmountOfFreeDiskSpace, home_path), base::BindOnce(&DriveInternalsWebUIHandler::OnGetFreeDiskSpace, weak_ptr_factory_.GetWeakPtr())); @@ -793,8 +794,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { "updateOtherServiceLogsUrl", base::Value(net::FilePathToFileURL(log_path.DirName()).spec())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetServiceLogContents, log_path, service_log_file_inode_, last_sent_line_number_), base::BindOnce(&DriveInternalsWebUIHandler::OnServiceLogRead, @@ -852,8 +855,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { const base::FilePath root_path = drive::util::GetCacheRootPath(profile()).DirName(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetGCacheContents, root_path), base::BindOnce(&DriveInternalsWebUIHandler::OnGetGCacheContents, weak_ptr_factory_.GetWeakPtr())); @@ -966,7 +971,7 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler { // Service log file is being parsed. bool service_log_file_is_processing_ = false; - base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_; + base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DriveInternalsWebUIHandler); }; @@ -983,8 +988,10 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer { drive_internals_(std::move(drive_internals)) {} void Start() { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::BindOnce(&LogsZipper::EnumerateLogFiles, logs_directory_, zip_path_), base::BindOnce(&LogsZipper::ZipLogFiles, base::Unretained(this))); @@ -997,7 +1004,7 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer { (new ZipFileCreator( base::BindRepeating(&LogsZipper::OnZipDone, base::Unretained(this)), logs_directory_, files, zip_path_)) - ->Start(content::GetSystemConnector()); + ->Start(LaunchFileUtilService()); } static std::vector<base::FilePath> EnumerateLogFiles( @@ -1040,8 +1047,9 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer { } void CleanUp() { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), zip_path_, false)); download_notifier_.reset(); diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc index 85c54f11143..1c6ecadb2f3 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc @@ -198,8 +198,7 @@ DeviceEmulatorMessageHandler::DeviceEmulatorMessageHandler() : fake_bluetooth_device_client_( static_cast<bluez::FakeBluetoothDeviceClient*>( bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient())), - fake_power_manager_client_(chromeos::FakePowerManagerClient::Get()), - weak_ptr_factory_(this) { + fake_power_manager_client_(chromeos::FakePowerManagerClient::Get()) { device::BluetoothAdapterFactory::GetAdapter( base::BindOnce(&DeviceEmulatorMessageHandler::BluetoothDeviceAdapterReady, weak_ptr_factory_.GetWeakPtr())); @@ -553,9 +552,9 @@ void DeviceEmulatorMessageHandler::RegisterMessages() { } void DeviceEmulatorMessageHandler::OnJavascriptAllowed() { - bluetooth_observer_.reset(new BluetoothObserver(this)); - cras_audio_observer_.reset(new CrasAudioObserver(this)); - power_observer_.reset(new PowerObserver(this)); + bluetooth_observer_ = std::make_unique<BluetoothObserver>(this); + cras_audio_observer_ = std::make_unique<CrasAudioObserver>(this); + power_observer_ = std::make_unique<PowerObserver>(this); system::InputDeviceSettings::Get()->TouchpadExists( base::BindOnce(&DeviceEmulatorMessageHandler::TouchpadExists, diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h index 0aca35bab32..3afd435d960 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h @@ -137,7 +137,7 @@ class DeviceEmulatorMessageHandler : scoped_refptr<device::BluetoothAdapter> bluetooth_adapter_; - base::WeakPtrFactory<DeviceEmulatorMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<DeviceEmulatorMessageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DeviceEmulatorMessageHandler); }; 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 d05e0369f39..46afde2fa0d 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 @@ -6,7 +6,7 @@ #include <utility> -#include "ash/public/interfaces/voice_interaction_controller.mojom.h" +#include "ash/public/mojom/voice_interaction_controller.mojom.h" #include "base/bind.h" #include "base/values.h" #include "chrome/browser/chromeos/assistant/assistant_util.h" diff --git a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc index 912347ea86e..a58bf9524c5 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc @@ -86,7 +86,7 @@ void SetLocalizedStrings(Profile* profile, content::WebUIDataSource* CreateDataSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIFirstRunHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_FIRST_RUN_HTML); source->AddResourcePath(kFirstRunJSPath, IDR_FIRST_RUN_JS); base::DictionaryValue localized_strings; diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc index d5942fc36e6..1a9ff112dda 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc @@ -16,7 +16,7 @@ #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/task/post_task.h" -#include "base/task/thread_pool/thread_pool.h" +#include "base/task/thread_pool/thread_pool_instance.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" @@ -40,9 +40,9 @@ void ImageLoaded( } // namespace -ImageSource::ImageSource() : weak_factory_(this) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, +ImageSource::ImageSource() { + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } @@ -55,7 +55,7 @@ std::string ImageSource::GetSource() { void ImageSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& got_data_callback) { if (!IsWhitelisted(path)) { got_data_callback.Run(nullptr); @@ -64,8 +64,9 @@ void ImageSource::StartDataRequest( const base::FilePath asset_dir(chrome::kChromeOSAssetPath); const base::FilePath image_path = asset_dir.AppendASCII(path); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&base::PathExists, image_path), base::Bind(&ImageSource::StartDataRequestAfterPathExists, weak_factory_.GetWeakPtr(), image_path, got_data_callback)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.h b/chromium/chrome/browser/ui/webui/chromeos/image_source.h index 5d7a5afcec0..4bf09ea101a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/image_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.h @@ -27,11 +27,10 @@ class ImageSource : public content::URLDataSource { // content::URLDataSource implementation. std::string GetSource() override; - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& got_data_callback) - override; + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const content::URLDataSource::GotDataCallback& + got_data_callback) override; std::string GetMimeType(const std::string& path) override; @@ -48,7 +47,7 @@ class ImageSource : public content::URLDataSource { // The background task runner on which file I/O and image decoding are done. scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<ImageSource> weak_factory_; + base::WeakPtrFactory<ImageSource> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ImageSource); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc index e46a6eabfa8..b95907fe477 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc @@ -19,7 +19,29 @@ namespace chromeos { -ConfirmPasswordChangeHandler::ConfirmPasswordChangeHandler() { +namespace { + +const InSessionPasswordChangeManager::Event kIncorrectPasswordEvent = + InSessionPasswordChangeManager::Event::CRYPTOHOME_PASSWORD_CHANGE_FAILURE; + +const InSessionPasswordChangeManager::PasswordSource kPasswordSource = + InSessionPasswordChangeManager::PasswordSource::PASSWORDS_RETYPED; + +// Returns one if it is non-empty, otherwise returns two. +const std::string& FirstNonEmpty(const std::string& one, + const std::string& two) { + return !one.empty() ? one : two; +} + +} // namespace + +ConfirmPasswordChangeHandler::ConfirmPasswordChangeHandler( + const std::string& scraped_old_password, + const std::string& scraped_new_password, + const bool show_spinner_initially) + : scraped_old_password_(scraped_old_password), + scraped_new_password_(scraped_new_password), + show_spinner_initially_(show_spinner_initially) { if (InSessionPasswordChangeManager::IsInitialized()) { InSessionPasswordChangeManager::Get()->AddObserver(this); } @@ -31,25 +53,52 @@ ConfirmPasswordChangeHandler::~ConfirmPasswordChangeHandler() { } } -void ConfirmPasswordChangeHandler::OnEvent( - InSessionPasswordChangeManager::Event event) { - if (event == - InSessionPasswordChangeManager::CRYPTOHOME_PASSWORD_CHANGE_FAILURE) { - AllowJavascript(); - FireWebUIListener("incorrect-old-password"); - } +void ConfirmPasswordChangeHandler::HandleGetInitialState( + const base::ListValue* params) { + const std::string callback_id = params->GetList()[0].GetString(); + + base::Value state(base::Value::Type::DICTIONARY); + state.SetBoolKey("showOldPasswordPrompt", scraped_old_password_.empty()); + state.SetBoolKey("showNewPasswordPrompt", scraped_new_password_.empty()); + state.SetBoolKey("showSpinner", show_spinner_initially_); + + AllowJavascript(); + ResolveJavascriptCallback(base::Value(callback_id), state); } void ConfirmPasswordChangeHandler::HandleChangePassword( const base::ListValue* params) { - const std::string old_password = params->GetList()[0].GetString(); - const std::string new_password = params->GetList()[1].GetString(); - InSessionPasswordChangeManager::Get()->ChangePassword(old_password, - new_password); + const std::string old_password = + FirstNonEmpty(params->GetList()[0].GetString(), scraped_old_password_); + const std::string new_password = + FirstNonEmpty(params->GetList()[1].GetString(), scraped_new_password_); + DCHECK(!old_password.empty() && !new_password.empty()); + + InSessionPasswordChangeManager::Get()->ChangePassword( + old_password, new_password, kPasswordSource); +} + +void ConfirmPasswordChangeHandler::OnEvent( + InSessionPasswordChangeManager::Event event) { + if (event == kIncorrectPasswordEvent) { + // If this event comes before getInitialState, then don't show the spinner + // initially after all - the initial password change attempt using scraped + // passwords already failed before the dialog finished loading. + show_spinner_initially_ = false; + // Discard the scraped old password and ask the user what it really is. + scraped_old_password_.clear(); + if (IsJavascriptAllowed()) { + FireWebUIListener("incorrect-old-password"); + } + } } void ConfirmPasswordChangeHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( + "getInitialState", + base::BindRepeating(&ConfirmPasswordChangeHandler::HandleGetInitialState, + weak_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( "changePassword", base::BindRepeating(&ConfirmPasswordChangeHandler::HandleChangePassword, weak_factory_.GetWeakPtr())); diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h index 7a69e7c624e..f3104499174 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h @@ -16,9 +16,14 @@ class ConfirmPasswordChangeHandler : public content::WebUIMessageHandler, public InSessionPasswordChangeManager::Observer { public: - ConfirmPasswordChangeHandler(); + ConfirmPasswordChangeHandler(const std::string& scraped_old_password, + const std::string& scraped_new_password, + const bool show_spinner_initially); ~ConfirmPasswordChangeHandler() override; + // Called by the JS UI to find out what to show and what size to be. + void HandleGetInitialState(const base::ListValue* params); + // Tries to change the cryptohome password once the confirm-password-change // dialog is filled in and the password change is confirmed. void HandleChangePassword(const base::ListValue* passwords); @@ -30,6 +35,10 @@ class ConfirmPasswordChangeHandler void RegisterMessages() override; private: + std::string scraped_old_password_; + std::string scraped_new_password_; + bool show_spinner_initially_ = false; + base::WeakPtrFactory<ConfirmPasswordChangeHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.cc new file mode 100644 index 00000000000..bba646a609d --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.cc @@ -0,0 +1,201 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h" + +#include <memory> + +#include "base/bind.h" +#include "base/json/json_writer.h" +#include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" +#include "ui/strings/grit/ui_strings.h" + +namespace chromeos { + +namespace { + +PasswordChangeDialog* g_dialog = nullptr; + +ConfirmPasswordChangeDialog* g_confirm_dialog = nullptr; + +UrgentPasswordExpiryNotificationDialog* g_notification_dialog = nullptr; + +constexpr gfx::Size kPasswordChangeSize(768, 640); + +constexpr gfx::Size kUrgentPasswordExpiryNotificationSize = kPasswordChangeSize; + +// The size of the confirm password change UI depends on which passwords were +// scraped and which ones we need to prompt for: +constexpr int kConfirmPasswordsWidth = 520; +constexpr int kConfirmOldPasswordHeight = 230; +constexpr int kConfirmNewPasswordHeight = 310; +constexpr int kConfirmBothPasswordsHeight = 380; + +// Given a desired size, returns the same size if it fits on screen, +// or the closest possible size that will fit on the screen. +gfx::Size FitSizeToDisplay(const gfx::Size& desired) { + const display::Display display = + display::Screen::GetScreen()->GetPrimaryDisplay(); + + gfx::Size display_size = display.size(); + + if (display.rotation() == display::Display::ROTATE_90 || + display.rotation() == display::Display::ROTATE_270) { + display_size = gfx::Size(display_size.height(), display_size.width()); + } + + return gfx::Size(std::min(desired.width(), display_size.width()), + std::min(desired.height(), display_size.height())); +} + +} // namespace + +BasePasswordDialog::BasePasswordDialog(GURL url, gfx::Size desired_size) + : SystemWebDialogDelegate(url, /*title=*/base::string16()), + desired_size_(desired_size) {} + +BasePasswordDialog::~BasePasswordDialog() {} + +void BasePasswordDialog::GetDialogSize(gfx::Size* size) const { + *size = FitSizeToDisplay(desired_size_); +} + +void BasePasswordDialog::AdjustWidgetInitParams( + views::Widget::InitParams* params) { + params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; +} + +ui::ModalType BasePasswordDialog::GetDialogModalType() const { + return ui::ModalType::MODAL_TYPE_SYSTEM; +} + +// static +void PasswordChangeDialog::Show() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_dialog) { + g_dialog->Focus(); + return; + } + g_dialog = new PasswordChangeDialog(); + g_dialog->ShowSystemDialog(); +} + +// static +void PasswordChangeDialog::Dismiss() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_dialog) + g_dialog->Close(); +} + +PasswordChangeDialog::PasswordChangeDialog() + : BasePasswordDialog(GURL(chrome::kChromeUIPasswordChangeUrl), + kPasswordChangeSize) {} + +PasswordChangeDialog::~PasswordChangeDialog() { + DCHECK_EQ(this, g_dialog); + g_dialog = nullptr; +} + +// static +void ConfirmPasswordChangeDialog::Show(const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_confirm_dialog) { + g_confirm_dialog->Focus(); + return; + } + g_confirm_dialog = new ConfirmPasswordChangeDialog( + scraped_old_password, scraped_new_password, show_spinner_initially); + g_confirm_dialog->ShowSystemDialog(); +} + +// static +void ConfirmPasswordChangeDialog::Dismiss() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_confirm_dialog) + g_confirm_dialog->Close(); +} + +ConfirmPasswordChangeDialog::ConfirmPasswordChangeDialog( + const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially) + : BasePasswordDialog( + GURL(chrome::kChromeUIConfirmPasswordChangeUrl), + GetSize(scraped_old_password.empty(), scraped_new_password.empty())), + scraped_old_password_(scraped_old_password), + scraped_new_password_(scraped_new_password), + show_spinner_initially_(show_spinner_initially) {} + +ConfirmPasswordChangeDialog::~ConfirmPasswordChangeDialog() { + DCHECK_EQ(this, g_confirm_dialog); + g_confirm_dialog = nullptr; +} + +// static +gfx::Size ConfirmPasswordChangeDialog::GetSize( + const bool show_old_password_prompt, + const bool show_new_password_prompt) { + const int desired_width = kConfirmPasswordsWidth; + if (show_old_password_prompt && show_new_password_prompt) { + return gfx::Size(desired_width, kConfirmBothPasswordsHeight); + } + if (show_new_password_prompt) { + return gfx::Size(desired_width, kConfirmNewPasswordHeight); + } + // Use the same size for these two cases: + // 1) We scraped new password, but not old, so we need to prompt for that. + // 2) We scraped both passwords, so we don't need to prompt for anything. + + // In case 2, we need to show a spinner. That spinner could be any size, so + // we size it the same as in case 1, because there is a chance that the + // scraped password will be wrong and so we will need to show the old password + // prompt. So it looks best if the dialog is already the right size. + return gfx::Size(desired_width, kConfirmOldPasswordHeight); +} + +void ConfirmPasswordChangeDialog::GetWebUIMessageHandlers( + std::vector<content::WebUIMessageHandler*>* handlers) const { + handlers->push_back(new ConfirmPasswordChangeHandler( + scraped_old_password_, scraped_new_password_, show_spinner_initially_)); +} + +// static +void UrgentPasswordExpiryNotificationDialog::Show() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_notification_dialog) { + g_notification_dialog->Focus(); + return; + } + g_notification_dialog = new UrgentPasswordExpiryNotificationDialog(); + g_notification_dialog->ShowSystemDialog(); +} + +// static +void UrgentPasswordExpiryNotificationDialog::Dismiss() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (g_notification_dialog) + g_notification_dialog->Close(); +} + +UrgentPasswordExpiryNotificationDialog::UrgentPasswordExpiryNotificationDialog() + : BasePasswordDialog( + GURL(chrome::kChromeUIUrgentPasswordExpiryNotificationUrl), + kUrgentPasswordExpiryNotificationSize) {} + +UrgentPasswordExpiryNotificationDialog:: + ~UrgentPasswordExpiryNotificationDialog() { + DCHECK_EQ(this, g_notification_dialog); + g_notification_dialog = nullptr; +} + +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h new file mode 100644 index 00000000000..d8c2b144e2c --- /dev/null +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h @@ -0,0 +1,92 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_DIALOGS_H_ +#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_DIALOGS_H_ + +#include "base/macros.h" +#include "base/strings/string16.h" +#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h" +#include "ui/web_dialogs/web_dialog_ui.h" + +namespace chromeos { + +// A modal system dialog without any frame decorating it. +class BasePasswordDialog : public SystemWebDialogDelegate { + protected: + BasePasswordDialog(GURL url, gfx::Size desired_size); + ~BasePasswordDialog() override; + + // ui::WebDialogDelegate: + void GetDialogSize(gfx::Size* size) const override; + void AdjustWidgetInitParams(views::Widget::InitParams* params) override; + ui::ModalType GetDialogModalType() const override; + + private: + gfx::Size desired_size_; + + DISALLOW_COPY_AND_ASSIGN(BasePasswordDialog); +}; + +// System dialog wrapping chrome:://password-change +class PasswordChangeDialog : public BasePasswordDialog { + public: + static void Show(); + static void Dismiss(); + + protected: + PasswordChangeDialog(); + ~PasswordChangeDialog() override; + + private: + DISALLOW_COPY_AND_ASSIGN(PasswordChangeDialog); +}; + +// System dialog wrapping chrome://confirm-password-change +class ConfirmPasswordChangeDialog : public BasePasswordDialog { + public: + static void Show(const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially); + static void Dismiss(); + + // How big does this dialog need to be to show these prompts: + static gfx::Size GetSize(bool show_old_password_prompt, + bool show_new_password_prompt); + + protected: + ConfirmPasswordChangeDialog(const std::string& scraped_old_password, + const std::string& scraped_new_password, + bool show_spinner_initially); + ~ConfirmPasswordChangeDialog() override; + + // ui::WebDialogDelegate: + void GetWebUIMessageHandlers( + std::vector<content::WebUIMessageHandler*>* handlers) const override; + + private: + std::string scraped_old_password_; + std::string scraped_new_password_; + bool show_spinner_initially_ = false; + + DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeDialog); +}; + +// System dialog wrapping chrome://urgent-password-expiry-notification +class UrgentPasswordExpiryNotificationDialog : public BasePasswordDialog { + public: + static void Show(); + static void Dismiss(); + + protected: + UrgentPasswordExpiryNotificationDialog(); + ~UrgentPasswordExpiryNotificationDialog() override; + + private: + DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationDialog); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_DIALOGS_H_ diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc index 8b85995d13c..04a7c285025 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc @@ -13,7 +13,7 @@ #include "chrome/browser/chromeos/login/saml/password_expiry_notification.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h" +#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_dialogs.h" #include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h" #include "chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h" #include "chrome/browser/ui/webui/localized_string.h" @@ -38,12 +38,6 @@ namespace chromeos { namespace { -PasswordChangeDialog* g_dialog = nullptr; - -ConfirmPasswordChangeDialog* g_confirm_dialog = nullptr; - -UrgentPasswordExpiryNotificationDialog* g_notification_dialog = nullptr; - std::string GetPasswordChangeUrl(Profile* profile) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSamlPasswordChangeUrl)) { @@ -73,79 +67,15 @@ base::string16 GetHostedHeaderText(const std::string& password_change_url) { host); } -constexpr int kMaxPasswordChangeDialogWidth = 768; -constexpr int kMaxPasswordChangeDialogHeight = 640; - -// TODO(https://crbug.com/930109): Change these numbers depending on what is -// shown in the dialog. -constexpr int kMaxConfirmPasswordChangeDialogWidth = 520; -constexpr int kMaxConfirmPasswordChangeDialogHeight = 380; - -constexpr int kMaxNotificationDialogWidth = 768; -constexpr int kMaxNotificationDialogHeight = 640; - -// Given a desired width and height, returns the same size if it fits on screen, -// or the closest possible size that will fit on the screen. -gfx::Size FitSizeToDisplay(int max_width, int max_height) { - const display::Display display = - display::Screen::GetScreen()->GetPrimaryDisplay(); - - gfx::Size display_size = display.size(); - - if (display.rotation() == display::Display::ROTATE_90 || - display.rotation() == display::Display::ROTATE_270) { - display_size = gfx::Size(display_size.height(), display_size.width()); - } - - display_size = gfx::Size(std::min(display_size.width(), max_width), - std::min(display_size.height(), max_height)); - - return display_size; +void AddSize(content::WebUIDataSource* source, + const std::string& suffix, + const gfx::Size& size) { + source->AddInteger("width" + suffix, size.width()); + source->AddInteger("height" + suffix, size.height()); } } // namespace -PasswordChangeDialog::PasswordChangeDialog() - : SystemWebDialogDelegate(GURL(chrome::kChromeUIPasswordChangeUrl), - /*title=*/base::string16()) {} - -PasswordChangeDialog::~PasswordChangeDialog() { - DCHECK_EQ(this, g_dialog); - g_dialog = nullptr; -} - -void PasswordChangeDialog::GetDialogSize(gfx::Size* size) const { - *size = FitSizeToDisplay(kMaxPasswordChangeDialogWidth, - kMaxPasswordChangeDialogHeight); -} - -void PasswordChangeDialog::AdjustWidgetInitParams( - views::Widget::InitParams* params) { - params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; -} - -ui::ModalType PasswordChangeDialog::GetDialogModalType() const { - return ui::ModalType::MODAL_TYPE_SYSTEM; -} - -// static -void PasswordChangeDialog::Show() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_dialog) { - g_dialog->Focus(); - return; - } - g_dialog = new PasswordChangeDialog(); - g_dialog->ShowSystemDialog(); -} - -// static -void PasswordChangeDialog::Dismiss() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_dialog) - g_dialog->Close(); -} - PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { Profile* profile = Profile::FromWebUI(web_ui); @@ -159,7 +89,7 @@ PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui) std::make_unique<PasswordChangeHandler>(password_change_url)); source->AddString("hostedHeader", GetHostedHeaderText(password_change_url)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_PASSWORD_CHANGE_HTML); @@ -173,66 +103,6 @@ PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui) PasswordChangeUI::~PasswordChangeUI() = default; -// static -void ConfirmPasswordChangeDialog::Show(const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_confirm_dialog) { - g_confirm_dialog->Focus(); - return; - } - g_confirm_dialog = new ConfirmPasswordChangeDialog( - scraped_old_password, scraped_new_password, show_spinner_initially); - g_confirm_dialog->ShowSystemDialog(); -} - -// static -void ConfirmPasswordChangeDialog::Dismiss() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_confirm_dialog) - g_confirm_dialog->Close(); -} - -ConfirmPasswordChangeDialog::ConfirmPasswordChangeDialog( - const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially) - : SystemWebDialogDelegate(GURL(chrome::kChromeUIConfirmPasswordChangeUrl), - /*title=*/base::string16()), - scraped_old_password_(scraped_old_password), - scraped_new_password_(scraped_new_password), - show_spinner_initially_(show_spinner_initially) {} - -ConfirmPasswordChangeDialog::~ConfirmPasswordChangeDialog() { - DCHECK_EQ(this, g_confirm_dialog); - g_confirm_dialog = nullptr; -} - -void ConfirmPasswordChangeDialog::GetDialogSize(gfx::Size* size) const { - *size = FitSizeToDisplay(kMaxConfirmPasswordChangeDialogWidth, - kMaxConfirmPasswordChangeDialogHeight); -} - -std::string ConfirmPasswordChangeDialog::GetDialogArgs() const { - // TODO(https://crbug.com/930109): Configure the embedded UI to only display - // prompts for the passwords that were not scraped. - std::string data; - base::DictionaryValue dialog_args; - dialog_args.SetBoolean("showSpinnerInitially", show_spinner_initially_); - base::JSONWriter::Write(dialog_args, &data); - return data; -} - -void ConfirmPasswordChangeDialog::AdjustWidgetInitParams( - views::Widget::InitParams* params) { - params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; -} - -ui::ModalType ConfirmPasswordChangeDialog::GetDialogModalType() const { - return ui::ModalType::MODAL_TYPE_SYSTEM; -} - ConfirmPasswordChangeUI::ConfirmPasswordChangeUI(content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { Profile* profile = Profile::FromWebUI(web_ui); @@ -252,69 +122,31 @@ ConfirmPasswordChangeUI::ConfirmPasswordChangeUI(content::WebUI* web_ui) {"oldPassword", IDS_PASSWORD_CHANGE_OLD_PASSWORD_LABEL}, {"newPassword", IDS_PASSWORD_CHANGE_NEW_PASSWORD_LABEL}, {"confirmNewPassword", IDS_PASSWORD_CHANGE_CONFIRM_NEW_PASSWORD_LABEL}, + {"incorrectPassword", IDS_LOGIN_CONFIRM_PASSWORD_INCORRECT_PASSWORD}, {"matchError", IDS_PASSWORD_CHANGE_PASSWORDS_DONT_MATCH}, {"save", IDS_PASSWORD_CHANGE_CONFIRM_SAVE_BUTTON}}; AddLocalizedStringsBulk(source, kLocalizedStrings, base::size(kLocalizedStrings)); - source->SetJsonPath("strings.js"); + AddSize(source, "", ConfirmPasswordChangeDialog::GetSize(false, false)); + AddSize(source, "Old", ConfirmPasswordChangeDialog::GetSize(true, false)); + AddSize(source, "New", ConfirmPasswordChangeDialog::GetSize(false, true)); + AddSize(source, "OldNew", ConfirmPasswordChangeDialog::GetSize(true, true)); + + source->UseStringsJs(); source->SetDefaultResource(IDR_CONFIRM_PASSWORD_CHANGE_HTML); source->AddResourcePath("confirm_password_change.js", IDR_CONFIRM_PASSWORD_CHANGE_JS); - web_ui->AddMessageHandler(std::make_unique<ConfirmPasswordChangeHandler>()); + // The ConfirmPasswordChangeHandler is added by the dialog, so no need to add + // it here. content::WebUIDataSource::Add(profile, source); } ConfirmPasswordChangeUI::~ConfirmPasswordChangeUI() = default; -UrgentPasswordExpiryNotificationDialog::UrgentPasswordExpiryNotificationDialog() - : SystemWebDialogDelegate( - GURL(chrome::kChromeUIUrgentPasswordExpiryNotificationUrl), - /*title=*/base::string16()) {} - -UrgentPasswordExpiryNotificationDialog:: - ~UrgentPasswordExpiryNotificationDialog() { - DCHECK_EQ(this, g_notification_dialog); - g_notification_dialog = nullptr; -} - -void UrgentPasswordExpiryNotificationDialog::GetDialogSize( - gfx::Size* size) const { - *size = FitSizeToDisplay(kMaxNotificationDialogWidth, - kMaxNotificationDialogHeight); -} - -void UrgentPasswordExpiryNotificationDialog::AdjustWidgetInitParams( - views::Widget::InitParams* params) { - params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; -} - -ui::ModalType UrgentPasswordExpiryNotificationDialog::GetDialogModalType() - const { - return ui::ModalType::MODAL_TYPE_SYSTEM; -} - -// static -void UrgentPasswordExpiryNotificationDialog::Show() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_notification_dialog) { - g_notification_dialog->Focus(); - return; - } - g_notification_dialog = new UrgentPasswordExpiryNotificationDialog(); - g_notification_dialog->ShowSystemDialog(); -} - -// static -void UrgentPasswordExpiryNotificationDialog::Dismiss() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (g_notification_dialog) - g_notification_dialog->Close(); -} - UrgentPasswordExpiryNotificationUI::UrgentPasswordExpiryNotificationUI( content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { @@ -340,7 +172,7 @@ UrgentPasswordExpiryNotificationUI::UrgentPasswordExpiryNotificationUI( AddLocalizedStringsBulk(source, kLocalizedStrings, base::size(kLocalizedStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HTML); source->AddResourcePath("urgent_password_expiry_notification.js", IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_JS); diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h index d1b2cb7e877..b8d19af17e1 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h @@ -12,25 +12,6 @@ namespace chromeos { -// System dialog wrapping chrome:://password-change -class PasswordChangeDialog : public SystemWebDialogDelegate { - public: - static void Show(); - static void Dismiss(); - - protected: - PasswordChangeDialog(); - ~PasswordChangeDialog() override; - - // ui::WebDialogDelegate: - void GetDialogSize(gfx::Size* size) const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - ui::ModalType GetDialogModalType() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(PasswordChangeDialog); -}; - // For chrome:://password-change class PasswordChangeUI : public ui::WebDialogUI { public: @@ -41,34 +22,6 @@ class PasswordChangeUI : public ui::WebDialogUI { DISALLOW_COPY_AND_ASSIGN(PasswordChangeUI); }; -// System dialog wrapping chrome://confirm-password-change -class ConfirmPasswordChangeDialog : public SystemWebDialogDelegate { - public: - static void Show(const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially); - static void Dismiss(); - - protected: - ConfirmPasswordChangeDialog(const std::string& scraped_old_password, - const std::string& scraped_new_password, - bool show_spinner_initially); - ~ConfirmPasswordChangeDialog() override; - - // ui::WebDialogDelegate: - void GetDialogSize(gfx::Size* size) const override; - std::string GetDialogArgs() const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - ui::ModalType GetDialogModalType() const override; - - private: - std::string scraped_old_password_; - std::string scraped_new_password_; - bool show_spinner_initially_ = false; - - DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeDialog); -}; - // For chrome:://confirm-password-change class ConfirmPasswordChangeUI : public ui::WebDialogUI { public: @@ -79,25 +32,6 @@ class ConfirmPasswordChangeUI : public ui::WebDialogUI { DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeUI); }; -// System dialog wrapping chrome://urgent-password-expiry-notification -class UrgentPasswordExpiryNotificationDialog : public SystemWebDialogDelegate { - public: - static void Show(); - static void Dismiss(); - - protected: - UrgentPasswordExpiryNotificationDialog(); - ~UrgentPasswordExpiryNotificationDialog() override; - - // ui::WebDialogDelegate: - void GetDialogSize(gfx::Size* size) const override; - void AdjustWidgetInitParams(views::Widget::InitParams* params) override; - ui::ModalType GetDialogModalType() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationDialog); -}; - // For chrome:://urgent-password-expiry-notification class UrgentPasswordExpiryNotificationUI : public ui::WebDialogUI { public: diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc index 24c46c4c6c8..4d8cca34874 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc @@ -142,7 +142,7 @@ InternetConfigDialogUI::InternetConfigDialogUI(content::WebUI* web_ui) AddInternetStrings(source); source->AddLocalizedString("title", IDS_SETTINGS_INTERNET_CONFIG); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->SetDefaultResource(IDR_INTERNET_CONFIG_DIALOG_VULCANIZED_HTML); source->AddResourcePath("crisper.js", IDR_INTERNET_CONFIG_DIALOG_CRISPER_JS); diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc index b1faef7f2de..2489cb2e124 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" #include "ash/public/cpp/ash_features.h" +#include "ash/public/cpp/network_config_service.h" #include "base/json/json_writer.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" @@ -16,11 +17,9 @@ #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_util.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/base/l10n/l10n_util.h" namespace chromeos { @@ -142,7 +141,7 @@ InternetDetailDialogUI::InternetDetailDialogUI(content::WebUI* web_ui) !ash::features::IsSeparateNetworkIconsEnabled()); AddInternetStrings(source); source->AddLocalizedString("title", IDS_SETTINGS_INTERNET_DETAIL); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->SetDefaultResource(IDR_INTERNET_DETAIL_DIALOG_VULCANIZED_HTML); source->AddResourcePath("crisper.js", IDR_INTERNET_DETAIL_DIALOG_CRISPER_JS); @@ -162,10 +161,7 @@ InternetDetailDialogUI::~InternetDetailDialogUI() {} void InternetDetailDialogUI::BindCrosNetworkConfig( chromeos::network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(chromeos::network_config::mojom::kServiceName, - std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc index a31ce2c2566..f2882ee9ec6 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc @@ -42,9 +42,7 @@ ActiveDirectoryPasswordChangeScreenHandler:: : BaseScreenHandler(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE, js_calls_container), authpolicy_login_helper_(std::make_unique<AuthPolicyHelper>()), - core_oobe_view_(core_oobe_view), - weak_factory_(this) { -} + core_oobe_view_(core_oobe_view) {} ActiveDirectoryPasswordChangeScreenHandler:: ~ActiveDirectoryPasswordChangeScreenHandler() {} diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h index 74b41552268..8768175e503 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h @@ -65,7 +65,7 @@ class ActiveDirectoryPasswordChangeScreenHandler : public BaseScreenHandler { CoreOobeView* core_oobe_view_ = nullptr; base::WeakPtrFactory<ActiveDirectoryPasswordChangeScreenHandler> - weak_factory_; + weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryPasswordChangeScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc index 29601c934c8..e6b65a80a77 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc @@ -294,8 +294,8 @@ void ArcTermsOfServiceScreenHandler::DoShow() { MaybeLoadPlayStoreToS(true); StartNetworkAndTimeZoneObserving(); - pref_handler_.reset(new arc::ArcOptInPreferenceHandler( - this, profile->GetPrefs())); + pref_handler_ = std::make_unique<arc::ArcOptInPreferenceHandler>( + this, profile->GetPrefs()); pref_handler_->Start(); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc index 622537cfdff..f53cede13a4 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc @@ -15,17 +15,16 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/ash/assistant/assistant_service_connection.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h" #include "chrome/grit/generated_resources.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/services/assistant/public/features.h" -#include "chromeos/services/assistant/public/mojom/constants.mojom.h" #include "chromeos/services/assistant/public/proto/settings_ui.pb.h" -#include "components/arc/arc_prefs.h" #include "components/login/localized_values_builder.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" -#include "services/service_manager/public/cpp/connector.h" +#include "ui/chromeos/devicetype_utils.h" namespace chromeos { @@ -50,13 +49,13 @@ constexpr StaticOobeScreenId AssistantOptInFlowScreenView::kScreenId; AssistantOptInFlowScreenHandler::AssistantOptInFlowScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), - client_binding_(this), - weak_factory_(this) { + : BaseScreenHandler(kScreenId, js_calls_container), client_binding_(this) { set_user_acted_method_path("login.AssistantOptInFlowScreen.userActed"); } AssistantOptInFlowScreenHandler::~AssistantOptInFlowScreenHandler() { + if (client_binding_) + StopSpeakerIdEnrollment(); if (arc::VoiceInteractionControllerClient::Get()) { arc::VoiceInteractionControllerClient::Get()->RemoveObserver(this); } @@ -113,10 +112,13 @@ void AssistantOptInFlowScreenHandler::DeclareLocalizedValues( builder->Add("assistantOptinSaveButton", IDS_ASSISTANT_SAVE_BUTTON); builder->Add("assistantOptinWaitMessage", IDS_ASSISTANT_WAIT_MESSAGE); builder->Add("assistantReadyTitle", IDS_ASSISTANT_READY_SCREEN_TITLE); - builder->Add("assistantReadyMessage", IDS_ASSISTANT_READY_SCREEN_MESSAGE); + builder->AddF("assistantReadyMessage", IDS_ASSISTANT_READY_SCREEN_MESSAGE, + ui::GetChromeOSDeviceName()); builder->Add("assistantReadyButton", IDS_ASSISTANT_DONE_BUTTON); builder->Add("back", IDS_EULA_BACK_BUTTON); builder->Add("next", IDS_EULA_NEXT_BUTTON); + builder->Add("assistantOobePopupOverlayLoading", + IDS_ASSISTANT_OOBE_POPUP_OVERLAY_LOADING); } void AssistantOptInFlowScreenHandler::RegisterMessages() { @@ -214,7 +216,7 @@ void AssistantOptInFlowScreenHandler::SetupAssistantConnection() { } // Make sure enable Assistant service since we need it during the flow. - prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true); + prefs->SetBoolean(chromeos::assistant::prefs::kAssistantEnabled, true); if (arc::VoiceInteractionControllerClient::Get()->voice_interaction_state() == ash::mojom::VoiceInteractionState::NOT_READY) { @@ -266,7 +268,7 @@ void AssistantOptInFlowScreenHandler::OnDialogClosed() { if (!voice_match_enrollment_done_ && flow_type_ == ash::FlowType::kSpeakerIdEnrollment) { ProfileManager::GetActiveUserProfile()->GetPrefs()->SetBoolean( - arc::prefs::kVoiceInteractionHotwordEnabled, false); + assistant::prefs::kAssistantHotwordEnabled, false); } } @@ -283,11 +285,10 @@ void AssistantOptInFlowScreenHandler::BindAssistantSettingsManager() { return; // Set up settings mojom. - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor( - ProfileManager::GetActiveUserProfile()); - connector->BindInterface(assistant::mojom::kServiceName, - mojo::MakeRequest(&settings_manager_)); + AssistantServiceConnection::GetForProfile( + ProfileManager::GetActiveUserProfile()) + ->service() + ->BindSettingsManager(mojo::MakeRequest(&settings_manager_)); if (initialized_) { SendGetSettingsRequest(); @@ -339,7 +340,7 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse( "opt-in flow."; PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); prefs->SetBoolean(assistant::prefs::kAssistantDisabledByPolicy, true); - prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, false); + prefs->SetBoolean(chromeos::assistant::prefs::kAssistantEnabled, false); HandleFlowFinished(); return; } @@ -508,13 +509,13 @@ void AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenUserAction( RecordAssistantOptInStatus(VOICE_MATCH_ENROLLMENT_SKIPPED); if (flow_type_ != ash::FlowType::kSpeakerIdRetrain) { // No need to disable hotword for retrain flow since user has a model. - prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, false); + prefs->SetBoolean(assistant::prefs::kAssistantHotwordEnabled, false); } StopSpeakerIdEnrollment(); ShowNextScreen(); } else if (action == kRecordPressed) { - if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled)) { - prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true); + if (!prefs->GetBoolean(assistant::prefs::kAssistantHotwordEnabled)) { + prefs->SetBoolean(assistant::prefs::kAssistantHotwordEnabled, true); } assistant::mojom::SpeakerIdEnrollmentClientPtr client_ptr; @@ -529,8 +530,7 @@ void AssistantOptInFlowScreenHandler::HandleGetMoreScreenUserAction( const bool email_opted_in) { RecordAssistantOptInStatus(GET_MORE_CONTINUED); PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); - prefs->SetBoolean(arc::prefs::kVoiceInteractionContextEnabled, - screen_context); + prefs->SetBoolean(assistant::prefs::kAssistantContextEnabled, screen_context); OnEmailOptInResult(email_opted_in); } @@ -576,7 +576,7 @@ void AssistantOptInFlowScreenHandler::HandleFlowFinished() { void AssistantOptInFlowScreenHandler::HandleFlowInitialized( const int flow_type) { auto* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); - if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled)) { + if (!prefs->GetBoolean(chromeos::assistant::prefs::kAssistantEnabled)) { HandleFlowFinished(); return; } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h index 8a24e879ca3..9810c088aea 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h @@ -163,7 +163,7 @@ class AssistantOptInFlowScreenHandler mojo::Binding<assistant::mojom::SpeakerIdEnrollmentClient> client_binding_; assistant::mojom::AssistantSettingsManagerPtr settings_manager_; - base::WeakPtrFactory<AssistantOptInFlowScreenHandler> weak_factory_; + base::WeakPtrFactory<AssistantOptInFlowScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AssistantOptInFlowScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc index 5326b0b1233..5474107730b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc @@ -8,7 +8,8 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/event_rewriter_controller.h" -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/cpp/tablet_mode.h" +#include "ash/public/mojom/constants.mojom.h" #include "ash/shell.h" #include "base/bind.h" #include "base/command_line.h" @@ -32,7 +33,6 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/webui/chromeos/login/demo_setup_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" @@ -88,9 +88,7 @@ void LaunchResetScreen() { // Note that show_oobe_ui_ defaults to false because WizardController assumes // OOBE UI is not visible by default. CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container) - : BaseWebUIHandler(js_calls_container), - version_info_updater_(this), - weak_ptr_factory_(this) { + : BaseWebUIHandler(js_calls_container), version_info_updater_(this) { DCHECK(js_calls_container); AccessibilityManager* accessibility_manager = AccessibilityManager::Get(); CHECK(accessibility_manager); @@ -98,8 +96,7 @@ CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container) base::Bind(&CoreOobeHandler::OnAccessibilityStatusChanged, base::Unretained(this))); - TabletModeClient* tablet_mode_client = TabletModeClient::Get(); - tablet_mode_client->AddObserver(this); + ash::TabletMode::Get()->AddObserver(this); // |connector| may be null in tests. auto* connector = content::GetSystemConnector(); @@ -112,7 +109,10 @@ CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container) CoreOobeHandler::~CoreOobeHandler() { OobeConfiguration::Get()->RemoveObserver(this); - TabletModeClient::Get()->RemoveObserver(this); + + // Ash may be released before us. + if (ash::TabletMode::Get()) + ash::TabletMode::Get()->RemoveObserver(this); } void CoreOobeHandler::DeclareLocalizedValues( @@ -178,7 +178,7 @@ void CoreOobeHandler::Initialize() { void CoreOobeHandler::GetAdditionalParameters(base::DictionaryValue* dict) { dict->SetKey("isInTabletMode", - base::Value(TabletModeClient::Get()->tablet_mode_enabled())); + base::Value(ash::TabletMode::Get()->InTabletMode())); dict->SetKey("isDemoModeEnabled", base::Value(DemoSetupController::IsDemoModeAllowed())); dict->SetKey("showTechnologyBadge", @@ -534,8 +534,12 @@ void CoreOobeHandler::UpdateKeyboardState() { SetVirtualKeyboardShown(is_keyboard_shown); } -void CoreOobeHandler::OnTabletModeToggled(bool enabled) { - CallJS("cr.ui.Oobe.setTabletModeState", enabled); +void CoreOobeHandler::OnTabletModeStarted() { + CallJS("cr.ui.Oobe.setTabletModeState", true); +} + +void CoreOobeHandler::OnTabletModeEnded() { + CallJS("cr.ui.Oobe.setTabletModeState", false); } void CoreOobeHandler::UpdateClientAreaSize() { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h index cb7db18c545..8e30d2b5363 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h @@ -9,7 +9,8 @@ #include <string> #include <vector> -#include "ash/public/interfaces/cros_display_config.mojom.h" +#include "ash/public/cpp/tablet_mode_observer.h" +#include "ash/public/mojom/cros_display_config.mojom.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -21,7 +22,6 @@ #include "chrome/browser/chromeos/login/oobe_configuration.h" #include "chrome/browser/chromeos/login/version_info_updater.h" #include "chrome/browser/chromeos/tpm_firmware_update.h" -#include "chrome/browser/ui/ash/tablet_mode_client_observer.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" #include "ui/events/event_source.h" @@ -72,7 +72,7 @@ class CoreOobeHandler : public BaseWebUIHandler, public VersionInfoUpdater::Delegate, public CoreOobeView, public ui::EventSource, - public TabletModeClientObserver, + public ash::TabletModeObserver, public OobeConfiguration::Observer { public: explicit CoreOobeHandler(JSCallsContainer* js_calls_container); @@ -146,8 +146,9 @@ class CoreOobeHandler : public BaseWebUIHandler, void StopDemoModeDetection() override; void UpdateKeyboardState() override; - // TabletModeClientObserver: - void OnTabletModeToggled(bool enabled) override; + // ash::TabletModeObserver: + void OnTabletModeStarted() override; + void OnTabletModeEnded() override; // OobeConfiguration::Observer: void OnOobeConfigurationChanged() override; @@ -223,7 +224,7 @@ class CoreOobeHandler : public BaseWebUIHandler, ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_; - base::WeakPtrFactory<CoreOobeHandler> weak_ptr_factory_; + base::WeakPtrFactory<CoreOobeHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CoreOobeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc index b43a2040cf9..c6fce1fdcd0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/discover/modules/discover_module_pin_setup.cc @@ -43,16 +43,14 @@ class DiscoverModulePinSetupHandler : public DiscoverHandler { base::WeakPtr<DiscoverModulePinSetup> module_; - base::WeakPtrFactory<DiscoverModulePinSetupHandler> weak_factory_; + base::WeakPtrFactory<DiscoverModulePinSetupHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DiscoverModulePinSetupHandler); }; DiscoverModulePinSetupHandler::DiscoverModulePinSetupHandler( base::WeakPtr<DiscoverModulePinSetup> module, JSCallsContainer* js_calls_container) - : DiscoverHandler(js_calls_container), - module_(module), - weak_factory_(this) {} + : DiscoverHandler(js_calls_container), module_(module) {} void DiscoverModulePinSetupHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc index a8d27784548..35e15951f2a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc @@ -36,9 +36,7 @@ constexpr StaticOobeScreenId EnableDebuggingScreenView::kScreenId; EnableDebuggingScreenHandler::EnableDebuggingScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), - weak_ptr_factory_(this) { -} + : BaseScreenHandler(kScreenId, js_calls_container) {} EnableDebuggingScreenHandler::~EnableDebuggingScreenHandler() { if (screen_) diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h index aaa881d0bbf..88dfc9a0a19 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.h @@ -97,7 +97,7 @@ class EnableDebuggingScreenHandler : public EnableDebuggingScreenView, // Keeps whether screen should be shown right after initialization. bool show_on_init_ = false; - base::WeakPtrFactory<EnableDebuggingScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<EnableDebuggingScreenHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EnableDebuggingScreenHandler); }; 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 ed23aaa3cda..b75aaa8b7cf 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 @@ -40,7 +40,7 @@ #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/system_connector.h" -#include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "services/device/public/mojom/constants.mojom.h" #include "services/device/public/mojom/wake_lock_provider.mojom.h" #include "services/service_manager/public/cpp/connector.h" @@ -258,8 +258,7 @@ constexpr StaticOobeScreenId EncryptionMigrationScreenView::kScreenId; EncryptionMigrationScreenHandler::EncryptionMigrationScreenHandler( JSCallsContainer* js_calls_container) : BaseScreenHandler(kScreenId, js_calls_container), - tick_clock_(base::DefaultTickClock::GetInstance()), - weak_ptr_factory_(this) { + tick_clock_(base::DefaultTickClock::GetInstance()) { free_disk_space_fetcher_ = base::Bind(&base::SysInfo::AmountOfFreeDiskSpace, base::FilePath(kCheckStoragePath)); } @@ -482,7 +481,8 @@ void EncryptionMigrationScreenHandler::HandleOpenFeedbackDialog() { "Auto generated feedback for http://crbug.com/719266.\n" "(uniquifier:%s)", base::NumberToString(base::Time::Now().ToInternalValue()).c_str()); - login_feedback_.reset(new LoginFeedback(Profile::FromWebUI(web_ui()))); + login_feedback_ = + std::make_unique<LoginFeedback>(Profile::FromWebUI(web_ui())); login_feedback_->Request(description, base::Closure()); } @@ -520,8 +520,9 @@ void EncryptionMigrationScreenHandler::UpdateUIState(UIState state) { } void EncryptionMigrationScreenHandler::CheckAvailableStorage() { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, free_disk_space_fetcher_, base::Bind(&EncryptionMigrationScreenHandler::OnGetAvailableStorage, weak_ptr_factory_.GetWeakPtr())); @@ -620,7 +621,8 @@ device::mojom::WakeLock* EncryptionMigrationScreenHandler::GetWakeLock() { if (wake_lock_) return wake_lock_.get(); - device::mojom::WakeLockRequest request = mojo::MakeRequest(&wake_lock_); + mojo::PendingReceiver<device::mojom::WakeLock> receiver = + wake_lock_.BindNewPipeAndPassReceiver(); // Service manager connection might be not initialized in some testing // contexts. @@ -629,13 +631,14 @@ device::mojom::WakeLock* EncryptionMigrationScreenHandler::GetWakeLock() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - device::mojom::WakeLockProviderPtr wake_lock_provider; - content::GetSystemConnector()->BindInterface( - device::mojom::kServiceName, mojo::MakeRequest(&wake_lock_provider)); + mojo::Remote<device::mojom::WakeLockProvider> wake_lock_provider; + content::GetSystemConnector()->Connect( + device::mojom::kServiceName, + wake_lock_provider.BindNewPipeAndPassReceiver()); wake_lock_provider->GetWakeLockWithoutContext( device::mojom::WakeLockType::kPreventAppSuspension, device::mojom::WakeLockReason::kOther, - "Encryption migration is in progress...", std::move(request)); + "Encryption migration is in progress...", std::move(receiver)); return wake_lock_.get(); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h index 4661fce4ee1..23dd21fc6bb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h @@ -18,6 +18,7 @@ #include "chromeos/dbus/cryptohome/rpc.pb.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/login/auth/user_context.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/wake_lock.mojom.h" #include "third_party/cros_system_api/dbus/cryptohome/dbus-constants.h" @@ -201,7 +202,7 @@ class EncryptionMigrationScreenHandler : public EncryptionMigrationScreenView, // Point in time when minimal migration started, as reported by |tick_clock_|. base::TimeTicks minimal_migration_start_; - device::mojom::WakeLockPtr wake_lock_; + mojo::Remote<device::mojom::WakeLock> wake_lock_; std::unique_ptr<LoginFeedback> login_feedback_; @@ -210,7 +211,8 @@ class EncryptionMigrationScreenHandler : public EncryptionMigrationScreenView, FreeDiskSpaceFetcher free_disk_space_fetcher_; - base::WeakPtrFactory<EncryptionMigrationScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<EncryptionMigrationScreenHandler> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(EncryptionMigrationScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc index 081fdff1bfb..bca31b6289f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc @@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" -#include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" +#include "base/test/task_environment.h" #include "chrome/browser/chromeos/arc/arc_migration_constants.h" #include "chrome/browser/chromeos/login/screens/encryption_migration_mode.h" #include "chrome/browser/chromeos/login/users/mock_user_manager.h" @@ -26,6 +26,7 @@ #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user_names.h" #include "content/public/test/test_web_ui.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -47,7 +48,8 @@ class FakeWakeLock : public device::mojom::WakeLock { // Implement device::mojom::WakeLock: void RequestWakeLock() override { has_wakelock_ = true; } void CancelWakeLock() override { has_wakelock_ = false; } - void AddClient(device::mojom::WakeLockRequest request) override {} + void AddClient( + mojo::PendingReceiver<device::mojom::WakeLock> receiver) override {} void ChangeType(device::mojom::WakeLockType type, ChangeTypeCallback callback) override { NOTIMPLEMENTED(); @@ -167,7 +169,7 @@ class EncryptionMigrationScreenHandlerTest : public testing::Test { protected: // Must be the first member. - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_enabler_; FakeCryptohomeClient* fake_cryptohome_client_ = nullptr; // unowned @@ -218,7 +220,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigration) { EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); EXPECT_TRUE( encryption_migration_screen_handler_->fake_wake_lock()->HasWakeLock()); @@ -247,7 +249,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, ResumeMinimalMigration) { EncryptionMigrationMode::RESUME_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); fake_cryptohome_client_->NotifyDircryptoMigrationProgress( cryptohome::DircryptoMigrationStatus::DIRCRYPTO_MIGRATION_SUCCESS, @@ -272,7 +274,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigrationSlow) { EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); encryption_migration_screen_handler_->testing_tick_clock()->Advance( base::TimeDelta::FromMinutes(1)); @@ -297,7 +299,7 @@ TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigrationFails) { EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); - scoped_task_environment_.RunUntilIdle(); + task_environment_.RunUntilIdle(); encryption_migration_screen_handler_->testing_tick_clock()->Advance( base::TimeDelta::FromMinutes(1)); 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 5c9688e360d..d0fa17ef808 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 @@ -182,8 +182,7 @@ EnrollmentScreenHandler::EnrollmentScreenHandler( : BaseScreenHandler(kScreenId, js_calls_container), network_state_informer_(network_state_informer), error_screen_(error_screen), - histogram_helper_(new ErrorScreensHistogramHelper("Enrollment")), - weak_ptr_factory_(this) { + histogram_helper_(new ErrorScreensHistogramHelper("Enrollment")) { DCHECK(network_state_informer_.get()); DCHECK(error_screen_); network_state_informer_->AddObserver(this); @@ -800,12 +799,12 @@ void EnrollmentScreenHandler::HandleCompleteLogin(const std::string& user) { void EnrollmentScreenHandler::OnGetCookiesForCompleteLogin( const std::string& user, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies) { std::string auth_code; - for (const auto& cookie : cookies) { - if (cookie.Name() == "oauth_code") { - auth_code = cookie.Value(); + for (const auto& cookie_with_status : cookies) { + if (cookie_with_status.cookie.Name() == "oauth_code") { + auth_code = cookie_with_status.cookie.Value(); break; } } 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 0d4ff94c225..2580ce653f0 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h @@ -17,10 +17,7 @@ #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "net/base/net_errors.h" - -namespace net { -class CanonicalCookie; -} +#include "net/cookies/canonical_cookie.h" namespace chromeos { @@ -107,7 +104,7 @@ class EnrollmentScreenHandler void HandleCompleteLogin(const std::string& user); void OnGetCookiesForCompleteLogin( const std::string& user, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies); void HandleAdCompleteLogin(const std::string& machine_name, const std::string& distinguished_name, @@ -191,8 +188,7 @@ class EnrollmentScreenHandler // Help application used for help dialogs. scoped_refptr<HelpAppLauncher> help_app_; - - base::WeakPtrFactory<EnrollmentScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<EnrollmentScreenHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EnrollmentScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc index e0638ca7a4a..b61b4f7bb1f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc @@ -32,8 +32,7 @@ constexpr StaticOobeScreenId EulaView::kScreenId; EulaScreenHandler::EulaScreenHandler(JSCallsContainer* js_calls_container, CoreOobeView* core_oobe_view) : BaseScreenHandler(kScreenId, js_calls_container), - core_oobe_view_(core_oobe_view), - weak_factory_(this) { + core_oobe_view_(core_oobe_view) { set_user_acted_method_path("login.EulaScreen.userActed"); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h index 395a459a27a..c6ace1d9492 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h @@ -79,7 +79,7 @@ class EulaScreenHandler : public EulaView, public BaseScreenHandler { // Keeps whether screen should be shown right after initialization. bool show_on_init_ = false; - base::WeakPtrFactory<EulaScreenHandler> weak_factory_; + base::WeakPtrFactory<EulaScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(EulaScreenHandler); }; 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 7ea94468de3..ee389c1f193 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc @@ -18,6 +18,7 @@ #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/metrics/histogram_macros.h" +#include "base/optional.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -26,6 +27,9 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" +#include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h" #include "chrome/browser/chromeos/language_preferences.h" #include "chrome/browser/chromeos/login/lock_screen_utils.h" #include "chrome/browser/chromeos/login/reauth_stats.h" @@ -58,11 +62,13 @@ #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/constants/devicetype.h" +#include "chromeos/constants/security_token_pin_types.h" #include "chromeos/dbus/util/version_loader.h" #include "chromeos/login/auth/challenge_response/cert_utils.h" #include "chromeos/login/auth/cryptohome_key_constants.h" #include "chromeos/login/auth/saml_password_attributes.h" #include "chromeos/login/auth/user_context.h" +#include "chromeos/network/onc/certificate_scope.h" #include "chromeos/settings/cros_settings_names.h" #include "components/login/localized_values_builder.h" #include "components/policy/proto/chrome_device_policy.pb.h" @@ -77,6 +83,7 @@ #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" #include "mojo/public/cpp/bindings/callback_helpers.h" +#include "net/base/net_errors.h" #include "net/cert/x509_certificate.h" #include "services/network/nss_temp_certs_cache_chromeos.h" #include "services/network/public/mojom/network_context.mojom.h" @@ -253,6 +260,27 @@ bool GaiaActionButtonsEnabled() { return base::FeatureList::IsEnabled(chromeos::features::kGaiaActionButtons); } +PinDialogManager* GetLoginScreenPinDialogManager() { + DCHECK(ProfileHelper::IsSigninProfileInitialized()); + CertificateProviderService* certificate_provider_service = + CertificateProviderServiceFactory::GetForBrowserContext( + ProfileHelper::GetSigninProfile()); + return certificate_provider_service->pin_dialog_manager(); +} + +base::Value MakeSecurityTokenPinDialogParameters( + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left) { + base::Value params(base::Value::Type::DICTIONARY); + params.SetIntKey("codeType", static_cast<int>(code_type)); + params.SetBoolKey("enableUserInput", enable_user_input); + params.SetIntKey("errorLabel", static_cast<int>(error_label)); + params.SetIntKey("attemptsLeft", attempts_left); + return params; +} + } // namespace constexpr StaticOobeScreenId GaiaView::kScreenId; @@ -289,14 +317,15 @@ GaiaScreenHandler::GaiaScreenHandler( 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) { + active_directory_password_change_screen_handler) { DCHECK(network_state_informer_.get()); } GaiaScreenHandler::~GaiaScreenHandler() { if (network_portal_detector_) network_portal_detector_->RemoveObserver(this); + if (is_security_token_pin_enabled_) + GetLoginScreenPinDialogManager()->RemovePinDialogHost(this); } void GaiaScreenHandler::MaybePreloadAuthExtension() { @@ -349,8 +378,7 @@ void GaiaScreenHandler::LoadGaiaWithPartition( base::BindOnce(&GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition, weak_factory_.GetWeakPtr(), context, partition_name); if (context.gaps_cookie.empty()) { - std::move(callback).Run( - net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + std::move(callback).Run(net::CanonicalCookie::CookieInclusionStatus()); return; } @@ -367,15 +395,15 @@ void GaiaScreenHandler::LoadGaiaWithPartition( std::string gaps_cookie_value(kGAPSCookie); gaps_cookie_value += "=" + context.gaps_cookie; + std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( + GaiaUrls::GetInstance()->gaia_url(), gaps_cookie_value, base::Time::Now(), + base::nullopt /* server_time */)); + net::CookieOptions options; options.set_include_httponly(); // Permit it to set a SameSite cookie if it wants to. options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( - GaiaUrls::GetInstance()->gaia_url(), gaps_cookie_value, base::Time::Now(), - options)); - partition->GetCookieManagerForBrowserProcess()->SetCanonicalCookie( *cc.get(), "https", options, std::move(callback)); } @@ -393,8 +421,9 @@ void GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition( &GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent, weak_factory_.GetWeakPtr(), context, partition_name, base::Owned(version.release()), base::Owned(consent.release())); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, std::move(get_version_and_consent), std::move(load_gaia)); } @@ -415,6 +444,30 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent( screen_mode_ = GetGaiaScreenMode(context.email, context.use_offline); params.SetInteger("screenMode", screen_mode_); + if (!context.email.empty()) { + const AccountId account_id = GetAccountId( + context.email, std::string() /* id */, AccountType::UNKNOWN); + const user_manager::User* const user = + user_manager::UserManager::Get()->FindUser(account_id); + if (user && user->using_saml() && + user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT && + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kPublicAccountsSamlUrl)) { + std::string saml_url = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kPublicAccountsSamlUrl); + params.SetBoolean("startsOnSamlPage", true); + params.SetString("frameUrl", saml_url); + params.SetString("email", account_id.GetUserEmail()); + CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kPublicAccountsSamlAclUrl)); + std::string saml_acl_url = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kPublicAccountsSamlAclUrl); + params.SetString("samlAclUrl", saml_acl_url); + } + } + if (screen_mode_ == GAIA_SCREEN_MODE_AD && !authpolicy_login_helper_) authpolicy_login_helper_ = std::make_unique<AuthPolicyHelper>(); @@ -573,6 +626,23 @@ void GaiaScreenHandler::DeclareLocalizedValues( IDS_AD_PASSWORD_CHANGE_NEW_PASSWORD_REJECTED_SHORT_ERROR); builder->Add("adPassChangePasswordsMismatch", IDS_AD_PASSWORD_CHANGE_PASSWORDS_MISMATCH_ERROR); + + builder->Add("securityTokenPinDialogTitle", + IDS_SAML_SECURITY_TOKEN_PIN_DIALOG_TITLE); + builder->Add("securityTokenPinDialogSubtitle", + IDS_SAML_SECURITY_TOKEN_PIN_DIALOG_SUBTITLE); + builder->Add("securityTokenPinDialogTryAgain", + IDS_SAML_SECURITY_TOKEN_PIN_DIALOG_TRY_AGAIN); + builder->Add("securityTokenPinDialogAttemptsLeft", + IDS_REQUEST_PIN_DIALOG_ATTEMPTS_LEFT); + builder->Add("securityTokenPinDialogUnknownError", + IDS_REQUEST_PIN_DIALOG_UNKNOWN_ERROR); + builder->Add("securityTokenPinDialogUnknownInvalidPin", + IDS_REQUEST_PIN_DIALOG_INVALID_PIN_ERROR); + builder->Add("securityTokenPinDialogUnknownInvalidPuk", + IDS_REQUEST_PIN_DIALOG_INVALID_PUK_ERROR); + builder->Add("securityTokenPinDialogUnknownMaxAttemptsExceeded", + IDS_REQUEST_PIN_DIALOG_MAX_ATTEMPTS_EXCEEDED_ERROR); } void GaiaScreenHandler::Initialize() { @@ -612,6 +682,9 @@ void GaiaScreenHandler::RegisterMessages() { AddCallback("updateSigninUIState", &GaiaScreenHandler::HandleUpdateSigninUIState); AddCallback("showGuestInOobe", &GaiaScreenHandler::HandleShowGuestInOobe); + AddCallback("samlStateChanged", &GaiaScreenHandler::HandleSamlStateChanged); + AddCallback("securityTokenPinEntered", + &GaiaScreenHandler::HandleSecurityTokenPinEntered); // Allow UMA metrics collection from JS. web_ui()->AddMessageHandler(std::make_unique<MetricsHandler>()); @@ -653,34 +726,15 @@ void GaiaScreenHandler::HandleAuthExtensionLoaded() { std::make_unique<LoginClientCertUsageObserver>(); } -void GaiaScreenHandler::HandleWebviewLoadAborted( - const std::string& error_reason_str) { - // TODO(nkostylev): Switch to int code once webview supports that. - // http://crbug.com/470483 - if (error_reason_str == "ERR_ABORTED") { - LOG(WARNING) << "Ignoring Gaia webview error: " << error_reason_str; +void GaiaScreenHandler::HandleWebviewLoadAborted(int error_code) { + if (error_code == net::ERR_ABORTED) { + LOG(WARNING) << "Ignoring Gaia webview error: " + << net::ErrorToShortString(error_code); return; } - // TODO(nkostylev): Switch to int code once webview supports that. - // http://crbug.com/470483 - // Extract some common codes used by SigninScreenHandler for now. - if (error_reason_str == "ERR_NAME_NOT_RESOLVED") - frame_error_ = net::ERR_NAME_NOT_RESOLVED; - else if (error_reason_str == "ERR_INTERNET_DISCONNECTED") - frame_error_ = net::ERR_INTERNET_DISCONNECTED; - else if (error_reason_str == "ERR_NETWORK_CHANGED") - frame_error_ = net::ERR_NETWORK_CHANGED; - else if (error_reason_str == "ERR_INTERNET_DISCONNECTED") - frame_error_ = net::ERR_INTERNET_DISCONNECTED; - else if (error_reason_str == "ERR_PROXY_CONNECTION_FAILED") - frame_error_ = net::ERR_PROXY_CONNECTION_FAILED; - else if (error_reason_str == "ERR_TUNNEL_CONNECTION_FAILED") - frame_error_ = net::ERR_TUNNEL_CONNECTION_FAILED; - else - frame_error_ = net::ERR_INTERNET_DISCONNECTED; - - LOG(ERROR) << "Gaia webview error: " << error_reason_str; + frame_error_ = static_cast<net::Error>(error_code); + LOG(ERROR) << "Gaia webview error: " << net::ErrorToShortString(error_code); NetworkError::ErrorReason error_reason = NetworkError::ERROR_REASON_FRAME_ERROR; frame_state_ = FRAME_STATE_ERROR; @@ -812,10 +866,11 @@ void GaiaScreenHandler::OnGetCookiesForCompleteAuthentication( bool using_saml, const ::login::StringList& services, const SamlPasswordAttributes& password_attributes, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies) { std::string auth_code, gaps_cookie; - for (const auto& cookie : cookies) { + for (const auto& cookie_with_status : cookies) { + const auto& cookie = cookie_with_status.cookie; if (cookie.Name() == kOAUTHCodeCookie) auth_code = cookie.Value(); else if (cookie.Name() == kGAPSCookie) @@ -948,6 +1003,48 @@ void GaiaScreenHandler::HandleShowGuestInOobe(bool show) { ash::LoginScreen::Get()->ShowGuestButtonInOobe(show); } +void GaiaScreenHandler::HandleSamlStateChanged(bool is_saml) { + if (is_saml == is_security_token_pin_enabled_) { + // We're already in the needed |is_security_token_pin_enabled_| state. + return; + } + // Enable ourselves as a security token PIN dialog host during the SAML + // sign-in, so that when the SAML page requires client authentication (e.g., + // against a smart card), this PIN request is embedded into the SAML login UI. + if (is_saml) { + GetLoginScreenPinDialogManager()->AddPinDialogHost(this); + } else { + security_token_pin_entered_callback_.Reset(); + security_token_pin_dialog_closed_callback_.Reset(); + GetLoginScreenPinDialogManager()->RemovePinDialogHost(this); + } + is_security_token_pin_enabled_ = is_saml; +} + +void GaiaScreenHandler::HandleSecurityTokenPinEntered( + const std::string& user_input) { + // Invariant: when the pin_entered_callback is present, the closed_callback + // must be present as well. + DCHECK(!security_token_pin_entered_callback_ || + security_token_pin_dialog_closed_callback_); + + if (!security_token_pin_dialog_closed_callback_) { + // The PIN request has already been canceled on the handler side. + return; + } + + if (user_input.empty()) { + security_token_pin_entered_callback_.Reset(); + std::move(security_token_pin_dialog_closed_callback_).Run(); + } else { + // The callback must be non-null, since the UI implementation should not + // send multiple non-empty results. + std::move(security_token_pin_entered_callback_).Run(user_input); + // Keep |security_token_pin_dialog_closed_callback_|, in order to be able to + // notify about the dialog closing afterwards. + } +} + void GaiaScreenHandler::OnShowAddUser() { signin_screen_handler_->is_account_picker_showing_first_time_ = false; lock_screen_utils::EnforcePolicyInputMethods(std::string()); @@ -1123,6 +1220,49 @@ void GaiaScreenHandler::ShowSigninScreenForTest(const std::string& username, } } +void GaiaScreenHandler::ShowSecurityTokenPinDialog( + const std::string& /*caller_extension_name*/, + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left, + const base::Optional<AccountId>& /*authenticating_user_account_id*/, + SecurityTokenPinEnteredCallback pin_entered_callback, + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) { + DCHECK(is_security_token_pin_enabled_); + // There must be either no active PIN dialog, or the active dialog for which + // the PIN has already been entered. + DCHECK(!security_token_pin_entered_callback_); + + security_token_pin_entered_callback_ = std::move(pin_entered_callback); + // Note that this overwrites the previous closed_callback in the case where + // the dialog was already shown. This is intended, since the closing callback + // should only be used to notify that the dialog got canceled, which imposes a + // stricter quota on the PIN request caller. + security_token_pin_dialog_closed_callback_ = + std::move(pin_dialog_closed_callback); + + CallJS("login.GaiaSigninScreen.showPinDialog", + MakeSecurityTokenPinDialogParameters(code_type, enable_user_input, + error_label, attempts_left)); +} + +void GaiaScreenHandler::CloseSecurityTokenPinDialog() { + DCHECK(is_security_token_pin_enabled_); + // Invariant: when the pin_entered_callback is present, the closed_callback + // must be present as well. + DCHECK(!security_token_pin_entered_callback_ || + security_token_pin_dialog_closed_callback_); + + security_token_pin_entered_callback_.Reset(); + security_token_pin_dialog_closed_callback_.Reset(); + + // Notify the page, unless it's already being shut down (which may happen if + // we're called from the destructor). + if (IsJavascriptAllowed()) + CallJS("login.GaiaSigninScreen.closePinDialog"); +} + bool GaiaScreenHandler::IsOfflineLoginActive() const { return (screen_mode_ == GAIA_SCREEN_MODE_OFFLINE) || offline_login_is_active_; } @@ -1207,7 +1347,8 @@ void GaiaScreenHandler::ShowGaiaScreenIfReady() { g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetDeviceNetworkConfigurationUpdater() - ->GetAllAuthorityCertificates()); + ->GetAllAuthorityCertificates( + chromeos::onc::CertificateScope::Default())); } LoadAuthExtension(!gaia_silent_load_ /* force */, false /* offline */); @@ -1296,7 +1437,6 @@ bool GaiaScreenHandler::BuildUserContextForGaiaSignIn( const SamlPasswordAttributes& password_attributes, UserContext* user_context, std::string* error_message) { - // TODO(emaxx,https://crbug.com/826417): Localize the error messages. *user_context = UserContext(user_type, account_id); if (using_saml && extension_provided_client_cert_usage_observer_ && extension_provided_client_cert_usage_observer_->ClientCertsWereUsed()) { @@ -1304,13 +1444,15 @@ bool GaiaScreenHandler::BuildUserContextForGaiaSignIn( std::vector<ChallengeResponseKey::SignatureAlgorithm> signature_algorithms; if (!extension_provided_client_cert_usage_observer_->GetOnlyUsedClientCert( &saml_client_cert, &signature_algorithms)) { - *error_message = "Multiple client certificates are not supported"; + *error_message = l10n_util::GetStringUTF8( + IDS_CHALLENGE_RESPONSE_AUTH_MULTIPLE_CLIENT_CERTS_ERROR); return false; } ChallengeResponseKey challenge_response_key; if (!ExtractChallengeResponseKeyFromCert( *saml_client_cert, signature_algorithms, &challenge_response_key)) { - *error_message = "Internal error"; + *error_message = l10n_util::GetStringUTF8( + IDS_CHALLENGE_RESPONSE_AUTH_INVALID_CLIENT_CERT_ERROR); return false; } user_context->GetMutableChallengeResponseKeys()->push_back( 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 1b1dd70e282..9cba09d99ff 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h @@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h" +#include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h" #include "chrome/browser/chromeos/login/login_client_cert_usage_observer.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h" @@ -19,6 +20,7 @@ #include "chromeos/network/portal_detector/network_portal_detector.h" #include "components/user_manager/user_type.h" #include "net/base/net_errors.h" +#include "net/cookies/canonical_cookie.h" class AccountId; @@ -26,10 +28,6 @@ namespace base { class DictionaryValue; } // namespace base -namespace net { -class CanonicalCookie; -} - namespace network { class NSSTempCertsCacheChromeOS; } @@ -75,7 +73,8 @@ class GaiaView { // A class that handles WebUI hooks in Gaia screen. class GaiaScreenHandler : public BaseScreenHandler, public GaiaView, - public NetworkPortalDetector::Observer { + public NetworkPortalDetector::Observer, + public SecurityTokenPinDialogHost { public: using TView = GaiaView; @@ -117,6 +116,18 @@ class GaiaScreenHandler : public BaseScreenHandler, const std::string& password, const std::string& services) override; + // SecurityTokenPinDialogHost: + void ShowSecurityTokenPinDialog( + const std::string& caller_extension_name, + SecurityTokenPinCodeType code_type, + bool enable_user_input, + SecurityTokenPinErrorLabel error_label, + int attempts_left, + const base::Optional<AccountId>& authenticating_user_account_id, + SecurityTokenPinEnteredCallback pin_entered_callback, + SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) override; + void CloseSecurityTokenPinDialog() override; + // Returns true if offline login mode was either required, or reported by the // WebUI (i.e. WebUI mignt not have completed transition to the new mode). bool IsOfflineLoginActive() const; @@ -174,7 +185,7 @@ class GaiaScreenHandler : public BaseScreenHandler, const NetworkPortalDetector::CaptivePortalState& state) override; // WebUI message handlers. - void HandleWebviewLoadAborted(const std::string& error_reason_str); + void HandleWebviewLoadAborted(int error_code); void HandleCompleteAuthentication( const std::string& gaia_id, const std::string& email, @@ -189,7 +200,7 @@ class GaiaScreenHandler : public BaseScreenHandler, bool using_saml, const ::login::StringList& services, const SamlPasswordAttributes& password_attributes, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies); void HandleCompleteLogin(const std::string& gaia_id, const std::string& typed_email, @@ -222,6 +233,12 @@ class GaiaScreenHandler : public BaseScreenHandler, // OOBE. void HandleShowGuestInOobe(bool show); + // Called to notify whether the SAML sign-in is currently happening. + void HandleSamlStateChanged(bool is_saml); + // Called to deliver the result of the security token PIN request. Called with + // an empty string when the request is canceled. + void HandleSecurityTokenPinEntered(const std::string& user_input); + void OnShowAddUser(); // Really handles the complete login message. @@ -397,7 +414,23 @@ class GaiaScreenHandler : public BaseScreenHandler, std::unique_ptr<LoginClientCertUsageObserver> extension_provided_client_cert_usage_observer_; - base::WeakPtrFactory<GaiaScreenHandler> weak_factory_; + // State of the security token PIN dialogs: + + // Whether this instance is currently registered as a host for showing the + // security token PIN dialogs. (See PinDialogManager for the default host.) + bool is_security_token_pin_enabled_ = false; + // The callback to run when the user submits a non-empty input to the security + // token PIN dialog. + // Is non-empty iff the dialog is active and the input wasn't sent yet. + SecurityTokenPinEnteredCallback security_token_pin_entered_callback_; + // The callback to run when the security token PIN dialog gets closed - either + // due to the user canceling the dialog or the whole sign-in attempt being + // aborted. + // Is non-empty iff the dialog is active. + SecurityTokenPinDialogClosedCallback + security_token_pin_dialog_closed_callback_; + + base::WeakPtrFactory<GaiaScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GaiaScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc index 476a82cbb5b..cc9f15d605b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.cc @@ -24,9 +24,7 @@ constexpr StaticOobeScreenId KioskEnableScreenView::kScreenId; KioskEnableScreenHandler::KioskEnableScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), - weak_ptr_factory_(this) { -} + : BaseScreenHandler(kScreenId, js_calls_container) {} KioskEnableScreenHandler::~KioskEnableScreenHandler() { if (delegate_) diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h index 7e7a8de528d..c6aa06760f7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h @@ -68,7 +68,7 @@ class KioskEnableScreenHandler : public KioskEnableScreenView, // True if machine's consumer kiosk mode is in a configurable state. bool is_configurable_ = false; - base::WeakPtrFactory<KioskEnableScreenHandler> weak_ptr_factory_; + base::WeakPtrFactory<KioskEnableScreenHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(KioskEnableScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc index c3dbe6c9ffb..8ec89e865c7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc @@ -426,8 +426,8 @@ void ResolveUILanguageList( const UILanguageListResolvedCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ResolveLanguageListInThreadPool, base::Passed(&language_switch_result), base::SequencedTaskRunnerHandle::Get(), callback)); @@ -581,9 +581,10 @@ void GetKeyboardLayoutsForLocale( // thread. std::string (*get_application_locale)(const std::string&, bool) = &l10n_util::GetApplicationLocale; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(get_application_locale, locale, false /* set_icu_locale */), base::BindOnce(&GetKeyboardLayoutsForResolvedLocale, locale, callback)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc index 7449e5194ca..25586cf34dd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util_unittest.cc @@ -11,7 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "base/values.h" #include "chrome/browser/chromeos/customization/customization_document.h" #include "chrome/browser/chromeos/input_method/input_method_configuration.h" @@ -58,7 +58,7 @@ class L10nUtilTest : public testing::Test { void SetInputMethods2(); private: - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; system::ScopedFakeStatisticsProvider scoped_fake_statistics_provider_; MockInputMethodManagerWithInputMethods* input_manager_; @@ -107,10 +107,10 @@ TEST_F(L10nUtilTest, FindMostRelevantLocale) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); dict->SetString("value", "de"); available_locales.Append(std::move(dict)); - dict.reset(new base::DictionaryValue); + dict = std::make_unique<base::DictionaryValue>(); dict->SetString("value", "fr"); available_locales.Append(std::move(dict)); - dict.reset(new base::DictionaryValue); + dict = std::make_unique<base::DictionaryValue>(); dict->SetString("value", "en-GB"); available_locales.Append(std::move(dict)); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc index 564cfbe0f74..e990f0f0868 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.cc @@ -7,7 +7,6 @@ #include "base/bind.h" #include "base/logging.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/screens/network_error.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chromeos/network/network_state.h" @@ -89,10 +88,7 @@ NetworkStateInformer::State GetStateForDefaultNetwork() { } // namespace -NetworkStateInformer::NetworkStateInformer() - : state_(OFFLINE), - weak_ptr_factory_(this) { -} +NetworkStateInformer::NetworkStateInformer() : state_(OFFLINE) {} NetworkStateInformer::~NetworkStateInformer() { if (NetworkHandler::IsInitialized()) { @@ -108,10 +104,6 @@ void NetworkStateInformer::Init() { this, FROM_HERE); network_portal_detector::GetInstance()->AddAndFireObserver(this); - - registrar_.Add(this, - chrome::NOTIFICATION_SESSION_STARTED, - content::NotificationService::AllSources()); } void NetworkStateInformer::AddObserver(NetworkStateInformerObserver* observer) { @@ -134,16 +126,6 @@ void NetworkStateInformer::OnPortalDetectionCompleted( UpdateStateAndNotify(); } -void NetworkStateInformer::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - if (type == chrome::NOTIFICATION_SESSION_STARTED) - registrar_.RemoveAll(); - else - NOTREACHED() << "Unknown notification: " << type; -} - void NetworkStateInformer::OnPortalDetected() { UpdateStateAndNotify(); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h index df2306eb8ec..32d79f0dc48 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/network_state_informer.h @@ -18,9 +18,6 @@ #include "chrome/browser/chromeos/login/ui/captive_portal_window_proxy.h" #include "chromeos/network/network_state_handler_observer.h" #include "chromeos/network/portal_detector/network_portal_detector.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" -#include "content/public/browser/notification_service.h" namespace base { class Value; @@ -34,7 +31,6 @@ namespace chromeos { class NetworkStateInformer : public chromeos::NetworkStateHandlerObserver, public chromeos::NetworkPortalDetector::Observer, - public content::NotificationObserver, public CaptivePortalWindowProxyDelegate, public base::RefCounted<NetworkStateInformer> { public: @@ -74,11 +70,6 @@ class NetworkStateInformer const NetworkState* network, const NetworkPortalDetector::CaptivePortalState& state) override; - // content::NotificationObserver implementation. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - // CaptivePortalWindowProxyDelegate implementation: void OnPortalDetected() override; @@ -102,9 +93,8 @@ class NetworkStateInformer std::unique_ptr<base::Value> proxy_config_; base::ObserverList<NetworkStateInformerObserver>::Unchecked observers_; - content::NotificationRegistrar registrar_; - base::WeakPtrFactory<NetworkStateInformer> weak_ptr_factory_; + base::WeakPtrFactory<NetworkStateInformer> weak_ptr_factory_{this}; }; } // namespace chromeos 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 57c06c6fd28..0b45e2d2f8f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc @@ -6,7 +6,7 @@ #include <stdint.h> -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/mojom/constants.mojom.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/strings/string_number_conversions.h" @@ -42,8 +42,7 @@ bool IsWhiteListedVendorId(uint16_t vendor_id) { } // namespace -OobeDisplayChooser::OobeDisplayChooser() - : scoped_observer_(this), weak_ptr_factory_(this) { +OobeDisplayChooser::OobeDisplayChooser() : scoped_observer_(this) { // |connector| may be null in tests. auto* connector = content::GetSystemConnector(); if (connector) { @@ -66,10 +65,9 @@ void OobeDisplayChooser::TryToPlaceUiOnTouchDisplay() { display::Screen::GetScreen()->GetPrimaryDisplay(); if (primary_display.is_valid() && !TouchSupportAvailable(primary_display)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay, - weak_ptr_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay, + weak_ptr_factory_.GetWeakPtr())); } } 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 5f2c67645d4..555050c7f87 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_OOBE_DISPLAY_CHOOSER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_OOBE_DISPLAY_CHOOSER_H_ -#include "ash/public/interfaces/cros_display_config.mojom.h" +#include "ash/public/mojom/cros_display_config.mojom.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" @@ -47,7 +47,7 @@ class OobeDisplayChooser : public ui::InputDeviceEventObserver { scoped_observer_; ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_; - base::WeakPtrFactory<OobeDisplayChooser> weak_ptr_factory_; + base::WeakPtrFactory<OobeDisplayChooser> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(OobeDisplayChooser); }; 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 b780e5acb2d..67f444cbacd 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc @@ -12,6 +12,7 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" +#include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "base/bind.h" #include "base/command_line.h" @@ -20,6 +21,7 @@ #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" +#include "build/branding_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/login/enrollment/auto_enrollment_check_screen_view.h" @@ -88,7 +90,6 @@ #include "chrome/grit/component_extension_resources.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/services/multidevice_setup/public/mojom/constants.mojom.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" @@ -133,9 +134,8 @@ constexpr char kOobeJSPath[] = "oobe.js"; constexpr char kProductLogoPath[] = "product-logo.png"; constexpr char kRecommendAppListViewHTMLPath[] = "recommend_app_list_view.html"; constexpr char kRecommendAppListViewJSPath[] = "recommend_app_list_view.js"; -constexpr char kStringsJSPath[] = "strings.js"; -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) constexpr char kLogo24PX1XSvgPath[] = "logo_24px-1x.svg"; constexpr char kLogo24PX2XSvgPath[] = "logo_24px-2x.svg"; constexpr char kSyncConsentIcons[] = "sync-consent-icons.html"; @@ -147,7 +147,7 @@ void AddProductLogoResources(content::WebUIDataSource* source) { source->AddResourcePath(kArcAssistantLogoPath, IDR_ASSISTANT_LOGO_PNG); source->AddResourcePath(kArcSupervisionIconPath, IDR_SUPERVISION_ICON_PNG); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) source->AddResourcePath(kLogo24PX1XSvgPath, IDR_PRODUCT_LOGO_24PX_1X); source->AddResourcePath(kLogo24PX2XSvgPath, IDR_PRODUCT_LOGO_24PX_2X); #endif @@ -157,7 +157,7 @@ void AddProductLogoResources(content::WebUIDataSource* source) { } void AddSyncConsentResources(content::WebUIDataSource* source) { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) source->AddResourcePath(kSyncConsentIcons, IDR_PRODUCT_CHROMEOS_SYNC_CONSENT_SCREEN_ICONS); // No #else section here as Sync Settings screen is Chrome-specific. @@ -179,12 +179,19 @@ void AddArcScreensResources(content::WebUIDataSource* source) { IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_HTML); } +void AddAssistantScreensResources(content::WebUIDataSource* source) { + source->AddResourcePath("voice_match_animation.json", + IDR_ASSISTANT_VOICE_MATCH_ANIMATION); + source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';"); +} + void AddFingerprintResources(content::WebUIDataSource* source) { int animation_id; + bool is_lottie_animation = false; switch (quick_unlock::GetFingerprintLocation()) { case quick_unlock::FingerprintLocation::TABLET_POWER_BUTTON: - animation_id = - IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_POWER_BUTTON_ANIMATION; + is_lottie_animation = true; + animation_id = IDR_LOGIN_FINGER_PRINT_TABLET_ANIMATION; break; case quick_unlock::FingerprintLocation::KEYBOARD_BOTTOM_RIGHT: animation_id = @@ -194,7 +201,20 @@ void AddFingerprintResources(content::WebUIDataSource* source) { animation_id = IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_TOP_RIGHT_ANIMATION; break; } - source->AddResourcePath("fingerprint_scanner_animation.png", animation_id); + if (is_lottie_animation) { + source->AddResourcePath("fingerprint_scanner_animation.json", animation_id); + + // To use lottie, the worker-src CSP needs to be updated for the web ui that + // is using it. Since as of now there are only a couple of webuis using + // lottie animations, this update has to be performed manually. As the usage + // increases, set this as the default so manual override is no longer + // required. + source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';"); + } else { + source->AddResourcePath("fingerprint_scanner_animation.png", animation_id); + } + + source->AddBoolean("useLottieAnimationForFingerprint", is_lottie_animation); } // Default and non-shared resource definition for kOobeDisplay display type. @@ -235,7 +255,7 @@ content::WebUIDataSource* CreateOobeUIDataSource( content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); - source->SetJsonPath(kStringsJSPath); + source->UseStringsJs(); // First, configure default and non-shared resources for the current display // type. @@ -255,6 +275,7 @@ content::WebUIDataSource* CreateOobeUIDataSource( AddFingerprintResources(source); AddSyncConsentResources(source); AddArcScreensResources(source); + AddAssistantScreensResources(source); source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyObjectSrc( @@ -482,10 +503,7 @@ void OobeUI::BindPrivilegedHostDeviceSetter( void OobeUI::BindCrosNetworkConfig( chromeos::network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(chromeos::network_config::mojom::kServiceName, - std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) @@ -552,7 +570,7 @@ void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) { const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, localized_strings); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) localized_strings->SetString("buildType", "chrome"); #else localized_strings->SetString("buildType", "chromium"); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc index 01aed9f684e..e86ea5107dc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.cc @@ -35,7 +35,7 @@ std::string ScreenlockIconSource::GetSource() const { void ScreenlockIconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { if (!icon_provider_) { callback.Run(GetDefaultIcon().As1xPNGBytes().get()); diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h index d6715f1afa8..44b13c43bd5 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/screenlock_icon_source.h @@ -24,7 +24,7 @@ class ScreenlockIconSource : public content::URLDataSource { std::string GetSource() const override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) const override; 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 eca0146a80f..aa0e6206df5 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,8 +11,9 @@ #include <vector> #include "ash/public/cpp/login_constants.h" +#include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/wallpaper_types.h" -#include "ash/public/interfaces/tray_action.mojom.h" +#include "ash/public/mojom/tray_action.mojom.h" #include "base/bind.h" #include "base/i18n/number_formatting.h" #include "base/location.h" @@ -64,7 +65,6 @@ #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/ui/ash/ime_controller_client.h" #include "chrome/browser/ui/ash/session_controller_client_impl.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/ash/wallpaper_controller_client.h" #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" #include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h" @@ -97,6 +97,8 @@ #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" #include "components/version_info/version_info.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_source.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -235,8 +237,7 @@ SigninScreenHandler::SigninScreenHandler( ->CapsLockIsEnabled()), proxy_auth_dialog_reload_times_(kMaxGaiaReloadForProxyAuthDialog), gaia_screen_handler_(gaia_screen_handler), - histogram_helper_(new ErrorScreensHistogramHelper("Signin")), - weak_factory_(this) { + histogram_helper_(new ErrorScreensHistogramHelper("Signin")) { DCHECK(network_state_informer_.get()); DCHECK(error_screen_); DCHECK(core_oobe_view_); @@ -266,9 +267,9 @@ SigninScreenHandler::SigninScreenHandler( base::Bind(&SigninScreenHandler::OnAllowedInputMethodsChanged, base::Unretained(this))); - TabletModeClient* tablet_mode_client = TabletModeClient::Get(); - tablet_mode_client->AddObserver(this); - OnTabletModeToggled(tablet_mode_client->tablet_mode_enabled()); + ash::TabletMode* tablet_mode = ash::TabletMode::Get(); + tablet_mode->AddObserver(this); + OnTabletModeToggled(tablet_mode->InTabletMode()); WallpaperControllerClient::Get()->AddObserver(this); } @@ -276,7 +277,9 @@ SigninScreenHandler::SigninScreenHandler( SigninScreenHandler::~SigninScreenHandler() { if (auto* wallpaper_controller_client = WallpaperControllerClient::Get()) wallpaper_controller_client->RemoveObserver(this); - TabletModeClient::Get()->RemoveObserver(this); + // Ash maybe released before us. + if (ash::TabletMode::Get()) + ash::TabletMode::Get()->RemoveObserver(this); OobeUI* oobe_ui = GetOobeUI(); if (oobe_ui && oobe_ui_observer_added_) oobe_ui->RemoveObserver(this); @@ -439,6 +442,8 @@ void SigninScreenHandler::RegisterMessages() { AddCallback("launchIncognito", &SigninScreenHandler::HandleLaunchIncognito); AddCallback("launchPublicSession", &SigninScreenHandler::HandleLaunchPublicSession); + AddCallback("launchSAMLPublicSession", + &SigninScreenHandler::HandleLaunchSAMLPublicSession); AddRawCallback("offlineLogin", &SigninScreenHandler::HandleOfflineLogin); AddCallback("rebootSystem", &SigninScreenHandler::HandleRebootSystem); AddCallback("removeUser", &SigninScreenHandler::HandleRemoveUser); @@ -1016,6 +1021,14 @@ void SigninScreenHandler::SuspendDone(const base::TimeDelta& sleep_duration) { } } +void SigninScreenHandler::OnTabletModeStarted() { + OnTabletModeToggled(true); +} + +void SigninScreenHandler::OnTabletModeEnded() { + OnTabletModeToggled(false); +} + void SigninScreenHandler::OnTabletModeToggled(bool enabled) { CallJS("login.AccountPickerScreen.setTabletModeState", enabled); } @@ -1102,6 +1115,14 @@ void SigninScreenHandler::HandleLaunchIncognito() { delegate_->Login(context, SigninSpecifics()); } +void SigninScreenHandler::HandleLaunchSAMLPublicSession( + const std::string& email) { + const AccountId account_id = user_manager::known_user::GetAccountId( + email, std::string() /* id */, AccountType::UNKNOWN); + SigninScreenHandler::HandleLaunchPublicSession(account_id, std::string(), + std::string()); +} + void SigninScreenHandler::HandleLaunchPublicSession( const AccountId& account_id, const std::string& locale, @@ -1367,7 +1388,7 @@ void SigninScreenHandler::SendPublicSessionKeyboardLayouts( void SigninScreenHandler::HandleGetTabletModeState() { CallJS("login.AccountPickerScreen.setTabletModeState", - TabletModeClient::Get()->tablet_mode_enabled()); + ash::TabletMode::Get()->InTabletMode()); } void SigninScreenHandler::HandleGetDemoModeState() { 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 48988d3b853..6195aa7c0d3 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,6 +10,7 @@ #include <set> #include <string> +#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/wallpaper_controller_observer.h" #include "base/callback.h" #include "base/compiler_specific.h" @@ -21,7 +22,6 @@ #include "chrome/browser/chromeos/login/signin_specifics.h" #include "chrome/browser/chromeos/login/ui/login_display.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/ui/ash/tablet_mode_client_observer.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" @@ -183,7 +183,7 @@ class SigninScreenHandler public NetworkStateInformer::NetworkStateInformerObserver, public PowerManagerClient::Observer, public input_method::ImeKeyboard::Observer, - public TabletModeClientObserver, + public ash::TabletModeObserver, public OobeUI::Observer, public ash::WallpaperControllerObserver { public: @@ -302,8 +302,11 @@ class SigninScreenHandler // PowerManagerClient::Observer implementation: void SuspendDone(const base::TimeDelta& sleep_duration) override; - // TabletModeClientObserver: - void OnTabletModeToggled(bool enabled) override; + // ash::TabletModeObserver: + void OnTabletModeStarted() override; + void OnTabletModeEnded() override; + + void OnTabletModeToggled(bool enabled); // Restore input focus to current user pod. void RefocusCurrentPod(); @@ -324,6 +327,7 @@ class SigninScreenHandler const std::string& password); void HandleAttemptUnlock(const std::string& username); void HandleLaunchIncognito(); + void HandleLaunchSAMLPublicSession(const std::string& email); void HandleLaunchPublicSession(const AccountId& account_id, const std::string& locale, const std::string& input_method); @@ -503,7 +507,7 @@ class SigninScreenHandler std::unique_ptr<AccountId> focused_pod_account_id_; - base::WeakPtrFactory<SigninScreenHandler> weak_factory_; + base::WeakPtrFactory<SigninScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SigninScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc index a235cccacbf..205688cf91b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_userlist_unittest.cc @@ -18,7 +18,7 @@ #include "components/account_id/account_id.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -52,8 +52,8 @@ class SigninPrepareUserListTest : public testing::Test, profile_manager_.reset( new TestingProfileManager(TestingBrowserProcess::GetGlobal())); ASSERT_TRUE(profile_manager_->SetUp()); - controller_.reset(new MultiProfileUserController( - this, TestingBrowserProcess::GetGlobal()->local_state())); + controller_ = std::make_unique<MultiProfileUserController>( + this, TestingBrowserProcess::GetGlobal()->local_state()); fake_user_manager_->set_multi_profile_user_controller(controller_.get()); for (size_t i = 0; i < base::size(kUsersPublic); ++i) @@ -78,7 +78,7 @@ class SigninPrepareUserListTest : public testing::Test, FakeChromeUserManager* user_manager() { return fake_user_manager_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; ScopedCrosSettingsTestHelper cros_settings_test_helper_; FakeChromeUserManager* fake_user_manager_; user_manager::ScopedUserManager user_manager_enabler_; diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc index bea38eec2ff..e4b7d641ffc 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.cc @@ -13,7 +13,7 @@ constexpr StaticOobeScreenId UserBoardView::kScreenId; UserBoardScreenHandler::UserBoardScreenHandler( JSCallsContainer* js_calls_container) - : BaseScreenHandler(kScreenId, js_calls_container), weak_factory_(this) {} + : BaseScreenHandler(kScreenId, js_calls_container) {} UserBoardScreenHandler::~UserBoardScreenHandler() { } diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h index ada66bdbba9..8aadb916d4d 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h @@ -63,7 +63,7 @@ class UserBoardScreenHandler : public BaseScreenHandler, public UserBoardView { base::WeakPtr<UserBoardView> GetWeakPtr() override; UserSelectionScreen* screen_ = nullptr; - base::WeakPtrFactory<UserBoardScreenHandler> weak_factory_; + base::WeakPtrFactory<UserBoardScreenHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(UserBoardScreenHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn index f6ccee9ab2e..3adbd9c1354 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn @@ -12,7 +12,4 @@ mojom("mojo_bindings") { deps = [ "//chromeos/services/machine_learning/public/mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc index a436b2ad466..dc4915027ca 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.cc @@ -91,7 +91,7 @@ MultiDeviceSetupDialogUI::MultiDeviceSetupDialogUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUIMultiDeviceSetupHost); chromeos::multidevice_setup::AddLocalizedStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource( IDR_MULTIDEVICE_SETUP_MULTIDEVICE_SETUP_DIALOG_HTML); diff --git a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc index 7a95459f913..9314ef72f38 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.cc @@ -25,6 +25,7 @@ #include "content/public/browser/web_ui_data_source.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/chromeos/devicetype_utils.h" namespace chromeos { @@ -47,8 +48,6 @@ constexpr LocalizedString kLocalizedStringsWithoutPlaceholders[] = { IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MULTIPLE_DEVICE_HEADER}, {"startSetupPageSingleDeviceHeader", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_SINGLE_DEVICE_HEADER}, - {"startSetupPageFeatureListHeader", - IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FEATURE_LIST_HEADER}, {"startSetupPageFeatureListInstallApps", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_INSTALL_APPS_DESCRIPTION}, {"startSetupPageFeatureListAddFeatures", @@ -83,6 +82,7 @@ GetLocalizedStringsWithPlaceholders() { "startSetupPageMessage", l10n_util::GetStringFUTF16( IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE, + ui::GetChromeOSDeviceName(), base::ASCIIToUTF16(kFootnoteMarker), base::UTF8ToUTF16( chromeos::multidevice_setup:: @@ -96,6 +96,12 @@ GetLocalizedStringsWithPlaceholders() { base::ASCIIToUTF16(kFootnoteMarker))); localized_strings.emplace_back( + "startSetupPageFeatureListHeader", + l10n_util::GetStringFUTF16( + IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FEATURE_LIST_HEADER, + ui::GetChromeOSDeviceName())); + + localized_strings.emplace_back( "startSetupPageFeatureListAwm", l10n_util::GetStringFUTF16( IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_AWM_DESCRIPTION, @@ -128,11 +134,15 @@ void AddLocalizedValuesToBuilder(::login::LocalizedValuesBuilder* builder) { // localization calls separately. builder->AddF( "startSetupPageMessage", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_MESSAGE, - base::ASCIIToUTF16(kFootnoteMarker), + ui::GetChromeOSDeviceName(), base::ASCIIToUTF16(kFootnoteMarker), base::UTF8ToUTF16(chromeos::multidevice_setup:: GetBoardSpecificBetterTogetherSuiteLearnMoreUrl() .spec())); + builder->AddF("startSetupPageFeatureListHeader", + IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FEATURE_LIST_HEADER, + ui::GetChromeOSDeviceName()); + builder->AddF("startSetupPageFootnote", IDS_MULTIDEVICE_SETUP_START_SETUP_PAGE_FOOTNOTE, base::ASCIIToUTF16(kFootnoteMarker)); 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 34e2447eafb..2bea1501801 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 @@ -32,7 +32,6 @@ constexpr LocalizedString kElementLocalizedStrings[] = { {"OncTypeTether", IDS_NETWORK_TYPE_TETHER}, {"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}, @@ -76,6 +75,8 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { IDS_ONC_CELLULAR_ACTIVATION_STATE_NOT_ACTIVATED}, {"OncCellular-ActivationState_PartiallyActivated", IDS_ONC_CELLULAR_ACTIVATION_STATE_PARTIALLY_ACTIVATED}, + {"OncCellular-ActivationState_NoService", + IDS_ONC_CELLULAR_ACTIVATION_STATE_NO_SERVICE}, {"OncCellular-Family", IDS_ONC_CELLULAR_FAMILY}, {"OncCellular-FirmwareRevision", IDS_ONC_CELLULAR_FIRMWARE_REVISION}, {"OncCellular-HardwareRevision", IDS_ONC_CELLULAR_HARDWARE_REVISION}, @@ -86,7 +87,6 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"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", @@ -138,11 +138,11 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"OncVPN-IPsec-PSK", IDS_ONC_VPN_IPSEC_PSK}, {"OncVPN-L2TP-Password", IDS_ONC_VPN_PASSWORD}, {"OncVPN-L2TP-Username", IDS_ONC_VPN_USERNAME}, + {"OncVPN-OpenVPN-ExtraHosts", IDS_ONC_VPN_OPENVPN_EXTRA_HOSTS}, {"OncVPN-OpenVPN-OTP", IDS_ONC_VPN_OPENVPN_OTP}, {"OncVPN-OpenVPN-Password", IDS_ONC_VPN_PASSWORD}, {"OncVPN-OpenVPN-Username", IDS_ONC_VPN_USERNAME}, - {"OncVPN-ThirdPartyVPN-ProviderName", - IDS_ONC_VPN_THIRD_PARTY_VPN_PROVIDER_NAME}, + {"OncVPN-ProviderName", IDS_ONC_VPN_THIRD_PARTY_VPN_PROVIDER_NAME}, {"OncVPN-Type", IDS_ONC_VPN_TYPE}, {"OncVPN-Type_L2TP_IPsec", IDS_ONC_VPN_TYPE_L2TP_IPSEC}, {"OncVPN-Type_L2TP_IPsec_PSK", IDS_ONC_VPN_TYPE_L2TP_IPSEC_PSK}, @@ -159,7 +159,6 @@ void AddOncLocalizedStrings(content::WebUIDataSource* html_source) { {"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}, diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc index 4c767fef5ea..6e1c9d1f886 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc @@ -8,6 +8,7 @@ #include <string> #include <utility> +#include "ash/public/cpp/network_config_service.h" #include "base/bind.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -27,14 +28,12 @@ #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/onc/onc_utils.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/device_event_log/device_event_log.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" -#include "services/service_manager/public/cpp/connector.h" #include "third_party/cros_system_api/dbus/service_constants.h" #include "ui/base/l10n/l10n_util.h" @@ -88,7 +87,7 @@ void SetDeviceProperties(base::DictionaryValue* dictionary) { class NetworkConfigMessageHandler : public content::WebUIMessageHandler { public: - NetworkConfigMessageHandler() : weak_ptr_factory_(this) {} + NetworkConfigMessageHandler() {} ~NetworkConfigMessageHandler() override {} // WebUIMessageHandler implementation. @@ -273,7 +272,7 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler { InternetConfigDialog::ShowDialogForNetworkType(onc_type); } - base::WeakPtrFactory<NetworkConfigMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<NetworkConfigMessageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NetworkConfigMessageHandler); }; @@ -363,7 +362,7 @@ NetworkUI::NetworkUI(content::WebUI* web_ui) network_element::AddLocalizedStrings(html); - html->SetJsonPath("strings.js"); + html->UseStringsJs(); html->AddResourcePath("network_ui.css", IDR_NETWORK_UI_CSS); html->AddResourcePath("network_ui.js", IDR_NETWORK_UI_JS); html->SetDefaultResource(IDR_NETWORK_UI_HTML); @@ -378,9 +377,7 @@ NetworkUI::~NetworkUI() {} void NetworkUI::BindCrosNetworkConfig( network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(network_config::mojom::kServiceName, std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc index dd93475bca4..b77f4d2f921 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/power_ui.cc @@ -33,8 +33,6 @@ namespace chromeos { namespace { -const char kStringsJsFile[] = "strings.js"; - const char kRequestBatteryChargeDataCallback[] = "requestBatteryChargeData"; const char kOnRequestBatteryChargeDataFunction[] = "powerUI.showBatteryChargeData"; @@ -260,7 +258,7 @@ PowerUI::PowerUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { }; AddLocalizedStringsBulk(html, kStrings, base::size(kStrings)); - html->SetJsonPath(kStringsJsFile); + html->UseStringsJs(); html->AddResourcePath("power.css", IDR_ABOUT_POWER_CSS); html->AddResourcePath("power.js", IDR_ABOUT_POWER_JS); 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 7c2890f0231..1376878c1d8 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc @@ -128,6 +128,12 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler, return; } + double seconds; + if (!args->GetDouble(0, &seconds)) { + NOTREACHED(); + return; + } + AccountId account_id; bool is_user_logged_in = user_manager::UserManager::Get()->IsUserLoggedIn(); if (is_user_logged_in) { @@ -139,7 +145,8 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler, base::BindRepeating(&SetTimeMessageHandler::OnParentAccessValidation, weak_factory_.GetWeakPtr()), ash::ParentAccessRequestReason::kChangeTime, - !is_user_logged_in /* extra_dimmer */); + !is_user_logged_in /* extra_dimmer */, + base::Time::FromDoubleT(seconds)); } void OnParentAccessValidation(bool success) { @@ -188,7 +195,7 @@ SetTimeUI::SetTimeUI(content::WebUI* web_ui) : WebDialogUI(web_ui) { values.SetDouble("buildTime", base::GetBuildTime().ToJsTime()); source->AddLocalizedStrings(values); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("set_time_browser_proxy.html", IDR_SET_TIME_BROWSER_PROXY_HTML); diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc index 07d906c1abd..c5c1b2cba55 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc @@ -34,7 +34,7 @@ std::string SlowTraceSource::GetSource() { void SlowTraceSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { int trace_id = 0; size_t pos = path.find('#'); diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h index 77a04463b1d..8d0007981f7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h @@ -32,7 +32,7 @@ class SlowTraceSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc index 4e199978350..1020d867f72 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/slow_ui.cc @@ -101,7 +101,7 @@ void SlowHandler::RegisterMessages() { kJsApiLoadComplete, base::BindRepeating(&SlowHandler::LoadComplete, base::Unretained(this))); - user_pref_registrar_.reset(new PrefChangeRegistrar); + user_pref_registrar_ = std::make_unique<PrefChangeRegistrar>(); user_pref_registrar_->Init(profile_->GetPrefs()); user_pref_registrar_->Add(prefs::kPerformanceTracingEnabled, base::Bind(&SlowHandler::UpdatePage, diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc index d20bb682266..4b31716cbeb 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc @@ -87,7 +87,7 @@ SmbCredentialsDialogUI::SmbCredentialsDialogUI(content::WebUI* web_ui) AddSmbCredentialsDialogStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SMB_CREDENTIALS_DIALOG_CONTAINER_HTML); source->AddResourcePath("smb_credentials_dialog.html", IDR_SMB_CREDENTIALS_DIALOG_HTML); diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc index 4b224daa69c..819e4fb6cf7 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc @@ -32,8 +32,7 @@ base::Value BuildShareList(const std::vector<smb_client::SmbUrl>& shares) { } // namespace -SmbHandler::SmbHandler(Profile* profile) - : profile_(profile), weak_ptr_factory_(this) {} +SmbHandler::SmbHandler(Profile* profile) : profile_(profile) {} SmbHandler::~SmbHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h index 38354b5e168..ef94923201b 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h @@ -6,7 +6,6 @@ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_SMB_SHARES_SMB_HANDLER_H_ #include "base/callback_forward.h" -#include "base/files/file.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/smb_client/smb_service.h" @@ -52,7 +51,7 @@ class SmbHandler : public content::WebUIMessageHandler { bool host_discovery_done_ = false; base::OnceClosure stored_mount_call_; Profile* const profile_; - base::WeakPtrFactory<SmbHandler> weak_ptr_factory_; + base::WeakPtrFactory<SmbHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SmbHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc index ac5be07201d..5bbece77c06 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc @@ -70,7 +70,7 @@ SmbShareDialogUI::SmbShareDialogUI(content::WebUI* web_ui) source->AddBoolean("isActiveDirectoryUser", user && user->IsActiveDirectoryUser()); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SMB_SHARES_DIALOG_CONTAINER_HTML); source->AddResourcePath("smb_share_dialog.html", IDR_SMB_SHARES_DIALOG_HTML); source->AddResourcePath("smb_share_dialog.js", IDR_SMB_SHARES_DIALOG_JS); diff --git a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc index d84d732aa42..23d28d7e47f 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.cc @@ -198,8 +198,7 @@ base::Value GetSysInfo() { } // namespace -SysInternalsMessageHandler::SysInternalsMessageHandler() - : weak_ptr_factory_(this) {} +SysInternalsMessageHandler::SysInternalsMessageHandler() {} SysInternalsMessageHandler::~SysInternalsMessageHandler() {} @@ -222,8 +221,9 @@ void SysInternalsMessageHandler::HandleGetSysInfo(const base::ListValue* args) { } base::Value callback_id = list[0].Clone(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, base::MayBlock(), base::BindOnce(&GetSysInfo), + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&GetSysInfo), base::BindOnce(&SysInternalsMessageHandler::ReplySysInfo, weak_ptr_factory_.GetWeakPtr(), std::move(callback_id))); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h index 4a21bbabe73..6e84b36f0b2 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_message_handler.h @@ -59,7 +59,7 @@ class SysInternalsMessageHandler : public content::WebUIMessageHandler { // void ReplySysInfo(base::Value callback_id, base::Value result); - base::WeakPtrFactory<SysInternalsMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<SysInternalsMessageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SysInternalsMessageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc index 6fcd5cd124a..ce6790a8ec3 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc @@ -162,8 +162,9 @@ void SystemWebDialogDelegate::ShowSystemDialogForBrowserContext( if (!parent && GetDialogModalType() == ui::MODAL_TYPE_NONE) extra_params.z_order = ui::ZOrderLevel::kFloatingWindow; AdjustWidgetInitParams(&extra_params); - dialog_window_ = chrome::ShowWebDialogWithParams(parent, browser_context, - this, &extra_params); + dialog_window_ = chrome::ShowWebDialogWithParams( + parent, browser_context, this, + base::make_optional<views::Widget::InitParams>(std::move(extra_params))); } void SystemWebDialogDelegate::ShowSystemDialog(gfx::NativeWindow parent) { diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc index 889a692e022..2609acbbbde 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc @@ -26,7 +26,8 @@ constexpr char kDefaultMime[] = "text/html"; void ReadFile(const base::FilePath& path, const content::URLDataSource::GotDataCallback& callback) { std::string content; - CHECK(base::ReadFileToString(path, &content)) << path; + bool result = base::ReadFileToString(path, &content); + DCHECK(result) << path; scoped_refptr<base::RefCountedString> response = base::RefCountedString::TakeString(&content); callback.Run(response.get()); @@ -39,16 +40,17 @@ std::string TerminalSource::GetSource() { void TerminalSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { - base::FilePath file_path(kTerminalRoot); - if (path.empty()) { - file_path = file_path.Append(kDefaultFile); - } else { - file_path = file_path.Append(path); - } - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + // Reparse path to strip any query or fragment, skip first '/' in path. + std::string reparsed = + GURL(chrome::kChromeUITerminalURL + path).path().substr(1); + if (reparsed.empty()) + reparsed = kDefaultFile; + base::FilePath file_path = base::FilePath(kTerminalRoot).Append(reparsed); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFile, file_path, callback)); } diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h index dc922840e02..b5acfdeb435 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h @@ -8,8 +8,8 @@ #include <string> #include "base/macros.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/browser/url_data_source.h" +#include "content/public/browser/web_contents.h" class TerminalSource : public content::URLDataSource { public: @@ -21,7 +21,7 @@ class TerminalSource : public content::URLDataSource { void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc index 63c867618b6..e8ca63d7cbf 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc @@ -179,7 +179,7 @@ std::string UserImageSource::GetSource() { void UserImageSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { std::string email; int frame = -1; diff --git a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h index 1e73aed0637..f20af23e762 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h @@ -33,7 +33,7 @@ class UserImageSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; diff --git a/chromium/chrome/browser/ui/webui/chromeos/video_source.cc b/chromium/chrome/browser/ui/webui/chromeos/video_source.cc index 4db1b33388d..4b56024a718 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/video_source.cc +++ b/chromium/chrome/browser/ui/webui/chromeos/video_source.cc @@ -14,7 +14,7 @@ #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/task/post_task.h" -#include "base/task/thread_pool/thread_pool.h" +#include "base/task/thread_pool/thread_pool_instance.h" #include "base/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/common/url_constants.h" @@ -54,9 +54,9 @@ void VideoLoaded( } // namespace -VideoSource::VideoSource() : weak_factory_(this) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, +VideoSource::VideoSource() { + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } @@ -68,7 +68,7 @@ std::string VideoSource::GetSource() { void VideoSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& got_data_callback) { if (!IsWhitelisted(path)) { got_data_callback.Run(nullptr); @@ -77,8 +77,9 @@ void VideoSource::StartDataRequest( const base::FilePath asset_dir(chrome::kChromeOSAssetPath); const base::FilePath video_path = asset_dir.AppendASCII(path); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&base::PathExists, video_path), base::BindOnce(&VideoSource::StartDataRequestAfterPathExists, weak_factory_.GetWeakPtr(), video_path, diff --git a/chromium/chrome/browser/ui/webui/chromeos/video_source.h b/chromium/chrome/browser/ui/webui/chromeos/video_source.h index 316509a93ec..c8f6cae1d3a 100644 --- a/chromium/chrome/browser/ui/webui/chromeos/video_source.h +++ b/chromium/chrome/browser/ui/webui/chromeos/video_source.h @@ -29,11 +29,10 @@ class VideoSource : public content::URLDataSource { // content::URLDataSource: std::string GetSource() override; - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& got_data_callback) - override; + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const content::URLDataSource::GotDataCallback& + got_data_callback) override; std::string GetMimeType(const std::string& path) override; private: @@ -46,7 +45,7 @@ class VideoSource : public content::URLDataSource { // The background task runner on which file I/O is performed. scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<VideoSource> weak_factory_; + base::WeakPtrFactory<VideoSource> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VideoSource); }; diff --git a/chromium/chrome/browser/ui/webui/components_ui.cc b/chromium/chrome/browser/ui/webui/components_ui.cc index 8ae8e72db64..e4686db9b66 100644 --- a/chromium/chrome/browser/ui/webui/components_ui.cc +++ b/chromium/chrome/browser/ui/webui/components_ui.cc @@ -67,7 +67,7 @@ content::WebUIDataSource* CreateComponentsUIHTMLSource(Profile* profile) { profile->IsOffTheRecord() #endif ); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("components.js", IDR_COMPONENTS_JS); source->SetDefaultResource(IDR_COMPONENTS_HTML); return source; diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc index 0b218719771..caf0202c54d 100644 --- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc @@ -495,17 +495,16 @@ void ConflictsDataFetcher::OnModuleDatabaseIdle() { #if defined(GOOGLE_CHROME_BUILD) // The state of third-party features must be determined on the UI thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( OnModuleDataFetched, std::move(on_conflicts_data_fetched_callback_), std::move(results), std::move(third_party_conflicts_manager_state_))); #else // The third-party features are always disabled on Chromium builds. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(OnConflictsDataFetched, - std::move(on_conflicts_data_fetched_callback_), - std::move(results), kNonGoogleChromeBuild)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(OnConflictsDataFetched, + std::move(on_conflicts_data_fetched_callback_), + std::move(results), kNonGoogleChromeBuild)); #endif } diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc index 55b5fc5ef3e..013e61657b4 100644 --- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.cc @@ -13,8 +13,7 @@ #include "content/public/browser/web_ui.h" ConflictsHandler::ConflictsHandler() - : conflicts_data_fetcher_(nullptr, base::OnTaskRunnerDeleter(nullptr)), - weak_ptr_factory_(this) {} + : conflicts_data_fetcher_(nullptr, base::OnTaskRunnerDeleter(nullptr)) {} ConflictsHandler::~ConflictsHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h index 35f4dcc7d36..e10db79f2a0 100644 --- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h +++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_handler.h @@ -40,7 +40,7 @@ class ConflictsHandler : public content::WebUIMessageHandler { // lives on a different sequence. ConflictsDataFetcher::UniquePtr conflicts_data_fetcher_; - base::WeakPtrFactory<ConflictsHandler> weak_ptr_factory_; + base::WeakPtrFactory<ConflictsHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ConflictsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/crashes_ui.cc b/chromium/chrome/browser/ui/webui/crashes_ui.cc index 9dbca7c9102..d150c2cc8d5 100644 --- a/chromium/chrome/browser/ui/webui/crashes_ui.cc +++ b/chromium/chrome/browser/ui/webui/crashes_ui.cc @@ -46,16 +46,17 @@ content::WebUIDataSource* CreateCrashesUIHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUICrashesHost); - for (size_t i = 0; i < crash::kCrashesUILocalizedStringsCount; ++i) { + for (size_t i = 0; i < crash_reporter::kCrashesUILocalizedStringsCount; ++i) { source->AddLocalizedString( - crash::kCrashesUILocalizedStrings[i].name, - crash::kCrashesUILocalizedStrings[i].resource_id); + crash_reporter::kCrashesUILocalizedStrings[i].name, + crash_reporter::kCrashesUILocalizedStrings[i].resource_id); } - source->AddLocalizedString(crash::kCrashesUIShortProductName, + source->AddLocalizedString(crash_reporter::kCrashesUIShortProductName, IDS_SHORT_PRODUCT_NAME); - source->SetJsonPath("strings.js"); - source->AddResourcePath(crash::kCrashesUICrashesJS, IDR_CRASH_CRASHES_JS); + source->UseStringsJs(); + source->AddResourcePath(crash_reporter::kCrashesUICrashesJS, + IDR_CRASH_CRASHES_JS); source->SetDefaultResource(IDR_CRASH_CRASHES_HTML); return source; } @@ -112,19 +113,19 @@ void CrashesDOMHandler::RegisterMessages() { upload_list_->Load(base::BindOnce(&CrashesDOMHandler::OnUploadListAvailable, base::Unretained(this))); web_ui()->RegisterMessageCallback( - crash::kCrashesUIRequestCrashList, + crash_reporter::kCrashesUIRequestCrashList, base::BindRepeating(&CrashesDOMHandler::HandleRequestCrashes, base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( - crash::kCrashesUIRequestCrashUpload, + crash_reporter::kCrashesUIRequestCrashUpload, base::BindRepeating(&CrashesDOMHandler::HandleRequestUploads, base::Unretained(this))); #endif web_ui()->RegisterMessageCallback( - crash::kCrashesUIRequestSingleCrashUpload, + crash_reporter::kCrashesUIRequestSingleCrashUpload, base::BindRepeating(&CrashesDOMHandler::HandleRequestSingleCrashUpload, base::Unretained(this))); } @@ -183,7 +184,7 @@ void CrashesDOMHandler::UpdateUI() { base::ListValue crash_list; if (upload_list) - crash::UploadListToValue(upload_list_.get(), &crash_list); + crash_reporter::UploadListToValue(upload_list_.get(), &crash_list); base::Value enabled(crash_reporting_enabled); base::Value dynamic_backend(system_crash_reporter); @@ -199,8 +200,8 @@ void CrashesDOMHandler::UpdateUI() { args.push_back(&crash_list); args.push_back(&version); args.push_back(&os_string); - web_ui()->CallJavascriptFunctionUnsafe(crash::kCrashesUIUpdateCrashList, - args); + web_ui()->CallJavascriptFunctionUnsafe( + crash_reporter::kCrashesUIUpdateCrashList, args); } void CrashesDOMHandler::HandleRequestSingleCrashUpload( diff --git a/chromium/chrome/browser/ui/webui/device_log_ui.cc b/chromium/chrome/browser/ui/webui/device_log_ui.cc index 1eb85455185..f30a8f8c9ae 100644 --- a/chromium/chrome/browser/ui/webui/device_log_ui.cc +++ b/chromium/chrome/browser/ui/webui/device_log_ui.cc @@ -91,7 +91,7 @@ DeviceLogUI::DeviceLogUI(content::WebUI* web_ui) }; AddLocalizedStringsBulk(html, kStrings, base::size(kStrings)); - html->SetJsonPath("strings.js"); + html->UseStringsJs(); html->AddResourcePath("device_log_ui.css", IDR_DEVICE_LOG_UI_CSS); html->AddResourcePath("device_log_ui.js", IDR_DEVICE_LOG_UI_JS); html->SetDefaultResource(IDR_DEVICE_LOG_UI_HTML); diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc index a9cc1d845e7..5217a31c8d6 100644 --- a/chromium/chrome/browser/ui/webui/devtools_ui.cc +++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc @@ -4,407 +4,16 @@ #include "chrome/browser/ui/webui/devtools_ui.h" -#include <list> -#include <utility> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/macros.h" -#include "base/memory/ref_counted_memory.h" -#include "base/path_service.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/task/post_task.h" #include "chrome/browser/devtools/url_constants.h" -#include "chrome/common/chrome_paths.h" +#include "chrome/browser/ui/webui/devtools_ui_data_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/user_agent.h" -#include "net/base/filename_util.h" #include "net/base/load_flags.h" -#include "net/traffic_annotation/network_traffic_annotation.h" -#include "services/network/public/cpp/resource_request.h" -#include "services/network/public/cpp/simple_url_loader.h" -#include "third_party/blink/public/public_buildflags.h" - -using content::BrowserThread; -using content::WebContents; - -namespace { - -std::string PathWithoutParams(const std::string& path) { - return GURL(std::string("devtools://devtools/") + path).path().substr(1); -} - -scoped_refptr<base::RefCountedMemory> CreateNotFoundResponse() { - const char kHttpNotFound[] = "HTTP/1.1 404 Not Found\n\n"; - return base::MakeRefCounted<base::RefCountedStaticMemory>( - kHttpNotFound, strlen(kHttpNotFound)); -} - -// DevToolsDataSource --------------------------------------------------------- - -std::string GetMimeTypeForPath(const std::string& path) { - std::string filename = PathWithoutParams(path); - if (base::EndsWith(filename, ".html", base::CompareCase::INSENSITIVE_ASCII)) { - return "text/html"; - } else if (base::EndsWith(filename, ".css", - base::CompareCase::INSENSITIVE_ASCII)) { - return "text/css"; - } else if (base::EndsWith(filename, ".js", - base::CompareCase::INSENSITIVE_ASCII)) { - return "application/javascript"; - } else if (base::EndsWith(filename, ".png", - base::CompareCase::INSENSITIVE_ASCII)) { - return "image/png"; - } else if (base::EndsWith(filename, ".gif", - base::CompareCase::INSENSITIVE_ASCII)) { - return "image/gif"; - } else if (base::EndsWith(filename, ".svg", - base::CompareCase::INSENSITIVE_ASCII)) { - return "image/svg+xml"; - } else if (base::EndsWith(filename, ".manifest", - base::CompareCase::INSENSITIVE_ASCII)) { - return "text/cache-manifest"; - } - return "text/html"; -} - -// An URLDataSource implementation that handles devtools://devtools/ -// requests. Three types of requests could be handled based on the URL path: -// 1. /bundled/: bundled DevTools frontend is served. -// 2. /remote/: remote DevTools frontend is served from App Engine. -// 3. /custom/: custom DevTools frontend is served from the server as specified -// by the --custom-devtools-frontend flag. -class DevToolsDataSource : public content::URLDataSource { - public: - using GotDataCallback = content::URLDataSource::GotDataCallback; - - explicit DevToolsDataSource( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) - : url_loader_factory_(std::move(url_loader_factory)) {} - ~DevToolsDataSource() override = default; - - // content::URLDataSource implementation. - std::string GetSource() override; - - void StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const GotDataCallback& callback) override; - - private: - struct PendingRequest; - - // content::URLDataSource overrides. - std::string GetMimeType(const std::string& path) override; - bool ShouldAddContentSecurityPolicy() override; - bool ShouldDenyXFrameOptions() override; - bool ShouldServeMimeTypeAsContentTypeHeader() override; - - void OnLoadComplete(std::list<PendingRequest>::iterator request_iter, - std::unique_ptr<std::string> response_body); - - // Serves bundled DevTools frontend from ResourceBundle. - void StartBundledDataRequest(const std::string& path, - const GotDataCallback& callback); - - // Serves remote DevTools frontend from hard-coded App Engine domain. - void StartRemoteDataRequest(const GURL& url, const GotDataCallback& callback); - - // Serves remote DevTools frontend from any endpoint, passed through - // command-line flag. - void StartCustomDataRequest(const GURL& url, - const GotDataCallback& callback); - - void StartNetworkRequest( - const GURL& url, - const net::NetworkTrafficAnnotationTag& traffic_annotation, - int load_flags, - const GotDataCallback& callback); - -#if BUILDFLAG(DEBUG_DEVTOOLS) - void StartFileRequestForDebugDevtools(const std::string& path, - const GotDataCallback& callback); -#endif - - struct PendingRequest { - PendingRequest() = default; - PendingRequest(PendingRequest&& other) = default; - PendingRequest& operator=(PendingRequest&& other) = default; - - ~PendingRequest() { - if (callback) - callback.Run(CreateNotFoundResponse()); - } - - GotDataCallback callback; - std::unique_ptr<network::SimpleURLLoader> loader; - - DISALLOW_COPY_AND_ASSIGN(PendingRequest); - }; - - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - std::list<PendingRequest> pending_requests_; - - DISALLOW_COPY_AND_ASSIGN(DevToolsDataSource); -}; - -std::string DevToolsDataSource::GetSource() { - return chrome::kChromeUIDevToolsHost; -} - -void DevToolsDataSource::StartDataRequest( - const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, - const content::URLDataSource::GotDataCallback& callback) { - // Serve request from local bundle. - std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath); - bundled_path_prefix += "/"; - if (base::StartsWith(path, bundled_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - std::string path_without_params = PathWithoutParams(path); - - DCHECK(base::StartsWith(path_without_params, bundled_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)); - std::string path_under_bundled = - path_without_params.substr(bundled_path_prefix.length()); -#if BUILDFLAG(DEBUG_DEVTOOLS) - StartFileRequestForDebugDevtools(path_under_bundled, callback); -#else - StartBundledDataRequest(path_under_bundled, callback); -#endif - return; - } - - // Serve empty page. - std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath); - if (base::StartsWith(path, empty_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - callback.Run(new base::RefCountedStaticMemory()); - return; - } - - // Serve request from remote location. - std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath); - remote_path_prefix += "/"; - if (base::StartsWith(path, remote_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length())); - - CHECK_EQ(url.host(), kRemoteFrontendDomain); - if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) { - StartRemoteDataRequest(url, callback); - } else { - DLOG(ERROR) << "Refusing to load invalid remote front-end URL"; - callback.Run(CreateNotFoundResponse()); - } - return; - } - - std::string custom_frontend_url = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kCustomDevtoolsFrontend); - - if (custom_frontend_url.empty()) { - callback.Run(NULL); - return; - } - - // Serve request from custom location. - std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath); - custom_path_prefix += "/"; - - if (base::StartsWith(path, custom_path_prefix, - base::CompareCase::INSENSITIVE_ASCII)) { - GURL url = GURL(custom_frontend_url + - path.substr(custom_path_prefix.length())); - DCHECK(url.is_valid()); - StartCustomDataRequest(url, callback); - return; - } - - callback.Run(NULL); -} - -std::string DevToolsDataSource::GetMimeType(const std::string& path) { - return GetMimeTypeForPath(path); -} - -bool DevToolsDataSource::ShouldAddContentSecurityPolicy() { - return false; -} - -bool DevToolsDataSource::ShouldDenyXFrameOptions() { - return false; -} - -bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() { - return true; -} - -void DevToolsDataSource::StartBundledDataRequest( - const std::string& path, - const content::URLDataSource::GotDataCallback& callback) { - base::StringPiece resource = - content::DevToolsFrontendHost::GetFrontendResource(path); - - DLOG_IF(WARNING, resource.empty()) - << "Unable to find dev tool resource: " << path - << ". If you compiled with debug_devtools=1, try running with " - "--debug-devtools."; - scoped_refptr<base::RefCountedStaticMemory> bytes( - new base::RefCountedStaticMemory(resource.data(), resource.length())); - callback.Run(bytes.get()); -} - -void DevToolsDataSource::StartRemoteDataRequest( - const GURL& url, - const content::URLDataSource::GotDataCallback& callback) { - CHECK(url.is_valid()); - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("devtools_hard_coded_data_source", R"( - semantics { - sender: "Developer Tools Remote Data Request From Google" - description: - "This service fetches Chromium DevTools front-end files from the " - "cloud for the remote debugging scenario." - trigger: - "When user attaches to mobile phone for debugging." - data: "None" - destination: GOOGLE_OWNED_SERVICE - } - policy { - cookies_allowed: YES - cookies_store: "user" - setting: "This feature cannot be disabled by settings." - chrome_policy { - DeveloperToolsAvailability { - policy_options {mode: MANDATORY} - DeveloperToolsAvailability: 2 - } - } - })"); - - StartNetworkRequest(url, traffic_annotation, net::LOAD_NORMAL, callback); -} - -void DevToolsDataSource::StartCustomDataRequest( - const GURL& url, - const content::URLDataSource::GotDataCallback& callback) { - if (!url.is_valid()) { - callback.Run(CreateNotFoundResponse()); - return; - } - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("devtools_free_data_source", R"( - semantics { - sender: "Developer Tools Remote Data Request" - description: - "This service fetches Chromium DevTools front-end files from the " - "cloud for the remote debugging scenario. This can only happen if " - "a URL was passed on the commandline via flag " - "'--custom-devtools-frontend'. This URL overrides the default " - "fetching from a Google website, see " - "devtools_hard_coded_data_source." - trigger: - "When command line flag --custom-devtools-frontend is specified " - "and DevTools is opened." - data: "None" - destination: WEBSITE - } - policy { - cookies_allowed: YES - cookies_store: "user" - setting: "This feature cannot be disabled by settings." - chrome_policy { - DeveloperToolsAvailability { - policy_options {mode: MANDATORY} - DeveloperToolsAvailability: 2 - } - } - })"); - - StartNetworkRequest(url, traffic_annotation, net::LOAD_DISABLE_CACHE, - callback); -} - -void DevToolsDataSource::StartNetworkRequest( - const GURL& url, - const net::NetworkTrafficAnnotationTag& traffic_annotation, - int load_flags, - const GotDataCallback& callback) { - auto request = std::make_unique<network::ResourceRequest>(); - request->url = url; - request->load_flags = load_flags; - - auto request_iter = pending_requests_.emplace(pending_requests_.begin()); - request_iter->callback = callback; - request_iter->loader = - network::SimpleURLLoader::Create(std::move(request), traffic_annotation); - request_iter->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( - url_loader_factory_.get(), - base::BindOnce(&DevToolsDataSource::OnLoadComplete, - base::Unretained(this), request_iter)); -} - -#if BUILDFLAG(DEBUG_DEVTOOLS) -scoped_refptr<base::RefCountedMemory> ReadFile(const base::FilePath& path) { - std::string buffer; - if (!base::ReadFileToString(path, &buffer)) { - LOG(ERROR) << "Failed to read " << path; - return CreateNotFoundResponse(); - } - return base::RefCountedString::TakeString(&buffer); -} - -void DevToolsDataSource::StartFileRequestForDebugDevtools( - const std::string& path, - const GotDataCallback& callback) { - base::FilePath inspector_debug_dir; - if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, - &inspector_debug_dir)) { - callback.Run(CreateNotFoundResponse()); - return; - } - - DCHECK(!inspector_debug_dir.empty()); - - base::FilePath full_path = inspector_debug_dir.AppendASCII(path); - - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, - base::TaskPriority::USER_VISIBLE}, - // The usage of BindRepeating below is only because the type of - // task callback needs to match that of response callback, which - // is currently a repeating callback. - base::BindRepeating(ReadFile, std::move(full_path)), callback); -} - -#endif // BUILDFLAG(DEBUG_DEVTOOLS) - -void DevToolsDataSource::OnLoadComplete( - std::list<PendingRequest>::iterator request_iter, - std::unique_ptr<std::string> response_body) { - std::move(request_iter->callback) - .Run(response_body - ? base::RefCountedString::TakeString(response_body.get()) - : CreateNotFoundResponse()); - pending_requests_.erase(request_iter); -} - -} // namespace - -// DevToolsUI ----------------------------------------------------------------- // static GURL DevToolsUI::GetProxyURL(const std::string& frontend_url) { diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc new file mode 100644 index 00000000000..95e73c57300 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc @@ -0,0 +1,348 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/devtools_ui_data_source.h" + +#include <list> +#include <utility> + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/memory/ref_counted_memory.h" +#include "base/path_service.h" +#include "base/strings/strcat.h" +#include "base/task/post_task.h" +#include "chrome/browser/devtools/devtools_ui_bindings.h" +#include "chrome/browser/devtools/url_constants.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/url_constants.h" +#include "chrome/common/webui_url_constants.h" +#include "content/public/browser/devtools_frontend_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/url_constants.h" +#include "net/base/load_flags.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "services/network/public/cpp/resource_request.h" +#include "url/url_constants.h" + +namespace { + +std::string PathWithoutParams(const std::string& path) { + return GURL(base::StrCat({content::kChromeDevToolsScheme, + url::kStandardSchemeSeparator, + chrome::kChromeUIDevToolsHost})) + .Resolve(path) + .path() + .substr(1); +} + +scoped_refptr<base::RefCountedMemory> CreateNotFoundResponse() { + const char kHttpNotFound[] = "HTTP/1.1 404 Not Found\n\n"; + return base::MakeRefCounted<base::RefCountedStaticMemory>( + kHttpNotFound, strlen(kHttpNotFound)); +} + +// DevToolsDataSource --------------------------------------------------------- + +std::string GetMimeTypeForPath(const std::string& path) { + std::string filename = PathWithoutParams(path); + if (base::EndsWith(filename, ".html", base::CompareCase::INSENSITIVE_ASCII)) { + return "text/html"; + } else if (base::EndsWith(filename, ".css", + base::CompareCase::INSENSITIVE_ASCII)) { + return "text/css"; + } else if (base::EndsWith(filename, ".js", + base::CompareCase::INSENSITIVE_ASCII)) { + return "application/javascript"; + } else if (base::EndsWith(filename, ".png", + base::CompareCase::INSENSITIVE_ASCII)) { + return "image/png"; + } else if (base::EndsWith(filename, ".gif", + base::CompareCase::INSENSITIVE_ASCII)) { + return "image/gif"; + } else if (base::EndsWith(filename, ".svg", + base::CompareCase::INSENSITIVE_ASCII)) { + return "image/svg+xml"; + } else if (base::EndsWith(filename, ".manifest", + base::CompareCase::INSENSITIVE_ASCII)) { + return "text/cache-manifest"; + } + return "text/html"; +} +} // namespace + +DevToolsDataSource::DevToolsDataSource( + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) + : url_loader_factory_(std::move(url_loader_factory)) {} + +DevToolsDataSource::~DevToolsDataSource() {} + +std::string DevToolsDataSource::GetSource() { + return chrome::kChromeUIDevToolsHost; +} + +void DevToolsDataSource::StartDataRequest( + const std::string& path, + const content::WebContents::Getter& wc_getter, + const GotDataCallback& callback) { + // Serve request from local bundle. + std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath); + bundled_path_prefix += "/"; + if (base::StartsWith(path, bundled_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + std::string path_without_params = PathWithoutParams(path); + + DCHECK(base::StartsWith(path_without_params, bundled_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)); + std::string path_under_bundled = + path_without_params.substr(bundled_path_prefix.length()); +#if BUILDFLAG(DEBUG_DEVTOOLS) + StartFileRequestForDebugDevtools(path_under_bundled, callback); +#else + StartBundledDataRequest(path_under_bundled, callback); +#endif + return; + } + + // Serve empty page. + std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath); + if (base::StartsWith(path, empty_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + callback.Run(new base::RefCountedStaticMemory()); + return; + } + + // Serve request from remote location. + std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath); + remote_path_prefix += "/"; + if (base::StartsWith(path, remote_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length())); + + CHECK_EQ(url.host(), kRemoteFrontendDomain); + if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) { + StartRemoteDataRequest(url, callback); + } else { + DLOG(ERROR) << "Refusing to load invalid remote front-end URL"; + callback.Run(CreateNotFoundResponse()); + } + return; + } + + std::string custom_frontend_url = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kCustomDevtoolsFrontend); + + if (custom_frontend_url.empty()) { + callback.Run(nullptr); + return; + } + + // Serve request from custom location. + std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath); + custom_path_prefix += "/"; + + if (base::StartsWith(path, custom_path_prefix, + base::CompareCase::INSENSITIVE_ASCII)) { + GURL url = + GURL(custom_frontend_url + path.substr(custom_path_prefix.length())); + DCHECK(url.is_valid()); + StartCustomDataRequest(url, callback); + return; + } + + callback.Run(nullptr); +} + +std::string DevToolsDataSource::GetMimeType(const std::string& path) { + return GetMimeTypeForPath(path); +} + +bool DevToolsDataSource::ShouldAddContentSecurityPolicy() { + return false; +} + +bool DevToolsDataSource::ShouldDenyXFrameOptions() { + return false; +} + +bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() { + return true; +} + +void DevToolsDataSource::StartBundledDataRequest( + const std::string& path, + const content::URLDataSource::GotDataCallback& callback) { + base::StringPiece resource = + content::DevToolsFrontendHost::GetFrontendResource(path); + + DLOG_IF(WARNING, resource.empty()) + << "Unable to find dev tool resource: " << path + << ". If you compiled with debug_devtools=1, try running with " + "--debug-devtools."; + scoped_refptr<base::RefCountedStaticMemory> bytes( + new base::RefCountedStaticMemory(resource.data(), resource.length())); + callback.Run(bytes.get()); +} + +void DevToolsDataSource::StartRemoteDataRequest( + const GURL& url, + const content::URLDataSource::GotDataCallback& callback) { + CHECK(url.is_valid()); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("devtools_hard_coded_data_source", + R"( + semantics { + sender: "Developer Tools Remote Data Request From Google" + description: + "This service fetches Chromium DevTools front-end files from the " + "cloud for the remote debugging scenario." + trigger: + "When user attaches to mobile phone for debugging." + data: "None" + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: YES + cookies_store: "user" + setting: "This feature cannot be disabled by settings." + chrome_policy { + DeveloperToolsAvailability { + policy_options {mode: MANDATORY} + DeveloperToolsAvailability: 2 + } + } + })"); + + StartNetworkRequest(url, traffic_annotation, net::LOAD_NORMAL, callback); +} + +void DevToolsDataSource::StartCustomDataRequest( + const GURL& url, + const content::URLDataSource::GotDataCallback& callback) { + if (!url.is_valid()) { + callback.Run(CreateNotFoundResponse()); + return; + } + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("devtools_free_data_source", R"( + semantics { + sender: "Developer Tools Remote Data Request" + description: + "This service fetches Chromium DevTools front-end files from the " + "cloud for the remote debugging scenario. This can only happen if " + "a URL was passed on the commandline via flag " + "'--custom-devtools-frontend'. This URL overrides the default " + "fetching from a Google website, see " + "devtools_hard_coded_data_source." + trigger: + "When command line flag --custom-devtools-frontend is specified " + "and DevTools is opened." + data: "None" + destination: WEBSITE + } + policy { + cookies_allowed: YES + cookies_store: "user" + setting: "This feature cannot be disabled by settings." + chrome_policy { + DeveloperToolsAvailability { + policy_options {mode: MANDATORY} + DeveloperToolsAvailability: 2 + } + } + })"); + + StartNetworkRequest(url, traffic_annotation, net::LOAD_DISABLE_CACHE, + callback); +} + +void DevToolsDataSource::StartNetworkRequest( + const GURL& url, + const net::NetworkTrafficAnnotationTag& traffic_annotation, + int load_flags, + const GotDataCallback& callback) { + auto request = std::make_unique<network::ResourceRequest>(); + request->url = url; + request->load_flags = load_flags; + + auto request_iter = pending_requests_.emplace(pending_requests_.begin()); + request_iter->callback = callback; + request_iter->loader = + network::SimpleURLLoader::Create(std::move(request), traffic_annotation); + request_iter->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + url_loader_factory_.get(), + base::BindOnce(&DevToolsDataSource::OnLoadComplete, + base::Unretained(this), request_iter)); +} + +#if BUILDFLAG(DEBUG_DEVTOOLS) +scoped_refptr<base::RefCountedMemory> ReadFileForDebugDevTools( + const base::FilePath& path) { + std::string buffer; + if (!base::ReadFileToString(path, &buffer)) { + LOG(ERROR) << "Failed to read " << path; + return CreateNotFoundResponse(); + } + return base::RefCountedString::TakeString(&buffer); +} + +void DevToolsDataSource::StartFileRequestForDebugDevtools( + const std::string& path, + const GotDataCallback& callback) { + base::FilePath inspector_debug_dir; + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kCustomDevtoolsFrontend)) { + inspector_debug_dir = + command_line->GetSwitchValuePath(switches::kCustomDevtoolsFrontend); + // --custom-devtools-frontend may already be used to specify an URL. + // In that case, fall back to the default debug-devtools bundle. + if (!base::PathExists(inspector_debug_dir)) + inspector_debug_dir.clear(); + } + if (inspector_debug_dir.empty() && + !base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, + &inspector_debug_dir)) { + callback.Run(CreateNotFoundResponse()); + return; + } + + DCHECK(!inspector_debug_dir.empty()); + + base::FilePath full_path = inspector_debug_dir.AppendASCII(path); + + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::ThreadPool(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::TaskPriority::USER_VISIBLE}, + // The usage of BindRepeating below is only because the type of + // task callback needs to match that of response callback, which + // is currently a repeating callback. + base::BindRepeating(ReadFileForDebugDevTools, std::move(full_path)), + callback); +} +#endif // BUILDFLAG(DEBUG_DEVTOOLS) + +void DevToolsDataSource::OnLoadComplete( + std::list<PendingRequest>::iterator request_iter, + std::unique_ptr<std::string> response_body) { + std::move(request_iter->callback) + .Run(response_body + ? base::RefCountedString::TakeString(response_body.get()) + : CreateNotFoundResponse()); + pending_requests_.erase(request_iter); +} + +DevToolsDataSource::PendingRequest::PendingRequest() = default; + +DevToolsDataSource::PendingRequest::PendingRequest(PendingRequest&& other) = + default; + +DevToolsDataSource::PendingRequest::~PendingRequest() { + if (callback) + callback.Run(CreateNotFoundResponse()); +} diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source.h b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.h new file mode 100644 index 00000000000..dddecbcd1ba --- /dev/null +++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.h @@ -0,0 +1,101 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_DATA_SOURCE_H_ +#define CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_DATA_SOURCE_H_ + +#include <list> +#include <memory> + +#include "content/public/browser/url_data_source.h" + +#include "base/macros.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/simple_url_loader.h" +#include "third_party/blink/public/public_buildflags.h" + +class GURL; + +namespace net { +struct NetworkTrafficAnnotationTag; +} + +// An URLDataSource implementation that handles devtools://devtools/ +// requests. Three types of requests could be handled based on the URL path: +// 1. /bundled/: bundled DevTools frontend is served. +// when built with debug_devtools=true, the path can be provided via +// --custom-devtools-frontend. +// 2. /remote/: remote DevTools frontend is served from App Engine. +// 3. /custom/: custom DevTools frontend is served from the server as specified +// by the --custom-devtools-frontend flag. +class DevToolsDataSource : public content::URLDataSource { + public: + using GotDataCallback = content::URLDataSource::GotDataCallback; + + explicit DevToolsDataSource( + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); + ~DevToolsDataSource() override; + + // content::URLDataSource implementation. + std::string GetSource() override; + + void StartDataRequest(const std::string& path, + const content::WebContents::Getter& wc_getter, + const GotDataCallback& callback) override; + + private: + friend class DevToolsUIDataSourceTest; + + struct PendingRequest; + + // content::URLDataSource overrides. + std::string GetMimeType(const std::string& path) override; + bool ShouldAddContentSecurityPolicy() override; + bool ShouldDenyXFrameOptions() override; + bool ShouldServeMimeTypeAsContentTypeHeader() override; + + void OnLoadComplete(std::list<PendingRequest>::iterator request_iter, + std::unique_ptr<std::string> response_body); + + // Serves bundled DevTools frontend from ResourceBundle. + void StartBundledDataRequest(const std::string& path, + const GotDataCallback& callback); + + // Serves remote DevTools frontend from hard-coded App Engine domain. + void StartRemoteDataRequest(const GURL& url, const GotDataCallback& callback); + + // Serves remote DevTools frontend from any endpoint, passed through + // command-line flag. + void StartCustomDataRequest(const GURL& url, const GotDataCallback& callback); + + virtual void StartNetworkRequest( + const GURL& url, + const net::NetworkTrafficAnnotationTag& traffic_annotation, + int load_flags, + const GotDataCallback& callback); + +#if BUILDFLAG(DEBUG_DEVTOOLS) + void StartFileRequestForDebugDevtools(const std::string& path, + const GotDataCallback& callback); +#endif + + struct PendingRequest { + PendingRequest(); + PendingRequest(PendingRequest&& other); + PendingRequest& operator=(PendingRequest&& other) = default; + ~PendingRequest(); + + GotDataCallback callback; + std::unique_ptr<network::SimpleURLLoader> loader; + + DISALLOW_COPY_AND_ASSIGN(PendingRequest); + }; + + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; + std::list<PendingRequest> pending_requests_; + + DISALLOW_COPY_AND_ASSIGN(DevToolsDataSource); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_DATA_SOURCE_H_ diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc b/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc new file mode 100644 index 00000000000..323ce84efc3 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc @@ -0,0 +1,235 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/devtools_ui_data_source.h" + +#include <memory> + +#include "base/bind.h" +#include "base/memory/ref_counted_memory.h" +#include "base/strings/strcat.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/url_constants.h" +#include "content/public/browser/url_data_source.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +constexpr char kDevToolsUITestFrontEndUrl[] = "/devtools_app.html"; +constexpr char kDevToolsUITest404Response[] = "HTTP/1.1 404 Not Found"; + +GURL DevToolsUrl() { + return GURL(base::StrCat({content::kChromeDevToolsScheme, + url::kStandardSchemeSeparator, + chrome::kChromeUIDevToolsHost})); +} + +std::string DevToolsBundledPath(const std::string& path) { + return base::StrCat({chrome::kChromeUIDevToolsBundledPath, path}); +} + +std::string DevToolsRemotePath(const std::string& path) { + return base::StrCat({chrome::kChromeUIDevToolsRemotePath, path}); +} + +std::string DevToolsCustomPath(const std::string& path) { + return base::StrCat({chrome::kChromeUIDevToolsCustomPath, path}); +} + +} // namespace + +class TestDevToolsDataSource : public DevToolsDataSource { + public: + TestDevToolsDataSource() : DevToolsDataSource(nullptr) {} + ~TestDevToolsDataSource() override {} + + void StartNetworkRequest( + const GURL& url, + const net::NetworkTrafficAnnotationTag& traffic_annotation, + int load_flags, + const GotDataCallback& callback) override { + std::string copy_of_url = url.spec(); + callback.Run(base::RefCountedString::TakeString(©_of_url)); + } +}; + +class DevToolsUIDataSourceTest : public testing::Test { + protected: + DevToolsUIDataSourceTest() {} + ~DevToolsUIDataSourceTest() override = default; + + void SetUp() override { + devtools_data_source_ = std::make_unique<TestDevToolsDataSource>(); + } + + void TearDown() override { devtools_data_source_.reset(); } + + TestDevToolsDataSource* data_source() const { + return devtools_data_source_.get(); + } + + bool data_received() const { return data_received_; } + + std::string data() const { return data_; } + + void StartRequest(const std::string& path) { + data_received_ = false; + data_.clear(); + std::string trimmed_path = path.substr(1); + content::WebContents::Getter wc_getter; + data_source()->StartDataRequest( + trimmed_path, std::move(wc_getter), + base::BindRepeating(&DevToolsUIDataSourceTest::OnDataReceived, + base::Unretained(this))); + } + + private: + void OnDataReceived(scoped_refptr<base::RefCountedMemory> bytes) { + data_received_ = true; + if (bytes.get() != nullptr) { + data_ = base::StringPiece(reinterpret_cast<const char*>(bytes->front()), + bytes->size()) + .as_string(); + } + } + + std::unique_ptr<TestDevToolsDataSource> devtools_data_source_; + bool data_received_ = false; + std::string data_; + + DISALLOW_COPY_AND_ASSIGN(DevToolsUIDataSourceTest); +}; + +// devtools/bundled path. + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURL) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_FALSE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURLWithQueryParam) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_FALSE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsInvalidBundledURL) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath("invalid_devtools_app.html")); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsInvalidBundledURLWithQueryParam) { + const GURL path = + DevToolsUrl().Resolve(DevToolsBundledPath("invalid_devtools_app.html")); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +// devtools/blank path + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBlankURL) { + const GURL path = DevToolsUrl().Resolve(chrome::kChromeUIDevToolsBlankPath); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsBlankURLWithQueryParam) { + const GURL path = DevToolsUrl().Resolve(chrome::kChromeUIDevToolsBlankPath); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +// devtools/remote path + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsRemoteURL) { + const GURL path = + DevToolsUrl().Resolve(DevToolsRemotePath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_EQ(data(), + "https://chrome-devtools-frontend.appspot.com/devtools_app.html"); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsRemoteURLWithQueryParam) { + const GURL path = + DevToolsUrl().Resolve(DevToolsRemotePath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + ASSERT_TRUE(base::StartsWith(data(), kDevToolsUITest404Response, + base::CompareCase::SENSITIVE)); +} + +// devtools/custom path. + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsCustomURLWithNoSwitch) { + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsCustomURLWithSwitch) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "http://localhost:8090/front_end/"); + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_EQ(data(), "http://localhost:8090/front_end/devtools_app.html"); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsCustomURLWithSwitchAndQueryParam) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "http://localhost:8090/front_end/"); + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path() + "?foo"); + EXPECT_TRUE(data_received()); + EXPECT_EQ(data(), "http://localhost:8090/front_end/devtools_app.html?foo"); +} + +#if !DCHECK_IS_ON() +TEST_F(DevToolsUIDataSourceTest, + TestDevToolsCustomURLWithSwitchAndInvalidServerURL) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "invalid-server-url"); + const GURL path = + DevToolsUrl().Resolve(DevToolsCustomPath(kDevToolsUITestFrontEndUrl)); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + ASSERT_TRUE(base::StartsWith(data(), kDevToolsUITest404Response, + base::CompareCase::SENSITIVE)); +} +#endif + +// devtools path (i.e. no route specified). + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsNoRoute) { + const GURL path = DevToolsUrl().Resolve(kDevToolsUITestFrontEndUrl); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} + +TEST_F(DevToolsUIDataSourceTest, TestDevToolsNoRouteWithSwitch) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kCustomDevtoolsFrontend, "invalid-server-url"); + const GURL path = DevToolsUrl().Resolve(kDevToolsUITestFrontEndUrl); + StartRequest(path.path()); + EXPECT_TRUE(data_received()); + EXPECT_TRUE(data().empty()); +} diff --git a/chromium/chrome/browser/ui/webui/discards/DEPS b/chromium/chrome/browser/ui/webui/discards/DEPS index f452a3a9db6..b6e5e564456 100644 --- a/chromium/chrome/browser/ui/webui/discards/DEPS +++ b/chromium/chrome/browser/ui/webui/discards/DEPS @@ -1,5 +1,10 @@ specific_include_rules = { + # TODO(siggi): Move WebUIGraphDumpImpl into this directory and kill these + # include rules. "discards_ui.h": [ "+chrome/browser/performance_manager/webui_graph_dump.mojom.h", ], + "discards_ui.cc": [ + "+chrome/browser/performance_manager/webui_graph_dump_impl.h", + ], } diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc index 597f062d388..04bc887b3d3 100644 --- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc +++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc @@ -15,6 +15,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/performance_manager/performance_manager.h" +#include "chrome/browser/performance_manager/webui_graph_dump_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/lifecycle_unit.h" #include "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom.h" @@ -464,6 +465,9 @@ void DiscardsUI::BindWebUIGraphDumpProvider( performance_manager::PerformanceManager::GetInstance(); if (performance_manager) { // Forward the interface request directly to the service. - performance_manager->BindInterface(std::move(request)); + performance_manager->CallOnGraph( + FROM_HERE, + base::BindOnce(&performance_manager::WebUIGraphDumpImpl::CreateAndBind, + std::move(request))); } } diff --git a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc index f8ba443b977..10c8baf3813 100644 --- a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc @@ -23,7 +23,7 @@ DownloadInternalsUI::DownloadInternalsUI(content::WebUI* web_ui) "script-src chrome://resources 'self' 'unsafe-eval';"); // Required resources. - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("download_internals.css", IDR_DOWNLOAD_INTERNALS_CSS); html_source->AddResourcePath("download_internals.js", diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc index 31e1659b50c..c4935b9397d 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_dom_handler_unittest.cc @@ -4,16 +4,16 @@ #include "chrome/browser/ui/webui/downloads/downloads_dom_handler.h" -#include <vector> #include <utility> +#include <vector> #include "chrome/browser/download/download_item_model.h" #include "chrome/browser/ui/webui/downloads/downloads.mojom.h" #include "chrome/browser/ui/webui/downloads/mock_downloads_page.h" #include "chrome/test/base/testing_profile.h" #include "components/download/public/common/mock_download_item.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_download_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gmock/include/gmock/gmock.h" @@ -57,7 +57,7 @@ class DownloadsDOMHandlerTest : public testing::Test { private: // NOTE: The initialization order of these members matters. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; testing::NiceMock<content::MockDownloadManager> manager_; diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc index 8b51693ecd6..4c9e7443170 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc @@ -21,14 +21,13 @@ #include "chrome/browser/download/download_item_model.h" #include "chrome/browser/download/download_query.h" #include "chrome/browser/extensions/api/downloads/downloads_api.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "components/download/public/common/download_danger_type.h" #include "components/download/public/common/download_item.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" #include "net/base/filename_util.h" #include "third_party/icu/source/i18n/unicode/datefmt.h" #include "ui/base/l10n/time_format.h" @@ -224,13 +223,11 @@ downloads::mojom::DataPtr DownloadsListTracker::CreateDownloadData( // Lookup the extension's current name() in case the user changed their // language. This won't work if the extension was uninstalled, so the name // might be the wrong language. - bool include_disabled = true; auto* profile = Profile::FromBrowserContext( content::DownloadItemUtils::GetBrowserContext(download_item)); - auto* service = - extensions::ExtensionSystem::Get(profile)->extension_service(); - const extensions::Extension* extension = - service->GetExtensionById(by_ext->id(), include_disabled); + auto* registry = extensions::ExtensionRegistry::Get(profile); + const extensions::Extension* extension = registry->GetExtensionById( + by_ext->id(), extensions::ExtensionRegistry::COMPATIBILITY); if (extension) by_ext_name = extension->name(); } @@ -338,8 +335,12 @@ void DownloadsListTracker::SetChunkSizeForTesting(size_t chunk_size) { } bool DownloadsListTracker::ShouldShow(const DownloadItem& item) const { - return !download_crx_util::IsExtensionDownload(item) && !item.IsTemporary() && - !item.IsTransient() && !item.GetFileNameToReportUser().empty() && + return !download_crx_util::IsTrustedExtensionDownload( + Profile::FromBrowserContext( + GetMainNotifierManager()->GetBrowserContext()), + item) && + !item.IsTemporary() && !item.IsTransient() && + !item.GetFileNameToReportUser().empty() && !item.GetTargetFilePath().empty() && !item.GetURL().is_empty() && DownloadItemModel(const_cast<DownloadItem*>(&item)) .ShouldShowInShelf() && @@ -357,8 +358,8 @@ void DownloadsListTracker::Init() { GetMainNotifierManager()->GetBrowserContext()); if (profile->IsOffTheRecord()) { Profile* original_profile = profile->GetOriginalProfile(); - original_notifier_.reset(new download::AllDownloadItemNotifier( - BrowserContext::GetDownloadManager(original_profile), this)); + original_notifier_ = std::make_unique<download::AllDownloadItemNotifier>( + BrowserContext::GetDownloadManager(original_profile), this); } RebuildSortedItems(); diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc index e56ac40279a..00ab6f9573c 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker_unittest.cc @@ -19,8 +19,8 @@ #include "chrome/browser/ui/webui/downloads/mock_downloads_page.h" #include "chrome/test/base/testing_profile.h" #include "components/download/public/common/mock_download_item.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_download_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -115,7 +115,7 @@ class DownloadsListTrackerTest : public testing::Test { } // NOTE: The initialization order of these members matters. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; testing::NiceMock<content::MockDownloadManager> manager_; diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc index b2b55ef537a..e1c53488cb0 100644 --- a/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc +++ b/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc @@ -16,6 +16,7 @@ #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/advanced_protection_status_manager.h" +#include "chrome/browser/safe_browsing/advanced_protection_status_manager_factory.h" #include "chrome/browser/ui/webui/downloads/downloads_dom_handler.h" #include "chrome/browser/ui/webui/localized_string.h" #include "chrome/browser/ui/webui/managed_ui_handler.h" @@ -51,8 +52,10 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIDownloadsHost); - bool requests_ap_verdicts = safe_browsing::AdvancedProtectionStatusManager:: - RequestsAdvancedProtectionVerdicts(profile); + bool requests_ap_verdicts = + safe_browsing::AdvancedProtectionStatusManagerFactory::GetForProfile( + profile) + ->RequestsAdvancedProtectionVerdicts(); source->AddBoolean("requestsApVerdicts", requests_ap_verdicts); static constexpr LocalizedString kStrings[] = { @@ -114,7 +117,7 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { // definitions from JS to C++. ui::Accelerator undoAccelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); source->AddString("undoDescription", l10n_util::GetStringFUTF16( - IDS_DOWNLOAD_UNDO_DESCRIPTION, + IDS_UNDO_DESCRIPTION, undoAccelerator.GetShortcutText())); PrefService* prefs = profile->GetPrefs(); @@ -146,7 +149,7 @@ content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { source->SetDefaultResource(IDR_DOWNLOADS_DOWNLOADS_HTML); #endif - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } @@ -198,6 +201,6 @@ void DownloadsUI::CreatePageHandler( Profile* profile = Profile::FromWebUI(web_ui()); DownloadManager* dlm = BrowserContext::GetDownloadManager(profile); - page_handler_.reset(new DownloadsDOMHandler(std::move(request), - std::move(page), dlm, web_ui())); + page_handler_ = std::make_unique<DownloadsDOMHandler>( + std::move(request), std::move(page), dlm, web_ui()); } 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 d21545e7601..2c97430d0dc 100644 --- a/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc +++ b/chromium/chrome/browser/ui/webui/engagement/site_engagement_ui.cc @@ -98,6 +98,6 @@ SiteEngagementUI::~SiteEngagementUI() {} void SiteEngagementUI::BindSiteEngagementDetailsProvider( mojom::SiteEngagementDetailsProviderRequest request) { - ui_handler_.reset(new SiteEngagementDetailsProviderImpl( - Profile::FromWebUI(web_ui()), std::move(request))); + ui_handler_ = std::make_unique<SiteEngagementDetailsProviderImpl>( + Profile::FromWebUI(web_ui()), std::move(request)); } diff --git a/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc b/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc index 255326cda96..661ba823499 100644 --- a/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_ui.cc @@ -45,9 +45,8 @@ ExploreSitesInternalsUI::~ExploreSitesInternalsUI() {} void ExploreSitesInternalsUI::BindExploreSitesInternalsPageHandler( explore_sites_internals::mojom::PageHandlerRequest request) { - page_handler_.reset(new ExploreSitesInternalsPageHandler( - std::move(request), explore_sites_service_, - Profile::FromWebUI(web_ui()))); + page_handler_ = std::make_unique<ExploreSitesInternalsPageHandler>( + std::move(request), explore_sites_service_, Profile::FromWebUI(web_ui())); } } // namespace explore_sites 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 22fee225778..d8295f8e69b 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 @@ -107,8 +107,7 @@ KioskAppsHandler::KioskAppsHandler(OwnerSettingsServiceChromeOS* service) initialized_(false), is_kiosk_enabled_(false), is_auto_launch_enabled_(false), - owner_settings_service_(service), - weak_ptr_factory_(this) {} + owner_settings_service_(service) {} KioskAppsHandler::~KioskAppsHandler() { // TODO(tommycli): This is needed because OnJavascriptDisallowed only called diff --git a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h index a7d38504888..aeb28325109 100644 --- a/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/extensions/chromeos/kiosk_apps_handler.h @@ -68,7 +68,7 @@ class KioskAppsHandler : public content::WebUIMessageHandler, bool is_kiosk_enabled_; bool is_auto_launch_enabled_; OwnerSettingsServiceChromeOS* const owner_settings_service_; // not owned - base::WeakPtrFactory<KioskAppsHandler> weak_ptr_factory_; + base::WeakPtrFactory<KioskAppsHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(KioskAppsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc index 618914d559b..76e1be57c95 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc @@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" @@ -45,7 +46,7 @@ namespace extensions { namespace { scoped_refptr<base::RefCountedMemory> BitmapToMemory(const SkBitmap* image) { - base::RefCountedBytes* image_bytes = new base::RefCountedBytes; + auto image_bytes = base::MakeRefCounted<base::RefCountedBytes>(); gfx::PNGCodec::EncodeBGRASkBitmap(*image, false, &image_bytes->data()); return image_bytes; } @@ -114,7 +115,7 @@ std::string ExtensionIconSource::GetMimeType(const std::string&) { void ExtensionIconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // This is where everything gets started. First, parse the request and make // the request data available for later. diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h index c7be8dc828f..0737257d85b 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h +++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h @@ -72,7 +72,7 @@ class ExtensionIconSource : public content::URLDataSource, std::string GetMimeType(const std::string&) override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc index 7d66742b077..93a7af977c7 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extension_settings_browsertest.cc @@ -91,13 +91,15 @@ void ExtensionSettingsUIBrowserTest::AddManagedPolicyProvider() { } void ExtensionSettingsUIBrowserTest::SetAutoConfirmUninstall() { - uninstall_auto_confirm_.reset(new extensions::ScopedTestDialogAutoConfirm( - extensions::ScopedTestDialogAutoConfirm::ACCEPT)); + uninstall_auto_confirm_ = + std::make_unique<extensions::ScopedTestDialogAutoConfirm>( + extensions::ScopedTestDialogAutoConfirm::ACCEPT); } void ExtensionSettingsUIBrowserTest::EnableErrorConsole() { - error_console_override_.reset(new extensions::FeatureSwitch::ScopedOverride( - extensions::FeatureSwitch::error_console(), true)); + error_console_override_ = + std::make_unique<extensions::FeatureSwitch::ScopedOverride>( + extensions::FeatureSwitch::error_console(), true); } void ExtensionSettingsUIBrowserTest::SetDevModeEnabled(bool enabled) { diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc index 9c1963ef46f..69157d3f489 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc @@ -435,7 +435,7 @@ std::string ExtensionsInternalsSource::GetMimeType(const std::string& path) { void ExtensionsInternalsSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { std::string json = WriteToString(); callback.Run(base::RefCountedString::TakeString(&json)); diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h index 4a8a6cabeaf..0b2840aec47 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h @@ -22,7 +22,7 @@ class ExtensionsInternalsSource : public content::URLDataSource { std::string GetMimeType(const std::string& path) override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; // Simpler interface to generate string output, without needing to diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc index b08cee7d5bd..645cf9d7c67 100644 --- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc @@ -59,7 +59,7 @@ content::WebUIDataSource* CreateMdExtensionsSource(Profile* profile, bool in_dev_mode) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIExtensionsHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); static constexpr LocalizedString kLocalizedStrings[] = { // Add common strings. @@ -178,6 +178,8 @@ content::WebUIDataSource* CreateMdExtensionsSource(Profile* profile, {"itemSourceUnpacked", IDS_EXTENSIONS_ITEM_SOURCE_UNPACKED}, {"itemSourceWebstore", IDS_EXTENSIONS_ITEM_SOURCE_WEBSTORE}, {"itemVersion", IDS_EXTENSIONS_ITEM_VERSION}, + {"itemReloaded", IDS_EXTENSIONS_ITEM_RELOADED}, + {"itemReloading", IDS_EXTENSIONS_ITEM_RELOADING}, // TODO(dpapad): Replace this with an Extensions specific string. {"itemSize", IDS_DIRECTORY_LISTING_SIZE}, {"itemAllowOnFileUrls", IDS_EXTENSIONS_ALLOW_FILE_ACCESS}, diff --git a/chromium/chrome/browser/ui/webui/favicon_source.cc b/chromium/chrome/browser/ui/webui/favicon_source.cc index 5175c36ac4d..498c9de6242 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source.cc +++ b/chromium/chrome/browser/ui/webui/favicon_source.cc @@ -15,14 +15,11 @@ #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_io_context.h" -#include "chrome/browser/sync/session_sync_service_factory.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" #include "components/favicon/core/history_ui_favicon_request_handler.h" #include "components/favicon_base/favicon_url_parser.h" #include "components/history/core/browser/top_sites.h" -#include "components/sync_sessions/open_tabs_ui_delegate.h" -#include "components/sync_sessions/session_sync_service.h" #include "content/public/browser/web_contents.h" #include "net/url_request/url_request.h" #include "ui/base/layout.h" @@ -38,8 +35,7 @@ namespace { // original URL that started the request, but we're only interested in verifying // if it was issued by a history page, for whom this is the case. If it is not // possible to obtain the URL, we return the empty GURL. -GURL GetUnsafeRequestOrigin( - const content::ResourceRequestInfo::WebContentsGetter& wc_getter) { +GURL GetUnsafeRequestOrigin(const content::WebContents::Getter& wc_getter) { content::WebContents* web_contents = wc_getter.Run(); return web_contents ? web_contents->GetLastCommittedURL() : GURL(); } @@ -80,7 +76,7 @@ std::string FaviconSource::GetSource() { void FaviconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile_, @@ -97,8 +93,9 @@ void FaviconSource::StartDataRequest( return; } - GURL url(parsed.url); - if (!url.is_valid()) { + GURL page_url(parsed.page_url); + GURL icon_url(parsed.icon_url); + if (!page_url.is_valid() && !icon_url.is_valid()) { SendDefaultResponse(callback); return; } @@ -106,11 +103,13 @@ void FaviconSource::StartDataRequest( int desired_size_in_pixel = std::ceil(parsed.size_in_dip * parsed.device_scale_factor); - if (parsed.is_icon_url) { + if (parsed.page_url.empty()) { + // Request by icon url. + // TODO(michaelbai): Change GetRawFavicon to support combination of // IconType. favicon_service->GetRawFavicon( - url, favicon_base::IconType::kFavicon, desired_size_in_pixel, + icon_url, favicon_base::IconType::kFavicon, desired_size_in_pixel, base::BindRepeating(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), callback, parsed.size_in_dip, parsed.device_scale_factor), @@ -121,7 +120,7 @@ void FaviconSource::StartDataRequest( TopSitesFactory::GetForProfile(profile_); if (top_sites) { for (const auto& prepopulated_page : top_sites->GetPrepopulatedPages()) { - if (url == prepopulated_page.most_visited.url) { + if (page_url == prepopulated_page.most_visited.url) { ui::ScaleFactor resource_scale_factor = ui::GetSupportedScaleFactor(parsed.device_scale_factor); callback.Run( @@ -142,7 +141,7 @@ void FaviconSource::StartDataRequest( // API and move the explanatory comment for |fallback_to_host| here. const bool fallback_to_host = true; favicon_service->GetRawFaviconForPageURL( - url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, + page_url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, fallback_to_host, base::Bind(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), callback, parsed.size_in_dip, @@ -161,19 +160,14 @@ void FaviconSource::StartDataRequest( SendDefaultResponse(callback); return; } - sync_sessions::SessionSyncService* session_sync_service = - SessionSyncServiceFactory::GetInstance()->GetForProfile(profile_); - sync_sessions::OpenTabsUIDelegate* open_tabs = - session_sync_service->GetOpenTabsUIDelegate(); history_ui_favicon_request_handler->GetRawFaviconForPageURL( - url, desired_size_in_pixel, + page_url, desired_size_in_pixel, base::BindOnce(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), callback, parsed.size_in_dip, parsed.device_scale_factor), favicon::FaviconRequestPlatform::kDesktop, parsed_history_ui_origin, /*icon_url_for_uma=*/ - open_tabs ? open_tabs->GetIconUrlForPageUrl(url) : GURL(), - &cancelable_task_tracker_); + GURL(parsed.icon_url), &cancelable_task_tracker_); } } @@ -231,7 +225,7 @@ void FaviconSource::SendDefaultResponse( const content::URLDataSource::GotDataCallback& callback, int size_in_dip, float scale_factor) { - const bool dark = GetNativeTheme()->SystemDarkModeEnabled(); + const bool dark = GetNativeTheme()->ShouldUseDarkColors(); int resource_id; switch (size_in_dip) { case 64: diff --git a/chromium/chrome/browser/ui/webui/favicon_source.h b/chromium/chrome/browser/ui/webui/favicon_source.h index d07df2fed51..35e52bab808 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source.h +++ b/chromium/chrome/browser/ui/webui/favicon_source.h @@ -45,7 +45,7 @@ class FaviconSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc b/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc index 5639be31fb3..95b83fcd6bc 100644 --- a/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc +++ b/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc @@ -17,9 +17,8 @@ #include "components/favicon/core/test/mock_favicon_service.h" #include "components/favicon_base/favicon_url_parser.h" #include "content/public/browser/browser_context.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/browser/web_contents.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/web_contents_tester.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -27,7 +26,7 @@ #include "ui/resources/grit/ui_resources.h" using GotDataCallback = content::URLDataSource::GotDataCallback; -using WebContentsGetter = content::ResourceRequestInfo::WebContentsGetter; +using WebContentsGetter = content::WebContents::Getter; using testing::_; using testing::Return; using testing::ReturnArg; @@ -141,7 +140,7 @@ class FaviconSourceTestBase : public testing::Test { protected: const scoped_refptr<base::RefCountedBytes> kDummyIconBytes; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; ui::TestNativeTheme theme_; TestingProfile profile_; MockHistoryUiFaviconRequestHandler* mock_history_ui_favicon_request_handler_; @@ -215,7 +214,7 @@ TEST_F(FaviconSourceTestWithFavicon2Format, .Times(0); source()->StartDataRequest( - "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google." + "?size=16&scale_factor=1x&page_url=https%3A%2F%2Fwww.google." "com&allow_google_server_fallback=0", test_web_contents_getter_, base::BindRepeating(&Noop)); } @@ -230,7 +229,7 @@ TEST_F(FaviconSourceTestWithFavicon2Format, .Times(0); source()->StartDataRequest( - "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google." + "?size=16&scale_factor=1x&page_url=https%3A%2F%2Fwww.google." "com&allow_google_server_fallback=1", test_web_contents_getter_, base::BindRepeating(&Noop)); } @@ -247,7 +246,7 @@ TEST_F( .Times(1); source()->StartDataRequest( - "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google." + "?size=16&scale_factor=1x&page_url=https%3A%2F%2Fwww.google." "com&allow_google_server_fallback=1", test_web_contents_getter_, base::BindRepeating(&Noop)); } diff --git a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc index 77f5faedee6..cbc85825f30 100644 --- a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc @@ -53,8 +53,7 @@ FeedInternalsPageHandler::FeedInternalsPageHandler( : binding_(this, std::move(request)), feed_scheduler_host_(feed_host_service->GetSchedulerHost()), feed_offline_host_(feed_host_service->GetOfflineHost()), - pref_service_(pref_service), - weak_ptr_factory_(this) {} + pref_service_(pref_service) {} FeedInternalsPageHandler::~FeedInternalsPageHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h index 67f1327fe9a..2d0352747a4 100644 --- a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h +++ b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h @@ -59,7 +59,7 @@ class FeedInternalsPageHandler : public feed_internals::mojom::PageHandler { feed::FeedOfflineHost* feed_offline_host_; PrefService* pref_service_; - base::WeakPtrFactory<FeedInternalsPageHandler> weak_ptr_factory_; + base::WeakPtrFactory<FeedInternalsPageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FeedInternalsPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.cc b/chromium/chrome/browser/ui/webui/fileicon_source.cc index 7706c0fffd1..a9e963a94da 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source.cc +++ b/chromium/chrome/browser/ui/webui/fileicon_source.cc @@ -114,7 +114,7 @@ std::string FileIconSource::GetSource() { void FileIconSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { base::FilePath file_path; IconLoader::IconSize icon_size = IconLoader::NORMAL; diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.h b/chromium/chrome/browser/ui/webui/fileicon_source.h index 38fd7797a60..d607cf1b49b 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source.h +++ b/chromium/chrome/browser/ui/webui/fileicon_source.h @@ -28,7 +28,7 @@ class FileIconSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool AllowCaching() override; diff --git a/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc b/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc index 42dd71a64ce..549f17167eb 100644 --- a/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc +++ b/chromium/chrome/browser/ui/webui/fileicon_source_unittest.cc @@ -10,7 +10,7 @@ #include "chrome/browser/icon_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,7 +34,7 @@ class FileIconSourceTest : public testing::Test { FileIconSourceTest() = default; private: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; const struct FetchFileIconExpectation { @@ -118,9 +118,7 @@ TEST_F(FileIconSourceTest, FileIconSource_Parse) { base::FilePath(kBasicExpectations[i].unescaped_path), kBasicExpectations[i].scale_factor, kBasicExpectations[i].size, CallbackIsNull())); - source->StartDataRequest( - kBasicExpectations[i].request_path, - content::ResourceRequestInfo::WebContentsGetter(), - callback); + source->StartDataRequest(kBasicExpectations[i].request_path, + content::WebContents::Getter(), callback); } } diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc index cdf598ea4d3..70df1a343d1 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui.cc @@ -58,9 +58,6 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUIFlagsHost); source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - - source->AddLocalizedString(flags_ui::kFlagsRestartNotice, - IDS_FLAGS_UI_RELAUNCH_NOTICE); source->AddString(flags_ui::kVersion, version_info::GetVersionNumber()); #if defined(OS_CHROMEOS) @@ -69,11 +66,11 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() { // Set the string to show which user can actually change the flags. std::string owner; chromeos::CrosSettings::Get()->GetString(chromeos::kDeviceOwner, &owner); - source->AddString(flags_ui::kOwnerEmail, base::UTF8ToUTF16(owner)); + source->AddString("owner-warning", + l10n_util::GetStringFUTF16(IDS_FLAGS_UI_OWNER_WARNING, + base::UTF8ToUTF16(owner))); } else { - // The warning will be only shown on ChromeOS, when the current user is not - // the owner. - source->AddString(flags_ui::kOwnerEmail, base::string16()); + source->AddString("owner-warning", base::string16()); } #endif @@ -87,7 +84,8 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() { // after finishing it the UI can be properly populated. This function is the // callback for whether the owner is signed in. It will respectively pick the // proper PrefService for the flags interface. -void FinishInitialization(base::WeakPtr<FlagsUI> flags_ui, +template <class T> +void FinishInitialization(base::WeakPtr<T> flags_ui, Profile* profile, FlagsUIHandler* dom_handler, bool current_user_is_owner) { @@ -117,9 +115,69 @@ void FinishInitialization(base::WeakPtr<FlagsUI> flags_ui, } // namespace -FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); +// static +void FlagsUI::AddStrings(content::WebUIDataSource* source) { + // Strings added here are all marked a non-translatable, so they are not + // actually localized. + source->AddLocalizedString(flags_ui::kFlagsRestartNotice, + IDS_FLAGS_UI_RELAUNCH_NOTICE); + source->AddLocalizedString("available", IDS_FLAGS_UI_AVAILABLE_FEATURE); + source->AddLocalizedString("clear-search", IDS_FLAGS_UI_CLEAR_SEARCH); + source->AddLocalizedString("disabled", IDS_FLAGS_UI_DISABLED_FEATURE); + source->AddLocalizedString("enabled", IDS_FLAGS_UI_ENABLED_FEATURE); + source->AddLocalizedString("experiment-enabled", + IDS_FLAGS_UI_EXPERIMENT_ENABLED); + source->AddLocalizedString("no-results", IDS_FLAGS_UI_NO_RESULTS); + source->AddLocalizedString("not-available-platform", + IDS_FLAGS_UI_NOT_AVAILABLE_ON_PLATFORM); + source->AddLocalizedString("page-warning", IDS_FLAGS_UI_PAGE_WARNING); + source->AddLocalizedString("page-warning-explanation", + IDS_FLAGS_UI_PAGE_WARNING_EXPLANATION); + source->AddLocalizedString("relaunch", IDS_FLAGS_UI_RELAUNCH); + source->AddLocalizedString("reset", IDS_FLAGS_UI_PAGE_RESET); + source->AddLocalizedString("reset-acknowledged", + IDS_FLAGS_UI_RESET_ACKNOWLEDGED); + source->AddLocalizedString("search-placeholder", + IDS_FLAGS_UI_SEARCH_PLACEHOLDER); + source->AddLocalizedString("title", IDS_FLAGS_UI_TITLE); + source->AddLocalizedString("unavailable", IDS_FLAGS_UI_UNAVAILABLE_FEATURE); +} + +// static +void FlagsDeprecatedUI::AddStrings(content::WebUIDataSource* source) { + source->AddLocalizedString(flags_ui::kFlagsRestartNotice, + IDS_DEPRECATED_FEATURES_RELAUNCH_NOTICE); + source->AddLocalizedString("available", + IDS_DEPRECATED_FEATURES_AVAILABLE_FEATURE); + source->AddLocalizedString("clear-search", IDS_DEPRECATED_UI_CLEAR_SEARCH); + source->AddLocalizedString("disabled", + IDS_DEPRECATED_FEATURES_DISABLED_FEATURE); + source->AddLocalizedString("enabled", + IDS_DEPRECATED_FEATURES_ENABLED_FEATURE); + source->AddLocalizedString("experiment-enabled", + IDS_DEPRECATED_UI_EXPERIMENT_ENABLED); + source->AddLocalizedString("no-results", IDS_DEPRECATED_FEATURES_NO_RESULTS); + source->AddLocalizedString("not-available-platform", + IDS_DEPRECATED_FEATURES_NOT_AVAILABLE_ON_PLATFORM); + source->AddLocalizedString("page-warning", + IDS_DEPRECATED_FEATURES_PAGE_WARNING); + source->AddLocalizedString("page-warning-explanation", + IDS_DEPRECATED_FEATURES_PAGE_WARNING_EXPLANATION); + source->AddLocalizedString("relaunch", IDS_DEPRECATED_FEATURES_RELAUNCH); + source->AddLocalizedString("reset", IDS_DEPRECATED_FEATURES_PAGE_RESET); + source->AddLocalizedString("reset-acknowledged", + IDS_DEPRECATED_UI_RESET_ACKNOWLEDGED); + source->AddLocalizedString("search-placeholder", + IDS_DEPRECATED_FEATURES_SEARCH_PLACEHOLDER); + source->AddLocalizedString("title", IDS_DEPRECATED_FEATURES_TITLE); + source->AddLocalizedString("unavailable", + IDS_DEPRECATED_FEATURES_UNAVAILABLE_FEATURE); +} +template <class T> +FlagsUIHandler* InitializeHandler(content::WebUI* web_ui, + Profile* profile, + base::WeakPtrFactory<T>& weak_factory) { auto handler_owner = std::make_unique<FlagsUIHandler>(); FlagsUIHandler* handler = handler_owner.get(); web_ui->AddMessageHandler(std::move(handler_owner)); @@ -133,11 +191,11 @@ FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) { chromeos::OwnerSettingsServiceChromeOS* service = chromeos::OwnerSettingsServiceChromeOSFactory::GetForBrowserContext( original_profile); - service->IsOwnerAsync(base::Bind(&FinishInitialization, - weak_factory_.GetWeakPtr(), + service->IsOwnerAsync(base::Bind(&FinishInitialization<T>, + weak_factory.GetWeakPtr(), original_profile, handler)); } else { - FinishInitialization(weak_factory_.GetWeakPtr(), original_profile, handler, + FinishInitialization(weak_factory.GetWeakPtr(), original_profile, handler, false /* current_user_is_owner */); } #else @@ -145,9 +203,20 @@ FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) { new flags_ui::PrefServiceFlagsStorage(g_browser_process->local_state()), flags_ui::kOwnerAccessToFlags); #endif + return handler; +} + +FlagsUI::FlagsUI(content::WebUI* web_ui) + : WebUIController(web_ui), weak_factory_(this) { + Profile* profile = Profile::FromWebUI(web_ui); + auto* handler = InitializeHandler(web_ui, profile, weak_factory_); + DCHECK(handler); + handler->set_deprecated_features_only(false); // Set up the about:flags source. - content::WebUIDataSource::Add(profile, CreateFlagsUIHTMLSource()); + auto* source = CreateFlagsUIHTMLSource(); + AddStrings(source); + content::WebUIDataSource::Add(profile, source); } FlagsUI::~FlagsUI() { @@ -159,3 +228,23 @@ base::RefCountedMemory* FlagsUI::GetFaviconResourceBytes( return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( IDR_FLAGS_FAVICON, scale_factor); } + +FlagsDeprecatedUI::FlagsDeprecatedUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + auto* handler = InitializeHandler(web_ui, profile, weak_factory_); + DCHECK(handler); + handler->set_deprecated_features_only(true); + + // Set up the about:flags/deprecated source. + auto* source = CreateFlagsUIHTMLSource(); + AddStrings(source); + content::WebUIDataSource::Add(profile, source); +} + +FlagsDeprecatedUI::~FlagsDeprecatedUI() {} + +// static +bool FlagsDeprecatedUI::IsDeprecatedUrl(const GURL& url) { + return url.path() == "/deprecated" || url.path() == "/deprecated/"; +} diff --git a/chromium/chrome/browser/ui/webui/flags_ui.h b/chromium/chrome/browser/ui/webui/flags_ui.h index c41991b2f88..3809b15190d 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui.h +++ b/chromium/chrome/browser/ui/webui/flags_ui.h @@ -19,11 +19,16 @@ namespace base { class RefCountedMemory; } +namespace content { +class WebUIDataSource; +} + class FlagsUI : public content::WebUIController { public: explicit FlagsUI(content::WebUI* web_ui); ~FlagsUI() override; + static void AddStrings(content::WebUIDataSource* source); static base::RefCountedMemory* GetFaviconResourceBytes( ui::ScaleFactor scale_factor); @@ -33,4 +38,17 @@ class FlagsUI : public content::WebUIController { DISALLOW_COPY_AND_ASSIGN(FlagsUI); }; +class FlagsDeprecatedUI : public content::WebUIController { + public: + explicit FlagsDeprecatedUI(content::WebUI* web_ui); + ~FlagsDeprecatedUI() override; + + static void AddStrings(content::WebUIDataSource* source); + static bool IsDeprecatedUrl(const GURL& url); + + private: + base::WeakPtrFactory<FlagsDeprecatedUI> weak_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(FlagsDeprecatedUI); +}; #endif // CHROME_BROWSER_UI_WEBUI_FLAGS_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/flags_ui_handler.cc b/chromium/chrome/browser/ui/webui/flags_ui_handler.cc index 0c03c7a56fa..3661f832926 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/flags_ui_handler.cc @@ -22,7 +22,8 @@ FlagsUIHandler::FlagsUIHandler() : access_(flags_ui::kGeneralAccessFlagsOnly), - experimental_features_requested_(false) {} + experimental_features_requested_(false), + deprecated_features_only_(false) {} FlagsUIHandler::~FlagsUIHandler() {} @@ -72,9 +73,15 @@ void FlagsUIHandler::HandleRequestExperimentalFeatures( std::unique_ptr<base::ListValue> supported_features(new base::ListValue); std::unique_ptr<base::ListValue> unsupported_features(new base::ListValue); - about_flags::GetFlagFeatureEntries(flags_storage_.get(), access_, - supported_features.get(), - unsupported_features.get()); + if (deprecated_features_only_) { + about_flags::GetFlagFeatureEntriesForDeprecatedPage( + flags_storage_.get(), access_, supported_features.get(), + unsupported_features.get()); + } else { + about_flags::GetFlagFeatureEntries(flags_storage_.get(), access_, + supported_features.get(), + unsupported_features.get()); + } results.Set(flags_ui::kSupportedFeatures, std::move(supported_features)); results.Set(flags_ui::kUnsupportedFeatures, std::move(unsupported_features)); @@ -85,10 +92,12 @@ void FlagsUIHandler::HandleRequestExperimentalFeatures( #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) version_info::Channel channel = chrome::GetChannel(); - results.SetBoolean(flags_ui::kShowBetaChannelPromotion, - channel == version_info::Channel::STABLE); - results.SetBoolean(flags_ui::kShowDevChannelPromotion, - channel == version_info::Channel::BETA); + results.SetBoolean( + flags_ui::kShowBetaChannelPromotion, + channel == version_info::Channel::STABLE && !deprecated_features_only_); + results.SetBoolean( + flags_ui::kShowDevChannelPromotion, + channel == version_info::Channel::BETA && !deprecated_features_only_); #else results.SetBoolean(flags_ui::kShowBetaChannelPromotion, false); results.SetBoolean(flags_ui::kShowDevChannelPromotion, false); diff --git a/chromium/chrome/browser/ui/webui/flags_ui_handler.h b/chromium/chrome/browser/ui/webui/flags_ui_handler.h index 05c6bfd343b..f76e2847a3e 100644 --- a/chromium/chrome/browser/ui/webui/flags_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/flags_ui_handler.h @@ -26,6 +26,12 @@ class FlagsUIHandler : public content::WebUIMessageHandler { // this was called, it calls |HandleRequestExperimentalFeatures| again. void Init(flags_ui::FlagsStorage* flags_storage, flags_ui::FlagAccess access); + // Configures the handler to return either all features or deprecated + // features only. + void set_deprecated_features_only(bool deprecatedFeaturesOnly) { + deprecated_features_only_ = deprecatedFeaturesOnly; + } + // WebUIMessageHandler implementation. void RegisterMessages() override; @@ -48,6 +54,7 @@ class FlagsUIHandler : public content::WebUIMessageHandler { std::unique_ptr<flags_ui::FlagsStorage> flags_storage_; flags_ui::FlagAccess access_; bool experimental_features_requested_; + bool deprecated_features_only_; DISALLOW_COPY_AND_ASSIGN(FlagsUIHandler); }; diff --git a/chromium/chrome/browser/ui/webui/flags_ui_unittest.cc b/chromium/chrome/browser/ui/webui/flags_ui_unittest.cc new file mode 100644 index 00000000000..e5f5a49a5ad --- /dev/null +++ b/chromium/chrome/browser/ui/webui/flags_ui_unittest.cc @@ -0,0 +1,50 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/flags_ui.h" + +#include "base/values.h" +#include "content/public/test/browser_task_environment.h" +#include "content/public/test/test_web_ui_data_source.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +class FlagsUITest : public testing::Test { + public: + FlagsUITest() = default; + + private: + content::TestBrowserThreadBundle bundle_; +}; + +TEST_F(FlagsUITest, IsDeprecatedUrl) { + const struct { + std::string url; + bool is_deprecated; + } expectations[] = { + {"chrome://flags", false}, + {"chrome://flags/no/deprecated", false}, + {"chrome://deprecated", false}, + {"chrome://flags/deprecated", true}, + {"chrome://flags/deprecated/", true}, + {"chrome://flags//deprecated/yes?no", false}, + }; + + for (const auto& expectation : expectations) { + EXPECT_EQ(expectation.is_deprecated, + FlagsDeprecatedUI::IsDeprecatedUrl(GURL(expectation.url))); + } +} + +TEST_F(FlagsUITest, FlagsAndDeprecatedSources) { + std::unique_ptr<content::TestWebUIDataSource> flags_strings = + content::TestWebUIDataSource::Create("A"); + std::unique_ptr<content::TestWebUIDataSource> deprecated_strings = + content::TestWebUIDataSource::Create("B"); + FlagsUI::AddStrings(flags_strings->GetWebUIDataSource()); + FlagsDeprecatedUI::AddStrings(deprecated_strings->GetWebUIDataSource()); + EXPECT_EQ(flags_strings->GetLocalizedStrings()->size(), + deprecated_strings->GetLocalizedStrings()->size()); +} diff --git a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc index 48900ea2404..dc148f71d72 100644 --- a/chromium/chrome/browser/ui/webui/foreign_session_handler.cc +++ b/chromium/chrome/browser/ui/webui/foreign_session_handler.cc @@ -89,6 +89,8 @@ std::unique_ptr<base::DictionaryValue> SessionTabToValue( new base::DictionaryValue()); NewTabUI::SetUrlTitleAndDirection(dictionary.get(), current_navigation.title(), tab_url); + dictionary->SetString("remoteIconUrlForUma", + current_navigation.favicon_url().spec()); dictionary->SetString("type", "tab"); dictionary->SetDouble("timestamp", static_cast<double>(tab.timestamp.ToInternalValue())); diff --git a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc index b1e16e87001..6fcce1ae41a 100644 --- a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc @@ -160,7 +160,7 @@ GCMInternalsUI::GCMInternalsUI(content::WebUI* web_ui) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIGCMInternalsHost); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); // Add required resources. html_source->AddResourcePath(gcm_driver::kGcmInternalsCSS, 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 fd278d7d6c2..55b745814a2 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc @@ -88,8 +88,6 @@ base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) { } if (chromeos::NetworkTypePattern::Ethernet().MatchesType(type)) return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_ETHERNET); - if (chromeos::NetworkTypePattern::Wimax().MatchesType(type)) - return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIMAX); if (chromeos::NetworkTypePattern::Mobile().MatchesType(type)) return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_MOBILE_DATA); if (chromeos::NetworkTypePattern::VPN().MatchesType(type)) @@ -252,17 +250,17 @@ void VersionUpdaterCros::GetEolStatus(EolStatusCallback cb) { weak_ptr_factory_.GetWeakPtr(), std::move(cb))); } -void VersionUpdaterCros::OnGetEolStatus(EolStatusCallback cb, - update_engine::EndOfLifeStatus status) { +void VersionUpdaterCros::OnGetEolStatus( + EolStatusCallback cb, + update_engine::EndOfLifeStatus status, + base::Optional<int32_t> number_of_milestones) { std::move(cb).Run(status); } VersionUpdaterCros::VersionUpdaterCros(content::WebContents* web_contents) : context_(web_contents ? web_contents->GetBrowserContext() : nullptr), last_operation_(UpdateEngineClient::UPDATE_STATUS_IDLE), - check_for_update_when_idle_(false), - weak_ptr_factory_(this) { -} + check_for_update_when_idle_(false) {} VersionUpdaterCros::~VersionUpdaterCros() { UpdateEngineClient* update_engine_client = 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 ec6ea7da17e..3ec09168b97 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h +++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.h @@ -59,7 +59,8 @@ class VersionUpdaterCros : public VersionUpdater, // Callback from UpdateEngineClient::GetEolStatus(). void OnGetEolStatus(EolStatusCallback cb, - update_engine::EndOfLifeStatus status); + update_engine::EndOfLifeStatus status, + base::Optional<int32_t> number_of_milestones); // BrowserContext in which the class was instantiated. content::BrowserContext* context_; @@ -73,7 +74,7 @@ class VersionUpdaterCros : public VersionUpdater, // True if an update check should be scheduled when the update engine is idle. bool check_for_update_when_idle_; - base::WeakPtrFactory<VersionUpdaterCros> weak_ptr_factory_; + base::WeakPtrFactory<VersionUpdaterCros> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VersionUpdaterCros); }; 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 a19b61e6e61..850f225d3e7 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 @@ -18,7 +18,7 @@ #include "chromeos/dbus/shill/shill_service_client.h" #include "chromeos/network/network_handler.h" #include "components/user_manager/scoped_user_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.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" @@ -90,7 +90,7 @@ class VersionUpdaterCrosTest : public ::testing::Test { NetworkHandler::Shutdown(); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<VersionUpdater> version_updater_; FakeUpdateEngineClient* fake_update_engine_client_; // Not owned. diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc index 7eb104ff796..6467d6e1dca 100644 --- a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc +++ b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc @@ -40,8 +40,10 @@ void VersionUpdaterWin::OnUpdateCheckComplete( if (new_version.empty()) { // Google Update says that no new version is available. Check to see if a // restart is needed for a previously-applied update to take effect. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}, base::Bind(&upgrade_util::IsUpdatePendingRestart), base::Bind(&VersionUpdaterWin::OnPendingRestartCheck, weak_factory_.GetWeakPtr())); diff --git a/chromium/chrome/browser/ui/webui/history_login_handler.cc b/chromium/chrome/browser/ui/webui/history_login_handler.cc index f8db85e08e6..0c3eb1a4047 100644 --- a/chromium/chrome/browser/ui/webui/history_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/history_login_handler.cc @@ -23,10 +23,10 @@ HistoryLoginHandler::HistoryLoginHandler(const base::Closure& signin_callback) HistoryLoginHandler::~HistoryLoginHandler() {} void HistoryLoginHandler::RegisterMessages() { - profile_info_watcher_.reset(new ProfileInfoWatcher( + profile_info_watcher_ = std::make_unique<ProfileInfoWatcher>( Profile::FromWebUI(web_ui()), base::Bind(&HistoryLoginHandler::ProfileInfoChanged, - base::Unretained(this)))); + base::Unretained(this))); web_ui()->RegisterMessageCallback( "otherDevicesInitialized", @@ -59,6 +59,6 @@ void HistoryLoginHandler::HandleStartSignInFlow( Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, signin::ManageAccountsParams(), + BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS, false); } diff --git a/chromium/chrome/browser/ui/webui/history_ui.cc b/chromium/chrome/browser/ui/webui/history_ui.cc index 368b995af9a..5f900c0829b 100644 --- a/chromium/chrome/browser/ui/webui/history_ui.cc +++ b/chromium/chrome/browser/ui/webui/history_ui.cc @@ -167,7 +167,7 @@ content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) { #endif source->SetDefaultResource(IDR_HISTORY_HISTORY_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc index 1a5607b50c2..51016ebb1a9 100644 --- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc +++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc @@ -27,7 +27,6 @@ #include "components/safe_browsing/db/database_manager.h" #include "components/security_interstitials/content/origin_policy_ui.h" #include "components/security_interstitials/core/ssl_error_ui.h" -#include "components/supervised_user_error_page/supervised_user_error_page.h" #include "content/public/browser/interstitial_page_delegate.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -49,6 +48,11 @@ #include "chrome/browser/ssl/captive_portal_blocking_page.h" #endif +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) +#include "chrome/browser/supervised_user/supervised_user_error_page/supervised_user_error_page.h" +#include "chrome/browser/supervised_user/supervised_user_interstitial.h" +#endif + using security_interstitials::TestSafeBrowsingBlockingPageQuiet; namespace { @@ -89,11 +93,13 @@ class InterstitialHTMLSource : public content::URLDataSource { std::string GetContentSecurityPolicyImgSrc() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; private: +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::string GetSupervisedUserInterstitialHTML(const std::string& path); +#endif DISALLOW_COPY_AND_ASSIGN(InterstitialHTMLSource); }; @@ -462,7 +468,7 @@ std::string InterstitialHTMLSource::GetContentSecurityPolicyImgSrc() { void InterstitialHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { content::WebContents* web_contents = wc_getter.Run(); if (!web_contents) { @@ -496,13 +502,15 @@ void InterstitialHTMLSource::StartDataRequest( CreateOriginPolicyInterstitialPage(web_contents)); } - if (path_without_query == "/supervised_user") { - html = GetSupervisedUserInterstitialHTML(path); - } else if (path_without_query == "/quietsafebrowsing") { + if (path_without_query == "/quietsafebrowsing") { TestSafeBrowsingBlockingPageQuiet* blocking_page = CreateSafeBrowsingQuietBlockingPage(web_contents); interstitial_delegate.reset(blocking_page); html = blocking_page->GetHTML(); +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) + } else if (path_without_query == "/supervised_user") { + html = GetSupervisedUserInterstitialHTML(path); +#endif } else if (interstitial_delegate.get()) { html = interstitial_delegate.get()->GetHTMLContents(); } else { @@ -514,6 +522,7 @@ void InterstitialHTMLSource::StartDataRequest( callback.Run(html_bytes.get()); } +#if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::string InterstitialHTMLSource::GetSupervisedUserInterstitialHTML( const std::string& path) { GURL url("https://localhost/" + path); @@ -571,3 +580,4 @@ std::string InterstitialHTMLSource::GetSupervisedUserInterstitialHTML( is_child_account, is_deprecated, reason, g_browser_process->GetApplicationLocale()); } +#endif 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 de85f80c7d1..867c83d78ca 100644 --- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui_browsertest.cc @@ -150,7 +150,7 @@ IN_PROC_BROWSER_TEST_F(InterstitialUITest, UnwantedSoftwareInterstitialQuiet) { IN_PROC_BROWSER_TEST_F(InterstitialUITest, BillingInterstitialQuiet) { TestInterstitial( GURL("chrome://interstitials/quietsafebrowsing?type=billing"), - "Security error", IDS_BILLING_WEBVIEW_HEADING); + "Page may charge money", IDS_BILLING_WEBVIEW_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsideMalwareInterstitial) { @@ -167,7 +167,7 @@ IN_PROC_BROWSER_TEST_F(InterstitialUITest, ClientsidePhishingInterstitial) { IN_PROC_BROWSER_TEST_F(InterstitialUITest, BillingInterstitial) { TestInterstitial(GURL("chrome://interstitials/safebrowsing?type=billing"), - "Security error", IDS_BILLING_HEADING); + "Page may charge money", IDS_BILLING_HEADING); } IN_PROC_BROWSER_TEST_F(InterstitialUITest, CaptivePortalInterstitial) { diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc index 3f8998adb52..c4b5994f991 100644 --- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc @@ -19,7 +19,7 @@ #include "base/run_loop.h" #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "base/time/default_clock.h" #include "build/build_config.h" #include "chrome/browser/flag_descriptions.h" @@ -38,7 +38,7 @@ #include "components/previews/core/previews_logger.h" #include "components/previews/core/previews_logger_observer.h" #include "components/previews/core/previews_switches.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "mojo/public/cpp/bindings/binding.h" #include "net/base/features.h" #include "net/nqe/effective_connection_type.h" @@ -310,7 +310,7 @@ class InterventionsInternalsPageHandlerTest : public testing::Test { page_.reset(); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; protected: TestingProfileManager profile_manager_; diff --git a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc index 858391be7b1..27b07ff974c 100644 --- a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc @@ -7,7 +7,6 @@ #include <utility> #include "base/bind.h" -#include "chrome/browser/invalidation/deprecated_profile_invalidation_provider_factory.h" #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/invalidation/impl/invalidation_logger.h" @@ -29,13 +28,8 @@ namespace { invalidation::ProfileInvalidationProvider* GetInvalidationProvider( Profile* profile) { - if (base::FeatureList::IsEnabled(invalidation::switches::kFCMInvalidations)) { - return invalidation::ProfileInvalidationProviderFactory::GetForProfile( - profile); - } else { - return invalidation::DeprecatedProfileInvalidationProviderFactory:: - GetForProfile(profile); - } + return invalidation::ProfileInvalidationProviderFactory::GetForProfile( + profile); } } // namespace 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 f422bff9918..4b2a6a713f2 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 @@ -81,7 +81,7 @@ content::WebUIDataSource* CreateLocalDiscoveryHTMLSource() { }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->DisableDenyXFrameOptions(); diff --git a/chromium/chrome/browser/ui/webui/managed_ui_handler.cc b/chromium/chrome/browser/ui/webui/managed_ui_handler.cc index 5fd6841ecd7..3d4e6125bbe 100644 --- a/chromium/chrome/browser/ui/webui/managed_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/managed_ui_handler.cc @@ -110,8 +110,12 @@ void ManagedUIHandler::RemoveObservers() { std::unique_ptr<base::DictionaryValue> ManagedUIHandler::GetDataSourceUpdate() const { auto update = std::make_unique<base::DictionaryValue>(); - update->SetKey("managedByOrg", + update->SetKey("browserManagedByOrg", base::Value(chrome::GetManagedUiWebUILabel(profile_))); +#if defined(OS_CHROMEOS) + update->SetKey("deviceManagedByOrg", + base::Value(chrome::GetDeviceManagedUiWebUILabel(profile_))); +#endif update->SetKey("isManaged", base::Value(managed_)); return update; } diff --git a/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc index f9a4b1b0c37..c165d33a633 100644 --- a/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc @@ -13,7 +13,7 @@ #include "components/policy/core/common/policy_service_impl.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "content/public/test/test_web_ui_data_source.h" #include "testing/gmock/include/gmock/gmock.h" @@ -75,7 +75,7 @@ class ManagedUIHandlerTest : public testing::Test { } private: - content::TestBrowserThreadBundle bundle_; + content::BrowserTaskEnvironment task_environment_; testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_; std::unique_ptr<TestingProfile> profile_; diff --git a/chromium/chrome/browser/ui/webui/management_ui.cc b/chromium/chrome/browser/ui/webui/management_ui.cc index fd0d3cbdde4..cf98a0cd441 100644 --- a/chromium/chrome/browser/ui/webui/management_ui.cc +++ b/chromium/chrome/browser/ui/webui/management_ui.cc @@ -86,6 +86,18 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) { IDS_MANAGEMENT_EXTENSION_REPORT_PERF_CRASH}, {kManagementExtensionReportUserBrowsingData, IDS_MANAGEMENT_EXTENSION_REPORT_USER_BROWSING_DATA}, + {kThreatProtectionTitle, IDS_MANAGEMENT_THREAT_PROTECTION}, + {kManagementDataLossPreventionName, + IDS_MANAGEMENT_DATA_LOSS_PREVENTION_NAME}, + {kManagementDataLossPreventionPermissions, + IDS_MANAGEMENT_DATA_LOSS_PREVENTION_PERMISSIONS}, + {kManagementMalwareScanningName, IDS_MANAGEMENT_MALWARE_SCANNING_NAME}, + {kManagementMalwareScanningPermissions, + IDS_MANAGEMENT_MALWARE_SCANNING_PERMISSIONS}, + {kManagementEnterpriseReportingName, + IDS_MANAGEMENT_ENTERPRISE_REPORTING_NAME}, + {kManagementEnterpriseReportingPermissions, + IDS_MANAGEMENT_ENTERPRISE_REPORTING_PERMISSIONS}, }; AddLocalizedStringsBulk(source, kLocalizedStrings, @@ -102,7 +114,7 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) { chrome::kManagedUiLearnMoreUrl); #endif // defined(OS_CHROMEOS) - source->SetJsonPath("strings.js"); + source->UseStringsJs(); // Add required resources. source->AddResourcePath("management_browser_proxy.html", IDR_MANAGEMENT_BROWSER_PROXY_HTML); diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.cc b/chromium/chrome/browser/ui/webui/management_ui_handler.cc index 329d86573be..6b9e20b4ac9 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/management_ui_handler.cc @@ -25,6 +25,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" +#include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" @@ -45,6 +46,7 @@ #include "chrome/browser/chromeos/policy/status_uploader.h" #include "chrome/browser/chromeos/policy/system_log_uploader.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/ui/webui/management_ui_handler_chromeos.h" #include "chrome/grit/chromium_strings.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" @@ -56,6 +58,7 @@ #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 "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "extensions/common/extension_set.h" @@ -95,6 +98,19 @@ const char kManagementExtensionReportPerfCrash[] = const char kManagementExtensionReportUserBrowsingData[] = "managementExtensionReportUserBrowsingData"; +const char kThreatProtectionTitle[] = "threatProtectionTitle"; +const char kManagementDataLossPreventionName[] = + "managementDataLossPreventionName"; +const char kManagementDataLossPreventionPermissions[] = + "managementDataLossPreventionPermissions"; +const char kManagementMalwareScanningName[] = "managementMalwareScanningName"; +const char kManagementMalwareScanningPermissions[] = + "managementMalwareScanningPermissions"; +const char kManagementEnterpriseReportingName[] = + "managementEnterpriseReportingName"; +const char kManagementEnterpriseReportingPermissions[] = + "managementEnterpriseReportingPermissions"; + const char kReportingTypeDevice[] = "device"; const char kReportingTypeExtensions[] = "extensions"; const char kReportingTypeSecurity[] = "security"; @@ -377,6 +393,10 @@ void ManagementUIHandler::RegisterMessages() { base::Unretained(this))); #endif // defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( + "getThreatProtectionInfo", + base::BindRepeating(&ManagementUIHandler::HandleGetThreatProtectionInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "initBrowserReportingInfo", base::BindRepeating(&ManagementUIHandler::HandleInitBrowserReportingInfo, base::Unretained(this))); @@ -560,6 +580,70 @@ base::DictionaryValue ManagementUIHandler::GetContextualManagedData( return response; } +base::Value ManagementUIHandler::GetThreatProtectionInfo( + Profile* profile) const { + base::Value info(base::Value::Type::LIST); + const policy::PolicyService* policy_service = GetPolicyService(); + const auto& chrome_policies = policy_service->GetPolicies( + policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())); + // CheckContentCompliance is a int-enum policy. The accepted values are + // defined in the enum CheckContentComplianceValues. + auto* check_content_compliance_value = + chrome_policies.GetValue(policy::key::kCheckContentCompliance); + if (check_content_compliance_value && + check_content_compliance_value->GetInt() > safe_browsing::CHECK_NONE && + check_content_compliance_value->GetInt() <= + safe_browsing::CHECK_CONTENT_COMPLIANCE_MAX) { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementDataLossPreventionName); + value.SetStringKey("permission", kManagementDataLossPreventionPermissions); + info.GetList().push_back(std::move(value)); + } + + // SendFilesForMalwareCheck is a int-enum policy. The accepted values are + // defined in the enum SendFilesForMalwareCheckValues. + auto* send_files_for_malware_check_value = + chrome_policies.GetValue(policy::key::kSendFilesForMalwareCheck); + if (send_files_for_malware_check_value && + send_files_for_malware_check_value->GetInt() > + safe_browsing::SEND_FILES_DISABLED && + send_files_for_malware_check_value->GetInt() <= + safe_browsing::SEND_FILES_FOR_MALWARE_CHECK_MAX) { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementMalwareScanningName); + value.SetStringKey("permission", kManagementMalwareScanningPermissions); + info.GetList().push_back(std::move(value)); + } + + auto* unsafe_event_reporting_value = + chrome_policies.GetValue(policy::key::kUnsafeEventsReportingEnabled); + if (unsafe_event_reporting_value && unsafe_event_reporting_value->GetBool()) { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementEnterpriseReportingName); + value.SetStringKey("permission", kManagementEnterpriseReportingPermissions); + info.GetList().push_back(std::move(value)); + } + +#if defined(OS_CHROMEOS) + std::string management_domain = GetDeviceDomain(); + if (management_domain.empty()) + management_domain = GetAccountDomain(profile); +#else + std::string management_domain = GetAccountDomain(profile); +#endif // defined(OS_CHROMEOS) + + base::Value result(base::Value::Type::DICTIONARY); + result.SetStringKey("description", + management_domain.empty() + ? l10n_util::GetStringUTF16( + IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION) + : l10n_util::GetStringFUTF16( + IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION_BY, + base::UTF8ToUTF16(management_domain))); + result.SetKey("info", std::move(info)); + return result; +} + policy::PolicyService* ManagementUIHandler::GetPolicyService() const { return Profile::FromWebUI(web_ui()) ->GetProfilePolicyConnector() @@ -579,29 +663,8 @@ void ManagementUIHandler::AsyncUpdateLogo() { g_browser_process->platform_part()->browser_policy_connector_chromeos(); const auto url = connector->GetCustomerLogoURL(); if (!url.empty() && GURL(url) != logo_url_) { - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("management_ui_customer_logo", R"( - semantics { - sender: "Management UI Handler" - description: - "Download organization logo for visualization on the " - "chrome://management page." - trigger: - "The user managed by organization that provides a company logo " - "in their GSuites account loads the chrome://management page." - data: - "Organization uploaded image URL." - destination: GOOGLE_OWNED_SERVICE - } - policy { - cookies_allowed: NO - setting: - "This feature cannot be disabled by settings, but it is only " - "triggered by a user action." - policy_exception_justification: "Not implemented." - })"); - icon_fetcher_ = - std::make_unique<BitmapFetcher>(GURL(url), this, traffic_annotation); + icon_fetcher_ = std::make_unique<BitmapFetcher>( + GURL(url), this, GetManagementUICustomerLogoAnnotation()); icon_fetcher_->Init( std::string(), net::URLRequest::NEVER_CLEAR_REFERRER, net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES); @@ -750,6 +813,14 @@ void ManagementUIHandler::HandleGetContextualManagedData( std::move(result)); } +void ManagementUIHandler::HandleGetThreatProtectionInfo( + const base::ListValue* args) { + AllowJavascript(); + ResolveJavascriptCallback( + args->GetList()[0] /* callback_id */, + GetThreatProtectionInfo(Profile::FromWebUI(web_ui()))); +} + void ManagementUIHandler::HandleInitBrowserReportingInfo( const base::ListValue* args) { base::Value report_sources(base::Value::Type::LIST); @@ -765,6 +836,11 @@ void ManagementUIHandler::NotifyBrowserReportingInfoUpdated() { FireWebUIListener("browser-reporting-info-updated", report_sources); } +void ManagementUIHandler::NotifyThreatProtectionInfoUpdated() { + FireWebUIListener("threat-protection-info-updated", + GetThreatProtectionInfo(Profile::FromWebUI(web_ui()))); +} + void ManagementUIHandler::OnExtensionLoaded( content::BrowserContext* /*browser_context*/, const extensions::Extension* extension) { @@ -808,6 +884,7 @@ void ManagementUIHandler::OnPolicyUpdated( const policy::PolicyMap& /*current*/) { UpdateManagedState(); NotifyBrowserReportingInfoUpdated(); + NotifyThreatProtectionInfoUpdated(); } void ManagementUIHandler::AddObservers() { diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.h b/chromium/chrome/browser/ui/webui/management_ui_handler.h index 1d40707ca7c..f06e8d6e58a 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler.h +++ b/chromium/chrome/browser/ui/webui/management_ui_handler.h @@ -48,6 +48,14 @@ extern const char kManagementExtensionReportSafeBrowsingWarnings[]; extern const char kManagementExtensionReportPerfCrash[]; extern const char kManagementExtensionReportUserBrowsingData[]; +extern const char kThreatProtectionTitle[]; +extern const char kManagementDataLossPreventionName[]; +extern const char kManagementDataLossPreventionPermissions[]; +extern const char kManagementMalwareScanningName[]; +extern const char kManagementMalwareScanningPermissions[]; +extern const char kManagementEnterpriseReportingName[]; +extern const char kManagementEnterpriseReportingPermissions[]; + extern const char kPolicyKeyReportMachineIdData[]; extern const char kPolicyKeyReportUserIdData[]; extern const char kPolicyKeyReportVersionData[]; @@ -108,6 +116,7 @@ class ManagementUIHandler : public content::WebUIMessageHandler, void AddExtensionReportingInfo(base::Value* report_sources); base::DictionaryValue GetContextualManagedData(Profile* profile); + base::Value GetThreatProtectionInfo(Profile* profile) const; virtual policy::PolicyService* GetPolicyService() const; virtual const extensions::Extension* GetEnabledExtension( const std::string& extensionId) const; @@ -130,6 +139,7 @@ class ManagementUIHandler : public content::WebUIMessageHandler, #endif // defined(OS_CHROMEOS) void HandleGetContextualManagedData(const base::ListValue* args); + void HandleGetThreatProtectionInfo(const base::ListValue* args); void HandleInitBrowserReportingInfo(const base::ListValue* args); void AsyncUpdateLogo(); @@ -138,6 +148,7 @@ class ManagementUIHandler : public content::WebUIMessageHandler, void OnFetchComplete(const GURL& url, const SkBitmap* bitmap) override; void NotifyBrowserReportingInfoUpdated(); + void NotifyThreatProtectionInfoUpdated(); // extensions::ExtensionRegistryObserver implementation. void OnExtensionLoaded(content::BrowserContext* browser_context, diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.cc new file mode 100644 index 00000000000..2702f506396 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.cc @@ -0,0 +1,28 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/management_ui_handler_chromeos.h" + +net::NetworkTrafficAnnotationTag GetManagementUICustomerLogoAnnotation() { + return net::DefineNetworkTrafficAnnotation("management_ui_customer_logo", R"( + semantics { + sender: "Management UI Handler" + description: + "Download organization logo for visualization on the " + "chrome://management page." + trigger: + "The user managed by organization that provides a company logo " + "in their GSuites account loads the chrome://management page." + data: + "Organization uploaded image URL." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: + "This feature cannot be disabled by settings, but it is only " + "triggered by a user action." + policy_exception_justification: "Not implemented." + })"); +} diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.h b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.h new file mode 100644 index 00000000000..b2deb928e03 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/management_ui_handler_chromeos.h @@ -0,0 +1,12 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_MANAGEMENT_UI_HANDLER_CHROMEOS_H_ +#define CHROME_BROWSER_UI_WEBUI_MANAGEMENT_UI_HANDLER_CHROMEOS_H_ + +#include "net/traffic_annotation/network_traffic_annotation.h" + +net::NetworkTrafficAnnotationTag GetManagementUICustomerLogoAnnotation(); + +#endif // CHROME_BROWSER_UI_WEBUI_MANAGEMENT_UI_HANDLER_CHROMEOS_H_ diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc index c118fd35680..8541fce2c79 100644 --- a/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc @@ -15,8 +15,9 @@ #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/strings/grit/components_strings.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "testing/gmock/include/gmock/gmock.h" @@ -64,6 +65,10 @@ class TestManagementUIHandler : public ManagementUIHandler { return report_sources; } + base::Value GetThreatProtectionInfo(Profile* profile) { + return ManagementUIHandler::GetThreatProtectionInfo(profile); + } + policy::PolicyService* GetPolicyService() const override { return policy_service_; } @@ -101,6 +106,20 @@ class ManagementUIHandlerTests : public testing::Test { policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(true), nullptr); } + void SetPolicyValue(const char* policy_key, + policy::PolicyMap& policies, + int value) { + policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>(value), nullptr); + } + void SetPolicyValue(const char* policy_key, + policy::PolicyMap& policies, + bool value) { + policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>(value), nullptr); + } void ExtractContextualSourceUpdate( const base::DictionaryValue& data, @@ -119,7 +138,7 @@ class ManagementUIHandlerTests : public testing::Test { protected: TestManagementUIHandler handler_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; policy::MockPolicyService policy_service_; policy::PolicyMap empty_policy_map_; base::string16 device_domain_; @@ -606,3 +625,81 @@ TEST_F(ManagementUIHandlerTests, ExtensionReportingInfoPoliciesMerge) { } EXPECT_EQ(reporting_info.GetList().size(), expected_messages.size()); } + +TEST_F(ManagementUIHandlerTests, ThreatReportingInfo) { + policy::PolicyMap chrome_policies; + const policy::PolicyNamespace chrome_policies_namespace = + policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()); + + TestingProfile::Builder builder_no_domain; + auto profile_no_domain = builder_no_domain.Build(); + + TestingProfile::Builder builder_known_domain; + builder_known_domain.SetProfileName("managed@manager.com"); + auto profile_known_domain = builder_known_domain.Build(); + +#if defined(OS_CHROMEOS) + handler_.SetDeviceDomain(""); +#endif // !defined(OS_CHROMEOS) + + EXPECT_CALL(policy_service_, GetPolicies(chrome_policies_namespace)) + .WillRepeatedly(ReturnRef(chrome_policies)); + + base::DictionaryValue* threat_protection_info = nullptr; + + // When no policies are set, nothing to report. + auto info = handler_.GetThreatProtectionInfo(profile_no_domain.get()); + info.GetAsDictionary(&threat_protection_info); + EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty()); + EXPECT_EQ( + l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION), + base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description"))); + + // When policies are set to uninteresting values, nothing to report. + SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 0); + SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 0); + SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies, + false); + info = handler_.GetThreatProtectionInfo(profile_known_domain.get()); + info.GetAsDictionary(&threat_protection_info); + EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty()); + EXPECT_EQ( + l10n_util::GetStringFUTF16( + IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION_BY, + base::UTF8ToUTF16("manager.com")), + base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description"))); + + // When policies are set to values that enable the feature, report it. + SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 1); + SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 2); + SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies, + true); + info = handler_.GetThreatProtectionInfo(profile_no_domain.get()); + info.GetAsDictionary(&threat_protection_info); + EXPECT_EQ(3u, threat_protection_info->FindListKey("info")->GetList().size()); + EXPECT_EQ( + l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION), + base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description"))); + + base::Value expected_info(base::Value::Type::LIST); + { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementDataLossPreventionName); + value.SetStringKey("permission", kManagementDataLossPreventionPermissions); + expected_info.GetList().push_back(std::move(value)); + } + { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementMalwareScanningName); + value.SetStringKey("permission", kManagementMalwareScanningPermissions); + expected_info.GetList().push_back(std::move(value)); + } + { + base::Value value(base::Value::Type::DICTIONARY); + value.SetStringKey("title", kManagementEnterpriseReportingName); + value.SetStringKey("permission", kManagementEnterpriseReportingPermissions); + expected_info.GetList().push_back(std::move(value)); + } + + EXPECT_EQ(expected_info, *threat_protection_info->FindListKey("info")); +} diff --git a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc index c4172e96053..e6899c4fcc4 100644 --- a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc +++ b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc @@ -75,7 +75,7 @@ content::WebUIDataSource* CreateWebRtcLogsUIHTMLSource() { }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("webrtc_logs.js", IDR_WEBRTC_LOGS_JS); source->SetDefaultResource(IDR_WEBRTC_LOGS_HTML); return source; diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc index 30482e50366..6ce8d49549e 100644 --- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc @@ -205,7 +205,7 @@ void MemoryInternalsDOMHandler::HandleRequestProcessList( const base::ListValue* args) { // This is called on the UI thread, the child process iterator must run on // the IO thread, while the render process iterator must run on the UI thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&MemoryInternalsDOMHandler::GetChildProcessesOnIOThread, weak_factory_.GetWeakPtr())); @@ -292,10 +292,9 @@ void MemoryInternalsDOMHandler::GetChildProcessesOnIOThread( } } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&MemoryInternalsDOMHandler::GetProfiledPids, dom_handler, - std::move(result))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&MemoryInternalsDOMHandler::GetProfiledPids, + dom_handler, std::move(result))); } void MemoryInternalsDOMHandler::GetProfiledPids( @@ -306,7 +305,7 @@ void MemoryInternalsDOMHandler::GetProfiledPids( // The supervisor hasn't started, so return an empty list. if (!supervisor->HasStarted()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&MemoryInternalsDOMHandler::ReturnProcessListOnUIThread, weak_factory_.GetWeakPtr(), std::move(children), diff --git a/chromium/chrome/browser/ui/webui/nacl_ui.cc b/chromium/chrome/browser/ui/webui/nacl_ui.cc index 89228f3b232..1fea3ce2ecc 100644 --- a/chromium/chrome/browser/ui/webui/nacl_ui.cc +++ b/chromium/chrome/browser/ui/webui/nacl_ui.cc @@ -63,7 +63,7 @@ content::WebUIDataSource* CreateNaClUIHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUINaClHost); source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS); source->AddResourcePath("about_nacl.js", IDR_ABOUT_NACL_JS); source->SetDefaultResource(IDR_ABOUT_NACL_HTML); @@ -364,8 +364,9 @@ void NaClDomHandler::MaybeRespondToPage() { if (!pnacl_path_validated_) { std::string* version_string = new std::string; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&CheckPathAndVersion, version_string), base::Bind(&NaClDomHandler::DidCheckPathAndVersion, weak_ptr_factory_.GetWeakPtr(), diff --git a/chromium/chrome/browser/ui/webui/net_export_ui.cc b/chromium/chrome/browser/ui/webui/net_export_ui.cc index c50cd8b8f77..081ef17bf0d 100644 --- a/chromium/chrome/browser/ui/webui/net_export_ui.cc +++ b/chromium/chrome/browser/ui/webui/net_export_ui.cc @@ -61,7 +61,7 @@ content::WebUIDataSource* CreateNetExportHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUINetExportHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath(net_log::kNetExportUIJS, IDR_NET_LOG_NET_EXPORT_JS); source->SetDefaultResource(IDR_NET_LOG_NET_EXPORT_HTML); return source; 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 5cc53f9c7d0..8c5bfd5d3fc 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 @@ -62,7 +62,7 @@ content::WebUIDataSource* CreateNetInternalsHTMLSource() { source->SetDefaultResource(IDR_NET_INTERNALS_INDEX_HTML); source->AddResourcePath("index.js", IDR_NET_INTERNALS_INDEX_JS); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); return source; } @@ -381,7 +381,7 @@ void NetInternalsMessageHandler::ImportONCFileToNSSDB( error += network_error; chromeos::onc::CertificateImporterImpl cert_importer( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), nssdb); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}), nssdb); auto certs = std::make_unique<chromeos::onc::OncParsedCertificates>(certificates); if (certs->has_error()) @@ -435,13 +435,13 @@ void NetInternalsMessageHandler::OnStoreDebugLogs(bool combined, if (file_manager::util::IsUnderNonNativeLocalPath(profile, path)) path = prefs->GetDefaultDownloadDirectoryForProfile(); base::FilePath policies_path = path.Append("policies.json"); - std::string json_policies = policy::GetAllPolicyValuesAsJSON( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, false /* with_device_data */, - true /* is_pretty_print */); - base::PostTaskWithTraitsAndReply( + std::string json_policies = + policy::DictionaryPolicyConversions() + .WithBrowserContext(web_ui()->GetWebContents()->GetBrowserContext()) + .ToJSON(); + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(DumpPolicyLogs, policies_path, json_policies), base::BindOnce(&NetInternalsMessageHandler::OnDumpPolicyLogsCompleted, diff --git a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc index 4b93e834575..eab07796c00 100644 --- a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc +++ b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc @@ -231,7 +231,7 @@ void NetInternalsTest::MessageHandler::DnsLookup( NetInternalsTest::NetInternalsTest() : test_server_started_(false) { - message_handler_.reset(new MessageHandler(this)); + message_handler_ = std::make_unique<MessageHandler>(this); } NetInternalsTest::~NetInternalsTest() { diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc index 9cca6cc57da..cd4c3f51c07 100644 --- a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc @@ -37,6 +37,9 @@ void NotificationsInternalsUIMessageHandler::HandleScheduleNotification( const base::ListValue* args) { CHECK_EQ(args->GetList().size(), 4u); notifications::ScheduleParams schedule_params; + schedule_params.deliver_time_start = base::Time::Now(); + schedule_params.deliver_time_end = + base::Time::Now() + base::TimeDelta::FromMinutes(5); notifications::NotificationData data; data.custom_data.emplace("url", args->GetList()[1].GetString()); data.title = base::UTF8ToUTF16(args->GetList()[2].GetString()); 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 eb64fce1c92..abeeef88687 100644 --- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc @@ -20,9 +20,9 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "chrome/browser/apps/launch_service/launch_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/extensions/bookmark_app_extension_util.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_ui_util.h" @@ -37,12 +37,12 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/extensions/extension_enable_flow.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/extensions/extension_basic_info.h" #include "chrome/browser/ui/webui/extensions/extension_icon_source.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" +#include "chrome/browser/web_applications/extensions/bookmark_app_finalizer_utils.h" #include "chrome/browser/web_applications/extensions/bookmark_app_util.h" #include "chrome/common/buildflags.h" #include "chrome/common/chrome_switches.h" @@ -488,8 +488,11 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { CHECK(launch_bucket >= 0 && launch_bucket < extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); + Profile* profile = extension_service_->profile(); + const Extension* extension = - extension_service_->GetExtensionById(extension_id, false); + extensions::ExtensionRegistry::Get(profile)->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); // Prompt the user to re-enable the application if disabled. if (!extension) { @@ -497,8 +500,6 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { return; } - Profile* profile = extension_service_->profile(); - WindowOpenDisposition disposition = args->GetSize() > 3 ? webui::GetDispositionFromClick(args, 3) : WindowOpenDisposition::CURRENT_TAB; @@ -526,11 +527,11 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { AppLaunchParams params( profile, extension_id, disposition == WindowOpenDisposition::NEW_WINDOW - ? extensions::LaunchContainer::kLaunchContainerWindow - : extensions::LaunchContainer::kLaunchContainerTab, - disposition, extensions::AppLaunchSource::kSourceNewTabPage); + ? apps::mojom::LaunchContainer::kLaunchContainerWindow + : apps::mojom::LaunchContainer::kLaunchContainerTab, + disposition, apps::mojom::AppLaunchSource::kSourceNewTabPage); params.override_url = override_url; - OpenApplication(params); + apps::LaunchService::Get(profile)->OpenApplication(params); } else { // To give a more "launchy" experience when using the NTP launcher, we close // it automatically. @@ -546,7 +547,8 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) { : WindowOpenDisposition::NEW_FOREGROUND_TAB, extensions::AppLaunchSource::kSourceNewTabPage); params.override_url = override_url; - WebContents* new_contents = OpenApplication(params); + WebContents* new_contents = + apps::LaunchService::Get(profile)->OpenApplication(params); // This will also destroy the handler, so do not perform any actions after. if (new_contents != old_contents && browser && @@ -563,7 +565,9 @@ void AppLauncherHandler::HandleSetLaunchType(const base::ListValue* args) { CHECK(args->GetDouble(1, &launch_type)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -615,7 +619,9 @@ void AppLauncherHandler::HandleCreateAppShortcut(const base::ListValue* args) { CHECK(args->GetString(0, &extension_id)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -631,7 +637,9 @@ void AppLauncherHandler::HandleInstallAppLocally(const base::ListValue* args) { CHECK(args->GetString(0, &extension_id)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -654,7 +662,9 @@ void AppLauncherHandler::HandleShowAppInfo(const base::ListValue* args) { CHECK(args->GetString(0, &extension_id)); const Extension* extension = - extension_service_->GetExtensionById(extension_id, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id, + extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) return; @@ -831,8 +841,8 @@ void AppLauncherHandler::PromptToEnableApp(const std::string& extension_id) { return; // Only one prompt at a time. extension_id_prompting_ = extension_id; - extension_enable_flow_.reset(new ExtensionEnableFlow( - Profile::FromWebUI(web_ui()), extension_id, this)); + extension_enable_flow_ = std::make_unique<ExtensionEnableFlow>( + Profile::FromWebUI(web_ui()), extension_id, this); extension_enable_flow_->StartForWebContents(web_ui()->GetWebContents()); } @@ -862,7 +872,9 @@ void AppLauncherHandler::ExtensionEnableFlowAborted(bool user_initiated) { // We record the histograms here because ExtensionUninstallCanceled is also // called when the extension uninstall dialog is canceled. const Extension* extension = - extension_service_->GetExtensionById(extension_id_prompting_, true); + extensions::ExtensionRegistry::Get(extension_service_->profile()) + ->GetExtensionById(extension_id_prompting_, + extensions::ExtensionRegistry::COMPATIBILITY); std::string histogram_name = user_initiated ? "ReEnableCancel" : "ReEnableAbort"; extensions::ExtensionService::RecordPermissionMessagesHistogram( diff --git a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc index 9102ea06af4..48f2a16a42c 100644 --- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc +++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc @@ -150,7 +150,7 @@ std::string NewTabUI::NewTabHTMLSource::GetSource() { void NewTabUI::NewTabHTMLSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); diff --git a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h index 61e2451c3db..01d668a40d7 100644 --- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h +++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h @@ -57,7 +57,7 @@ class NewTabUI : public content::WebUIController { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string&) override; bool ShouldReplaceExistingSource() override; diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc index 6b89090bf8a..fd62303ce45 100644 --- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui.cc @@ -22,7 +22,7 @@ OfflineInternalsUI::OfflineInternalsUI(content::WebUI* web_ui) content::WebUIDataSource::Create(chrome::kChromeUIOfflineInternalsHost); // Required resources. - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("offline_internals.css", IDR_OFFLINE_INTERNALS_CSS); html_source->AddResourcePath("offline_internals.js", 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 d8eadc545f5..b1ad92cf59c 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 @@ -82,8 +82,7 @@ std::string GetStringFromSavePageStatus() { OfflineInternalsUIMessageHandler::OfflineInternalsUIMessageHandler() : offline_page_model_(nullptr), request_coordinator_(nullptr), - prefetch_service_(nullptr), - weak_ptr_factory_(this) {} + prefetch_service_(nullptr) {} OfflineInternalsUIMessageHandler::~OfflineInternalsUIMessageHandler() {} diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h index 09a718680fa..01c291664fe 100644 --- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h +++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h @@ -134,7 +134,8 @@ class OfflineInternalsUIMessageHandler : public content::WebUIMessageHandler { offline_pages::PrefetchService* prefetch_service_; // Factory for creating references in callbacks. - base::WeakPtrFactory<OfflineInternalsUIMessageHandler> weak_ptr_factory_; + base::WeakPtrFactory<OfflineInternalsUIMessageHandler> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(OfflineInternalsUIMessageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom index de8253d461c..7ffa3971673 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom @@ -31,6 +31,7 @@ struct AutocompleteMatch { array<ACMatchClassification> contents_class; string description; array<ACMatchClassification> description_class; + bool swap_contents_and_description; string answer; string transition; bool allowed_to_be_default_match; @@ -59,12 +60,15 @@ struct OmniboxResponse { string type; string host; bool is_typed_host; + string input_text; array<AutocompleteMatch> combined_results; array<AutocompleteResultsForProvider> results_by_provider; }; interface OmniboxPageHandler { + // Registers the webui page. SetClientPage(OmniboxPage page); + // Prompts a autocopmlete controller to process an omnibox query. StartOmniboxQuery(string input_string, bool reset_autocomplete_controller, int32 cursor_position, @@ -76,8 +80,15 @@ interface OmniboxPageHandler { }; interface OmniboxPage { - handleNewAutocompleteResponse(OmniboxResponse response, - bool isPageController); - HandleNewAutocompleteQuery(bool isPageController, string input_text); + // Notifies the page of an omnibox response from a autocomplete + // controller. |is_page_controller| indicates wether the response + // originates from a query initiated from the page via + // |StartOmniboxQuery| or from the browser omnibox. + HandleNewAutocompleteResponse(OmniboxResponse response, + bool is_page_controller); + // Notifies the page a new omnibox query has begun. + HandleNewAutocompleteQuery(bool is_page_controller, string input_text); + // Asyncronously notifies the page of the image data URLs for previous omnibox + // responses. HandleAnswerImageData(string image_url, string image_data); }; diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc index 97def4ae86d..3c90ef1508e 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc @@ -174,6 +174,7 @@ struct TypeConverter<mojom::AutocompleteMatchPtr, AutocompleteMatch> { result->description_class = mojo::ConvertTo<std::vector<mojom::ACMatchClassificationPtr>>( input.description_class); + result->swap_contents_and_description = input.swap_contents_and_description; if (input.answer) { result->answer = SuggestionAnswerImageLineToString(input.answer->first_line()) + @@ -254,6 +255,7 @@ void OmniboxPageHandler::OnOmniboxResultChanged( if (!LookupIsTypedHost(host, &is_typed_host)) is_typed_host = false; response->is_typed_host = is_typed_host; + response->input_text = base::UTF16ToUTF8(input_.text()); { // Copy to an ACMatches to make conversion easier. Since this isn't @@ -295,7 +297,7 @@ void OmniboxPageHandler::OnOmniboxResultChanged( image_urls.push_back(result_by_provider.results[j]->image); } - page_->handleNewAutocompleteResponse(std::move(response), + page_->HandleNewAutocompleteResponse(std::move(response), controller == controller_.get()); // Fill in image data @@ -417,7 +419,7 @@ void OmniboxPageHandler::StartOmniboxQuery(const std::string& input_string, } void OmniboxPageHandler::ResetController() { - controller_.reset(new AutocompleteController( + controller_ = std::make_unique<AutocompleteController>( std::make_unique<ChromeAutocompleteProviderClient>(profile_), this, - AutocompleteClassifier::DefaultOmniboxProviders())); + AutocompleteClassifier::DefaultOmniboxProviders()); } diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc index af3ee72c3cd..4e95206d915 100644 --- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc +++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc @@ -9,6 +9,7 @@ #include "base/bind.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/omnibox/omnibox_page_handler.h" +#include "chrome/browser/ui/webui/version_handler.h" #include "chrome/browser/ui/webui/version_ui.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" @@ -16,14 +17,15 @@ #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_data_source.h" -OmniboxUI::OmniboxUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) { +OmniboxUI::OmniboxUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) { // Set up the chrome://omnibox/ source. content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOmniboxHost); // Expose version information to client because it is useful in output. VersionUI::AddVersionDetailStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("omnibox.css", IDR_OMNIBOX_CSS); source->AddResourcePath("omnibox_input.css", IDR_OMNIBOX_INPUT_CSS); @@ -43,6 +45,7 @@ OmniboxUI::OmniboxUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) { content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); AddHandlerToRegistry(base::BindRepeating(&OmniboxUI::BindOmniboxPageHandler, base::Unretained(this))); + web_ui->AddMessageHandler(std::make_unique<VersionHandler>()); } OmniboxUI::~OmniboxUI() {} diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc deleted file mode 100644 index 5e92515c354..00000000000 --- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc +++ /dev/null @@ -1,134 +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/password_manager_internals/password_manager_internals_ui.h" - -#include "base/values.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/url_constants.h" -#include "components/autofill/core/browser/logging/log_receiver.h" -#include "components/autofill/core/browser/logging/log_router.h" -#include "components/grit/components_resources.h" -#include "components/password_manager/content/browser/password_manager_log_router_factory.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/browser/web_ui_message_handler.h" -#include "net/base/escape.h" - -using autofill::LogRouter; -using password_manager::PasswordManagerLogRouterFactory; - -namespace { - -content::WebUIDataSource* CreatePasswordManagerInternalsHTMLSource() { - content::WebUIDataSource* source = content::WebUIDataSource::Create( - chrome::kChromeUIPasswordManagerInternalsHost); - source->AddResourcePath("autofill_and_password_manager_internals.js", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_JS); - source->AddResourcePath("autofill_and_password_manager_internals.css", - IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_CSS); - source->SetDefaultResource(IDR_AUTOFILL_AND_PASSWORD_MANAGER_INTERNALS_HTML); - return source; -} - -// chrome://password-manager-internals specific UI handler that takes care of -// subscribing to the autofill logging instance. -class PasswordManagerInternalsUIHandler : public content::WebUIMessageHandler, - public autofill::LogReceiver { - public: - PasswordManagerInternalsUIHandler() = default; - ~PasswordManagerInternalsUIHandler() override; - - private: - // content::WebUIMessageHandler: - void RegisterMessages() override; - - // Implements content::WebUIMessageHandler. - void OnJavascriptAllowed() override; - void OnJavascriptDisallowed() override; - - // LogReceiver implementation. - void LogEntry(const base::Value& entry) override; - - void StartSubscription(); - void EndSubscription(); - - // JavaScript call handler. - void OnLoaded(const base::ListValue* args); - - // Whether |this| is registered as a log receiver with the LogRouter. - bool registered_with_log_router_ = false; - - DISALLOW_COPY_AND_ASSIGN(PasswordManagerInternalsUIHandler); -}; - -PasswordManagerInternalsUIHandler::~PasswordManagerInternalsUIHandler() { - EndSubscription(); -} - -void PasswordManagerInternalsUIHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "loaded", - base::BindRepeating(&PasswordManagerInternalsUIHandler::OnLoaded, - base::Unretained(this))); -} - -void PasswordManagerInternalsUIHandler::OnJavascriptAllowed() { - StartSubscription(); -} - -void PasswordManagerInternalsUIHandler::OnJavascriptDisallowed() { - EndSubscription(); -} - -void PasswordManagerInternalsUIHandler::OnLoaded(const base::ListValue* args) { - AllowJavascript(); - CallJavascriptFunction("setUpPasswordManagerInternals"); - CallJavascriptFunction( - "notifyAboutIncognito", - base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile())); -} - -void PasswordManagerInternalsUIHandler::StartSubscription() { - LogRouter* log_router = PasswordManagerLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - if (!log_router) - return; - - registered_with_log_router_ = true; - - const auto& past_logs = log_router->RegisterReceiver(this); - for (const auto& entry : past_logs) - LogEntry(entry); -} - -void PasswordManagerInternalsUIHandler::EndSubscription() { - if (!registered_with_log_router_) - return; - registered_with_log_router_ = false; - LogRouter* log_router = PasswordManagerLogRouterFactory::GetForBrowserContext( - Profile::FromWebUI(web_ui())); - if (log_router) - log_router->UnregisterReceiver(this); -} - -void PasswordManagerInternalsUIHandler::LogEntry(const base::Value& entry) { - if (!registered_with_log_router_ || entry.is_none()) - return; - CallJavascriptFunction("addRawLog", entry); -} - -} // namespace - -PasswordManagerInternalsUI::PasswordManagerInternalsUI(content::WebUI* web_ui) - : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - content::WebUIDataSource::Add(profile, - CreatePasswordManagerInternalsHTMLSource()); - web_ui->AddMessageHandler( - std::make_unique<PasswordManagerInternalsUIHandler>()); -} - -PasswordManagerInternalsUI::~PasswordManagerInternalsUI() = default; diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc index 85b71b8f5ea..22075e1d920 100644 --- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc +++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc @@ -739,7 +739,7 @@ void PolicyUIHandler::AddCommonLocalizedStringsToSource( }; AddLocalizedStringsBulk(source, kStrings, base::size(kStrings)); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); } void PolicyUIHandler::RegisterMessages() { @@ -923,11 +923,10 @@ base::Value PolicyUIHandler::GetPolicyNames() const { } base::Value PolicyUIHandler::GetPolicyValues() const { - return policy::GetAllPolicyValuesAsArray( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, true /* convert_values */, - false /* with_device_data */, true /* is_pretty_print */, - true /* convert_types */); + return policy::ArrayPolicyConversions() + .WithBrowserContext(web_ui()->GetWebContents()->GetBrowserContext()) + .EnableConvertValues(true) + .ToValue(); } void PolicyUIHandler::SendStatus() { @@ -1030,11 +1029,10 @@ void DoWritePoliciesToJSONFile(const base::FilePath& path, void PolicyUIHandler::WritePoliciesToJSONFile( const base::FilePath& path) const { - constexpr bool is_pretty_print = true; - base::Value dict = policy::GetAllPolicyValuesAsDictionary( - web_ui()->GetWebContents()->GetBrowserContext(), - true /* with_user_policies */, false /* convert_values */, - false /* with_device_data */, is_pretty_print, true /* convert_types */); + base::Value dict = + policy::DictionaryPolicyConversions() + .WithBrowserContext(web_ui()->GetWebContents()->GetBrowserContext()) + .ToValue(); base::Value chrome_metadata(base::Value::Type::DICTIONARY); @@ -1085,12 +1083,11 @@ void PolicyUIHandler::WritePoliciesToJSONFile( std::string json_policies; base::JSONWriter::WriteWithOptions( - dict, (is_pretty_print ? base::JSONWriter::OPTIONS_PRETTY_PRINT : 0), - &json_policies); + dict, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json_policies); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(&DoWritePoliciesToJSONFile, path, json_policies)); } diff --git a/chromium/chrome/browser/ui/webui/prefs_internals_source.cc b/chromium/chrome/browser/ui/webui/prefs_internals_source.cc index 382f02f3391..152af756c8d 100644 --- a/chromium/chrome/browser/ui/webui/prefs_internals_source.cc +++ b/chromium/chrome/browser/ui/webui/prefs_internals_source.cc @@ -29,7 +29,7 @@ std::string PrefsInternalsSource::GetMimeType(const std::string& path) { void PrefsInternalsSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string json; diff --git a/chromium/chrome/browser/ui/webui/prefs_internals_source.h b/chromium/chrome/browser/ui/webui/prefs_internals_source.h index d20af558b90..922302643d7 100644 --- a/chromium/chrome/browser/ui/webui/prefs_internals_source.h +++ b/chromium/chrome/browser/ui/webui/prefs_internals_source.h @@ -21,7 +21,7 @@ class PrefsInternalsSource : public content::URLDataSource { std::string GetMimeType(const std::string& path) override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; private: 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 13276fa5968..f1efaf51d10 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 @@ -35,6 +35,7 @@ #include "extensions/browser/api/usb/usb_device_manager.h" #include "extensions/common/extension.h" #include "extensions/common/value_builder.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "printing/pdf_render_settings.h" #include "printing/print_job_constants.h" #include "printing/pwg_raster_settings.h" @@ -507,10 +508,10 @@ class ExtensionPrinterHandlerTest : public testing::Test { std::move(pwg_raster_converter)); // Set fake USB device manager for extensions::UsbDeviceManager. - device::mojom::UsbDeviceManagerPtr usb_manager_ptr; - fake_usb_manager_.AddBinding(mojo::MakeRequest(&usb_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager; + fake_usb_manager_.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver()); extensions::UsbDeviceManager::Get(env_.profile()) - ->SetDeviceManagerForTesting(std::move(usb_manager_ptr)); + ->SetDeviceManagerForTesting(std::move(usb_manager)); base::RunLoop().RunUntilIdle(); } diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc index 9534da45d8d..9b926a8b629 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc @@ -19,7 +19,6 @@ #include "chrome/browser/chromeos/printing/cups_print_job_manager_factory.h" #include "chrome/browser/chromeos/printing/cups_printers_manager.h" #include "chrome/browser/chromeos/printing/cups_printers_manager_factory.h" -#include "chrome/browser/chromeos/printing/ppd_provider_factory.h" #include "chrome/browser/chromeos/printing/printer_configurer.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" @@ -27,7 +26,6 @@ #include "chrome/common/pref_names.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" -#include "chromeos/printing/ppd_provider.h" #include "chromeos/printing/printer_configuration.h" #include "components/prefs/pref_service.h" #include "components/printing/browser/printer_capabilities.h" @@ -83,8 +81,9 @@ void FetchCapabilities(const chromeos::Printer& printer, printer.GetProtocol() == chromeos::Printer::kIpps; // USER_VISIBLE because the result is displayed in the print preview dialog. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&GetSettingsOnBlockingPool, printer.id(), basic_info, PrinterSemanticCapsAndDefaults::Papers(), has_secure_protocol, nullptr), @@ -101,8 +100,7 @@ LocalPrinterHandlerChromeos::LocalPrinterHandlerChromeos( : profile_(profile), preview_web_contents_(preview_web_contents), printers_manager_(printers_manager), - printer_configurer_(std::move(printer_configurer)), - weak_factory_(this) { + printer_configurer_(std::move(printer_configurer)) { // Construct the CupsPrintJobManager to listen for printing events. chromeos::CupsPrintJobManagerFactory::GetForBrowserContext(profile); } @@ -147,8 +145,8 @@ void LocalPrinterHandlerChromeos::GetDefaultPrinter(DefaultPrinterCallback cb) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // TODO(crbug.com/660898): Add default printers to ChromeOS. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(cb), "")); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(cb), "")); } void LocalPrinterHandlerChromeos::StartGetPrinters( @@ -158,11 +156,8 @@ void LocalPrinterHandlerChromeos::StartGetPrinters( // thread. DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // TODO(crbug.com/971823): Re-enable printing from OOBE. - if (chromeos::ProfileHelper::IsSigninProfile(profile_)) { - std::move(done_callback).Run(); - return; - } + // Printing is not allowed during OOBE. + CHECK(!chromeos::ProfileHelper::IsSigninProfile(profile_)); PrinterList printer_list; AddPrintersToList(printers_manager_->GetPrinters(PrinterClass::kSaved), @@ -185,8 +180,8 @@ void LocalPrinterHandlerChromeos::StartGetCapability( printers_manager_->GetPrinter(printer_name); if (!printer) { // If the printer was removed, the lookup will fail. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(cb), base::Value())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(cb), base::Value())); return; } @@ -215,7 +210,9 @@ void LocalPrinterHandlerChromeos::OnPrinterInstalled( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (result == chromeos::PrinterSetupResult::kSuccess) { - printers_manager_->PrinterInstalled(printer, true /*is_automatic*/); + printers_manager_->PrinterInstalled( + printer, /*is_automatic=*/true, + chromeos::PrinterSetupSource::kPrintPreview); } HandlePrinterSetup(printer, std::move(cb), printer.IsUsbProtocol(), result); diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h index 7136f4e03a9..609eafc64f0 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h @@ -77,9 +77,8 @@ class LocalPrinterHandlerChromeos : public PrinterHandler { Profile* const profile_; content::WebContents* const preview_web_contents_; chromeos::CupsPrintersManager* printers_manager_; - scoped_refptr<chromeos::PpdProvider> ppd_provider_; std::unique_ptr<chromeos::PrinterConfigurer> printer_configurer_; - base::WeakPtrFactory<LocalPrinterHandlerChromeos> weak_factory_; + base::WeakPtrFactory<LocalPrinterHandlerChromeos> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LocalPrinterHandlerChromeos); }; diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc index e968ba221e5..756f3b374ea 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos_unittest.cc @@ -21,7 +21,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/printing/browser/printer_capabilities.h" #include "components/sync_preferences/testing_pref_service_syncable.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "printing/backend/print_backend.h" #include "printing/backend/printing_restrictions.h" #include "printing/backend/test_print_backend.h" @@ -140,7 +140,7 @@ class LocalPrinterHandlerChromeosTest : public testing::Test { protected: // Must outlive |profile_|. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; // Must outlive |printers_manager_|. TestingProfile profile_; scoped_refptr<TestPrintBackend> test_backend_; @@ -230,7 +230,7 @@ TEST_F(LocalPrinterHandlerChromeosTest, StartGetCapabilityValidPrinter) { local_printer_handler_->StartGetCapability( "printer1", base::BindOnce(&RecordGetCapability, &fetched_caps)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_TRUE(fetched_caps); base::DictionaryValue* dict; @@ -257,7 +257,7 @@ TEST_F(LocalPrinterHandlerChromeosTest, StartGetCapabilityPrinterNotInstalled) { local_printer_handler_->StartGetCapability( "printer1", base::BindOnce(&RecordGetCapability, &fetched_caps)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_TRUE(fetched_caps); base::DictionaryValue* dict; @@ -273,7 +273,7 @@ TEST_F(LocalPrinterHandlerChromeosTest, StartGetCapabilityInvalidPrinter) { local_printer_handler_->StartGetCapability( "invalid printer", base::BindOnce(&RecordGetCapability, &fetched_caps)); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_TRUE(fetched_caps); EXPECT_TRUE(fetched_caps->is_none()); diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc index 0074a2f8b68..84ecb34377b 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc @@ -31,14 +31,17 @@ namespace { scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. static constexpr base::TaskTraits kTraits = { - base::MayBlock(), base::TaskPriority::USER_VISIBLE}; + base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}; -#if defined(OS_WIN) - // Windows drivers are likely not thread-safe. - return base::CreateSingleThreadTaskRunnerWithTraits(kTraits); -#elif defined(USE_CUPS) +#if defined(USE_CUPS) // CUPS is thread safe. - return base::CreateTaskRunnerWithTraits(kTraits); + return base::CreateTaskRunner(kTraits); +#elif defined(OS_WIN) + // Windows drivers are likely not thread-safe. + return base::CreateSingleThreadTaskRunner(kTraits); +#else + // Be conservative on unsupported platforms. + return base::CreateSingleThreadTaskRunner(kTraits); #endif } @@ -67,15 +70,12 @@ base::Value FetchCapabilitiesAsync(const std::string& device_name) { VLOG(1) << "Get printer capabilities start for " << device_name; - if (!print_backend->IsValidPrinter(device_name)) { + PrinterBasicInfo basic_info; + if (!print_backend->GetPrinterBasicInfo(device_name, &basic_info)) { LOG(WARNING) << "Invalid printer " << device_name; return base::Value(); } - PrinterBasicInfo basic_info; - if (!print_backend->GetPrinterBasicInfo(device_name, &basic_info)) - return base::Value(); - return GetSettingsOnBlockingPool(device_name, basic_info, additional_papers, /* has_secure_protocol */ false, print_backend); diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc index 6147b07f6da..00cf10991ed 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc @@ -312,8 +312,9 @@ void PdfPrinterHandler::SelectFile(const base::FilePath& default_filename, // Handle the no prompting case. Like the dialog prompt, this function // returns and eventually FileSelected() gets called. if (!prompt_user) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&base::GetUniquePath, path.Append(default_filename)), base::BindOnce(&PdfPrinterHandler::OnGotUniqueFileName, weak_ptr_factory_.GetWeakPtr())); @@ -330,16 +331,18 @@ void PdfPrinterHandler::SelectFile(const base::FilePath& default_filename, // Get default download directory. This will be used as a fallback if the // save directory does not exist. base::FilePath default_path = download_prefs->DownloadPath(); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&SelectSaveDirectory, path, default_path), base::BindOnce(&PdfPrinterHandler::OnDirectorySelected, weak_ptr_factory_.GetWeakPtr(), default_filename)); } void PdfPrinterHandler::PostPrintToPdfTask() { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&PrintToPdfCallback, print_data_, print_to_pdf_path_, std::move(pdf_file_saved_closure_))); print_to_pdf_path_.clear(); 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 e3d7c5f14cd..977fa0091ff 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 @@ -79,9 +79,11 @@ #include "third_party/icu/source/i18n/unicode/ulocdata.h" #if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/account_manager/account_manager_util.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" +#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h" #include "chromeos/printing/printer_configuration.h" #include "services/identity/public/cpp/scope_set.h" #endif @@ -221,12 +223,12 @@ const char kIsInKioskAutoPrintMode[] = "isInKioskAutoPrintMode"; const char kIsInAppKioskMode[] = "isInAppKioskMode"; // Name of a dictionary field holding the UI locale. const char kUiLocale[] = "uiLocale"; -// Name of a dictionary field holding the thousands delimeter according to the +// Name of a dictionary field holding the thousands delimiter according to the // locale. -const char kThousandsDelimeter[] = "thousandsDelimeter"; -// Name of a dictionary field holding the decimal delimeter according to the +const char kThousandsDelimiter[] = "thousandsDelimiter"; +// Name of a dictionary field holding the decimal delimiter according to the // locale. -const char kDecimalDelimeter[] = "decimalDelimeter"; +const char kDecimalDelimiter[] = "decimalDelimiter"; // Name of a dictionary field holding the measurement system according to the // locale. const char kUnitType[] = "unitType"; @@ -830,7 +832,25 @@ void PrintPreviewHandler::HandleSignin(const base::ListValue* args) { bool add_account = false; CHECK(args->GetBoolean(0, &add_account)); - chrome::ScopedTabbedBrowserDisplayer displayer(Profile::FromWebUI(web_ui())); + Profile* profile = Profile::FromWebUI(web_ui()); + DCHECK(profile); + +#if defined(OS_CHROMEOS) + if (chromeos::IsAccountManagerAvailable(profile)) { + // Chrome OS Account Manager is enabled on this Profile and hence, all + // account management flows will go through native UIs and not through a + // tabbed browser window. + if (add_account) { + chromeos::InlineLoginHandlerDialogChromeOS::Show(); + } else { + chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( + profile, chrome::kAccountManagerSubPage); + } + return; + } +#endif + + chrome::ScopedTabbedBrowserDisplayer displayer(profile); print_dialog_cloud::CreateCloudPrintSigninTab( displayer.browser(), add_account, base::BindOnce(&PrintPreviewHandler::OnSignInTabClosed, @@ -894,7 +914,7 @@ void PrintPreviewHandler::HandleClosePreviewDialog( void PrintPreviewHandler::HandleOpenPrinterSettings( const base::ListValue* args) { chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( - Profile::FromWebUI(web_ui()), chrome::kPrintingSettingsSubPage); + Profile::FromWebUI(web_ui()), chrome::kNativePrintingSettingsSubPage); } #endif @@ -913,8 +933,15 @@ void PrintPreviewHandler::GetLocaleInformation(base::Value* settings) { // Getting the number formatting based on the locale and writing to // dictionary. base::string16 number_format = base::FormatDouble(123456.78, 2); - settings->SetStringKey(kDecimalDelimeter, number_format.substr(7, 1)); - settings->SetStringKey(kThousandsDelimeter, number_format.substr(3, 1)); + size_t thousands_pos = number_format.find('3') + 1; + base::string16 thousands_delimiter = number_format.substr(thousands_pos, 1); + if (number_format[thousands_pos] == '4') + thousands_delimiter.clear(); + size_t decimal_pos = number_format.find('6') + 1; + DCHECK_NE(number_format[decimal_pos], '7'); + base::string16 decimal_delimiter = number_format.substr(decimal_pos, 1); + settings->SetStringKey(kDecimalDelimiter, decimal_delimiter); + settings->SetStringKey(kThousandsDelimiter, thousands_delimiter); settings->SetIntKey(kUnitType, system); } 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 305ba9357f5..bdccac1a8a4 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 @@ -144,11 +144,6 @@ class PrintPreviewHandler : public content::WebUIMessageHandler, FRIEND_TEST_ALL_PREFIXES(PrintPreviewPdfGeneratedBrowserTest, MANUAL_DummyTest); friend class PrintPreviewHandlerTest; - FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, InitialSettingsSimple); - FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, - InitialSettingsEnableHeaderFooter); - FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, - InitialSettingsDisableHeaderFooter); FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, GetPrinters); FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, GetPrinterCapabilities); FRIEND_TEST_ALL_PREFIXES(PrintPreviewHandlerTest, Print); diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc index 004dec28a15..e56a96a4703 100644 --- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc @@ -10,6 +10,7 @@ #include "base/base64.h" #include "base/containers/flat_set.h" +#include "base/i18n/number_formatting.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/memory/ref_counted_memory.h" @@ -25,6 +26,7 @@ #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" #include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/common/pref_names.h" +#include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" #include "components/printing/common/print_messages.h" @@ -32,8 +34,8 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_controller.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_render_process_host.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/test_web_ui.h" #include "ipc/ipc_test_sink.h" @@ -284,18 +286,30 @@ class PrintPreviewHandlerTest : public testing::Test { return std::make_unique<TestPrinterHandler>(printers); } - void Initialize() { - // Set locale since the delimeters we check in VerifyInitialSettings() - // depend on it. - base::test::ScopedRestoreICUDefaultLocale scoped_locale("en"); + void Initialize() { InitializeWithLocale("en"); } + void InitializeWithLocale(const std::string& locale) { // Sending this message will enable javascript, so it must always be called // before any other messages are sent. base::Value args(base::Value::Type::LIST); args.GetList().emplace_back("test-callback-id-0"); std::unique_ptr<base::ListValue> list_args = base::ListValue::From(base::Value::ToUniquePtrValue(std::move(args))); - handler()->HandleGetInitialSettings(list_args.get()); + + auto* browser_process = TestingBrowserProcess::GetGlobal(); + std::string original_locale = browser_process->GetApplicationLocale(); + { + // Set locale since the delimiters checked in VerifyInitialSettings() + // depend on it. This has to be done in several ways to make various + // locale code sync up correctly. + browser_process->SetApplicationLocale(locale); + base::test::ScopedRestoreICUDefaultLocale scoped_locale(locale); + base::testing::ResetFormatters(); + handler()->HandleGetInitialSettings(list_args.get()); + } + // Reset again now that |scoped_locale| has been destroyed. + browser_process->SetApplicationLocale(original_locale); + base::testing::ResetFormatters(); // In response to get initial settings, the initial settings are sent back. ASSERT_EQ(1u, web_ui()->call_data().size()); @@ -321,18 +335,33 @@ class PrintPreviewHandlerTest : public testing::Test { EXPECT_EQ(expect_success, success); } + void ValidateInitialSettings(const content::TestWebUI::CallData& data, + const std::string& default_printer_name, + const std::string& initiator_title, + base::Optional<bool> expected_header_footer) { + ValidateInitialSettingsForLocale(data, default_printer_name, + initiator_title, "en", ",", ".", + expected_header_footer); + } + // Validates the initial settings structure in the response matches the // print_preview.NativeInitialSettings type in // chrome/browser/resources/print_preview/native_layer.js. Checks that: // - |default_printer_name| is the printer name returned // - |initiator_title| is the initiator title returned // - |expected_header_footer| is the header/footer state returned, if any - // Also validates that delimeters are correct for "en" locale (set in - // Initialize()). Assumes "test-callback-id-0" was used as the callback id. - void ValidateInitialSettings(const content::TestWebUI::CallData& data, - const std::string& default_printer_name, - const std::string& initiator_title, - base::Optional<bool> expected_header_footer) { + // Also validates that delimiters are correct for |locale| (set in + // InitializeWithLocale()) with the associated |thousands_delimiter| and + // |decimal_delimiter|. + // Assumes "test-callback-id-0" was used as the callback id. + void ValidateInitialSettingsForLocale( + const content::TestWebUI::CallData& data, + const std::string& default_printer_name, + const std::string& initiator_title, + const std::string& locale, + const std::string& thousands_delimiter, + const std::string& decimal_delimiter, + base::Optional<bool> expected_header_footer) { CheckWebUIResponse(data, "test-callback-id-0", true); const base::Value* settings = data.arg3(); ASSERT_TRUE(settings->FindKeyOfType("isInKioskAutoPrintMode", @@ -340,18 +369,17 @@ class PrintPreviewHandlerTest : public testing::Test { ASSERT_TRUE(settings->FindKeyOfType("isInAppKioskMode", base::Value::Type::BOOLEAN)); - const base::Value* locale = - settings->FindKeyOfType("uiLocale", base::Value::Type::STRING); - ASSERT_TRUE(locale); - EXPECT_EQ("en", locale->GetString()); - const base::Value* thousands_delimeter = settings->FindKeyOfType( - "thousandsDelimeter", base::Value::Type::STRING); - ASSERT_TRUE(thousands_delimeter); - EXPECT_EQ(",", thousands_delimeter->GetString()); - const base::Value* decimal_delimeter = - settings->FindKeyOfType("decimalDelimeter", base::Value::Type::STRING); - ASSERT_TRUE(decimal_delimeter); - EXPECT_EQ(".", decimal_delimeter->GetString()); + const std::string* actual_locale = settings->FindStringKey("uiLocale"); + ASSERT_TRUE(actual_locale); + EXPECT_EQ(locale, *actual_locale); + const std::string* actual_thousands_delimiter = + settings->FindStringKey("thousandsDelimiter"); + ASSERT_TRUE(actual_thousands_delimiter); + EXPECT_EQ(thousands_delimiter, *actual_thousands_delimiter); + const std::string* actual_decimal_delimiter = + settings->FindStringKey("decimalDelimiter"); + ASSERT_TRUE(actual_decimal_delimiter); + EXPECT_EQ(decimal_delimiter, *actual_decimal_delimiter); ASSERT_TRUE( settings->FindKeyOfType("unitType", base::Value::Type::INTEGER)); @@ -416,7 +444,7 @@ class PrintPreviewHandlerTest : public testing::Test { std::vector<PrinterInfo>& printers() { return printers_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<TestingProfile> profile_; std::unique_ptr<content::TestWebUI> web_ui_; content::RenderViewHostTestEnabler rvh_test_enabler_; @@ -437,6 +465,24 @@ TEST_F(PrintPreviewHandlerTest, InitialSettingsSimple) { kDummyInitiatorName, {}); } +TEST_F(PrintPreviewHandlerTest, InitialSettingsHiLocale) { + InitializeWithLocale("hi"); + + // Verify initial settings were sent for Hindi. + ValidateInitialSettingsForLocale(*web_ui()->call_data().back(), + kDummyPrinterName, kDummyInitiatorName, "hi", + ",", ".", {}); +} + +TEST_F(PrintPreviewHandlerTest, InitialSettingsRuLocale) { + InitializeWithLocale("ru"); + + // Verify initial settings were sent for Russian. + ValidateInitialSettingsForLocale(*web_ui()->call_data().back(), + kDummyPrinterName, kDummyInitiatorName, "ru", + "\xC2\xA0", ",", {}); +} + TEST_F(PrintPreviewHandlerTest, InitialSettingsEnableHeaderFooter) { // Set a pref that should take priority over StickySettings. prefs()->SetBoolean(prefs::kPrintHeaderFooter, true); 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 2dfc91469b8..a855e2f1d97 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 @@ -345,10 +345,6 @@ void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { {"pdf/browser_api.js", IDR_PDF_BROWSER_API_JS}, {"pdf/elements/icons.html", IDR_PDF_ICONS_HTML}, {"pdf/elements/shared-vars.html", IDR_PDF_SHARED_VARS_HTML}, - {"pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.html", - IDR_PDF_VIEWER_BOOKMARKS_CONTENT_HTML}, - {"pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js", - IDR_PDF_VIEWER_BOOKMARKS_CONTENT_JS}, {"pdf/elements/viewer-bookmark/viewer-bookmark.html", IDR_PDF_VIEWER_BOOKMARK_HTML}, {"pdf/elements/viewer-bookmark/viewer-bookmark.js", @@ -412,7 +408,6 @@ void SetupPrintPreviewPlugin(content::WebUIDataSource* source) { {"pdf/pdf_scripting_api.js", IDR_PDF_PDF_SCRIPTING_API_JS}, {"pdf/pdf_viewer.js", IDR_PDF_PDF_VIEWER_JS}, {"pdf/toolbar_manager.js", IDR_PDF_TOOLBAR_MANAGER_JS}, - {"pdf/viewport_interface.js", IDR_PDF_VIEWPORT_INTERFACE_JS}, {"pdf/viewport.js", IDR_PDF_VIEWPORT_JS}, {"pdf/viewport_scroller.js", IDR_PDF_VIEWPORT_SCROLLER_JS}, {"pdf/zoom_manager.js", IDR_PDF_ZOOM_MANAGER_JS}, @@ -432,7 +427,7 @@ content::WebUIDataSource* CreatePrintPreviewUISource(Profile* profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIPrintHost); AddPrintPreviewStrings(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #if BUILDFLAG(OPTIMIZE_WEBUI) source->AddResourcePath("crisper.js", IDR_PRINT_PREVIEW_CRISPER_JS); source->SetDefaultResource(IDR_PRINT_PREVIEW_VULCANIZED_HTML); diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc index fd564930748..daefcc3f6ca 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc @@ -27,7 +27,7 @@ void QuotaInternalsProxy::RequestInfo( scoped_refptr<storage::QuotaManager> quota_manager) { DCHECK(quota_manager.get()); if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&QuotaInternalsProxy::RequestInfo, this, quota_manager)); return; @@ -69,18 +69,17 @@ void QuotaInternalsProxy::RequestInfo( QuotaInternalsProxy::~QuotaInternalsProxy() {} -#define RELAY_TO_HANDLER(func, arg_t) \ - void QuotaInternalsProxy::func(arg_t arg) { \ - if (!handler_) \ - return; \ - if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { \ - base::PostTaskWithTraits( \ - FROM_HERE, {BrowserThread::UI}, \ - base::BindOnce(&QuotaInternalsProxy::func, this, arg)); \ - return; \ - } \ - \ - handler_->func(arg); \ +#define RELAY_TO_HANDLER(func, arg_t) \ + void QuotaInternalsProxy::func(arg_t arg) { \ + if (!handler_) \ + return; \ + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { \ + base::PostTask(FROM_HERE, {BrowserThread::UI}, \ + base::BindOnce(&QuotaInternalsProxy::func, this, arg)); \ + return; \ + } \ + \ + handler_->func(arg); \ } RELAY_TO_HANDLER(ReportAvailableSpace, int64_t) diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc index 61b1ba55e9e..c119a8f17f8 100644 --- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_ui.cc @@ -23,7 +23,7 @@ content::WebUIDataSource* CreateQuotaInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIQuotaInternalsHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath( "event_handler.js", IDR_QUOTA_INTERNALS_EVENT_HANDLER_JS); source->AddResourcePath( diff --git a/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn b/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn index bf4768bf16e..46529aa8ccb 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn @@ -8,7 +8,4 @@ mojom("mojo_bindings") { sources = [ "reset_password.mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/reset_password/OWNERS b/chromium/chrome/browser/ui/webui/reset_password/OWNERS index 310210ec249..c30ee078ee0 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/OWNERS +++ b/chromium/chrome/browser/ui/webui/reset_password/OWNERS @@ -1,6 +1,7 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS +drubery@chromium.org nparker@chromium.org vakh@chromium.org diff --git a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc index 739a6f401c3..b4b7b46f2c6 100644 --- a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc +++ b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc @@ -10,9 +10,10 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "components/safe_browsing/password_protection/metrics_util.h" #include "components/safe_browsing/password_protection/password_protection_service.h" +#include "components/safe_browsing/proto/csd.pb.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/url_formatter.h" #include "components/user_prefs/user_prefs.h" @@ -23,6 +24,9 @@ #include "mojo/public/cpp/bindings/binding.h" #include "ui/base/l10n/l10n_util.h" +using safe_browsing::LoginReputationClientResponse; +using safe_browsing::RequestOutcome; + namespace { constexpr char kStringTypeUMAName[] = "PasswordProtection.InterstitialString"; @@ -42,10 +46,8 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler { public: ResetPasswordHandlerImpl( content::WebContents* web_contents, - PasswordType password_type, mojo::InterfaceRequest<mojom::ResetPasswordHandler> request) : web_contents_(web_contents), - password_type_(password_type), binding_(this, std::move(request)) { DCHECK(web_contents); } @@ -59,15 +61,18 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler { safe_browsing::ChromePasswordProtectionService* service = safe_browsing:: ChromePasswordProtectionService::GetPasswordProtectionService(profile); if (service) { - service->OnUserAction(web_contents_, password_type_, - safe_browsing::WarningUIType::INTERSTITIAL, - safe_browsing::WarningAction::CHANGE_PASSWORD); + service->OnUserAction( + web_contents_, + service->reused_password_account_type_for_last_shown_warning(), + RequestOutcome::UNKNOWN, + LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED, + /*verdict_token=*/"", safe_browsing::WarningUIType::INTERSTITIAL, + safe_browsing::WarningAction::CHANGE_PASSWORD); } } private: content::WebContents* web_contents_; - PasswordType password_type_; mojo::Binding<mojom::ResetPasswordHandler> binding_; DISALLOW_COPY_AND_ASSIGN(ResetPasswordHandlerImpl); @@ -123,14 +128,14 @@ ResetPasswordUI::~ResetPasswordUI() {} void ResetPasswordUI::BindResetPasswordHandler( mojom::ResetPasswordHandlerRequest request) { ui_handler_ = std::make_unique<ResetPasswordHandlerImpl>( - web_ui()->GetWebContents(), password_type_, std::move(request)); + web_ui()->GetWebContents(), std::move(request)); } base::DictionaryValue ResetPasswordUI::PopulateStrings() const { - std::string org_name = - safe_browsing::ChromePasswordProtectionService:: - GetPasswordProtectionService(Profile::FromWebUI(web_ui())) - ->GetOrganizationName(password_type_); + auto* service = safe_browsing::ChromePasswordProtectionService:: + GetPasswordProtectionService(Profile::FromWebUI(web_ui())); + std::string org_name = service->GetOrganizationName( + service->reused_password_account_type_for_last_shown_warning()); bool known_password_type = password_type_ != PasswordType::PASSWORD_TYPE_UNKNOWN; diff --git a/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc b/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc index 200baa9c15f..e09f9d4a1e9 100644 --- a/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sandbox_internals_ui.cc @@ -69,7 +69,7 @@ content::WebUIDataSource* CreateDataSource() { #if defined(OS_LINUX) SetSandboxStatusData(source); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); #endif return source; diff --git a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_browsertest_win.cc b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_browsertest_win.cc deleted file mode 100644 index ec06882aeab..00000000000 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_browsertest_win.cc +++ /dev/null @@ -1,59 +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/set_as_default_browser_ui_win.h" - -#include "base/command_line.h" -#include "base/win/windows_version.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "ui/views/widget/widget.h" - -namespace { - -bool IsBrowserVisible(Browser* browser) { - return views::Widget::GetWidgetForNativeWindow( - browser->window()->GetNativeWindow()) - ->IsVisible(); -} - -} // namespace - -using SetAsDefaultBrowserUIBrowserTestWithoutFirstRun = InProcessBrowserTest; - -class SetAsDefaultBrowserUIBrowserTestWithFirstRun - : public InProcessBrowserTest { - public: - void SetUpCommandLine(base::CommandLine* command_line) override { - command_line->AppendSwitch(switches::kForceFirstRun); - } - - protected: - void TearDownInProcessBrowserTestFixture() override { - ASSERT_FALSE(SetAsDefaultBrowserUI::GetDialogWidgetForTesting()); - } -}; - -IN_PROC_BROWSER_TEST_F(SetAsDefaultBrowserUIBrowserTestWithFirstRun, Test) { - // Windows 8 only test case. - if (base::win::GetVersion() != base::win::Version::WIN8 && - base::win::GetVersion() != base::win::Version::WIN8_1) { - return; - } - ASSERT_FALSE(IsBrowserVisible(browser())); - views::Widget* dialog_widget = - SetAsDefaultBrowserUI::GetDialogWidgetForTesting(); - ASSERT_TRUE(dialog_widget); - ASSERT_TRUE(dialog_widget->IsVisible()); - dialog_widget->CloseNow(); - ASSERT_TRUE(IsBrowserVisible(browser())); -} - -IN_PROC_BROWSER_TEST_F(SetAsDefaultBrowserUIBrowserTestWithoutFirstRun, - TestWithoutFirstRun) { - ASSERT_TRUE(IsBrowserVisible(browser())); - EXPECT_EQ(nullptr, SetAsDefaultBrowserUI::GetDialogWidgetForTesting()); -} 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 deleted file mode 100644 index c72f92b4a6c..00000000000 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.cc +++ /dev/null @@ -1,396 +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/set_as_default_browser_ui_win.h" - -#include <string> -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/metrics/histogram_macros.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/shell_integration.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_dialogs.h" -#include "chrome/browser/ui/browser_finder.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_list_observer.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/chrome_pages.h" -#include "chrome/browser/ui/singleton_tabs.h" -#include "chrome/browser/ui/startup/default_browser_prompt.h" -#include "chrome/browser/ui/sync/sync_promo_ui.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/webui/localized_string.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/grit/locale_settings.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_delegate.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/browser/web_ui_message_handler.h" -#include "ui/base/l10n/l10n_font_util.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/font.h" -#include "ui/views/widget/widget.h" -#include "ui/web_dialogs/web_dialog_delegate.h" - -using content::BrowserThread; -using content::WebContents; -using content::WebUIMessageHandler; - -namespace { - -const char kSetAsDefaultBrowserHistogram[] = "DefaultBrowser.InteractionResult"; - -// 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 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 -}; - -content::WebUIDataSource* CreateSetAsDefaultBrowserUIHTMLSource() { - content::WebUIDataSource* data_source = - content::WebUIDataSource::Create(chrome::kChromeUIMetroFlowHost); - - static constexpr LocalizedString kStrings[] = { - {"pageTitle", IDS_METRO_FLOW_TAB_TITLE}, - {"flowTitle", IDS_METRO_FLOW_TITLE_SHORT}, - {"flowDescription", IDS_METRO_FLOW_DESCRIPTION}, - {"flowNext", IDS_METRO_FLOW_SET_DEFAULT}, - {"chromeLogoString", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT}, - }; - AddLocalizedStringsBulk(data_source, kStrings, base::size(kStrings)); - - data_source->SetJsonPath("strings.js"); - data_source->AddResourcePath("set_as_default_browser.js", - IDR_SET_AS_DEFAULT_BROWSER_JS); - data_source->SetDefaultResource(IDR_SET_AS_DEFAULT_BROWSER_HTML); - return data_source; -} - -// A simple class serving as a delegate for passing down the result of the -// interaction. -class ResponseDelegate { - public: - virtual void SetDialogInteractionResult(MakeChromeDefaultResult result) = 0; - - protected: - virtual ~ResponseDelegate() {} -}; - -// Event handler for SetAsDefaultBrowserUI. Capable of setting Chrome as the -// default browser on button click, closing itself and triggering Chrome -// restart. -class SetAsDefaultBrowserHandler : public WebUIMessageHandler { - public: - explicit SetAsDefaultBrowserHandler( - const base::WeakPtr<ResponseDelegate>& response_delegate); - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - private: - // Handler for the 'Next' (or 'make Chrome the Metro browser') button. - void HandleLaunchSetDefaultBrowserFlow(const base::ListValue* args); - - // Close this web ui. - void ConcludeInteraction(MakeChromeDefaultResult interaction_result); - - void OnDefaultBrowserWorkerFinished( - shell_integration::DefaultWebClientState state); - - // 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. - scoped_refptr<shell_integration::DefaultBrowserWorker> - default_browser_worker_; - base::WeakPtr<ResponseDelegate> response_delegate_; - - // Used to invalidate the DefaultBrowserWorker callback. - base::WeakPtrFactory<SetAsDefaultBrowserHandler> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserHandler); -}; - -SetAsDefaultBrowserHandler::SetAsDefaultBrowserHandler( - const base::WeakPtr<ResponseDelegate>& response_delegate) - : response_delegate_(response_delegate), weak_ptr_factory_(this) { - default_browser_worker_ = new shell_integration::DefaultBrowserWorker( - base::Bind(&SetAsDefaultBrowserHandler::OnDefaultBrowserWorkerFinished, - weak_ptr_factory_.GetWeakPtr())); -} - -void SetAsDefaultBrowserHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback( - "SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow", - base::BindRepeating( - &SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow, - base::Unretained(this))); -} - -void SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow( - const base::ListValue* args) { - default_browser_worker_->StartSetAsDefault(); -} - -void SetAsDefaultBrowserHandler::ConcludeInteraction( - MakeChromeDefaultResult interaction_result) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (response_delegate_) - response_delegate_->SetDialogInteractionResult(interaction_result); - - WebContents* contents = web_ui()->GetWebContents(); - - if (contents) { - content::WebContentsDelegate* delegate = contents->GetDelegate(); - if (delegate) - delegate->CloseContents(contents); - } -} - -void SetAsDefaultBrowserHandler::OnDefaultBrowserWorkerFinished( - shell_integration::DefaultWebClientState state) { - // The callback is expected to be invoked once the procedure has completed. - DCHECK_CURRENTLY_ON(BrowserThread::UI); - 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 - // choice. -} - -// A web dialog delegate implementation for when 'Make Chrome Metro' UI -// is displayed on a dialog. -class SetAsDefaultBrowserDialogImpl : public ui::WebDialogDelegate, - public ResponseDelegate, - public BrowserListObserver { - public: - explicit SetAsDefaultBrowserDialogImpl(Profile* profile); - ~SetAsDefaultBrowserDialogImpl() override; - // Show a modal web dialog with kChromeUIMetroFlowURL page. - void ShowDialog(); - static views::Widget* dialog_widget() { return dialog_widget_; } - - protected: - // Overridden from WebDialogDelegate: - ui::ModalType GetDialogModalType() const override; - base::string16 GetDialogTitle() const override; - GURL GetDialogContentURL() const override; - void GetWebUIMessageHandlers( - std::vector<WebUIMessageHandler*>* handlers) const override; - void GetDialogSize(gfx::Size* size) const override; - std::string GetDialogArgs() const override; - void OnDialogClosed(const std::string& json_retval) override; - void OnCloseContents(WebContents* source, bool* out_close_dialog) override; - bool ShouldShowDialogTitle() const override; - bool HandleContextMenu(content::RenderFrameHost* render_frame_host, - const content::ContextMenuParams& params) override; - - // Overridden from ResponseDelegate: - void SetDialogInteractionResult(MakeChromeDefaultResult result) override; - - // Overridden from BrowserListObserver: - void OnBrowserAdded(Browser* browser) override; - void OnBrowserRemoved(Browser* browser) override; - - private: - Profile* profile_; - Browser* browser_; - mutable bool owns_handler_; - base::WeakPtrFactory<ResponseDelegate> response_delegate_ptr_factory_; - SetAsDefaultBrowserHandler* handler_; - MakeChromeDefaultResult dialog_interaction_result_; - - static views::Widget* dialog_widget_; - - DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserDialogImpl); -}; - -// static -views::Widget* SetAsDefaultBrowserDialogImpl::dialog_widget_ = nullptr; - -SetAsDefaultBrowserDialogImpl::SetAsDefaultBrowserDialogImpl(Profile* profile) - : profile_(profile), - browser_(nullptr), - owns_handler_(true), - response_delegate_ptr_factory_(this), - handler_(new SetAsDefaultBrowserHandler( - response_delegate_ptr_factory_.GetWeakPtr())), - dialog_interaction_result_(MAKE_CHROME_DEFAULT_DECLINED) { - BrowserList::AddObserver(this); -} - -SetAsDefaultBrowserDialogImpl::~SetAsDefaultBrowserDialogImpl() { - if (browser_) - BrowserList::RemoveObserver(this); - if (owns_handler_) - delete handler_; -} - -void SetAsDefaultBrowserDialogImpl::ShowDialog() { - // Use a NULL parent window to make sure that the dialog will have an item - // in the Windows task bar. The code below will make it highlight if the - // dialog is not in the foreground. - gfx::NativeWindow native_window = chrome::ShowWebDialog(NULL, profile_, this); - DCHECK(!dialog_widget_); - dialog_widget_ = views::Widget::GetWidgetForNativeWindow(native_window); - dialog_widget_->FlashFrame(true); -} - -ui::ModalType SetAsDefaultBrowserDialogImpl::GetDialogModalType() const { - return ui::MODAL_TYPE_SYSTEM; -} - -base::string16 SetAsDefaultBrowserDialogImpl::GetDialogTitle() const { - return l10n_util::GetStringUTF16(IDS_METRO_FLOW_TAB_TITLE); -} - -GURL SetAsDefaultBrowserDialogImpl::GetDialogContentURL() const { - std::string url_string(chrome::kChromeUIMetroFlowURL); - return GURL(url_string); -} - -void SetAsDefaultBrowserDialogImpl::GetWebUIMessageHandlers( - std::vector<WebUIMessageHandler*>* handlers) const { - handlers->push_back(handler_); - owns_handler_ = false; -} - -void SetAsDefaultBrowserDialogImpl::GetDialogSize(gfx::Size* size) const { - PrefService* prefs = profile_->GetPrefs(); - gfx::Font approximate_web_font( - prefs->GetString(prefs::kWebKitSansSerifFontFamily), - prefs->GetInteger(prefs::kWebKitDefaultFontSize)); - - *size = ui::GetLocalizedContentsSizeForFont(IDS_METRO_FLOW_WIDTH_CHARS, - IDS_METRO_FLOW_HEIGHT_LINES, - approximate_web_font); -} - -std::string SetAsDefaultBrowserDialogImpl::GetDialogArgs() const { - return "[]"; -} - -void SetAsDefaultBrowserDialogImpl::OnDialogClosed( - const std::string& json_retval) { - // Register the user's response in UMA. - UMA_HISTOGRAM_ENUMERATION(kSetAsDefaultBrowserHistogram, - dialog_interaction_result_, - MAKE_CHROME_DEFAULT_MAX); - - // Suppress showing the default browser infobar if the user explicitly elected - // *not to* make Chrome default. - if (dialog_interaction_result_ == MAKE_CHROME_DEFAULT_REGRETTED || - dialog_interaction_result_ == MAKE_CHROME_DEFAULT_ACCEPTED_OTHER_MODE) { - 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 - // show it. - if (browser_) { - BrowserWindow* window = browser_->window(); - WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); - window->Show(); - if (contents) - contents->SetInitialFocus(); - } - - DCHECK(dialog_widget_); - dialog_widget_ = nullptr; - - delete this; -} - -void SetAsDefaultBrowserDialogImpl::OnCloseContents(WebContents* source, - bool* out_close_dialog) { - *out_close_dialog = true; -} - -bool SetAsDefaultBrowserDialogImpl::ShouldShowDialogTitle() const { - return true; -} - -bool SetAsDefaultBrowserDialogImpl::HandleContextMenu( - content::RenderFrameHost* render_frame_host, - const content::ContextMenuParams& params) { - return true; -} - -void SetAsDefaultBrowserDialogImpl::SetDialogInteractionResult( - MakeChromeDefaultResult result) { - dialog_interaction_result_ = result; -} - -void SetAsDefaultBrowserDialogImpl::OnBrowserAdded(Browser* browser) { - if (browser_ || !browser || !browser->is_type_tabbed()) - return; - browser_ = browser; - ShowDialog(); -} - -void SetAsDefaultBrowserDialogImpl::OnBrowserRemoved(Browser* browser) { - if (browser_ == browser) { - browser_ = NULL; - BrowserList::RemoveObserver(this); - } -} - -} // namespace - -SetAsDefaultBrowserUI::SetAsDefaultBrowserUI(content::WebUI* web_ui) - : ui::WebDialogUI(web_ui) { - content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), - CreateSetAsDefaultBrowserUIHTMLSource()); -} - -// static -void SetAsDefaultBrowserUI::Show(Profile* profile) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - new SetAsDefaultBrowserDialogImpl(profile); -} - -// static -views::Widget* SetAsDefaultBrowserUI::GetDialogWidgetForTesting() { - return SetAsDefaultBrowserDialogImpl::dialog_widget(); -} diff --git a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.h b/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.h deleted file mode 100644 index 308200d435f..00000000000 --- a/chromium/chrome/browser/ui/webui/set_as_default_browser_ui_win.h +++ /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. - -#ifndef CHROME_BROWSER_UI_WEBUI_SET_AS_DEFAULT_BROWSER_UI_WIN_H_ -#define CHROME_BROWSER_UI_WEBUI_SET_AS_DEFAULT_BROWSER_UI_WIN_H_ - -#include "base/macros.h" -#include "ui/web_dialogs/web_dialog_ui.h" - -class Profile; - -namespace views { -class Widget; -} - -// The UI used in first-run flow to prompt the user to set Chrome as the -// default Windows browser and *the browser* of Metro mode. Intended for -// Windows 8 only. -class SetAsDefaultBrowserUI : public ui::WebDialogUI { - public: - explicit SetAsDefaultBrowserUI(content::WebUI* web_ui); - - // Present metroizer UI either in a new singleton tab or in a dialog window. - static void Show(Profile* profile); - - // Returns the web dialog widget for testing. - static views::Widget* GetDialogWidgetForTesting(); - - private: - DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_SET_AS_DEFAULT_BROWSER_UI_WIN_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc index 517f2c413cb..7245f9a91e3 100644 --- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc @@ -25,6 +25,7 @@ #include "base/task/post_task.h" #include "base/time/time.h" #include "base/values.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_content_browser_client.h" @@ -325,7 +326,7 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, html_source->AddString("aboutObsoleteSystemURL", ObsoleteSystem::GetLinkURL()); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) base::string16 tos = l10n_util::GetStringFUTF16( IDS_ABOUT_TERMS_OF_SERVICE, base::UTF8ToUTF16(chrome::kChromeUITermsURL)); html_source->AddString("aboutProductTos", tos); @@ -334,7 +335,7 @@ AboutHandler* AboutHandler::Create(content::WebUIDataSource* html_source, #if defined(OS_CHROMEOS) std::string safetyInfoLink = GetSafetyInfoLink(); html_source->AddBoolean("shouldShowSafetyInfo", !safetyInfoLink.empty()); -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) html_source->AddString( "aboutProductSafety", l10n_util::GetStringUTF16(IDS_ABOUT_SAFETY_INFORMATION)); @@ -450,9 +451,9 @@ void AboutHandler::RegisterMessages() { void AboutHandler::OnJavascriptAllowed() { apply_changes_from_upgrade_observer_ = true; version_updater_.reset(VersionUpdater::Create(web_ui()->GetWebContents())); - policy_registrar_.reset(new policy::PolicyChangeRegistrar( + policy_registrar_ = std::make_unique<policy::PolicyChangeRegistrar>( g_browser_process->policy_service(), - policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()))); + policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())); policy_registrar_->Observe( policy::key::kDeviceAutoUpdateDisabled, base::Bind(&AboutHandler::OnDeviceAutoUpdatePolicyChanged, @@ -604,8 +605,9 @@ void AboutHandler::HandleGetVersionInfo(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&GetVersionInfo), base::Bind(&AboutHandler::OnGetVersionInfoReady, weak_factory_.GetWeakPtr(), callback_id)); @@ -622,8 +624,9 @@ void AboutHandler::HandleGetRegulatoryInfo(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&FindRegulatoryLabelDir), base::Bind(&AboutHandler::OnRegulatoryLabelDirFound, weak_factory_.GetWeakPtr(), callback_id)); @@ -801,8 +804,9 @@ void AboutHandler::OnRegulatoryLabelDirFound( return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&ReadRegulatoryLabelText, label_dir_path), base::Bind(&AboutHandler::OnRegulatoryLabelTextRead, weak_factory_.GetWeakPtr(), callback_id, label_dir_path)); diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc index 86695044727..4fceb887f1c 100644 --- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc @@ -12,10 +12,6 @@ #include "chrome/browser/themes/theme_service_factory.h" #include "content/public/browser/web_ui.h" -#if defined(OS_CHROMEOS) -#include "chrome/browser/ui/ash/wallpaper_controller_client.h" -#endif - namespace settings { AppearanceHandler::AppearanceHandler(content::WebUI* webui) @@ -37,22 +33,6 @@ void AppearanceHandler::RegisterMessages() { base::BindRepeating(&AppearanceHandler::HandleUseSystemTheme, base::Unretained(this))); #endif -#if defined(OS_CHROMEOS) - web_ui()->RegisterMessageCallback( - "openWallpaperManager", - base::BindRepeating(&AppearanceHandler::HandleOpenWallpaperManager, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback( - "isWallpaperSettingVisible", - base::BindRepeating(&AppearanceHandler::IsWallpaperSettingVisible, - base::Unretained(this))); - - web_ui()->RegisterMessageCallback( - "isWallpaperPolicyControlled", - base::BindRepeating(&AppearanceHandler::IsWallpaperPolicyControlled, - base::Unretained(this))); -#endif } void AppearanceHandler::HandleUseDefaultTheme(const base::ListValue* args) { @@ -68,31 +48,4 @@ void AppearanceHandler::HandleUseSystemTheme(const base::ListValue* args) { } #endif -#if defined(OS_CHROMEOS) -void AppearanceHandler::IsWallpaperSettingVisible(const base::ListValue* args) { - CHECK_EQ(args->GetSize(), 1U); - bool result = WallpaperControllerClient::Get()->ShouldShowWallpaperSetting(); - ResolveCallback(args->GetList()[0], result); -} - -void AppearanceHandler::IsWallpaperPolicyControlled( - const base::ListValue* args) { - CHECK_EQ(args->GetSize(), 1U); - bool result = WallpaperControllerClient::Get() - ->IsActiveUserWallpaperControlledByPolicy(); - ResolveCallback(args->GetList()[0], result); -} - -void AppearanceHandler::HandleOpenWallpaperManager( - const base::ListValue* args) { - WallpaperControllerClient::Get()->OpenWallpaperPickerIfAllowed(); -} - -void AppearanceHandler::ResolveCallback(const base::Value& callback_id, - bool result) { - AllowJavascript(); - ResolveJavascriptCallback(callback_id, base::Value(result)); -} -#endif - } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h index dabbd53601d..961e16eec2d 100644 --- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h @@ -41,20 +41,6 @@ class AppearanceHandler : public SettingsPageUIHandler { void HandleUseSystemTheme(const base::ListValue* args); #endif -#if defined(OS_CHROMEOS) - // Whether the wallpaper setting should be shown. - 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); - - // Helper function to resolve the Javascript callback. - void ResolveCallback(const base::Value& callback_id, bool result); -#endif - Profile* profile_; // Weak pointer. base::WeakPtrFactory<AppearanceHandler> weak_ptr_factory_{this}; diff --git a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc index 7047d2983da..b34815f9c76 100644 --- a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc @@ -7,8 +7,9 @@ #include "base/bind.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/prefs/pref_service.h" +#include "components/safe_browsing/password_protection/metrics_util.h" +#include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -16,6 +17,8 @@ namespace settings { using password_manager::metrics_util::PasswordType; using safe_browsing::ChromePasswordProtectionService; +using safe_browsing::LoginReputationClientResponse; +using safe_browsing::RequestOutcome; ChangePasswordHandler::ChangePasswordHandler( Profile* profile, @@ -40,7 +43,7 @@ void ChangePasswordHandler::RegisterMessages() { void ChangePasswordHandler::OnJavascriptAllowed() { pref_registrar_.Init(profile_->GetPrefs()); pref_registrar_.Add( - prefs::kSafeBrowsingUnhandledSyncPasswordReuses, + prefs::kSafeBrowsingUnhandledGaiaPasswordReuses, base::Bind(&ChangePasswordHandler::UpdateChangePasswordCardVisibility, base::Unretained(this))); } @@ -55,18 +58,24 @@ void ChangePasswordHandler::HandleInitialize(const base::ListValue* args) { } void ChangePasswordHandler::HandleChangePassword(const base::ListValue* args) { - service_->OnUserAction(web_ui()->GetWebContents(), - PasswordType::PRIMARY_ACCOUNT_PASSWORD, - safe_browsing::WarningUIType::CHROME_SETTINGS, - safe_browsing::WarningAction::CHANGE_PASSWORD); + service_->OnUserAction( + web_ui()->GetWebContents(), + service_->reused_password_account_type_for_last_shown_warning(), + RequestOutcome::UNKNOWN, + LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED, "unused_token", + safe_browsing::WarningUIType::CHROME_SETTINGS, + safe_browsing::WarningAction::CHANGE_PASSWORD); } void ChangePasswordHandler::UpdateChangePasswordCardVisibility() { FireWebUIListener( "change-password-visibility", - base::Value(service_->IsWarningEnabled() && - safe_browsing::ChromePasswordProtectionService:: - ShouldShowChangePasswordSettingUI(profile_))); + base::Value( + service_->IsWarningEnabled( + service_ + ->reused_password_account_type_for_last_shown_warning()) && + safe_browsing::ChromePasswordProtectionService:: + ShouldShowChangePasswordSettingUI(profile_))); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc index d7a9cd51101..37f8b056c86 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc @@ -18,6 +18,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/values.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_service.h" @@ -119,7 +120,7 @@ void ChromeCleanupHandler::GetExtensionNamesFromIds( Profile* profile, const std::set<base::string16>& extension_ids, std::set<base::string16>* extension_names) { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) extensions::ExtensionRegistry* extension_registry = extensions::ExtensionRegistry::Get(profile); for (const base::string16& extension_id : extension_ids) { @@ -303,16 +304,16 @@ void ChromeCleanupHandler::HandleNotifyChromeCleanupLearnMoreClicked( void ChromeCleanupHandler::HandleGetMoreItemsPluralString( const base::ListValue* args) { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) GetPluralString(IDS_SETTINGS_RESET_CLEANUP_DETAILS_MORE, args); -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) } void ChromeCleanupHandler::HandleGetItemsToRemovePluralString( const base::ListValue* args) { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) GetPluralString(IDS_SETTINGS_RESET_CLEANUP_DETAILS_ITEMS_TO_BE_REMOVED, args); -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) } void ChromeCleanupHandler::GetPluralString(int id, diff --git a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc index a9fb0bb1553..cff17fb6870 100644 --- a/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc @@ -4,12 +4,13 @@ #include "chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h" +#include "build/branding_buildflags.h" #include "chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" @@ -19,7 +20,7 @@ namespace settings { using safe_browsing::MockChromeCleanerProcess; TEST(ChromeCleanupHandlerTest, GetExtensionsNamesFromIds) { - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_(TestingBrowserProcess::GetGlobal()); // Set up the testing profile to get the extensions registry from it. @@ -35,7 +36,7 @@ TEST(ChromeCleanupHandlerTest, GetExtensionsNamesFromIds) { }; std::set<base::string16> expected_names = { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) // Extension names are only available in Google-branded builds. MockChromeCleanerProcess::kInstalledExtensionName1, MockChromeCleanerProcess::kInstalledExtensionName2, diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc index 56f573121d0..34dbb5b6fac 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.cc @@ -35,10 +35,6 @@ void AccessibilityHandler::RegisterMessages() { &AccessibilityHandler::HandleShowSelectToSpeakSettings, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "showSwitchAccessSettings", - base::BindRepeating(&AccessibilityHandler::HandleShowSwitchAccessSettings, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( "getStartupSoundEnabled", base::BindRepeating(&AccessibilityHandler::HandleGetStartupSoundEnabled, base::Unretained(this))); @@ -58,11 +54,6 @@ void AccessibilityHandler::HandleShowSelectToSpeakSettings( OpenExtensionOptionsPage(extension_misc::kSelectToSpeakExtensionId); } -void AccessibilityHandler::HandleShowSwitchAccessSettings( - const base::ListValue* args) { - OpenExtensionOptionsPage(extension_misc::kSwitchAccessExtensionId); -} - void AccessibilityHandler::HandleGetStartupSoundEnabled( const base::ListValue* args) { AllowJavascript(); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h index 26f284ad260..80d735832cb 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h @@ -32,11 +32,10 @@ class AccessibilityHandler : public ::settings::SettingsPageUIHandler { void OnJavascriptDisallowed() override {} private: - // Callback for the messages to show settings for ChromeVox, - // Select To Speak, or Switch Access. + // Callback for the messages to show settings for ChromeVox or + // Select To Speak. void HandleShowChromeVoxSettings(const base::ListValue* args); void HandleShowSelectToSpeakSettings(const base::ListValue* args); - void HandleShowSwitchAccessSettings(const base::ListValue* args); void HandleGetStartupSoundEnabled(const base::ListValue* args); void HandleSetStartupSoundEnabled(const base::ListValue* args); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc index e06d7205e11..3978c28d325 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc @@ -101,8 +101,7 @@ AccountManagerUIHandler::AccountManagerUIHandler( : account_manager_(account_manager), identity_manager_(identity_manager), account_manager_observer_(this), - identity_manager_observer_(this), - weak_factory_(this) { + identity_manager_observer_(this) { DCHECK(account_manager_); DCHECK(identity_manager_); } @@ -141,21 +140,18 @@ void AccountManagerUIHandler::HandleGetAccounts(const base::ListValue* args) { AllowJavascript(); const auto& args_list = args->GetList(); - CHECK_EQ(args_list.size(), 2u); + CHECK_EQ(args_list.size(), 1u); CHECK(args_list[0].is_string()); - CHECK(args_list[1].is_bool()); base::Value callback_id = args_list[0].Clone(); - bool include_images = args_list[1].GetBool(); - account_manager_->GetAccounts(base::BindOnce( - &AccountManagerUIHandler::OnGetAccounts, weak_factory_.GetWeakPtr(), - std::move(callback_id), include_images)); + account_manager_->GetAccounts( + base::BindOnce(&AccountManagerUIHandler::OnGetAccounts, + weak_factory_.GetWeakPtr(), std::move(callback_id))); } void AccountManagerUIHandler::OnGetAccounts( base::Value callback_id, - bool include_images, const std::vector<AccountManager::Account>& stored_accounts) { base::ListValue accounts; @@ -179,8 +175,9 @@ void AccountManagerUIHandler::OnGetAccounts( account.SetBoolean("isDeviceAccount", false); base::Optional<AccountInfo> maybe_account_info = - identity_manager_->FindAccountInfoForAccountWithRefreshTokenByGaiaId( - account_key.id); + identity_manager_ + ->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId( + account_key.id); DCHECK(maybe_account_info.has_value()); account.SetBoolean( @@ -189,20 +186,17 @@ void AccountManagerUIHandler::OnGetAccounts( maybe_account_info->account_id)); account.SetString("fullName", maybe_account_info->full_name); account.SetString("email", stored_account.raw_email); - // Images can be large, so only send them if requested. - if (include_images) { - if (!maybe_account_info->account_image.IsEmpty()) { - account.SetString("pic", - webui::GetBitmapDataUrl( - maybe_account_info->account_image.AsBitmap())); - } else { - gfx::ImageSkia default_icon = - *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( - IDR_LOGIN_DEFAULT_USER); - account.SetString( - "pic", webui::GetBitmapDataUrl( - default_icon.GetRepresentation(1.0f).GetBitmap())); - } + if (!maybe_account_info->account_image.IsEmpty()) { + account.SetString("pic", + webui::GetBitmapDataUrl( + maybe_account_info->account_image.AsBitmap())); + } else { + gfx::ImageSkia default_icon = + *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( + IDR_LOGIN_DEFAULT_USER); + account.SetString("pic", + webui::GetBitmapDataUrl( + default_icon.GetRepresentation(1.0f).GetBitmap())); } account.SetBoolean("unmigrated", account_manager_->HasDummyGaiaToken(account_key)); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h index 071c7cf9b22..c915a10cfa6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h @@ -64,7 +64,6 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, // |AccountManager::GetAccounts| callback. void OnGetAccounts( base::Value callback_id, - bool include_images, const std::vector<AccountManager::Account>& stored_accounts); // Refreshes the UI. @@ -86,7 +85,7 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; - base::WeakPtrFactory<AccountManagerUIHandler> weak_factory_; + base::WeakPtrFactory<AccountManagerUIHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccountManagerUIHandler); }; 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 4cf92f5fcda..df482d3555e 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 @@ -20,8 +20,7 @@ namespace settings { AndroidAppsHandler::AndroidAppsHandler(Profile* profile) : arc_prefs_observer_(this), arc_session_manager_observer_(this), - profile_(profile), - weak_ptr_factory_(this) {} + profile_(profile) {} AndroidAppsHandler::~AndroidAppsHandler() {} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h index cb89bc38224..3a7d0549e7d 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/android_apps_handler.h @@ -60,7 +60,7 @@ class AndroidAppsHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<arc::ArcSessionManager, arc::ArcSessionManager::Observer> arc_session_manager_observer_; Profile* profile_; // unowned - base::WeakPtrFactory<AndroidAppsHandler> weak_ptr_factory_; + base::WeakPtrFactory<AndroidAppsHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AndroidAppsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS new file mode 100644 index 00000000000..94b2e07d850 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/OWNERS @@ -0,0 +1,4 @@ +dominickn@chromium.org +jshikaram@chromium.org + +# COMPONENT: Platform>Apps>Foundation diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc new file mode 100644 index 00000000000..8b3abcc9b50 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc @@ -0,0 +1,55 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h" + +#include <memory> +#include <utility> + +#include "base/bind.h" +#include "base/feature_list.h" +#include "chrome/browser/apps/app_service/app_icon_source.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/app_management/app_management_page_handler.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/chromium_strings.h" +#include "chrome/grit/generated_resources.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/url_data_source.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" +#include "ui/base/resource/resource_bundle.h" + +AppManagementPageHandlerFactory::AppManagementPageHandlerFactory( + Profile* profile) + : page_factory_binding_(this), profile_(profile) {} + +AppManagementPageHandlerFactory::~AppManagementPageHandlerFactory() = default; + +void AppManagementPageHandlerFactory::Bind( + app_management::mojom::PageHandlerFactoryRequest request) { + if (page_factory_binding_.is_bound()) { + page_factory_binding_.Unbind(); + } + + page_factory_binding_.Bind(std::move(request)); +} + +void AppManagementPageHandlerFactory::BindPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request) { + if (page_factory_binding_.is_bound()) { + page_factory_binding_.Unbind(); + } + + page_factory_binding_.Bind(std::move(request)); +} + +void AppManagementPageHandlerFactory::CreatePageHandler( + app_management::mojom::PagePtr page, + app_management::mojom::PageHandlerRequest request) { + DCHECK(page); + + page_handler_ = std::make_unique<AppManagementPageHandler>( + std::move(request), std::move(page), profile_); +} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h new file mode 100644 index 00000000000..3779071f093 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h @@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ + +#include <memory> + +#include "base/macros.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" + +class Profile; + +class AppManagementPageHandler; + +class AppManagementPageHandlerFactory + : public app_management::mojom::PageHandlerFactory { + public: + explicit AppManagementPageHandlerFactory(Profile* profile); + ~AppManagementPageHandlerFactory() override; + + void Bind(app_management::mojom::PageHandlerFactoryRequest request); + + private: + void BindPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request); + + // app_management::mojom::PageHandlerFactory: + void CreatePageHandler( + app_management::mojom::PagePtr page, + app_management::mojom::PageHandlerRequest request) override; + + std::unique_ptr<AppManagementPageHandler> page_handler_; + + mojo::Binding<app_management::mojom::PageHandlerFactory> + page_factory_binding_; + + Profile* profile_; + + DISALLOW_COPY_AND_ASSIGN(AppManagementPageHandlerFactory); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_APP_MANAGEMENT_APP_MANAGEMENT_PAGE_HANDLER_FACTORY_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc index 3a2b3bc5b12..c548d8996f3 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc @@ -6,12 +6,9 @@ #include <string> #include <utility> -#include <vector> #include "base/bind.h" #include "base/bind_helpers.h" -#include "chrome/browser/chromeos/crostini/crostini_export_import.h" -#include "chrome/browser/chromeos/crostini/crostini_manager.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/chromeos/guest_os/guest_os_share_path.h" @@ -21,8 +18,7 @@ namespace chromeos { namespace settings { -CrostiniHandler::CrostiniHandler(Profile* profile) - : profile_(profile), weak_ptr_factory_(this) {} +CrostiniHandler::CrostiniHandler(Profile* profile) : profile_(profile) {} CrostiniHandler::~CrostiniHandler() { DisallowJavascript(); @@ -67,6 +63,11 @@ void CrostiniHandler::RegisterMessages() { base::BindRepeating( &CrostiniHandler::HandleCrostiniInstallerStatusRequest, weak_ptr_factory_.GetWeakPtr())); + web_ui()->RegisterMessageCallback( + "requestCrostiniExportImportOperationStatus", + base::BindRepeating( + &CrostiniHandler::HandleCrostiniExportImportOperationStatusRequest, + weak_ptr_factory_.GetWeakPtr())); } void CrostiniHandler::OnJavascriptAllowed() { @@ -75,6 +76,7 @@ void CrostiniHandler::OnJavascriptAllowed() { if (chromeos::CrosUsbDetector::Get()) { chromeos::CrosUsbDetector::Get()->AddUsbDeviceObserver(this); } + crostini::CrostiniExportImport::GetForProfile(profile_)->AddObserver(this); } void CrostiniHandler::OnJavascriptDisallowed() { @@ -86,6 +88,7 @@ void CrostiniHandler::OnJavascriptDisallowed() { if (chromeos::CrosUsbDetector::Get()) { chromeos::CrosUsbDetector::Get()->RemoveUsbDeviceObserver(this); } + crostini::CrostiniExportImport::GetForProfile(profile_)->RemoveObserver(this); } void CrostiniHandler::HandleRequestCrostiniInstallerView( @@ -130,7 +133,8 @@ void CrostiniHandler::HandleRemoveCrostiniSharedPath( vm_name, base::FilePath(path), /*unpersist=*/true, base::BindOnce( - [](const std::string& path, bool result, std::string failure_reason) { + [](const std::string& path, bool result, + const std::string& failure_reason) { if (!result) { LOG(ERROR) << "Error unsharing " << path << ": " << failure_reason; @@ -225,6 +229,15 @@ void CrostiniHandler::HandleCrostiniInstallerStatusRequest( OnCrostiniInstallerViewStatusChanged(status); } +void CrostiniHandler::HandleCrostiniExportImportOperationStatusRequest( + const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(0U, args->GetSize()); + bool in_progress = crostini::CrostiniExportImport::GetForProfile(profile_) + ->GetExportImportOperationStatus(); + OnCrostiniExportImportOperationStatusChanged(in_progress); +} + void CrostiniHandler::OnCrostiniInstallerViewStatusChanged(bool status) { // It's technically possible for this to be called before Javascript is // enabled, in which case we must not call FireWebUIListener @@ -234,5 +247,12 @@ void CrostiniHandler::OnCrostiniInstallerViewStatusChanged(bool status) { } } +void CrostiniHandler::OnCrostiniExportImportOperationStatusChanged( + bool in_progress) { + // Other side listens with cr.addWebUIListener + FireWebUIListener("crostini-export-import-operation-status-changed", + base::Value(in_progress)); +} + } // namespace settings } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h index 97f4605f475..c5d4a353f6e 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h @@ -8,6 +8,7 @@ #include <vector> #include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/crostini/crostini_export_import.h" #include "chrome/browser/chromeos/crostini/crostini_manager.h" #include "chrome/browser/chromeos/usb/cros_usb_detector.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" @@ -23,6 +24,7 @@ namespace settings { class CrostiniHandler : public ::settings::SettingsPageUIHandler, public crostini::InstallerViewStatusObserver, + public crostini::CrostiniExportImport::Observer, public chromeos::CrosUsbDeviceObserver { public: explicit CrostiniHandler(Profile* profile); @@ -56,10 +58,15 @@ class CrostiniHandler : public ::settings::SettingsPageUIHandler, void HandleCrostiniInstallerStatusRequest(const base::ListValue* args); // Handle the CrostiniInstallerView opening/closing. void OnCrostiniInstallerViewStatusChanged(bool open) override; + // Handle a request for the CrostiniExportImport operation status. + void HandleCrostiniExportImportOperationStatusRequest( + const base::ListValue* args); + // CrostiniExportImport::Observer: + void OnCrostiniExportImportOperationStatusChanged(bool in_progress) override; Profile* profile_; // weak_ptr_factory_ should always be last member. - base::WeakPtrFactory<CrostiniHandler> weak_ptr_factory_; + base::WeakPtrFactory<CrostiniHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CrostiniHandler); }; 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 b6021b75156..2f4c1749e9a 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 @@ -260,8 +260,7 @@ CupsPrintersHandler::CupsPrintersHandler( printer_configurer_(std::move(printer_configurer)), printers_manager_(printers_manager), endpoint_resolver_(std::make_unique<local_discovery::EndpointResolver>()), - printers_manager_observer_(this), - weak_factory_(this) {} + printers_manager_observer_(this) {} // static std::unique_ptr<CupsPrintersHandler> CupsPrintersHandler::Create( @@ -745,7 +744,8 @@ void CupsPrintersHandler::OnAddedOrEditedPrinterCommon( UMA_HISTOGRAM_ENUMERATION("Printing.CUPS.PrinterAdded", printer.GetProtocol(), Printer::kProtocolMax); PRINTER_LOG(USER) << "Performing printer setup"; - printers_manager_->PrinterInstalled(printer, is_automatic); + printers_manager_->PrinterInstalled(printer, is_automatic, + PrinterSetupSource::kSettings); printers_manager_->SavePrinter(printer); if (printer.IsUsbProtocol()) { // Record UMA for USB printer setup source. @@ -945,8 +945,9 @@ void CupsPrintersHandler::FileSelected(const base::FilePath& path, // VerifyPpdContents() in order to determine whether the file appears to be a // PPD file. The task's priority is USER_BLOCKING because the this task // updates the UI as a result of a direct user action. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFileToStringWithMaxSize, path, kPpdMaxLineLength), base::BindOnce(&CupsPrintersHandler::VerifyPpdContents, weak_factory_.GetWeakPtr(), path)); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h index d2b16b0ec44..3fe1146c725 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h @@ -232,7 +232,7 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<CupsPrintersManager, CupsPrintersManager::Observer> printers_manager_observer_; - base::WeakPtrFactory<CupsPrintersHandler> weak_factory_; + base::WeakPtrFactory<CupsPrintersHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CupsPrintersHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc index 3a0aa798540..c9c52df5e53 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc @@ -13,7 +13,7 @@ #include "chrome/test/base/testing_profile.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -78,7 +78,7 @@ class FakePpdProvider : public PpdProvider { class CupsPrintersHandlerTest : public testing::Test { public: CupsPrintersHandlerTest() - : thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD), + : task_environment_(content::BrowserTaskEnvironment::REAL_IO_THREAD), profile_(), web_ui_(), printers_handler_() {} @@ -94,7 +94,7 @@ class CupsPrintersHandlerTest : public testing::Test { protected: // Must outlive |profile_|. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; content::TestWebUI web_ui_; std::unique_ptr<CupsPrintersHandler> printers_handler_; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc index 812cffcf10f..e2de1a94c72 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc @@ -9,12 +9,14 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" +#include "base/time/time.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/child_accounts/parent_access_code/parent_access_service.h" #include "chrome/browser/chromeos/set_time_dialog.h" #include "chrome/browser/chromeos/system/timezone_resolver_manager.h" #include "chrome/browser/chromeos/system/timezone_util.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/dbus/system_clock/system_clock_client.h" @@ -64,8 +66,7 @@ bool IsTimezoneAutomaticDetectionUserEditable() { } // namespace -DateTimeHandler::DateTimeHandler() - : scoped_observer_(this), weak_ptr_factory_(this) {} +DateTimeHandler::DateTimeHandler() : scoped_observer_(this) {} DateTimeHandler::~DateTimeHandler() = default; @@ -76,6 +77,9 @@ DateTimeHandler* DateTimeHandler::Create( html_source->AddString( "timeZoneID", system::TimezoneSettings::GetInstance()->GetCurrentTimezoneID()); + html_source->AddBoolean( + "timeActionsProtectedForChild", + base::FeatureList::IsEnabled(features::kParentAccessCodeForTimeChange)); return new DateTimeHandler; } @@ -165,7 +169,8 @@ void DateTimeHandler::HandleShowParentAccessForTimeZone( user_manager::UserManager::Get()->GetActiveUser()->GetAccountId(), base::BindRepeating(&DateTimeHandler::OnParentAccessValidation, weak_ptr_factory_.GetWeakPtr()), - ash::ParentAccessRequestReason::kChangeTimezone); + ash::ParentAccessRequestReason::kChangeTimezone, false /* extra_dimmer */, + base::Time()); } void DateTimeHandler::OnParentAccessValidation(bool success) { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h index bd69d936bc8..2a3c44a9b29 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h @@ -75,7 +75,7 @@ class DateTimeHandler : public ::settings::SettingsPageUIHandler, ScopedObserver<SystemClockClient, SystemClockClient::Observer> scoped_observer_; - base::WeakPtrFactory<DateTimeHandler> weak_ptr_factory_; + base::WeakPtrFactory<DateTimeHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DateTimeHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc index de342d5a55e..c38687e6415 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc @@ -5,11 +5,11 @@ #include "chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h" #include "ash/public/cpp/keyboard_shortcut_viewer.h" -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/cpp/tablet_mode.h" +#include "ash/public/mojom/constants.mojom.h" #include "base/bind.h" #include "base/command_line.h" #include "base/values.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chromeos/constants/chromeos_switches.h" #include "content/public/browser/web_ui.h" #include "content/public/common/service_manager_connection.h" @@ -114,8 +114,7 @@ void KeyboardHandler::HandleKeyboardChange(const base::ListValue* args) { void KeyboardHandler::UpdateKeyboards() { bool physical_keyboard = false; // In tablet mode, physical keybards are disabled / ignored. - if (!TabletModeClient::Get() || - !TabletModeClient::Get()->tablet_mode_enabled()) { + if (!ash::TabletMode::Get() || !ash::TabletMode::Get()->InTabletMode()) { physical_keyboard = true; } if (!physical_keyboard) { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc index 0f5933cc8a8..f9ac3140904 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_pointer_handler.cc @@ -24,7 +24,8 @@ void PointerHandler::RegisterMessages() { void PointerHandler::OnJavascriptAllowed() { if (!pointer_device_observer_) { - pointer_device_observer_.reset(new system::PointerDeviceObserver()); + pointer_device_observer_ = + std::make_unique<system::PointerDeviceObserver>(); pointer_device_observer_->Init(); } 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 ca32d32706f..79feea807e9 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 @@ -110,9 +110,7 @@ void PowerHandler::TestAPI::SetLidClosedBehavior( } PowerHandler::PowerHandler(PrefService* prefs) - : prefs_(prefs), - power_manager_client_observer_(this), - weak_ptr_factory_(this) {} + : prefs_(prefs), power_manager_client_observer_(this) {} PowerHandler::~PowerHandler() {} diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h index 78869c7978e..a362dcd45be 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_power_handler.h @@ -130,7 +130,7 @@ class PowerHandler : public ::settings::SettingsPageUIHandler, bool last_lid_closed_controlled_ = false; bool last_has_lid_ = true; - base::WeakPtrFactory<PowerHandler> weak_ptr_factory_; + base::WeakPtrFactory<PowerHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PowerHandler); }; 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 cf9b1c9342e..b9737dc9919 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 @@ -35,6 +35,7 @@ #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/disks/disk.h" #include "components/arc/arc_features.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" @@ -49,6 +50,9 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/text/bytes_formatting.h" +using chromeos::disks::Disk; +using chromeos::disks::DiskMountManager; + namespace chromeos { namespace settings { namespace { @@ -90,7 +94,7 @@ StorageHandler::StorageHandler(Profile* profile, profile_(profile), source_name_(html_source->GetSource()), arc_observer_(this), - weak_ptr_factory_(this) { + special_volume_path_pattern_("[a-z]+://.*") { html_source->AddBoolean( kAndroidEnabled, base::FeatureList::IsEnabled(arc::kUsbStorageUIFeature) && @@ -98,6 +102,7 @@ StorageHandler::StorageHandler(Profile* profile, } StorageHandler::~StorageHandler() { + DiskMountManager::GetInstance()->RemoveObserver(this); arc::ArcServiceManager::Get() ->arc_bridge_service() ->storage_manager() @@ -126,6 +131,10 @@ void StorageHandler::RegisterMessages() { "clearDriveCache", base::BindRepeating(&StorageHandler::HandleClearDriveCache, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "updateExternalStorages", + base::BindRepeating(&StorageHandler::HandleUpdateExternalStorages, + base::Unretained(this))); } void StorageHandler::OnJavascriptAllowed() { @@ -139,12 +148,18 @@ void StorageHandler::OnJavascriptAllowed() { ->arc_bridge_service() ->storage_manager() ->AddObserver(this); + + // Start observing mount/unmount events to update the connected device list. + DiskMountManager::GetInstance()->AddObserver(this); } void StorageHandler::OnJavascriptDisallowed() { // Ensure that pending callbacks do not complete and cause JS to be evaluated. weak_ptr_factory_.InvalidateWeakPtrs(); + // Stop observing mount/unmount events to update the connected device list. + DiskMountManager::GetInstance()->RemoveObserver(this); + // Stop observing the mojo connection so that OnConnectionReady() and // OnConnectionClosed() that use FireWebUIListener() won't be called while JS // is disabled. @@ -202,6 +217,11 @@ void StorageHandler::HandleClearDriveCache( weak_ptr_factory_.GetWeakPtr())); } +void StorageHandler::HandleUpdateExternalStorages( + const base::ListValue* unused_args) { + UpdateExternalStorages(); +} + void StorageHandler::OnClearDriveCacheDone(bool /*success*/) { UpdateDriveCacheSize(); } @@ -212,8 +232,9 @@ void StorageHandler::UpdateSizeStat() { int64_t* total_size = new int64_t(0); int64_t* available_size = new int64_t(0); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&GetSizeStatBlocking, downloads_path, total_size, available_size), base::Bind(&StorageHandler::OnGetSizeStat, weak_ptr_factory_.GetWeakPtr(), @@ -247,8 +268,9 @@ void StorageHandler::UpdateDownloadsSize() { const base::FilePath downloads_path = file_manager::util::GetDownloadsFolderForProfile(profile_); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&base::ComputeDirectorySize, downloads_path), base::Bind(&StorageHandler::OnGetDownloadsSize, weak_ptr_factory_.GetWeakPtr())); @@ -300,7 +322,7 @@ void StorageHandler::UpdateBrowsingDataSize() { if (!site_data_size_collector_.get()) { content::StoragePartition* storage_partition = content::BrowserContext::GetDefaultStoragePartition(profile_); - site_data_size_collector_.reset(new SiteDataSizeCollector( + site_data_size_collector_ = std::make_unique<SiteDataSizeCollector>( storage_partition->GetPath(), new BrowsingDataCookieHelper(storage_partition), new BrowsingDataDatabaseHelper(profile_), @@ -314,7 +336,7 @@ void StorageHandler::UpdateBrowsingDataSize() { storage_partition->GetServiceWorkerContext()), new BrowsingDataCacheStorageHelper( storage_partition->GetCacheStorageContext()), - BrowsingDataFlashLSOHelper::Create(profile_))); + BrowsingDataFlashLSOHelper::Create(profile_)); } site_data_size_collector_->Fetch( base::Bind(&StorageHandler::OnGetBrowsingDataSize, @@ -453,6 +475,36 @@ void StorageHandler::OnGetOtherUserSize( } } +void StorageHandler::UpdateExternalStorages() { + base::Value devices(base::Value::Type::LIST); + for (const auto& itr : DiskMountManager::GetInstance()->mount_points()) { + const DiskMountManager::MountPointInfo& mount_info = itr.second; + if (!IsEligibleForAndroidStorage(mount_info.source_path)) + continue; + + const chromeos::disks::Disk* disk = + DiskMountManager::GetInstance()->FindDiskBySourcePath( + mount_info.source_path); + if (!disk) + continue; + + std::string label = disk->device_label(); + if (label.empty()) { + // To make volume labels consistent with Files app, we follow how Files + // generates a volume label when the volume doesn't have specific label. + // That is, we use the base name of mount path instead in such cases. + // TODO(fukino): Share the implementation to compute the volume name with + // Files app. crbug.com/1002535. + label = base::FilePath(mount_info.mount_path).BaseName().AsUTF8Unsafe(); + } + base::Value device(base::Value::Type::DICTIONARY); + device.SetKey("uuid", base::Value(disk->fs_uuid())); + device.SetKey("label", base::Value(label)); + devices.GetList().push_back(std::move(device)); + } + FireWebUIListener("onExternalStoragesUpdated", devices); +} + void StorageHandler::OnConnectionReady() { is_android_running_ = true; UpdateAndroidRunning(); @@ -471,5 +523,25 @@ void StorageHandler::OnArcPlayStoreEnabledChanged(bool enabled) { content::WebUIDataSource::Update(profile_, source_name_, std::move(update)); } +void StorageHandler::OnMountEvent( + DiskMountManager::MountEvent event, + chromeos::MountError error_code, + const DiskMountManager::MountPointInfo& mount_info) { + if (error_code != chromeos::MountError::MOUNT_ERROR_NONE) + return; + + if (!IsEligibleForAndroidStorage(mount_info.source_path)) + return; + + UpdateExternalStorages(); +} + +bool StorageHandler::IsEligibleForAndroidStorage(std::string source_path) { + // Android's StorageManager volume concept relies on assumption that it is + // local filesystem. Hence, special volumes like DriveFS should not be + // listed on the Settings. + return !RE2::FullMatch(source_path, special_volume_path_pattern_); +} + } // namespace settings } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h index cefa5753f66..32078b3aa56 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h @@ -19,10 +19,12 @@ #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "components/arc/common/storage_manager.mojom.h" +#include "chromeos/disks/disk_mount_manager.h" +#include "components/arc/mojom/storage_manager.mojom.h" #include "components/arc/session/connection_observer.h" #include "components/arc/storage_manager/arc_storage_manager.h" #include "components/user_manager/user.h" +#include "third_party/re2/src/re2/re2.h" class Profile; @@ -40,7 +42,8 @@ namespace settings { class StorageHandler : public ::settings::SettingsPageUIHandler, public arc::ConnectionObserver<arc::mojom::StorageManagerInstance>, - public arc::ArcSessionManager::Observer { + public arc::ArcSessionManager::Observer, + public chromeos::disks::DiskMountManager::Observer { public: // Enumeration for device state about remaining space. These values must be // kept in sync with settings.StorageSpaceState in JS code. @@ -65,6 +68,12 @@ class StorageHandler // arc::ArcSessionManager::Observer: void OnArcPlayStoreEnabledChanged(bool enabled) override; + // chromeos::disks::DiskMountManager::Observer: + void OnMountEvent(chromeos::disks::DiskMountManager::MountEvent event, + chromeos::MountError error_code, + const chromeos::disks::DiskMountManager::MountPointInfo& + mount_info) override; + private: // Handlers of JS messages. void HandleUpdateAndroidEnabled(const base::ListValue* unused_args); @@ -72,6 +81,7 @@ class StorageHandler void HandleOpenDownloads(const base::ListValue* unused_args); void HandleOpenArcStorage(const base::ListValue* unused_args); void HandleClearDriveCache(const base::ListValue* unused_args); + void HandleUpdateExternalStorages(const base::ListValue* unused_args); // Callback called when clearing Drive cache is done. void OnClearDriveCacheDone(bool success); @@ -125,6 +135,13 @@ class StorageHandler // Callback to save the fetched user sizes and update the UI. void OnGetOtherUserSize(base::Optional<cryptohome::BaseReply> reply); + // Updates list of external storages. + void UpdateExternalStorages(); + + // Returns true if the volume from |source_path| can be used as Android + // storage. + bool IsEligibleForAndroidStorage(std::string source_path); + // Total size of cache data in browsing data. int64_t browser_cache_size_; @@ -163,8 +180,9 @@ class StorageHandler const std::string source_name_; ScopedObserver<arc::ArcSessionManager, arc::ArcSessionManager::Observer> arc_observer_; + const re2::RE2 special_volume_path_pattern_; - base::WeakPtrFactory<StorageHandler> weak_ptr_factory_; + base::WeakPtrFactory<StorageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(StorageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc index 8af7cb25dac..577dc77a406 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc @@ -58,10 +58,7 @@ std::unique_ptr<base::DictionaryValue> GetFingerprintsInfo( } // namespace FingerprintHandler::FingerprintHandler(Profile* profile) - : profile_(profile), - binding_(this), - session_observer_(this), - weak_ptr_factory_(this) { + : profile_(profile), binding_(this), session_observer_(this) { content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, &fp_service_); user_id_ = ProfileHelper::Get()->GetUserIdHashFromProfile(profile); diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h index e4d6c7e1fad..766d8842ee6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.h @@ -85,7 +85,7 @@ class FingerprintHandler : public ::settings::SettingsPageUIHandler, session_manager::SessionManagerObserver> session_observer_; - base::WeakPtrFactory<FingerprintHandler> weak_ptr_factory_; + base::WeakPtrFactory<FingerprintHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FingerprintHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc index 25814f623e6..a734cd0dc87 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc @@ -12,21 +12,20 @@ #include "base/bind_helpers.h" #include "base/values.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/ash/assistant/assistant_service_connection.h" #include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h" #include "chromeos/audio/cras_audio_handler.h" -#include "chromeos/constants/chromeos_switches.h" -#include "chromeos/services/assistant/public/mojom/constants.mojom.h" +#include "chromeos/constants/chromeos_features.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" #include "content/public/browser/browser_context.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/gfx/geometry/rect.h" namespace chromeos { namespace settings { GoogleAssistantHandler::GoogleAssistantHandler(Profile* profile) - : profile_(profile), weak_factory_(this) { + : profile_(profile) { chromeos::CrasAudioHandler::Get()->AddAudioObserver(this); } @@ -77,8 +76,7 @@ void GoogleAssistantHandler::RegisterMessages() { void GoogleAssistantHandler::HandleShowGoogleAssistantSettings( const base::ListValue* args) { CHECK_EQ(0U, args->GetSize()); - if (chromeos::switches::IsAssistantEnabled()) - ash::OpenAssistantSettings(); + ash::OpenAssistantSettings(); } void GoogleAssistantHandler::HandleRetrainVoiceModel( @@ -106,9 +104,9 @@ void GoogleAssistantHandler::BindAssistantSettingsManager() { DCHECK(!settings_manager_.is_bound()); // Set up settings mojom. - service_manager::Connector* connector = - content::BrowserContext::GetConnectorFor(profile_); - connector->BindInterface(assistant::mojom::kServiceName, &settings_manager_); + AssistantServiceConnection::GetForProfile(profile_) + ->service() + ->BindSettingsManager(mojo::MakeRequest(&settings_manager_)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h index 8891f4e53d7..067eae00af2 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h @@ -49,7 +49,7 @@ class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler, bool pending_hotword_update_ = false; - base::WeakPtrFactory<GoogleAssistantHandler> weak_factory_; + base::WeakPtrFactory<GoogleAssistantHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(GoogleAssistantHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc index 6d0b2214df2..883457370ee 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc @@ -14,14 +14,13 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" +#include "chromeos/network/network_connect.h" #include "chromeos/network/network_event_log.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "components/arc/arc_service_manager.h" -#include "components/arc/common/net.mojom.h" -#include "components/arc/metrics/arc_metrics_constants.h" +#include "components/arc/mojom/net.mojom.h" #include "components/arc/session/arc_bridge_service.h" -#include "components/arc/session/connection_holder.h" #include "components/onc/onc_constants.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -36,8 +35,7 @@ namespace { const char kAddThirdPartyVpnMessage[] = "addThirdPartyVpn"; const char kConfigureThirdPartyVpnMessage[] = "configureThirdPartyVpn"; -const char kRequestArcVpnProviders[] = "requestArcVpnProviders"; -const char kSendArcVpnProviders[] = "sendArcVpnProviders"; +const char kShowCellularSetupUI[] = "showCellularSetupUI"; const char kRequestGmsCoreNotificationsDisabledDeviceNames[] = "requestGmsCoreNotificationsDisabledDeviceNames"; const char kSendGmsCoreNotificationsDisabledDeviceNames[] = @@ -48,18 +46,6 @@ Profile* GetProfileForPrimaryUser() { user_manager::UserManager::Get()->GetPrimaryUser()); } -std::unique_ptr<base::DictionaryValue> ArcVpnProviderToValue( - const app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) { - std::unique_ptr<base::DictionaryValue> serialized_entry = - std::make_unique<base::DictionaryValue>(); - serialized_entry->SetString("PackageName", arc_vpn_provider->package_name); - serialized_entry->SetString("ProviderName", arc_vpn_provider->app_name); - serialized_entry->SetString("AppID", arc_vpn_provider->app_id); - serialized_entry->SetDouble("LastLaunchTime", - arc_vpn_provider->last_launch_time.ToDoubleT()); - return serialized_entry; -} - } // namespace namespace settings { @@ -67,10 +53,6 @@ namespace settings { InternetHandler::InternetHandler(Profile* profile) : profile_(profile) { DCHECK(profile_); - arc_vpn_provider_manager_ = app_list::ArcVpnProviderManager::Get(profile_); - if (arc_vpn_provider_manager_) - arc_vpn_provider_manager_->AddObserver(this); - TetherService* tether_service = TetherService::Get(profile); gms_core_notifications_state_tracker_ = tether_service ? tether_service->GetGmsCoreNotificationsStateTracker() @@ -80,8 +62,6 @@ InternetHandler::InternetHandler(Profile* profile) : profile_(profile) { } InternetHandler::~InternetHandler() { - if (arc_vpn_provider_manager_) - arc_vpn_provider_manager_->RemoveObserver(this); if (gms_core_notifications_state_tracker_) gms_core_notifications_state_tracker_->RemoveObserver(this); } @@ -96,41 +76,20 @@ void InternetHandler::RegisterMessages() { base::BindRepeating(&InternetHandler::ConfigureThirdPartyVpn, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kRequestArcVpnProviders, - base::BindRepeating(&InternetHandler::RequestArcVpnProviders, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( kRequestGmsCoreNotificationsDisabledDeviceNames, base::BindRepeating( &InternetHandler::RequestGmsCoreNotificationsDisabledDeviceNames, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kShowCellularSetupUI, + base::BindRepeating(&InternetHandler::ShowCellularSetupUI, + base::Unretained(this))); } void InternetHandler::OnJavascriptAllowed() {} void InternetHandler::OnJavascriptDisallowed() {} -void InternetHandler::OnArcVpnProviderRemoved(const std::string& package_name) { - if (arc_vpn_providers_.find(package_name) == arc_vpn_providers_.end()) - return; - arc_vpn_providers_.erase(package_name); - SendArcVpnProviders(); -} - -void InternetHandler::OnArcVpnProvidersRefreshed( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers) { - SetArcVpnProviders(arc_vpn_providers); -} - -void InternetHandler::OnArcVpnProviderUpdated( - app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) { - arc_vpn_providers_[arc_vpn_provider->package_name] = - ArcVpnProviderToValue(arc_vpn_provider); - SendArcVpnProviders(); -} - void InternetHandler::OnGmsCoreNotificationStateChanged() { SetGmsCoreNotificationsDisabledDeviceNames(); } @@ -213,41 +172,19 @@ void InternetHandler::ConfigureThirdPartyVpn(const base::ListValue* args) { << network->GetVpnProviderType() << " For: " << guid; } -void InternetHandler::RequestArcVpnProviders(const base::ListValue* args) { - if (!arc_vpn_provider_manager_) - return; - - AllowJavascript(); - SetArcVpnProviders(arc_vpn_provider_manager_->GetArcVpnProviders()); -} - void InternetHandler::RequestGmsCoreNotificationsDisabledDeviceNames( const base::ListValue* args) { AllowJavascript(); SetGmsCoreNotificationsDisabledDeviceNames(); } -void InternetHandler::SetArcVpnProviders( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers) { - arc_vpn_providers_.clear(); - for (const auto& arc_vpn_provider : arc_vpn_providers) { - arc_vpn_providers_[arc_vpn_provider->package_name] = - ArcVpnProviderToValue(arc_vpn_provider.get()); - } - SendArcVpnProviders(); -} - -void InternetHandler::SendArcVpnProviders() { - if (!IsJavascriptAllowed()) +void InternetHandler::ShowCellularSetupUI(const base::ListValue* args) { + std::string guid; + if (args->GetSize() < 1 || !args->GetString(0, &guid)) { + NOTREACHED() << "Invalid args for: " << kConfigureThirdPartyVpnMessage; return; - - base::ListValue arc_vpn_providers_value; - for (const auto& iter : arc_vpn_providers_) { - arc_vpn_providers_value.GetList().push_back(iter.second->Clone()); } - FireWebUIListener(kSendArcVpnProviders, arc_vpn_providers_value); + chromeos::NetworkConnect::Get()->ShowMobileSetup(guid); } void InternetHandler::SetGmsCoreNotificationsDisabledDeviceNames() { diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h index 31ed7c90e43..89f10828b9a 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_handler.h @@ -8,7 +8,6 @@ #include <memory> #include "base/macros.h" -#include "chrome/browser/ui/app_list/arc/arc_vpn_provider_manager.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chromeos/components/tether/gms_core_notifications_state_tracker.h" #include "ui/gfx/native_widget_types.h" @@ -25,8 +24,7 @@ namespace settings { // Chrome OS Internet settings page UI handler. class InternetHandler - : public app_list::ArcVpnProviderManager::Observer, - public chromeos::tether::GmsCoreNotificationsStateTracker::Observer, + : public chromeos::tether::GmsCoreNotificationsStateTracker::Observer, public ::settings::SettingsPageUIHandler { public: explicit InternetHandler(Profile* profile); @@ -37,15 +35,6 @@ class InternetHandler void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; - // app_list::ArcVpnProviderManager::Observer: - void OnArcVpnProvidersRefreshed( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers) override; - void OnArcVpnProviderRemoved(const std::string& package_name) override; - void OnArcVpnProviderUpdated(app_list::ArcVpnProviderManager::ArcVpnProvider* - arc_vpn_provider) override; - // chromeos::tether::GmsCoreNotificationsStateTracker::Observer: void OnGmsCoreNotificationStateChanged() override; @@ -55,18 +44,9 @@ class InternetHandler // Settings JS handlers. void AddThirdPartyVpn(const base::ListValue* args); void ConfigureThirdPartyVpn(const base::ListValue* args); - void RequestArcVpnProviders(const base::ListValue* args); void RequestGmsCoreNotificationsDisabledDeviceNames( const base::ListValue* args); - - // Sets list of Arc Vpn providers. - void SetArcVpnProviders( - const std::vector< - std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& - arc_vpn_providers); - - // Sends list of Arc Vpn providers to Chrome://settings. - void SendArcVpnProviders(); + void ShowCellularSetupUI(const base::ListValue* args); // Sets list of names of devices whose "Google Play Services" notifications // are disabled. @@ -81,17 +61,10 @@ class InternetHandler chromeos::tether::GmsCoreNotificationsStateTracker* gms_core_notifications_state_tracker); - std::map<std::string, std::unique_ptr<base::DictionaryValue>> - arc_vpn_providers_; - std::vector<std::unique_ptr<base::Value>> device_names_without_notifications_; Profile* const profile_; - // |arc_vpn_provider_manager_| and |gms_core_notifications_state_tracker_| are - // provided by BrowserContextKeyedServices which are guaranteed to outlive - // WebUIMessageHandlers. - app_list::ArcVpnProviderManager* arc_vpn_provider_manager_; chromeos::tether::GmsCoreNotificationsStateTracker* gms_core_notifications_state_tracker_; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc index fdf98ee2cf5..d6125af737b 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc @@ -22,7 +22,7 @@ namespace chromeos { namespace settings { KerberosAccountsHandler::KerberosAccountsHandler() - : credentials_manager_observer_(this), weak_factory_(this) {} + : credentials_manager_observer_(this) {} KerberosAccountsHandler::~KerberosAccountsHandler() = default; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h index 78493fb26a9..296cf45bb46 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h @@ -79,7 +79,7 @@ class KerberosAccountsHandler : public ::settings::SettingsPageUIHandler, KerberosCredentialsManager::Observer> credentials_manager_observer_; - base::WeakPtrFactory<KerberosAccountsHandler> weak_factory_; + base::WeakPtrFactory<KerberosAccountsHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(KerberosAccountsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc index 8d03f47642a..19977ff73a7 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.cc @@ -62,9 +62,8 @@ MultideviceHandler::MultideviceHandler( android_sms_app_manager_(android_sms_app_manager), multidevice_setup_observer_(this), android_sms_pairing_state_tracker_observer_(this), - android_sms_app_manager_observer_(this), - callback_weak_ptr_factory_(this) { - RegisterPrefChangeListeners(); + android_sms_app_manager_observer_(this) { + pref_change_registrar_.Init(prefs_); } MultideviceHandler::~MultideviceHandler() {} @@ -123,9 +122,22 @@ void MultideviceHandler::OnJavascriptAllowed() { if (android_sms_app_manager_) android_sms_app_manager_observer_.Add(android_sms_app_manager_); + + pref_change_registrar_.Add( + proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled, + base::BindRepeating( + &MultideviceHandler::NotifySmartLockSignInEnabledChanged, + base::Unretained(this))); + pref_change_registrar_.Add( + multidevice_setup::kSmartLockSigninAllowedPrefName, + base::BindRepeating( + &MultideviceHandler::NotifySmartLockSignInAllowedChanged, + base::Unretained(this))); } void MultideviceHandler::OnJavascriptDisallowed() { + pref_change_registrar_.RemoveAll(); + if (multidevice_setup_client_) multidevice_setup_observer_.Remove(multidevice_setup_client_); @@ -377,23 +389,7 @@ MultideviceHandler::GeneratePageContentDataDictionary() { return page_content_dictionary; } -void MultideviceHandler::RegisterPrefChangeListeners() { - pref_change_registrar_.Init(prefs_); - pref_change_registrar_.Add( - proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled, - base::BindRepeating( - &MultideviceHandler::NotifySmartLockSignInEnabledChanged, - base::Unretained(this))); - pref_change_registrar_.Add( - multidevice_setup::kSmartLockSigninAllowedPrefName, - base::BindRepeating( - &MultideviceHandler::NotifySmartLockSignInAllowedChanged, - base::Unretained(this))); -} - void MultideviceHandler::NotifySmartLockSignInEnabledChanged() { - AllowJavascript(); - bool sign_in_enabled = prefs_->GetBoolean( proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled); FireWebUIListener("smart-lock-signin-enabled-changed", diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h index efb5ac7c6e9..8ee0b692ac1 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h @@ -82,7 +82,6 @@ class MultideviceHandler void OnSetFeatureStateEnabledResult(const std::string& js_callback_id, bool success); - void RegisterPrefChangeListeners(); void NotifySmartLockSignInEnabledChanged(); void NotifySmartLockSignInAllowedChanged(); // Generate android sms info dictionary containing the messages for web @@ -126,7 +125,7 @@ class MultideviceHandler android_sms_app_manager_observer_; // Used to cancel callbacks when JavaScript becomes disallowed. - base::WeakPtrFactory<MultideviceHandler> callback_weak_ptr_factory_; + base::WeakPtrFactory<MultideviceHandler> callback_weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MultideviceHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc index 8af51c05725..e0efafd8f75 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_handler_unittest.cc @@ -124,7 +124,7 @@ class MultideviceHandlerTest : public testing::Test { fake_android_sms_app_manager_ = std::make_unique<android_sms::FakeAndroidSmsAppManager>(); - prefs_.reset(new TestingPrefServiceSimple()); + prefs_ = std::make_unique<TestingPrefServiceSimple>(); handler_ = std::make_unique<TestMultideviceHandler>( prefs_.get(), fake_multidevice_setup_client_.get(), diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc index d01be34282e..a0fd1fe87ff 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc @@ -11,15 +11,21 @@ #include <utility> #include <vector> +#include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" +#include "base/bind.h" +#include "base/feature_list.h" #include "build/build_config.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "chrome/browser/ui/webui/app_management/app_management_page_handler.h" #include "chrome/browser/ui/webui/managed_ui_handler.h" #include "chrome/browser/ui/webui/metrics_handler.h" #include "chrome/browser/ui/webui/plural_string_handler.h" #include "chrome/browser/ui/webui/settings/about_handler.h" #include "chrome/browser/ui/webui/settings/accessibility_main_handler.h" -#include "chrome/browser/ui/webui/settings/appearance_handler.h" #include "chrome/browser/ui/webui/settings/browser_lifetime_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" #include "chrome/browser/ui/webui/settings/downloads_handler.h" #include "chrome/browser/ui/webui/settings/extension_control_handler.h" #include "chrome/browser/ui/webui/settings/languages_handler.h" @@ -33,22 +39,25 @@ #include "chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h" #include "chrome/browser/ui/webui/settings/settings_ui.h" #include "chrome/browser/web_applications/system_web_app_manager.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/os_settings_resources.h" #include "chrome/grit/os_settings_resources_map.h" -#include "chromeos/services/network_config/public/mojom/constants.mojom.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/unified_consent/feature.h" #include "content/public/browser/web_ui_data_source.h" -#include "services/service_manager/public/cpp/connector.h" namespace chromeos { namespace settings { OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) - : ui::MojoWebUIController(web_ui, /*enable_chrome_send =*/true) { + : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true), + webui_load_timer_(web_ui->GetWebContents(), + "ChromeOS.Settings.LoadDocumentTime", + "ChromeOS.Settings.LoadCompletedTime") { Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIOSSettingsHost); @@ -62,8 +71,9 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) // page_visibility.js). html_source->AddBoolean("showOSSettings", true); - AddSettingsPageUIHandler( - std::make_unique<::settings::AppearanceHandler>(web_ui)); + html_source->AddBoolean( + "showParentalControls", + chromeos::settings::ShouldShowParentalControls(profile)); AddSettingsPageUIHandler( std::make_unique<::settings::AccessibilityMainHandler>()); @@ -86,10 +96,21 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) std::make_unique<::settings::ProtocolHandlersHandler>()); AddSettingsPageUIHandler( std::make_unique<::settings::SearchEnginesHandler>(profile)); + AddSettingsPageUIHandler( + std::make_unique<chromeos::settings::WallpaperHandler>(web_ui)); html_source->AddBoolean("unifiedConsentEnabled", unified_consent::IsUnifiedConsentFeatureEnabled()); + html_source->AddBoolean( + "showApps", base::FeatureList::IsEnabled(features::kAppManagement)); + +#if defined(OS_CHROMEOS) + html_source->AddBoolean( + "isSupportedArcVersion", + AppManagementPageHandler::IsCurrentArcVersionSupported(profile)); +#endif // OS_CHROMEOS + AddSettingsPageUIHandler( base::WrapUnique(::settings::AboutHandler::Create(html_source, profile))); AddSettingsPageUIHandler(base::WrapUnique( @@ -122,6 +143,17 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) html_source->SetDefaultResource(IDR_OS_SETTINGS_SETTINGS_HTML); #endif + html_source->AddResourcePath("app-management/app_management.mojom-lite.js", + IDR_APP_MANAGEMENT_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/types.mojom-lite.js", + IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/bitmap.mojom-lite.js", + IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/image.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS); + html_source->AddResourcePath("app-management/image_info.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); + ::settings::AddLocalizedStrings(html_source, profile); auto plural_string_handler = std::make_unique<PluralStringHandler>(); @@ -136,6 +168,10 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) AddHandlerToRegistry(base::BindRepeating(&OSSettingsUI::BindCrosNetworkConfig, base::Unretained(this))); + + AddHandlerToRegistry( + base::BindRepeating(&OSSettingsUI::BindAppManagementPageHandlerFactory, + base::Unretained(this))); } OSSettingsUI::~OSSettingsUI() = default; @@ -148,9 +184,17 @@ void OSSettingsUI::AddSettingsPageUIHandler( void OSSettingsUI::BindCrosNetworkConfig( network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(network_config::mojom::kServiceName, std::move(request)); + ash::GetNetworkConfigService(std::move(request)); +} + +void OSSettingsUI::BindAppManagementPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request) { + if (!app_management_page_handler_factory_) { + app_management_page_handler_factory_ = + std::make_unique<AppManagementPageHandlerFactory>( + Profile::FromWebUI(web_ui())); + } + app_management_page_handler_factory_->Bind(std::move(request)); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h index 4e600afc38b..63131cfb6f6 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h @@ -8,8 +8,10 @@ #include <memory> #include "base/macros.h" -#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" -#include "content/public/browser/web_ui_controller.h" +#include "chrome/browser/ui/webui/app_management/app_management.mojom-forward.h" +#include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h" +#include "chrome/browser/ui/webui/webui_load_timer.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom-forward.h" #include "ui/webui/mojo_web_ui_controller.h" namespace content { @@ -30,8 +32,13 @@ class OSSettingsUI : public ui::MojoWebUIController { std::unique_ptr<content::WebUIMessageHandler> handler); void BindCrosNetworkConfig( network_config::mojom::CrosNetworkConfigRequest request); + void BindAppManagementPageHandlerFactory( + app_management::mojom::PageHandlerFactoryRequest request); - // TODO(crbug/950007): Create load histograms and embed WebuiLoadTimer. + WebuiLoadTimer webui_load_timer_; + + std::unique_ptr<AppManagementPageHandlerFactory> + app_management_page_handler_factory_; DISALLOW_COPY_AND_ASSIGN(OSSettingsUI); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc index b76ceac4ab6..19182163f23 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc @@ -9,8 +9,9 @@ #include "base/values.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" -#include "chrome/browser/chromeos/arc/arc_session_manager.h" +#include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" @@ -18,7 +19,7 @@ #include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "chrome/services/app_service/public/cpp/app_update.h" #include "chrome/services/app_service/public/mojom/types.mojom.h" -#include "components/arc/arc_util.h" +#include "chromeos/constants/chromeos_features.h" #include "ui/base/page_transition_types.h" #include "ui/base/window_open_disposition.h" #include "ui/display/types/display_constants.h" @@ -81,19 +82,32 @@ void ParentalControlsHandler::HandleLaunchFamilyLinkSettings( proxy->Launch(app_id, ui::EventFlags::EF_NONE, apps::mojom::LaunchSource::kFromParentalControls, display::kDefaultDisplayId); - } else if (arc::IsArcAvailable() && - arc::ArcSessionManager::Get()->IsAllowed()) { - // No FLH app installed, but ARC is enabled so launch Play Store - // to FLH app install page. - arc::LaunchPlayStoreWithUrl(kFamilyLinkChildHelperAppPlayStoreURL); - } else { - // As a last resort, launch browser to the family link site. - NavigateParams params(profile_, GURL(kFamilyLinkSiteURL), - ui::PAGE_TRANSITION_FROM_API); - params.disposition = WindowOpenDisposition::NEW_WINDOW; - params.window_action = NavigateParams::SHOW_WINDOW; - Navigate(¶ms); + return; } + // No FLH app installed, so try to launch Play Store to FLH app install page. + // If there is no Play Store available LaunchPlayStoreWithUrl() will return + // false. + if (arc::LaunchPlayStoreWithUrl(kFamilyLinkChildHelperAppPlayStoreURL)) { + return; + } + // As a last resort, launch browser to the family link site. + NavigateParams params(profile_, GURL(kFamilyLinkSiteURL), + ui::PAGE_TRANSITION_FROM_API); + params.disposition = WindowOpenDisposition::NEW_WINDOW; + params.window_action = NavigateParams::SHOW_WINDOW; + Navigate(¶ms); +} + +bool ShouldShowParentalControls(Profile* profile) { + // Show Parental controls for regular and child accounts that are the + // primary profile. Do not show it to any secondary profiles, managed + // accounts that aren't child accounts (i.e. enterprise and EDU accounts), + // OTR accounts, or legacy supervised user accounts. + return chromeos::features::IsParentalControlsSettingsEnabled() && + profile == ProfileManager::GetPrimaryUserProfile() && + !profile->IsLegacySupervised() && !profile->IsGuestSession() && + (profile->IsChild() || + !profile->GetProfilePolicyConnector()->IsManaged()); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h index cb498d3db33..517bc1b50fd 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h @@ -37,6 +37,9 @@ class ParentalControlsHandler : public ::settings::SettingsPageUIHandler { DISALLOW_COPY_AND_ASSIGN(ParentalControlsHandler); }; +// Indicates whether parental controls should be shown in the settings UI. +bool ShouldShowParentalControls(Profile* profile); + } // namespace settings } // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc index 09518e994a3..715782b0b11 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc @@ -18,8 +18,7 @@ namespace chromeos { namespace settings { -PluginVmHandler::PluginVmHandler(Profile* profile) - : profile_(profile), weak_ptr_factory_(this) {} +PluginVmHandler::PluginVmHandler(Profile* profile) : profile_(profile) {} PluginVmHandler::~PluginVmHandler() = default; @@ -59,7 +58,8 @@ void PluginVmHandler::HandleRemovePluginVmSharedPath( vm_name, base::FilePath(path), /*unpersist=*/true, base::BindOnce( - [](const std::string& path, bool result, std::string failure_reason) { + [](const std::string& path, bool result, + const std::string& failure_reason) { if (!result) { LOG(ERROR) << "Error unsharing " << path << ": " << failure_reason; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h index 64e9d850299..d57b34da1db 100644 --- a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h @@ -35,7 +35,7 @@ class PluginVmHandler : public ::settings::SettingsPageUIHandler { Profile* profile_; // weak_ptr_factory_ should always be last member. - base::WeakPtrFactory<PluginVmHandler> weak_ptr_factory_; + base::WeakPtrFactory<PluginVmHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PluginVmHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.cc new file mode 100644 index 00000000000..5f169f010f8 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.cc @@ -0,0 +1,67 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" + +#include "base/bind.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/ash/wallpaper_controller_client.h" +#include "content/public/browser/web_ui.h" + +namespace chromeos { +namespace settings { + +WallpaperHandler::WallpaperHandler(content::WebUI* webui) + : profile_(Profile::FromWebUI(webui)) {} + +WallpaperHandler::~WallpaperHandler() = default; + +void WallpaperHandler::OnJavascriptAllowed() {} +void WallpaperHandler::OnJavascriptDisallowed() {} + +void WallpaperHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "openWallpaperManager", + base::BindRepeating(&WallpaperHandler::HandleOpenWallpaperManager, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "isWallpaperSettingVisible", + base::BindRepeating(&WallpaperHandler::HandleIsWallpaperSettingVisible, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "isWallpaperPolicyControlled", + base::BindRepeating(&WallpaperHandler::HandleIsWallpaperPolicyControlled, + base::Unretained(this))); +} + +void WallpaperHandler::HandleIsWallpaperSettingVisible( + const base::ListValue* args) { + CHECK_EQ(args->GetSize(), 1U); + ResolveCallback( + args->GetList()[0], + WallpaperControllerClient::Get()->ShouldShowWallpaperSetting()); +} + +void WallpaperHandler::HandleIsWallpaperPolicyControlled( + const base::ListValue* args) { + CHECK_EQ(args->GetSize(), 1U); + bool result = WallpaperControllerClient::Get() + ->IsActiveUserWallpaperControlledByPolicy(); + ResolveCallback(args->GetList()[0], result); +} + +void WallpaperHandler::HandleOpenWallpaperManager(const base::ListValue* args) { + WallpaperControllerClient::Get()->OpenWallpaperPickerIfAllowed(); +} + +void WallpaperHandler::ResolveCallback(const base::Value& callback_id, + bool result) { + AllowJavascript(); + ResolveJavascriptCallback(callback_id, base::Value(result)); +} + +} // namespace settings +} // namespace chromeos diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h new file mode 100644 index 00000000000..6e0c811b9e0 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h @@ -0,0 +1,56 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_WALLPAPER_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_WALLPAPER_HANDLER_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" + +namespace base { +class ListValue; +} + +namespace content { +class WebUI; +} + +class Profile; + +namespace chromeos { +namespace settings { + +// Chrome "Personalization" settings page UI handler. +class WallpaperHandler : public ::settings::SettingsPageUIHandler { + public: + explicit WallpaperHandler(content::WebUI* webui); + ~WallpaperHandler() override; + + // SettingsPageUIHandler implementation. + void RegisterMessages() override; + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + private: + // Whether the wallpaper setting should be shown. + void HandleIsWallpaperSettingVisible(const base::ListValue* args); + + // Whether the wallpaper is policy controlled. + void HandleIsWallpaperPolicyControlled(const base::ListValue* args); + + // Open the wallpaper manager app. + void HandleOpenWallpaperManager(const base::ListValue* args); + + // Helper function to resolve the Javascript callback. + void ResolveCallback(const base::Value& callback_id, bool result); + + Profile* const profile_; + + DISALLOW_COPY_AND_ASSIGN(WallpaperHandler); +}; + +} // namespace settings +} // namespace chromeos + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_WALLPAPER_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc index 7e7628fb021..80ea9d4632c 100644 --- a/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/downloads_handler_unittest.cc @@ -13,8 +13,8 @@ #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_download_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -74,7 +74,7 @@ class DownloadsHandlerTest : public testing::Test { DownloadsHandler* handler() { return &handler_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; content::TestWebUI test_web_ui_; TestingProfile profile_; diff --git a/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc index d5adb2866a2..c33bd5da63e 100644 --- a/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/metrics_reporting_handler_unittest.cc @@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) +#include "build/branding_buildflags.h" + +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && !defined(OS_CHROMEOS) #include "chrome/browser/ui/webui/settings/metrics_reporting_handler.h" @@ -18,7 +20,7 @@ #include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,10 +36,10 @@ class MetricsReportingHandlerTest : public testing::Test { public: MetricsReportingHandlerTest() { // Local state must be set up before |handler_|. - local_state_.reset(new ScopedTestingLocalState( - TestingBrowserProcess::GetGlobal())); + local_state_ = std::make_unique<ScopedTestingLocalState>( + TestingBrowserProcess::GetGlobal()); - handler_.reset(new TestingMetricsReportingHandler); + handler_ = std::make_unique<TestingMetricsReportingHandler>(); handler_->set_web_ui(&test_web_ui_); EXPECT_CALL(provider_, IsInitializationComplete(testing::_)).WillRepeatedly( @@ -75,7 +77,7 @@ class MetricsReportingHandlerTest : public testing::Test { policy::MockConfigurationPolicyProvider* provider() { return &provider_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; content::TestWebUI test_web_ui_; std::unique_ptr<ScopedTestingLocalState> local_state_; std::unique_ptr<TestingMetricsReportingHandler> handler_; @@ -124,4 +126,4 @@ TEST_F(MetricsReportingHandlerTest, PolicyChangesNotifyPage) { } // namespace settings -#endif // defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && !defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc index 6a2dd312163..2b60755b794 100644 --- a/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/on_startup_handler_unittest.cc @@ -17,7 +17,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -58,7 +58,7 @@ class OnStartupHandlerTest : public testing::Test { profile_ = profile_manager_.CreateTestingProfile("Profile 1"); #endif - handler_.reset(new TestOnStartupHandler(profile_)); + handler_ = std::make_unique<TestOnStartupHandler>(profile_); handler_->set_web_ui(&web_ui_); } @@ -67,7 +67,7 @@ class OnStartupHandlerTest : public testing::Test { content::TestWebUI* web_ui() { return &web_ui_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; std::unique_ptr<TestOnStartupHandler> handler_; Profile* profile_; diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc index 3ea106d0157..5d7331dbf92 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc @@ -36,7 +36,6 @@ #include "components/autofill/core/common/autofill_prefs.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/public/base/signin_metrics.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/identity_manager/accounts_mutator.h" @@ -221,6 +220,7 @@ base::string16 GetEnterPassphraseBody(syncer::PassphraseType passphrase_type, base::TimeFormatShortDate(passphrase_time)); case syncer::PassphraseType::IMPLICIT_PASSPHRASE: case syncer::PassphraseType::KEYSTORE_PASSPHRASE: + case syncer::PassphraseType::TRUSTED_VAULT_PASSPHRASE: case syncer::PassphraseType::PASSPHRASE_TYPE_SIZE: break; } @@ -243,6 +243,7 @@ base::string16 GetFullEncryptionBody(syncer::PassphraseType passphrase_type, base::TimeFormatShortDate(passphrase_time)); case syncer::PassphraseType::IMPLICIT_PASSPHRASE: case syncer::PassphraseType::KEYSTORE_PASSPHRASE: + case syncer::PassphraseType::TRUSTED_VAULT_PASSPHRASE: case syncer::PassphraseType::PASSPHRASE_TYPE_SIZE: break; } @@ -303,6 +304,10 @@ void PeopleHandler::RegisterMessages() { "SyncSetupGetSyncStatus", base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncPrefsDispatch", + base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "AttemptUserExit", @@ -404,13 +409,11 @@ void PeopleHandler::DisplayGaiaLoginInNewTabOrWindow( SigninErrorController* error_controller = SigninErrorControllerFactory::GetForProfile(browser->profile()); DCHECK(error_controller->HasError()); - browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH, - signin::ManageAccountsParams(), access_point, false); + browser->window()->ShowAvatarBubbleFromAvatarButton( + BrowserWindow::AVATAR_BUBBLE_MODE_REAUTH, access_point, false); } else { browser->window()->ShowAvatarBubbleFromAvatarButton( - BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, - signin::ManageAccountsParams(), access_point, false); + BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN, access_point, false); } } #endif @@ -426,7 +429,7 @@ void PeopleHandler::DisplaySpinner() { const int kTimeoutSec = 30; DCHECK(!engine_start_timer_); - engine_start_timer_.reset(new base::OneShotTimer()); + engine_start_timer_ = std::make_unique<base::OneShotTimer>(); engine_start_timer_->Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutSec), this, &PeopleHandler::DisplayTimeout); @@ -554,7 +557,7 @@ base::Value PeopleHandler::GetStoredAccountsList() { // account. auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_); base::Optional<AccountInfo> primary_account_info = - identity_manager->FindExtendedAccountInfoForAccount( + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager->GetPrimaryAccountInfo()); if (primary_account_info.has_value()) accounts_list.push_back(GetAccountValue(primary_account_info.value())); @@ -575,7 +578,7 @@ void PeopleHandler::HandleStartSyncingWithEmail(const base::ListValue* args) { base::Optional<AccountInfo> maybe_account = IdentityManagerFactory::GetForProfile(profile_) - ->FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + ->FindExtendedAccountInfoForAccountWithRefreshTokenByEmailAddress( email->GetString()); signin_ui_util::EnableSyncFromPromo( @@ -850,6 +853,11 @@ void PeopleHandler::HandleGetSyncStatus(const base::ListValue* args) { ResolveJavascriptCallback(*callback_id, *GetSyncStatusDictionary()); } +void PeopleHandler::HandleSyncPrefsDispatch(const base::ListValue* args) { + AllowJavascript(); + PushSyncPrefs(); +} + void PeopleHandler::CloseSyncSetup() { // Stop a timer to handle timeout in waiting for checking network connection. engine_start_timer_.reset(); @@ -1037,9 +1045,8 @@ std::unique_ptr<base::DictionaryValue> PeopleHandler::GetSyncStatusDictionary() "disabled", !service || disallowed_by_policy || !service->GetUserSettings()->IsSyncAllowedByPlatform()); sync_status->SetBoolean("signedIn", identity_manager->HasPrimaryAccount()); - sync_status->SetString( - "signedInUsername", - signin_ui_util::GetAuthenticatedUsername(identity_manager)); + sync_status->SetString("signedInUsername", + signin_ui_util::GetAuthenticatedUsername(profile_)); sync_status->SetBoolean("hasUnrecoverableError", service && service->HasUnrecoverableError()); return sync_status; diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h index 83cd8916760..51e9195e619 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h @@ -176,6 +176,7 @@ class PeopleHandler : public SettingsPageUIHandler, void HandleSetEncryption(const base::ListValue* args); void HandleShowSetupUI(const base::ListValue* args); void HandleAttemptUserExit(const base::ListValue* args); + void HandleSyncPrefsDispatch(const base::ListValue* args); #if defined(OS_CHROMEOS) void HandleRequestPinLoginState(const base::ListValue* args); #endif 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 87b349ecacc..1a327ed2a6f 100644 --- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc @@ -46,8 +46,8 @@ #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/browser_task_environment.h" #include "content/public/test/navigation_simulator.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" @@ -109,6 +109,8 @@ std::string GetConfiguration(const base::DictionaryValue* extra_values, types.Has(syncer::UserSelectableType::kExtensions)); result.SetBoolean("passwordsSynced", types.Has(syncer::UserSelectableType::kPasswords)); + result.SetBoolean("wifiConfigurationsSynced", + types.Has(syncer::UserSelectableType::kWifiConfigurations)); result.SetBoolean("preferencesSynced", types.Has(syncer::UserSelectableType::kPreferences)); result.SetBoolean("tabsSynced", types.Has(syncer::UserSelectableType::kTabs)); @@ -164,6 +166,8 @@ void CheckConfigDataTypeArguments(const base::DictionaryValue* dictionary, types.Has(syncer::UserSelectableType::kExtensions)); CheckBool(dictionary, "passwordsSynced", types.Has(syncer::UserSelectableType::kPasswords)); + CheckBool(dictionary, "wifiConfigurationsSynced", + types.Has(syncer::UserSelectableType::kWifiConfigurations)); CheckBool(dictionary, "preferencesSynced", types.Has(syncer::UserSelectableType::kPreferences)); CheckBool(dictionary, "tabsSynced", @@ -249,7 +253,7 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { &PeopleHandlerTest::OnSetupInProgressHandleDestroyed, base::Unretained(this)))))); - handler_.reset(new TestingPeopleHandler(&web_ui_, profile())); + handler_ = std::make_unique<TestingPeopleHandler>(&web_ui_, profile()); handler_->AllowJavascript(); web_ui_.set_web_contents(web_contents()); } @@ -262,12 +266,9 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness { ChromeRenderViewHostTestHarness::TearDown(); } - content::BrowserContext* CreateBrowserContext() override { - // Setup the profile. - std::unique_ptr<TestingProfile> profile = - IdentityTestEnvironmentProfileAdaptor:: - CreateProfileForIdentityTestEnvironment(); - return profile.release(); + TestingProfile::TestingFactories GetTestingFactories() const override { + return IdentityTestEnvironmentProfileAdaptor:: + GetIdentityTestEnvironmentFactories(); } // Setup the expectations for calls made when displaying the config page. @@ -1107,6 +1108,7 @@ TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) { CheckBool(dictionary, "bookmarksRegistered", true); CheckBool(dictionary, "extensionsRegistered", true); CheckBool(dictionary, "passwordsRegistered", true); + CheckBool(dictionary, "wifiConfigurationsRegistered", true); CheckBool(dictionary, "preferencesRegistered", true); CheckBool(dictionary, "tabsRegistered", true); CheckBool(dictionary, "themesRegistered", true); @@ -1402,7 +1404,7 @@ TEST_P(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList) { base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoFirstRun); ASSERT_FALSE(first_run::IsChromeFirstRun()); - content::TestBrowserThreadBundle test_browser_thread_bundle; + content::BrowserTaskEnvironment task_environment; // Decode test parameters. bool dice_enabled; diff --git a/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc index a5229444221..8bccab5cf80 100644 --- a/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc @@ -14,7 +14,7 @@ #include "chrome/test/base/testing_profile_manager.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "net/base/data_url.h" #include "testing/gtest/include/gtest/gtest.h" @@ -66,7 +66,7 @@ class ProfileInfoHandlerTest : public testing::Test { profile_ = profile_manager_.CreateTestingProfile("Profile 1"); #endif - handler_.reset(new TestProfileInfoHandler(profile_)); + handler_ = std::make_unique<TestProfileInfoHandler>(profile_); handler_->set_web_ui(&web_ui_); } @@ -101,7 +101,7 @@ class ProfileInfoHandlerTest : public testing::Test { TestProfileInfoHandler* handler() const { return handler_.get(); } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; content::TestWebUI web_ui_; 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 a1ef45f40ef..7dae9628108 100644 --- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc @@ -212,17 +212,17 @@ void ResetSettingsHandler::OnGetReportedSettingsDone(std::string callback_id) { void ResetSettingsHandler::OnShowResetProfileDialog( const base::ListValue* args) { if (!GetResetter()->IsActive()) { - setting_snapshot_.reset(new ResettableSettingsSnapshot(profile_)); + setting_snapshot_ = std::make_unique<ResettableSettingsSnapshot>(profile_); } if (brandcode_.empty()) return; - config_fetcher_.reset(new BrandcodeConfigFetcher( + config_fetcher_ = std::make_unique<BrandcodeConfigFetcher>( g_browser_process->system_network_context_manager() ->GetURLLoaderFactory(), base::Bind(&ResetSettingsHandler::OnSettingsFetched, base::Unretained(this)), - GURL("https://tools.google.com/service/update2"), brandcode_)); + GURL("https://tools.google.com/service/update2"), brandcode_); } void ResetSettingsHandler::OnHideResetProfileDialog( @@ -260,7 +260,7 @@ void ResetSettingsHandler::ResetProfile( // If failed to fetch BrandcodedDefaultSettings or this is an organic // installation, use default settings. if (!default_settings) - default_settings.reset(new BrandcodedDefaultSettings); + default_settings = std::make_unique<BrandcodedDefaultSettings>(); GetResetter()->Reset( ProfileResetter::ALL, std::move(default_settings), @@ -275,7 +275,7 @@ void ResetSettingsHandler::ResetProfile( ProfileResetter* ResetSettingsHandler::GetResetter() { if (!resetter_) - resetter_.reset(new ProfileResetter(profile_)); + resetter_ = std::make_unique<ProfileResetter>(profile_); return resetter_.get(); } diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc index 7c8f38e8be7..b21f85e169b 100644 --- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler_unittest.cc @@ -11,7 +11,7 @@ #include "chrome/browser/ui/webui/settings/reset_settings_handler.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -73,7 +73,8 @@ class ResetSettingsHandlerTest : public testing::Test { public: ResetSettingsHandlerTest() { google_brand::BrandForTesting brand_for_testing(""); - handler_.reset(new TestingResetSettingsHandler(&profile_, &web_ui_)); + handler_ = + std::make_unique<TestingResetSettingsHandler>(&profile_, &web_ui_); } TestingResetSettingsHandler* handler() { return handler_.get(); } @@ -81,7 +82,7 @@ class ResetSettingsHandlerTest : public testing::Test { private: // The order here matters. - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; content::TestWebUI web_ui_; std::unique_ptr<TestingResetSettingsHandler> handler_; diff --git a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc index 24247be5a14..37eab4887a8 100644 --- a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc @@ -195,8 +195,8 @@ SearchEnginesHandler::CreateDictionaryForEngine(int index, bool is_default) { "keyword", table_model->GetText(index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN)); Profile* profile = Profile::FromWebUI(web_ui()); - dict->SetString("url", template_url->url_ref().DisplayURL( - UIThreadSearchTermsData(profile))); + dict->SetString( + "url", template_url->url_ref().DisplayURL(UIThreadSearchTermsData())); dict->SetBoolean("urlLocked", template_url->prepopulate_id() > 0); GURL icon_url = template_url->favicon_url(); if (icon_url.is_valid()) @@ -284,10 +284,10 @@ void SearchEnginesHandler::HandleSearchEngineEditStarted( return; } - edit_controller_.reset(new EditSearchEngineController( + edit_controller_ = std::make_unique<EditSearchEngineController>( index == kNewSearchEngineIndex ? nullptr : list_controller_.GetTemplateURL(index), - this, Profile::FromWebUI(web_ui()))); + this, Profile::FromWebUI(web_ui())); } void SearchEnginesHandler::OnEditedKeyword(TemplateURL* template_url, diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc index d9c05922474..25dbe1f03e7 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc @@ -20,6 +20,7 @@ #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/same_site_data_remover.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_ui.h" @@ -130,6 +131,7 @@ void CookiesViewHandler::OnJavascriptAllowed() { } void CookiesViewHandler::OnJavascriptDisallowed() { + callback_weak_ptr_factory_.InvalidateWeakPtrs(); } void CookiesViewHandler::RegisterMessages() { @@ -164,6 +166,10 @@ void CookiesViewHandler::RegisterMessages() { base::BindRepeating(&CookiesViewHandler::HandleRemove, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "localData.removeThirdPartyCookies", + base::BindRepeating(&CookiesViewHandler::HandleRemoveThirdParty, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "localData.reload", base::BindRepeating(&CookiesViewHandler::HandleReloadCookies, base::Unretained(this))); @@ -244,6 +250,13 @@ void CookiesViewHandler::EnsureCookiesTreeModelCreated() { } } +void CookiesViewHandler::RecreateCookiesTreeModel() { + cookies_tree_model_.reset(); + filter_.clear(); + sorted_sites_.clear(); + EnsureCookiesTreeModelCreated(); +} + void CookiesViewHandler::HandleGetCookieDetails(const base::ListValue* args) { CHECK(request_.callback_id_.empty()); CHECK_EQ(2U, args->GetSize()); @@ -306,10 +319,7 @@ void CookiesViewHandler::HandleReloadCookies(const base::ListValue* args) { CHECK(args->GetString(0, &request_.callback_id_)); AllowJavascript(); - cookies_tree_model_.reset(); - filter_.clear(); - sorted_sites_.clear(); - EnsureCookiesTreeModelCreated(); + RecreateCookiesTreeModel(); } void CookiesViewHandler::HandleRemoveAll(const base::ListValue* args) { @@ -335,6 +345,20 @@ void CookiesViewHandler::HandleRemove(const base::ListValue* args) { } } +void CookiesViewHandler::HandleRemoveThirdParty(const base::ListValue* args) { + CHECK(request_.callback_id_.empty()); + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &request_.callback_id_)); + + AllowJavascript(); + Profile* profile = Profile::FromWebUI(web_ui()); + ClearSameSiteNoneData( + base::BindOnce(&CookiesViewHandler::RecreateCookiesTreeModel, + callback_weak_ptr_factory_.GetWeakPtr()), + profile, + /* clear_storage */ true); +} + void CookiesViewHandler::HandleRemoveShownItems(const base::ListValue* args) { CHECK_EQ(0U, args->GetSize()); diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h index 574978c9b97..d5a031bf16a 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h @@ -49,6 +49,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, // Creates the CookiesTreeModel if necessary. void EnsureCookiesTreeModelCreated(); + // Resets the CookiesTreeModel, the current |filter_|, and the site list. + void RecreateCookiesTreeModel(); + // Set |filter_| and get a portion (or all) of the list items. void HandleGetDisplayList(const base::ListValue* args); @@ -70,6 +73,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, // Remove selected sites data. void HandleRemove(const base::ListValue* args); + // Removes cookies and site data available in third-party contexts. + void HandleRemoveThirdParty(const base::ListValue* args); + // Get children nodes data and pass it to 'CookiesView.loadChildren' to // update the WebUI. void SendChildren(const CookieTreeNode* parent); @@ -111,6 +117,9 @@ class CookiesViewHandler : public SettingsPageUIHandler, std::unique_ptr<CookiesTreeModelUtil> model_util_; + // Used to cancel callbacks when JavaScript becomes disallowed. + base::WeakPtrFactory<CookiesViewHandler> callback_weak_ptr_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(CookiesViewHandler); }; 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 f546887fdfc..b2e78bd722b 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 @@ -147,7 +147,7 @@ void ImportDataHandler::InitializeDialog(const base::ListValue* args) { std::string callback_id; CHECK(args->GetString(0, &callback_id)); - importer_list_.reset(new ImporterList()); + importer_list_ = std::make_unique<ImporterList>(); importer_list_->DetectSourceProfiles( g_browser_process->GetApplicationLocale(), true, // include_interactive_profiles diff --git a/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 9dc2fca39cb..3ff5f45c78b 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc @@ -13,6 +13,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/win/windows_version.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/buildflag.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" @@ -40,6 +41,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_payments_features.h" +#include "components/browsing_data/core/features.h" #include "components/google/core/common/google_util.h" #include "components/omnibox/common/omnibox_features.h" #include "components/password_manager/core/browser/manage_passwords_referrer.h" @@ -59,12 +61,14 @@ #include "media/base/media_switches.h" #include "net/base/url_util.h" #include "services/device/public/cpp/device_features.h" +#include "third_party/blink/public/common/features.h" #include "ui/accessibility/accessibility_switches.h" +#include "ui/base/accelerators/accelerator.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_CHROMEOS) #include "ash/public/cpp/ash_switches.h" -#include "ash/public/interfaces/voice_interaction_controller.mojom.h" +#include "ash/public/mojom/voice_interaction_controller.mojom.h" #include "base/system/sys_info.h" #include "chrome/browser/chromeos/account_manager/account_manager_util.h" #include "chrome/browser/chromeos/arc/arc_util.h" @@ -81,6 +85,7 @@ #include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h" #include "chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.h" #include "chrome/common/pref_names.h" +#include "chrome/common/webui_url_constants.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/services/assistant/public/features.h" @@ -101,12 +106,12 @@ #include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" #include "device/fido/win/webauthn_api.h" -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) #include "base/metrics/field_trial_params.h" #include "base/strings/strcat.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "ui/base/resource/resource_bundle.h" -#endif // defined(GOOGLE_CHROME_BUILD) +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) #endif // defined(OS_WIN) #if defined(USE_NSS_CERTS) @@ -116,10 +121,6 @@ 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. -constexpr char kLocalizedStringsFile[] = "strings.js"; - #if defined(OS_CHROMEOS) // Generates a Google Help URL which includes a "board type" parameter. Some // help pages need to be adjusted depending on the type of CrOS device that is @@ -195,13 +196,17 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"moreFeaturesLinkDescription", IDS_SETTINGS_MORE_FEATURES_LINK_DESCRIPTION}, {"captionsTitle", IDS_SETTINGS_CAPTIONS}, + {"captionsSettings", IDS_SETTINGS_CAPTIONS_SETTINGS}, + {"captionsPreview", IDS_SETTINGS_CAPTIONS_PREVIEW}, {"captionsTextSize", IDS_SETTINGS_CAPTIONS_TEXT_SIZE}, {"captionsTextFont", IDS_SETTINGS_CAPTIONS_TEXT_FONT}, {"captionsTextColor", IDS_SETTINGS_CAPTIONS_TEXT_COLOR}, {"captionsTextOpacity", IDS_SETTINGS_CAPTIONS_TEXT_OPACITY}, {"captionsBackgroundOpacity", IDS_SETTINGS_CAPTIONS_BACKGROUND_OPACITY}, - {"captionsOpacityMin", IDS_SETTINGS_CAPTIONS_OPACITY_MIN}, - {"captionsOpacityMax", IDS_SETTINGS_CAPTIONS_OPACITY_MAX}, + {"captionsOpacityOpaque", IDS_SETTINGS_CAPTIONS_OPACITY_OPAQUE}, + {"captionsOpacitySemiTransparent", + IDS_SETTINGS_CAPTIONS_OPACITY_SEMI_TRANSPARENT}, + {"captionsOpacityTransparent", IDS_SETTINGS_CAPTIONS_OPACITY_TRANSPARENT}, {"captionsTextShadow", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW}, {"captionsTextShadowNone", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_NONE}, {"captionsTextShadowRaised", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_RAISED}, @@ -307,6 +312,8 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { {"switchAccessAutoScanLabel", IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_LABEL}, {"switchAccessAutoScanSpeedLabel", IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_SPEED_LABEL}, + {"switchAccessAutoScanKeyboardSpeedLabel", + IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_KEYBOARD_SPEED_LABEL}, {"durationInSeconds", IDS_SETTINGS_DURATION_IN_SECONDS}, {"manageAccessibilityFeatures", IDS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES}, @@ -396,6 +403,11 @@ void AddA11yStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean( "showExperimentalAccessibilitySwitchAccess", cmd.HasSwitch(::switches::kEnableExperimentalAccessibilitySwitchAccess)); + + html_source->AddBoolean( + "showExperimentalAccessibilitySwitchAccessImprovedTextInput", + cmd.HasSwitch( + ::switches::kEnableExperimentalAccessibilitySwitchAccessText)); #endif } @@ -403,7 +415,7 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kLocalizedStrings[] = { {"aboutProductLogoAlt", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT}, -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) {"aboutReportAnIssue", IDS_SETTINGS_ABOUT_PAGE_REPORT_AN_ISSUE}, #endif @@ -431,6 +443,8 @@ void AddAboutStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_ABOUT_PAGE_RELAUNCH_AND_POWERWASH}, {"aboutRollbackInProgress", IDS_SETTINGS_UPGRADE_ROLLBACK_IN_PROGRESS}, {"aboutRollbackSuccess", IDS_SETTINGS_UPGRADE_ROLLBACK_SUCCESS}, + {"aboutUpdateOsSettingsLink", + IDS_SETTINGS_ABOUT_SEE_OS_SETTINGS_FOR_UPDATE_MESSAGE}, {"aboutUpgradeUpdatingChannelSwitch", IDS_SETTINGS_UPGRADE_UPDATING_CHANNEL_SWITCH}, {"aboutUpgradeSuccessChannelSwitch", @@ -567,9 +581,6 @@ void AddCrostiniStrings(content::WebUIDataSource* html_source, html_source->AddBoolean( "showCrostiniExportImport", crostini::IsCrostiniExportImportUIAllowedForProfile(profile)); - html_source->AddBoolean( - "enableCrostiniUsbDeviceSupport", - base::FeatureList::IsEnabled(chromeos::features::kCrostiniUsbSupport)); } void AddPluginVmStrings(content::WebUIDataSource* html_source, @@ -622,13 +633,45 @@ void AddAndroidAppStrings(content::WebUIDataSource* html_source) { void AddAppsStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"appsPageTitle", IDS_SETTINGS_APPS_TITLE}, - {"manageYourApps", IDS_SETTINGS_APPS_LINK_TEXT}, - {"manageYourAppsSublabel", IDS_SETTINGS_APPS_LINK_SUBLABEL_TEXT}, + {"appManagementTitle", IDS_SETTINGS_APPS_LINK_TEXT}, }; AddLocalizedStringsBulk(html_source, localized_strings, base::size(localized_strings)); } + +void AddAppManagementStrings(content::WebUIDataSource* html_source) { + static constexpr LocalizedString localized_strings[] = { + {"appListTitle", IDS_APP_MANAGEMENT_APP_LIST_TITLE}, + {"appNoPermission", IDS_APPLICATION_INFO_APP_NO_PERMISSIONS_TEXT}, + {"camera", IDS_APP_MANAGEMENT_CAMERA}, + {"contacts", IDS_APP_MANAGEMENT_CONTACTS}, + {"controlledByPolicy", IDS_CONTROLLED_SETTING_POLICY}, + {"lessApps", IDS_APP_MANAGEMENT_LESS_APPS}, + {"location", IDS_APP_MANAGEMENT_LOCATION}, + {"microphone", IDS_APP_MANAGEMENT_MICROPHONE}, + {"moreApps", IDS_APP_MANAGEMENT_MORE_APPS}, + {"moreSettings", IDS_APP_MANAGEMENT_MORE_SETTINGS}, + {"notifications", IDS_APP_MANAGEMENT_NOTIFICATIONS}, + {"notificationSublabel", IDS_APP_MANAGEMENT_NOTIFICATIONS_SUBLABEL}, + {"openAndroidSettings", IDS_APP_MANAGEMENT_ANDROID_SETTINGS}, + {"openExtensionsSettings", IDS_APP_MANAGEMENT_EXTENSIONS_SETTINGS}, + {"openSiteSettings", IDS_APP_MANAGEMENT_SITE_SETTING}, + {"permissions", IDS_APP_MANAGEMENT_PERMISSIONS}, + {"pinControlledByPolicy", IDS_APP_MANAGEMENT_PIN_ENFORCED_BY_POLICY}, + {"pinToShelf", IDS_APP_MANAGEMENT_PIN_TO_SHELF}, + {"policyAppUninstallPolicy", IDS_APP_MANAGEMENT_POLICY_APP_POLICY_STRING}, + {"size", IDS_APP_MANAGEMENT_SIZE}, + {"storage", IDS_APP_MANAGEMENT_STORAGE}, + {"systemAppUninstallPolicy", IDS_APP_MANAGEMENT_SYSTEM_APP_POLICY_STRING}, + {"thisAppCan", IDS_APP_MANAGEMENT_THIS_APP_CAN}, + {"title", IDS_APP_MANAGEMENT_TITLE}, + {"uninstallApp", IDS_APP_MANAGEMENT_UNINSTALL_APP}, + {"version", IDS_APP_MANAGEMENT_VERSION}, + }; + AddLocalizedStringsBulk(html_source, localized_strings, + base::size(localized_strings)); +} #endif #if defined(OS_CHROMEOS) @@ -678,7 +721,6 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source, {"personalizationPageTitle", IDS_OS_SETTINGS_PERSONALIZATION}, {"openWallpaperApp", IDS_OS_SETTINGS_OPEN_WALLPAPER_APP}, {"setWallpaper", IDS_OS_SETTINGS_SET_WALLPAPER}, - {"osLanguagesPageTitle", IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE}, #endif #if defined(OS_LINUX) && !defined(OS_CHROMEOS) {"showWindowDecorations", IDS_SHOW_WINDOW_DECORATIONS}, @@ -842,6 +884,7 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"mouseSpeed", IDS_SETTINGS_MOUSE_SPEED_LABEL}, {"mouseSwapButtons", IDS_SETTINGS_MOUSE_SWAP_BUTTONS_LABEL}, {"mouseReverseScroll", IDS_SETTINGS_MOUSE_REVERSE_SCROLL_LABEL}, + {"pointerAccelerationLabel", IDS_SETTINGS_POINTER_ACCELERATION_LABEL}, }; AddLocalizedStringsBulk(html_source, kPointersStrings, base::size(kPointersStrings)); @@ -988,6 +1031,10 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { html_source->AddBoolean("hasExternalTouchDevice", display::HasExternalTouchscreenDevice()); + html_source->AddBoolean( + "allowDisableMouseAcceleration", + base::FeatureList::IsEnabled(features::kAllowDisableMouseAcceleration)); + static constexpr LocalizedString kStorageStrings[] = { {"storageTitle", IDS_SETTINGS_STORAGE_TITLE}, {"storageItemInUse", IDS_SETTINGS_STORAGE_ITEM_IN_USE}, @@ -1019,10 +1066,10 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) { {"storageDeleteAllButtonTitle", IDS_SETTINGS_STORAGE_DELETE_ALL_BUTTON_TITLE}, {"storageExternal", IDS_SETTINGS_STORAGE_EXTERNAL}, - {"storageAndroidAppsExternalDrives", - IDS_SETTINGS_STORAGE_ANDROID_APPS_ACCESS_EXTERNAL_DRIVES}, {"storageAndroidAppsExternalDrivesNote", - IDS_SETTINGS_STORAGE_ANDROID_APPS_ACCESS_EXTERNAL_DRIVES_NOTE}}; + IDS_SETTINGS_STORAGE_ANDROID_APPS_ACCESS_EXTERNAL_DRIVES_NOTE}, + {"storageExternalStorageListHeader", + IDS_SETTINGS_STORAGE_EXTERNAL_STORAGE_LIST_HEADER}}; AddLocalizedStringsBulk(html_source, kStorageStrings, base::size(kStorageStrings)); @@ -1098,7 +1145,7 @@ void AddDownloadsStrings(content::WebUIDataSource* html_source) { base::size(kLocalizedStrings)); } -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) void AddChromeCleanupStrings(content::WebUIDataSource* html_source) { const wchar_t kUnwantedSoftwareProtectionWhitePaperUrl[] = L"https://www.google.ca/chrome/browser/privacy/" @@ -1227,11 +1274,11 @@ void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) { html_source->AddString("incompatibleApplicationsSubpageLearnHow", learn_how_text); } -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) void AddResetStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kLocalizedStrings[] = { -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) {"resetPageTitle", IDS_SETTINGS_RESET_AND_CLEANUP}, #else {"resetPageTitle", IDS_SETTINGS_RESET}, @@ -1254,7 +1301,7 @@ void AddResetStrings(content::WebUIDataSource* html_source) { {"resetAutomatedDialogTitle", IDS_SETTINGS_RESET_AUTOMATED_DIALOG_TITLE}, {"resetProfileBannerButton", IDS_SETTINGS_RESET_BANNER_RESET_BUTTON_TEXT}, {"resetProfileBannerDescription", IDS_SETTINGS_RESET_BANNER_TEXT}, -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) {"resetCleanupComputerTrigger", IDS_SETTINGS_RESET_CLEAN_UP_COMPUTER_TRIGGER}, #endif @@ -1381,8 +1428,6 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_INTERNET_ADD_CONNECTION_NOT_ALLOWED}, {"internetAddThirdPartyVPN", IDS_SETTINGS_INTERNET_ADD_THIRD_PARTY_VPN}, {"internetAddVPN", IDS_SETTINGS_INTERNET_ADD_VPN}, - {"internetAddArcVPN", IDS_SETTINGS_INTERNET_ADD_ARC_VPN}, - {"internetAddArcVPNProvider", IDS_SETTINGS_INTERNET_ADD_ARC_VPN_PROVIDER}, {"internetAddWiFi", IDS_SETTINGS_INTERNET_ADD_WIFI}, {"internetConfigName", IDS_SETTINGS_INTERNET_CONFIG_NAME}, {"internetDetailPageTitle", IDS_SETTINGS_INTERNET_DETAIL}, @@ -1400,8 +1445,6 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_INTERNET_TOGGLE_TETHER_SUBTEXT}, {"internetToggleWiFiA11yLabel", IDS_SETTINGS_INTERNET_TOGGLE_WIFI_ACCESSIBILITY_LABEL}, - {"internetToggleWiMAXA11yLabel", - IDS_SETTINGS_INTERNET_TOGGLE_WIMAX_ACCESSIBILITY_LABEL}, {"knownNetworksAll", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_ALL}, {"knownNetworksButton", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_BUTTON}, {"knownNetworksMessage", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_MESSAGE}, @@ -1452,6 +1495,10 @@ void AddInternetStrings(content::WebUIDataSource* html_source) { {"networkShared", IDS_SETTINGS_INTERNET_NETWORK_SHARED}, {"networkVpnBuiltin", IDS_NETWORK_TYPE_VPN_BUILTIN}, {"networkOutOfRange", IDS_SETTINGS_INTERNET_WIFI_NETWORK_OUT_OF_RANGE}, + {"cellularContactSpecificCarrier", + IDS_SETTINGS_INTERNET_CELLULAR_CONTACT_SPECIFIC_CARRIER}, + {"cellularContactDefaultCarrier", + IDS_SETTINGS_INTERNET_CELLULAR_CONTACT_DEFAULT_CARRIER}, {"tetherPhoneOutOfRange", IDS_SETTINGS_INTERNET_TETHER_PHONE_OUT_OF_RANGE}, {"gmscoreNotificationsTitle", @@ -1521,6 +1568,8 @@ void AddLanguagesStrings(content::WebUIDataSource* html_source) { {"removeLanguage", IDS_SETTINGS_LANGUAGES_LANGUAGES_LIST_REMOVE}, {"addLanguages", IDS_SETTINGS_LANGUAGES_LANGUAGES_ADD}, #if defined(OS_CHROMEOS) + {"osLanguagesPageTitle", IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE}, + {"osLanguagesListTitle", IDS_OS_SETTINGS_LANGUAGES_LIST_TITLE}, {"inputMethodsListTitle", IDS_SETTINGS_LANGUAGES_INPUT_METHODS_LIST_TITLE}, {"inputMethodEnabled", IDS_SETTINGS_LANGUAGES_INPUT_METHOD_ENABLED}, {"inputMethodsExpandA11yLabel", @@ -1612,6 +1661,15 @@ void AddChromeOSUserStrings(content::WebUIDataSource* html_source, "secondaryUserBannerText", l10n_util::GetStringFUTF16(IDS_SETTINGS_SECONDARY_USER_BANNER, base::ASCIIToUTF16(primary_user_email))); + html_source->AddString("browserSettingsBannerText", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_BROWSER_SETTINGS_BANNER, + base::ASCIIToUTF16(chrome::kChromeUISettingsURL))); + html_source->AddString( + "osSettingsBannerText", + l10n_util::GetStringFUTF16( + IDS_SETTINGS_OS_SETTINGS_BANNER, + base::ASCIIToUTF16(chrome::kChromeUIOSSettingsURL))); html_source->AddBoolean("isActiveDirectoryUser", user && user->IsActiveDirectoryUser()); @@ -1688,6 +1746,14 @@ void AddAutofillStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL}, {"passwordsAutosigninDescription", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC}, + {"passwordsLeakDetectionLabel", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL}, + {"passwordsLeakDetectionSignedInDescription", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_IN_DESC}, + {"passwordsLeakDetectionSignedOutDisabledDescription", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_DISABLED_DESC}, + {"passwordsLeakDetectionSignedOutEnabledDescription", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_ENABLED_DESC}, {"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING}, {"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING}, {"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION}, @@ -1766,6 +1832,16 @@ void AddAutofillStrings(content::WebUIDataSource* html_source, /*is_test_mode=*/false, /*log_manager=*/nullptr)); + html_source->AddBoolean( + "passwordsLeakDetectionEnabled", + base::FeatureList::IsEnabled(password_manager::features::kLeakDetection)); + + ui::Accelerator undoAccelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); + html_source->AddString( + "undoDescription", + l10n_util::GetStringFUTF16(IDS_UNDO_DESCRIPTION, + undoAccelerator.GetShortcutText())); + AddLocalizedStringsBulk(html_source, kLocalizedStrings, base::size(kLocalizedStrings)); } @@ -1835,6 +1911,8 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_KERBEROS_ACCOUNTS_REMOVE_ACCOUNT_LABEL}, {"kerberosAccountsAccountRemovedTip", IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REMOVED_TIP}, + {"kerberosAccountsAccountRefreshedTip", + IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REFRESHED_TIP}, {"kerberosAccountsSignedIn", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_IN}, {"kerberosAccountsSignedOut", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_OUT}, {"kerberosAccountsReauthenticationLabel", @@ -1909,7 +1987,6 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_LESS_SECURE}, {"lockScreenDeleteFingerprintLabel", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_DELETE_FINGERPRINT_ARIA_LABEL}, - {"lockScreenMediaKeys", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_MEDIA_KEYS}, {"lockScreenNotificationHide", IDS_ASH_SETTINGS_LOCK_SCREEN_NOTIFICATION_HIDE}, {"lockScreenNotificationHideSensitive", @@ -1960,6 +2037,8 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) { {"photoDiscardAccessibleText", IDS_SETTINGS_PHOTO_DISCARD_ACCESSIBLE_TEXT}, {"photoModeAccessibleText", IDS_SETTINGS_PHOTO_MODE_ACCESSIBLE_TEXT}, {"videoModeAccessibleText", IDS_SETTINGS_VIDEO_MODE_ACCESSIBLE_TEXT}, + {"wifiConfigurationsCheckboxLabel", + IDS_SETTINGS_WIFI_CONFIGURATIONS_CHECKBOX_LABEL}, #else // !defined(OS_CHROMEOS) {"domainManagedProfile", IDS_SETTINGS_PEOPLE_DOMAIN_MANAGED_PROFILE}, {"editPerson", IDS_SETTINGS_EDIT_PERSON}, @@ -2223,7 +2302,8 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { {"addCupsPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_ADD_PRINTER}, {"editPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_EDIT}, {"removePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_REMOVE}, - {"configurePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_CONFIGURE_BUTTON}, + {"setupPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_SETUP_BUTTON}, + {"savePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_SAVE_BUTTON}, {"searchLabel", IDS_SETTINGS_PRINTING_CUPS_SEARCH_LABEL}, {"noSearchResults", IDS_SEARCH_NO_RESULTS}, {"printerDetailsTitle", IDS_SETTINGS_PRINTING_CUPS_PRINTER_DETAILS_TITLE}, @@ -2276,6 +2356,8 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_PRINTING_CUPS_PRINTER_ADDED_PRINTER_DONE_MESSAGE}, {"printerEditedSuccessfulMessage", IDS_SETTINGS_PRINTING_CUPS_PRINTER_EDITED_PRINTER_DONE_MESSAGE}, + {"printerUnavailableMessage", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_UNAVAILABLE_MESSAGE}, {"noPrinterNearbyMessage", IDS_SETTINGS_PRINTING_CUPS_PRINTER_NO_PRINTER_NEARBY}, {"searchingNearbyPrinters", @@ -2300,6 +2382,12 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) { IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_INVALID_PRINTER_UPDATE}, {"requireNetworkMessage", IDS_SETTINGS_PRINTING_CUPS_PRINTER_REQUIRE_INTERNET_MESSAGE}, + {"checkNetworkMessage", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_CHECK_CONNECTION_MESSAGE}, + {"noInternetConnection", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_NO_INTERNET_CONNECTION}, + {"checkNetworkAndTryAgain", + IDS_SETTINGS_PRINTING_CUPS_PRINTER_CONNECT_TO_NETWORK_SUBTEXT}, {"editPrinterDialogTitle", IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_DIALOG_TITLE}, {"editPrinterButtonText", IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_BUTTON}, @@ -2594,7 +2682,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, {"appCacheOrigin", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL}, {"cookieAppCache", IDS_SETTINGS_COOKIES_APPLICATION_CACHE}, {"cookieCacheStorage", IDS_SETTINGS_COOKIES_CACHE_STORAGE}, - {"cookieChannelId", IDS_SETTINGS_COOKIES_CHANNEL_ID}, {"cookieDatabaseStorage", IDS_SETTINGS_COOKIES_DATABASE_STORAGE}, {"cookieFileSystem", IDS_SETTINGS_COOKIES_FILE_SYSTEM}, {"cookieFlashLso", IDS_SETTINGS_COOKIES_FLASH_LSO}, @@ -2610,10 +2697,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_COOKIES_LOCAL_STORAGE_LAST_MODIFIED_LABEL}, {"cacheStorageOrigin", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_ORIGIN_LABEL}, {"cacheStorageSize", IDS_SETTINGS_COOKIES_LOCAL_STORAGE_SIZE_ON_DISK_LABEL}, - {"channelIdServerId", IDS_SETTINGS_COOKIES_CHANNEL_ID_ORIGIN_LABEL}, - {"channelIdType", IDS_SETTINGS_COOKIES_CHANNEL_ID_TYPE_LABEL}, - {"channelIdCreated", IDS_SETTINGS_COOKIES_CHANNEL_ID_CREATED_LABEL}, - {"channelIdExpires", IDS_SETTINGS_COOKIES_CHANNEL_ID_EXPIRES_LABEL}, {"cookieAccessibleToScript", IDS_SETTINGS_COOKIES_COOKIE_ACCESSIBLE_TO_SCRIPT_LABEL}, {"cookieContent", IDS_SETTINGS_COOKIES_COOKIE_CONTENT_LABEL}, @@ -2739,6 +2822,14 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_ASK_RECOMMENDED}, {"siteSettingsUsbDevicesBlock", IDS_SETTINGS_SITE_SETTINGS_USB_DEVICES_BLOCK}, + {"siteSettingsNativeFileSystemWrite", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE}, + {"siteSettingsNativeFileSystemWriteAsk", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE_ASK}, + {"siteSettingsNativeFileSystemWriteAskRecommended", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE_ASK_RECOMMENDED}, + {"siteSettingsNativeFileSystemWriteBlock", + IDS_SETTINGS_SITE_SETTINGS_NATIVE_FILE_SYSTEM_WRITE_BLOCK}, {"siteSettingsRemoveZoomLevel", IDS_SETTINGS_SITE_SETTINGS_REMOVE_ZOOM_LEVEL}, {"siteSettingsZoomLevels", IDS_SETTINGS_SITE_SETTINGS_ZOOM_LEVELS}, @@ -2848,6 +2939,14 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL}, {"siteSettingsCookieRemoveAllShown", IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL_SHOWN}, + {"siteSettingsCookieRemoveAllThirdParty", + IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_ALL_THIRD_PARTY}, + {"siteSettingsCookieRemoveThirdPartyDialogTitle", + IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE_REMOVE_DIALOG_TITLE}, + {"siteSettingsCookieRemoveThirdPartyConfirmation", + IDS_SETTINGS_SITE_SETTINGS_THIRD_PARTY_COOKIE_REMOVE_CONFIRMATION}, + {"siteSettingsCookiesClearThirdParty", + IDS_SETTINGS_SITE_SETTINGS_CLEAR_THIRD_PARTY_COOKIES}, {"siteSettingsCookieRemoveDialogTitle", IDS_SETTINGS_SITE_SETTINGS_COOKIE_REMOVE_DIALOG_TITLE}, {"siteSettingsCookieRemoveMultipleConfirmation", @@ -2951,10 +3050,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, base::FeatureList::IsEnabled(media::kAutoplayWhitelistSettings)); html_source->AddBoolean( - "enableSensorsContentSetting", - base::FeatureList::IsEnabled(features::kSensorContentSetting)); - - html_source->AddBoolean( "enablePaymentHandlerContentSetting", base::FeatureList::IsEnabled(features::kServiceWorkerPaymentApps)); @@ -2966,6 +3061,15 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source, html_source->AddBoolean( "enableBluetoothScanningContentSetting", cmd.HasSwitch(::switches::kEnableWebBluetoothScanning)); + + html_source->AddBoolean( + "enableNativeFileSystemWriteContentSetting", + base::FeatureList::IsEnabled(::blink::features::kNativeFileSystemAPI)); + + html_source->AddBoolean( + "enableRemovingAllThirdPartyCookies", + base::FeatureList::IsEnabled( + browsing_data::features::kEnableRemovingAllThirdPartyCookies)); } #if defined(OS_CHROMEOS) @@ -3128,6 +3232,20 @@ void AddExtensionsStrings(content::WebUIDataSource* html_source) { void AddSecurityKeysStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kSecurityKeysStrings[] = { + {"securityKeysBioEnrollmentDialogTitle", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_DIALOG_TITLE}, + {"securityKeysBioEnrollmentEnrollingLabel", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_ENROLLING_LABEL}, + {"securityKeysBioEnrollmentLabel", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_LABEL}, + {"securityKeysBioEnrollmentNoEnrollments", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_NO_ENROLLMENTS}, + {"securityKeysBioEnrollmentPinPrompt", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_PIN_PROMPT}, + {"securityKeysBioEnrollmentSubpageDescription", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_SUBPAGE_DESCRIPTION}, + {"securityKeysBioEnrollmentTouch", + IDS_SETTINGS_SECURITY_KEYS_BIO_ENROLLMENT_TOUCH}, {"securityKeysPINTooShort", IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR_TOO_SHORT}, {"securityKeysConfirmPIN", IDS_SETTINGS_SECURITY_KEYS_CONFIRM_PIN}, @@ -3201,24 +3319,22 @@ void AddSecurityKeysStrings(content::WebUIDataSource* html_source) { }; AddLocalizedStringsBulk(html_source, kSecurityKeysStrings, base::size(kSecurityKeysStrings)); - - html_source->AddBoolean( - "enableSecurityKeysSubpage", - base::FeatureList::IsEnabled(device::kWebAuthPINSupport) + bool win_native_api_available = false; #if defined(OS_WIN) - && (!base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) || - !device::WinWebAuthnApi::GetDefault()->IsAvailable()) + win_native_api_available = + base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) && + device::WinWebAuthnApi::GetDefault()->IsAvailable(); #endif - ); + html_source->AddBoolean("enableSecurityKeysSubpage", + !win_native_api_available); html_source->AddBoolean( "enableSecurityKeysCredentialManagement", - base::FeatureList::IsEnabled(device::kWebAuthPINSupport) && - base::FeatureList::IsEnabled(device::kWebAuthCredentialManagement) -#if defined(OS_WIN) - && (!base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) || - !device::WinWebAuthnApi::GetDefault()->IsAvailable()) -#endif - ); + base::FeatureList::IsEnabled(device::kWebAuthCredentialManagement) && + !win_native_api_available); + html_source->AddBoolean( + "enableSecurityKeysBioEnrollment", + base::FeatureList::IsEnabled(device::kWebAuthBiometricEnrollment) && + !win_native_api_available); } } // namespace @@ -3230,10 +3346,10 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddAutofillStrings(html_source, profile); AddAppearanceStrings(html_source, profile); -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) AddChromeCleanupStrings(html_source); AddIncompatibleApplicationsStrings(html_source); -#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) AddChangePasswordStrings(html_source); AddClearBrowsingDataStrings(html_source, profile); @@ -3255,12 +3371,12 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddWebContentStrings(html_source); #if defined(OS_CHROMEOS) - AddCrostiniStrings(html_source, profile); - AddPluginVmStrings(html_source, profile); AddAndroidAppStrings(html_source); + AddAppManagementStrings(html_source); AddAppsStrings(html_source); AddBluetoothStrings(html_source); AddChromeOSUserStrings(html_source, profile); + AddCrostiniStrings(html_source, profile); AddDateTimeStrings(html_source); AddDeviceStrings(html_source); AddEasyUnlockStrings(html_source); @@ -3268,6 +3384,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, AddInternetStrings(html_source); AddMultideviceStrings(html_source); AddParentalControlStrings(html_source); + AddPluginVmStrings(html_source, profile); AddUsersStrings(html_source); #else AddDefaultBrowserStrings(html_source); @@ -3290,7 +3407,7 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source, policy_indicator::AddLocalizedStrings(html_source); AddSecurityKeysStrings(html_source); - html_source->SetJsonPath(kLocalizedStringsFile); + html_source->UseStringsJs(); } } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc index d7ee5c19f6d..3cc1952359a 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc @@ -11,7 +11,7 @@ #include "chrome/test/base/testing_profile_manager.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,7 +40,7 @@ class ManageProfileHandlerTest : public testing::Test { ASSERT_TRUE(profile_manager_.SetUp()); profile_ = profile_manager_.CreateTestingProfile("Profile 1"); - handler_.reset(new TestManageProfileHandler(profile_)); + handler_ = std::make_unique<TestManageProfileHandler>(profile_); handler_->set_web_ui(&web_ui_); handler()->AllowJavascript(); web_ui()->ClearTrackedCalls(); @@ -60,7 +60,7 @@ class ManageProfileHandlerTest : public testing::Test { TestManageProfileHandler* handler() const { return handler_.get(); } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; content::TestWebUI web_ui_; diff --git a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc index 0215a9b4c38..8f725e8ca0d 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc @@ -11,11 +11,14 @@ #include "base/optional.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chrome/browser/ui/webui/settings/settings_security_key_handler.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/system_connector.h" #include "content/public/browser/web_ui.h" #include "content/public/common/service_manager_connection.h" +#include "device/fido/bio/enrollment_handler.h" #include "device/fido/credential_management.h" #include "device/fido/credential_management_handler.h" #include "device/fido/fido_discovery_factory.h" @@ -408,7 +411,8 @@ void SecurityKeysCredentialHandler::OnHaveCredentials( DCHECK(!callback_id_.empty()); if (status != device::CtapDeviceResponseCode::kSuccess) { - OnFinished(device::FidoReturnCode::kAuthenticatorResponseInvalid); + OnFinished( + device::CredentialManagementStatus::kAuthenticatorResponseInvalid); return; } DCHECK(responses); @@ -481,38 +485,294 @@ void SecurityKeysCredentialHandler::OnCredentialsDeleted( : IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_FAILED))); } -void SecurityKeysCredentialHandler::OnFinished(device::FidoReturnCode status) { +void SecurityKeysCredentialHandler::OnFinished( + device::CredentialManagementStatus status) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int error; switch (status) { - case device::FidoReturnCode::kSoftPINBlock: + case device::CredentialManagementStatus::kSoftPINBlock: error = IDS_SETTINGS_SECURITY_KEYS_PIN_SOFT_LOCK; break; - case device::FidoReturnCode::kHardPINBlock: + case device::CredentialManagementStatus::kHardPINBlock: error = IDS_SETTINGS_SECURITY_KEYS_PIN_HARD_LOCK; break; - case device::FidoReturnCode::kAuthenticatorMissingCredentialManagement: + case device::CredentialManagementStatus:: + kAuthenticatorMissingCredentialManagement: error = IDS_SETTINGS_SECURITY_KEYS_NO_CREDENTIAL_MANAGEMENT; break; - case device::FidoReturnCode::kAuthenticatorMissingUserVerification: + case device::CredentialManagementStatus::kNoPINSet: error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_NO_PIN; break; - case device::FidoReturnCode::kAuthenticatorResponseInvalid: + case device::CredentialManagementStatus::kAuthenticatorResponseInvalid: error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR; break; - case device::FidoReturnCode::kSuccess: + case device::CredentialManagementStatus::kSuccess: error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_REMOVED; break; - default: - NOTREACHED(); - error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR; - break; } FireWebUIListener("security-keys-credential-management-finished", base::Value(l10n_util::GetStringUTF8(std::move(error)))); } +SecurityKeysBioEnrollmentHandler::SecurityKeysBioEnrollmentHandler() = default; +SecurityKeysBioEnrollmentHandler::~SecurityKeysBioEnrollmentHandler() = default; + +void SecurityKeysBioEnrollmentHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollStart", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleStart, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollProvidePIN", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleProvidePIN, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollEnumerate", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleEnumerate, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollStartEnrolling", + base::BindRepeating( + &SecurityKeysBioEnrollmentHandler::HandleStartEnrolling, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollDelete", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleDelete, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollCancel", + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::HandleCancel, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "securityKeyBioEnrollClose", + base::BindRepeating( + &HandleClose, + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::Close, + base::Unretained(this)))); +} + +void SecurityKeysBioEnrollmentHandler::Close() { + weak_factory_.InvalidateWeakPtrs(); + state_ = State::kNone; + discovery_factory_.reset(); + bio_.reset(); + callback_id_.clear(); + discovery_factory_.reset(); + provide_pin_cb_.Reset(); +} + +void SecurityKeysBioEnrollmentHandler::HandleStart( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(state_, State::kNone); + DCHECK_EQ(1u, args->GetSize()); + DCHECK(callback_id_.empty()); + + AllowJavascript(); + state_ = State::kStart; + callback_id_ = args->GetList()[0].GetString(); + discovery_factory_ = std::make_unique<device::FidoDiscoveryFactory>(); + bio_ = std::make_unique<device::BioEnrollmentHandler>( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), + supported_transports(), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnReady, + weak_factory_.GetWeakPtr()), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnError, + weak_factory_.GetWeakPtr()), + base::BindRepeating(&SecurityKeysBioEnrollmentHandler::OnGatherPIN, + weak_factory_.GetWeakPtr()), + discovery_factory_.get()); +} + +void SecurityKeysBioEnrollmentHandler::OnReady() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(bio_); + DCHECK_EQ(state_, State::kGatherPIN); + DCHECK(!callback_id_.empty()); + state_ = State::kReady; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value()); +} + +void SecurityKeysBioEnrollmentHandler::OnError( + device::BioEnrollmentStatus status) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + state_ = State::kNone; + + int error; + switch (status) { + case device::BioEnrollmentStatus::kSoftPINBlock: + error = IDS_SETTINGS_SECURITY_KEYS_PIN_SOFT_LOCK; + break; + case device::BioEnrollmentStatus::kHardPINBlock: + error = IDS_SETTINGS_SECURITY_KEYS_PIN_HARD_LOCK; + break; + case device::BioEnrollmentStatus::kAuthenticatorMissingBioEnrollment: + error = IDS_SETTINGS_SECURITY_KEYS_NO_BIOMETRIC_ENROLLMENT; + break; + case device::BioEnrollmentStatus::kNoPINSet: + error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_NO_PIN; + break; + case device::BioEnrollmentStatus::kAuthenticatorResponseInvalid: + error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR; + break; + case device::BioEnrollmentStatus::kSuccess: + error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_REMOVED; + break; + } + + FireWebUIListener("security-keys-bio-enroll-error", + base::Value(l10n_util::GetStringUTF8(error))); + + // If |callback_id_| is not empty, there is an ongoing operation, + // which means there is an unresolved Promise. Reject it so that + // it isn't leaked. + if (!callback_id_.empty()) { + RejectJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value()); + } +} + +void SecurityKeysBioEnrollmentHandler::OnGatherPIN( + int64_t retries, + base::OnceCallback<void(std::string)> cb) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(!callback_id_.empty()); + DCHECK(state_ == State::kStart || state_ == State::kGatherPIN); + state_ = State::kGatherPIN; + provide_pin_cb_ = std::move(cb); + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(static_cast<int>(retries))); +} + +void SecurityKeysBioEnrollmentHandler::HandleProvidePIN( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(2u, args->GetSize()); + DCHECK_EQ(state_, State::kGatherPIN); + state_ = State::kGatherPIN; + callback_id_ = args->GetList()[0].GetString(); + std::move(provide_pin_cb_).Run(args->GetList()[1].GetString()); +} + +void SecurityKeysBioEnrollmentHandler::HandleEnumerate( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + DCHECK_EQ(state_, State::kReady); + state_ = State::kEnumerating; + callback_id_ = args->GetList()[0].GetString(); + bio_->EnumerateTemplates( + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnHaveEnumeration, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnHaveEnumeration( + device::CtapDeviceResponseCode code, + base::Optional<std::map<std::vector<uint8_t>, std::string>> enrollments) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(!callback_id_.empty()); + DCHECK_EQ(state_, State::kEnumerating); + + base::Value::ListStorage list; + if (enrollments) { + for (const auto& enrollment : *enrollments) { + base::DictionaryValue elem; + elem.SetStringKey("name", std::move(enrollment.second)); + elem.SetStringKey("id", base::HexEncode(enrollment.first.data(), + enrollment.first.size())); + list.emplace_back(std::move(elem)); + } + } + + state_ = State::kReady; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::ListValue(std::move(list))); +} + +void SecurityKeysBioEnrollmentHandler::HandleStartEnrolling( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + DCHECK_EQ(state_, State::kReady); + state_ = State::kEnrolling; + callback_id_ = args->GetList()[0].GetString(); + bio_->EnrollTemplate( + base::BindRepeating( + &SecurityKeysBioEnrollmentHandler::OnEnrollingResponse, + weak_factory_.GetWeakPtr()), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnEnrollmentFinished, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnEnrollingResponse( + device::BioEnrollmentSampleStatus status, + uint8_t remaining_samples) { + DCHECK_EQ(state_, State::kEnrolling); + base::DictionaryValue d; + d.SetIntKey("status", static_cast<int>(status)); + d.SetIntKey("remaining", static_cast<int>(remaining_samples)); + FireWebUIListener("security-keys-bio-enroll-status", std::move(d)); +} + +void SecurityKeysBioEnrollmentHandler::OnEnrollmentFinished( + device::CtapDeviceResponseCode code) { + DCHECK_EQ(state_, State::kEnrolling); + DCHECK(!callback_id_.empty()); + state_ = State::kReady; + base::DictionaryValue d; + d.SetIntKey("code", static_cast<int>(code)); + d.SetIntKey("remaining", 0); + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), std::move(d)); +} + +void SecurityKeysBioEnrollmentHandler::HandleDelete( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(2u, args->GetSize()); + state_ = State::kDeleting; + callback_id_ = args->GetList()[0].GetString(); + std::vector<uint8_t> template_id; + if (!base::HexStringToBytes(args->GetList()[1].GetString(), &template_id)) { + NOTREACHED(); + return; + } + bio_->DeleteTemplate( + std::move(template_id), + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnDelete, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnDelete( + device::CtapDeviceResponseCode c) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(state_, State::kDeleting); + DCHECK(!callback_id_.empty()); + state_ = State::kEnumerating; + bio_->EnumerateTemplates( + base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnHaveEnumeration, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::HandleCancel( + const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + state_ = State::kCancelling; + callback_id_ = args->GetList()[0].GetString(); + bio_->Cancel(base::BindOnce(&SecurityKeysBioEnrollmentHandler::OnEnrollCancel, + weak_factory_.GetWeakPtr())); +} + +void SecurityKeysBioEnrollmentHandler::OnEnrollCancel( + device::CtapDeviceResponseCode) { + DCHECK_EQ(state_, State::kCancelling); + state_ = State::kReady; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value()); +} + } // namespace settings diff --git a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h index 2b9e1b17317..60196df0fba 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h @@ -14,6 +14,8 @@ #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "device/fido/fido_constants.h" +#include "device/fido/bio/enrollment.h" + namespace base { class ListValue; } @@ -22,8 +24,11 @@ namespace device { struct AggregatedEnumerateCredentialsResponse; class FidoDiscoveryFactory; class CredentialManagementHandler; +enum class CredentialManagementStatus; class SetPINRequestHandler; class ResetRequestHandler; +class BioEnrollmentHandler; +enum class BioEnrollmentStatus; } // namespace device namespace settings { @@ -149,7 +154,7 @@ class SecurityKeysCredentialHandler : public SecurityKeysHandlerBase { base::Optional<size_t> remaining_credentials); void OnGatherPIN(int64_t num_retries, base::OnceCallback<void(std::string)>); void OnCredentialsDeleted(device::CtapDeviceResponseCode status); - void OnFinished(device::FidoReturnCode status); + void OnFinished(device::CredentialManagementStatus status); State state_ = State::kNone; base::OnceCallback<void(std::string)> credential_management_provide_pin_cb_; @@ -161,6 +166,60 @@ class SecurityKeysCredentialHandler : public SecurityKeysHandlerBase { base::WeakPtrFactory<SecurityKeysCredentialHandler> weak_factory_{this}; }; +// SecurityKeysBioEnrollmentHandler processes messages from the "Manage +// fingerprints" dialog of the "Security Keys" settings subpage. An instance of +// this class is created for each settings tab and is destroyed when the tab is +// closed. See SecurityKeysBioEnrollProxy about the interface. +class SecurityKeysBioEnrollmentHandler : public SecurityKeysHandlerBase { + public: + SecurityKeysBioEnrollmentHandler(); + ~SecurityKeysBioEnrollmentHandler() override; + + private: + enum class State { + kNone, + kStart, + kGatherPIN, + kReady, + kEnumerating, + kEnrolling, + kDeleting, + kCancelling, + }; + + void RegisterMessages() override; + void Close() override; + + void HandleStart(const base::ListValue* args); + void OnReady(); + void OnError(device::BioEnrollmentStatus status); + void OnGatherPIN(int64_t retries, base::OnceCallback<void(std::string)>); + + void HandleProvidePIN(const base::ListValue* args); + + void HandleEnumerate(const base::ListValue* args); + void OnHaveEnumeration( + device::CtapDeviceResponseCode, + base::Optional<std::map<std::vector<uint8_t>, std::string>>); + + void HandleStartEnrolling(const base::ListValue* args); + void OnEnrollingResponse(device::BioEnrollmentSampleStatus, uint8_t); + void OnEnrollmentFinished(device::CtapDeviceResponseCode); + + void HandleDelete(const base::ListValue* args); + void OnDelete(device::CtapDeviceResponseCode); + + void HandleCancel(const base::ListValue* args); + void OnEnrollCancel(device::CtapDeviceResponseCode); + + State state_ = State::kNone; + std::string callback_id_; + base::OnceCallback<void(std::string)> provide_pin_cb_; + std::unique_ptr<device::FidoDiscoveryFactory> discovery_factory_; + std::unique_ptr<device::BioEnrollmentHandler> bio_; + base::WeakPtrFactory<SecurityKeysBioEnrollmentHandler> weak_factory_{this}; +}; + } // namespace settings #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_SECURITY_KEY_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc index d33e9f09336..3ea47f5691e 100644 --- a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc @@ -17,7 +17,6 @@ #include "base/stl_util.h" #include "build/branding_buildflags.h" #include "build/build_config.h" -#include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" @@ -55,6 +54,7 @@ #include "components/favicon_base/favicon_url_parser.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/pref_registry/pref_registry_syncable.h" +#include "components/safe_browsing/buildflags.h" #include "components/unified_consent/feature.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" @@ -79,6 +79,7 @@ #endif // defined(OS_WIN) || defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) +#include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "ash/public/cpp/stylus_utils.h" #include "chrome/browser/browser_process.h" @@ -92,7 +93,6 @@ #include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/chromeos/plugin_vm/plugin_vm_util.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h" @@ -113,24 +113,23 @@ #include "chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" #include "chrome/browser/web_applications/system_web_app_manager.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/grit/browser_resources.h" #include "chromeos/components/account_manager/account_manager.h" #include "chromeos/components/account_manager/account_manager_factory.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_pref_names.h" -#include "chromeos/constants/chromeos_switches.h" #include "chromeos/login/auth/password_visibility_utils.h" #include "chromeos/services/multidevice_setup/public/cpp/prefs.h" #include "chromeos/services/network_config/public/mojom/constants.mojom.h" // nogncheck #include "components/arc/arc_util.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user.h" -#include "services/service_manager/public/cpp/connector.h" #include "ui/base/ui_base_features.h" #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" +#include "ui/resources/grit/webui_resources.h" #else // !defined(OS_CHROMEOS) #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" @@ -148,32 +147,12 @@ #include "chrome/browser/ui/webui/settings/printing_handler.h" #endif -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "chrome/browser/ui/webui/settings/change_password_handler.h" #endif namespace settings { - -namespace { - -#if defined(OS_CHROMEOS) -bool ShouldShowParentalControls(Profile* profile) { - // Show Parental controls for regular and child accounts that are the - // primary profile. Do not show it to any secondary profiles, managed - // accounts that aren't child accounts (i.e. enterprise and EDU accounts), - // OTR accounts, or legacy supervised user accounts. - return chromeos::switches::IsParentalControlsSettingsEnabled() && - profile == ProfileManager::GetPrimaryUserProfile() && - !profile->IsLegacySupervised() && !profile->IsGuestSession() && - (profile->IsChild() || - !profile->GetProfilePolicyConnector()->IsManaged()); -} - -#endif // defined(OS_CHROMEOS) - -} // namespace - // static void SettingsUI::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { @@ -234,6 +213,8 @@ SettingsUI::SettingsUI(content::WebUI* web_ui) AddSettingsPageUIHandler(std::make_unique<SecurityKeysPINHandler>()); AddSettingsPageUIHandler(std::make_unique<SecurityKeysResetHandler>()); AddSettingsPageUIHandler(std::make_unique<SecurityKeysCredentialHandler>()); + AddSettingsPageUIHandler( + std::make_unique<SecurityKeysBioEnrollmentHandler>()); #if defined(OS_WIN) || defined(OS_MACOSX) AddSettingsPageUIHandler(std::make_unique<CaptionsHandler>()); @@ -270,7 +251,7 @@ SettingsUI::SettingsUI(content::WebUI* web_ui) #endif // OS_WIN && BUILDFLAG(GOOGLE_CHROME_BRANDING) bool password_protection_available = false; -#if defined(FULL_SAFE_BROWSING) +#if BUILDFLAG(FULL_SAFE_BROWSING) safe_browsing::ChromePasswordProtectionService* password_protection = safe_browsing::ChromePasswordProtectionService:: GetPasswordProtectionService(profile); @@ -301,8 +282,9 @@ SettingsUI::SettingsUI(content::WebUI* web_ui) password_manager::features::kPasswordImport)); #if defined(OS_CHROMEOS) - html_source->AddBoolean("showParentalControls", - ShouldShowParentalControls(profile)); + html_source->AddBoolean( + "showParentalControls", + chromeos::settings::ShouldShowParentalControls(profile)); #endif #if defined(OS_CHROMEOS) @@ -412,10 +394,8 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, chromeos::settings::DateTimeHandler::Create(html_source))); web_ui->AddMessageHandler( std::make_unique<chromeos::settings::FingerprintHandler>(profile)); - if (chromeos::switches::IsAssistantEnabled()) { - web_ui->AddMessageHandler( - std::make_unique<chromeos::settings::GoogleAssistantHandler>(profile)); - } + web_ui->AddMessageHandler( + std::make_unique<chromeos::settings::GoogleAssistantHandler>(profile)); if (g_browser_process->local_state()->GetBoolean(prefs::kKerberosEnabled)) { // Note that UI is also dependent on this pref. web_ui->AddMessageHandler( @@ -423,6 +403,12 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, } web_ui->AddMessageHandler( std::make_unique<chromeos::settings::KeyboardHandler>()); + + // TODO(crbug/950007): Remove adding WallpaperHandler when + // SplitSettings complete. + web_ui->AddMessageHandler( + std::make_unique<chromeos::settings::WallpaperHandler>(web_ui)); + if (plugin_vm::IsPluginVmEnabled(profile)) { web_ui->AddMessageHandler( std::make_unique<chromeos::settings::PluginVmHandler>(profile)); @@ -454,7 +440,7 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, : nullptr, android_sms_service ? android_sms_service->android_sms_app_manager() : nullptr)); - if (ShouldShowParentalControls(profile)) { + if (chromeos::settings::ShouldShowParentalControls(profile)) { web_ui->AddMessageHandler( std::make_unique<chromeos::settings::ParentalControlsHandler>( profile)); @@ -485,15 +471,22 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, html_source->AddInteger( "fingerprintReaderLocation", static_cast<int32_t>(chromeos::quick_unlock::GetFingerprintLocation())); + + // To use lottie, the worker-src CSP needs to be updated for the web ui that + // is using it. Since as of now there are only a couple of webuis using + // lottie animations, this update has to be performed manually. As the usage + // increases, set this as the default so manual override is no longer + // required. + html_source->OverrideContentSecurityPolicyWorkerSrc( + "worker-src blob: 'self';"); + html_source->AddResourcePath("finger_print.json", + IDR_LOGIN_FINGER_PRINT_TABLET_ANIMATION); } html_source->AddBoolean("lockScreenNotificationsEnabled", ash::features::IsLockScreenNotificationsEnabled()); html_source->AddBoolean( "lockScreenHideSensitiveNotificationsSupported", ash::features::IsLockScreenHideSensitiveNotificationsSupported()); - html_source->AddBoolean( - "lockScreenMediaKeysEnabled", - base::FeatureList::IsEnabled(ash::features::kLockScreenMediaKeys)); html_source->AddBoolean("showTechnologyBadge", !ash::features::IsSeparateNetworkIconsEnabled()); html_source->AddBoolean("hasInternalStylus", @@ -512,9 +505,6 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, html_source->AddBoolean("isDemoSession", chromeos::DemoSession::IsDeviceInDemoMode()); - html_source->AddBoolean("assistantEnabled", - chromeos::switches::IsAssistantEnabled()); - // We have 2 variants of Android apps settings. Default case, when the Play // Store app exists we show expandable section that allows as to // enable/disable the Play Store and link to Android settings which is @@ -531,10 +521,8 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile, std::make_unique<chromeos::settings::PowerHandler>(profile->GetPrefs())); html_source->AddBoolean( - "showApps", base::FeatureList::IsEnabled(features::kAppManagement)); - - html_source->AddBoolean("showParentalControlsSettings", - ShouldShowParentalControls(profile)); + "showParentalControlsSettings", + chromeos::settings::ShouldShowParentalControls(profile)); } #endif // defined(OS_CHROMEOS) @@ -547,10 +535,7 @@ void SettingsUI::AddSettingsPageUIHandler( #if defined(OS_CHROMEOS) void SettingsUI::BindCrosNetworkConfig( chromeos::network_config::mojom::CrosNetworkConfigRequest request) { - content::BrowserContext::GetConnectorFor( - web_ui()->GetWebContents()->GetBrowserContext()) - ->BindInterface(chromeos::network_config::mojom::kServiceName, - std::move(request)); + ash::GetNetworkConfigService(std::move(request)); } #endif // defined(OS_CHROMEOS) 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 b0869cafd40..3d5fc205b3d 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 @@ -48,10 +48,11 @@ #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/browser_task_environment.h" #include "content/public/test/test_web_ui.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "ppapi/buildflags/buildflags.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "testing/gtest/include/gtest/gtest.h" @@ -468,7 +469,7 @@ class SiteSettingsHandlerTest : public testing::Test { const std::string kFlash; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; TestingProfile* incognito_profile_; content::TestWebUI web_ui_; @@ -1009,8 +1010,7 @@ TEST_F(SiteSettingsHandlerTest, GetAndSetOriginPermissions) { #if BUILDFLAG(ENABLE_PLUGINS) TEST_F(SiteSettingsHandlerTest, ChangingFlashSettingForSiteIsRemembered) { - ChromePluginServiceFilter::GetInstance()->RegisterResourceContext( - profile(), profile()->GetResourceContext()); + ChromePluginServiceFilter::GetInstance()->RegisterProfile(profile()); FlashContentSettingsChangeWaiter waiter(profile()); const std::string origin_with_port("https://www.example.com:443"); @@ -1561,9 +1561,10 @@ class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest { 6355, 0, "Google", "Widget", "789XYZ"); auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); - device::mojom::UsbDeviceManagerPtr device_manager_ptr; - device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); - chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; + device_manager_.AddReceiver( + device_manager.InitWithNewPipeAndPassReceiver()); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); @@ -1603,9 +1604,10 @@ class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest { CreateIncognitoProfile(); auto* chooser_context = UsbChooserContextFactory::GetForProfile(incognito_profile()); - device::mojom::UsbDeviceManagerPtr device_manager_ptr; - device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); - chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; + device_manager_.AddReceiver( + device_manager.InitWithNewPipeAndPassReceiver()); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc index 440e917e224..605afeb6055 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc @@ -11,6 +11,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_observer.h" +#include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/tts_controller.h" @@ -24,7 +25,7 @@ #include "ui/base/l10n/l10n_util.h" namespace settings { -TtsHandler::TtsHandler() : weak_factory_(this) {} +TtsHandler::TtsHandler() {} TtsHandler::~TtsHandler() { content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this); @@ -143,7 +144,8 @@ void TtsHandler::HandlePreviewTtsVoice(const base::ListValue* args) { utterance->SetText(text); utterance->SetVoiceName(name); utterance->SetEngineId(extension_id); - utterance->SetSrcUrl(GURL("chrome://settings/manageAccessibility/tts")); + utterance->SetSrcUrl( + GURL(chrome::GetOSSettingsUrl("manageAccessibility/tts"))); utterance->SetEventDelegate(this); content::TtsController::GetInstance()->Stop(); diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.h b/chromium/chrome/browser/ui/webui/settings/tts_handler.h index f26fbb230e5..a839dee3c0b 100644 --- a/chromium/chrome/browser/ui/webui/settings/tts_handler.h +++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.h @@ -46,7 +46,7 @@ class TtsHandler : public SettingsPageUIHandler, int GetVoiceLangMatchScore(const content::VoiceData* voice, const std::string& app_locale); - base::WeakPtrFactory<TtsHandler> weak_factory_; + base::WeakPtrFactory<TtsHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(TtsHandler); }; diff --git a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc index 9eef3566d25..19f554e3951 100644 --- a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc +++ b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc @@ -133,9 +133,9 @@ void DetectAndStartProxyConfigUtil(int render_process_id, if (launched) return; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ShowLinuxProxyConfigUrl, - render_process_id, render_view_id)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ShowLinuxProxyConfigUrl, render_process_id, + render_view_id)); } } // namespace @@ -143,8 +143,9 @@ void DetectAndStartProxyConfigUtil(int render_process_id, namespace settings_utils { void ShowNetworkProxySettings(content::WebContents* web_contents) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&DetectAndStartProxyConfigUtil, web_contents->GetRenderViewHost()->GetProcess()->GetID(), web_contents->GetRenderViewHost()->GetRoutingID())); diff --git a/chromium/chrome/browser/ui/webui/settings_utils_win.cc b/chromium/chrome/browser/ui/webui/settings_utils_win.cc index 69db0748f26..c5d1717a99a 100644 --- a/chromium/chrome/browser/ui/webui/settings_utils_win.cc +++ b/chromium/chrome/browser/ui/webui/settings_utils_win.cc @@ -109,9 +109,10 @@ void ShowNetworkProxySettings(content::WebContents* web_contents) { Profile::FromBrowserContext(web_contents->GetBrowserContext()), GURL("ms-settings:network-proxy")); } else { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, - base::BindOnce(&OpenConnectionDialogCallback)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock()}, + base::BindOnce(&OpenConnectionDialogCallback)); } } diff --git a/chromium/chrome/browser/ui/webui/signin/OWNERS b/chromium/chrome/browser/ui/webui/signin/OWNERS index a058d8e5b28..74b64b88981 100644 --- a/chromium/chrome/browser/ui/webui/signin/OWNERS +++ b/chromium/chrome/browser/ui/webui/signin/OWNERS @@ -1,6 +1,5 @@ achuith@chromium.org msarda@chromium.org -rogerta@chromium.org xiyuan@chromium.org per-file inline_login_handler_impl*=file://chrome/credential_provider/OWNERS diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc index dd5f7fb4911..0086f6c69f5 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc @@ -74,8 +74,9 @@ class DiceTurnSyncOnHelperShutdownNotifierFactory AccountInfo GetAccountInfo(signin::IdentityManager* identity_manager, const std::string& account_id) { auto maybe_account_info = - identity_manager->FindAccountInfoForAccountWithRefreshTokenByAccountId( - account_id); + identity_manager + ->FindExtendedAccountInfoForAccountWithRefreshTokenByAccountId( + account_id); return maybe_account_info.has_value() ? maybe_account_info.value() : AccountInfo(); } diff --git a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc index bcc7150897b..b3d39140ff4 100644 --- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc @@ -38,7 +38,7 @@ #include "components/unified_consent/feature.h" #include "components/unified_consent/scoped_unified_consent.h" #include "components/unified_consent/url_keyed_data_collection_consent_helper.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "google_apis/gaia/google_service_auth_error.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -405,7 +405,7 @@ class DiceTurnSyncOnHelperTestBase : public testing::Test { bool expected_sync_settings_shown_ = false; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; ScopedTestingLocalState local_state_; std::string account_id_; @@ -612,7 +612,7 @@ TEST_F(DiceTurnSyncOnHelperTest, EnterpriseConfirmationAbort) { } // Continue after the enterprise confirmation prompt. -TEST_F(DiceTurnSyncOnHelperTest, EnterpriseConfirmationContinue) { +TEST_F(DiceTurnSyncOnHelperTest, DISABLED_EnterpriseConfirmationContinue) { // Set expectations. expected_enterprise_confirmation_email_ = kEmail; expected_sync_confirmation_shown_ = true; 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 d025828e2ed..fb483f45025 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc @@ -46,6 +46,10 @@ void InlineLoginHandler::RegisterMessages() { base::BindRepeating(&InlineLoginHandler::HandleInitializeMessage, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "authExtensionReady", + base::BindRepeating(&InlineLoginHandler::HandleAuthExtensionReadyMessage, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "completeLogin", base::BindRepeating(&InlineLoginHandler::HandleCompleteLoginMessage, base::Unretained(this))); @@ -170,7 +174,7 @@ void InlineLoginHandler::HandleCompleteLoginMessage( void InlineLoginHandler::HandleCompleteLoginMessageWithCookies( const base::ListValue& args, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies) { const base::DictionaryValue* dict = nullptr; args.GetDictionary(0, &dict); @@ -180,9 +184,9 @@ void InlineLoginHandler::HandleCompleteLoginMessageWithCookies( const std::string& gaia_id = dict->FindKey("gaiaId")->GetString(); std::string auth_code; - for (const auto& cookie : cookies) { - if (cookie.Name() == "oauth_code") - auth_code = cookie.Value(); + for (const auto& cookie_with_status : cookies) { + if (cookie_with_status.cookie.Name() == "oauth_code") + auth_code = cookie_with_status.cookie.Value(); } bool skip_for_now = false; @@ -233,6 +237,8 @@ void InlineLoginHandler::HandleNavigationButtonClicked( #if !defined(OS_CHROMEOS) NOTREACHED() << "The inline login handler is no longer used in a browser " "or tab modal dialog."; +#else + FireWebUIListener("navigateBackInWebview"); #endif } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h index 65e1ac89af0..ef8ce7823e3 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_H_ +#include <string> #include <vector> #include "base/macros.h" @@ -16,10 +17,6 @@ namespace base { class DictionaryValue; } -namespace net { -class CanonicalCookie; -} - namespace signin_metrics { enum class AccessPoint; } @@ -57,6 +54,9 @@ class InlineLoginHandler : public content::WebUIMessageHandler { // |SetExtraInitParams| to set extra init params. void ContinueHandleInitializeMessage(); + // JS callback to handle tasks after auth extension loads. + virtual void HandleAuthExtensionReadyMessage(const base::ListValue* args) {} + // JS callback to complete login. It calls |CompleteLogin| to do the real // work. void HandleCompleteLoginMessage(const base::ListValue* args); @@ -65,7 +65,7 @@ class InlineLoginHandler : public content::WebUIMessageHandler { // from the CookieManager. void HandleCompleteLoginMessageWithCookies( const base::ListValue& args, - const std::vector<net::CanonicalCookie>& cookies, + const net::CookieStatusList& cookies, const net::CookieStatusList& excluded_cookies); // JS callback to switch the UI from a constrainted dialog to a full tab. @@ -76,7 +76,7 @@ class InlineLoginHandler : public content::WebUIMessageHandler { void HandleNavigationButtonClicked(const base::ListValue* args); // Handles the web ui message sent when the window is closed from javascript. - void HandleDialogClose(const base::ListValue* args); + virtual void HandleDialogClose(const base::ListValue* args); virtual void SetExtraInitParams(base::DictionaryValue& params) {} virtual void CompleteLogin(const std::string& email, diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index 3e034ca354a..a127593b60e 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc @@ -132,6 +132,12 @@ void InlineLoginHandlerChromeOS::SetExtraInitParams( params.SetBoolean("ignoreCrOSIdpSetting", true); } +void InlineLoginHandlerChromeOS::HandleAuthExtensionReadyMessage( + const base::ListValue* args) { + AllowJavascript(); + FireWebUIListener("showBackButton"); +} + void InlineLoginHandlerChromeOS::CompleteLogin(const std::string& email, const std::string& password, const std::string& gaia_id, @@ -161,6 +167,12 @@ void InlineLoginHandlerChromeOS::CompleteLogin(const std::string& email, auth_code); } +void InlineLoginHandlerChromeOS::HandleDialogClose( + const base::ListValue* args) { + AllowJavascript(); + close_dialog_closure_.Run(); +} + void InlineLoginHandlerChromeOS::ShowIncognitoAndCloseDialog( const base::ListValue* args) { chrome::NewIncognitoWindow(Profile::FromWebUI(web_ui())); diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h index 415bf57ea09..56c511d5973 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.h @@ -23,6 +23,7 @@ class InlineLoginHandlerChromeOS : public InlineLoginHandler { // InlineLoginHandler overrides. void RegisterMessages() override; void SetExtraInitParams(base::DictionaryValue& params) override; + void HandleAuthExtensionReadyMessage(const base::ListValue* args) override; void CompleteLogin(const std::string& email, const std::string& password, const std::string& gaia_id, @@ -31,6 +32,7 @@ class InlineLoginHandlerChromeOS : public InlineLoginHandler { bool trusted, bool trusted_found, bool choose_what_to_sync) override; + void HandleDialogClose(const base::ListValue* args) override; private: void ShowIncognitoAndCloseDialog(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 201e1922675..08092d21e0c 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 @@ -258,7 +258,7 @@ void OnSyncSetupComplete(Profile* profile, ServiceAccessType::EXPLICIT_ACCESS); password_store->SaveGaiaPasswordHash( username, base::UTF8ToUTF16(password), - password_manager::metrics_util::SyncPasswordHashChange:: + password_manager::metrics_util::GaiaPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); if (profiles::IsLockAvailable(profile)) @@ -374,7 +374,7 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( if (password_store && !primary_email.empty()) { password_store->SaveGaiaPasswordHash( primary_email, base::UTF8ToUTF16(password_), - password_manager::metrics_util::SyncPasswordHashChange:: + password_manager::metrics_util::GaiaPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); } } diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc index 9b42b10cf06..62f1e70fb49 100644 --- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc @@ -37,7 +37,7 @@ content::WebUIDataSource* CreateWebUIDataSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIChromeSigninHost); source->OverrideContentSecurityPolicyObjectSrc("object-src chrome:;"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_INLINE_LOGIN_HTML); diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc index aff12cc4469..e9b169c910f 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc @@ -16,7 +16,6 @@ #include "chrome/browser/ui/scoped_tabbed_browser_displayer.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" -#include "components/signin/core/browser/signin_header_helper.h" #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/user_manager.h" @@ -112,7 +111,7 @@ void LoginUIService::DisplayLoginResult(Browser* browser, } else if (browser) { browser->window()->ShowAvatarBubbleFromAvatarButton( BrowserWindow::AVATAR_BUBBLE_MODE_CONFIRM_SIGNIN, - signin::ManageAccountsParams(), + signin_metrics::AccessPoint::ACCESS_POINT_EXTENSIONS, false); } #endif diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc b/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc index b2fb62b06da..d5a7a11066e 100644 --- a/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -43,7 +43,7 @@ class LoginUIServiceTest : public testing::Test { } protected: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfileManager profile_manager_; // Test profile used by all tests - this is owned by profile_manager_. diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc index dec3301d61e..b08ea973884 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc @@ -18,7 +18,6 @@ #include "base/value_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.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" @@ -28,6 +27,7 @@ #include "chrome/browser/signin/signin_error_controller_factory.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/user_manager.h" #include "chrome/browser/ui/webui/profile_helper.h" #include "chrome/browser/ui/webui/signin/signin_utils.h" @@ -39,14 +39,14 @@ #include "components/prefs/pref_service.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 "ui/base/l10n/l10n_util.h" -SigninCreateProfileHandler::SigninCreateProfileHandler() - : profile_creation_type_(NO_CREATION_IN_PROGRESS) {} +SigninCreateProfileHandler::SigninCreateProfileHandler() = default; -SigninCreateProfileHandler::~SigninCreateProfileHandler() {} +SigninCreateProfileHandler::~SigninCreateProfileHandler() { + BrowserList::RemoveObserver(this); +} void SigninCreateProfileHandler::GetLocalizedValues( base::DictionaryValue* localized_strings) { @@ -83,6 +83,43 @@ void SigninCreateProfileHandler::RegisterMessages() { base::Unretained(this))); } +void SigninCreateProfileHandler::OnBrowserAdded(Browser* browser) { + // Only respond to one OnBrowserAdded. + BrowserList::RemoveObserver(this); + UserManager::Hide(); +} + +void SigninCreateProfileHandler::OpenNewWindowForProfile( + Profile* profile, + Profile::CreateStatus status) { + profiles::OpenBrowserWindowForProfile( + base::Bind(&SigninCreateProfileHandler::OnBrowserReadyCallback, + weak_ptr_factory_.GetWeakPtr()), + false, // Don't create a window if one already exists. + true, // Create a first run window. + false, // There is no need to unblock all extensions because we only open + // browser window if the Profile is not locked. Hence there is no + // extension blocked. + profile, status); +} + +void SigninCreateProfileHandler::OpenForceSigninDialogForProfile( + Profile* profile) { + UserManagerProfileDialog::ShowForceSigninDialog( + web_ui()->GetWebContents()->GetBrowserContext(), profile->GetPath()); +} + +void SigninCreateProfileHandler::DoCreateProfile(const base::string16& name, + const std::string& icon_url, + bool create_shortcut) { + ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_USER_DIALOG); + + profile_path_being_created_ = ProfileManager::CreateMultiProfileAsync( + name, icon_url, + base::Bind(&SigninCreateProfileHandler::OnProfileCreated, + weak_ptr_factory_.GetWeakPtr(), create_shortcut)); +} + void SigninCreateProfileHandler::RequestDefaultProfileIcons( const base::ListValue* args) { web_ui()->CallJavascriptFunctionUnsafe( @@ -121,17 +158,6 @@ void SigninCreateProfileHandler::CreateProfile(const base::ListValue* args) { DoCreateProfile(name, icon_url, create_shortcut); } -void SigninCreateProfileHandler::DoCreateProfile(const base::string16& name, - const std::string& icon_url, - bool create_shortcut) { - ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_USER_DIALOG); - - profile_path_being_created_ = ProfileManager::CreateMultiProfileAsync( - name, icon_url, - base::Bind(&SigninCreateProfileHandler::OnProfileCreated, - weak_ptr_factory_.GetWeakPtr(), create_shortcut)); -} - void SigninCreateProfileHandler::OnProfileCreated( bool create_shortcut, Profile* profile, @@ -210,26 +236,6 @@ void SigninCreateProfileHandler::CreateShortcutAndShowSuccess( profile_creation_type_ = NO_CREATION_IN_PROGRESS; } -void SigninCreateProfileHandler::OpenNewWindowForProfile( - Profile* profile, - Profile::CreateStatus status) { - profiles::OpenBrowserWindowForProfile( - base::Bind(&SigninCreateProfileHandler::OnBrowserReadyCallback, - weak_ptr_factory_.GetWeakPtr()), - false, // Don't create a window if one already exists. - true, // Create a first run window. - false, // There is no need to unblock all extensions because we only open - // browser window if the Profile is not locked. Hence there is no - // extension blocked. - profile, status); -} - -void SigninCreateProfileHandler::OpenForceSigninDialogForProfile( - Profile* profile) { - UserManagerProfileDialog::ShowForceSigninDialog( - web_ui()->GetWebContents()->GetBrowserContext(), profile->GetPath()); -} - void SigninCreateProfileHandler::ShowProfileCreationError( Profile* profile, const base::string16& error) { @@ -260,30 +266,16 @@ base::string16 SigninCreateProfileHandler::GetProfileCreationErrorMessageLocal() return l10n_util::GetStringUTF16(IDS_PROFILES_CREATE_LOCAL_ERROR); } -void SigninCreateProfileHandler::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_BROWSER_OPENED, type); - - // Only respond to one Browser Opened event. - registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - UserManager::Hide(); -} - void SigninCreateProfileHandler::OnBrowserReadyCallback( Profile* profile, Profile::CreateStatus profile_create_status) { Browser* browser = chrome::FindAnyBrowser(profile, false); // Closing the User Manager before the window is created can flakily cause // Chrome to close. - if (browser && browser->window()) { + if (browser && browser->window()) UserManager::Hide(); - } else { - registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - } + else + BrowserList::AddObserver(this); } base::Value SigninCreateProfileHandler::GetWebUIListenerName( diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h index db7c0811783..020f91adad3 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h @@ -12,9 +12,8 @@ #include "base/time/time.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_window.h" +#include "chrome/browser/ui/browser_list_observer.h" #include "chrome/common/buildflags.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_ui_message_handler.h" #include "google_apis/gaia/google_service_auth_error.h" @@ -25,14 +24,35 @@ class ListValue; // Handler for the 'create profile' page. class SigninCreateProfileHandler : public content::WebUIMessageHandler, - public content::NotificationObserver { + public BrowserListObserver { public: SigninCreateProfileHandler(); ~SigninCreateProfileHandler() override; void GetLocalizedValues(base::DictionaryValue* localized_strings); + // WebUIMessageHandler: + void RegisterMessages() override; + + // BrowserListObserver: + void OnBrowserAdded(Browser* browser) override; + protected: + // These methods are virtual for testing. + // Opens a new window for |profile|. + virtual void OpenNewWindowForProfile(Profile* profile, + Profile::CreateStatus status); + + // Opens a new signin dialog for |profile|. + virtual void OpenForceSigninDialogForProfile(Profile* profile); + + // Asynchronously creates and initializes a new profile. + virtual void DoCreateProfile(const base::string16& name, + const std::string& icon_url, + bool create_shortcut); + + private: + friend class TestSigninCreateProfileHandler; FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest, ReturnDefaultProfileIcons); FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest, @@ -41,15 +61,6 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler, CreateProfile); FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest, CreateProfileWithForceSignin); - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - // content::NotificationObserver implementation: - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - // Represents the final profile creation status. It is used to map // the status to the javascript method to be called. enum ProfileCreationStatus { @@ -92,13 +103,6 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler, void CreateShortcutAndShowSuccess(bool create_shortcut, Profile* profile); - // Opens a new window for |profile|. - virtual void OpenNewWindowForProfile(Profile* profile, - Profile::CreateStatus status); - - // Opens a new signin dialog for |profile|. - virtual void OpenForceSigninDialogForProfile(Profile* profile); - // This callback is run after a new browser (but not the window) has been // created for the new profile. void OnBrowserReadyCallback(Profile* profile, Profile::CreateStatus status); @@ -123,18 +127,10 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler, // 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_; - - // Asynchronously creates and initializes a new profile. - virtual void DoCreateProfile(const base::string16& name, - const std::string& icon_url, - bool create_shortcut); - - content::NotificationRegistrar registrar_; + ProfileCreationOperationType profile_creation_type_ = NO_CREATION_IN_PROGRESS; base::WeakPtrFactory<SigninCreateProfileHandler> weak_ptr_factory_{this}; - private: DISALLOW_COPY_AND_ASSIGN(SigninCreateProfileHandler); }; diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc index 8e714ee6b01..1a448873b44 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc @@ -101,8 +101,8 @@ class SigninCreateProfileHandlerTest : public BrowserWithTestWindowTest { BrowserWithTestWindowTest::SetUp(); profile_manager()->DeleteAllTestingProfiles(); - handler_.reset(new TestSigninCreateProfileHandler(web_ui(), - profile_manager())); + handler_ = std::make_unique<TestSigninCreateProfileHandler>( + web_ui(), profile_manager()); } void TearDown() override { diff --git a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc index 1aaef4ddc1f..fbdc4b44378 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_ui.cc @@ -23,7 +23,7 @@ SigninEmailConfirmationUI::SigninEmailConfirmationUI(content::WebUI* web_ui) content::WebUIDataSource* source = content::WebUIDataSource::Create( chrome::kChromeUISigninEmailConfirmationHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SIGNIN_EMAIL_CONFIRMATION_HTML); source->AddResourcePath("signin_email_confirmation.js", IDR_SIGNIN_EMAIL_CONFIRMATION_JS); diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc index 1f5e003de36..362f08bf1fa 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_error_handler_unittest.cc @@ -71,7 +71,7 @@ class SigninErrorHandlerTest : public BrowserWithTestWindowTest { chrome::NewTab(browser()); web_ui()->set_web_contents( browser()->tab_strip_model()->GetActiveWebContents()); - signin_error_ui_.reset(new SigninErrorUI(web_ui())); + signin_error_ui_ = std::make_unique<SigninErrorUI>(web_ui()); } void TearDown() override { @@ -85,7 +85,7 @@ class SigninErrorHandlerTest : public BrowserWithTestWindowTest { auto handler = std::make_unique<TestingSigninErrorHandler>( browser(), false /* is_system_profile */, web_ui()); handler_ = handler.get(); - signin_error_ui_.reset(new SigninErrorUI(web_ui())); + signin_error_ui_ = std::make_unique<SigninErrorUI>(web_ui()); web_ui()->AddMessageHandler(std::move(handler)); } diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc index b7fc877daf6..5a6f3effed4 100644 --- a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc @@ -66,7 +66,7 @@ void SigninErrorUI::Initialize(Browser* browser, bool is_system_profile) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISigninErrorHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->SetDefaultResource(IDR_SIGNIN_ERROR_HTML); source->AddResourcePath("signin_error.js", IDR_SIGNIN_ERROR_JS); source->AddResourcePath("signin_shared_css.html", IDR_SIGNIN_SHARED_CSS_HTML); diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc index 59859724861..2ae8e584e01 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc @@ -104,7 +104,7 @@ void SyncConfirmationHandler::HandleAccountImageRequest( const base::ListValue* args) { DCHECK(profile_->IsSyncAllowed()); base::Optional<AccountInfo> primary_account_info = - identity_manager_->FindExtendedAccountInfoForAccount( + identity_manager_->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager_->GetPrimaryAccountInfo()); // Fire the "account-image-changed" listener from |SetUserImageURL()|. @@ -215,7 +215,7 @@ void SyncConfirmationHandler::HandleInitializedWithSize( return; base::Optional<AccountInfo> primary_account_info = - identity_manager_->FindExtendedAccountInfoForAccount( + identity_manager_->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager_->GetPrimaryAccountInfo()); if (!primary_account_info) { // No account is signed in, so there is nothing to be displayed in the sync diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc index 3593351d31e..a38f485d26e 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc @@ -31,7 +31,7 @@ #include "components/consent_auditor/fake_consent_auditor.h" #include "components/signin/public/base/avatar_icon_util.h" #include "components/unified_consent/scoped_unified_consent.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_web_ui.h" const int kExpectedProfileImageSize = 128; @@ -86,7 +86,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, auto handler = std::make_unique<TestingSyncConfirmationHandler>( browser(), web_ui(), GetStringToGrdIdMap()); handler_ = handler.get(); - sync_confirmation_ui_.reset(new SyncConfirmationUI(web_ui())); + sync_confirmation_ui_ = std::make_unique<SyncConfirmationUI>(web_ui()); web_ui()->AddMessageHandler(std::move(handler)); identity_test_env_adaptor_ = @@ -168,7 +168,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest, signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile()); base::Optional<AccountInfo> primary_account = - identity_manager->FindExtendedAccountInfoForAccount( + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager->GetPrimaryAccountInfo()); std::string original_picture_url = diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index 5d58676bbbe..233b67c2b9d 100644 --- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc @@ -33,7 +33,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISyncConfirmationHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("signin_shared_css.html", IDR_SIGNIN_SHARED_CSS_HTML); if (is_sync_allowed) { @@ -67,7 +67,7 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui) signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); base::Optional<AccountInfo> primary_account_info = - identity_manager->FindExtendedAccountInfoForAccount( + identity_manager->FindExtendedAccountInfoForAccountWithRefreshToken( identity_manager->GetPrimaryAccountInfo()); GURL account_picture_url(primary_account_info ? primary_account_info->picture_url 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 1e7be5fffb2..faa9222bb43 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 @@ -21,7 +21,6 @@ #include "base/value_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" @@ -52,7 +51,6 @@ #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" -#include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" @@ -296,7 +294,9 @@ UserManagerScreenHandler::UserManagerScreenHandler() { } } -UserManagerScreenHandler::~UserManagerScreenHandler() {} +UserManagerScreenHandler::~UserManagerScreenHandler() { + BrowserList::RemoveObserver(this); +} void UserManagerScreenHandler::HandleInitialize(const base::ListValue* args) { // If the URL has a hash parameter, store it for later. @@ -349,10 +349,10 @@ void UserManagerScreenHandler::HandleAuthenticatedLaunchUser( // still have a hash of the old one. The new way of checking a password // change makes use of a token so we do that... if it's available. if (!oauth_client_) { - oauth_client_.reset(new gaia::GaiaOAuthClient( + oauth_client_ = std::make_unique<gaia::GaiaOAuthClient>( content::BrowserContext::GetDefaultStoragePartition( web_ui()->GetWebContents()->GetBrowserContext()) - ->GetURLLoaderFactoryForBrowserProcess())); + ->GetURLLoaderFactoryForBrowserProcess()); } const std::string token = entry->GetPasswordChangeDetectionToken(); @@ -620,6 +620,37 @@ void UserManagerScreenHandler::RegisterMessages() { web_ui()->RegisterMessageCallback("noPodFocused", base::DoNothing()); } +void UserManagerScreenHandler::OnBrowserAdded(Browser* browser) { + // Only respond to one Browser Opened event. + BrowserList::RemoveObserver(this); + + // Unlock the profile after browser opens so startup can read the lock bit. + // Any necessary authentication must have been successful to reach this point. + ProfileAttributesEntry* entry = nullptr; + if (!browser->profile()->IsGuestSession()) { + bool has_entry = g_browser_process->profile_manager() + ->GetProfileAttributesStorage() + .GetProfileAttributesWithPath( + browser->profile()->GetPath(), &entry); + DCHECK(has_entry); + // If force sign in is enabled and profile is not signed in, do not close + // UserManager and unlock profile. + if (signin_util::IsForceSigninEnabled() && !entry->IsAuthenticated()) + return; + entry->SetIsSigninRequired(false); + } + + if (!url_hash_.empty()) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&UrlHashHelper::ExecuteUrlHash, + base::Owned(new UrlHashHelper(browser, url_hash_)))); + } + + // This call is last as it deletes this object. + UserManager::Hide(); +} + void UserManagerScreenHandler::GetLocalizedValues( base::DictionaryValue* localized_strings) { // For Control Bar. @@ -827,48 +858,6 @@ void UserManagerScreenHandler::ReportAuthenticationResult( } } -void UserManagerScreenHandler::OnBrowserOpened(Browser* browser) { - DCHECK(browser); - DCHECK(browser->window()); - - // Unlock the profile after browser opens so startup can read the lock bit. - // Any necessary authentication must have been successful to reach this point. - ProfileAttributesEntry* entry = nullptr; - if (!browser->profile()->IsGuestSession()) { - bool has_entry = g_browser_process->profile_manager()-> - GetProfileAttributesStorage(). - GetProfileAttributesWithPath(browser->profile()->GetPath(), &entry); - DCHECK(has_entry); - // If force sign in is enabled and profile is not signed in, do not close - // UserManager and unlock profile. - if (signin_util::IsForceSigninEnabled() && !entry->IsAuthenticated()) - return; - entry->SetIsSigninRequired(false); - } - - if (!url_hash_.empty()) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&UrlHashHelper::ExecuteUrlHash, - base::Owned(new UrlHashHelper(browser, url_hash_)))); - } - - // This call is last as it deletes this object. - UserManager::Hide(); -} - -void UserManagerScreenHandler::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_BROWSER_OPENED, type); - - // Only respond to one Browser Opened event. - registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - OnBrowserOpened(content::Source<Browser>(source).ptr()); -} - // This callback is run after switching to a new profile has finished. This // means either a new browser has been created (but not the window), or an // existing one has been found. The HideUserManager task needs to be posted @@ -877,10 +866,8 @@ void UserManagerScreenHandler::Observe( void UserManagerScreenHandler::OnSwitchToProfileComplete( Profile* profile, Profile::CreateStatus profile_create_status) { Browser* browser = chrome::FindAnyBrowser(profile, false); - if (browser && browser->window()) { - OnBrowserOpened(browser); - } else { - registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED, - content::NotificationService::AllSources()); - } + if (browser && browser->window()) + OnBrowserAdded(browser); + else + BrowserList::AddObserver(this); } diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h index 8906900c485..0e405c571b0 100644 --- a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h +++ b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h @@ -17,8 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_statistics.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" +#include "chrome/browser/ui/browser_list_observer.h" #include "content/public/browser/web_ui_message_handler.h" #include "google_apis/gaia/gaia_oauth_client.h" @@ -43,10 +42,9 @@ enum AuthenticatedLaunchUserEvent { EVENT_COUNT, }; -class UserManagerScreenHandler - : public content::WebUIMessageHandler, - public gaia::GaiaOAuthClient::Delegate, - public content::NotificationObserver { +class UserManagerScreenHandler : public content::WebUIMessageHandler, + public BrowserListObserver, + public gaia::GaiaOAuthClient::Delegate { public: UserManagerScreenHandler(); ~UserManagerScreenHandler() override; @@ -58,13 +56,11 @@ class UserManagerScreenHandler // that all the visible user manager screens can be updated. class ProfileUpdateObserver; - // WebUIMessageHandler implementation. + // WebUIMessageHandler: void RegisterMessages() override; - // content::NotificationObserver implementation: - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; + // BrowserListObserver: + void OnBrowserAdded(Browser* browser) override; void HandleInitialize(const base::ListValue* args); void HandleAuthenticatedLaunchUser(const base::ListValue* args); @@ -83,15 +79,12 @@ class UserManagerScreenHandler base::Time start_time, profiles::ProfileCategoryStats result); - // Handle GAIA auth results. + // gaia::GaiaOAuthClient::Delegate: void OnGetTokenInfoResponse( std::unique_ptr<base::DictionaryValue> token_info) override; void OnOAuthError() override; void OnNetworkError(int response_code) override; - // Handle when Notified of a NOTIFICATION_BROWSER_OPENED event. - void OnBrowserOpened(Browser* browser); - // Sends user list to account chooser. void SendUserList(); @@ -119,8 +112,6 @@ class UserManagerScreenHandler // URL hash, used to key post-profile actions if present. std::string url_hash_; - content::NotificationRegistrar registrar_; - // The CancelableTaskTracker is currently used by GetProfileStatistics base::CancelableTaskTracker tracker_; diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc index cd70f2e9a14..628865ae71b 100644 --- a/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc @@ -61,7 +61,7 @@ content::WebUIDataSource* UserManagerUI::CreateUIDataSource( source->AddBoolean("isForceSigninEnabled", signin_util::IsForceSigninEnabled()); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("control_bar.html", IDR_CONTROL_BAR_HTML); source->AddResourcePath("control_bar.js", IDR_CONTROL_BAR_JS); diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc index 6181aae010b..8f288996daf 100644 --- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc @@ -27,7 +27,7 @@ content::WebUIDataSource* CreateSignInInternalsHTMLSource() { source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("signin_internals.js", IDR_SIGNIN_INTERNALS_INDEX_JS); source->SetDefaultResource(IDR_SIGNIN_INTERNALS_INDEX_HTML); return source; diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc index 701e6da03b0..3430d836de6 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc @@ -90,6 +90,8 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = { {CONTENT_SETTINGS_TYPE_BLUETOOTH_SCANNING, "bluetooth-scanning"}, {CONTENT_SETTINGS_TYPE_HID_GUARD, "hid-devices"}, {CONTENT_SETTINGS_TYPE_HID_CHOOSER_DATA, kHidChooserDataGroupType}, + {CONTENT_SETTINGS_TYPE_NATIVE_FILE_SYSTEM_WRITE_GUARD, + "native-file-system-write"}, // Add new content settings here if a corresponding Javascript string // representation for it is not required. Note some exceptions do have UI in 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 0a9cddf2b14..fa6bc52b900 100644 --- a/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc +++ b/chromium/chrome/browser/ui/webui/site_settings_helper_unittest.cc @@ -20,8 +20,9 @@ #include "components/content_settings/core/test/content_settings_mock_provider.h" #include "components/content_settings/core/test/content_settings_test_utils.h" #include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/extension_registry.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -63,7 +64,7 @@ class SiteSettingsHelperTest : public testing::Test { } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(SiteSettingsHelperTest, CheckExceptionOrder) { @@ -457,9 +458,10 @@ class SiteSettingsHelperChooserExceptionTest : public testing::Test { device_manager_.CreateAndAddDevice(6354, 0, "Google", "Gadget", ""); auto* chooser_context = UsbChooserContextFactory::GetForProfile(profile()); - device::mojom::UsbDeviceManagerPtr device_manager_ptr; - device_manager_.AddBinding(mojo::MakeRequest(&device_manager_ptr)); - chooser_context->SetDeviceManagerForTesting(std::move(device_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager; + device_manager_.AddReceiver( + device_manager.InitWithNewPipeAndPassReceiver()); + chooser_context->SetDeviceManagerForTesting(std::move(device_manager)); chooser_context->GetDevices( base::DoNothing::Once<std::vector<device::mojom::UsbDeviceInfoPtr>>()); base::RunLoop().RunUntilIdle(); @@ -490,7 +492,7 @@ class SiteSettingsHelperChooserExceptionTest : public testing::Test { device::FakeUsbDeviceManager device_manager_; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn index 0575b4b15d2..f83f5c25536 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn +++ b/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn @@ -8,7 +8,4 @@ mojom("mojo_bindings") { sources = [ "snippets_internals.mojom", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc index 82628d37081..2bcda35f859 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc +++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.cc @@ -117,8 +117,7 @@ SnippetsInternalsPageHandler::SnippetsInternalsPageHandler( content_suggestions_service_ ->remote_suggestions_provider_for_debugging()), pref_service_(pref_service), - page_(std::move(page)), - weak_ptr_factory_(this) {} + page_(std::move(page)) {} SnippetsInternalsPageHandler::~SnippetsInternalsPageHandler() {} diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h index e2ab4c8cbb3..7702050a60e 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h +++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_page_handler.h @@ -92,7 +92,7 @@ class SnippetsInternalsPageHandler // Handle back to the page by which we can update. snippets_internals::mojom::PagePtr page_; - base::WeakPtrFactory<SnippetsInternalsPageHandler> weak_ptr_factory_; + base::WeakPtrFactory<SnippetsInternalsPageHandler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SnippetsInternalsPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc index cfe01dc50f0..89f723083ee 100644 --- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc @@ -53,9 +53,9 @@ void SnippetsInternalsUI::CreatePageHandler( CreatePageHandlerCallback callback) { DCHECK(page); snippets_internals::mojom::PageHandlerPtr handler; - page_handler_.reset(new SnippetsInternalsPageHandler( + page_handler_ = std::make_unique<SnippetsInternalsPageHandler>( mojo::MakeRequest(&handler), std::move(page), - content_suggestions_service_, pref_service_)); + content_suggestions_service_, pref_service_); std::move(callback).Run(std::move(handler)); } diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc index 28d6c59af0f..be07aad14bc 100644 --- a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc +++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc @@ -17,6 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service.h" +#include "chrome/browser/supervised_user/supervised_user_error_page/supervised_user_error_page.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" @@ -24,7 +25,6 @@ #include "chrome/browser/supervised_user/supervised_user_url_filter.h" #include "chrome/common/channel_info.h" #include "components/signin/public/identity_manager/identity_manager.h" -#include "components/supervised_user_error_page/supervised_user_error_page.h" #include "components/url_formatter/url_fixer.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h index 7be0cfac16b..f257eaac9ec 100644 --- a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h +++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h @@ -9,9 +9,9 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" +#include "chrome/browser/supervised_user/supervised_user_error_page/supervised_user_error_page.h" #include "chrome/browser/supervised_user/supervised_user_service_observer.h" #include "chrome/browser/supervised_user/supervised_user_url_filter.h" -#include "components/supervised_user_error_page/supervised_user_error_page.h" #include "content/public/browser/web_ui_message_handler.h" namespace base { diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc index cf5c1ba9541..d21278ee6f6 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc @@ -18,6 +18,7 @@ #include "chrome/browser/sync_file_system/sync_file_system_service_factory.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/common/extension.h" @@ -28,6 +29,10 @@ namespace syncfs_internals { namespace { +// TODO(crbug.com/989631): Break this and GetExtensionStatusesAsDictionary +// into a separate library, so the callbacks can use weak pointers to the +// calling instances. This will also break the dependency between +// ExtensionStatusesHandler and FileMetadataHandler. void ConvertExtensionStatusToDictionary( const base::WeakPtr<extensions::ExtensionService>& extension_service, const base::Callback<void(const base::ListValue&)>& callback, @@ -37,13 +42,17 @@ void ConvertExtensionStatusToDictionary( return; } + extensions::ExtensionRegistry* extension_registry = + extensions::ExtensionRegistry::Get(extension_service->profile()); + base::ListValue list; for (auto itr = status_map.begin(); itr != status_map.end(); ++itr) { std::string extension_id = itr->first.HostNoBrackets(); // Join with human readable extension name. const extensions::Extension* extension = - extension_service->GetExtensionById(extension_id, true); + extension_registry->GetExtensionById( + extension_id, extensions::ExtensionRegistry::COMPATIBILITY); if (!extension) continue; diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc index 50edaaa95b8..bdc01392797 100644 --- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.cc @@ -22,7 +22,7 @@ content::WebUIDataSource* CreateSyncFileSystemInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create( chrome::kChromeUISyncFileSystemInternalsHost); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath( "utils.js", IDR_SYNC_FILE_SYSTEM_INTERNALS_UTILS_JS); diff --git a/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc index 0e69a9c4617..b4091b4eab5 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler_unittest.cc @@ -120,11 +120,11 @@ class SyncInternalsMessageHandlerTest : public ChromeRenderViewHostTestHarness { browser_sync::UserEventServiceFactory::GetInstance() ->SetTestingFactoryAndUse( profile(), base::BindRepeating(&BuildFakeUserEventService))); - handler_.reset(new TestableSyncInternalsMessageHandler( + handler_ = std::make_unique<TestableSyncInternalsMessageHandler>( &web_ui_, base::BindRepeating( &SyncInternalsMessageHandlerTest::ConstructAboutInformation, - base::Unretained(this)))); + base::Unretained(this))); } void TearDown() override { diff --git a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc index 8b360af1286..d4d18359242 100644 --- a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc @@ -22,7 +22,7 @@ content::WebUIDataSource* CreateSyncInternalsHTMLSource() { source->OverrideContentSecurityPolicyScriptSrc( "script-src chrome://resources 'self' 'unsafe-eval';"); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath(syncer::sync_ui_util::kSyncIndexJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_JS); source->AddResourcePath(syncer::sync_ui_util::kChromeSyncJS, diff --git a/chromium/chrome/browser/ui/webui/system_info_ui.cc b/chromium/chrome/browser/ui/webui/system_info_ui.cc index cf886af54c8..12a75b82441 100644 --- a/chromium/chrome/browser/ui/webui/system_info_ui.cc +++ b/chromium/chrome/browser/ui/webui/system_info_ui.cc @@ -66,7 +66,7 @@ content::WebUIDataSource* CreateSystemInfoUIDataSource() { html_source->AddResourcePath("about_sys.js", IDR_ABOUT_SYS_JS); html_source->AddResourcePath("about_sys.css", IDR_ABOUT_SYS_CSS); html_source->SetDefaultResource(IDR_ABOUT_SYS_HTML); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); return html_source; } diff --git a/chromium/chrome/browser/ui/webui/tab_strip/OWNERS b/chromium/chrome/browser/ui/webui/tab_strip/OWNERS new file mode 100644 index 00000000000..b84c705bb6e --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/OWNERS @@ -0,0 +1,4 @@ +dpapad@chromium.org +johntlee@chromium.org + +# COMPONENT: UI>Browser>WebUI diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.cc b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.cc new file mode 100644 index 00000000000..f294f8d2890 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.cc @@ -0,0 +1,166 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui.h" + +#include <memory> +#include <string> +#include <utility> +#include <vector> + +#include "base/base64.h" +#include "base/values.h" +#include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/favicon_source.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/tab_strip_resources.h" +#include "chrome/grit/tab_strip_resources_map.h" +#include "components/favicon_base/favicon_url_parser.h" +#include "content/public/browser/url_data_source.h" +#include "content/public/browser/web_ui_data_source.h" +#include "content/public/browser/web_ui_message_handler.h" +#include "third_party/skia/include/core/SkImageEncoder.h" +#include "third_party/skia/include/core/SkStream.h" + +namespace { + +// Writes bytes to a std::vector that can be fetched. This is used to record the +// output of skia image encoding. +// +// TODO(crbug.com/991393): remove this when we no longer transcode images here. +class BufferWStream : public SkWStream { + public: + BufferWStream() = default; + ~BufferWStream() override = default; + + // Returns the output buffer by moving. + std::vector<unsigned char> GetBuffer() { return std::move(result_); } + + // SkWStream: + bool write(const void* buffer, size_t size) override { + const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buffer); + result_.insert(result_.end(), bytes, bytes + size); + return true; + } + + size_t bytesWritten() const override { return result_.size(); } + + private: + std::vector<unsigned char> result_; +}; + +class TabStripUIHandler : public content::WebUIMessageHandler { + public: + explicit TabStripUIHandler(Profile* profile) + : profile_(profile), + thumbnail_tracker_(base::Bind(&TabStripUIHandler::HandleThumbnailUpdate, + base::Unretained(this))) {} + ~TabStripUIHandler() override = default; + + protected: + void RegisterMessages() override { + web_ui()->RegisterMessageCallback( + "addTrackedTab", + base::Bind(&TabStripUIHandler::AddTrackedTab, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "removeTrackedTab", base::Bind(&TabStripUIHandler::RemoveTrackedTab, + base::Unretained(this))); + } + + private: + void AddTrackedTab(const base::ListValue* args) { + AllowJavascript(); + + int tab_id = 0; + if (!args->GetInteger(0, &tab_id)) + return; + + content::WebContents* tab = nullptr; + if (!extensions::ExtensionTabUtil::GetTabById(tab_id, profile_, true, + &tab)) { + // ID didn't refer to a valid tab. + DVLOG(1) << "Invalid tab ID"; + return; + } + thumbnail_tracker_.WatchTab(tab); + } + + void RemoveTrackedTab(const base::ListValue* args) { + AllowJavascript(); + + int tab_id = 0; + if (!args->GetInteger(0, &tab_id)) + return; + // TODO(crbug.com/991393): un-watch tabs when we are done. + } + + // Callback passed to |thumbnail_tracker_|. Called when a tab's thumbnail + // changes, or when we start watching the tab. + void HandleThumbnailUpdate(content::WebContents* tab, gfx::ImageSkia image) { + const SkBitmap& bitmap = + image.GetRepresentation(web_ui()->GetDeviceScaleFactor()).GetBitmap(); + BufferWStream stream; + const bool encoding_succeeded = + SkEncodeImage(&stream, bitmap, SkEncodedImageFormat::kJPEG, 100); + DCHECK(encoding_succeeded); + const std::vector<unsigned char> image_data = stream.GetBuffer(); + + // Send base-64 encoded image to JS side. + // + // TODO(crbug.com/991393): streamline the process from tab capture to + // sending the image. Currently, a frame is captured, sent to + // ThumbnailImage, encoded to JPEG (w/ a copy), decoded to a raw bitmap + // (another copy), and sent to observers. Here, we then re-encode the image + // to a JPEG (another copy), encode to base64 (another copy), append the + // base64 header (another copy), and send it (another copy). This is 6 + // copies of essentially the same image, and it is de-encoded and re-encoded + // to the same format. We can reduce the number of copies and avoid the + // redundant encoding. + std::string encoded_image = + base::Base64Encode(base::as_bytes(base::make_span(image_data))); + encoded_image = "data:image/jpeg;base64," + encoded_image; + + const int tab_id = extensions::ExtensionTabUtil::GetTabId(tab); + FireWebUIListener("tab-thumbnail-updated", base::Value(tab_id), + base::Value(encoded_image)); + } + + Profile* profile_; + ThumbnailTracker thumbnail_tracker_; + + DISALLOW_COPY_AND_ASSIGN(TabStripUIHandler); +}; + +} // namespace + +TabStripUI::TabStripUI(content::WebUI* web_ui) + : content::WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource* html_source = + content::WebUIDataSource::Create(chrome::kChromeUITabStripHost); + + std::string generated_path = + "@out_folder@/gen/chrome/browser/resources/tab_strip/"; + + for (size_t i = 0; i < kTabStripResourcesSize; ++i) { + std::string path = kTabStripResources[i].name; + if (path.rfind(generated_path, 0) == 0) { + path = path.substr(generated_path.length()); + } + html_source->AddResourcePath(path, kTabStripResources[i].value); + } + + html_source->SetDefaultResource(IDR_TAB_STRIP_HTML); + + content::WebUIDataSource::Add(profile, html_source); + + content::URLDataSource::Add( + profile, std::make_unique<FaviconSource>( + profile, chrome::FaviconUrlFormat::kFavicon2)); + + web_ui->AddMessageHandler(std::make_unique<TabStripUIHandler>(profile)); +} + +TabStripUI::~TabStripUI() {} diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.h b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.h new file mode 100644 index 00000000000..8e8b31d9ddf --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui.h @@ -0,0 +1,25 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_TAB_STRIP_TAB_STRIP_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_TAB_STRIP_TAB_STRIP_UI_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h" +#include "content/public/browser/web_ui_controller.h" + +// The WebUI version of the tab strip in the browser. It is currently only +// supported on ChromeOS in tablet mode. +class TabStripUI : public content::WebUIController { + public: + explicit TabStripUI(content::WebUI* web_ui); + ~TabStripUI() override; + + private: + void HandleThumbnailUpdate(int extension_tab_id, gfx::ImageSkia image); + + DISALLOW_COPY_AND_ASSIGN(TabStripUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_TAB_STRIP_TAB_STRIP_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.cc b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.cc new file mode 100644 index 00000000000..6c74dd96578 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.cc @@ -0,0 +1,103 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h" + +#include <memory> +#include <utility> + +#include "base/scoped_observer.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/thumbnails/thumbnail_image.h" +#include "chrome/browser/ui/thumbnails/thumbnail_tab_helper.h" +#include "content/public/browser/web_contents_observer.h" + +// Handles requests for a given tab's thumbnail and watches for thumbnail +// updates for the lifetime of the tab. +class ThumbnailTracker::ContentsData : public content::WebContentsObserver, + public ThumbnailImage::Observer { + public: + ContentsData(ThumbnailTracker* parent, content::WebContents* contents) + : content::WebContentsObserver(contents), + parent_(parent), + observer_(this) { + thumbnail_ = parent_->thumbnail_getter_.Run(contents); + if (thumbnail_) + observer_.Add(thumbnail_.get()); + } + + void RequestThumbnail() { + if (thumbnail_) + thumbnail_->RequestThumbnailImage(); + } + + // content::WebContents: + void WebContentsDestroyed() override { + // We must un-observe each ThumbnailImage when the WebContents it came from + // closes. + if (thumbnail_) { + observer_.Remove(thumbnail_.get()); + thumbnail_.reset(); + } + + // Destroy ourself. After this call, |this| doesn't exist! + parent_->ContentsClosed(web_contents()); + } + + // ThumbnailImage::Observer: + void OnThumbnailImageAvailable(gfx::ImageSkia thumbnail_image) override { + parent_->ThumbnailUpdated(web_contents(), thumbnail_image); + } + + private: + ThumbnailTracker* parent_; + scoped_refptr<ThumbnailImage> thumbnail_; + ScopedObserver<ThumbnailImage, ContentsData> observer_; +}; + +ThumbnailTracker::ThumbnailTracker(ThumbnailUpdatedCallback callback) + : ThumbnailTracker(std::move(callback), + base::Bind(GetThumbnailFromTabHelper)) {} + +ThumbnailTracker::ThumbnailTracker(ThumbnailUpdatedCallback callback, + GetThumbnailCallback thumbnail_getter) + : thumbnail_getter_(std::move(thumbnail_getter)), + callback_(std::move(callback)) {} + +ThumbnailTracker::~ThumbnailTracker() = default; + +void ThumbnailTracker::WatchTab(content::WebContents* contents) { + auto data_it = contents_data_.find(contents); + if (data_it == contents_data_.end()) { + data_it = contents_data_.emplace_hint( + data_it, contents, std::make_unique<ContentsData>(this, contents)); + } + + data_it->second->RequestThumbnail(); +} + +void ThumbnailTracker::ThumbnailUpdated(content::WebContents* contents, + gfx::ImageSkia image) { + callback_.Run(contents, image); +} + +void ThumbnailTracker::ContentsClosed(content::WebContents* contents) { + contents_data_.erase(contents); +} + +// static +scoped_refptr<ThumbnailImage> ThumbnailTracker::GetThumbnailFromTabHelper( + content::WebContents* contents) { + ThumbnailTabHelper* thumbnail_helper = + ThumbnailTabHelper::FromWebContents(contents); + // Gracefully handle when ThumbnailTabHelper isn't available. + if (thumbnail_helper) { + auto thumbnail = thumbnail_helper->thumbnail(); + DCHECK(thumbnail); + return thumbnail; + } else { + DVLOG(1) << "ThumbnailTabHelper doesn't exist for tab"; + return nullptr; + } +} diff --git a/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h new file mode 100644 index 00000000000..2d64d3d8ecc --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h @@ -0,0 +1,64 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_TAB_STRIP_THUMBNAIL_TRACKER_H_ +#define CHROME_BROWSER_UI_WEBUI_TAB_STRIP_THUMBNAIL_TRACKER_H_ + +#include <memory> + +#include "base/containers/flat_map.h" +#include "base/memory/scoped_refptr.h" +#include "ui/gfx/image/image_skia.h" + +namespace content { +class WebContents; +} + +class ThumbnailImage; + +// Tracks the thumbnails of a set of WebContentses. This set is dynamically +// managed, and WebContents closure is handled gracefully. The user is notified +// of any thumbnail change via a callback specified on construction. +class ThumbnailTracker { + public: + // Should return the ThumbnailImage instance for a WebContents. + using GetThumbnailCallback = + base::RepeatingCallback<scoped_refptr<ThumbnailImage>( + content::WebContents*)>; + + // Handles a thumbnail update for a tab. + using ThumbnailUpdatedCallback = + base::RepeatingCallback<void(content::WebContents*, gfx::ImageSkia)>; + + explicit ThumbnailTracker(ThumbnailUpdatedCallback callback); + // Specifies how to get a ThumbnailImage for a WebContents. This is intended + // for tests. + ThumbnailTracker(ThumbnailUpdatedCallback callback, + GetThumbnailCallback thumbnail_getter); + + ~ThumbnailTracker(); + + // Registers a tab to receive thumbnail updates for. Also immediately requests + // the current thumbnail. + void WatchTab(content::WebContents* contents); + + private: + void ThumbnailUpdated(content::WebContents* contents, gfx::ImageSkia image); + void ContentsClosed(content::WebContents* contents); + + // The default |GetThumbnailCallback| implementation. + static scoped_refptr<ThumbnailImage> GetThumbnailFromTabHelper( + content::WebContents* contents); + + GetThumbnailCallback thumbnail_getter_; + ThumbnailUpdatedCallback callback_; + + // ContentsData tracks a particular WebContents. One is created for a tab on + // its first thumbnail request and exists until the contents is closed. + class ContentsData; + base::flat_map<content::WebContents*, std::unique_ptr<ContentsData>> + contents_data_; +}; + +#endif // CHROME_BROWSER_UI_WEBUI_TAB_STRIP_THUMBNAIL_TRACKER_H_ diff --git a/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker_unittest.cc b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker_unittest.cc new file mode 100644 index 00000000000..eac65cc2104 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/tab_strip/thumbnail_tracker_unittest.cc @@ -0,0 +1,153 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/tab_strip/thumbnail_tracker.h" + +#include <map> +#include <memory> +#include <utility> + +#include "base/run_loop.h" +#include "base/test/mock_callback.h" +#include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/sessions/session_tab_helper.h" +#include "chrome/browser/ui/thumbnails/thumbnail_image.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/test/browser_task_environment.h" +#include "content/public/test/web_contents_tester.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkBitmap.h" + +namespace { + +class TestThumbnailImageDelegate : public ThumbnailImage::Delegate { + public: + TestThumbnailImageDelegate() = default; + + ~TestThumbnailImageDelegate() override = default; + + void ThumbnailImageBeingObservedChanged(bool is_being_observed) override {} +}; + +class ThumbnailTrackerTest : public ::testing::Test, + public ThumbnailImage::Delegate { + protected: + ThumbnailTrackerTest() + : thumbnail_tracker_( + thumbnail_updated_callback_.Get(), + base::Bind(&ThumbnailTrackerTest::GetTestingThumbnail, + base::Unretained(this))) {} + + static SkBitmap CreateTestingBitmap() { + SkBitmap bitmap; + bitmap.allocN32Pixels(1, 1, true); + bitmap.eraseColor(SK_ColorBLACK); + bitmap.setImmutable(); + return bitmap; + } + + std::unique_ptr<content::WebContents> CreateWebContents() { + auto contents = + content::WebContentsTester::CreateTestWebContents(&profile_, nullptr); + SessionTabHelper::CreateForWebContents(contents.get()); + return contents; + } + + scoped_refptr<ThumbnailImage> GetTestingThumbnail( + content::WebContents* contents) { + return tab_thumbnails_[contents].thumbnail_image; + } + + // ThumbnailImage::Delegate: + void ThumbnailImageBeingObservedChanged(bool is_being_observed) override {} + + content::BrowserTaskEnvironment task_environment_; + TestingProfile profile_; + + base::MockCallback<ThumbnailTracker::ThumbnailUpdatedCallback> + thumbnail_updated_callback_; + + struct ThumbnailData { + ThumbnailData() + : thumbnail_image(base::MakeRefCounted<ThumbnailImage>(&delegate)) {} + + TestThumbnailImageDelegate delegate; + scoped_refptr<ThumbnailImage> thumbnail_image; + }; + std::map<content::WebContents*, ThumbnailData> tab_thumbnails_; + + ThumbnailTracker thumbnail_tracker_; +}; + +} // namespace + +using ::testing::_; + +TEST_F(ThumbnailTrackerTest, WatchTabGetsCurrentThumbnail) { + auto contents = CreateWebContents(); + auto thumbnail = GetTestingThumbnail(contents.get()); + + // Set the thumbnail image and wait for it to be stored. + base::RunLoop encode_loop; + thumbnail->set_async_operation_finished_callback_for_testing( + encode_loop.QuitClosure()); + thumbnail->AssignSkBitmap(CreateTestingBitmap()); + encode_loop.Run(); + + // Verify that WatchTab() gets the current image, waiting for the decoding to + // happen. + EXPECT_CALL(thumbnail_updated_callback_, Run(contents.get(), _)).Times(1); + base::RunLoop notify_loop; + thumbnail->set_async_operation_finished_callback_for_testing( + notify_loop.QuitClosure()); + thumbnail_tracker_.WatchTab(contents.get()); + notify_loop.Run(); +} + +TEST_F(ThumbnailTrackerTest, PropagatesThumbnailUpdate) { + auto contents1 = CreateWebContents(); + auto thumbnail1 = GetTestingThumbnail(contents1.get()); + auto contents2 = CreateWebContents(); + auto thumbnail2 = GetTestingThumbnail(contents2.get()); + + // Since no thumbnail image exists yet, this shouldn't notify our callback. + thumbnail_tracker_.WatchTab(contents1.get()); + thumbnail_tracker_.WatchTab(contents2.get()); + + { + ::testing::InSequence seq; + EXPECT_CALL(thumbnail_updated_callback_, Run(contents1.get(), _)).Times(1); + EXPECT_CALL(thumbnail_updated_callback_, Run(contents2.get(), _)).Times(1); + } + + base::RunLoop first_update_loop; + thumbnail1->set_async_operation_finished_callback_for_testing( + first_update_loop.QuitClosure()); + thumbnail1->AssignSkBitmap(CreateTestingBitmap()); + first_update_loop.Run(); + + base::RunLoop second_update_loop; + thumbnail2->set_async_operation_finished_callback_for_testing( + second_update_loop.QuitClosure()); + thumbnail2->AssignSkBitmap(CreateTestingBitmap()); + second_update_loop.Run(); +} + +TEST_F(ThumbnailTrackerTest, StopsObservingOnTabClose) { + auto contents = CreateWebContents(); + auto thumbnail = GetTestingThumbnail(contents.get()); + thumbnail_tracker_.WatchTab(contents.get()); + + // |thumbnail| is still valid, but |thumbnail_tracker_| should stop watching + // it when |contents| goes away. + EXPECT_CALL(thumbnail_updated_callback_, Run(_, _)).Times(0); + contents.reset(); + + base::RunLoop update_loop; + thumbnail->set_async_operation_finished_callback_for_testing( + update_loop.QuitClosure()); + thumbnail->AssignSkBitmap(CreateTestingBitmap()); + update_loop.Run(); +} diff --git a/chromium/chrome/browser/ui/webui/test_data_source.cc b/chromium/chrome/browser/ui/webui/test_data_source.cc index b857b4fd032..3c2b5ac0d41 100644 --- a/chromium/chrome/browser/ui/webui/test_data_source.cc +++ b/chromium/chrome/browser/ui/webui/test_data_source.cc @@ -31,10 +31,11 @@ std::string TestDataSource::GetSource() { void TestDataSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&TestDataSource::ReadFile, base::Unretained(this), path, callback)); } @@ -71,11 +72,22 @@ GURL TestDataSource::GetURLForPath(const std::string& path) { void TestDataSource::ReadFile( const std::string& path, const content::URLDataSource::GotDataCallback& callback) { - if (test_data_.empty()) { - CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_)); - CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_)); + if (src_root_.empty()) { + base::FilePath test_data; + CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data)); + src_root_ = test_data.Append(FILE_PATH_LITERAL("webui")); } - base::FilePath root = test_data_.Append(FILE_PATH_LITERAL("webui")); + + if (gen_root_.empty()) { + std::string gen_path = "gen/chrome/test/data/webui/"; +#if defined(OS_WIN) + base::ReplaceChars(gen_path, "//", "\\", &gen_path); +#endif + base::FilePath exe_dir; + base::PathService::Get(base::DIR_EXE, &exe_dir); + gen_root_ = exe_dir.AppendASCII(gen_path); + } + std::string content; GURL url = GetURLForPath(path); @@ -83,18 +95,32 @@ void TestDataSource::ReadFile( if (base::StartsWith(url.query(), kModuleQuery, base::CompareCase::INSENSITIVE_ASCII)) { std::string js_path = url.query().substr(strlen(kModuleQuery)); + base::FilePath file_path = - root.Append(base::FilePath::FromUTF8Unsafe(js_path)); + src_root_.Append(base::FilePath::FromUTF8Unsafe(js_path)); // Do some basic validation of the JS file path provided in the query. CHECK_EQ(file_path.Extension(), FILE_PATH_LITERAL(".js")); - CHECK(base::PathExists(file_path)) + + base::FilePath file_path2 = + gen_root_.Append(base::FilePath::FromUTF8Unsafe(js_path)); + CHECK(base::PathExists(file_path) || base::PathExists(file_path2)) << url.spec() << "=" << file_path.value(); content = "<script type=\"module\" src=\"" + js_path + "\"></script>"; } else { + // Try the |src_root_| folder first. base::FilePath file_path = - root.Append(base::FilePath::FromUTF8Unsafe(path)); - CHECK(base::ReadFileToString(file_path, &content)) - << url.spec() << "=" << file_path.value(); + src_root_.Append(base::FilePath::FromUTF8Unsafe(path)); + if (base::PathExists(file_path)) { + CHECK(base::ReadFileToString(file_path, &content)) + << url.spec() << "=" << file_path.value(); + } else { + // Then try the |gen_root_| folder, covering cases where the test file is + // generated at build time. + base::FilePath file_path = + gen_root_.Append(base::FilePath::FromUTF8Unsafe(path)); + CHECK(base::ReadFileToString(file_path, &content)) + << url.spec() << "=" << file_path.value(); + } } scoped_refptr<base::RefCountedString> response = diff --git a/chromium/chrome/browser/ui/webui/test_data_source.h b/chromium/chrome/browser/ui/webui/test_data_source.h index 680979c02c1..86816587eb2 100644 --- a/chromium/chrome/browser/ui/webui/test_data_source.h +++ b/chromium/chrome/browser/ui/webui/test_data_source.h @@ -21,7 +21,7 @@ class TestDataSource : public content::URLDataSource { private: void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; @@ -39,8 +39,8 @@ class TestDataSource : public content::URLDataSource { void ReadFile(const std::string& path, const content::URLDataSource::GotDataCallback& callback); - base::FilePath test_data_; - base::FilePath source_root_; + base::FilePath src_root_; + base::FilePath gen_root_; DISALLOW_COPY_AND_ASSIGN(TestDataSource); }; diff --git a/chromium/chrome/browser/ui/webui/theme_source.cc b/chromium/chrome/browser/ui/webui/theme_source.cc index 673b625f6e0..cc006a1e38e 100644 --- a/chromium/chrome/browser/ui/webui/theme_source.cc +++ b/chromium/chrome/browser/ui/webui/theme_source.cc @@ -80,7 +80,7 @@ std::string ThemeSource::GetSource() { void ThemeSource::StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // Default scale factor if not specified. float scale = 1.0f; @@ -233,7 +233,7 @@ void ThemeSource::SendThemeImage( DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // Fetching image data in ResourceBundle should happen on the UI thread. See // crbug.com/449277 - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ProcessResourceOnUiThread, resource_id, scale, data), base::BindOnce(callback, data)); diff --git a/chromium/chrome/browser/ui/webui/theme_source.h b/chromium/chrome/browser/ui/webui/theme_source.h index aa323d6efbc..321ea0b8fbd 100644 --- a/chromium/chrome/browser/ui/webui/theme_source.h +++ b/chromium/chrome/browser/ui/webui/theme_source.h @@ -24,7 +24,7 @@ class ThemeSource : public content::URLDataSource { std::string GetSource() override; void StartDataRequest( const std::string& path, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter, + const content::WebContents::Getter& wc_getter, const content::URLDataSource::GotDataCallback& callback) override; std::string GetMimeType(const std::string& path) override; scoped_refptr<base::SingleThreadTaskRunner> TaskRunnerForRequestPath( diff --git a/chromium/chrome/browser/ui/webui/theme_source_unittest.cc b/chromium/chrome/browser/ui/webui/theme_source_unittest.cc index abbf029bf54..55ee176f9b1 100644 --- a/chromium/chrome/browser/ui/webui/theme_source_unittest.cc +++ b/chromium/chrome/browser/ui/webui/theme_source_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/common/url_constants.h" #include "chrome/grit/theme_resources.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" class WebUISourcesTest : public testing::Test { @@ -24,18 +24,16 @@ class WebUISourcesTest : public testing::Test { size_t result_data_size() const { return result_data_size_; } void StartDataRequest(const std::string& source) { - theme_source()->StartDataRequest( - source, - content::ResourceRequestInfo::WebContentsGetter(), - callback_); + theme_source()->StartDataRequest(source, content::WebContents::Getter(), + callback_); } size_t result_data_size_; private: void SetUp() override { - profile_.reset(new TestingProfile()); - theme_source_.reset(new ThemeSource(profile_.get())); + profile_ = std::make_unique<TestingProfile>(); + theme_source_ = std::make_unique<ThemeSource>(profile_.get()); callback_ = base::Bind(&WebUISourcesTest::SendResponse, base::Unretained(this)); } @@ -51,7 +49,7 @@ class WebUISourcesTest : public testing::Test { content::URLDataSource::GotDataCallback callback_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<TestingProfile> profile_; std::unique_ptr<ThemeSource> theme_source_; diff --git a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc index dfd9efd9f8f..42d192b77dd 100644 --- a/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/translate_internals/translate_internals_ui.cc @@ -29,7 +29,7 @@ content::WebUIDataSource* CreateTranslateInternalsHTMLSource() { content::WebUIDataSource::Create(chrome::kChromeUITranslateInternalsHost); source->SetDefaultResource(IDR_TRANSLATE_INTERNALS_HTML); - source->SetJsonPath("strings.js"); + source->UseStringsJs(); source->AddResourcePath("translate_internals.js", IDR_TRANSLATE_INTERNALS_JS); base::DictionaryValue langs; diff --git a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn index 5229f5ba6f3..d193360fcec 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") { "//services/device/public/mojom:usb", "//services/device/public/mojom:usb_test", ] - - # TODO(https://crbug.com/968369): Change to use new names. - use_old_js_lite_bindings_names = true } diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom index 88b50f749a2..b980f6586de 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals.mojom @@ -8,9 +8,11 @@ import "services/device/public/mojom/usb_manager.mojom"; import "services/device/public/mojom/usb_manager_test.mojom"; interface UsbInternalsPageHandler { - // Bind the UsbDeviceManager interface to get all devices that connected. - BindUsbDeviceManagerInterface(device.mojom.UsbDeviceManager& request); + // Bind the UsbDeviceManager receiver to get all devices that connected. + BindUsbDeviceManagerInterface( + pending_receiver<device.mojom.UsbDeviceManager> receiver); // Simulate the connection of a new device with the given properties. - BindTestInterface(device.mojom.UsbDeviceManagerTest& request); + BindTestInterface( + pending_receiver<device.mojom.UsbDeviceManagerTest> receiver); }; 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 c5989ed4357..1b4796bba02 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 @@ -11,21 +11,21 @@ #include "services/service_manager/public/cpp/connector.h" UsbInternalsPageHandler::UsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request) - : binding_(this, std::move(request)) {} + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver) + : receiver_(this, std::move(receiver)) {} UsbInternalsPageHandler::~UsbInternalsPageHandler() {} void UsbInternalsPageHandler::BindTestInterface( - device::mojom::UsbDeviceManagerTestRequest request) { + mojo::PendingReceiver<device::mojom::UsbDeviceManagerTest> receiver) { // Forward the request to the DeviceService. - content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, - std::move(request)); + content::GetSystemConnector()->Connect(device::mojom::kServiceName, + std::move(receiver)); } void UsbInternalsPageHandler::BindUsbDeviceManagerInterface( - device::mojom::UsbDeviceManagerRequest request) { + mojo::PendingReceiver<device::mojom::UsbDeviceManager> receiver) { // Forward the request to the DeviceService. - content::GetSystemConnector()->BindInterface(device::mojom::kServiceName, - std::move(request)); + content::GetSystemConnector()->Connect(device::mojom::kServiceName, + std::move(receiver)); } 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 5530f76bc98..01f967c9ce1 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 @@ -7,24 +7,26 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals.mojom.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "services/device/public/mojom/usb_manager.mojom.h" #include "services/device/public/mojom/usb_manager_test.mojom.h" class UsbInternalsPageHandler : public mojom::UsbInternalsPageHandler { public: explicit UsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request); + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver); ~UsbInternalsPageHandler() override; void BindUsbDeviceManagerInterface( - device::mojom::UsbDeviceManagerRequest request) override; + mojo::PendingReceiver<device::mojom::UsbDeviceManager> receiver) override; void BindTestInterface( - device::mojom::UsbDeviceManagerTestRequest request) override; + mojo::PendingReceiver<device::mojom::UsbDeviceManagerTest> receiver) + override; private: - mojo::Binding<mojom::UsbInternalsPageHandler> binding_; + mojo::Receiver<mojom::UsbInternalsPageHandler> receiver_; DISALLOW_COPY_AND_ASSIGN(UsbInternalsPageHandler); }; diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc index abd87cd6619..7b8d5847b99 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.cc @@ -45,6 +45,7 @@ UsbInternalsUI::UsbInternalsUI(content::WebUI* web_ui) UsbInternalsUI::~UsbInternalsUI() {} void UsbInternalsUI::BindUsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request) { - page_handler_.reset(new UsbInternalsPageHandler(std::move(request))); + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver) { + page_handler_ = + std::make_unique<UsbInternalsPageHandler>(std::move(receiver)); } diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h index 0f4fc201756..249d376248e 100644 --- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h +++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_ui.h @@ -7,6 +7,7 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/usb_internals/usb_internals.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/webui/mojo_web_ui_controller.h" class UsbInternalsPageHandler; @@ -19,7 +20,7 @@ class UsbInternalsUI : public ui::MojoWebUIController { private: void BindUsbInternalsPageHandler( - mojom::UsbInternalsPageHandlerRequest request); + mojo::PendingReceiver<mojom::UsbInternalsPageHandler> receiver); std::unique_ptr<UsbInternalsPageHandler> page_handler_; diff --git a/chromium/chrome/browser/ui/webui/version_handler.cc b/chromium/chrome/browser/ui/webui/version_handler.cc index b62cff1dceb..8589c0479e3 100644 --- a/chromium/chrome/browser/ui/webui/version_handler.cc +++ b/chromium/chrome/browser/ui/webui/version_handler.cc @@ -26,6 +26,7 @@ #include "content/public/browser/plugin_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_message_handler.h" #include "content/public/common/content_constants.h" #include "ppapi/buildflags/buildflags.h" #include "ui/base/l10n/l10n_util.h" @@ -66,53 +67,103 @@ void VersionHandler::RegisterMessages() { version_ui::kRequestVersionInfo, base::BindRepeating(&VersionHandler::HandleRequestVersionInfo, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + version_ui::kRequestVariationInfo, + base::BindRepeating(&VersionHandler::HandleRequestVariationInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + version_ui::kRequestPluginInfo, + base::BindRepeating(&VersionHandler::HandleRequestPluginInfo, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + version_ui::kRequestPathInfo, + base::BindRepeating(&VersionHandler::HandleRequestPathInfo, + base::Unretained(this))); } void VersionHandler::HandleRequestVersionInfo(const base::ListValue* args) { + // This method is overridden by platform-specific handlers which may still + // use |CallJavascriptFunction|. Main version info is returned by promise + // using handlers below. + // TODO(orinj): To fully eliminate chrome.send usage in JS, derived classes + // could be made to work more like this base class, using + // |ResolveJavascriptCallback| instead of |CallJavascriptFunction|. + AllowJavascript(); +} + +void VersionHandler::HandleRequestVariationInfo(const base::ListValue* args) { + AllowJavascript(); + + std::string callback_id; + bool include_variations_cmd; + CHECK_EQ(2U, args->GetSize()); + CHECK(args->GetString(0, &callback_id)); + CHECK(args->GetBoolean(1, &include_variations_cmd)); + + base::Value response(base::Value::Type::DICTIONARY); + response.SetKey(version_ui::kKeyVariationsList, + std::move(*version_ui::GetVariationsList())); + if (include_variations_cmd) { + response.SetKey(version_ui::kKeyVariationsCmd, + version_ui::GetVariationsCommandLineAsValue()); + } + ResolveJavascriptCallback(base::Value(callback_id), response); +} + +void VersionHandler::HandleRequestPluginInfo(const base::ListValue* args) { AllowJavascript(); + + std::string callback_id; + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &callback_id)); + #if BUILDFLAG(ENABLE_PLUGINS) // The Flash version information is needed in the response, so make sure // the plugins are loaded. content::PluginService::GetInstance()->GetPlugins( - base::Bind(&VersionHandler::OnGotPlugins, - weak_ptr_factory_.GetWeakPtr())); + base::Bind(&VersionHandler::OnGotPlugins, weak_ptr_factory_.GetWeakPtr(), + callback_id)); +#else + RejectJavascriptCallback(base::Value(callback_id), base::Value()); #endif +} + +void VersionHandler::HandleRequestPathInfo(const base::ListValue* args) { + AllowJavascript(); + + std::string callback_id; + CHECK_EQ(1U, args->GetSize()); + CHECK(args->GetString(0, &callback_id)); // Grab the executable path on the FILE thread. It is returned in // OnGotFilePaths. base::string16* exec_path_buffer = new base::string16; base::string16* profile_path_buffer = new base::string16; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&GetFilePaths, Profile::FromWebUI(web_ui())->GetPath(), base::Unretained(exec_path_buffer), base::Unretained(profile_path_buffer)), - base::BindOnce( - &VersionHandler::OnGotFilePaths, weak_ptr_factory_.GetWeakPtr(), - base::Owned(exec_path_buffer), base::Owned(profile_path_buffer))); - - // Respond with the variations info immediately. - CallJavascriptFunction(version_ui::kReturnVariationInfo, - *version_ui::GetVariationsList()); - GURL current_url = web_ui()->GetWebContents()->GetVisibleURL(); - if (current_url.query().find(version_ui::kVariationsShowCmdQuery) != - std::string::npos) { - CallJavascriptFunction(version_ui::kReturnVariationCmd, - version_ui::GetVariationsCommandLineAsValue()); - } + base::BindOnce(&VersionHandler::OnGotFilePaths, + weak_ptr_factory_.GetWeakPtr(), callback_id, + base::Owned(exec_path_buffer), + base::Owned(profile_path_buffer))); } -void VersionHandler::OnGotFilePaths(base::string16* executable_path_data, +void VersionHandler::OnGotFilePaths(std::string callback_id, + base::string16* executable_path_data, base::string16* profile_path_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - base::Value exec_path(*executable_path_data); - base::Value profile_path(*profile_path_data); - CallJavascriptFunction(version_ui::kReturnFilePaths, exec_path, profile_path); + base::Value response(base::Value::Type::DICTIONARY); + response.SetKey(version_ui::kKeyExecPath, base::Value(*executable_path_data)); + response.SetKey(version_ui::kKeyProfilePath, base::Value(*profile_path_data)); + ResolveJavascriptCallback(base::Value(callback_id), response); } #if BUILDFLAG(ENABLE_PLUGINS) void VersionHandler::OnGotPlugins( + std::string callback_id, const std::vector<content::WebPluginInfo>& plugins) { // Obtain the version of the first enabled Flash plugin. std::vector<content::WebPluginInfo> info_array; @@ -132,9 +183,7 @@ void VersionHandler::OnGotPlugins( } } } - - base::Value arg(flash_version_and_path); - - CallJavascriptFunction(version_ui::kReturnFlashVersion, arg); + ResolveJavascriptCallback(base::Value(callback_id), + base::Value(flash_version_and_path)); } #endif // BUILDFLAG(ENABLE_PLUGINS) diff --git a/chromium/chrome/browser/ui/webui/version_handler.h b/chromium/chrome/browser/ui/webui/version_handler.h index e4c27a5308e..47e66e7a029 100644 --- a/chromium/chrome/browser/ui/webui/version_handler.h +++ b/chromium/chrome/browser/ui/webui/version_handler.h @@ -22,20 +22,36 @@ class VersionHandler : public content::WebUIMessageHandler { // content::WebUIMessageHandler implementation. void RegisterMessages() override; - // Callback for the "requestVersionInfo" message. This asynchronously requests - // the flash version and eventually returns it to the front end along with the - // list of variations using OnGotPlugins. + // Callback for the "requestVersionInfo" message sent by |chrome.send| in JS. + // This is still supported for platform-specific asynchronous calls (see + // derived classes) but the main version information is now retrieved with + // below messages using |cr.sendWithPromise|. virtual void HandleRequestVersionInfo(const base::ListValue* args); + // Callback for the "requestVariationInfo" message. This resolves immediately + // with variations list as well as command variations if requested. + virtual void HandleRequestVariationInfo(const base::ListValue* args); + + // Callback for the "requestPluginInfo" message. This asynchronously requests + // the flash version and eventually returns it to the front end along with the + // list of variations using |OnGotPlugins|. + virtual void HandleRequestPluginInfo(const base::ListValue* args); + + // Callback for the "requestPathInfo" message. This resolves asynchronously + // with |OnGotFilePaths|. + virtual void HandleRequestPathInfo(const base::ListValue* args); + private: // Callback which handles returning the executable and profile paths to the // front end. - void OnGotFilePaths(base::string16* executable_path_data, + void OnGotFilePaths(std::string callback_id, + base::string16* executable_path_data, base::string16* profile_path_data); // Callback for GetPlugins which responds to the page with the Flash version. // This also initiates the OS Version load on ChromeOS. - void OnGotPlugins(const std::vector<content::WebPluginInfo>& plugins); + void OnGotPlugins(std::string callback_id, + const std::vector<content::WebPluginInfo>& plugins); // Factory for the creating refs in callbacks. base::WeakPtrFactory<VersionHandler> weak_ptr_factory_{this}; diff --git a/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc index 07917010b9f..a2ed0a779c2 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc +++ b/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc @@ -10,32 +10,34 @@ #include "components/version_info/channel.h" #include "content/public/browser/web_ui.h" -VersionHandlerChromeOS::VersionHandlerChromeOS() : weak_factory_(this) {} +VersionHandlerChromeOS::VersionHandlerChromeOS() {} VersionHandlerChromeOS::~VersionHandlerChromeOS() {} void VersionHandlerChromeOS::HandleRequestVersionInfo( const base::ListValue* args) { + VersionHandler::HandleRequestVersionInfo(args); + // Start the asynchronous load of the versions. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetVersion, chromeos::version_loader::VERSION_FULL), base::Bind(&VersionHandlerChromeOS::OnVersion, weak_factory_.GetWeakPtr())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetFirmware), base::Bind(&VersionHandlerChromeOS::OnOSFirmware, weak_factory_.GetWeakPtr())); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&chromeos::version_loader::GetARCVersion), base::Bind(&VersionHandlerChromeOS::OnARCVersion, weak_factory_.GetWeakPtr())); - - // Parent class takes care of the rest. - VersionHandler::HandleRequestVersionInfo(args); } void VersionHandlerChromeOS::OnVersion(const std::string& version) { diff --git a/chromium/chrome/browser/ui/webui/version_handler_chromeos.h b/chromium/chrome/browser/ui/webui/version_handler_chromeos.h index e36377fc778..0bc597a3270 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_chromeos.h +++ b/chromium/chrome/browser/ui/webui/version_handler_chromeos.h @@ -28,7 +28,7 @@ class VersionHandlerChromeOS : public VersionHandler { void OnARCVersion(const std::string& version); private: - base::WeakPtrFactory<VersionHandlerChromeOS> weak_factory_; + base::WeakPtrFactory<VersionHandlerChromeOS> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VersionHandlerChromeOS); }; diff --git a/chromium/chrome/browser/ui/webui/version_handler_win.cc b/chromium/chrome/browser/ui/webui/version_handler_win.cc index 3540aa13b9b..315ce149694 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_win.cc +++ b/chromium/chrome/browser/ui/webui/version_handler_win.cc @@ -11,21 +11,21 @@ #include "chrome/browser/ui/webui/version_util_win.h" #include "content/public/browser/web_ui.h" -VersionHandlerWindows::VersionHandlerWindows() : weak_factory_(this) {} +VersionHandlerWindows::VersionHandlerWindows() {} VersionHandlerWindows::~VersionHandlerWindows() {} void VersionHandlerWindows::HandleRequestVersionInfo( const base::ListValue* args) { + VersionHandler::HandleRequestVersionInfo(args); + // Start the asynchronous load of the versions. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&version_utils::win::GetFullWindowsVersion), base::BindOnce(&VersionHandlerWindows::OnVersion, weak_factory_.GetWeakPtr())); - - // Parent class takes care of the rest. - VersionHandler::HandleRequestVersionInfo(args); } void VersionHandlerWindows::OnVersion(const std::string& version) { diff --git a/chromium/chrome/browser/ui/webui/version_handler_win.h b/chromium/chrome/browser/ui/webui/version_handler_win.h index 83a41ecce31..2c424dcc2f2 100644 --- a/chromium/chrome/browser/ui/webui/version_handler_win.h +++ b/chromium/chrome/browser/ui/webui/version_handler_win.h @@ -27,7 +27,7 @@ class VersionHandlerWindows : public VersionHandler { static std::string GetFullWindowsVersionForTesting(); private: - base::WeakPtrFactory<VersionHandlerWindows> weak_factory_; + base::WeakPtrFactory<VersionHandlerWindows> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VersionHandlerWindows); }; diff --git a/chromium/chrome/browser/ui/webui/version_ui.cc b/chromium/chrome/browser/ui/webui/version_ui.cc index e0759744e1f..aab730053ec 100644 --- a/chromium/chrome/browser/ui/webui/version_ui.cc +++ b/chromium/chrome/browser/ui/webui/version_ui.cc @@ -83,7 +83,7 @@ WebUIDataSource* CreateVersionUIDataSource() { VersionUI::AddVersionDetailStrings(html_source); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath(version_ui::kVersionJS, IDR_VERSION_UI_JS); html_source->AddResourcePath(version_ui::kAboutVersionCSS, IDR_VERSION_UI_CSS); diff --git a/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.cc b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.cc new file mode 100644 index 00000000000..396b82eaa37 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.cc @@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/web_footer_experiment_ui.h" + +#include "base/logging.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/managed_ui_handler.h" +#include "chrome/browser/ui/webui/theme_source.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "content/public/browser/web_ui_data_source.h" + +WebFooterExperimentUI::WebFooterExperimentUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + + content::WebUIDataSource* source = content::WebUIDataSource::Create( + chrome::kChromeUIWebFooterExperimentHost); + source->AddResourcePath("index.html", IDR_WEB_FOOTER_EXPERIMENT_HTML); + source->SetDefaultResource(IDR_WEB_FOOTER_EXPERIMENT_HTML); + ManagedUIHandler::Initialize(web_ui, source); + content::WebUIDataSource::Add(profile, source); +} + +WebFooterExperimentUI::~WebFooterExperimentUI() = default; diff --git a/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.h b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.h new file mode 100644 index 00000000000..7dda354b888 --- /dev/null +++ b/chromium/chrome/browser/ui/webui/web_footer_experiment_ui.h @@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_WEB_FOOTER_EXPERIMENT_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_WEB_FOOTER_EXPERIMENT_UI_H_ + +#include "base/macros.h" +#include "content/public/browser/web_ui_controller.h" + +class WebFooterExperimentUI : public content::WebUIController { + public: + explicit WebFooterExperimentUI(content::WebUI* web_ui); + ~WebFooterExperimentUI() override; + + private: + DISALLOW_COPY_AND_ASSIGN(WebFooterExperimentUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_WEB_FOOTER_EXPERIMENT_UI_H_ diff --git a/chromium/chrome/browser/ui/webui/webapks_ui.cc b/chromium/chrome/browser/ui/webui/webapks_ui.cc index 953c000a908..9e45e8dc7d6 100644 --- a/chromium/chrome/browser/ui/webui/webapks_ui.cc +++ b/chromium/chrome/browser/ui/webui/webapks_ui.cc @@ -21,7 +21,7 @@ namespace { WebUIDataSource* CreateWebApksUIDataSource() { WebUIDataSource* html_source = WebUIDataSource::Create(chrome::kChromeUIWebApksHost); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); html_source->AddResourcePath("webapks.js", IDR_WEBAPKS_UI_JS); html_source->AddResourcePath("about_webapks.css", IDR_WEBAPKS_UI_CSS); html_source->SetDefaultResource(IDR_WEBAPKS_UI_HTML); diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer.cc b/chromium/chrome/browser/ui/webui/webui_load_timer.cc index f865c2131df..9bfadd5fb83 100644 --- a/chromium/chrome/browser/ui/webui/webui_load_timer.cc +++ b/chromium/chrome/browser/ui/webui/webui_load_timer.cc @@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/webui_load_timer.h" #include "base/metrics/histogram.h" +#include "base/timer/elapsed_timer.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer.h b/chromium/chrome/browser/ui/webui/webui_load_timer.h index 0fee6dfb048..5474b646af3 100644 --- a/chromium/chrome/browser/ui/webui/webui_load_timer.h +++ b/chromium/chrome/browser/ui/webui/webui_load_timer.h @@ -9,9 +9,12 @@ #include <string> #include "base/macros.h" -#include "base/timer/elapsed_timer.h" #include "content/public/browser/web_contents_observer.h" +namespace base { +class ElapsedTimer; +} + // Measures and reports page load times for WebUI. class WebuiLoadTimer : public content::WebContentsObserver { public: diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/DEPS b/chromium/chrome/browser/ui/webui/welcome/DEPS index cbcb3569274..cbcb3569274 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/DEPS +++ b/chromium/chrome/browser/ui/webui/welcome/DEPS diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc b/chromium/chrome/browser/ui/webui/welcome/bookmark_handler.cc index e09ec04fbc0..74dea3937c1 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_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/welcome/nux/bookmark_handler.h" +#include "chrome/browser/ui/webui/welcome/bookmark_handler.h" #include "base/bind.h" #include "chrome/grit/browser_resources.h" @@ -10,7 +10,7 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" -namespace nux { +namespace welcome { BookmarkHandler::BookmarkHandler(PrefService* prefs) : prefs_(prefs) {} @@ -46,4 +46,4 @@ void BookmarkHandler::HandleIsBookmarkBarShown(const base::ListValue* args) { base::Value(prefs_->GetBoolean(bookmarks::prefs::kShowBookmarkBar))); } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h b/chromium/chrome/browser/ui/webui/welcome/bookmark_handler.h index b9240c93816..c3cf53d941e 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_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_WELCOME_NUX_BOOKMARK_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_HANDLER_H_ #include "base/macros.h" #include "base/values.h" @@ -11,7 +11,7 @@ class PrefService; -namespace nux { +namespace welcome { class BookmarkHandler : public content::WebUIMessageHandler { public: @@ -32,6 +32,6 @@ class BookmarkHandler : public content::WebUIMessageHandler { DISALLOW_COPY_AND_ASSIGN(BookmarkHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.cc index ba59a856786..fc61b6b3567 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.cc +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/bookmark_item.h" #include "base/strings/string16.h" #include "base/values.h" -namespace nux { +namespace welcome { base::ListValue BookmarkItemsToListValue(const BookmarkItem items[], size_t count) { @@ -41,4 +41,4 @@ base::ListValue BookmarkItemsToListValue( return list_value; } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.h b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.h index 838735a9a8a..fbea6f52a13 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/bookmark_item.h +++ b/chromium/chrome/browser/ui/webui/welcome/bookmark_item.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_WELCOME_NUX_BOOKMARK_ITEM_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_ITEM_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_ITEM_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_ITEM_H_ #include <stddef.h> #include <string> @@ -13,7 +13,7 @@ namespace base { class ListValue; } // namespace base -namespace nux { +namespace welcome { struct BookmarkItem { const int id; @@ -29,6 +29,6 @@ base::ListValue BookmarkItemsToListValue(const BookmarkItem items[], base::ListValue BookmarkItemsToListValue( const std::vector<BookmarkItem>& items); -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_BOOKMARK_ITEM_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_BOOKMARK_ITEM_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.cc index b76a8185d3d..4cedf809283 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.cc @@ -2,19 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/google_apps_handler.h" +#include "chrome/browser/ui/webui/welcome/google_apps_handler.h" #include "base/bind.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" +#include "build/branding_buildflags.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" -#include "chrome/browser/ui/webui/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/onboarding_welcome_resources.h" +#include "chrome/grit/welcome_resources.h" #include "components/favicon/core/favicon_service.h" #include "components/grit/components_resources.h" #include "components/grit/components_scaled_resources.h" @@ -24,7 +25,7 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -namespace nux { +namespace welcome { // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. @@ -45,50 +46,48 @@ const char* kGoogleAppsInteractionHistogram = constexpr const int kGoogleAppIconSize = 48; // Pixels. GoogleAppsHandler::GoogleAppsHandler() { -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) // Do not translate icon name as it is not human visible and needs to // match CSS. BookmarkItem gmail = { static_cast<int>(GoogleApps::kGmail), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_GMAIL), - "gmail", "https://accounts.google.com/b/0/AddMailService", - IDS_ONBOARDING_WELCOME_GMAIL}; + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_GMAIL), "gmail", + "https://accounts.google.com/b/0/AddMailService", IDS_WELCOME_GMAIL}; if (IsAppVariationEnabled()) { - google_apps_.push_back( - {static_cast<int>(GoogleApps::kSearch), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_SEARCH), - "search", "https://google.com", IDS_ONBOARDING_WELCOME_SEARCH}); + google_apps_.push_back({static_cast<int>(GoogleApps::kSearch), + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_SEARCH), + "search", "https://google.com", + IDS_WELCOME_SEARCH}); } else { google_apps_.push_back(gmail); } google_apps_.push_back( {static_cast<int>(GoogleApps::kYouTube), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_YOUTUBE), - "youtube", "https://youtube.com", IDS_ONBOARDING_WELCOME_YOUTUBE}); + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_YOUTUBE), "youtube", + "https://youtube.com", IDS_WELCOME_YOUTUBE}); google_apps_.push_back( {static_cast<int>(GoogleApps::kMaps), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_MAPS), - "maps", "https://maps.google.com", IDS_ONBOARDING_WELCOME_MAPS}); + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_MAPS), "maps", + "https://maps.google.com", IDS_WELCOME_MAPS}); if (IsAppVariationEnabled()) { google_apps_.push_back(gmail); } else { google_apps_.push_back( {static_cast<int>(GoogleApps::kNews), - l10n_util::GetStringUTF8(IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_NEWS), - "news", "https://news.google.com", IDS_ONBOARDING_WELCOME_NEWS}); + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_NEWS), "news", + "https://news.google.com", IDS_WELCOME_NEWS}); } - google_apps_.push_back({static_cast<int>(GoogleApps::kTranslate), - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_TRANSLATE), - "translate", "https://translate.google.com", - IDS_ONBOARDING_WELCOME_TRANSLATE}); -#endif // defined(GOOGLE_CHROME_BUILD) + google_apps_.push_back( + {static_cast<int>(GoogleApps::kTranslate), + l10n_util::GetStringUTF8(IDS_WELCOME_GOOGLE_APPS_TRANSLATE), "translate", + "https://translate.google.com", IDS_WELCOME_TRANSLATE}); +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) } GoogleAppsHandler::~GoogleAppsHandler() {} @@ -109,7 +108,7 @@ void GoogleAppsHandler::HandleCacheGoogleAppIcon(const base::ListValue* args) { int appId; args->GetInteger(0, &appId); - const BookmarkItem* selectedApp = NULL; + const BookmarkItem* selectedApp = nullptr; for (const auto& google_app : google_apps_) { if (google_app.id == appId) { selectedApp = &google_app; @@ -141,4 +140,4 @@ void GoogleAppsHandler::HandleGetGoogleAppsList(const base::ListValue* args) { BookmarkItemsToListValue(google_apps_.data(), google_apps_.size())); } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.h index f35e22d4cb3..1d28ebf3307 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/google_apps_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/google_apps_handler.h @@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_GOOGLE_APPS_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_GOOGLE_APPS_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_GOOGLE_APPS_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_GOOGLE_APPS_HANDLER_H_ #include <vector> #include "base/macros.h" #include "base/values.h" -#include "chrome/browser/ui/webui/welcome/nux/bookmark_item.h" +#include "chrome/browser/ui/webui/welcome/bookmark_item.h" #include "content/public/browser/web_ui_message_handler.h" -namespace nux { +namespace welcome { extern const char* kGoogleAppsInteractionHistogram; @@ -43,6 +43,6 @@ class GoogleAppsHandler : public content::WebUIMessageHandler { DISALLOW_COPY_AND_ASSIGN(GoogleAppsHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_GOOGLE_APPS_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_GOOGLE_APPS_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc b/chromium/chrome/browser/ui/webui/welcome/helpers.cc index f8e669c0863..0fe4562325e 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc +++ b/chromium/chrome/browser/ui/webui/welcome/helpers.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/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" #include <string> #include <vector> @@ -14,13 +14,16 @@ #include "base/strings/string_tokenizer.h" #include "base/values.h" #include "build/branding_buildflags.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/policy/browser_signin_policy_handler.h" #include "chrome/browser/policy/profile_policy_connector.h" #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/search/ntp_features.h" #include "chrome/browser/search/search.h" -#include "chrome/browser/ui/webui/welcome/nux/constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/policy/core/common/policy_map.h" @@ -28,30 +31,55 @@ #include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" -namespace nux { +namespace welcome { -bool CanShowGoogleAppModule(const policy::PolicyMap& policies) { - const base::Value* bookmark_bar_enabled_value = - policies.GetValue(policy::key::kBookmarkBarEnabled); +// Available modules for both new and returning users. +const char kDefaultNewUserModules[] = + "nux-google-apps,nux-ntp-background,nux-set-as-default,signin-view"; +const char kDefaultReturningUserModules[] = "nux-set-as-default"; - if (bookmark_bar_enabled_value && !bookmark_bar_enabled_value->GetBool()) { - return false; - } +// Feature flag. +const base::Feature kFeature{"NuxOnboarding", base::FEATURE_ENABLED_BY_DEFAULT}; +// For testing purposes +const base::Feature kForceEnabled = {"NuxOnboardingForceEnabled", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// The value of these FeatureParam values should be a comma-delimited list +// of element names whitelisted in the MODULES_WHITELIST list, defined in +// chrome/browser/resources/welcome/welcome_app.js +const base::FeatureParam<std::string> kNewUserModules{ + &kFeature, "new-user-modules", kDefaultNewUserModules}; +const base::FeatureParam<std::string> kReturningUserModules{ + &kFeature, "returning-user-modules", kDefaultReturningUserModules}; +// For testing purposes +const base::FeatureParam<std::string> kForceEnabledNewUserModules = { + &kForceEnabled, "new-user-modules", kDefaultNewUserModules}; +const base::FeatureParam<std::string> kForceEnabledReturningUserModules = { + &kForceEnabled, "returning-user-modules", kDefaultReturningUserModules}; + +// FeatureParam for app variation. +const base::FeatureParam<bool> kShowGoogleApp{&kFeature, + "app-variation-enabled", false}; +// For testing purposes +const base::FeatureParam<bool> kForceEnabledShowGoogleApp = { + &kForceEnabled, "app-variation-enabled", false}; + +bool IsPolicySetAndFalse(const policy::PolicyMap& policies, + const std::string& policy_name) { + const base::Value* policy = policies.GetValue(policy_name); + return policy && policy->is_bool() && !policy->GetBool(); +} - const base::Value* edit_bookmarks_value = - policies.GetValue(policy::key::kEditBookmarksEnabled); +bool CanShowGoogleAppModule(const policy::PolicyMap& policies) { + if (IsPolicySetAndFalse(policies, policy::key::kBookmarkBarEnabled)) + return false; - if (edit_bookmarks_value && !edit_bookmarks_value->GetBool()) { + if (IsPolicySetAndFalse(policies, policy::key::kEditBookmarksEnabled)) return false; - } return true; } -bool CanShowGoogleAppModuleForTesting(const policy::PolicyMap& policies) { - return CanShowGoogleAppModule(policies); -} - bool CanShowNTPBackgroundModule(const policy::PolicyMap& policies, Profile* profile) { // We can't set the background if the NTP is something other than Google. @@ -59,20 +87,11 @@ bool CanShowNTPBackgroundModule(const policy::PolicyMap& policies, search::DefaultSearchProviderIsGoogle(profile); } -bool CanShowNTPBackgroundModuleForTesting(const policy::PolicyMap& policies, - Profile* profile) { - return CanShowNTPBackgroundModule(policies, profile); -} - bool CanShowSetDefaultModule(const policy::PolicyMap& policies) { - const base::Value* set_default_value = - policies.GetValue(policy::key::kDefaultBrowserSettingEnabled); - - return !set_default_value || set_default_value->GetBool(); -} + if (IsPolicySetAndFalse(policies, policy::key::kDefaultBrowserSettingEnabled)) + return false; -bool CanShowSetDefaultModuleForTesting(const policy::PolicyMap& policies) { - return CanShowSetDefaultModule(policies); + return true; } bool CanShowSigninModule(const policy::PolicyMap& policies) { @@ -90,11 +109,7 @@ bool CanShowSigninModule(const policy::PolicyMap& policies) { policy::BrowserSigninMode::kDisabled; } -bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies) { - return CanShowSigninModule(policies); -} - -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) +#if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN) // These feature flags are used to tie our experiment to specific studies. // go/navi-app-variation for details. // TODO(hcarmona): find a solution that scales better. @@ -108,33 +123,12 @@ const base::Feature kNaviShortcutVariationEnabled = { "NaviShortcutVariationEnabled", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) -// This feature flag is used to force the feature to be turned on for non-win -// and non-branded builds, like with tests or development on other platforms. -const base::Feature kNuxOnboardingForceEnabled = { - "NuxOnboardingForceEnabled", base::FEATURE_DISABLED_BY_DEFAULT}; - -// The value of these FeatureParam values should be a comma-delimited list -// of element names whitelisted in the MODULES_WHITELIST list, defined in -// chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js -const base::FeatureParam<std::string> kNuxOnboardingForceEnabledNewUserModules = - {&kNuxOnboardingForceEnabled, "new-user-modules", - "nux-google-apps,nux-ntp-background,nux-set-as-default," - "signin-view"}; -const base::FeatureParam<std::string> - kNuxOnboardingForceEnabledReturningUserModules = { - &kNuxOnboardingForceEnabled, "returning-user-modules", - "nux-set-as-default"}; -const base::FeatureParam<bool> kNuxOnboardingForceEnabledShowGoogleApp = { - &kNuxOnboardingForceEnabled, "app-variation-enabled", false}; - -// Onboarding experiments depend on Google being the default search provider. +// Welcome experiments depend on Google being the default search provider. bool CanExperimentWithVariations(Profile* profile) { return search::DefaultSearchProviderIsGoogle(profile); } -// Must match study name in configs. -const char kNuxOnboardingStudyName[] = "NaviOnboarding"; - +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) // Get the group for users who onboard in this experiment. // Groups are: // - Specified by study @@ -151,59 +145,56 @@ std::string GetOnboardingGroup(Profile* profile) { // We need to use |base::GetFieldTrialParamValue| instead of // |base::FeatureParam| because our control group needs a custom value for // this param. - return base::GetFieldTrialParamValue(kNuxOnboardingStudyName, - "onboarding-group"); + // "NaviOnboarding" match study name in configs. + return base::GetFieldTrialParamValue("NaviOnboarding", "onboarding-group"); } -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) void JoinOnboardingGroup(Profile* profile) { PrefService* prefs = profile->GetPrefs(); - std::string onboard_group; + std::string group; if (prefs->GetBoolean(prefs::kHasSeenWelcomePage)) { - // Get user's original onboarding group. - onboard_group = prefs->GetString(prefs::kNaviOnboardGroup); + // Get user's original group. + group = prefs->GetString(prefs::kNaviOnboardGroup); - // Users who onboarded before Navi won't have an onboarding group. - if (onboard_group.empty()) + // Users who onboarded before Navi won't have a group. + if (group.empty()) return; } else { // Join the latest group if onboarding for the first time! - onboard_group = GetOnboardingGroup(profile); - profile->GetPrefs()->SetString(prefs::kNaviOnboardGroup, onboard_group); + group = GetOnboardingGroup(profile); + profile->GetPrefs()->SetString(prefs::kNaviOnboardGroup, group); } - // User will be tied to their original onboarding group, even after - // experiment ends. + // User will be tied to their original group, even after experiment ends. ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( - "NaviOnboardingSynthetic", onboard_group); + "NaviOnboardingSynthetic", group); - // Check for feature based on onboarding group. + // Check for feature based on group. // TODO(hcarmona): find a solution that scales better. - if (onboard_group.compare("ControlSynthetic-008") == 0) + if (group.compare("ControlSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviControlEnabled); - else if (onboard_group.compare("AppVariationSynthetic-008") == 0) + else if (group.compare("AppVariationSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviAppVariationEnabled); - else if (onboard_group.compare("NTPVariationSynthetic-008") == 0) + else if (group.compare("NTPVariationSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviNTPVariationEnabled); - else if (onboard_group.compare("ShortcutVariationSynthetic-008") == 0) + else if (group.compare("ShortcutVariationSynthetic-008") == 0) base::FeatureList::IsEnabled(kNaviShortcutVariationEnabled); } #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN) -bool IsNuxOnboardingEnabled(Profile* profile) { -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) - return base::FeatureList::IsEnabled(nux::kNuxOnboardingFeature) || - base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled); +bool IsEnabled(Profile* profile) { +#if defined(GOOGLE_CHROME_BUILD) + return base::FeatureList::IsEnabled(welcome::kFeature) || + base::FeatureList::IsEnabled(welcome::kForceEnabled); #else // Allow enabling outside official builds for testing purposes. - return base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled); -#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) + return base::FeatureList::IsEnabled(welcome::kForceEnabled); +#endif // defined(GOOGLE_CHROME_BUILD) } bool IsAppVariationEnabled() { - return kNuxOnboardingForceEnabledShowGoogleApp.Get() || - kNuxOnboardingShowGoogleApp.Get(); + return kForceEnabledShowGoogleApp.Get() || kShowGoogleApp.Get(); } const policy::PolicyMap& GetPoliciesFromProfile(Profile* profile) { @@ -230,13 +221,13 @@ std::vector<std::string> GetAvailableModules(Profile* profile) { return available_modules; } -bool DoesOnboardingHaveModulesToShow(Profile* profile) { - const base::Value* force_ephemeral_profiles_value = - GetPoliciesFromProfile(profile).GetValue( - policy::key::kForceEphemeralProfiles); - // Modules won't have a lasting effect if profile is ephemeral. - if (force_ephemeral_profiles_value && - force_ephemeral_profiles_value->GetBool()) { +bool HasModulesToShow(Profile* profile) { + // Modules won't have lasting effect if profile is ephemeral, so we can skip. + ProfileAttributesStorage& storage = + g_browser_process->profile_manager()->GetProfileAttributesStorage(); + ProfileAttributesEntry* entry = nullptr; + if (storage.GetProfileAttributesWithPath(profile->GetPath(), &entry) && + entry->IsEphemeral()) { return false; } @@ -259,20 +250,19 @@ std::string FilterModules(const std::string& requested_modules, return base::JoinString(filtered_modules, ","); } -base::DictionaryValue GetNuxOnboardingModules(Profile* profile) { - // This function should not be called when nux onboarding feature is not on. - DCHECK(nux::IsNuxOnboardingEnabled(profile)); +base::DictionaryValue GetModules(Profile* profile) { + // This function should not be called when feature is not on. + DCHECK(welcome::IsEnabled(profile)); std::string new_user_modules = kDefaultNewUserModules; std::string returning_user_modules = kDefaultReturningUserModules; - if (base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled)) { - new_user_modules = kNuxOnboardingForceEnabledNewUserModules.Get(); - returning_user_modules = - kNuxOnboardingForceEnabledReturningUserModules.Get(); + if (base::FeatureList::IsEnabled(welcome::kForceEnabled)) { + new_user_modules = kForceEnabledNewUserModules.Get(); + returning_user_modules = kForceEnabledReturningUserModules.Get(); } else if (CanExperimentWithVariations(profile)) { - new_user_modules = kNuxOnboardingNewUserModules.Get(); - returning_user_modules = kNuxOnboardingReturningUserModules.Get(); + new_user_modules = kNewUserModules.Get(); + returning_user_modules = kReturningUserModules.Get(); } std::vector<std::string> available_modules = GetAvailableModules(profile); @@ -284,4 +274,21 @@ base::DictionaryValue GetNuxOnboardingModules(Profile* profile) { FilterModules(returning_user_modules, available_modules)); return modules; } -} // namespace nux + +bool CanShowGoogleAppModuleForTesting(const policy::PolicyMap& policies) { + return CanShowGoogleAppModule(policies); +} + +bool CanShowNTPBackgroundModuleForTesting(const policy::PolicyMap& policies, + Profile* profile) { + return CanShowNTPBackgroundModule(policies, profile); +} + +bool CanShowSetDefaultModuleForTesting(const policy::PolicyMap& policies) { + return CanShowSetDefaultModule(policies); +} + +bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies) { + return CanShowSigninModule(policies); +} +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h b/chromium/chrome/browser/ui/webui/welcome/helpers.h index fb99d65d282..258c956b80c 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h +++ b/chromium/chrome/browser/ui/webui/welcome/helpers.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_WELCOME_NUX_HELPER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_HELPERS_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_HELPERS_H_ #include <string> @@ -22,14 +22,7 @@ class PolicyMap; class Profile; -namespace nux { -extern const base::Feature kNuxOnboardingForceEnabled; - -extern const base::FeatureParam<std::string> - kNuxOnboardingForceEnabledNewUserModules; -extern const base::FeatureParam<std::string> - kNuxOnboardingForceEnabledReturningUserModules; - +namespace welcome { #if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN) // Onboarding groups are used for running field trials related to first run // experience. This will make a new profile join whatever group is currently @@ -38,21 +31,23 @@ extern const base::FeatureParam<std::string> void JoinOnboardingGroup(Profile* profile); #endif // defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN) -bool IsNuxOnboardingEnabled(Profile* profile); +bool IsEnabled(Profile* profile); bool IsAppVariationEnabled(); -bool DoesOnboardingHaveModulesToShow(Profile* profile); +bool HasModulesToShow(Profile* profile); -base::DictionaryValue GetNuxOnboardingModules(Profile* profile); +base::DictionaryValue GetModules(Profile* profile); // Exposed for testing. +extern const base::Feature kForceEnabled; + bool CanShowGoogleAppModuleForTesting(const policy::PolicyMap& policies); bool CanShowNTPBackgroundModuleForTesting(const policy::PolicyMap& policies, Profile* profile); bool CanShowSetDefaultModuleForTesting(const policy::PolicyMap& policies); bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies); -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_HELPER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_HELPERS_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.cc b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.cc index 658de1d4c86..33ff4884574 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.cc +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_fetcher.h" #include <utility> #include "chrome/browser/browser_process.h" #include "chrome/browser/net/system_network_context_manager.h" -#include "chrome/browser/search/background/onboarding_ntp_backgrounds.h" +#include "chrome/browser/search/background/ntp_backgrounds.h" #include "net/base/load_flags.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request.h" @@ -16,7 +16,7 @@ #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "url/gurl.h" -namespace nux { +namespace welcome { NtpBackgroundFetcher::NtpBackgroundFetcher( size_t index, @@ -46,7 +46,7 @@ NtpBackgroundFetcher::NtpBackgroundFetcher( policy_exception_justification: "Not implemented." })"); - auto backgrounds = GetOnboardingNtpBackgrounds(); + auto backgrounds = GetNtpBackgrounds(); if (index_ >= backgrounds.size()) { OnFetchCompleted(nullptr); @@ -56,8 +56,7 @@ NtpBackgroundFetcher::NtpBackgroundFetcher( GURL url = backgrounds[index_]; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = url; - resource_request->load_flags = - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); @@ -80,4 +79,4 @@ void NtpBackgroundFetcher::OnFetchCompleted( } } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.h index 1e4892a4ad9..bfd25a376a8 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_fetcher.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_WELCOME_NUX_NTP_BACKGROUND_FETCHER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_FETCHER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_FETCHER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_FETCHER_H_ #include <memory> #include <string> @@ -16,7 +16,7 @@ namespace network { class SimpleURLLoader; } -namespace nux { +namespace welcome { class NtpBackgroundFetcher { public: @@ -35,6 +35,6 @@ class NtpBackgroundFetcher { DISALLOW_COPY_AND_ASSIGN(NtpBackgroundFetcher); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_FETCHER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_FETCHER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.cc index 914372cffe1..b970bec8740 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.cc @@ -2,25 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_handler.h" #include <memory> #include <utility> #include "base/bind.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/background/onboarding_ntp_backgrounds.h" +#include "chrome/browser/search/background/ntp_backgrounds.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/onboarding_welcome_resources.h" +#include "chrome/grit/welcome_resources.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -namespace nux { +namespace welcome { enum class NtpBackgrounds { kArt = 0, @@ -53,7 +54,7 @@ void NtpBackgroundHandler::RegisterMessages() { void NtpBackgroundHandler::HandleClearBackground(const base::ListValue* args) { InstantService* instant_service = InstantServiceFactory::GetForProfile(Profile::FromWebUI(web_ui())); - instant_service->SetCustomBackgroundURL(GURL("")); + instant_service->ResetCustomBackgroundInfo(); } void NtpBackgroundHandler::HandleGetBackgrounds(const base::ListValue* args) { @@ -63,58 +64,52 @@ void NtpBackgroundHandler::HandleGetBackgrounds(const base::ListValue* args) { CHECK(args->Get(0, &callback_id)); base::ListValue list_value; - std::array<GURL, kOnboardingNtpBackgroundsCount> onboardingNtpBackgrounds = - GetOnboardingNtpBackgrounds(); + std::array<GURL, kNtpBackgroundsCount> NtpBackgrounds = GetNtpBackgrounds(); const std::string kUrlPrefix = "preview-background.jpg?"; auto element = std::make_unique<base::DictionaryValue>(); int id = static_cast<int>(NtpBackgrounds::kEarth); element->SetInteger("id", id); - element->SetString("title", - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_EARTH_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_EARTH_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "earth"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kCityscape); element->SetInteger("id", id); - element->SetString( - "title", l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_CITYSCAPE_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_CITYSCAPE_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "cityscape"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kLandscape); element->SetInteger("id", id); - element->SetString( - "title", l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_LANDSCAPE_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_LANDSCAPE_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "landscape"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kArt); element->SetInteger("id", id); - element->SetString("title", - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_ART_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString( + "title", l10n_util::GetStringUTF8(IDS_WELCOME_NTP_BACKGROUND_ART_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "art"); list_value.Append(std::move(element)); element = std::make_unique<base::DictionaryValue>(); id = static_cast<int>(NtpBackgrounds::kGeometricShapes); element->SetInteger("id", id); - element->SetString( - "title", - l10n_util::GetStringUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_GEOMETRIC_SHAPES_TITLE)); - element->SetString("imageUrl", kUrlPrefix + std::to_string(id)); + element->SetString("title", + l10n_util::GetStringUTF8( + IDS_WELCOME_NTP_BACKGROUND_GEOMETRIC_SHAPES_TITLE)); + element->SetString("imageUrl", kUrlPrefix + base::NumberToString(id)); element->SetString("thumbnailClass", "geometric-shapes"); list_value.Append(std::move(element)); @@ -126,24 +121,22 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) { int backgroundIndex; args->GetInteger(0, &backgroundIndex); - std::array<GURL, kOnboardingNtpBackgroundsCount> onboardingNtpBackgrounds = - GetOnboardingNtpBackgrounds(); + std::array<GURL, kNtpBackgroundsCount> NtpBackgrounds = GetNtpBackgrounds(); InstantService* instant_service = InstantServiceFactory::GetForProfile(Profile::FromWebUI(web_ui())); switch (backgroundIndex) { case static_cast<int>(NtpBackgrounds::kArt): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], "Universe Cosmic Vacum", + NtpBackgrounds[backgroundIndex], "Universe Cosmic Vacum", "Philipp Rietz — Walli", GURL("https://walli.shanga.co/image/view/?id=370"), ""); break; case static_cast<int>(NtpBackgrounds::kCityscape): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], - l10n_util::GetStringFUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, - base::UTF8ToUTF16("Ev Tchebotarev")), + NtpBackgrounds[backgroundIndex], + l10n_util::GetStringFUTF8(IDS_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, + base::UTF8ToUTF16("Ev Tchebotarev")), "", GURL("https://500px.com/photo/135751035/" "soulseek-by-%E5%B0%A4%E9%87%91%E5%B0%BC-ev-tchebotarev"), @@ -151,24 +144,22 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) { break; case static_cast<int>(NtpBackgrounds::kEarth): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], - l10n_util::GetStringFUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, - base::UTF8ToUTF16("NASA Image Library")), + NtpBackgrounds[backgroundIndex], + l10n_util::GetStringFUTF8(IDS_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, + base::UTF8ToUTF16("NASA Image Library")), "", GURL("https://www.google.com/sky/"), ""); break; case static_cast<int>(NtpBackgrounds::kGeometricShapes): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], "Tessellation 15", + NtpBackgrounds[backgroundIndex], "Tessellation 15", "Justin Prno — Walli", GURL("https://walli.shanga.co/image/view/?id=1375"), ""); break; case static_cast<int>(NtpBackgrounds::kLandscape): instant_service->SetCustomBackgroundInfo( - onboardingNtpBackgrounds[backgroundIndex], - l10n_util::GetStringFUTF8( - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, - base::UTF8ToUTF16("Giulio Rosso Chioso")), + NtpBackgrounds[backgroundIndex], + l10n_util::GetStringFUTF8(IDS_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL, + base::UTF8ToUTF16("Giulio Rosso Chioso")), "", GURL("https://500px.com/photo/41149196/" "le-piscine-sunset-by-giulio-rosso-chioso"), @@ -177,4 +168,4 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) { } } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.h index d2c23fab9d2..acf86d33a7f 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/ntp_background_handler.h @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_HANDLER_H_ #include "content/public/browser/web_ui_message_handler.h" -namespace nux { +namespace welcome { class NtpBackgroundHandler : public content::WebUIMessageHandler { public: @@ -26,6 +26,6 @@ class NtpBackgroundHandler : public content::WebUIMessageHandler { DISALLOW_COPY_AND_ASSIGN(NtpBackgroundHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_NTP_BACKGROUND_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NTP_BACKGROUND_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/README b/chromium/chrome/browser/ui/webui/welcome/nux/README deleted file mode 100644 index b2d6888146e..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/README +++ /dev/null @@ -1,3 +0,0 @@ -New User Experience Experiment (NUX). Code here will prompt new users to go -through an onboarding experience to customize their new browser install to -their common usages.
\ No newline at end of file diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc b/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc deleted file mode 100644 index ac31489fd77..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/constants.cc +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/welcome/nux/constants.h" - -#include "base/feature_list.h" - -namespace nux { - -const base::Feature kNuxOnboardingFeature{"NuxOnboarding", - base::FEATURE_ENABLED_BY_DEFAULT}; - -const char kDefaultNewUserModules[] = - "nux-google-apps,nux-set-as-default,signin-view"; -const char kDefaultReturningUserModules[] = "nux-set-as-default"; - -// The value of these FeatureParam values should be a comma-delimited list -// of element names whitelisted in the MODULES_WHITELIST list, defined in -// chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js -const base::FeatureParam<std::string> kNuxOnboardingNewUserModules{ - &kNuxOnboardingFeature, "new-user-modules", kDefaultNewUserModules}; -const base::FeatureParam<std::string> kNuxOnboardingReturningUserModules{ - &kNuxOnboardingFeature, "returning-user-modules", - kDefaultReturningUserModules}; - -const base::FeatureParam<bool> kNuxOnboardingShowGoogleApp{ - &kNuxOnboardingFeature, "app-variation-enabled", false}; - -} // namespace nux diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/constants.h b/chromium/chrome/browser/ui/webui/welcome/nux/constants.h deleted file mode 100644 index de397b2f0d6..00000000000 --- a/chromium/chrome/browser/ui/webui/welcome/nux/constants.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ - -#include <string> -#include "base/metrics/field_trial_params.h" - -namespace base { -struct Feature; -} // namespace base - -namespace nux { - -extern const base::Feature kNuxOnboardingFeature; - -extern const char kDefaultNewUserModules[]; -extern const char kDefaultReturningUserModules[]; - -extern const base::FeatureParam<std::string> kNuxOnboardingNewUserModules; -extern const base::FeatureParam<std::string> kNuxOnboardingReturningUserModules; -extern const base::FeatureParam<bool> kNuxOnboardingShowGoogleApp; - -} // namespace nux - -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_CONSTANTS_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.cc index 3d4f3387ec8..bd511dcc572 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.cc @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h" +#include "chrome/browser/ui/webui/welcome/set_as_default_handler.h" -namespace nux { +namespace welcome { SetAsDefaultHandler::SetAsDefaultHandler() : settings::DefaultBrowserHandler() {} @@ -15,4 +15,4 @@ void SetAsDefaultHandler::RecordSetAsDefaultUMA() { // TODO(hcarmona): Add UMA tracking. } -} // namespace nux +} // namespace welcome diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.h index 5f70e699ea6..e06476a4583 100644 --- a/chromium/chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h +++ b/chromium/chrome/browser/ui/webui/welcome/set_as_default_handler.h @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SET_AS_DEFAULT_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SET_AS_DEFAULT_HANDLER_H_ +#ifndef CHROME_BROWSER_UI_WEBUI_WELCOME_SET_AS_DEFAULT_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_WELCOME_SET_AS_DEFAULT_HANDLER_H_ #include "base/macros.h" #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" -namespace nux { +namespace welcome { class SetAsDefaultHandler : public settings::DefaultBrowserHandler { public: @@ -21,6 +21,6 @@ class SetAsDefaultHandler : public settings::DefaultBrowserHandler { DISALLOW_COPY_AND_ASSIGN(SetAsDefaultHandler); }; -} // namespace nux +} // namespace welcome -#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_NUX_SET_AS_DEFAULT_HANDLER_H_ +#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_SET_AS_DEFAULT_HANDLER_H_ diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc index 222a102b2be..17d4764ec78 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc @@ -61,7 +61,7 @@ void WelcomeHandler::OnSyncConfirmationUIClosed( if (result != LoginUIService::ABORT_SIGNIN) { result_ = WelcomeResult::SIGNED_IN; - // When signed in from NUX onboarding flow, it's possible to come back to + // When signed in from welcome flow, it's possible to come back to // chrome://welcome/... after closing sync-confirmation UI. If current URL // matches such a case, do not navigate away. if (!is_redirected_welcome_impression_) { @@ -110,7 +110,7 @@ void WelcomeHandler::HandleUserDecline(const base::ListValue* args) { // Override from WebUIMessageHandler. void WelcomeHandler::RegisterMessages() { - // Check if this instance of WelcomeHandler is spawned by onboarding flow + // Check if this instance of WelcomeHandler is spawned by welcome flow // redirecting users back to welcome page. This is done here instead of // constructor, because web_ui hasn't loaded yet at that time. is_redirected_welcome_impression_ = isValidRedirectUrl(); diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc index d05ae4c1e86..d0b69ca81d4 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc @@ -9,19 +9,18 @@ #include "build/branding_buildflags.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/ui/webui/localized_string.h" -#include "chrome/browser/ui/webui/welcome/nux/bookmark_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/constants.h" -#include "chrome/browser/ui/webui/welcome/nux/google_apps_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_handler.h" -#include "chrome/browser/ui/webui/welcome/nux/set_as_default_handler.h" -#include "chrome/browser/ui/webui/welcome/nux_helper.h" +#include "chrome/browser/ui/webui/welcome/bookmark_handler.h" +#include "chrome/browser/ui/webui/welcome/google_apps_handler.h" +#include "chrome/browser/ui/webui/welcome/helpers.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_handler.h" +#include "chrome/browser/ui/webui/welcome/set_as_default_handler.h" #include "chrome/browser/ui/webui/welcome/welcome_handler.h" #include "chrome/common/pref_names.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "chrome/grit/onboarding_welcome_resources.h" -#include "chrome/grit/onboarding_welcome_resources_map.h" +#include "chrome/grit/welcome_resources.h" +#include "chrome/grit/welcome_resources_map.h" #include "components/prefs/pref_service.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/strings/grit/components_strings.h" @@ -67,49 +66,44 @@ void HandleRequestCallback( weak_ptr->CreateBackgroundFetcher(background_index, callback); } -void AddOnboardingStrings(content::WebUIDataSource* html_source) { +void AddStrings(content::WebUIDataSource* html_source) { static constexpr LocalizedString kLocalizedStrings[] = { // Shared strings. - {"bookmarkAdded", IDS_ONBOARDING_WELCOME_BOOKMARK_ADDED}, - {"bookmarksAdded", IDS_ONBOARDING_WELCOME_BOOKMARKS_ADDED}, - {"bookmarkRemoved", IDS_ONBOARDING_WELCOME_BOOKMARK_REMOVED}, - {"bookmarksRemoved", IDS_ONBOARDING_WELCOME_BOOKMARKS_REMOVED}, - {"defaultBrowserChanged", IDS_ONBOARDING_DEFAULT_BROWSER_CHANGED}, + {"bookmarkAdded", IDS_WELCOME_BOOKMARK_ADDED}, + {"bookmarksAdded", IDS_WELCOME_BOOKMARKS_ADDED}, + {"bookmarkRemoved", IDS_WELCOME_BOOKMARK_REMOVED}, + {"bookmarksRemoved", IDS_WELCOME_BOOKMARKS_REMOVED}, + {"defaultBrowserChanged", IDS_DEFAULT_BROWSER_CHANGED}, {"headerText", IDS_WELCOME_HEADER}, - {"next", IDS_ONBOARDING_WELCOME_NEXT}, + {"next", IDS_WELCOME_NEXT}, {"noThanks", IDS_NO_THANKS}, - {"skip", IDS_ONBOARDING_WELCOME_SKIP}, + {"skip", IDS_WELCOME_SKIP}, // Sign-in view strings. - {"signInHeader", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_HEADER}, - {"signInSubHeader", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_SUB_HEADER}, - {"signIn", IDS_ONBOARDING_WELCOME_SIGNIN_VIEW_SIGNIN}, + {"signInHeader", IDS_WELCOME_SIGNIN_VIEW_HEADER}, + {"signInSubHeader", IDS_WELCOME_SIGNIN_VIEW_SUB_HEADER}, + {"signIn", IDS_WELCOME_SIGNIN_VIEW_SIGNIN}, // Google apps module strings. - {"googleAppsDescription", - IDS_ONBOARDING_WELCOME_NUX_GOOGLE_APPS_DESCRIPTION}, + {"googleAppsDescription", IDS_WELCOME_GOOGLE_APPS_DESCRIPTION}, // New Tab Page background module strings. - {"ntpBackgroundDescription", - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_DESCRIPTION}, - {"ntpBackgroundDefault", - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_DEFAULT_TITLE}, + {"ntpBackgroundDescription", IDS_WELCOME_NTP_BACKGROUND_DESCRIPTION}, + {"ntpBackgroundDefault", IDS_WELCOME_NTP_BACKGROUND_DEFAULT_TITLE}, {"ntpBackgroundPreviewUpdated", - IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PREVIEW_UPDATED}, - {"ntpBackgroundReset", IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_RESET}, + IDS_WELCOME_NTP_BACKGROUND_PREVIEW_UPDATED}, + {"ntpBackgroundReset", IDS_WELCOME_NTP_BACKGROUND_RESET}, // Set as default module strings. - {"setDefaultHeader", IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_HEADER}, - {"setDefaultSubHeader", - IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SUB_HEADER}, - {"setDefaultConfirm", - IDS_ONBOARDING_WELCOME_NUX_SET_AS_DEFAULT_SET_AS_DEFAULT}, + {"setDefaultHeader", IDS_WELCOME_SET_AS_DEFAULT_HEADER}, + {"setDefaultSubHeader", IDS_WELCOME_SET_AS_DEFAULT_SUB_HEADER}, + {"setDefaultConfirm", IDS_WELCOME_SET_AS_DEFAULT_SET_AS_DEFAULT}, // Landing view strings. - {"landingTitle", IDS_ONBOARDING_WELCOME_LANDING_TITLE}, - {"landingDescription", IDS_ONBOARDING_WELCOME_LANDING_DESCRIPTION}, - {"landingNewUser", IDS_ONBOARDING_WELCOME_LANDING_NEW_USER}, - {"landingExistingUser", IDS_ONBOARDING_WELCOME_LANDING_EXISTING_USER}, + {"landingTitle", IDS_WELCOME_LANDING_TITLE}, + {"landingDescription", IDS_WELCOME_LANDING_DESCRIPTION}, + {"landingNewUser", IDS_WELCOME_LANDING_NEW_USER}, + {"landingExistingUser", IDS_WELCOME_LANDING_EXISTING_USER}, }; AddLocalizedStringsBulk(html_source, kLocalizedStrings, base::size(kLocalizedStrings)); @@ -134,13 +128,13 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) content::WebUIDataSource* html_source = content::WebUIDataSource::Create(url.host()); - // Add Onboarding welcome strings. - AddOnboardingStrings(html_source); + // Add welcome strings. + AddStrings(html_source); - // Add all Onboarding resources. - for (size_t i = 0; i < kOnboardingWelcomeResourcesSize; ++i) { - html_source->AddResourcePath(kOnboardingWelcomeResources[i].name, - kOnboardingWelcomeResources[i].value); + // Add all welcome resources. + for (size_t i = 0; i < kWelcomeResourcesSize; ++i) { + html_source->AddResourcePath(kWelcomeResources[i].name, + kWelcomeResources[i].value); } #if BUILDFLAG(GOOGLE_CHROME_BRANDING) @@ -174,33 +168,32 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) // chrome://welcome - html_source->SetDefaultResource(IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_HTML); + html_source->SetDefaultResource(IDR_WELCOME_HTML); #if defined(OS_WIN) html_source->AddBoolean("is_win10", base::win::GetVersion() >= base::win::Version::WIN10); #endif - // Add the shared bookmark handler for onboarding modules. + // Add the shared bookmark handler for welcome modules. web_ui->AddMessageHandler( - std::make_unique<nux::BookmarkHandler>(profile->GetPrefs())); + std::make_unique<welcome::BookmarkHandler>(profile->GetPrefs())); - // Add google apps bookmarking onboarding module. - web_ui->AddMessageHandler(std::make_unique<nux::GoogleAppsHandler>()); + // Add google apps bookmarking module. + web_ui->AddMessageHandler(std::make_unique<welcome::GoogleAppsHandler>()); - // Add NTP custom background onboarding module. - web_ui->AddMessageHandler(std::make_unique<nux::NtpBackgroundHandler>()); + // Add NTP custom background module. + web_ui->AddMessageHandler(std::make_unique<welcome::NtpBackgroundHandler>()); - // Add set-as-default onboarding module. - web_ui->AddMessageHandler(std::make_unique<nux::SetAsDefaultHandler>()); + // Add set-as-default module. + web_ui->AddMessageHandler(std::make_unique<welcome::SetAsDefaultHandler>()); html_source->AddString( "newUserModules", - nux::GetNuxOnboardingModules(profile).FindKey("new-user")->GetString()); - html_source->AddString("returningUserModules", - nux::GetNuxOnboardingModules(profile) - .FindKey("returning-user") - ->GetString()); + welcome::GetModules(profile).FindKey("new-user")->GetString()); + html_source->AddString( + "returningUserModules", + welcome::GetModules(profile).FindKey("returning-user")->GetString()); html_source->AddBoolean( "signinAllowed", profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed)); html_source->SetRequestFilter( @@ -208,7 +201,7 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) weak_ptr_factory_.GetWeakPtr()), base::BindRepeating(&HandleRequestCallback, weak_ptr_factory_.GetWeakPtr())); - html_source->SetJsonPath("strings.js"); + html_source->UseStringsJs(); content::WebUIDataSource::Add(profile, html_source); } @@ -218,8 +211,8 @@ WelcomeUI::~WelcomeUI() {} void WelcomeUI::CreateBackgroundFetcher( size_t background_index, const content::WebUIDataSource::GotDataCallback& callback) { - background_fetcher_ = - std::make_unique<nux::NtpBackgroundFetcher>(background_index, callback); + background_fetcher_ = std::make_unique<welcome::NtpBackgroundFetcher>( + background_index, callback); } void WelcomeUI::StorePageSeen(Profile* profile) { diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h index ed54ca23bc1..3f0be1af968 100644 --- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h +++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h @@ -10,7 +10,7 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/welcome/nux/ntp_background_fetcher.h" +#include "chrome/browser/ui/webui/welcome/ntp_background_fetcher.h" #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_data_source.h" #include "url/gurl.h" @@ -34,7 +34,7 @@ class WelcomeUI : public content::WebUIController { private: void StorePageSeen(Profile* profile); - std::unique_ptr<nux::NtpBackgroundFetcher> background_fetcher_; + std::unique_ptr<welcome::NtpBackgroundFetcher> background_fetcher_; base::WeakPtrFactory<WelcomeUI> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WelcomeUI); diff --git a/chromium/chrome/browser/vr/BUILD.gn b/chromium/chrome/browser/vr/BUILD.gn index 0dc72c1ee03..ffbf1706796 100644 --- a/chromium/chrome/browser/vr/BUILD.gn +++ b/chromium/chrome/browser/vr/BUILD.gn @@ -246,8 +246,8 @@ component("vr_common") { "service/interface_set.h", "service/vr_service_impl.cc", "service/vr_service_impl.h", - "service/xr_device_impl.cc", - "service/xr_device_impl.h", + "service/xr_device_service.cc", + "service/xr_device_service.h", "service/xr_runtime_manager.cc", "service/xr_runtime_manager.h", "service/xr_runtime_manager_observer.h", @@ -276,6 +276,7 @@ component("vr_common") { public_deps = [ ":vr_base", + "//device/vr/public/mojom", ] deps = [ @@ -390,6 +391,7 @@ component("vr_base") { "pose_util.h", "render_info.h", "scheduler_ui_interface.h", + "service/xr_consent_prompt_level.h", "speech_recognizer.cc", "speech_recognizer.h", "text_edit_action.cc", @@ -771,12 +773,18 @@ if (!is_android) { ] deps += [ + ":vr_common", "//components/content_settings/core/browser", "//device/vr:directx_helpers", "//third_party/openvr", ] data_deps += [ "//device/vr:openvr_mock" ] + + if (enable_openxr) { + deps += [ "//third_party/openxr" ] + data_deps += [ "//device/vr:openxr_mock" ] + } } } diff --git a/chromium/chrome/browser/web_applications/BUILD.gn b/chromium/chrome/browser/web_applications/BUILD.gn index 00d0ad6f6b9..a5a977d0293 100644 --- a/chromium/chrome/browser/web_applications/BUILD.gn +++ b/chromium/chrome/browser/web_applications/BUILD.gn @@ -12,10 +12,16 @@ group("web_app_test_group") { source_set("web_applications") { sources = [ "abstract_web_app_database.h", - "external_web_apps.cc", - "external_web_apps.h", + "external_web_app_manager.cc", + "external_web_app_manager.h", "file_utils_wrapper.cc", "file_utils_wrapper.h", + "pending_app_install_task.cc", + "pending_app_install_task.h", + "pending_app_manager_impl.cc", + "pending_app_manager_impl.h", + "pending_app_registration_task.cc", + "pending_app_registration_task.h", "system_web_app_manager.cc", "system_web_app_manager.h", "web_app.cc", @@ -24,6 +30,8 @@ source_set("web_applications") { "web_app_database.h", "web_app_database_factory.cc", "web_app_database_factory.h", + "web_app_file_handler_manager.cc", + "web_app_file_handler_manager.h", "web_app_icon_manager.cc", "web_app_icon_manager.h", "web_app_install_finalizer.cc", @@ -34,12 +42,12 @@ source_set("web_applications") { "web_app_install_task.h", "web_app_registrar.cc", "web_app_registrar.h", + "web_app_registry_update.cc", + "web_app_registry_update.h", "web_app_sync_bridge.cc", "web_app_sync_bridge.h", "web_app_sync_manager.cc", "web_app_sync_manager.h", - "web_app_tab_helper.cc", - "web_app_tab_helper.h", ] deps = [ @@ -57,7 +65,7 @@ source_set("web_applications") { "//ash/public/cpp:cpp", "//chromeos/constants", "//components/arc:arc_base", - "//components/arc/common", + "//components/arc/mojom", ] } @@ -66,6 +74,7 @@ source_set("web_applications") { ] } +# This test_support library doesn't use extensions. source_set("web_applications_test_support") { testonly = true @@ -74,6 +83,8 @@ source_set("web_applications_test_support") { "test/test_app_registrar.h", "test/test_data_retriever.cc", "test/test_data_retriever.h", + "test/test_file_handler_manager.cc", + "test/test_file_handler_manager.h", "test/test_file_utils.cc", "test/test_file_utils.h", "test/test_install_finalizer.cc", @@ -90,7 +101,12 @@ source_set("web_applications_test_support") { "test/test_web_app_ui_manager.h", "test/test_web_app_url_loader.cc", "test/test_web_app_url_loader.h", - "test/web_app_test.cc", + "test/web_app_icon_test_utils.cc", + "test/web_app_icon_test_utils.h", + "test/web_app_install_observer.cc", + "test/web_app_install_observer.h", + "test/web_app_registration_waiter.cc", + "test/web_app_registration_waiter.h", "test/web_app_test.h", ] @@ -111,6 +127,8 @@ source_set("web_applications_unit_tests") { testonly = true sources = [ + "external_web_app_manager_unittest.cc", + "pending_app_manager_impl_unittest.cc", "web_app_database_unittest.cc", "web_app_icon_manager_unittest.cc", "web_app_install_manager_unittest.cc", @@ -121,6 +139,7 @@ source_set("web_applications_unit_tests") { deps = [ ":web_app_test_group", ":web_applications", + ":web_applications_on_extensions_test_support", ":web_applications_test_support", "//base/test:test_support", "//chrome/browser", @@ -137,13 +156,31 @@ source_set("web_applications_unit_tests") { "//chrome/browser/chromeos", "//components/arc:arc", "//components/arc:arc_test_support", - "//components/arc/common", + "//components/arc/mojom", ] } } -# TODO(loyso): Erase this and move WebAppProvider into web_applications set. -# crbug.com/877898 +source_set("web_applications_browser_tests") { + testonly = true + + sources = [ + "pending_app_manager_impl_browsertest.cc", + ] + + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] + + deps = [ + ":web_applications", + ":web_applications_test_support", + "//chrome/browser/web_applications/components", + "//chrome/test:test_support", + "//chrome/test:test_support_ui", + ] +} + +# TODO(crbug.com/877898): Erase this and move WebAppProvider into +# web_applications set. source_set("web_applications_on_extensions") { sources = [ "web_app_provider.cc", @@ -155,7 +192,6 @@ source_set("web_applications_on_extensions") { deps = [ ":web_app_group", ":web_applications", - "//chrome/browser/web_applications/bookmark_apps", "//chrome/browser/web_applications/components", "//chrome/browser/web_applications/extensions", "//chrome/common", @@ -165,24 +201,45 @@ source_set("web_applications_on_extensions") { ] } -source_set("unit_tests") { +# TODO(crbug.com/877898): Erase this and move TestWebAppProvider into +# web_applications_test_support set. +source_set("web_applications_on_extensions_test_support") { + testonly = true + + sources = [ + "test/test_web_app_provider.cc", + "test/test_web_app_provider.h", + ] + + deps = [ + ":web_app_test_group", + ":web_applications", + ":web_applications_on_extensions", + ":web_applications_test_support", + "//base", + "//chrome/browser", + "//chrome/browser/web_applications/components", + "//components/keyed_service/content", + ] +} + +group("unit_tests") { testonly = true deps = [ ":web_app_test_group", ":web_applications_unit_tests", - "//chrome/browser/web_applications/bookmark_apps:unit_tests", "//chrome/browser/web_applications/components:unit_tests", "//chrome/browser/web_applications/extensions:unit_tests", ] } -source_set("browser_tests") { +group("browser_tests") { testonly = true deps = [ ":web_app_test_group", - "//chrome/browser/web_applications/bookmark_apps:browser_tests", + ":web_applications_browser_tests", "//chrome/browser/web_applications/components:browser_tests", "//chrome/browser/web_applications/extensions:browser_tests", ] diff --git a/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn b/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn deleted file mode 100644 index a0e5d37981a..00000000000 --- a/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn +++ /dev/null @@ -1,111 +0,0 @@ -# Copyright 2018 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//extensions/buildflags/buildflags.gni") - -assert(enable_extensions) - -source_set("bookmark_apps") { - sources = [ - "bookmark_app_install_manager.cc", - "bookmark_app_install_manager.h", - ] - - deps = [ - "//chrome/browser/extensions", - "//chrome/browser/web_applications:web_app_group", - "//chrome/browser/web_applications/components", - "//chrome/browser/web_applications/extensions", - "//chrome/common", - "//components/favicon/content", - "//components/pref_registry", - "//extensions/browser", - "//skia", - ] -} - -source_set("test_support") { - testonly = true - - sources = [ - "test_web_app_provider.cc", - "test_web_app_provider.h", - ] - - deps = [ - ":bookmark_apps", - "//base", - "//chrome/browser", - "//chrome/browser/web_applications", - "//chrome/browser/web_applications:web_app_test_group", - "//chrome/browser/web_applications:web_applications_on_extensions", - "//chrome/browser/web_applications:web_applications_test_support", - "//chrome/browser/web_applications/components", - "//components/keyed_service/content", - ] -} - -source_set("unit_tests") { - testonly = true - - sources = [ - "bookmark_app_install_manager_unittest.cc", - "external_web_apps_unittest.cc", - "policy/web_app_policy_manager_unittest.cc", - "system_web_app_manager_unittest.cc", - ] - - deps = [ - ":bookmark_apps", - ":test_support", - "//base", - "//chrome/browser", - "//chrome/browser/web_applications", - "//chrome/browser/web_applications:web_app_test_group", - "//chrome/browser/web_applications:web_applications_on_extensions", - "//chrome/browser/web_applications:web_applications_test_support", - "//chrome/browser/web_applications/components", - "//chrome/browser/web_applications/extensions", - "//chrome/common:constants", - "//chrome/test:test_support", - "//components/account_id", - "//components/crx_file:crx_file", - "//components/sync_preferences:test_support", - "//content/test:test_support", - "//extensions/common", - "//skia", - "//testing/gmock", - "//testing/gtest", - "//url", - ] -} - -source_set("browser_tests") { - testonly = true - - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] - - sources = [ - "system_web_app_manager_browsertest.cc", - "system_web_app_manager_browsertest.h", - ] - - deps = [ - ":bookmark_apps", - ":test_support", - "//base", - "//base/test:test_support", - "//chrome/app/theme:chrome_unscaled_resources_grit", - "//chrome/browser/web_applications", - "//chrome/browser/web_applications:web_applications_on_extensions", - "//chrome/browser/web_applications:web_applications_test_support", - "//chrome/browser/web_applications/components", - "//chrome/browser/web_applications/extensions", - "//chrome/common:constants", - "//chrome/test:test_support", - "//chrome/test:test_support_ui", - "//extensions/browser", - "//url", - ] -} diff --git a/chromium/chrome/browser/web_applications/components/BUILD.gn b/chromium/chrome/browser/web_applications/components/BUILD.gn index 3e00c9d2dc4..d8ff81bdce2 100644 --- a/chromium/chrome/browser/web_applications/components/BUILD.gn +++ b/chromium/chrome/browser/web_applications/components/BUILD.gn @@ -4,6 +4,8 @@ source_set("components") { sources = [ + "app_icon_manager.cc", + "app_icon_manager.h", "app_registrar.cc", "app_registrar.h", "app_registrar_observer.h", @@ -11,12 +13,17 @@ source_set("components") { "external_install_options.h", "externally_installed_web_app_prefs.cc", "externally_installed_web_app_prefs.h", + "file_handler_manager.h", "install_bounce_metric.cc", "install_bounce_metric.h", + "install_finalizer.cc", "install_finalizer.h", "install_manager.cc", "install_manager.h", - "install_manager_observer.h", + "manifest_update_manager.cc", + "manifest_update_manager.h", + "manifest_update_task.cc", + "manifest_update_task.h", "pending_app_manager.cc", "pending_app_manager.h", "policy/web_app_policy_constants.cc", @@ -25,6 +32,7 @@ source_set("components") { "policy/web_app_policy_manager.h", "web_app_audio_focus_id_map.cc", "web_app_audio_focus_id_map.h", + "web_app_constants.cc", "web_app_constants.h", "web_app_data_retriever.cc", "web_app_data_retriever.h", @@ -45,8 +53,8 @@ source_set("components") { "web_app_shortcut_mac.mm", "web_app_shortcut_win.cc", "web_app_shortcut_win.h", - "web_app_tab_helper_base.cc", - "web_app_tab_helper_base.h", + "web_app_tab_helper.cc", + "web_app_tab_helper.h", "web_app_ui_manager.h", "web_app_url_loader.cc", "web_app_url_loader.h", @@ -131,13 +139,16 @@ source_set("browser_tests") { testonly = true sources = [ + "manifest_update_manager_browsertest.cc", "web_app_url_loader_browsertest.cc", ] defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] deps = [ - "//chrome/browser/web_applications/components", + ":components", + "//chrome/app:command_ids", + "//chrome/browser/web_applications:web_applications_test_support", "//chrome/test:test_support", "//chrome/test:test_support_ui", "//net:test_support", diff --git a/chromium/chrome/browser/web_applications/extensions/BUILD.gn b/chromium/chrome/browser/web_applications/extensions/BUILD.gn index 6f05beba117..0f7147cf70b 100644 --- a/chromium/chrome/browser/web_applications/extensions/BUILD.gn +++ b/chromium/chrome/browser/web_applications/extensions/BUILD.gn @@ -8,18 +8,18 @@ assert(enable_extensions) source_set("extensions") { sources = [ + "bookmark_app_file_handler_manager.cc", + "bookmark_app_file_handler_manager.h", + "bookmark_app_finalizer_utils.cc", + "bookmark_app_finalizer_utils.h", + "bookmark_app_icon_manager.cc", + "bookmark_app_icon_manager.h", "bookmark_app_install_finalizer.cc", "bookmark_app_install_finalizer.h", - "bookmark_app_installation_task.cc", - "bookmark_app_installation_task.h", "bookmark_app_registrar.cc", "bookmark_app_registrar.h", - "bookmark_app_tab_helper.cc", - "bookmark_app_tab_helper.h", "bookmark_app_util.cc", "bookmark_app_util.h", - "pending_bookmark_app_manager.cc", - "pending_bookmark_app_manager.h", "web_app_extension_shortcut.cc", "web_app_extension_shortcut.h", "web_app_extension_shortcut_mac.h", @@ -42,14 +42,13 @@ source_set("unit_tests") { testonly = true sources = [ - # Deprecated tests. TODO(crbug.com/915043): Erase this .cc file: - "bookmark_app_helper_installation_task_unittest.cc", "bookmark_app_install_finalizer_unittest.cc", - "bookmark_app_installation_task_unittest.cc", "bookmark_app_util_unittest.cc", "externally_installed_web_app_prefs_unittest.cc", "install_manager_bookmark_app_unittest.cc", - "pending_bookmark_app_manager_unittest.cc", + "pending_app_install_task_unittest.cc", + "system_web_app_manager_unittest.cc", + "web_app_policy_manager_unittest.cc", "web_app_provider_unittest.cc", ] @@ -59,8 +58,8 @@ source_set("unit_tests") { "//chrome/browser/web_applications:web_app_test_group", "//chrome/browser/web_applications:web_applications", "//chrome/browser/web_applications:web_applications_on_extensions", + "//chrome/browser/web_applications:web_applications_on_extensions_test_support", "//chrome/browser/web_applications:web_applications_test_support", - "//chrome/browser/web_applications/bookmark_apps", "//chrome/browser/web_applications/components", "//chrome/common", "//chrome/test:test_support", @@ -79,8 +78,8 @@ source_set("browser_tests") { sources = [ "bookmark_app_registrar_browsertest.cc", - "install_manager_bookmark_app_browsertest.cc", - "pending_bookmark_app_manager_browsertest.cc", + "system_web_app_manager_browsertest.cc", + "system_web_app_manager_browsertest.h", "web_app_audio_focus_browsertest.cc", ] @@ -89,10 +88,13 @@ source_set("browser_tests") { deps = [ ":extensions", "//base/test:test_support", + "//chrome/app/theme:chrome_unscaled_resources_grit", "//chrome/browser", "//chrome/browser/ui", "//chrome/browser/web_applications:web_app_test_group", "//chrome/browser/web_applications:web_applications_on_extensions", + "//chrome/browser/web_applications:web_applications_on_extensions_test_support", + "//chrome/browser/web_applications:web_applications_test_support", "//chrome/browser/web_applications/components", "//chrome/test:test_support", "//chrome/test:test_support_ui", |