diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-01-04 14:17:57 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-01-05 10:05:06 +0000 |
commit | 39d357e3248f80abea0159765ff39554affb40db (patch) | |
tree | aba0e6bfb76de0244bba0f5fdbd64b830dd6e621 /chromium/chrome/browser/extensions | |
parent | 87778abf5a1f89266f37d1321b92a21851d8244d (diff) | |
download | qtwebengine-chromium-39d357e3248f80abea0159765ff39554affb40db.tar.gz |
BASELINE: Update Chromium to 55.0.2883.105
And updates ninja to 1.7.2
Change-Id: I20d43c737f82764d857ada9a55586901b18b9243
Reviewed-by: Michael BrĂ¼ning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/chrome/browser/extensions')
328 files changed, 6152 insertions, 10985 deletions
diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn index c304abdfcf8..2e050759cac 100644 --- a/chromium/chrome/browser/extensions/BUILD.gn +++ b/chromium/chrome/browser/extensions/BUILD.gn @@ -4,21 +4,796 @@ import("//build/config/features.gni") import("//build/config/ui.gni") +import("//chrome/common/features.gni") assert(enable_extensions) -gypi_values = - exec_script("//build/gypi_to_gn.py", - [ rebase_path("../../chrome_browser_extensions.gypi") ], - "scope", - [ "../../chrome_browser_extensions.gypi" ]) - -# GYP version: chrome/chrome_browser_extensions.gypi:browser_extensions static_library("extensions") { - sources = [] - sources += rebase_path(gypi_values.chrome_browser_extensions_enabled_sources, - ".", - "//chrome") + sources = [ + # TODO These references to files in //chrome/browser/ should either be + # moved to the browser target or the files moved to this directory. + "../apps/app_launch_for_metro_restart_win.cc", + "../apps/app_launch_for_metro_restart_win.h", + "../apps/app_url_redirector.cc", + "../apps/app_url_redirector.h", + "../apps/app_window_registry_util.cc", + "../apps/app_window_registry_util.h", + "../apps/install_chrome_app.cc", + "../apps/install_chrome_app.h", + "../apps/shortcut_manager.cc", + "../apps/shortcut_manager.h", + "../apps/shortcut_manager_factory.cc", + "../apps/shortcut_manager_factory.h", + "../ui/app_icon_loader.cc", + "../ui/app_icon_loader.h", + "../ui/toolbar/toolbar_actions_model.cc", + "../ui/toolbar/toolbar_actions_model.h", + "../ui/toolbar/toolbar_actions_model_factory.cc", + "../ui/toolbar/toolbar_actions_model_factory.h", + "../web_applications/update_shortcut_worker_win.cc", + "../web_applications/update_shortcut_worker_win.h", + "../web_applications/web_app.cc", + "../web_applications/web_app.h", + "../web_applications/web_app_chromeos.cc", + "../web_applications/web_app_mac.h", + "../web_applications/web_app_mac.mm", + "../web_applications/web_app_win.cc", + "../web_applications/web_app_win.h", + "active_install_data.cc", + "active_install_data.h", + "active_tab_permission_granter.cc", + "active_tab_permission_granter.h", + "activity_log/activity_action_constants.cc", + "activity_log/activity_action_constants.h", + "activity_log/activity_actions.cc", + "activity_log/activity_actions.h", + "activity_log/activity_database.cc", + "activity_log/activity_database.h", + "activity_log/activity_log.cc", + "activity_log/activity_log.h", + "activity_log/activity_log_policy.cc", + "activity_log/activity_log_policy.h", + "activity_log/counting_policy.cc", + "activity_log/counting_policy.h", + "activity_log/database_string_table.cc", + "activity_log/database_string_table.h", + "activity_log/fullstream_ui_policy.cc", + "activity_log/fullstream_ui_policy.h", + "api/activity_log_private/activity_log_private_api.cc", + "api/activity_log_private/activity_log_private_api.h", + "api/autofill_private/autofill_private_api.cc", + "api/autofill_private/autofill_private_api.h", + "api/autofill_private/autofill_private_event_router.cc", + "api/autofill_private/autofill_private_event_router.h", + "api/autofill_private/autofill_private_event_router_factory.cc", + "api/autofill_private/autofill_private_event_router_factory.h", + "api/autofill_private/autofill_util.cc", + "api/autofill_private/autofill_util.h", + "api/automation_internal/automation_action_adapter.h", + "api/automation_internal/automation_event_router.cc", + "api/automation_internal/automation_event_router.h", + "api/automation_internal/automation_internal_api.cc", + "api/automation_internal/automation_internal_api.h", + "api/autotest_private/autotest_private_api.cc", + "api/autotest_private/autotest_private_api.h", + "api/bookmark_manager_private/bookmark_manager_private_api.cc", + "api/bookmark_manager_private/bookmark_manager_private_api.h", + "api/bookmarks/bookmark_api_constants.cc", + "api/bookmarks/bookmark_api_constants.h", + "api/bookmarks/bookmark_api_helpers.cc", + "api/bookmarks/bookmark_api_helpers.h", + "api/bookmarks/bookmarks_api.cc", + "api/bookmarks/bookmarks_api.h", + "api/braille_display_private/braille_controller.h", + "api/braille_display_private/braille_controller_brlapi.h", + "api/braille_display_private/braille_display_private_api.cc", + "api/braille_display_private/braille_display_private_api.h", + "api/braille_display_private/stub_braille_controller.cc", + "api/braille_display_private/stub_braille_controller.h", + "api/browser/browser_api.cc", + "api/browser/browser_api.h", + "api/browsing_data/browsing_data_api.cc", + "api/browsing_data/browsing_data_api.h", + "api/chrome_device_permissions_prompt.h", + "api/chrome_extensions_api_client.cc", + "api/chrome_extensions_api_client.h", + "api/cloud_print_private/cloud_print_private_api.cc", + "api/cloud_print_private/cloud_print_private_api.h", + "api/command_line_private/command_line_private_api.cc", + "api/command_line_private/command_line_private_api.h", + "api/commands/command_service.cc", + "api/commands/command_service.h", + "api/commands/commands.cc", + "api/commands/commands.h", + "api/content_settings/content_settings_api.cc", + "api/content_settings/content_settings_api.h", + "api/content_settings/content_settings_api_constants.cc", + "api/content_settings/content_settings_api_constants.h", + "api/content_settings/content_settings_custom_extension_provider.cc", + "api/content_settings/content_settings_custom_extension_provider.h", + "api/content_settings/content_settings_helpers.cc", + "api/content_settings/content_settings_helpers.h", + "api/content_settings/content_settings_service.cc", + "api/content_settings/content_settings_service.h", + "api/content_settings/content_settings_store.cc", + "api/content_settings/content_settings_store.h", + "api/context_menus/context_menus_api.cc", + "api/context_menus/context_menus_api.h", + "api/context_menus/context_menus_api_helpers.cc", + "api/context_menus/context_menus_api_helpers.h", + "api/cookies/cookies_api.cc", + "api/cookies/cookies_api.h", + "api/cookies/cookies_api_constants.cc", + "api/cookies/cookies_api_constants.h", + "api/cookies/cookies_helpers.cc", + "api/cookies/cookies_helpers.h", + "api/cryptotoken_private/cryptotoken_private_api.cc", + "api/cryptotoken_private/cryptotoken_private_api.h", + "api/dashboard_private/dashboard_private_api.cc", + "api/dashboard_private/dashboard_private_api.h", + "api/data_reduction_proxy/data_reduction_proxy_api.cc", + "api/data_reduction_proxy/data_reduction_proxy_api.h", + "api/debugger/debugger_api.cc", + "api/debugger/debugger_api.h", + "api/debugger/debugger_api_constants.cc", + "api/debugger/debugger_api_constants.h", + "api/declarative_content/chrome_content_rules_registry.cc", + "api/declarative_content/chrome_content_rules_registry.h", + "api/declarative_content/content_action.cc", + "api/declarative_content/content_action.h", + "api/declarative_content/content_condition.cc", + "api/declarative_content/content_condition.h", + "api/declarative_content/content_constants.cc", + "api/declarative_content/content_constants.h", + "api/declarative_content/content_predicate.cc", + "api/declarative_content/content_predicate.h", + "api/declarative_content/content_predicate_evaluator.cc", + "api/declarative_content/content_predicate_evaluator.h", + "api/declarative_content/declarative_content_css_condition_tracker.cc", + "api/declarative_content/declarative_content_css_condition_tracker.h", + "api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc", + "api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h", + "api/declarative_content/declarative_content_page_url_condition_tracker.cc", + "api/declarative_content/declarative_content_page_url_condition_tracker.h", + "api/declarative_content/default_content_predicate_evaluators.cc", + "api/declarative_content/default_content_predicate_evaluators.h", + "api/desktop_capture/desktop_capture_api.cc", + "api/desktop_capture/desktop_capture_api.h", + "api/desktop_capture/desktop_capture_base.cc", + "api/desktop_capture/desktop_capture_base.h", + "api/developer_private/developer_private_api.cc", + "api/developer_private/developer_private_api.h", + "api/developer_private/developer_private_mangle.cc", + "api/developer_private/developer_private_mangle.h", + "api/developer_private/entry_picker.cc", + "api/developer_private/entry_picker.h", + "api/developer_private/extension_info_generator.cc", + "api/developer_private/extension_info_generator.h", + "api/developer_private/inspectable_views_finder.cc", + "api/developer_private/inspectable_views_finder.h", + "api/developer_private/show_permissions_dialog_helper.cc", + "api/developer_private/show_permissions_dialog_helper.h", + "api/dial/dial_api.cc", + "api/dial/dial_api.h", + "api/dial/dial_api_factory.cc", + "api/dial/dial_api_factory.h", + "api/dial/dial_device_data.cc", + "api/dial/dial_device_data.h", + "api/dial/dial_registry.cc", + "api/dial/dial_registry.h", + "api/dial/dial_service.cc", + "api/dial/dial_service.h", + "api/downloads/downloads_api.cc", + "api/downloads/downloads_api.h", + "api/downloads_internal/downloads_internal_api.cc", + "api/downloads_internal/downloads_internal_api.h", + "api/easy_unlock_private/easy_unlock_private_api.cc", + "api/easy_unlock_private/easy_unlock_private_api.h", + "api/easy_unlock_private/easy_unlock_private_connection.cc", + "api/easy_unlock_private/easy_unlock_private_connection.h", + "api/easy_unlock_private/easy_unlock_private_connection_manager.cc", + "api/easy_unlock_private/easy_unlock_private_connection_manager.h", + "api/easy_unlock_private/easy_unlock_private_crypto_delegate.h", + "api/easy_unlock_private/easy_unlock_private_crypto_delegate_chromeos.cc", + "api/experience_sampling_private/experience_sampling.cc", + "api/experience_sampling_private/experience_sampling.h", + "api/experience_sampling_private/experience_sampling_private_api.cc", + "api/experience_sampling_private/experience_sampling_private_api.h", + "api/extension_action/extension_action_api.cc", + "api/extension_action/extension_action_api.h", + "api/extension_action/extension_page_actions_api_constants.cc", + "api/extension_action/extension_page_actions_api_constants.h", + "api/feedback_private/feedback_private_api.cc", + "api/feedback_private/feedback_private_api.h", + "api/feedback_private/feedback_service.cc", + "api/feedback_private/feedback_service.h", + "api/file_handlers/app_file_handler_util.cc", + "api/file_handlers/app_file_handler_util.h", + "api/file_handlers/directory_util.cc", + "api/file_handlers/directory_util.h", + "api/file_handlers/mime_util.cc", + "api/file_handlers/mime_util.h", + "api/file_system/file_system_api.cc", + "api/file_system/file_system_api.h", + "api/font_settings/font_settings_api.cc", + "api/font_settings/font_settings_api.h", + "api/gcm/gcm_api.cc", + "api/gcm/gcm_api.h", + "api/history/history_api.cc", + "api/history/history_api.h", + "api/hotword_private/hotword_private_api.cc", + "api/hotword_private/hotword_private_api.h", + "api/i18n/i18n_api.cc", + "api/i18n/i18n_api.h", + "api/identity/extension_token_key.cc", + "api/identity/extension_token_key.h", + "api/identity/gaia_web_auth_flow.cc", + "api/identity/gaia_web_auth_flow.h", + "api/identity/identity_api.cc", + "api/identity/identity_api.h", + "api/identity/identity_mint_queue.cc", + "api/identity/identity_mint_queue.h", + "api/identity/identity_signin_flow.cc", + "api/identity/identity_signin_flow.h", + "api/identity/web_auth_flow.cc", + "api/identity/web_auth_flow.h", + "api/idltest/idltest_api.cc", + "api/idltest/idltest_api.h", + "api/image_writer_private/destroy_partitions_operation.cc", + "api/image_writer_private/destroy_partitions_operation.h", + "api/image_writer_private/error_messages.cc", + "api/image_writer_private/error_messages.h", + "api/image_writer_private/image_writer_private_api.cc", + "api/image_writer_private/image_writer_private_api.h", + "api/image_writer_private/image_writer_utility_client.cc", + "api/image_writer_private/image_writer_utility_client.h", + "api/image_writer_private/operation.cc", + "api/image_writer_private/operation.h", + "api/image_writer_private/operation_chromeos.cc", + "api/image_writer_private/operation_manager.cc", + "api/image_writer_private/operation_manager.h", + "api/image_writer_private/removable_storage_provider.cc", + "api/image_writer_private/removable_storage_provider.h", + "api/image_writer_private/removable_storage_provider_chromeos.cc", + "api/image_writer_private/removable_storage_provider_mac.cc", + "api/image_writer_private/removable_storage_provider_win.cc", + "api/image_writer_private/write_from_file_operation.cc", + "api/image_writer_private/write_from_file_operation.h", + "api/image_writer_private/write_from_url_operation.cc", + "api/image_writer_private/write_from_url_operation.h", + "api/inline_install_private/inline_install_private_api.cc", + "api/inline_install_private/inline_install_private_api.h", + "api/instance_id/instance_id_api.cc", + "api/instance_id/instance_id_api.h", + "api/language_settings_private/language_settings_private_api.cc", + "api/language_settings_private/language_settings_private_api.h", + "api/language_settings_private/language_settings_private_delegate.cc", + "api/language_settings_private/language_settings_private_delegate.h", + "api/language_settings_private/language_settings_private_delegate_factory.cc", + "api/language_settings_private/language_settings_private_delegate_factory.h", + "api/management/chrome_management_api_delegate.cc", + "api/management/chrome_management_api_delegate.h", + "api/media_galleries/media_galleries_api.cc", + "api/media_galleries/media_galleries_api.h", + "api/messaging/extension_message_port.cc", + "api/messaging/extension_message_port.h", + "api/messaging/incognito_connectability.cc", + "api/messaging/incognito_connectability.h", + "api/messaging/message_property_provider.cc", + "api/messaging/message_property_provider.h", + "api/messaging/message_service.cc", + "api/messaging/message_service.h", + "api/messaging/native_message_port.cc", + "api/messaging/native_message_port.h", + "api/messaging/native_messaging_host_manifest.cc", + "api/messaging/native_messaging_host_manifest.h", + "api/messaging/native_messaging_policy_handler.cc", + "api/messaging/native_messaging_policy_handler.h", + "api/metrics_private/chrome_metrics_private_delegate.cc", + "api/metrics_private/chrome_metrics_private_delegate.h", + "api/metrics_private/metrics_private_api.cc", + "api/metrics_private/metrics_private_api.h", + "api/module/module.cc", + "api/module/module.h", + "api/music_manager_private/device_id.cc", + "api/music_manager_private/device_id.h", + "api/music_manager_private/device_id_chromeos.cc", + "api/music_manager_private/device_id_linux.cc", + "api/music_manager_private/device_id_mac.cc", + "api/music_manager_private/device_id_win.cc", + "api/music_manager_private/music_manager_private_api.cc", + "api/music_manager_private/music_manager_private_api.h", + "api/networking_private/networking_private_credentials_getter_chromeos.cc", + "api/networking_private/networking_private_ui_delegate_chromeos.cc", + "api/networking_private/networking_private_ui_delegate_chromeos.h", + "api/networking_private/networking_private_ui_delegate_factory_impl.cc", + "api/networking_private/networking_private_ui_delegate_factory_impl.h", + "api/networking_private/networking_private_verify_delegate_factory_impl.cc", + "api/networking_private/networking_private_verify_delegate_factory_impl.h", + "api/notification_provider/notification_provider_api.cc", + "api/notification_provider/notification_provider_api.h", + "api/notifications/notifications_api.cc", + "api/notifications/notifications_api.h", + "api/omnibox/omnibox_api.cc", + "api/omnibox/omnibox_api.h", + "api/page_capture/page_capture_api.cc", + "api/page_capture/page_capture_api.h", + "api/passwords_private/passwords_private_api.cc", + "api/passwords_private/passwords_private_api.h", + "api/passwords_private/passwords_private_delegate.h", + "api/passwords_private/passwords_private_delegate_factory.cc", + "api/passwords_private/passwords_private_delegate_factory.h", + "api/passwords_private/passwords_private_delegate_impl.cc", + "api/passwords_private/passwords_private_delegate_impl.h", + "api/passwords_private/passwords_private_event_router.cc", + "api/passwords_private/passwords_private_event_router.h", + "api/passwords_private/passwords_private_event_router_factory.cc", + "api/passwords_private/passwords_private_event_router_factory.h", + "api/permissions/permissions_api.cc", + "api/permissions/permissions_api.h", + "api/permissions/permissions_api_helpers.cc", + "api/permissions/permissions_api_helpers.h", + "api/preference/chrome_direct_setting.cc", + "api/preference/chrome_direct_setting.h", + "api/preference/chrome_direct_setting_api.cc", + "api/preference/chrome_direct_setting_api.h", + "api/preference/preference_api.cc", + "api/preference/preference_api.h", + "api/preference/preference_api_constants.cc", + "api/preference/preference_api_constants.h", + "api/preference/preference_helpers.cc", + "api/preference/preference_helpers.h", + "api/proxy/proxy_api.cc", + "api/proxy/proxy_api.h", + "api/proxy/proxy_api_constants.cc", + "api/proxy/proxy_api_constants.h", + "api/proxy/proxy_api_helpers.cc", + "api/proxy/proxy_api_helpers.h", + "api/resources_private/resources_private_api.cc", + "api/resources_private/resources_private_api.h", + "api/runtime/chrome_runtime_api_delegate.cc", + "api/runtime/chrome_runtime_api_delegate.h", + "api/screenlock_private/screenlock_private_api.cc", + "api/screenlock_private/screenlock_private_api.h", + "api/sessions/session_id.cc", + "api/sessions/session_id.h", + "api/sessions/sessions_api.cc", + "api/sessions/sessions_api.h", + "api/settings_overrides/settings_overrides_api.cc", + "api/settings_overrides/settings_overrides_api.h", + "api/settings_private/prefs_util.cc", + "api/settings_private/prefs_util.h", + "api/settings_private/settings_private_api.cc", + "api/settings_private/settings_private_api.h", + "api/settings_private/settings_private_delegate.cc", + "api/settings_private/settings_private_delegate.h", + "api/settings_private/settings_private_delegate_factory.cc", + "api/settings_private/settings_private_delegate_factory.h", + "api/settings_private/settings_private_event_router.cc", + "api/settings_private/settings_private_event_router.h", + "api/settings_private/settings_private_event_router_factory.cc", + "api/settings_private/settings_private_event_router_factory.h", + "api/signed_in_devices/id_mapping_helper.cc", + "api/signed_in_devices/id_mapping_helper.h", + "api/signed_in_devices/signed_in_devices_api.cc", + "api/signed_in_devices/signed_in_devices_api.h", + "api/signed_in_devices/signed_in_devices_manager.cc", + "api/signed_in_devices/signed_in_devices_manager.h", + "api/spellcheck/spellcheck_api.cc", + "api/spellcheck/spellcheck_api.h", + "api/storage/managed_value_store_cache.cc", + "api/storage/managed_value_store_cache.h", + "api/storage/policy_value_store.cc", + "api/storage/policy_value_store.h", + "api/storage/setting_sync_data.cc", + "api/storage/setting_sync_data.h", + "api/storage/settings_sync_processor.cc", + "api/storage/settings_sync_processor.h", + "api/storage/settings_sync_util.cc", + "api/storage/settings_sync_util.h", + "api/storage/sync_storage_backend.cc", + "api/storage/sync_storage_backend.h", + "api/storage/sync_value_store_cache.cc", + "api/storage/sync_value_store_cache.h", + "api/storage/syncable_settings_storage.cc", + "api/storage/syncable_settings_storage.h", + "api/streams_private/streams_private_api.cc", + "api/streams_private/streams_private_api.h", + "api/sync_file_system/extension_sync_event_observer.cc", + "api/sync_file_system/extension_sync_event_observer.h", + "api/sync_file_system/sync_file_system_api.cc", + "api/sync_file_system/sync_file_system_api.h", + "api/sync_file_system/sync_file_system_api_helpers.cc", + "api/sync_file_system/sync_file_system_api_helpers.h", + "api/system_indicator/system_indicator_api.h", + "api/system_indicator/system_indicator_manager.cc", + "api/system_indicator/system_indicator_manager.h", + "api/system_indicator/system_indicator_manager_factory.cc", + "api/system_indicator/system_indicator_manager_factory.h", + "api/system_private/system_private_api.cc", + "api/system_private/system_private_api.h", + "api/tab_capture/offscreen_tab.cc", + "api/tab_capture/offscreen_tab.h", + "api/tab_capture/tab_capture_api.cc", + "api/tab_capture/tab_capture_api.h", + "api/tab_capture/tab_capture_registry.cc", + "api/tab_capture/tab_capture_registry.h", + "api/tabs/app_base_window.cc", + "api/tabs/app_base_window.h", + "api/tabs/app_window_controller.cc", + "api/tabs/app_window_controller.h", + "api/tabs/tabs_api.cc", + "api/tabs/tabs_api.h", + "api/tabs/tabs_constants.cc", + "api/tabs/tabs_constants.h", + "api/tabs/tabs_event_router.cc", + "api/tabs/tabs_event_router.h", + "api/tabs/tabs_windows_api.cc", + "api/tabs/tabs_windows_api.h", + "api/tabs/windows_event_router.cc", + "api/tabs/windows_event_router.h", + "api/tabs/windows_util.cc", + "api/tabs/windows_util.h", + "api/top_sites/top_sites_api.cc", + "api/top_sites/top_sites_api.h", + "api/web_navigation/frame_navigation_state.cc", + "api/web_navigation/frame_navigation_state.h", + "api/web_navigation/web_navigation_api.cc", + "api/web_navigation/web_navigation_api.h", + "api/web_navigation/web_navigation_api_constants.cc", + "api/web_navigation/web_navigation_api_constants.h", + "api/web_navigation/web_navigation_api_helpers.cc", + "api/web_navigation/web_navigation_api_helpers.h", + "api/web_request/chrome_extension_web_request_event_router_delegate.cc", + "api/web_request/chrome_extension_web_request_event_router_delegate.h", + "api/web_view/chrome_web_view_internal_api.cc", + "api/web_view/chrome_web_view_internal_api.h", + "api/webrtc_audio_private/webrtc_audio_private_api.cc", + "api/webrtc_audio_private/webrtc_audio_private_api.h", + "api/webrtc_desktop_capture_private/webrtc_desktop_capture_private_api.cc", + "api/webrtc_desktop_capture_private/webrtc_desktop_capture_private_api.h", + "api/webrtc_logging_private/webrtc_logging_private_api.h", + "api/webstore_private/webstore_private_api.cc", + "api/webstore_private/webstore_private_api.h", + "app_data_migrator.cc", + "app_data_migrator.h", + "blacklist.cc", + "blacklist.h", + "blacklist_factory.cc", + "blacklist_factory.h", + "blacklist_state_fetcher.cc", + "blacklist_state_fetcher.h", + "blob_reader.cc", + "blob_reader.h", + "bookmark_app_helper.cc", + "bookmark_app_helper.h", + "browser_action_test_util.h", + "browser_context_keyed_service_factories.cc", + "browser_context_keyed_service_factories.h", + "browser_extension_window_controller.cc", + "browser_extension_window_controller.h", + "chrome_app_sorting.cc", + "chrome_app_sorting.h", + "chrome_component_extension_resource_manager.cc", + "chrome_component_extension_resource_manager.h", + "chrome_content_browser_client_extensions_part.cc", + "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_chooser_dialog.h", + "chrome_extension_function.cc", + "chrome_extension_function.h", + "chrome_extension_function_details.cc", + "chrome_extension_function_details.h", + "chrome_extension_host_delegate.cc", + "chrome_extension_host_delegate.h", + "chrome_extension_web_contents_observer.cc", + "chrome_extension_web_contents_observer.h", + "chrome_extensions_browser_client.cc", + "chrome_extensions_browser_client.h", + "chrome_kiosk_delegate.h", + "chrome_kiosk_delegate_chromeos.cc", + "chrome_mojo_service_registration.cc", + "chrome_mojo_service_registration.h", + "chrome_process_manager_delegate.cc", + "chrome_process_manager_delegate.h", + "chrome_requirements_checker.cc", + "chrome_requirements_checker.h", + "chrome_url_request_util.cc", + "chrome_url_request_util.h", + "component_extensions_whitelist/whitelist.cc", + "component_extensions_whitelist/whitelist.h", + "component_loader.cc", + "component_loader.h", + "component_migration_helper.cc", + "component_migration_helper.h", + "context_menu_matcher.cc", + "context_menu_matcher.h", + "convert_user_script.cc", + "convert_user_script.h", + "convert_web_app.cc", + "convert_web_app.h", + "crx_installer.cc", + "crx_installer.h", + "data_deleter.cc", + "data_deleter.h", + "dev_mode_bubble_delegate.cc", + "dev_mode_bubble_delegate.h", + "devtools_util.cc", + "devtools_util.h", + "display_info_provider_chromeos.cc", + "display_info_provider_chromeos.h", + "display_info_provider_mac.cc", + "display_info_provider_mac.h", + "display_info_provider_win.cc", + "display_info_provider_win.h", + "error_console/error_console.cc", + "error_console/error_console.h", + "error_console/error_console_factory.cc", + "error_console/error_console_factory.h", + "event_router_forwarder.cc", + "event_router_forwarder.h", + "extension_action.cc", + "extension_action.h", + "extension_action_icon_factory.cc", + "extension_action_icon_factory.h", + "extension_action_manager.cc", + "extension_action_manager.h", + "extension_action_runner.cc", + "extension_action_runner.h", + "extension_action_storage_manager.cc", + "extension_action_storage_manager.h", + "extension_app_icon_loader.cc", + "extension_app_icon_loader.h", + "extension_assets_manager.cc", + "extension_assets_manager.h", + "extension_assets_manager_chromeos.cc", + "extension_assets_manager_chromeos.h", + "extension_commands_global_registry.cc", + "extension_commands_global_registry.h", + "extension_context_menu_model.cc", + "extension_context_menu_model.h", + "extension_cookie_monster_delegate.cc", + "extension_cookie_monster_delegate.h", + "extension_creator.cc", + "extension_creator.h", + "extension_creator_filter.cc", + "extension_creator_filter.h", + "extension_disabled_ui.cc", + "extension_disabled_ui.h", + "extension_error_controller.cc", + "extension_error_controller.h", + "extension_error_reporter.cc", + "extension_error_reporter.h", + "extension_error_ui.cc", + "extension_error_ui.h", + "extension_error_ui_default.cc", + "extension_error_ui_default.h", + "extension_garbage_collector.cc", + "extension_garbage_collector.h", + "extension_garbage_collector_chromeos.cc", + "extension_garbage_collector_chromeos.h", + "extension_garbage_collector_factory.cc", + "extension_garbage_collector_factory.h", + "extension_gcm_app_handler.cc", + "extension_gcm_app_handler.h", + "extension_icon_manager.cc", + "extension_icon_manager.h", + "extension_install_checker.cc", + "extension_install_checker.h", + "extension_install_error_menu_item_id_provider.cc", + "extension_install_error_menu_item_id_provider.h", + "extension_install_prompt.cc", + "extension_install_prompt.h", + "extension_install_prompt_show_params.cc", + "extension_install_prompt_show_params.h", + "extension_install_ui_util.cc", + "extension_install_ui_util.h", + "extension_keybinding_registry.cc", + "extension_keybinding_registry.h", + "extension_management.cc", + "extension_management.h", + "extension_management_constants.cc", + "extension_management_constants.h", + "extension_management_internal.cc", + "extension_management_internal.h", + "extension_message_bubble_controller.cc", + "extension_message_bubble_controller.h", + "extension_migrator.cc", + "extension_migrator.h", + "extension_reenabler.cc", + "extension_reenabler.h", + "extension_resource_protocols.cc", + "extension_resource_protocols.h", + "extension_service.cc", + "extension_service.h", + "extension_special_storage_policy.cc", + "extension_special_storage_policy.h", + "extension_storage_monitor.cc", + "extension_storage_monitor.h", + "extension_storage_monitor_factory.cc", + "extension_storage_monitor_factory.h", + "extension_sync_data.cc", + "extension_sync_data.h", + "extension_sync_service.cc", + "extension_sync_service.h", + "extension_sync_service_factory.cc", + "extension_sync_service_factory.h", + "extension_system_factory.cc", + "extension_system_factory.h", + "extension_system_impl.cc", + "extension_system_impl.h", + "extension_tab_util.cc", + "extension_tab_util.h", + "extension_ui_util.cc", + "extension_ui_util.h", + "extension_uninstall_dialog.cc", + "extension_uninstall_dialog.h", + "extension_util.cc", + "extension_util.h", + "extension_view_host.cc", + "extension_view_host.h", + "extension_view_host_factory.cc", + "extension_view_host_factory.h", + "extension_web_ui.cc", + "extension_web_ui.h", + "extension_web_ui_override_registrar.cc", + "extension_web_ui_override_registrar.h", + "extension_webkit_preferences.cc", + "extension_webkit_preferences.h", + "external_component_loader.cc", + "external_component_loader.h", + "external_install_error.cc", + "external_install_error.h", + "external_install_manager.cc", + "external_install_manager.h", + "external_loader.cc", + "external_loader.h", + "external_policy_loader.cc", + "external_policy_loader.h", + "external_pref_loader.cc", + "external_pref_loader.h", + "external_provider_impl.cc", + "external_provider_impl.h", + "external_registry_loader_win.cc", + "external_registry_loader_win.h", + "favicon_downloader.cc", + "favicon_downloader.h", + "global_shortcut_listener.cc", + "global_shortcut_listener.h", + "global_shortcut_listener_chromeos.cc", + "global_shortcut_listener_chromeos.h", + "global_shortcut_listener_mac.h", + "global_shortcut_listener_mac.mm", + "global_shortcut_listener_ozone.cc", + "global_shortcut_listener_ozone.h", + "global_shortcut_listener_win.cc", + "global_shortcut_listener_win.h", + "global_shortcut_listener_x11.cc", + "global_shortcut_listener_x11.h", + "install_gate.h", + "install_observer.cc", + "install_observer.h", + "install_signer.cc", + "install_signer.h", + "install_tracker.cc", + "install_tracker.h", + "install_tracker_factory.cc", + "install_tracker_factory.h", + "install_verifier.cc", + "install_verifier.h", + "install_verifier_factory.cc", + "install_verifier_factory.h", + "installed_loader.cc", + "installed_loader.h", + "launch_util.cc", + "launch_util.h", + "location_bar_controller.cc", + "location_bar_controller.h", + "menu_manager.cc", + "menu_manager.h", + "menu_manager_factory.cc", + "menu_manager_factory.h", + "navigation_observer.cc", + "navigation_observer.h", + "ntp_overridden_bubble_delegate.cc", + "ntp_overridden_bubble_delegate.h", + "pack_extension_job.cc", + "pack_extension_job.h", + "path_util.cc", + "path_util.h", + "pending_extension_info.cc", + "pending_extension_info.h", + "pending_extension_manager.cc", + "pending_extension_manager.h", + "permissions_based_management_policy_provider.cc", + "permissions_based_management_policy_provider.h", + "permissions_updater.cc", + "permissions_updater.h", + "plugin_manager.cc", + "plugin_manager.h", + "policy_handlers.cc", + "policy_handlers.h", + "proxy_overridden_bubble_delegate.cc", + "proxy_overridden_bubble_delegate.h", + "scripting_permissions_modifier.cc", + "scripting_permissions_modifier.h", + "settings_api_bubble_delegate.cc", + "settings_api_bubble_delegate.h", + "settings_api_helpers.cc", + "settings_api_helpers.h", + "shared_module_service.cc", + "shared_module_service.h", + "shared_user_script_master.cc", + "shared_user_script_master.h", + "signin/gaia_auth_extension_loader.cc", + "signin/gaia_auth_extension_loader.h", + "signin/scoped_gaia_auth_extension.cc", + "signin/scoped_gaia_auth_extension.h", + "standard_management_policy_provider.cc", + "standard_management_policy_provider.h", + "startup_helper.cc", + "startup_helper.h", + "state_store_notification_observer.cc", + "state_store_notification_observer.h", + "suspicious_extension_bubble_delegate.cc", + "suspicious_extension_bubble_delegate.h", + "sync_bundle.cc", + "sync_bundle.h", + "tab_helper.cc", + "tab_helper.h", + "theme_installed_infobar_delegate.cc", + "theme_installed_infobar_delegate.h", + "token_cache/token_cache_service.cc", + "token_cache/token_cache_service.h", + "token_cache/token_cache_service_factory.cc", + "token_cache/token_cache_service_factory.h", + "unpacked_installer.cc", + "unpacked_installer.h", + "update_install_gate.cc", + "update_install_gate.h", + "updater/chrome_extension_downloader_factory.cc", + "updater/chrome_extension_downloader_factory.h", + "updater/chrome_update_client_config.cc", + "updater/chrome_update_client_config.h", + "updater/extension_updater.cc", + "updater/extension_updater.h", + "user_script_listener.cc", + "user_script_listener.h", + "warning_badge_service.cc", + "warning_badge_service.h", + "warning_badge_service_factory.cc", + "warning_badge_service_factory.h", + "webstore_data_fetcher.cc", + "webstore_data_fetcher.h", + "webstore_data_fetcher_delegate.cc", + "webstore_data_fetcher_delegate.h", + "webstore_inline_installer.cc", + "webstore_inline_installer.h", + "webstore_inline_installer_factory.cc", + "webstore_inline_installer_factory.h", + "webstore_install_helper.cc", + "webstore_install_helper.h", + "webstore_install_with_prompt.cc", + "webstore_install_with_prompt.h", + "webstore_installer.cc", + "webstore_installer.h", + "webstore_reinstaller.cc", + "webstore_reinstaller.h", + "webstore_standalone_installer.cc", + "webstore_standalone_installer.h", + "webstore_startup_installer.cc", + "webstore_startup_installer.h", + "window_controller.cc", + "window_controller.h", + "window_controller_list.cc", + "window_controller_list.h", + "window_controller_list_observer.h", + "zipfile_installer.cc", + "zipfile_installer.h", + ] configs += [ "//build/config:precompiled_headers", @@ -33,29 +808,76 @@ static_library("extensions") { # browser, then we can clean up these dependencies. public_deps = [ "//chrome/common/extensions/api", + "//components/safe_browsing_db:util", "//content/public/browser", ] deps = [ "//chrome:extra_resources", "//chrome:resources", "//chrome:strings", + "//chrome/app:command_ids", "//chrome/app/resources:platform_locale_settings", + "//chrome/app/theme:chrome_unscaled_resources", "//chrome/app/theme:theme_resources", "//chrome/browser/devtools", + "//chrome/browser/media/router", "//chrome/common", "//chrome/common/extensions/api:api_registration", + "//chrome/common/extensions/api:extensions_features", "//chrome/common/safe_browsing:proto", "//chrome/installer/util:with_no_strings", - "//components/copresence", - "//components/data_reduction_proxy/proto:data_reduction_proxy_proto", + "//components/app_modal", + "//components/autofill/content/browser", + "//components/bookmarks/browser", + "//components/bookmarks/managed", + "//components/browser_sync", + "//components/browsing_data/core", + "//components/bubble", + "//components/content_settings/core/browser", + "//components/crx_file", + "//components/data_reduction_proxy/core/browser", "//components/dom_distiller/core", + "//components/favicon/content", + "//components/feedback", + "//components/gcm_driver", + "//components/guest_view/browser", + "//components/history/core/browser", + "//components/infobars/core", + "//components/keyed_service/content", + "//components/navigation_interception", + "//components/net_log", + "//components/omnibox/browser", "//components/onc", - "//components/policy", + "//components/password_manager/core/browser", + "//components/pdf/browser", + "//components/policy:generated", + "//components/policy/core/browser", + "//components/pref_registry", "//components/proximity_auth", + "//components/proximity_auth/ble", + "//components/proximity_auth/cryptauth", + "//components/proximity_auth/logging", + "//components/proxy_config", + "//components/rappor", "//components/resources", + "//components/safe_browsing_db:database_manager", + "//components/safe_json", + "//components/search_engines", + "//components/sessions", + "//components/signin/core/browser", + "//components/spellcheck/browser", + "//components/storage_monitor", "//components/strings", + "//components/sync", + "//components/sync_sessions", + "//components/syncable_prefs", + "//components/translate/core/browser", + "//components/undo", "//components/update_client", "//components/url_matcher", + "//components/user_prefs", + "//components/web_modal", + "//components/zoom", "//content/app/resources", "//content/public/common", "//crypto", @@ -68,9 +890,9 @@ static_library("extensions") { "//extensions/strings", "//net", "//skia", + "//sql", "//storage/browser", "//storage/common", - "//sync", "//third_party/WebKit/public:image_resources", "//third_party/WebKit/public:resources", "//third_party/cacheinvalidation", @@ -84,67 +906,121 @@ static_library("extensions") { "//ui/base/ime", "//ui/gfx", "//ui/gfx/geometry", + "//ui/native_theme", "//ui/resources", + "//ui/shell_dialogs", "//ui/strings", "//url", ] - if (enable_task_manager) { - sources += rebase_path( - gypi_values.chrome_browser_extensions_task_manager_enabled_sources, - ".", - "//chrome") + if (!is_chromeos) { + sources += [ "chrome_kiosk_delegate.cc" ] } if (is_chromeos) { - sources += - rebase_path(gypi_values.chrome_browser_extensions_chromeos_sources, - ".", - "//chrome") + sources += [ + "api/cast_devices_private/cast_devices_private_api.cc", + "api/cast_devices_private/cast_devices_private_api.h", + "api/certificate_provider/certificate_provider_api.cc", + "api/certificate_provider/certificate_provider_api.h", + "api/enterprise_device_attributes/enterprise_device_attributes_api.cc", + "api/enterprise_device_attributes/enterprise_device_attributes_api.h", + "api/enterprise_platform_keys/enterprise_platform_keys_api.cc", + "api/enterprise_platform_keys/enterprise_platform_keys_api.h", + "api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc", + "api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h", + "api/file_system/request_file_system_dialog_view.cc", + "api/file_system/request_file_system_dialog_view.h", + "api/file_system/request_file_system_notification.cc", + "api/file_system/request_file_system_notification.h", + "api/input_ime/input_ime_api.cc", + "api/input_ime/input_ime_api.h", + "api/input_ime/input_ime_api_chromeos.cc", + "api/input_ime/input_ime_api_chromeos.h", + "api/input_ime/input_ime_event_router_base.cc", + "api/input_ime/input_ime_event_router_base.h", + "api/log_private/filter_handler.cc", + "api/log_private/filter_handler.h", + "api/log_private/log_parser.cc", + "api/log_private/log_parser.h", + "api/log_private/log_private_api.h", + "api/log_private/log_private_api_chromeos.cc", + "api/log_private/syslog_parser.cc", + "api/log_private/syslog_parser.h", + "api/messaging/native_message_host_chromeos.cc", + "api/networking_private/crypto_verify_impl.cc", + "api/networking_private/crypto_verify_impl.h", + "api/platform_keys/platform_keys_api.cc", + "api/platform_keys/platform_keys_api.h", + "api/platform_keys/verify_trust_api.cc", + "api/platform_keys/verify_trust_api.h", + "api/terminal/terminal_extension_helper.cc", + "api/terminal/terminal_extension_helper.h", + "api/terminal/terminal_private_api.cc", + "api/terminal/terminal_private_api.h", + "api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc", + "api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h", + "api/vpn_provider/vpn_service_factory.cc", + "api/webstore_widget_private/app_installer.cc", + "api/webstore_widget_private/app_installer.h", + "api/webstore_widget_private/webstore_widget_private_api.cc", + "api/webstore_widget_private/webstore_widget_private_api.h", + "updater/chromeos_extension_cache_delegate.cc", + "updater/chromeos_extension_cache_delegate.h", + "updater/extension_cache_delegate.cc", + "updater/extension_cache_delegate.h", + "updater/extension_cache_impl.cc", + "updater/extension_cache_impl.h", + "updater/local_extension_cache.cc", + "updater/local_extension_cache.h", + ] + sources -= [ "api/music_manager_private/device_id_linux.cc" ] if (use_dbus) { configs += [ "//build/config/linux/dbus" ] } deps += [ "//components/chrome_apps", + "//components/constrained_window", + "//components/drive", + "//components/user_manager", + "//remoting/host", "//remoting/host/it2me:common", "//third_party/protobuf:protobuf_lite", + "//ui/app_list", + "//ui/chromeos", + "//ui/file_manager", + "//ui/views/", ] } else { sources += [ + "api/easy_unlock_private/easy_unlock_private_crypto_delegate_stub.cc", + "api/image_writer_private/operation_nonchromeos.cc", + "api/image_writer_private/removable_storage_provider_linux.cc", + "api/messaging/native_message_process_host.cc", + "api/messaging/native_message_process_host.h", + "api/messaging/native_process_launcher.cc", + "api/messaging/native_process_launcher.h", + "api/messaging/native_process_launcher_posix.cc", + "api/messaging/native_process_launcher_win.cc", "default_apps.cc", - "default_apps.h'", + "default_apps.h", ] - sources += - rebase_path(gypi_values.chrome_browser_extensions_non_chromeos_sources, - ".", - "//chrome") - } - - if (enable_service_discovery) { - sources += rebase_path( - gypi_values.chrome_browser_extensions_service_discovery_sources, - ".", - "//chrome") } - if (use_ash) { - sources += [ - "api/tabs/ash_panel_contents.cc", - "api/tabs/ash_panel_contents.h", + # chromeos uses its own global_shortcut_listener, _x11 is not necessary. + if (is_chromeos || !use_x11) { + sources -= [ + "global_shortcut_listener_x11.cc", + "global_shortcut_listener_x11.h", ] } - if (use_aura) { - deps += [ - "//ui/keyboard", - "//ui/keyboard:keyboard_with_content", - "//ui/keyboard:resources", - ] + if (is_chromeos && use_ozone) { + sources -= [ "global_shortcut_listener_chromeos.cc" ] } - - if (toolkit_views) { - deps += [ "//ui/views" ] + if (!use_ozone) { + sources -= [ "global_shortcut_listener_ozone.cc" ] } if (is_linux) { @@ -153,6 +1029,9 @@ static_library("extensions") { if (use_dbus) { deps += [ "//dbus" ] } + if (use_udev) { + deps += [ "//device/udev_linux" ] + } if (use_x11) { configs += [ "//build/config/linux:x11" ] @@ -162,44 +1041,22 @@ static_library("extensions") { "//ui/events/platform/x11", ] } - if (!is_chromeos) { - sources += rebase_path( - gypi_values.chrome_browser_extensions_input_ime_linux_win_sources, - ".", - "//chrome") - } } - if (enable_webrtc) { - sources += [ "api/webrtc_logging_private/webrtc_logging_private_api.cc" ] - } else { - sources += - [ "api/webrtc_logging_private/webrtc_logging_private_api_stub.cc" ] - } - - if (use_brlapi) { - deps += [ "//build/linux/libbrlapi" ] - sources += rebase_path(gypi_values.chrome_browser_extensions_brlapi_sources, - ".", - "//chrome") - } else { - sources += [ "api/braille_display_private/braille_controller_stub.cc" ] - } - - # chromeos uses its own global_shortcut_listener, _x11 is not necessary. - if (is_chromeos || !use_x11) { - sources -= [ - "global_shortcut_listener_x11.cc", - "global_shortcut_listener_x11.h", - ] + if (!is_android && !is_ios) { + # Non-mobile. + #deps += [ "//apps" ] } if (is_win || is_mac) { + sources += [ + "api/networking_private/crypto_verify_impl.cc", + "api/networking_private/crypto_verify_impl.h", + "api/networking_private/networking_private_credentials_getter.h", + "api/networking_private/networking_private_credentials_getter_mac.cc", + "api/networking_private/networking_private_credentials_getter_win.cc", + ] deps += [ "//components/wifi" ] - sources += rebase_path( - gypi_values.chrome_browser_extensions_networking_private_sources_winmac, - ".", - "//chrome") } if (is_win) { @@ -207,10 +1064,6 @@ static_library("extensions") { "//third_party/iaccessible2", "//third_party/isimpledom", ] - sources += rebase_path( - gypi_values.chrome_browser_extensions_input_ime_linux_win_sources, - ".", - "//chrome") } else if (use_aura && !is_chromeos) { sources += [ "display_info_provider_aura.cc", @@ -218,17 +1071,107 @@ static_library("extensions") { ] } + if (is_win || (is_linux && !is_chromeos)) { + sources += [ + "api/input_ime/input_ime_api.cc", + "api/input_ime/input_ime_api.h", + "api/input_ime/input_ime_api_nonchromeos.cc", + "api/input_ime/input_ime_api_nonchromeos.h", + "api/input_ime/input_ime_event_router_base.cc", + "api/input_ime/input_ime_event_router_base.h", + ] + } + if (enable_app_list) { + sources += [ + # TODO These references to files in //chrome/browser/ should either be + # moved to the browser target or the files moved to this directory. + "../apps/drive/drive_app_converter.cc", + "../apps/drive/drive_app_converter.h", + "../apps/drive/drive_app_mapping.cc", + "../apps/drive/drive_app_mapping.h", + "../apps/drive/drive_app_provider.cc", + "../apps/drive/drive_app_provider.h", + "../apps/drive/drive_app_uninstall_sync_service.h", + "../apps/drive/drive_service_bridge.cc", + "../apps/drive/drive_service_bridge.h", + "api/launcher_page/launcher_page_api.cc", + "api/launcher_page/launcher_page_api.h", + ] + } + + if (enable_hotwording) { + defines += [ "ENABLE_HOTWORDING" ] + } + + if (enable_service_discovery) { + sources += [ + "api/gcd_private/gcd_private_api.cc", + "api/gcd_private/gcd_private_api.h", + "api/gcd_private/privet_v3_context_getter.cc", + "api/gcd_private/privet_v3_context_getter.h", + "api/gcd_private/privet_v3_session.cc", + "api/gcd_private/privet_v3_session.h", + "api/mdns/dns_sd_delegate.cc", + "api/mdns/dns_sd_delegate.h", + "api/mdns/dns_sd_device_lister.cc", + "api/mdns/dns_sd_device_lister.h", + "api/mdns/dns_sd_registry.cc", + "api/mdns/dns_sd_registry.h", + "api/mdns/mdns_api.cc", + "api/mdns/mdns_api.h", + ] + } + + if (enable_task_manager) { + sources += [ + "api/processes/processes_api.cc", + "api/processes/processes_api.h", + ] + } + + if (enable_rlz_support) { + deps += [ "//rlz:rlz_lib" ] + } + + if (enable_webrtc) { + sources += [ "api/webrtc_logging_private/webrtc_logging_private_api.cc" ] + } else { sources += - rebase_path(gypi_values.chrome_browser_extensions_app_list_sources, - ".", - "//chrome") + [ "api/webrtc_logging_private/webrtc_logging_private_api_stub.cc" ] } - if (is_chromeos && use_ozone) { - sources -= [ "global_shortcut_listener_chromeos.cc" ] + if (toolkit_views) { + deps += [ "//ui/views" ] } - if (!use_ozone) { - sources -= [ "global_shortcut_listener_ozone.cc" ] + + if (use_ash) { + sources += [ + "api/tabs/ash_panel_contents.cc", + "api/tabs/ash_panel_contents.h", + ] + deps += [ "//ash" ] + } + + if (use_aura) { + deps += [ + "//ui/aura", + "//ui/keyboard", + "//ui/keyboard:keyboard_with_content", + "//ui/keyboard:resources", + ] + } + + if (use_brlapi) { + sources += [ + "api/braille_display_private/braille_controller_brlapi.cc", + "api/braille_display_private/brlapi_connection.cc", + "api/braille_display_private/brlapi_connection.h", + "api/braille_display_private/brlapi_keycode_map.cc", + "api/braille_display_private/brlapi_keycode_map.h", + ] + deps += [ "//build/linux/libbrlapi" ] + } else { + sources += [ "api/braille_display_private/braille_controller_stub.cc" ] } } diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc index ed8cd7b117c..2da6ff04812 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc @@ -6,6 +6,8 @@ #include <stddef.h> #include <stdint.h> + +#include <memory> #include <utility> #include "base/lazy_instance.h" @@ -103,10 +105,9 @@ bool ActivityLogPrivateGetExtensionActivitiesFunction::RunAsync() { EXTENSION_FUNCTION_VALIDATE(params.get()); // Get the arguments in the right format. - std::unique_ptr<Filter> filter; - filter.reset(¶ms.release()->filter); + Filter filter = std::move(params->filter); Action::ActionType action_type = Action::ACTION_API_CALL; - switch (filter->activity_type) { + switch (filter.activity_type) { case activity_log_private::EXTENSION_ACTIVITY_FILTER_API_CALL: action_type = Action::ACTION_API_CALL; break; @@ -130,16 +131,13 @@ bool ActivityLogPrivateGetExtensionActivitiesFunction::RunAsync() { action_type = Action::ACTION_ANY; } std::string extension_id = - filter->extension_id.get() ? *filter->extension_id : std::string(); - std::string api_call = - filter->api_call.get() ? *filter->api_call : std::string(); - std::string page_url = - filter->page_url.get() ? *filter->page_url : std::string(); - std::string arg_url = - filter->arg_url.get() ? *filter->arg_url : std::string(); + filter.extension_id ? *filter.extension_id : std::string(); + std::string api_call = filter.api_call ? *filter.api_call : std::string(); + std::string page_url = filter.page_url ? *filter.page_url : std::string(); + std::string arg_url = filter.arg_url ? *filter.arg_url : std::string(); int days_ago = -1; - if (filter->days_ago.get()) - days_ago = *filter->days_ago; + if (filter.days_ago) + days_ago = *filter.days_ago; // Call the ActivityLog. ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile()); @@ -209,12 +207,9 @@ ExtensionFunction::ResponseAction ActivityLogPrivateDeleteUrlsFunction::Run() { // Put the arguments in the right format. std::vector<GURL> gurls; - std::vector<std::string> urls = *params->urls.get(); - for (std::vector<std::string>::iterator it = urls.begin(); - it != urls.end(); - ++it) { - gurls.push_back(GURL(*it)); - } + const std::vector<std::string>& urls = *params->urls; + for (const std::string& url : urls) + gurls.push_back(GURL(url)); ActivityLog* activity_log = ActivityLog::GetInstance(browser_context()); DCHECK(activity_log); diff --git a/chromium/chrome/browser/extensions/api/api_registration.gyp b/chromium/chrome/browser/extensions/api/api_registration.gyp deleted file mode 100644 index 0dc611fea80..00000000000 --- a/chromium/chrome/browser/extensions/api/api_registration.gyp +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'targets': [ - { - # GN version: //chrome/browser/extensions/api:api_registration - 'target_name': 'chrome_api_registration', - 'type': 'static_library', - # TODO(jschuh): http://crbug.com/167187 size_t -> int - 'msvs_disabled_warnings': [ 4267 ], - 'includes': [ - '../../../../build/json_schema_bundle_registration_compile.gypi', - '../../../common/extensions/api/schemas.gypi', - ], - 'dependencies': [ - '<(DEPTH)/chrome/common/extensions/api/api.gyp:chrome_api', - - # Different APIs include headers from these targets. - "<(DEPTH)/content/content.gyp:content_browser", - - # Different APIs include some headers from chrome/common that in turn - # include generated headers from these targets. - # TODO(brettw) this should be made unnecessary if possible. - '<(DEPTH)/components/components.gyp:component_metrics_proto', - '<(DEPTH)/components/components.gyp:copresence_proto', - '<(DEPTH)/skia/skia.gyp:skia', - '<(DEPTH)/sync/sync.gyp:sync', - '<(DEPTH)/ui/accessibility/accessibility.gyp:ax_gen', - ], - 'conditions': [ - ['chromeos==1', { - 'dependencies': [ - '<(DEPTH)/components/components.gyp:drive_proto', - ], - }], - ], - }, - ], -} diff --git a/chromium/chrome/browser/extensions/api/audio_modem/OWNERS b/chromium/chrome/browser/extensions/api/audio_modem/OWNERS deleted file mode 100644 index 9364bf79813..00000000000 --- a/chromium/chrome/browser/extensions/api/audio_modem/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -ckehoe@chromium.org -rkc@chromium.org diff --git a/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api.cc b/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api.cc deleted file mode 100644 index 65a90d59fe5..00000000000 --- a/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api.cc +++ /dev/null @@ -1,366 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/audio_modem/audio_modem_api.h" - -#include <stdint.h> - -#include <map> -#include <memory> -#include <string> -#include <utility> -#include <vector> - -#include "base/base64.h" -#include "base/bind.h" -#include "base/guid.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_util.h" -#include "base/timer/timer.h" -#include "chrome/browser/copresence/chrome_whispernet_client.h" -#include "chrome/common/extensions/api/audio_modem.h" -#include "extensions/browser/event_router.h" - -// TODO(ckehoe): Implement transmit fail checking. - -namespace extensions { - -using api::audio_modem::AUDIOBAND_AUDIBLE; -using api::audio_modem::AUDIOBAND_INAUDIBLE; -using api::audio_modem::Audioband; -using api::audio_modem::STATUS_CODERERROR; -using api::audio_modem::STATUS_INUSE; -using api::audio_modem::STATUS_INVALIDREQUEST; -using api::audio_modem::STATUS_SUCCESS; -using api::audio_modem::ReceivedToken; -using api::audio_modem::RequestParams; -using api::audio_modem::Status; - -namespace Transmit = api::audio_modem::Transmit; -namespace StopTransmit = api::audio_modem::StopTransmit; -namespace Receive = api::audio_modem::Receive; -namespace StopReceive = api::audio_modem::StopReceive; -namespace OnReceived = api::audio_modem::OnReceived; - -using audio_modem::AUDIBLE; -using audio_modem::AudioToken; -using audio_modem::AudioType; -using audio_modem::INAUDIBLE; -using audio_modem::TokenParameters; - -namespace { - -const char kInitFailedError[] = "The audio modem is not available. " - "Failed to initialize the token encoder/decoder."; -const char kInvalidTokenLengthError[] = - "The token length must be greater than zero."; -const char kIncorrectTokenLengthError[] = - "The token provided did not match the declared token length."; -const char kInvalidTimeoutError[] = - "Transmit and receive timeouts must be greater than zero."; - -const int kMaxTransmitTimeout = 10 * 60 * 1000; // 10 minutes -const int kMaxReceiveTimeout = 60 * 60 * 1000; // 1 hour - -base::LazyInstance<BrowserContextKeyedAPIFactory<AudioModemAPI>> - g_factory = LAZY_INSTANCE_INITIALIZER; - -AudioType AudioTypeForBand(Audioband band) { - switch (band) { - case AUDIOBAND_AUDIBLE: - return AUDIBLE; - case AUDIOBAND_INAUDIBLE: - return INAUDIBLE; - default: - NOTREACHED(); - return audio_modem::AUDIO_TYPE_UNKNOWN; - } -} - -TokenParameters TokenParamsForEncoding( - const api::audio_modem::TokenEncoding& encoding) { - return TokenParameters(encoding.token_length, - encoding.crc ? *encoding.crc : false, - encoding.parity ? *encoding.parity : true); -} - -const std::string DecodeBase64Token(std::string encoded_token) { - // Make sure the token is padded correctly. - while (encoded_token.size() % 4 > 0) - encoded_token += "="; - - // Decode and return the token. - std::string raw_token; - bool decode_success = base::Base64Decode(encoded_token, &raw_token); - DCHECK(decode_success); - return raw_token; -} - -} // namespace - - -// Public functions. - -AudioModemAPI::AudioModemAPI(content::BrowserContext* context) - : AudioModemAPI(context, - base::WrapUnique(new ChromeWhispernetClient(context)), - audio_modem::Modem::Create()) {} - -AudioModemAPI::AudioModemAPI( - content::BrowserContext* context, - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client, - std::unique_ptr<audio_modem::Modem> modem) - : browser_context_(context), - whispernet_client_(std::move(whispernet_client)), - modem_(std::move(modem)), - init_failed_(false) { - // We own these objects, so these callbacks will not outlive us. - whispernet_client_->Initialize( - base::Bind(&AudioModemAPI::WhispernetInitComplete, - base::Unretained(this))); - modem_->Initialize(whispernet_client_.get(), - base::Bind(&AudioModemAPI::TokensReceived, - base::Unretained(this))); -} - -AudioModemAPI::~AudioModemAPI() { - for (const auto& timer_entry : receive_timers_[0]) - delete timer_entry.second; - for (const auto& timer_entry : receive_timers_[1]) - delete timer_entry.second; -} - -Status AudioModemAPI::StartTransmit(const std::string& app_id, - const RequestParams& params, - const std::string& token) { - AudioType audio_type = AudioTypeForBand(params.band); - if (transmitters_[audio_type].empty()) - transmitters_[audio_type] = app_id; - else if (transmitters_[audio_type] != app_id) - return STATUS_INUSE; - - DVLOG(3) << "Starting transmit for app " << app_id; - - std::string encoded_token; - base::Base64Encode(token, &encoded_token); - base::RemoveChars(encoded_token, "=", &encoded_token); - - modem_->SetTokenParams(audio_type, TokenParamsForEncoding(params.encoding)); - modem_->SetToken(audio_type, encoded_token); - modem_->StartPlaying(audio_type); - - transmit_timers_[audio_type].Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(params.timeout_millis), - base::Bind(base::IgnoreResult(&AudioModemAPI::StopTransmit), - base::Unretained(this), - app_id, - audio_type)); - return STATUS_SUCCESS; -} - -Status AudioModemAPI::StopTransmit(const std::string& app_id, - AudioType audio_type) { - if (transmitters_[audio_type] != app_id) - return STATUS_INVALIDREQUEST; - - DVLOG(3) << "Stopping transmit for app " << app_id; - transmitters_[audio_type].clear(); - modem_->StopPlaying(audio_type); - return STATUS_SUCCESS; -} - -void AudioModemAPI::StartReceive(const std::string& app_id, - const RequestParams& params) { - DVLOG(3) << "Starting receive for app " << app_id; - - AudioType audio_type = AudioTypeForBand(params.band); - modem_->SetTokenParams(audio_type, TokenParamsForEncoding(params.encoding)); - modem_->StartRecording(audio_type); - - if (receive_timers_[audio_type].count(app_id) == 0) - receive_timers_[audio_type][app_id] = new base::OneShotTimer; - DCHECK(receive_timers_[audio_type][app_id]); - receive_timers_[audio_type][app_id]->Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(params.timeout_millis), - base::Bind(base::IgnoreResult(&AudioModemAPI::StopReceive), - base::Unretained(this), - app_id, - audio_type)); -} - -Status AudioModemAPI::StopReceive(const std::string& app_id, - AudioType audio_type) { - if (receive_timers_[audio_type].count(app_id) == 0) - return STATUS_INVALIDREQUEST; - - DCHECK(receive_timers_[audio_type][app_id]); - delete receive_timers_[audio_type][app_id]; - receive_timers_[audio_type].erase(app_id); - - DVLOG(3) << "Stopping receive for app " << app_id; - if (receive_timers_[audio_type].empty()) - modem_->StopRecording(audio_type); - return STATUS_SUCCESS; -} - -// static -BrowserContextKeyedAPIFactory<AudioModemAPI>* -AudioModemAPI::GetFactoryInstance() { - return g_factory.Pointer(); -} - - -// Private functions. - -void AudioModemAPI::WhispernetInitComplete(bool success) { - if (success) { - VLOG(2) << "Whispernet initialized successfully."; - } else { - LOG(ERROR) << "Failed to initialize Whispernet!"; - init_failed_ = true; - } -} - -void AudioModemAPI::TokensReceived(const std::vector<AudioToken>& tokens) { - // Distribute the tokens to the appropriate app(s). - std::list<ReceivedToken> all_tokens; - std::map<std::string, std::vector<ReceivedToken*>> tokens_by_app; - for (const AudioToken& token : tokens) { - ReceivedToken api_token; - const std::string& raw_token = DecodeBase64Token(token.token); - api_token.token.assign(raw_token.c_str(), - raw_token.c_str() + raw_token.size()); - api_token.band = token.audible ? AUDIOBAND_AUDIBLE : AUDIOBAND_INAUDIBLE; - all_tokens.push_back(std::move(api_token)); - for (const auto& receiver : - receive_timers_[token.audible ? AUDIBLE : INAUDIBLE]) { - tokens_by_app[receiver.first].push_back(&all_tokens.back()); - } - } - - // Send events to the appropriate app(s). - for (const auto& app_entry : tokens_by_app) { - const std::string& app_id = app_entry.first; - const auto& app_tokens = app_entry.second; - if (app_id.empty()) - continue; - - // Construct the event arguments by hand because a given token can be - // present for multiple listeners, so constructing a - // std::vector<ReceivedToken> for each is inefficient. - std::unique_ptr<base::ListValue> tokens_value(new base::ListValue()); - for (const ReceivedToken* token : app_tokens) - tokens_value->Append(token->ToValue()); - std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(std::move(tokens_value)); - - EventRouter::Get(browser_context_) - ->DispatchEventToExtension( - app_id, base::WrapUnique(new Event(events::AUDIO_MODEM_ON_RECEIVED, - OnReceived::kEventName, - std::move(args)))); - } -} - - -// Functions outside the API scope. - -template <> -void -BrowserContextKeyedAPIFactory<AudioModemAPI>::DeclareFactoryDependencies() { - DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); -} - -ExtensionFunction::ResponseAction AudioModemTransmitFunction::Run() { - std::unique_ptr<Transmit::Params> params(Transmit::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - AudioModemAPI* api = - AudioModemAPI::GetFactoryInstance()->Get(browser_context()); - if (api->init_failed()) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_CODERERROR), - kInitFailedError)); - } - - // Check the token length. - int token_length = params->params.encoding.token_length; - if (token_length <= 0) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_INVALIDREQUEST), - kInvalidTokenLengthError)); - } - const char* token = params->token.data(); - std::string token_str(token, params->token.size()); - if (static_cast<int>(token_str.size()) != token_length) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_INVALIDREQUEST), - kIncorrectTokenLengthError)); - } - - // Check the timeout. - int64_t timeout_millis = params->params.timeout_millis; - if (timeout_millis <= 0) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_INVALIDREQUEST), - kInvalidTimeoutError)); - } - if (timeout_millis > kMaxTransmitTimeout) - timeout_millis = kMaxTransmitTimeout; - - // Start transmission. - Status status = api->StartTransmit(extension_id(), params->params, token_str); - return RespondNow(ArgumentList(Transmit::Results::Create(status))); -} - -ExtensionFunction::ResponseAction AudioModemStopTransmitFunction::Run() { - std::unique_ptr<StopTransmit::Params> params( - StopTransmit::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - Status status = AudioModemAPI::GetFactoryInstance()->Get(browser_context()) - ->StopTransmit(extension_id(), AudioTypeForBand(params->band)); - return RespondNow(ArgumentList(StopTransmit::Results::Create(status))); -} - -ExtensionFunction::ResponseAction AudioModemReceiveFunction::Run() { - std::unique_ptr<Receive::Params> params(Receive::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - AudioModemAPI* api = - AudioModemAPI::GetFactoryInstance()->Get(browser_context()); - if (api->init_failed()) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_CODERERROR), - kInitFailedError)); - } - - // Check the timeout. - int64_t timeout_millis = params->params.timeout_millis; - if (timeout_millis <= 0) { - return RespondNow(ErrorWithArguments( - Receive::Results::Create(STATUS_INVALIDREQUEST), - kInvalidTimeoutError)); - } - if (timeout_millis > kMaxReceiveTimeout) - timeout_millis = kMaxReceiveTimeout; - - // Start receiving. - api->StartReceive(extension_id(), params->params); - return RespondNow(ArgumentList(Receive::Results::Create(STATUS_SUCCESS))); -} - -ExtensionFunction::ResponseAction AudioModemStopReceiveFunction::Run() { - std::unique_ptr<StopReceive::Params> params( - StopReceive::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - Status status = AudioModemAPI::GetFactoryInstance()->Get(browser_context()) - ->StopReceive(extension_id(), AudioTypeForBand(params->band)); - return RespondNow(ArgumentList(StopReceive::Results::Create(status))); -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api.h b/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api.h deleted file mode 100644 index 557e606e51d..00000000000 --- a/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api.h +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_AUDIO_MODEM_AUDIO_MODEM_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_AUDIO_MODEM_AUDIO_MODEM_API_H_ - -#include <map> -#include <memory> -#include <string> -#include <vector> - -#include "base/macros.h" -#include "chrome/common/extensions/api/audio_modem.h" -#include "components/audio_modem/public/modem.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/extension_function_histogram_value.h" - -namespace extensions { - -// Implementation of the chrome.audioModem API. -class AudioModemAPI final : public BrowserContextKeyedAPI { - public: - // Default constructor. - explicit AudioModemAPI(content::BrowserContext* context); - - // Testing constructor: pass in dependencies. - AudioModemAPI( - content::BrowserContext* context, - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client, - std::unique_ptr<audio_modem::Modem> modem); - - ~AudioModemAPI() override; - - // Starts transmitting a token, and returns the associated API status. - // Fails if another app is already transmitting the same AudioType. - api::audio_modem::Status StartTransmit( - const std::string& app_id, - const api::audio_modem::RequestParams& params, - const std::string& token); - - // Stops an in-progress transmit, and returns the associated API status. - // Fails if the specified app is not currently transmitting. - api::audio_modem::Status StopTransmit(const std::string& app_id, - audio_modem::AudioType audio_type); - - // Starts receiving for the specified app. - // Multiple apps may receive the same AudioType simultaneously. - void StartReceive(const std::string& app_id, - const api::audio_modem::RequestParams& params); - - // Stops receiving for the specified app, and returns the associated - // API status. Fails if that app is not currently receiving. - api::audio_modem::Status StopReceive(const std::string& app_id, - audio_modem::AudioType audio_type); - - bool init_failed() const { return init_failed_; } - - // BrowserContextKeyedAPI implementation. - static BrowserContextKeyedAPIFactory<AudioModemAPI>* GetFactoryInstance(); - - private: - friend class BrowserContextKeyedAPIFactory<AudioModemAPI>; - - void WhispernetInitComplete(bool success); - void TokensReceived(const std::vector<audio_modem::AudioToken>& tokens); - - content::BrowserContext* const browser_context_; - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client_; - std::unique_ptr<audio_modem::Modem> modem_; - bool init_failed_; - - // IDs for the currently transmitting app (if any), indexed by AudioType. - std::string transmitters_[2]; - - // Timeouts for the currently active transmits, indexed by AudioType. - base::OneShotTimer transmit_timers_[2]; - - // Maps of currently receiving app ID => timeouts. Indexed by AudioType. - // We own all of these pointers. Do not remove them without calling delete. - std::map<std::string, base::OneShotTimer*> receive_timers_[2]; - - // BrowserContextKeyedAPI implementation. - static const bool kServiceIsCreatedWithBrowserContext = false; - static const char* service_name() { return "AudioModemAPI"; } - - DISALLOW_COPY_AND_ASSIGN(AudioModemAPI); -}; - -template<> -void BrowserContextKeyedAPIFactory<AudioModemAPI>::DeclareFactoryDependencies(); - -class AudioModemTransmitFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.transmit", AUDIOMODEM_TRANSMIT); - - protected: - ~AudioModemTransmitFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class AudioModemStopTransmitFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.stopTransmit", - AUDIOMODEM_STOPTRANSMIT); - - protected: - ~AudioModemStopTransmitFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class AudioModemReceiveFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.receive", AUDIOMODEM_RECEIVE); - - protected: - ~AudioModemReceiveFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class AudioModemStopReceiveFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.stopReceive", AUDIOMODEM_STOPRECEIVE); - - protected: - ~AudioModemStopReceiveFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_AUDIO_MODEM_AUDIO_MODEM_API_H_ diff --git a/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api_unittest.cc b/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api_unittest.cc deleted file mode 100644 index 22daaff577c..00000000000 --- a/chromium/chrome/browser/extensions/api/audio_modem/audio_modem_api_unittest.cc +++ /dev/null @@ -1,395 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/audio_modem/audio_modem_api.h" - -#include <map> -#include <memory> -#include <string> -#include <utility> -#include <vector> - -#include "base/callback.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/values.h" -#include "chrome/browser/extensions/extension_api_unittest.h" -#include "chrome/browser/extensions/extension_function_test_utils.h" -#include "chrome/browser/extensions/test_extension_system.h" -#include "components/audio_modem/public/modem.h" -#include "components/audio_modem/test/stub_modem.h" -#include "components/audio_modem/test/stub_whispernet_client.h" -#include "extensions/browser/api_test_utils.h" -#include "extensions/browser/event_router.h" -#include "extensions/browser/event_router_factory.h" - -using audio_modem::AUDIBLE; -using audio_modem::AudioToken; -using audio_modem::INAUDIBLE; -using audio_modem::StubModem; -using audio_modem::StubWhispernetClient; - -using base::BinaryValue; -using base::DictionaryValue; -using base::ListValue; -using base::StringValue; -using base::Value; - -using content::BrowserContext; - -namespace ext_test_utils = extension_function_test_utils; - -namespace extensions { - -namespace { - -// The TestingFactoryFunction uses a BrowserContext as its context pointer. -// But each BrowserContext is still associated with a unit test. -// So we store the StubModem created in each test. -std::map<BrowserContext*, StubModem*> g_modems; - -// Create a test AudioModemAPI and store the modem it uses. -std::unique_ptr<KeyedService> ApiFactoryFunction(BrowserContext* context) { - StubModem* modem = new StubModem; - g_modems[context] = modem; - return base::WrapUnique(new AudioModemAPI( - context, - base::WrapUnique<audio_modem::WhispernetClient>(new StubWhispernetClient), - base::WrapUnique<audio_modem::Modem>(modem))); -} - -std::unique_ptr<DictionaryValue> CreateParams(const std::string& audio_band) { - std::unique_ptr<DictionaryValue> params(new DictionaryValue); - params->SetInteger("timeoutMillis", 60000); - params->SetString("band", audio_band); - params->SetInteger("encoding.tokenLength", 4); - return params; -} - -std::unique_ptr<BinaryValue> CreateToken(const std::string& token) { - return BinaryValue::CreateWithCopiedBuffer(token.c_str(), token.size()); -} - -std::unique_ptr<ListValue> CreateList(std::unique_ptr<Value> single_elt) { - std::unique_ptr<ListValue> list(new ListValue); - list->Append(std::move(single_elt)); - return list; -} - -std::unique_ptr<ListValue> CreateList(std::unique_ptr<Value> elt1, - std::unique_ptr<Value> elt2) { - std::unique_ptr<ListValue> list(new ListValue); - list->Append(std::move(elt1)); - list->Append(std::move(elt2)); - return list; -} - -DictionaryValue* CreateReceivedToken(const std::string& token, - const std::string& audio_band) { - DictionaryValue* out = new DictionaryValue; - out->Set("token", CreateToken(token)); - out->SetString("band", audio_band); - return out; -} - -bool ReceivedSingleToken(const Event* event, - const DictionaryValue* expected_token) { - ListValue* received_tokens; - event->event_args->GetList(0, &received_tokens); - if (received_tokens->GetSize() != 1) - return false; - - DictionaryValue* received_token; - received_tokens->GetDictionary(0, &received_token); - return received_token->Equals(expected_token); -} - -// TODO(ckehoe): Put this in //extensions/test. -// Then replace the other EventRouter mocks. -class StubEventRouter : public EventRouter { - public: - // Callback to receive events. First argument is - // the extension id to receive the event. - using EventCallback = - base::Callback<void(const std::string&, std::unique_ptr<Event>)>; - - explicit StubEventRouter(BrowserContext* context) - : EventRouter(context, nullptr) {} - - void DispatchEventToExtension(const std::string& extension_id, - std::unique_ptr<Event> event) override { - event_callback_.Run(extension_id, std::move(event)); - } - - void SetEventCallBack(EventCallback event_callback) { - event_callback_ = event_callback; - } - - void ClearEventCallback() { - event_callback_.Reset(); - } - - private: - EventCallback event_callback_; -}; - -// StubEventRouter factory function -std::unique_ptr<KeyedService> StubEventRouterFactoryFunction( - content::BrowserContext* context) { - return base::WrapUnique(new StubEventRouter(context)); -} - -} // namespace - -class AudioModemApiUnittest : public ExtensionApiUnittest { - public: - AudioModemApiUnittest() {} - ~AudioModemApiUnittest() override {} - - protected: - template <typename Function> - const std::string RunFunction(std::unique_ptr<ListValue> args, - const Extension* extension) { - scoped_refptr<UIThreadExtensionFunction> function(new Function); - function->set_extension(extension); - function->set_browser_context(profile()); - function->set_has_callback(true); - ext_test_utils::RunFunction(function.get(), std::move(args), browser(), - ext_test_utils::NONE); - - std::string result_status; - CHECK(function->GetResultList()->GetString(0, &result_status)); - return result_status; - } - - template <typename Function> - const std::string RunFunction(std::unique_ptr<ListValue> args) { - return RunFunction<Function>(std::move(args), GetExtension(std::string())); - } - - StubModem* GetModem() const { - return g_modems[profile()]; - } - - const Extension* GetExtension(const std::string& name) { - if (!extensions_by_name_[name].get()) { - std::unique_ptr<DictionaryValue> extension_definition( - new DictionaryValue); - extension_definition->SetString("name", name); - extension_definition->SetString("version", "1.0"); - extensions_by_name_[name] = api_test_utils::CreateExtension( - Manifest::INTERNAL, extension_definition.get(), name); - DVLOG(2) << "Created extension " << extensions_by_name_[name]->id(); - } - return extensions_by_name_[name].get(); - } - - const std::vector<std::unique_ptr<const Event>>& GetEventsForExtension( - const std::string& name) { - const Extension* extension = extensions_by_name_[name].get(); - DCHECK(extension); - return events_by_extension_id_[extension->id()]; - } - - const std::vector<std::unique_ptr<const Event>>& GetEvents() { - return GetEventsForExtension(std::string()); - } - - private: - void SetUp() override { - ExtensionApiUnittest::SetUp(); - AudioModemAPI::GetFactoryInstance()->SetTestingFactory( - profile(), &ApiFactoryFunction); - - StubEventRouter* stub_event_router = static_cast<StubEventRouter*>( - extensions::EventRouterFactory::GetInstance()->SetTestingFactoryAndUse( - profile(), &StubEventRouterFactoryFunction)); - stub_event_router->SetEventCallBack(base::Bind( - &AudioModemApiUnittest::CaptureEvent, base::Unretained(this))); - } - - void CaptureEvent(const std::string& extension_id, - std::unique_ptr<Event> event) { - events_by_extension_id_[extension_id].push_back(std::move(event)); - } - - std::map<std::string, scoped_refptr<Extension>> extensions_by_name_; - - std::map<std::string, std::vector<std::unique_ptr<const Event>>> - events_by_extension_id_; -}; - -TEST_F(AudioModemApiUnittest, TransmitBasic) { - // Start transmitting inaudibly. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("inaudible"), CreateToken("1234")))); - EXPECT_TRUE(GetModem()->IsPlaying(INAUDIBLE)); - - // Can't cancel audible transmit - we haven't started it yet. - EXPECT_EQ("invalidRequest", - RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("audible")))); - - // Start transmitting audibly. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("ABCD")))); - EXPECT_TRUE(GetModem()->IsPlaying(AUDIBLE)); - - // Stop audible transmit. We're still transmitting inaudibly. - EXPECT_EQ("success", RunFunction<AudioModemStopTransmitFunction>(CreateList( - base::MakeUnique<StringValue>("audible")))); - EXPECT_FALSE(GetModem()->IsPlaying(AUDIBLE)); - EXPECT_TRUE(GetModem()->IsPlaying(INAUDIBLE)); - - // Stop inaudible transmit. - EXPECT_EQ("success", RunFunction<AudioModemStopTransmitFunction>(CreateList( - base::MakeUnique<StringValue>("inaudible")))); - EXPECT_FALSE(GetModem()->IsPlaying(INAUDIBLE)); -} - -TEST_F(AudioModemApiUnittest, ReceiveBasic) { - // Start listening for audible tokens. - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("audible")))); - EXPECT_TRUE(GetModem()->IsRecording(AUDIBLE)); - - // Can't cancel inaudible receive - we haven't started it yet. - EXPECT_EQ("invalidRequest", - RunFunction<AudioModemStopReceiveFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")))); - - // Send some audible tokens. - std::vector<AudioToken> tokens; - tokens.push_back(AudioToken("1234", true)); - tokens.push_back(AudioToken("ABCD", true)); - tokens.push_back(AudioToken("abcd", false)); - GetModem()->DeliverTokens(tokens); - - // Check the tokens received. - EXPECT_EQ(1u, GetEvents().size()); - std::unique_ptr<ListValue> expected_tokens(new ListValue); - expected_tokens->Append(CreateReceivedToken("1234", "audible")); - expected_tokens->Append(CreateReceivedToken("ABCD", "audible")); - ListValue* received_tokens; - GetEvents()[0]->event_args->GetList(0, &received_tokens); - EXPECT_TRUE(received_tokens->Equals(expected_tokens.get())); - - // Start listening for inaudible tokens. - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("inaudible")))); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - - // Send some more tokens. - tokens.push_back(AudioToken("5678", false)); - GetModem()->DeliverTokens(tokens); - - // Check the tokens received. - EXPECT_EQ(2u, GetEvents().size()); - expected_tokens->Append(CreateReceivedToken("abcd", "inaudible")); - expected_tokens->Append(CreateReceivedToken("5678", "inaudible")); - GetEvents()[1]->event_args->GetList(0, &received_tokens); - EXPECT_TRUE(received_tokens->Equals(expected_tokens.get())); - - // Stop audible receive. We're still receiving inaudible. - EXPECT_EQ("success", RunFunction<AudioModemStopReceiveFunction>(CreateList( - base::MakeUnique<StringValue>("audible")))); - EXPECT_FALSE(GetModem()->IsRecording(AUDIBLE)); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - - // Stop inaudible receive. - EXPECT_EQ("success", RunFunction<AudioModemStopReceiveFunction>(CreateList( - base::MakeUnique<StringValue>("inaudible")))); - EXPECT_FALSE(GetModem()->IsRecording(INAUDIBLE)); -} - -TEST_F(AudioModemApiUnittest, TransmitMultiple) { - // Start transmit. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("1234")), - GetExtension("ext1"))); - EXPECT_TRUE(GetModem()->IsPlaying(AUDIBLE)); - - // Another extension can't interfere with the first one. - EXPECT_EQ("inUse", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("ABCD")), - GetExtension("ext2"))); - EXPECT_EQ("invalidRequest", - RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("audible")), - GetExtension("ext2"))); - EXPECT_TRUE(GetModem()->IsPlaying(AUDIBLE)); - - // The other extension can use the other audio band, however. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("inaudible"), CreateToken("ABCD")), - GetExtension("ext2"))); - EXPECT_TRUE(GetModem()->IsPlaying(INAUDIBLE)); - - // The first extension can change its token. - // But the other band is still in use. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("abcd")), - GetExtension("ext1"))); - EXPECT_EQ("inUse", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("inaudible"), CreateToken("1234")), - GetExtension("ext1"))); - - // Stop transmission. - EXPECT_EQ("success", RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("audible")), - GetExtension("ext1"))); - EXPECT_FALSE(GetModem()->IsPlaying(AUDIBLE)); - EXPECT_EQ("success", - RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")), - GetExtension("ext2"))); - EXPECT_FALSE(GetModem()->IsPlaying(INAUDIBLE)); -} - -TEST_F(AudioModemApiUnittest, ReceiveMultiple) { - // Start receive. Multiple extensions can receive on the same band. - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("inaudible")), GetExtension("ext1"))); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("inaudible")), GetExtension("ext2"))); - - // Receive a token. - GetModem()->DeliverTokens(std::vector<AudioToken>( - 1, AudioToken("abcd", false))); - EXPECT_EQ(1u, GetEventsForExtension("ext1").size()); - EXPECT_EQ(1u, GetEventsForExtension("ext2").size()); - - // Check the token received. - std::unique_ptr<DictionaryValue> expected_token( - CreateReceivedToken("abcd", "inaudible")); - EXPECT_TRUE(ReceivedSingleToken(GetEventsForExtension("ext1")[0].get(), - expected_token.get())); - EXPECT_TRUE(ReceivedSingleToken(GetEventsForExtension("ext2")[0].get(), - expected_token.get())); - - // If one extension stops, the modem is still receiving for the other. - EXPECT_EQ("success", - RunFunction<AudioModemStopReceiveFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")), - GetExtension("ext1"))); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - - // Receive another token. Should only go to ext2. - GetModem()->DeliverTokens(std::vector<AudioToken>( - 1, AudioToken("1234", false))); - EXPECT_EQ(1u, GetEventsForExtension("ext1").size()); - EXPECT_EQ(2u, GetEventsForExtension("ext2").size()); - expected_token.reset(CreateReceivedToken("1234", "inaudible")); - EXPECT_TRUE(ReceivedSingleToken(GetEventsForExtension("ext2")[1].get(), - expected_token.get())); - - EXPECT_EQ("success", - RunFunction<AudioModemStopReceiveFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")), - GetExtension("ext2"))); - EXPECT_FALSE(GetModem()->IsRecording(INAUDIBLE)); -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc index 2aafbddd824..6adbbac3568 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc @@ -14,7 +14,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/autofill_private/autofill_util.h" #include "chrome/common/extensions/api/autofill_private.h" -#include "chrome/grit/generated_resources.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "extensions/browser/extension_function.h" @@ -179,10 +178,8 @@ ExtensionFunction::ResponseAction AutofillPrivateSaveAddressFunction::Run() { autofill::PersonalDataManager* personal_data = autofill::PersonalDataManagerFactory::GetForProfile( chrome_details_.GetProfile()); - if (!personal_data || !personal_data->IsDataLoaded()) { - error_ = kErrorDataUnavailable; - return RespondNow(NoArguments()); - } + if (!personal_data || !personal_data->IsDataLoaded()) + return RespondNow(Error(kErrorDataUnavailable)); api::autofill_private::AddressEntry* address = ¶meters->address; @@ -368,10 +365,8 @@ ExtensionFunction::ResponseAction AutofillPrivateSaveCreditCardFunction::Run() { autofill::PersonalDataManager* personal_data = autofill::PersonalDataManagerFactory::GetForProfile( chrome_details_.GetProfile()); - if (!personal_data || !personal_data->IsDataLoaded()) { - error_ = kErrorDataUnavailable; - return RespondNow(NoArguments()); - } + if (!personal_data || !personal_data->IsDataLoaded()) + return RespondNow(Error(kErrorDataUnavailable)); api::autofill_private::CreditCardEntry* card = ¶meters->card; @@ -427,10 +422,8 @@ ExtensionFunction::ResponseAction AutofillPrivateRemoveEntryFunction::Run() { autofill::PersonalDataManager* personal_data = autofill::PersonalDataManagerFactory::GetForProfile( chrome_details_.GetProfile()); - if (!personal_data || !personal_data->IsDataLoaded()) { - error_ = kErrorDataUnavailable; - return RespondNow(NoArguments()); - } + if (!personal_data || !personal_data->IsDataLoaded()) + return RespondNow(Error(kErrorDataUnavailable)); personal_data->RemoveByGUID(parameters->guid); @@ -479,10 +472,8 @@ ExtensionFunction::ResponseAction AutofillPrivateMaskCreditCardFunction::Run() { autofill::PersonalDataManager* personal_data = autofill::PersonalDataManagerFactory::GetForProfile( chrome_details_.GetProfile()); - if (!personal_data || !personal_data->IsDataLoaded()) { - error_ = kErrorDataUnavailable; - return RespondNow(NoArguments()); - } + if (!personal_data || !personal_data->IsDataLoaded()) + return RespondNow(Error(kErrorDataUnavailable)); personal_data->ResetFullServerCard(parameters->guid); diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc index f5844570170..2b95e0ec180 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc @@ -44,11 +44,23 @@ class AutofillPrivateApiTest : public ExtensionApiTest { // TODO(hcarmona): Investigate converting these tests to unittests. -IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, SaveAddress) { +// TODO(crbug.com/643097) Disabled for flakiness. +#if defined(OS_WIN) +#define MAYBE_SaveAddress DISABLED_SaveAddress +#else +#define MAYBE_SaveAddress SaveAddress +#endif // defined(OS_WIN) +IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, MAYBE_SaveAddress) { EXPECT_TRUE(RunAutofillSubtest("saveAddress")) << message_; } -IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, GetCountryList) { +// TODO(crbug.com/643097) Disabled for flakiness. +#if defined(OS_WIN) +#define MAYBE_GetCountryList DISABLED_GetCountryList +#else +#define MAYBE_GetCountryList GetCountryList +#endif // defined(OS_WIN) +IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, MAYBE_GetCountryList) { EXPECT_TRUE(RunAutofillSubtest("getCountryList")) << message_; } @@ -56,11 +68,23 @@ IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, GetAddressComponents) { EXPECT_TRUE(RunAutofillSubtest("getAddressComponents")) << message_; } -IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, SaveCreditCard) { +// TODO(crbug.com/643097) Disabled for flakiness. +#if defined(OS_WIN) +#define MAYBE_SaveCreditCard DISABLED_SaveCreditCard +#else +#define MAYBE_SaveCreditCard SaveCreditCard +#endif // defined(OS_WIN) +IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, MAYBE_SaveCreditCard) { EXPECT_TRUE(RunAutofillSubtest("saveCreditCard")) << message_; } -IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, RemoveEntry) { +// TODO(crbug.com/643097) Disabled for flakiness. +#if defined(OS_WIN) +#define MAYBE_RemoveEntry DISABLED_RemoveEntry +#else +#define MAYBE_RemoveEntry RemoveEntry +#endif // defined(OS_WIN) +IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, MAYBE_RemoveEntry) { EXPECT_TRUE(RunAutofillSubtest("removeEntry")) << message_; } diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc index 3eb7f25eba3..6f6d7f976ff 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc @@ -23,7 +23,7 @@ #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/field_types.h" #include "components/prefs/pref_service.h" -#include "grit/components_strings.h" +#include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace autofill_private = extensions::api::autofill_private; @@ -62,8 +62,8 @@ std::unique_ptr<std::vector<std::string>> GetValueList( std::unique_ptr<std::string> GetStringFromProfile( const autofill::AutofillProfile& profile, const autofill::ServerFieldType& type) { - return base::WrapUnique( - new std::string(base::UTF16ToUTF8(profile.GetRawInfo(type)))); + return base::MakeUnique<std::string>( + base::UTF16ToUTF8(profile.GetRawInfo(type))); } autofill_private::AddressEntry ProfileToAddressEntry( @@ -101,8 +101,8 @@ autofill_private::AddressEntry ProfileToAddressEntry( // Parse |label| so that it can be used to create address metadata. base::string16 separator = l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_SUMMARY_SEPARATOR); - std::vector<base::string16> label_pieces; - base::SplitStringUsingSubstr(label, separator, &label_pieces); + std::vector<base::string16> label_pieces = base::SplitStringUsingSubstr( + label, separator, base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); // Create address metadata and add it to |address|. std::unique_ptr<autofill_private::AutofillMetadata> metadata( diff --git a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc index d3a5767cf16..8d9d827dad5 100644 --- a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc @@ -33,8 +33,8 @@ #include "ui/accessibility/tree_generator.h" #if defined(OS_CHROMEOS) -#include "ash/accelerators/accelerator_controller.h" -#include "ash/shell.h" +#include "ash/common/accelerators/accelerator_controller.h" +#include "ash/common/wm_shell.h" #include "chrome/browser/ui/aura/accessibility/automation_manager_aura.h" #endif @@ -125,6 +125,12 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, Location) { << message_; } +IN_PROC_BROWSER_TEST_F(AutomationApiTest, Location2) { + StartEmbeddedTestServer(); + ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "location2.html")) + << message_; +} + IN_PROC_BROWSER_TEST_F(AutomationApiTest, BoundsForRange) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", @@ -132,6 +138,13 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, BoundsForRange) { << message_; } +IN_PROC_BROWSER_TEST_F(AutomationApiTest, LineStartOffsets) { + StartEmbeddedTestServer(); + ASSERT_TRUE( + RunExtensionSubtest("automation/tests/tabs", "line_start_offsets.html")) + << message_; +} + IN_PROC_BROWSER_TEST_F(AutomationApiTest, TabsAutomationBooleanPermissions) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest( @@ -154,18 +167,15 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, TabsAutomationHostsPermissions) { } #if defined(USE_AURA) -IN_PROC_BROWSER_TEST_F(AutomationApiTest, Desktop) { +// Flaky, see http://crbug.com/637525 +IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_Desktop) { ASSERT_TRUE(RunExtensionSubtest("automation/tests/desktop", "desktop.html")) << message_; } #if defined(OS_CHROMEOS) -#if defined(MEMORY_SANITIZER) -#define MAYBE_DesktopInitialFocus DISABLED_DesktopInitialFocus -#else -#define MAYBE_DesktopInitialFocus DesktopInitialFocus -#endif -IN_PROC_BROWSER_TEST_F(AutomationApiTest, MAYBE_DesktopInitialFocus) { +// TODO(crbug.com/615908): Flaky on CrOS sanitizers. +IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_DesktopInitialFocus) { ASSERT_TRUE( RunExtensionSubtest("automation/tests/desktop", "initial_focus.html")) << message_; @@ -187,7 +197,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopFocusIframe) { IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopFocusViews) { AutomationManagerAura::GetInstance()->Enable(browser()->profile()); // Trigger the shelf subtree to be computed. - ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled( + ash::WmShell::Get()->accelerator_controller()->PerformActionIfEnabled( ash::FOCUS_SHELF); ASSERT_TRUE( @@ -205,7 +215,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopNotRequested) { IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopActions) { AutomationManagerAura::GetInstance()->Enable(browser()->profile()); // Trigger the shelf subtree to be computed. - ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled( + ash::WmShell::Get()->accelerator_controller()->PerformActionIfEnabled( ash::FOCUS_SHELF); ASSERT_TRUE(RunExtensionSubtest("automation/tests/desktop", "actions.html")) diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc index 291a61083e2..d86ceaf30ee 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc @@ -12,6 +12,7 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/common/extensions/api/automation_api_constants.h" #include "chrome/common/extensions/api/automation_internal.h" #include "chrome/common/extensions/chrome_extension_messages.h" #include "content/public/browser/notification_service.h" @@ -19,6 +20,7 @@ #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/event_router.h" +#include "extensions/common/extension.h" #include "ui/accessibility/ax_enums.h" #include "ui/accessibility/ax_node_data.h" @@ -61,7 +63,7 @@ void AutomationEventRouter::RegisterListenerWithDesktopPermission( Register(extension_id, listener_process_id, listener_routing_id, - 0 /* desktop tree ID */, + api::automation::kDesktopTreeID, true); } @@ -87,6 +89,23 @@ void AutomationEventRouter::DispatchAccessibilityEvent( } } +void AutomationEventRouter::DispatchAccessibilityLocationChange( + const ExtensionMsg_AccessibilityLocationChangeParams& params) { + for (const auto& listener : listeners_) { + // Skip listeners that don't want to listen to this tree. + if (!listener.desktop && + listener.tree_ids.find(params.tree_id) == listener.tree_ids.end()) { + continue; + } + + content::RenderProcessHost* rph = + content::RenderProcessHost::FromID(listener.process_id); + rph->Send(new ExtensionMsg_AccessibilityLocationChange( + listener.routing_id, + params)); + } +} + void AutomationEventRouter::DispatchTreeDestroyedEvent( int tree_id, content::BrowserContext* browser_context) { diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h index 82239ea18bb..be7fc766c2a 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_AUTOMATION_INTERNAL_AUTOMATION_EVENT_ROUTER_H_ #define CHROME_BROWSER_EXTENSIONS_API_AUTOMATION_INTERNAL_AUTOMATION_EVENT_ROUTER_H_ +#include <set> #include <vector> #include "base/macros.h" @@ -13,7 +14,7 @@ #include "content/public/browser/ax_event_notification_details.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" -#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" class Profile; @@ -22,10 +23,11 @@ class BrowserContext; } // namespace content struct ExtensionMsg_AccessibilityEventParams; +struct ExtensionMsg_AccessibilityLocationChangeParams; namespace extensions { - struct AutomationListener; +class Extension; class AutomationEventRouter : public content::NotificationObserver { public: @@ -50,6 +52,9 @@ class AutomationEventRouter : public content::NotificationObserver { void DispatchAccessibilityEvent( const ExtensionMsg_AccessibilityEventParams& params); + void DispatchAccessibilityLocationChange( + const ExtensionMsg_AccessibilityLocationChangeParams& params); + // Notify all automation extensions that an accessibility tree was // destroyed. If |browser_context| is null, void DispatchTreeDestroyedEvent( diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc index b52ee36034e..6ada5f161f5 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc @@ -20,6 +20,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/extensions/api/automation_api_constants.h" #include "chrome/common/extensions/api/automation_internal.h" #include "chrome/common/extensions/chrome_extension_messages.h" #include "chrome/common/extensions/manifest_handlers/automation.h" @@ -51,7 +52,6 @@ namespace extensions { namespace { -const int kDesktopTreeID = 0; const char kCannotRequestAutomationOnPage[] = "Cannot request automation tree on url \"*\". " "Extension manifest must request permission to access this host."; @@ -203,10 +203,7 @@ class AutomationWebContentsObserver void AccessibilityEventReceived( const std::vector<content::AXEventNotificationDetails>& details) override { - std::vector<content::AXEventNotificationDetails>::const_iterator iter = - details.begin(); - for (; iter != details.end(); ++iter) { - const content::AXEventNotificationDetails& event = *iter; + for (const auto& event : details) { ExtensionMsg_AccessibilityEventParams params; params.tree_id = event.ax_tree_id; params.id = event.id; @@ -214,12 +211,26 @@ class AutomationWebContentsObserver params.update = event.update; params.location_offset = web_contents()->GetContainerBounds().OffsetFromOrigin(); + params.event_from = event.event_from; AutomationEventRouter* router = AutomationEventRouter::GetInstance(); router->DispatchAccessibilityEvent(params); } } + void AccessibilityLocationChangesReceived( + const std::vector<content::AXLocationChangeNotificationDetails>& details) + override { + for (const auto& src : details) { + ExtensionMsg_AccessibilityLocationChangeParams dst; + dst.id = src.id; + dst.tree_id = src.ax_tree_id; + dst.new_location = src.new_location; + AutomationEventRouter* router = AutomationEventRouter::GetInstance(); + router->DispatchAccessibilityLocationChange(dst); + } + } + void RenderFrameDeleted( content::RenderFrameHost* render_frame_host) override { int tree_id = render_frame_host->GetAXTreeID(); @@ -325,7 +336,7 @@ AutomationInternalPerformActionFunction::Run() { std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - if (params->args.tree_id == kDesktopTreeID) { + if (params->args.tree_id == api::automation::kDesktopTreeID) { #if defined(USE_AURA) return RouteActionToAdapter(params.get(), AutomationManagerAura::GetInstance()); @@ -422,7 +433,7 @@ AutomationInternalQuerySelectorFunction::Run() { std::unique_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - if (params->args.tree_id == kDesktopTreeID) { + if (params->args.tree_id == api::automation::kDesktopTreeID) { return RespondNow( Error("domQuerySelector queries may not be used on the desktop.")); } diff --git a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc index e5a85eb14cf..d8aee6b8404 100644 --- a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc +++ b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc @@ -8,6 +8,7 @@ #include <utility> #include "base/lazy_instance.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "chrome/browser/extensions/extension_action_manager.h" @@ -66,39 +67,39 @@ base::ListValue* GetAPIPermissions(const Extension* ext) { return permissions; } -bool IsTestMode(Profile* profile) { - return AutotestPrivateAPI::GetFactoryInstance()->Get(profile)->test_mode(); +bool IsTestMode(content::BrowserContext* context) { + return AutotestPrivateAPI::GetFactoryInstance()->Get(context)->test_mode(); } } // namespace -bool AutotestPrivateLogoutFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateLogoutFunction::Run() { DVLOG(1) << "AutotestPrivateLogoutFunction"; - if (!IsTestMode(GetProfile())) + if (!IsTestMode(browser_context())) chrome::AttemptUserExit(); - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateRestartFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateRestartFunction::Run() { DVLOG(1) << "AutotestPrivateRestartFunction"; - if (!IsTestMode(GetProfile())) + if (!IsTestMode(browser_context())) chrome::AttemptRestart(); - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateShutdownFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateShutdownFunction::Run() { std::unique_ptr<api::autotest_private::Shutdown::Params> params( api::autotest_private::Shutdown::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DVLOG(1) << "AutotestPrivateShutdownFunction " << params->force; - if (!IsTestMode(GetProfile())) + if (!IsTestMode(browser_context())) chrome::AttemptExit(); - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateLoginStatusFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateLoginStatusFunction::Run() { DVLOG(1) << "AutotestPrivateLoginStatusFunction"; std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue); @@ -141,29 +142,29 @@ bool AutotestPrivateLoginStatusFunction::RunSync() { } #endif - SetResult(std::move(result)); - return true; + return RespondNow(OneArgument(std::move(result))); } -bool AutotestPrivateLockScreenFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateLockScreenFunction::Run() { DVLOG(1) << "AutotestPrivateLockScreenFunction"; #if defined(OS_CHROMEOS) chromeos::DBusThreadManager::Get()->GetSessionManagerClient()-> RequestLockScreen(); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateGetExtensionsInfoFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateGetExtensionsInfoFunction::Run() { DVLOG(1) << "AutotestPrivateGetExtensionsInfoFunction"; ExtensionService* service = - ExtensionSystem::Get(GetProfile())->extension_service(); - ExtensionRegistry* registry = ExtensionRegistry::Get(GetProfile()); + ExtensionSystem::Get(browser_context())->extension_service(); + ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); const ExtensionSet& extensions = registry->enabled_extensions(); const ExtensionSet& disabled_extensions = registry->disabled_extensions(); ExtensionActionManager* extension_action_manager = - ExtensionActionManager::Get(GetProfile()); + ExtensionActionManager::Get(browser_context()); base::ListValue* extensions_values = new base::ListValue; ExtensionList all; @@ -200,8 +201,8 @@ bool AutotestPrivateGetExtensionsInfoFunction::RunSync() { location == Manifest::INTERNAL || Manifest::IsUnpackedLocation(location)); extension_value->SetBoolean("isEnabled", service->IsExtensionEnabled(id)); - extension_value->SetBoolean("allowedInIncognito", - util::IsIncognitoEnabled(id, GetProfile())); + extension_value->SetBoolean( + "allowedInIncognito", util::IsIncognitoEnabled(id, browser_context())); extension_value->SetBoolean( "hasPageAction", extension_action_manager->GetPageAction(*extension) != NULL); @@ -212,17 +213,17 @@ bool AutotestPrivateGetExtensionsInfoFunction::RunSync() { std::unique_ptr<base::DictionaryValue> return_value( new base::DictionaryValue); return_value->Set("extensions", extensions_values); - SetResult(std::move(return_value)); - return true; + return RespondNow(OneArgument(std::move(return_value))); } static int AccessArray(const volatile int arr[], const volatile int *index) { return arr[*index]; } -bool AutotestPrivateSimulateAsanMemoryBugFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateSimulateAsanMemoryBugFunction::Run() { DVLOG(1) << "AutotestPrivateSimulateAsanMemoryBugFunction"; - if (!IsTestMode(GetProfile())) { + if (!IsTestMode(browser_context())) { // This array is volatile not to let compiler optimize us out. volatile int testarray[3] = {0, 0, 0}; @@ -230,10 +231,11 @@ bool AutotestPrivateSimulateAsanMemoryBugFunction::RunSync() { volatile int index = 5; AccessArray(testarray, &index); } - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetTouchpadSensitivityFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateSetTouchpadSensitivityFunction::Run() { std::unique_ptr<api::autotest_private::SetTouchpadSensitivity::Params> params( api::autotest_private::SetTouchpadSensitivity::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -244,10 +246,10 @@ bool AutotestPrivateSetTouchpadSensitivityFunction::RunSync() { chromeos::system::InputDeviceSettings::Get()->SetTouchpadSensitivity( params->value); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetTapToClickFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateSetTapToClickFunction::Run() { std::unique_ptr<api::autotest_private::SetTapToClick::Params> params( api::autotest_private::SetTapToClick::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -257,10 +259,11 @@ bool AutotestPrivateSetTapToClickFunction::RunSync() { #if defined(OS_CHROMEOS) chromeos::system::InputDeviceSettings::Get()->SetTapToClick(params->enabled); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetThreeFingerClickFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateSetThreeFingerClickFunction::Run() { std::unique_ptr<api::autotest_private::SetThreeFingerClick::Params> params( api::autotest_private::SetThreeFingerClick::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -271,10 +274,10 @@ bool AutotestPrivateSetThreeFingerClickFunction::RunSync() { chromeos::system::InputDeviceSettings::Get()->SetThreeFingerClick( params->enabled); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetTapDraggingFunction::RunSync() { +ExtensionFunction::ResponseAction AutotestPrivateSetTapDraggingFunction::Run() { std::unique_ptr<api::autotest_private::SetTapDragging::Params> params( api::autotest_private::SetTapDragging::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -284,10 +287,11 @@ bool AutotestPrivateSetTapDraggingFunction::RunSync() { #if defined(OS_CHROMEOS) chromeos::system::InputDeviceSettings::Get()->SetTapDragging(params->enabled); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetNaturalScrollFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateSetNaturalScrollFunction::Run() { std::unique_ptr<api::autotest_private::SetNaturalScroll::Params> params( api::autotest_private::SetNaturalScroll::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -298,10 +302,11 @@ bool AutotestPrivateSetNaturalScrollFunction::RunSync() { chromeos::system::InputDeviceSettings::Get()->SetNaturalScroll( params->enabled); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetMouseSensitivityFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateSetMouseSensitivityFunction::Run() { std::unique_ptr<api::autotest_private::SetMouseSensitivity::Params> params( api::autotest_private::SetMouseSensitivity::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -312,10 +317,11 @@ bool AutotestPrivateSetMouseSensitivityFunction::RunSync() { chromeos::system::InputDeviceSettings::Get()->SetMouseSensitivity( params->value); #endif - return true; + return RespondNow(NoArguments()); } -bool AutotestPrivateSetPrimaryButtonRightFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateSetPrimaryButtonRightFunction::Run() { std::unique_ptr<api::autotest_private::SetPrimaryButtonRight::Params> params( api::autotest_private::SetPrimaryButtonRight::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -326,7 +332,7 @@ bool AutotestPrivateSetPrimaryButtonRightFunction::RunSync() { chromeos::system::InputDeviceSettings::Get()->SetPrimaryButtonRight( params->right); #endif - return true; + return RespondNow(NoArguments()); } // static @@ -351,25 +357,25 @@ std::string AutotestPrivateGetVisibleNotificationsFunction::ConvertToString( return "unknown"; } -bool AutotestPrivateGetVisibleNotificationsFunction::RunSync() { +ExtensionFunction::ResponseAction +AutotestPrivateGetVisibleNotificationsFunction::Run() { DVLOG(1) << "AutotestPrivateGetVisibleNotificationsFunction"; std::unique_ptr<base::ListValue> values(new base::ListValue); #if defined(OS_CHROMEOS) for (auto* notification : message_center::MessageCenter::Get()->GetVisibleNotifications()) { - base::DictionaryValue* result(new base::DictionaryValue); + auto result = base::MakeUnique<base::DictionaryValue>(); result->SetString("id", notification->id()); result->SetString("type", ConvertToString(notification->type())); result->SetString("title", notification->title()); result->SetString("message", notification->message()); result->SetInteger("priority", notification->priority()); result->SetInteger("progress", notification->progress()); - values->Append(result); + values->Append(std::move(result)); } #endif - SetResult(std::move(values)); - return true; + return RespondNow(OneArgument(std::move(values))); } static base::LazyInstance<BrowserContextKeyedAPIFactory<AutotestPrivateAPI> > diff --git a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h index 092329ecf3f..a84c368557d 100644 --- a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h +++ b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h @@ -14,155 +14,153 @@ namespace extensions { -class AutotestPrivateLogoutFunction : public ChromeSyncExtensionFunction { +class AutotestPrivateLogoutFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.logout", AUTOTESTPRIVATE_LOGOUT) private: ~AutotestPrivateLogoutFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class AutotestPrivateRestartFunction : public ChromeSyncExtensionFunction { +class AutotestPrivateRestartFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.restart", AUTOTESTPRIVATE_RESTART) private: ~AutotestPrivateRestartFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class AutotestPrivateShutdownFunction : public ChromeSyncExtensionFunction { +class AutotestPrivateShutdownFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.shutdown", AUTOTESTPRIVATE_SHUTDOWN) private: ~AutotestPrivateShutdownFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class AutotestPrivateLoginStatusFunction : public ChromeSyncExtensionFunction { +class AutotestPrivateLoginStatusFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.loginStatus", AUTOTESTPRIVATE_LOGINSTATUS) private: ~AutotestPrivateLoginStatusFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class AutotestPrivateLockScreenFunction : public ChromeSyncExtensionFunction { +class AutotestPrivateLockScreenFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.lockScreen", AUTOTESTPRIVATE_LOCKSCREEN) private: ~AutotestPrivateLockScreenFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateGetExtensionsInfoFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.getExtensionsInfo", AUTOTESTPRIVATE_GETEXTENSIONSINFO) private: ~AutotestPrivateGetExtensionsInfoFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateSimulateAsanMemoryBugFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.simulateAsanMemoryBug", AUTOTESTPRIVATE_SIMULATEASANMEMORYBUG) private: ~AutotestPrivateSimulateAsanMemoryBugFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateSetTouchpadSensitivityFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setTouchpadSensitivity", AUTOTESTPRIVATE_SETTOUCHPADSENSITIVITY) private: ~AutotestPrivateSetTouchpadSensitivityFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class AutotestPrivateSetTapToClickFunction - : public ChromeSyncExtensionFunction { +class AutotestPrivateSetTapToClickFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setTapToClick", AUTOTESTPRIVATE_SETTAPTOCLICK) private: ~AutotestPrivateSetTapToClickFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateSetThreeFingerClickFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setThreeFingerClick", AUTOTESTPRIVATE_SETTHREEFINGERCLICK) private: ~AutotestPrivateSetThreeFingerClickFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class AutotestPrivateSetTapDraggingFunction - : public ChromeSyncExtensionFunction { +class AutotestPrivateSetTapDraggingFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setTapDragging", AUTOTESTPRIVATE_SETTAPDRAGGING) private: ~AutotestPrivateSetTapDraggingFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateSetNaturalScrollFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setNaturalScroll", AUTOTESTPRIVATE_SETNATURALSCROLL) private: ~AutotestPrivateSetNaturalScrollFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateSetMouseSensitivityFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setMouseSensitivity", AUTOTESTPRIVATE_SETMOUSESENSITIVITY) private: ~AutotestPrivateSetMouseSensitivityFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateSetPrimaryButtonRightFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setPrimaryButtonRight", AUTOTESTPRIVATE_SETPRIMARYBUTTONRIGHT) private: ~AutotestPrivateSetPrimaryButtonRightFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class AutotestPrivateGetVisibleNotificationsFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.getVisibleNotifications", AUTOTESTPRIVATE_GETVISIBLENOTIFICATIONS) @@ -171,7 +169,7 @@ class AutotestPrivateGetVisibleNotificationsFunction static std::string ConvertToString(message_center::NotificationType type); ~AutotestPrivateGetVisibleNotificationsFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; // Don't kill the browser when we're in a browser test. diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/OWNERS b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/OWNERS index 6a2cb03fd3e..3ed331b322e 100644 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/OWNERS +++ b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/OWNERS @@ -1 +1 @@ -rkc@chromium.org +steel@chromium.org diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.cc deleted file mode 100644 index 9eb998ec26b..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.h" - -#include "base/lazy_instance.h" -#include "device/bluetooth/bluetooth_advertisement.h" -#include "net/base/io_buffer.h" - -namespace extensions { - -// static -static base::LazyInstance<BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothApiAdvertisement>>> g_server_factory = - LAZY_INSTANCE_INITIALIZER; - -// static -template <> -BrowserContextKeyedAPIFactory<ApiResourceManager<BluetoothApiAdvertisement>>* -ApiResourceManager<BluetoothApiAdvertisement>::GetFactoryInstance() { - return g_server_factory.Pointer(); -} - -BluetoothApiAdvertisement::BluetoothApiAdvertisement( - const std::string& owner_extension_id, - scoped_refptr<device::BluetoothAdvertisement> advertisement) - : ApiResource(owner_extension_id), advertisement_(advertisement) { - DCHECK_CURRENTLY_ON(kThreadId); -} - -BluetoothApiAdvertisement::~BluetoothApiAdvertisement() { -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.h b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.h deleted file mode 100644 index f570dfa2873..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_API_ADVERTISEMENT_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_API_ADVERTISEMENT_H_ - -#include <string> - -#include "base/macros.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" -#include "device/bluetooth/bluetooth_advertisement.h" -#include "extensions/browser/api/api_resource.h" -#include "extensions/browser/api/api_resource_manager.h" - -namespace device { -class BluetoothAdvertisement; -} // namespace device - -namespace extensions { - -// Representation of advertisement instances from the "bluetooth" namespace, -// abstracting the underlying BluetoothAdvertisementXxx class. All methods -// must be called on the |kThreadId| thread. -class BluetoothApiAdvertisement : public ApiResource { - public: - BluetoothApiAdvertisement(const std::string& owner_extension_id, - scoped_refptr<device::BluetoothAdvertisement>); - ~BluetoothApiAdvertisement() override; - - device::BluetoothAdvertisement* advertisement() { - return advertisement_.get(); - } - - // Implementations of |BluetoothAdvertisement| require being called on the - // UI thread. - static const content::BrowserThread::ID kThreadId = - content::BrowserThread::UI; - - private: - friend class ApiResourceManager<BluetoothApiAdvertisement>; - - static const char* service_name() { - return "BluetoothApiAdvertisementManager"; - } - - // The underlying advertisement instance. - scoped_refptr<device::BluetoothAdvertisement> advertisement_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothApiAdvertisement); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_API_ADVERTISEMENT_H_ diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.cc deleted file mode 100644 index ea511be894e..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.cc +++ /dev/null @@ -1,1497 +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/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.h" - -#include <stdint.h> -#include <algorithm> -#include <iterator> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/callback_forward.h" -#include "base/command_line.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/memory/weak_ptr.h" -#include "base/values.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/utils.h" -#include "chrome/common/extensions/api/bluetooth_low_energy.h" -#include "content/public/browser/browser_thread.h" -#include "device/bluetooth/bluetooth_adapter.h" -#include "device/bluetooth/bluetooth_gatt_characteristic.h" -#include "device/bluetooth/bluetooth_local_gatt_characteristic.h" -#include "device/bluetooth/bluetooth_local_gatt_descriptor.h" -#include "device/bluetooth/bluetooth_local_gatt_service.h" -#include "device/bluetooth/bluetooth_uuid.h" -#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h" -#include "extensions/common/extension.h" -#include "extensions/common/switches.h" - -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h" -#endif - -using content::BrowserContext; -using content::BrowserThread; - -namespace apibtle = extensions::api::bluetooth_low_energy; - -namespace extensions { - -namespace { - -const char kErrorAdapterNotInitialized[] = - "Could not initialize Bluetooth adapter"; -const char kErrorAlreadyConnected[] = "Already connected"; -const char kErrorAlreadyNotifying[] = "Already notifying"; -const char kErrorAttributeLengthInvalid[] = "Attribute length invalid"; -const char kErrorAuthenticationFailed[] = "Authentication failed"; -const char kErrorCanceled[] = "Request canceled"; -const char kErrorConnectionCongested[] = "Connection congested"; -const char kErrorGattNotSupported[] = "Operation not supported by this service"; -const char kErrorHigherSecurity[] = "Higher security needed"; -const char kErrorInProgress[] = "In progress"; -const char kErrorInsufficientAuthorization[] = "Insufficient authorization"; -const char kErrorInsufficientEncryption[] = "Insufficient encryption"; -const char kErrorInvalidAdvertisementLength[] = "Invalid advertisement length"; -const char kErrorInvalidLength[] = "Invalid attribute value length"; -const char kErrorNotConnected[] = "Not connected"; -const char kErrorNotFound[] = "Instance not found"; -const char kErrorNotNotifying[] = "Not notifying"; -const char kErrorOffsetInvalid[] = "Offset invalid"; -const char kErrorOperationFailed[] = "Operation failed"; -const char kErrorPermissionDenied[] = "Permission denied"; -const char kErrorPlatformNotSupported[] = - "This operation is not supported on the current platform"; -const char kErrorRequestNotSupported[] = "Request not supported"; -const char kErrorTimeout[] = "Operation timed out"; -const char kErrorUnsupportedDevice[] = - "This device is not supported on the current platform"; -const char kErrorInvalidServiceId[] = "The service ID doesn't exist."; -const char kErrorInvalidCharacteristicId[] = - "The characteristic ID doesn't exist."; -const char kErrorNotifyPropertyNotSet[] = - "The characteristic does not have the notify property set."; -const char kErrorIndicatePropertyNotSet[] = - "The characteristic does not have the indicate property set."; -const char kErrorServiceNotRegistered[] = - "The characteristic is not owned by a service that is registered."; -const char kErrorUnknownNotificationError[] = - "An unknown notification error occured."; - -const char kStatusAdvertisementAlreadyExists[] = - "An advertisement is already advertising"; -const char kStatusAdvertisementDoesNotExist[] = - "This advertisement does not exist"; - -// Returns the correct error string based on error status |status|. This is used -// to set the value of |chrome.runtime.lastError.message| and should not be -// passed |BluetoothLowEnergyEventRouter::kStatusSuccess|. -std::string StatusToString(BluetoothLowEnergyEventRouter::Status status) { - switch (status) { - case BluetoothLowEnergyEventRouter::kStatusErrorAlreadyConnected: - return kErrorAlreadyConnected; - case BluetoothLowEnergyEventRouter::kStatusErrorAlreadyNotifying: - return kErrorAlreadyNotifying; - case BluetoothLowEnergyEventRouter::kStatusErrorAttributeLengthInvalid: - return kErrorAttributeLengthInvalid; - case BluetoothLowEnergyEventRouter::kStatusErrorAuthenticationFailed: - return kErrorAuthenticationFailed; - case BluetoothLowEnergyEventRouter::kStatusErrorCanceled: - return kErrorCanceled; - case BluetoothLowEnergyEventRouter::kStatusErrorConnectionCongested: - return kErrorConnectionCongested; - case BluetoothLowEnergyEventRouter::kStatusErrorGattNotSupported: - return kErrorGattNotSupported; - case BluetoothLowEnergyEventRouter::kStatusErrorHigherSecurity: - return kErrorHigherSecurity; - case BluetoothLowEnergyEventRouter::kStatusErrorInProgress: - return kErrorInProgress; - case BluetoothLowEnergyEventRouter::kStatusErrorInsufficientAuthorization: - return kErrorInsufficientAuthorization; - case BluetoothLowEnergyEventRouter::kStatusErrorInsufficientEncryption: - return kErrorInsufficientEncryption; - case BluetoothLowEnergyEventRouter::kStatusErrorInvalidLength: - return kErrorInvalidLength; - case BluetoothLowEnergyEventRouter::kStatusErrorNotConnected: - return kErrorNotConnected; - case BluetoothLowEnergyEventRouter::kStatusErrorNotFound: - return kErrorNotFound; - case BluetoothLowEnergyEventRouter::kStatusErrorNotNotifying: - return kErrorNotNotifying; - case BluetoothLowEnergyEventRouter::kStatusErrorOffsetInvalid: - return kErrorOffsetInvalid; - case BluetoothLowEnergyEventRouter::kStatusErrorPermissionDenied: - return kErrorPermissionDenied; - case BluetoothLowEnergyEventRouter::kStatusErrorRequestNotSupported: - return kErrorRequestNotSupported; - case BluetoothLowEnergyEventRouter::kStatusErrorTimeout: - return kErrorTimeout; - case BluetoothLowEnergyEventRouter::kStatusErrorUnsupportedDevice: - return kErrorUnsupportedDevice; - case BluetoothLowEnergyEventRouter::kStatusErrorInvalidServiceId: - return kErrorInvalidServiceId; - case BluetoothLowEnergyEventRouter::kStatusSuccess: - NOTREACHED(); - break; - default: - return kErrorOperationFailed; - } - return ""; -} - -extensions::BluetoothLowEnergyEventRouter* GetEventRouter( - BrowserContext* context) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return extensions::BluetoothLowEnergyAPI::Get(context)->event_router(); -} - -template <typename T> -void DoWorkCallback(const base::Callback<T()>& callback) { - DCHECK(!callback.is_null()); - callback.Run(); -} - -std::unique_ptr<device::BluetoothAdvertisement::ManufacturerData> -CreateManufacturerData( - std::vector<apibtle::ManufacturerData>* manufacturer_data) { - std::unique_ptr<device::BluetoothAdvertisement::ManufacturerData> - created_data(new device::BluetoothAdvertisement::ManufacturerData()); - for (const auto& it : *manufacturer_data) { - std::vector<uint8_t> data(it.data.size()); - std::copy(it.data.begin(), it.data.end(), data.begin()); - (*created_data)[it.id] = data; - } - return created_data; -} - -std::unique_ptr<device::BluetoothAdvertisement::ServiceData> CreateServiceData( - std::vector<apibtle::ServiceData>* service_data) { - std::unique_ptr<device::BluetoothAdvertisement::ServiceData> created_data( - new device::BluetoothAdvertisement::ServiceData()); - for (const auto& it : *service_data) { - std::vector<uint8_t> data(it.data.size()); - std::copy(it.data.begin(), it.data.end(), data.begin()); - (*created_data)[it.uuid] = data; - } - return created_data; -} - -bool HasProperty( - const std::vector<apibtle::CharacteristicProperty>& api_properties, - apibtle::CharacteristicProperty property) { - return find(api_properties.begin(), api_properties.end(), property) != - api_properties.end(); -} - -bool HasPermission( - const std::vector<apibtle::DescriptorPermission>& api_permissions, - apibtle::DescriptorPermission permission) { - return find(api_permissions.begin(), api_permissions.end(), permission) != - api_permissions.end(); -} - -device::BluetoothGattCharacteristic::Properties GetBluetoothProperties( - const std::vector<apibtle::CharacteristicProperty>& api_properties) { - device::BluetoothGattCharacteristic::Properties properties = - device::BluetoothGattCharacteristic::PROPERTY_NONE; - - static_assert( - apibtle::CHARACTERISTIC_PROPERTY_LAST == 14, - "Update required if the number of characteristic properties changes."); - - if (HasProperty(api_properties, apibtle::CHARACTERISTIC_PROPERTY_BROADCAST)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_BROADCAST; - } - - if (HasProperty(api_properties, apibtle::CHARACTERISTIC_PROPERTY_READ)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_READ; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_WRITEWITHOUTRESPONSE)) { - properties |= - device::BluetoothGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE; - } - - if (HasProperty(api_properties, apibtle::CHARACTERISTIC_PROPERTY_WRITE)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_WRITE; - } - - if (HasProperty(api_properties, apibtle::CHARACTERISTIC_PROPERTY_NOTIFY)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_NOTIFY; - } - - if (HasProperty(api_properties, apibtle::CHARACTERISTIC_PROPERTY_INDICATE)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_INDICATE; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_AUTHENTICATEDSIGNEDWRITES)) { - properties |= device::BluetoothGattCharacteristic:: - PROPERTY_AUTHENTICATED_SIGNED_WRITES; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_EXTENDEDPROPERTIES)) { - properties |= - device::BluetoothGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_RELIABLEWRITE)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_RELIABLE_WRITE; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_WRITABLEAUXILIARIES)) { - properties |= - device::BluetoothGattCharacteristic::PROPERTY_WRITABLE_AUXILIARIES; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_ENCRYPTREAD)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_READ_ENCRYPTED; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_ENCRYPTWRITE)) { - properties |= device::BluetoothGattCharacteristic::PROPERTY_WRITE_ENCRYPTED; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_ENCRYPTAUTHENTICATEDREAD)) { - properties |= device::BluetoothGattCharacteristic:: - PROPERTY_READ_ENCRYPTED_AUTHENTICATED; - } - - if (HasProperty(api_properties, - apibtle::CHARACTERISTIC_PROPERTY_ENCRYPTAUTHENTICATEDWRITE)) { - properties |= device::BluetoothGattCharacteristic:: - PROPERTY_WRITE_ENCRYPTED_AUTHENTICATED; - } - - return properties; -} - -device::BluetoothGattCharacteristic::Permissions GetBluetoothPermissions( - const std::vector<apibtle::DescriptorPermission>& api_permissions) { - device::BluetoothGattCharacteristic::Permissions permissions = - device::BluetoothGattCharacteristic::PERMISSION_NONE; - - static_assert( - apibtle::DESCRIPTOR_PERMISSION_LAST == 6, - "Update required if the number of descriptor permissions changes."); - - if (HasPermission(api_permissions, apibtle::DESCRIPTOR_PERMISSION_READ)) { - permissions |= device::BluetoothGattCharacteristic::PERMISSION_READ; - } - - if (HasPermission(api_permissions, apibtle::DESCRIPTOR_PERMISSION_WRITE)) { - permissions |= device::BluetoothGattCharacteristic::PERMISSION_WRITE; - } - - if (HasPermission(api_permissions, - apibtle::DESCRIPTOR_PERMISSION_ENCRYPTEDREAD)) { - permissions |= - device::BluetoothGattCharacteristic::PERMISSION_READ_ENCRYPTED; - } - - if (HasPermission(api_permissions, - apibtle::DESCRIPTOR_PERMISSION_ENCRYPTEDWRITE)) { - permissions |= - device::BluetoothGattCharacteristic::PERMISSION_WRITE_ENCRYPTED; - } - - if (HasPermission( - api_permissions, - apibtle::DESCRIPTOR_PERMISSION_ENCRYPTEDAUTHENTICATEDREAD)) { - permissions |= device::BluetoothGattCharacteristic:: - PERMISSION_READ_ENCRYPTED_AUTHENTICATED; - } - - if (HasPermission( - api_permissions, - apibtle::DESCRIPTOR_PERMISSION_ENCRYPTEDAUTHENTICATEDWRITE)) { - permissions |= device::BluetoothGattCharacteristic:: - PERMISSION_WRITE_ENCRYPTED_AUTHENTICATED; - } - - return permissions; -} - -bool IsAutoLaunchedKioskApp(const ExtensionId& id) { -#if defined(OS_CHROMEOS) - chromeos::KioskAppManager::App app_info; - return chromeos::KioskAppManager::Get()->GetApp(id, &app_info) && - app_info.was_auto_launched_with_zero_delay; -#else - return false; -#endif -} - -bool IsPeripheralFlagEnabled() { - return base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableBLEAdvertising); -} - -} // namespace - - -static base::LazyInstance<BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI> > - g_factory = LAZY_INSTANCE_INITIALIZER; - -// static -BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>* -BluetoothLowEnergyAPI::GetFactoryInstance() { - return g_factory.Pointer(); -} - -// static -BluetoothLowEnergyAPI* BluetoothLowEnergyAPI::Get(BrowserContext* context) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return GetFactoryInstance()->Get(context); -} - -BluetoothLowEnergyAPI::BluetoothLowEnergyAPI(BrowserContext* context) - : event_router_(new BluetoothLowEnergyEventRouter(context)) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); -} - -BluetoothLowEnergyAPI::~BluetoothLowEnergyAPI() { -} - -void BluetoothLowEnergyAPI::Shutdown() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); -} - -namespace api { - -BluetoothLowEnergyExtensionFunctionDeprecated:: - BluetoothLowEnergyExtensionFunctionDeprecated() {} - -BluetoothLowEnergyExtensionFunctionDeprecated:: - ~BluetoothLowEnergyExtensionFunctionDeprecated() {} - -bool BluetoothLowEnergyExtensionFunctionDeprecated::RunAsync() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (!BluetoothManifestData::CheckLowEnergyPermitted(extension())) { - error_ = kErrorPermissionDenied; - return false; - } - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - if (!event_router->IsBluetoothSupported()) { - SetError(kErrorPlatformNotSupported); - return false; - } - - // It is safe to pass |this| here as ExtensionFunction is refcounted. - if (!event_router->InitializeAdapterAndInvokeCallback(base::Bind( - &DoWorkCallback<bool>, - base::Bind(&BluetoothLowEnergyExtensionFunctionDeprecated::DoWork, - this)))) { - SetError(kErrorAdapterNotInitialized); - return false; - } - - return true; -} - -BluetoothLowEnergyExtensionFunction::BluetoothLowEnergyExtensionFunction() - : event_router_(nullptr) {} - -BluetoothLowEnergyExtensionFunction::~BluetoothLowEnergyExtensionFunction() {} - -ExtensionFunction::ResponseAction BluetoothLowEnergyExtensionFunction::Run() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (!BluetoothManifestData::CheckLowEnergyPermitted(extension())) - return RespondNow(Error(kErrorPermissionDenied)); - - event_router_ = GetEventRouter(browser_context()); - if (!event_router_->IsBluetoothSupported()) - return RespondNow(Error(kErrorPlatformNotSupported)); - - // It is safe to pass |this| here as ExtensionFunction is refcounted. - if (!event_router_->InitializeAdapterAndInvokeCallback(base::Bind( - &DoWorkCallback<void>, - base::Bind(&BluetoothLowEnergyExtensionFunction::PreDoWork, this)))) { - // DoWork will respond when the adapter gets initialized. - return RespondNow(Error(kErrorAdapterNotInitialized)); - } - - return RespondLater(); -} - -void BluetoothLowEnergyExtensionFunction::PreDoWork() { - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router_->HasAdapter()) { - Respond(Error(kErrorAdapterNotInitialized)); - return; - } - DoWork(); -} - -template <typename Params> -BLEPeripheralExtensionFunction<Params>::BLEPeripheralExtensionFunction() {} - -template <typename Params> -BLEPeripheralExtensionFunction<Params>::~BLEPeripheralExtensionFunction() {} - -template <typename Params> -ExtensionFunction::ResponseAction -BLEPeripheralExtensionFunction<Params>::Run() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - // Check permissions in manifest. - if (!BluetoothManifestData::CheckPeripheralPermitted(extension())) - return RespondNow(Error(kErrorPermissionDenied)); - - if (!(IsAutoLaunchedKioskApp(extension()->id()) || - IsPeripheralFlagEnabled())) { - return RespondNow(Error(kErrorPermissionDenied)); - } - -// Causes link error on Windows. API will never be on Windows, so #ifdefing. -#if !defined(OS_WIN) - params_ = Params::Create(*args_); - EXTENSION_FUNCTION_VALIDATE(params_.get() != NULL); -#endif - - return BluetoothLowEnergyExtensionFunction::Run(); -} - -bool BluetoothLowEnergyConnectFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::Connect::Params> params( - apibtle::Connect::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - bool persistent = false; // Not persistent by default. - apibtle::ConnectProperties* properties = params.get()->properties.get(); - if (properties) - persistent = properties->persistent; - - event_router->Connect( - persistent, - extension(), - params->device_address, - base::Bind(&BluetoothLowEnergyConnectFunction::SuccessCallback, this), - base::Bind(&BluetoothLowEnergyConnectFunction::ErrorCallback, this)); - - return true; -} - -void BluetoothLowEnergyConnectFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyConnectFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyDisconnectFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::Disconnect::Params> params( - apibtle::Disconnect::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - event_router->Disconnect( - extension(), - params->device_address, - base::Bind(&BluetoothLowEnergyDisconnectFunction::SuccessCallback, this), - base::Bind(&BluetoothLowEnergyDisconnectFunction::ErrorCallback, this)); - - return true; -} - -void BluetoothLowEnergyDisconnectFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyDisconnectFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyGetServiceFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetService::Params> params( - apibtle::GetService::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - apibtle::Service service; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetService(params->service_id, &service); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - results_ = apibtle::GetService::Results::Create(service); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetServicesFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetServices::Params> params( - apibtle::GetServices::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::ServiceList service_list; - if (!event_router->GetServices(params->device_address, &service_list)) { - SetError(kErrorNotFound); - SendResponse(false); - return false; - } - - results_ = apibtle::GetServices::Results::Create(service_list); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetCharacteristicFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetCharacteristic::Params> params( - apibtle::GetCharacteristic::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - apibtle::Characteristic characteristic; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetCharacteristic( - extension(), params->characteristic_id, &characteristic); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetCharacteristic::Result::Create as it doesn't convert lists of - // enums correctly. - SetResult(apibtle::CharacteristicToValue(&characteristic)); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetCharacteristicsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetCharacteristics::Params> params( - apibtle::GetCharacteristics::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::CharacteristicList characteristic_list; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetCharacteristics( - extension(), params->service_id, &characteristic_list); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetCharacteristics::Result::Create as it doesn't convert lists of - // enums correctly. - std::unique_ptr<base::ListValue> result(new base::ListValue()); - for (apibtle::Characteristic& characteristic : characteristic_list) - result->Append(apibtle::CharacteristicToValue(&characteristic)); - - SetResult(std::move(result)); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetIncludedServicesFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetIncludedServices::Params> params( - apibtle::GetIncludedServices::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::ServiceList service_list; - BluetoothLowEnergyEventRouter::Status status = - event_router->GetIncludedServices(params->service_id, &service_list); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - results_ = apibtle::GetIncludedServices::Results::Create(service_list); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetDescriptorFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetDescriptor::Params> params( - apibtle::GetDescriptor::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - apibtle::Descriptor descriptor; - BluetoothLowEnergyEventRouter::Status status = event_router->GetDescriptor( - extension(), params->descriptor_id, &descriptor); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetDescriptor::Result::Create as it doesn't convert lists of enums - // correctly. - SetResult(apibtle::DescriptorToValue(&descriptor)); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyGetDescriptorsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::GetDescriptors::Params> params( - apibtle::GetDescriptors::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothLowEnergyEventRouter::DescriptorList descriptor_list; - BluetoothLowEnergyEventRouter::Status status = event_router->GetDescriptors( - extension(), params->characteristic_id, &descriptor_list); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return false; - } - - // Manually construct the result instead of using - // apibtle::GetDescriptors::Result::Create as it doesn't convert lists of - // enums correctly. - std::unique_ptr<base::ListValue> result(new base::ListValue()); - for (apibtle::Descriptor& descriptor : descriptor_list) - result->Append(apibtle::DescriptorToValue(&descriptor)); - - SetResult(std::move(result)); - SendResponse(true); - - return true; -} - -bool BluetoothLowEnergyReadCharacteristicValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::ReadCharacteristicValue::Params> params( - apibtle::ReadCharacteristicValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - instance_id_ = params->characteristic_id; - event_router->ReadCharacteristicValue( - extension(), - instance_id_, - base::Bind( - &BluetoothLowEnergyReadCharacteristicValueFunction::SuccessCallback, - this), - base::Bind( - &BluetoothLowEnergyReadCharacteristicValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyReadCharacteristicValueFunction::SuccessCallback() { - // Obtain info on the characteristic and see whether or not the characteristic - // is still around. - apibtle::Characteristic characteristic; - BluetoothLowEnergyEventRouter::Status status = - GetEventRouter(browser_context()) - ->GetCharacteristic(extension(), instance_id_, &characteristic); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return; - } - - // Manually construct the result instead of using - // apibtle::GetCharacteristic::Result::Create as it doesn't convert lists of - // enums correctly. - SetResult(apibtle::CharacteristicToValue(&characteristic)); - SendResponse(true); -} - -void BluetoothLowEnergyReadCharacteristicValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyWriteCharacteristicValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::WriteCharacteristicValue::Params> params( - apibtle::WriteCharacteristicValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - std::vector<uint8_t> value(params->value.begin(), params->value.end()); - event_router->WriteCharacteristicValue( - extension(), - params->characteristic_id, - value, - base::Bind( - &BluetoothLowEnergyWriteCharacteristicValueFunction::SuccessCallback, - this), - base::Bind( - &BluetoothLowEnergyWriteCharacteristicValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyWriteCharacteristicValueFunction::SuccessCallback() { - results_ = apibtle::WriteCharacteristicValue::Results::Create(); - SendResponse(true); -} - -void BluetoothLowEnergyWriteCharacteristicValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyStartCharacteristicNotificationsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::StartCharacteristicNotifications::Params> params( - apibtle::StartCharacteristicNotifications::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - bool persistent = false; // Not persistent by default. - apibtle::NotificationProperties* properties = params.get()->properties.get(); - if (properties) - persistent = properties->persistent; - - event_router->StartCharacteristicNotifications( - persistent, - extension(), - params->characteristic_id, - base::Bind(&BluetoothLowEnergyStartCharacteristicNotificationsFunction:: - SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyStartCharacteristicNotificationsFunction:: - ErrorCallback, - this)); - - return true; -} - -void -BluetoothLowEnergyStartCharacteristicNotificationsFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyStartCharacteristicNotificationsFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyStopCharacteristicNotificationsFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::StopCharacteristicNotifications::Params> params( - apibtle::StopCharacteristicNotifications::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - event_router->StopCharacteristicNotifications( - extension(), - params->characteristic_id, - base::Bind(&BluetoothLowEnergyStopCharacteristicNotificationsFunction:: - SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyStopCharacteristicNotificationsFunction:: - ErrorCallback, - this)); - - return true; -} - -void -BluetoothLowEnergyStopCharacteristicNotificationsFunction::SuccessCallback() { - SendResponse(true); -} - -void BluetoothLowEnergyStopCharacteristicNotificationsFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyReadDescriptorValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::ReadDescriptorValue::Params> params( - apibtle::ReadDescriptorValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - instance_id_ = params->descriptor_id; - event_router->ReadDescriptorValue( - extension(), - instance_id_, - base::Bind( - &BluetoothLowEnergyReadDescriptorValueFunction::SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyReadDescriptorValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyReadDescriptorValueFunction::SuccessCallback() { - // Obtain info on the descriptor and see whether or not the descriptor is - // still around. - apibtle::Descriptor descriptor; - BluetoothLowEnergyEventRouter::Status status = - GetEventRouter(browser_context()) - ->GetDescriptor(extension(), instance_id_, &descriptor); - if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) { - SetError(StatusToString(status)); - SendResponse(false); - return; - } - - // Manually construct the result instead of using - // apibtle::GetDescriptor::Results::Create as it doesn't convert lists of - // enums correctly. - SetResult(apibtle::DescriptorToValue(&descriptor)); - SendResponse(true); -} - -void BluetoothLowEnergyReadDescriptorValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -bool BluetoothLowEnergyWriteDescriptorValueFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::WriteDescriptorValue::Params> params( - apibtle::WriteDescriptorValue::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - std::vector<uint8_t> value(params->value.begin(), params->value.end()); - event_router->WriteDescriptorValue( - extension(), - params->descriptor_id, - value, - base::Bind( - &BluetoothLowEnergyWriteDescriptorValueFunction::SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyWriteDescriptorValueFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyWriteDescriptorValueFunction::SuccessCallback() { - results_ = apibtle::WriteDescriptorValue::Results::Create(); - SendResponse(true); -} - -void BluetoothLowEnergyWriteDescriptorValueFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - SetError(StatusToString(status)); - SendResponse(false); -} - -BluetoothLowEnergyAdvertisementFunction:: - BluetoothLowEnergyAdvertisementFunction() - : advertisements_manager_(nullptr) { -} - -BluetoothLowEnergyAdvertisementFunction:: - ~BluetoothLowEnergyAdvertisementFunction() { -} - -int BluetoothLowEnergyAdvertisementFunction::AddAdvertisement( - BluetoothApiAdvertisement* advertisement) { - DCHECK(advertisements_manager_); - return advertisements_manager_->Add(advertisement); -} - -BluetoothApiAdvertisement* -BluetoothLowEnergyAdvertisementFunction::GetAdvertisement( - int advertisement_id) { - DCHECK(advertisements_manager_); - return advertisements_manager_->Get(extension_id(), advertisement_id); -} - -void BluetoothLowEnergyAdvertisementFunction::RemoveAdvertisement( - int advertisement_id) { - DCHECK(advertisements_manager_); - advertisements_manager_->Remove(extension_id(), advertisement_id); -} - -bool BluetoothLowEnergyAdvertisementFunction::RunAsync() { - Initialize(); - return BluetoothLowEnergyExtensionFunctionDeprecated::RunAsync(); -} - -void BluetoothLowEnergyAdvertisementFunction::Initialize() { - advertisements_manager_ = - ApiResourceManager<BluetoothApiAdvertisement>::Get(browser_context()); -} - -// RegisterAdvertisement: - -bool BluetoothLowEnergyRegisterAdvertisementFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - // Check permissions in manifest. - if (!BluetoothManifestData::CheckPeripheralPermitted(extension())) { - error_ = kErrorPermissionDenied; - SendResponse(false); - return false; - } - - // For this API to be available the app has to be either auto - // launched in Kiosk Mode or the enable-ble-advertisement-in-apps - // should be set. - if (!(IsAutoLaunchedKioskApp(extension()->id()) || - IsPeripheralFlagEnabled())) { - error_ = kErrorPermissionDenied; - SendResponse(false); - return false; - } - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // The adapter must be initialized at this point, but return an error instead - // of asserting. - if (!event_router->HasAdapter()) { - SetError(kErrorAdapterNotInitialized); - SendResponse(false); - return false; - } - - std::unique_ptr<apibtle::RegisterAdvertisement::Params> params( - apibtle::RegisterAdvertisement::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - std::unique_ptr<device::BluetoothAdvertisement::Data> advertisement_data( - new device::BluetoothAdvertisement::Data( - params->advertisement.type == - apibtle::AdvertisementType::ADVERTISEMENT_TYPE_BROADCAST - ? device::BluetoothAdvertisement::AdvertisementType:: - ADVERTISEMENT_TYPE_BROADCAST - : device::BluetoothAdvertisement::AdvertisementType:: - ADVERTISEMENT_TYPE_PERIPHERAL)); - - advertisement_data->set_service_uuids( - std::move(params->advertisement.service_uuids)); - advertisement_data->set_solicit_uuids( - std::move(params->advertisement.solicit_uuids)); - if (params->advertisement.manufacturer_data) { - advertisement_data->set_manufacturer_data( - CreateManufacturerData(params->advertisement.manufacturer_data.get())); - } - if (params->advertisement.service_data) { - advertisement_data->set_service_data( - CreateServiceData(params->advertisement.service_data.get())); - } - - event_router->adapter()->RegisterAdvertisement( - std::move(advertisement_data), - base::Bind( - &BluetoothLowEnergyRegisterAdvertisementFunction::SuccessCallback, - this), - base::Bind( - &BluetoothLowEnergyRegisterAdvertisementFunction::ErrorCallback, - this)); - - return true; -} - -void BluetoothLowEnergyRegisterAdvertisementFunction::SuccessCallback( - scoped_refptr<device::BluetoothAdvertisement> advertisement) { - results_ = apibtle::RegisterAdvertisement::Results::Create(AddAdvertisement( - new BluetoothApiAdvertisement(extension_id(), advertisement))); - SendResponse(true); -} - -void BluetoothLowEnergyRegisterAdvertisementFunction::ErrorCallback( - device::BluetoothAdvertisement::ErrorCode status) { - switch (status) { - case device::BluetoothAdvertisement::ErrorCode:: - ERROR_ADVERTISEMENT_ALREADY_EXISTS: - SetError(kStatusAdvertisementAlreadyExists); - break; - case device::BluetoothAdvertisement::ErrorCode:: - ERROR_ADVERTISEMENT_INVALID_LENGTH: - SetError(kErrorInvalidAdvertisementLength); - break; - default: - SetError(kErrorOperationFailed); - } - SendResponse(false); -} - -// UnregisterAdvertisement: - -bool BluetoothLowEnergyUnregisterAdvertisementFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - // Check permission in the manifest. - if (!BluetoothManifestData::CheckPeripheralPermitted(extension())) { - error_ = kErrorPermissionDenied; - SendResponse(false); - return false; - } - - // For this API to be available the app has to be either auto - // launched in Kiosk Mode or the enable-ble-advertisement-in-apps - // should be set. - if (!(IsAutoLaunchedKioskApp(extension()->id()) || - IsPeripheralFlagEnabled())) { - error_ = kErrorPermissionDenied; - SendResponse(false); - return false; - } - - BluetoothLowEnergyEventRouter* event_router = - GetEventRouter(browser_context()); - - // If we don't have an initialized adapter, unregistering is a no-op. - if (!event_router->HasAdapter()) - return true; - - std::unique_ptr<apibtle::UnregisterAdvertisement::Params> params( - apibtle::UnregisterAdvertisement::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get() != NULL); - - BluetoothApiAdvertisement* advertisement = - GetAdvertisement(params->advertisement_id); - if (!advertisement) { - error_ = kStatusAdvertisementDoesNotExist; - SendResponse(false); - return false; - } - - advertisement->advertisement()->Unregister( - base::Bind( - &BluetoothLowEnergyUnregisterAdvertisementFunction::SuccessCallback, - this, params->advertisement_id), - base::Bind( - &BluetoothLowEnergyUnregisterAdvertisementFunction::ErrorCallback, - this, params->advertisement_id)); - - return true; -} - -void BluetoothLowEnergyUnregisterAdvertisementFunction::SuccessCallback( - int advertisement_id) { - RemoveAdvertisement(advertisement_id); - SendResponse(true); -} - -void BluetoothLowEnergyUnregisterAdvertisementFunction::ErrorCallback( - int advertisement_id, - device::BluetoothAdvertisement::ErrorCode status) { - RemoveAdvertisement(advertisement_id); - switch (status) { - case device::BluetoothAdvertisement::ErrorCode:: - ERROR_ADVERTISEMENT_DOES_NOT_EXIST: - SetError(kStatusAdvertisementDoesNotExist); - break; - default: - SetError(kErrorOperationFailed); - } - SendResponse(false); -} - -// createService: - -template class BLEPeripheralExtensionFunction<apibtle::CreateService::Params>; - -void BluetoothLowEnergyCreateServiceFunction::DoWork() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); -// Causes link error on Windows. API will never be on Windows, so #ifdefing. -// TODO: Ideally this should be handled by our feature system, so that this -// code doesn't even compile on OSes it isn't being used on, but currently this -// is not possible. -#if !defined(OS_WIN) - base::WeakPtr<device::BluetoothLocalGattService> service = - device::BluetoothLocalGattService::Create( - event_router_->adapter(), - device::BluetoothUUID(params_->service.uuid), - params_->service.is_primary, nullptr, event_router_); - - event_router_->AddServiceToApp(extension_id(), service->GetIdentifier()); - Respond(ArgumentList( - apibtle::CreateService::Results::Create(service->GetIdentifier()))); -#else - Respond(Error(kErrorPlatformNotSupported)); -#endif -} - -// createCharacteristic: - -template class BLEPeripheralExtensionFunction< - apibtle::CreateCharacteristic::Params>; - -void BluetoothLowEnergyCreateCharacteristicFunction::DoWork() { - device::BluetoothLocalGattService* service = - event_router_->adapter()->GetGattService(params_->service_id); - if (!service) { - Respond(Error(kErrorInvalidServiceId)); - return; - } - - base::WeakPtr<device::BluetoothLocalGattCharacteristic> characteristic = - device::BluetoothLocalGattCharacteristic::Create( - device::BluetoothUUID(params_->characteristic.uuid), - GetBluetoothProperties(params_->characteristic.properties), - device::BluetoothGattCharacteristic::Permissions(), service); - - // Keep a track of this characteristic so we can look it up later if a - // descriptor lists it as its parent. - event_router_->AddLocalCharacteristic(characteristic->GetIdentifier(), - service->GetIdentifier()); - - Respond(ArgumentList(apibtle::CreateCharacteristic::Results::Create( - characteristic->GetIdentifier()))); -} - -// createDescriptor: - -template class BLEPeripheralExtensionFunction< - apibtle::CreateDescriptor::Params>; - -void BluetoothLowEnergyCreateDescriptorFunction::DoWork() { - device::BluetoothLocalGattCharacteristic* characteristic = - event_router_->GetLocalCharacteristic(params_->characteristic_id); - if (!characteristic) { - Respond(Error(kErrorInvalidCharacteristicId)); - return; - } - - base::WeakPtr<device::BluetoothLocalGattDescriptor> descriptor = - device::BluetoothLocalGattDescriptor::Create( - device::BluetoothUUID(params_->descriptor.uuid), - GetBluetoothPermissions(params_->descriptor.permissions), - characteristic); - - Respond(ArgumentList( - apibtle::CreateDescriptor::Results::Create(descriptor->GetIdentifier()))); -} - -// registerService: - -template class BLEPeripheralExtensionFunction<apibtle::RegisterService::Params>; - -void BluetoothLowEnergyRegisterServiceFunction::DoWork() { - event_router_->RegisterGattService( - extension(), params_->service_id, - base::Bind(&BluetoothLowEnergyRegisterServiceFunction::SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyRegisterServiceFunction::ErrorCallback, - this)); -} - -void BluetoothLowEnergyRegisterServiceFunction::SuccessCallback() { - Respond(NoArguments()); -} - -void BluetoothLowEnergyRegisterServiceFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - Respond(Error(StatusToString(status))); -} - -// unregisterService: - -template class BLEPeripheralExtensionFunction< - apibtle::UnregisterService::Params>; - -void BluetoothLowEnergyUnregisterServiceFunction::DoWork() { - event_router_->UnregisterGattService( - extension(), params_->service_id, - base::Bind(&BluetoothLowEnergyUnregisterServiceFunction::SuccessCallback, - this), - base::Bind(&BluetoothLowEnergyUnregisterServiceFunction::ErrorCallback, - this)); -} - -void BluetoothLowEnergyUnregisterServiceFunction::SuccessCallback() { - Respond(NoArguments()); -} - -void BluetoothLowEnergyUnregisterServiceFunction::ErrorCallback( - BluetoothLowEnergyEventRouter::Status status) { - Respond(Error(StatusToString(status))); -} - -// notifyCharacteristicValueChanged: - -template class BLEPeripheralExtensionFunction< - apibtle::NotifyCharacteristicValueChanged::Params>; - -void BluetoothLowEnergyNotifyCharacteristicValueChangedFunction::DoWork() { - device::BluetoothLocalGattCharacteristic* characteristic = - event_router_->GetLocalCharacteristic(params_->characteristic_id); - if (!characteristic) { - Respond(Error(kErrorInvalidCharacteristicId)); - return; - } - std::vector<uint8_t> uint8_vector; - uint8_vector.assign(params_->notification.value.begin(), - params_->notification.value.end()); - - bool indicate = params_->notification.should_indicate.get() - ? *params_->notification.should_indicate - : false; - device::BluetoothLocalGattCharacteristic::NotificationStatus status = - characteristic->NotifyValueChanged(nullptr, uint8_vector, indicate); - - switch (status) { - case device::BluetoothLocalGattCharacteristic::NOTIFICATION_SUCCESS: - Respond(NoArguments()); - break; - case device::BluetoothLocalGattCharacteristic::NOTIFY_PROPERTY_NOT_SET: - Respond(Error(kErrorNotifyPropertyNotSet)); - break; - case device::BluetoothLocalGattCharacteristic::INDICATE_PROPERTY_NOT_SET: - Respond(Error(kErrorIndicatePropertyNotSet)); - break; - case device::BluetoothLocalGattCharacteristic::SERVICE_NOT_REGISTERED: - Respond(Error(kErrorServiceNotRegistered)); - break; - default: - LOG(ERROR) << "Unknown notification error!"; - Respond(Error(kErrorUnknownNotificationError)); - } -} - -// removeService: - -template class BLEPeripheralExtensionFunction<apibtle::RemoveService::Params>; - -void BluetoothLowEnergyRemoveServiceFunction::DoWork() { - device::BluetoothLocalGattService* service = - event_router_->adapter()->GetGattService(params_->service_id); - if (!service) { - Respond(Error(kErrorInvalidServiceId)); - return; - } - event_router_->RemoveServiceFromApp(extension_id(), service->GetIdentifier()); - service->Delete(); - Respond(NoArguments()); -} - -// sendRequestResponse: - -template class BLEPeripheralExtensionFunction< - apibtle::SendRequestResponse::Params>; - -void BluetoothLowEnergySendRequestResponseFunction::DoWork() { - std::vector<uint8_t> uint8_vector; - if (params_->response.value) { - uint8_vector.assign(params_->response.value->begin(), - params_->response.value->end()); - } - event_router_->HandleRequestResponse( - extension(), params_->response.request_id, params_->response.is_error, - uint8_vector); - Respond(NoArguments()); -} - -} // namespace api -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.h b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.h deleted file mode 100644 index 277a5fb575e..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.h +++ /dev/null @@ -1,620 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_API_H_ - -#include <string> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_api_advertisement.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" -#include "content/public/browser/browser_context.h" -#include "device/bluetooth/bluetooth_advertisement.h" -#include "extensions/browser/api/api_resource_manager.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/extension_function_histogram_value.h" - -namespace extensions { -class BluetoothApiAdvertisement; -class BluetoothLowEnergyEventRouter; - -namespace api { -namespace bluetooth_low_energy { -namespace CreateService { -struct Params; -} -namespace CreateCharacteristic { -struct Params; -} -namespace CreateDescriptor { -struct Params; -} -namespace RegisterService { -struct Params; -} -namespace UnregisterService { -struct Params; -} -namespace NotifyCharacteristicValueChanged { -struct Params; -} -namespace RemoveService { -struct Params; -} -namespace SendRequestResponse { -struct Params; -} -} // namespace bluetooth_low_energy -} // namespace api - -// The profile-keyed service that manages the bluetoothLowEnergy extension API. -class BluetoothLowEnergyAPI : public BrowserContextKeyedAPI { - public: - static BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>* - GetFactoryInstance(); - - // Convenience method to get the BluetoothLowEnergy API for a browser context. - static BluetoothLowEnergyAPI* Get(content::BrowserContext* context); - - explicit BluetoothLowEnergyAPI(content::BrowserContext* context); - ~BluetoothLowEnergyAPI() override; - - // KeyedService implementation.. - void Shutdown() override; - - BluetoothLowEnergyEventRouter* event_router() const { - return event_router_.get(); - } - - // BrowserContextKeyedAPI implementation. - static const char* service_name() { return "BluetoothLowEnergyAPI"; } - static const bool kServiceRedirectedInIncognito = true; - static const bool kServiceIsNULLWhileTesting = true; - - private: - friend class BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>; - - std::unique_ptr<BluetoothLowEnergyEventRouter> event_router_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyAPI); -}; - -namespace api { - -// Base class for bluetoothLowEnergy API functions. This class handles some of -// the common logic involved in all API functions, such as checking for -// platform support and returning the correct error. -// -// DEPRECATED: This inherits from AsyncExtensionFunction, which we're trying to -// get rid of for various reasons. Please inherit from the -// BluetoothLowEnergyExtensionFunction class instead. -class BluetoothLowEnergyExtensionFunctionDeprecated - : public AsyncExtensionFunction { - public: - BluetoothLowEnergyExtensionFunctionDeprecated(); - - protected: - ~BluetoothLowEnergyExtensionFunctionDeprecated() override; - - // AsyncExtensionFunction override. - bool RunAsync() override; - - // Implemented by individual bluetoothLowEnergy extension functions to perform - // the body of the function. This invoked asynchonously after RunAsync after - // the BluetoothLowEnergyEventRouter has obtained a handle on the - // BluetoothAdapter. - virtual bool DoWork() = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyExtensionFunctionDeprecated); -}; - -// Replacement for BluetoothLowEnergyExtensionFunctionDeprecated. Has the same -// functionality except that instead of the SendResponse/return combo, we'll -// return our response with Respond(). -class BluetoothLowEnergyExtensionFunction : public UIThreadExtensionFunction { - public: - BluetoothLowEnergyExtensionFunction(); - - protected: - ~BluetoothLowEnergyExtensionFunction() override; - - // ExtensionFunction override. - ResponseAction Run() override; - - // Implemented by individual bluetoothLowEnergy extension functions to perform - // the body of the function. This invoked asynchonously after Run after - // the BluetoothLowEnergyEventRouter has obtained a handle on the - // BluetoothAdapter. - virtual void DoWork() = 0; - - BluetoothLowEnergyEventRouter* event_router_; - - private: - // Internal method to do common setup before actual DoWork is called. - void PreDoWork(); - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyExtensionFunction); -}; - -// Base class for bluetoothLowEnergy API peripheral mode functions. This class -// handles some of the common logic involved in all API peripheral mode -// functions, such as checking for peripheral permissions and returning the -// correct error. -template <typename Params> -class BLEPeripheralExtensionFunction - : public BluetoothLowEnergyExtensionFunction { - public: - BLEPeripheralExtensionFunction(); - - protected: - ~BLEPeripheralExtensionFunction() override; - - // ExtensionFunction override. - ResponseAction Run() override; - -// Causes link error on Windows. API will never be on Windows, so #ifdefing. -#if !defined(OS_WIN) - std::unique_ptr<Params> params_; -#else - Params* params_; -#endif - - private: - DISALLOW_COPY_AND_ASSIGN(BLEPeripheralExtensionFunction); -}; - -class BluetoothLowEnergyConnectFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.connect", - BLUETOOTHLOWENERGY_CONNECT); - - protected: - ~BluetoothLowEnergyConnectFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::Connect. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyDisconnectFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.disconnect", - BLUETOOTHLOWENERGY_DISCONNECT); - - protected: - ~BluetoothLowEnergyDisconnectFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::Disconnect. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyGetServiceFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getService", - BLUETOOTHLOWENERGY_GETSERVICE); - - protected: - ~BluetoothLowEnergyGetServiceFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetServicesFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getServices", - BLUETOOTHLOWENERGY_GETSERVICES); - - protected: - ~BluetoothLowEnergyGetServicesFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetCharacteristicFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getCharacteristic", - BLUETOOTHLOWENERGY_GETCHARACTERISTIC); - - protected: - ~BluetoothLowEnergyGetCharacteristicFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetCharacteristicsFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getCharacteristics", - BLUETOOTHLOWENERGY_GETCHARACTERISTICS); - - protected: - ~BluetoothLowEnergyGetCharacteristicsFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetIncludedServicesFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getIncludedServices", - BLUETOOTHLOWENERGY_GETINCLUDEDSERVICES); - - protected: - ~BluetoothLowEnergyGetIncludedServicesFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetDescriptorFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getDescriptor", - BLUETOOTHLOWENERGY_GETDESCRIPTOR); - - protected: - ~BluetoothLowEnergyGetDescriptorFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyGetDescriptorsFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.getDescriptors", - BLUETOOTHLOWENERGY_GETDESCRIPTORS); - - protected: - ~BluetoothLowEnergyGetDescriptorsFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; -}; - -class BluetoothLowEnergyReadCharacteristicValueFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.readCharacteristicValue", - BLUETOOTHLOWENERGY_READCHARACTERISTICVALUE); - - protected: - ~BluetoothLowEnergyReadCharacteristicValueFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::ReadCharacteristicValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested characteristic. - std::string instance_id_; -}; - -class BluetoothLowEnergyWriteCharacteristicValueFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.writeCharacteristicValue", - BLUETOOTHLOWENERGY_WRITECHARACTERISTICVALUE); - - protected: - ~BluetoothLowEnergyWriteCharacteristicValueFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::WriteCharacteristicValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested characteristic. - std::string instance_id_; -}; - -class BluetoothLowEnergyStartCharacteristicNotificationsFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION( - "bluetoothLowEnergy.startCharacteristicNotifications", - BLUETOOTHLOWENERGY_STARTCHARACTERISTICNOTIFICATIONS); - - protected: - ~BluetoothLowEnergyStartCharacteristicNotificationsFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::StartCharacteristicNotifications. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyStopCharacteristicNotificationsFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION( - "bluetoothLowEnergy.stopCharacteristicNotifications", - BLUETOOTHLOWENERGY_STOPCHARACTERISTICNOTIFICATIONS); - - protected: - ~BluetoothLowEnergyStopCharacteristicNotificationsFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::StopCharacteristicNotifications. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyReadDescriptorValueFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.readDescriptorValue", - BLUETOOTHLOWENERGY_READDESCRIPTORVALUE); - - protected: - ~BluetoothLowEnergyReadDescriptorValueFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::ReadDescriptorValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyWriteDescriptorValueFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.writeDescriptorValue", - BLUETOOTHLOWENERGY_WRITEDESCRIPTORVALUE); - - protected: - ~BluetoothLowEnergyWriteDescriptorValueFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::WriteDescriptorValue. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyAdvertisementFunction - : public BluetoothLowEnergyExtensionFunctionDeprecated { - public: - BluetoothLowEnergyAdvertisementFunction(); - - protected: - ~BluetoothLowEnergyAdvertisementFunction() override; - - // Takes ownership. - int AddAdvertisement(BluetoothApiAdvertisement* advertisement); - BluetoothApiAdvertisement* GetAdvertisement(int advertisement_id); - void RemoveAdvertisement(int advertisement_id); - - // ExtensionFunction override. - bool RunAsync() override; - - private: - void Initialize(); - - ApiResourceManager<BluetoothApiAdvertisement>* advertisements_manager_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyAdvertisementFunction); -}; - -class BluetoothLowEnergyRegisterAdvertisementFunction - : public BluetoothLowEnergyAdvertisementFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.registerAdvertisement", - BLUETOOTHLOWENERGY_REGISTERADVERTISEMENT); - - protected: - ~BluetoothLowEnergyRegisterAdvertisementFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - void SuccessCallback(scoped_refptr<device::BluetoothAdvertisement>); - void ErrorCallback(device::BluetoothAdvertisement::ErrorCode status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyUnregisterAdvertisementFunction - : public BluetoothLowEnergyAdvertisementFunction { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.unregisterAdvertisement", - BLUETOOTHLOWENERGY_UNREGISTERADVERTISEMENT); - - protected: - ~BluetoothLowEnergyUnregisterAdvertisementFunction() override {} - - // BluetoothLowEnergyExtensionFunctionDeprecated override. - bool DoWork() override; - - private: - void SuccessCallback(int advertisement_id); - void ErrorCallback(int advertisement_id, - device::BluetoothAdvertisement::ErrorCode status); - - // The instance ID of the requested descriptor. - std::string instance_id_; -}; - -class BluetoothLowEnergyCreateServiceFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::CreateService::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.createService", - BLUETOOTHLOWENERGY_CREATESERVICE); - - protected: - ~BluetoothLowEnergyCreateServiceFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; -}; - -class BluetoothLowEnergyCreateCharacteristicFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::CreateCharacteristic::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.createCharacteristic", - BLUETOOTHLOWENERGY_CREATECHARACTERISTIC); - - protected: - ~BluetoothLowEnergyCreateCharacteristicFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; -}; - -class BluetoothLowEnergyNotifyCharacteristicValueChangedFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy:: - NotifyCharacteristicValueChanged::Params> { - public: - DECLARE_EXTENSION_FUNCTION( - "bluetoothLowEnergy.notifyCharacteristicValueChanged", - BLUETOOTHLOWENERGY_NOTIFYCHARACTERISTICVALUECHANGED); - - protected: - ~BluetoothLowEnergyNotifyCharacteristicValueChangedFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; -}; - -class BluetoothLowEnergyCreateDescriptorFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::CreateDescriptor::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.createDescriptor", - BLUETOOTHLOWENERGY_CREATEDESCRIPTOR); - - protected: - ~BluetoothLowEnergyCreateDescriptorFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; -}; - -class BluetoothLowEnergyRegisterServiceFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::RegisterService::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.registerService", - BLUETOOTHLOWENERGY_REGISTERSERVICE); - - protected: - ~BluetoothLowEnergyRegisterServiceFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; - - private: - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyUnregisterServiceFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::UnregisterService::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.unregisterService", - BLUETOOTHLOWENERGY_UNREGISTERSERVICE); - - protected: - ~BluetoothLowEnergyUnregisterServiceFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; - - private: - // Success and error callbacks, called by - // BluetoothLowEnergyEventRouter::RegisterService. - void SuccessCallback(); - void ErrorCallback(BluetoothLowEnergyEventRouter::Status status); -}; - -class BluetoothLowEnergyRemoveServiceFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::RemoveService::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.removeService", - BLUETOOTHLOWENERGY_REMOVESERVICE); - - protected: - ~BluetoothLowEnergyRemoveServiceFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; -}; - -class BluetoothLowEnergySendRequestResponseFunction - : public BLEPeripheralExtensionFunction< - extensions::api::bluetooth_low_energy::SendRequestResponse::Params> { - public: - DECLARE_EXTENSION_FUNCTION("bluetoothLowEnergy.sendRequestResponse", - BLUETOOTHLOWENERGY_SENDREQUESTRESPONSE); - - protected: - ~BluetoothLowEnergySendRequestResponseFunction() override {} - - // BluetoothLowEnergyPeripheralExtensionFunction override. - void DoWork() override; -}; - -} // namespace api -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_API_H_ 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 1d7df8a1c46..7cb0a30d441 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 @@ -7,8 +7,6 @@ #include <memory> #include <utility> -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_api.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" #include "chrome/browser/extensions/extension_apitest.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h" @@ -17,6 +15,8 @@ #include "device/bluetooth/test/mock_bluetooth_gatt_descriptor.h" #include "device/bluetooth/test/mock_bluetooth_gatt_notify_session.h" #include "device/bluetooth/test/mock_bluetooth_gatt_service.h" +#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h" +#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" #include "extensions/common/test_util.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" @@ -652,10 +652,10 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, CharacteristicValueChanged) { BluetoothGattNotifySession* session0 = new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId0); + chrc0_->GetWeakPtr()); BluetoothGattNotifySession* session1 = new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId2); + chrc2_->GetWeakPtr()); EXPECT_CALL(*chrc0_, StartNotifySession(_, _)) .Times(1) @@ -1282,10 +1282,10 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, StartStopNotifications) { BluetoothGattNotifySession* session0 = new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId0); + chrc0_->GetWeakPtr()); MockBluetoothGattNotifySession* session1 = new testing::NiceMock<MockBluetoothGattNotifySession>( - kTestCharacteristicId1); + chrc1_->GetWeakPtr()); EXPECT_CALL(*session1, Stop(_)) .Times(1) diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc index 6b5ce5ee676..f279dfe4921 100644 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest_chromeos.cc @@ -108,6 +108,16 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTestChromeOs, << message_; } +IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTestChromeOs, + SetAdvertisingInterval) { + EnterKioskSession(); + SetAutoLaunchApp(); + ASSERT_TRUE( + RunPlatformAppTest("api_test/bluetooth_low_energy/" + "set_advertising_interval")) + << message_; +} + IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTestChromeOs, CreateService) { EnterKioskSession(); SetAutoLaunchApp(); diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc deleted file mode 100644 index 0cfbbe0c157..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.h" - -#include "base/lazy_instance.h" - -namespace extensions { - -static base::LazyInstance<BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyConnection> > > g_factory = - LAZY_INSTANCE_INITIALIZER; - -template <> -BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyConnection> >* -ApiResourceManager<BluetoothLowEnergyConnection>::GetFactoryInstance() { - return g_factory.Pointer(); -} - -BluetoothLowEnergyConnection::BluetoothLowEnergyConnection( - bool persistent, - const std::string& owner_extension_id, - std::unique_ptr<device::BluetoothGattConnection> connection) - : ApiResource(owner_extension_id), - persistent_(persistent), - connection_(connection.release()) {} - -BluetoothLowEnergyConnection::~BluetoothLowEnergyConnection() { -} - -device::BluetoothGattConnection* -BluetoothLowEnergyConnection::GetConnection() const { - return connection_.get(); -} - -bool BluetoothLowEnergyConnection::IsPersistent() const { - return persistent_; -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.h b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.h deleted file mode 100644 index 28e3d9d8a6e..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_CONNECTION_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_CONNECTION_H_ - -#include <memory> - -#include "base/macros.h" -#include "device/bluetooth/bluetooth_gatt_connection.h" -#include "extensions/browser/api/api_resource.h" -#include "extensions/browser/api/api_resource_manager.h" - -namespace extensions { - -// An ApiResource wrapper for a device::BluetoothGattConnection. -class BluetoothLowEnergyConnection : public ApiResource { - public: - explicit BluetoothLowEnergyConnection( - bool persistent, - const std::string& owner_extension_id, - std::unique_ptr<device::BluetoothGattConnection> connection); - ~BluetoothLowEnergyConnection() override; - - // Returns a pointer to the underlying connection object. - device::BluetoothGattConnection* GetConnection() const; - - // ApiResource override. - bool IsPersistent() const override; - - // This resource should be managed on the UI thread. - static const content::BrowserThread::ID kThreadId = - content::BrowserThread::UI; - - private: - friend class ApiResourceManager<BluetoothLowEnergyConnection>; - static const char* service_name() { - return "BluetoothLowEnergyConnectionManager"; - } - - // True, if this resource should be persistent. - bool persistent_; - - // The connection is owned by this instance and will automatically disconnect - // when deleted. - std::unique_ptr<device::BluetoothGattConnection> connection_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyConnection); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_CONNECTION_H_ diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc deleted file mode 100644 index a3e5ae01224..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc +++ /dev/null @@ -1,1929 +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/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h" - -#include <algorithm> -#include <iterator> -#include <utility> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/containers/hash_tables.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_connection.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h" -#include "chrome/browser/extensions/api/bluetooth_low_energy/utils.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" -#include "device/bluetooth/bluetooth_adapter_factory.h" -#include "device/bluetooth/bluetooth_gatt_characteristic.h" -#include "device/bluetooth/bluetooth_gatt_service.h" -#include "device/bluetooth/bluetooth_local_gatt_characteristic.h" -#include "device/bluetooth/bluetooth_local_gatt_descriptor.h" -#include "device/bluetooth/bluetooth_remote_gatt_characteristic.h" -#include "device/bluetooth/bluetooth_remote_gatt_descriptor.h" -#include "extensions/browser/api/api_resource_manager.h" -#include "extensions/browser/event_listener_map.h" -#include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h" -#include "extensions/common/extension.h" - -using content::BrowserThread; - -using device::BluetoothAdapter; -using device::BluetoothAdapterFactory; -using device::BluetoothDevice; -using device::BluetoothRemoteGattCharacteristic; -using device::BluetoothGattConnection; -using device::BluetoothRemoteGattDescriptor; -using device::BluetoothRemoteGattService; - -namespace apibtle = extensions::api::bluetooth_low_energy; - -namespace { - -void PopulateService(const BluetoothRemoteGattService* service, - apibtle::Service* out) { - DCHECK(out); - - out->uuid = service->GetUUID().canonical_value(); - out->is_primary = service->IsPrimary(); - out->instance_id.reset(new std::string(service->GetIdentifier())); - - if (!service->GetDevice()) - return; - - out->device_address.reset( - new std::string(service->GetDevice()->GetAddress())); -} - -void PopulateCharacteristicProperties( - BluetoothRemoteGattCharacteristic::Properties properties, - std::vector<apibtle::CharacteristicProperty>* api_properties) { - DCHECK(api_properties && api_properties->empty()); - - if (properties == BluetoothRemoteGattCharacteristic::PROPERTY_NONE) - return; - - if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_BROADCAST) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_BROADCAST); - if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_READ) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_READ); - if (properties & - BluetoothRemoteGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_WRITEWITHOUTRESPONSE); - } - if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_WRITE) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_WRITE); - if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_NOTIFY); - if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_INDICATE) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_INDICATE); - if (properties & - BluetoothRemoteGattCharacteristic::PROPERTY_AUTHENTICATED_SIGNED_WRITES) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_AUTHENTICATEDSIGNEDWRITES); - } - if (properties & - BluetoothRemoteGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_EXTENDEDPROPERTIES); - } - if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_RELIABLE_WRITE) - api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_RELIABLEWRITE); - if (properties & - BluetoothRemoteGattCharacteristic::PROPERTY_WRITABLE_AUXILIARIES) { - api_properties->push_back( - apibtle::CHARACTERISTIC_PROPERTY_WRITABLEAUXILIARIES); - } -} - -void PopulateCharacteristic( - const BluetoothRemoteGattCharacteristic* characteristic, - apibtle::Characteristic* out) { - DCHECK(out); - - out->uuid = characteristic->GetUUID().canonical_value(); - out->instance_id.reset(new std::string(characteristic->GetIdentifier())); - - out->service = base::WrapUnique(new apibtle::Service()); - PopulateService(characteristic->GetService(), out->service.get()); - PopulateCharacteristicProperties(characteristic->GetProperties(), - &out->properties); - - const std::vector<uint8_t>& value = characteristic->GetValue(); - if (value.empty()) - return; - - out->value.reset(new std::vector<char>(value.begin(), value.end())); -} - -void PopulateDescriptor(const BluetoothRemoteGattDescriptor* descriptor, - apibtle::Descriptor* out) { - DCHECK(out); - - out->uuid = descriptor->GetUUID().canonical_value(); - out->instance_id.reset(new std::string(descriptor->GetIdentifier())); - - out->characteristic = base::WrapUnique(new apibtle::Characteristic()); - PopulateCharacteristic(descriptor->GetCharacteristic(), - out->characteristic.get()); - - const std::vector<uint8_t>& value = descriptor->GetValue(); - if (value.empty()) - return; - - out->value.reset(new std::vector<char>(value.begin(), value.end())); -} - -void PopulateDevice(const device::BluetoothDevice* device, - apibtle::Request* request) { - if (!device) - return; - request->device.address = device->GetAddress(); - request->device.name.reset( - new std::string(base::UTF16ToUTF8(device->GetNameForDisplay()))); - request->device.device_class.reset(new int(device->GetBluetoothClass())); -} - -typedef extensions::ApiResourceManager<extensions::BluetoothLowEnergyConnection> - ConnectionResourceManager; -ConnectionResourceManager* GetConnectionResourceManager( - content::BrowserContext* context) { - ConnectionResourceManager* manager = ConnectionResourceManager::Get(context); - DCHECK(manager) - << "There is no Bluetooth low energy connection manager. " - "If this assertion is failing during a test, then it is likely that " - "TestExtensionSystem is failing to provide an instance of " - "ApiResourceManager<BluetoothLowEnergyConnection>."; - return manager; -} - -typedef extensions::ApiResourceManager< - extensions::BluetoothLowEnergyNotifySession> NotifySessionResourceManager; -NotifySessionResourceManager* GetNotifySessionResourceManager( - content::BrowserContext* context) { - NotifySessionResourceManager* manager = - NotifySessionResourceManager::Get(context); - DCHECK(manager) - << "There is no Bluetooth low energy value update session manager." - "If this assertion is failing during a test, then it is likely that " - "TestExtensionSystem is failing to provide an instance of " - "ApiResourceManager<BluetoothLowEnergyNotifySession>."; - return manager; -} - -// Translates GattErrorCodes to RouterError Codes -extensions::BluetoothLowEnergyEventRouter::Status GattErrorToRouterError( - BluetoothRemoteGattService::GattErrorCode error_code) { - extensions::BluetoothLowEnergyEventRouter::Status error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorFailed; - if (error_code == BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorInProgress; - } else if (error_code == - BluetoothRemoteGattService::GATT_ERROR_INVALID_LENGTH) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorInvalidLength; - } else if (error_code == - BluetoothRemoteGattService::GATT_ERROR_NOT_PERMITTED) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorPermissionDenied; - } else if (error_code == - BluetoothRemoteGattService::GATT_ERROR_NOT_AUTHORIZED) { - error_status = extensions::BluetoothLowEnergyEventRouter:: - kStatusErrorInsufficientAuthorization; - } else if (error_code == BluetoothRemoteGattService::GATT_ERROR_NOT_PAIRED) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorHigherSecurity; - } else if (error_code == - BluetoothRemoteGattService::GATT_ERROR_NOT_SUPPORTED) { - error_status = - extensions::BluetoothLowEnergyEventRouter::kStatusErrorGattNotSupported; - } - - return error_status; -} - -} // namespace - -namespace extensions { - -BluetoothLowEnergyEventRouter::AttributeValueRequest::AttributeValueRequest( - const Delegate::ValueCallback& value_callback, - const Delegate::ErrorCallback& error_callback) { - this->type = ATTRIBUTE_READ_REQUEST; - this->value_callback = value_callback; - this->error_callback = error_callback; -} - -BluetoothLowEnergyEventRouter::AttributeValueRequest::AttributeValueRequest( - const base::Closure& success_callback, - const Delegate::ErrorCallback& error_callback) { - this->type = ATTRIBUTE_WRITE_REQUEST; - this->success_callback = success_callback; - this->error_callback = error_callback; -} - -BluetoothLowEnergyEventRouter::AttributeValueRequest::~AttributeValueRequest() { -} - -BluetoothLowEnergyEventRouter::BluetoothLowEnergyEventRouter( - content::BrowserContext* context) - : adapter_(NULL), - last_callback_request_id_(0), - browser_context_(context), - extension_registry_observer_(this), - weak_ptr_factory_(this) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(browser_context_); - VLOG(1) << "Initializing BluetoothLowEnergyEventRouter."; - - if (!IsBluetoothSupported()) { - VLOG(1) << "Bluetooth not supported on the current platform."; - return; - } - - // Register for unload event so we clean up created services for apps that - // get unloaded. - extension_registry_observer_.Add(ExtensionRegistry::Get(context)); -} - -BluetoothLowEnergyEventRouter::~BluetoothLowEnergyEventRouter() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) - return; - - // Delete any services owned by any apps. This will also unregister them all. - for (const auto& services : app_id_to_service_ids_) { - for (const auto& service_id : services.second) { - device::BluetoothLocalGattService* service = - adapter_->GetGattService(service_id); - if (service) - service->Delete(); - } - } - - adapter_->RemoveObserver(this); - adapter_ = NULL; -} - -bool BluetoothLowEnergyEventRouter::IsBluetoothSupported() const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - return adapter_.get() || - BluetoothAdapterFactory::IsBluetoothAdapterAvailable(); -} - -bool BluetoothLowEnergyEventRouter::InitializeAdapterAndInvokeCallback( - const base::Closure& callback) { - if (!IsBluetoothSupported()) - return false; - - if (adapter_.get()) { - callback.Run(); - return true; - } - - BluetoothAdapterFactory::GetAdapter( - base::Bind(&BluetoothLowEnergyEventRouter::OnGetAdapter, - weak_ptr_factory_.GetWeakPtr(), - callback)); - return true; -} - -bool BluetoothLowEnergyEventRouter::HasAdapter() const { - return (adapter_.get() != NULL); -} - -void BluetoothLowEnergyEventRouter::Connect( - bool persistent, - const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - const std::string connect_id = extension_id + device_address; - - if (connecting_devices_.count(connect_id) != 0) { - error_callback.Run(kStatusErrorInProgress); - return; - } - - BluetoothLowEnergyConnection* conn = - FindConnection(extension_id, device_address); - if (conn) { - if (conn->GetConnection()->IsConnected()) { - VLOG(1) << "Application already connected to device: " << device_address; - error_callback.Run(kStatusErrorAlreadyConnected); - return; - } - - // There is a connection object but it's no longer active. Simply remove it. - RemoveConnection(extension_id, device_address); - } - - BluetoothDevice* device = adapter_->GetDevice(device_address); - if (!device) { - VLOG(1) << "Bluetooth device not found: " << device_address; - error_callback.Run(kStatusErrorNotFound); - return; - } - - connecting_devices_.insert(connect_id); - device->CreateGattConnection( - base::Bind(&BluetoothLowEnergyEventRouter::OnCreateGattConnection, - weak_ptr_factory_.GetWeakPtr(), - persistent, - extension_id, - device_address, - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnConnectError, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - device_address, - error_callback)); -} - -void BluetoothLowEnergyEventRouter::Disconnect( - const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - - BluetoothLowEnergyConnection* conn = - FindConnection(extension_id, device_address); - if (!conn || !conn->GetConnection()->IsConnected()) { - VLOG(1) << "Application not connected to device: " << device_address; - error_callback.Run(kStatusErrorNotConnected); - return; - } - - conn->GetConnection()->Disconnect(); - VLOG(2) << "GATT connection terminated."; - - if (!RemoveConnection(extension_id, device_address)) { - VLOG(1) << "The connection was removed before disconnect completed, id: " - << extension_id << ", device: " << device_address; - } - - callback.Run(); -} - -bool BluetoothLowEnergyEventRouter::GetServices( - const std::string& device_address, - ServiceList* out_services) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(out_services); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return false; - } - - BluetoothDevice* device = adapter_->GetDevice(device_address); - if (!device) { - VLOG(1) << "Bluetooth device not found: " << device_address; - return false; - } - - out_services->clear(); - - for (const BluetoothRemoteGattService* service : device->GetGattServices()) { - // Populate an API service and add it to the return value. - apibtle::Service api_service; - PopulateService(service, &api_service); - out_services->push_back(std::move(api_service)); - } - - return true; -} - -BluetoothLowEnergyEventRouter::Status BluetoothLowEnergyEventRouter::GetService( - const std::string& instance_id, - apibtle::Service* out_service) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(out_service); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothRemoteGattService* gatt_service = FindServiceById(instance_id); - if (!gatt_service) { - VLOG(1) << "Service not found: " << instance_id; - return kStatusErrorNotFound; - } - - PopulateService(gatt_service, out_service); - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetIncludedServices( - const std::string& instance_id, - ServiceList* out_services) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(out_services); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothRemoteGattService* service = FindServiceById(instance_id); - if (!service) { - VLOG(1) << "Service not found: " << instance_id; - return kStatusErrorNotFound; - } - - out_services->clear(); - - for (const BluetoothRemoteGattService* included : - service->GetIncludedServices()) { - // Populate an API service and add it to the return value. - apibtle::Service api_service; - PopulateService(included, &api_service); - out_services->push_back(std::move(api_service)); - } - - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetCharacteristics( - const Extension* extension, - const std::string& instance_id, - CharacteristicList* out_characteristics) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_characteristics); - if (!adapter_.get()) { - VLOG(1) << "BlutoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothRemoteGattService* service = FindServiceById(instance_id); - if (!service) { - VLOG(1) << "Service not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request(service->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access the characteristics of this " - << "service: " << instance_id; - return kStatusErrorPermissionDenied; - } - - out_characteristics->clear(); - - for (const BluetoothRemoteGattCharacteristic* characteristic : - service->GetCharacteristics()) { - // Populate an API characteristic and add it to the return value. - apibtle::Characteristic api_characteristic; - PopulateCharacteristic(characteristic, &api_characteristic); - out_characteristics->push_back(std::move(api_characteristic)); - } - - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetCharacteristic( - const Extension* extension, - const std::string& instance_id, - apibtle::Characteristic* out_characteristic) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_characteristic); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothRemoteGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - return kStatusErrorPermissionDenied; - } - - PopulateCharacteristic(characteristic, out_characteristic); - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetDescriptors( - const Extension* extension, - const std::string& instance_id, - DescriptorList* out_descriptors) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_descriptors); - if (!adapter_.get()) { - VLOG(1) << "BlutoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothRemoteGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access the descriptors of this " - << "characteristic: " << instance_id; - return kStatusErrorPermissionDenied; - } - - out_descriptors->clear(); - - for (const BluetoothRemoteGattDescriptor* descriptor : - characteristic->GetDescriptors()) { - // Populate an API descriptor and add it to the return value. - apibtle::Descriptor api_descriptor; - PopulateDescriptor(descriptor, &api_descriptor); - out_descriptors->push_back(std::move(api_descriptor)); - } - - return kStatusSuccess; -} - -BluetoothLowEnergyEventRouter::Status -BluetoothLowEnergyEventRouter::GetDescriptor( - const Extension* extension, - const std::string& instance_id, - api::bluetooth_low_energy::Descriptor* out_descriptor) const { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - DCHECK(out_descriptor); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - return kStatusErrorFailed; - } - - BluetoothRemoteGattDescriptor* descriptor = FindDescriptorById(instance_id); - if (!descriptor) { - VLOG(1) << "Descriptor not found: " << instance_id; - return kStatusErrorNotFound; - } - - BluetoothPermissionRequest request( - descriptor->GetCharacteristic()->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this descriptor: " - << instance_id; - return kStatusErrorPermissionDenied; - } - - PopulateDescriptor(descriptor, out_descriptor); - return kStatusSuccess; -} - -void BluetoothLowEnergyEventRouter::ReadCharacteristicValue( - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothRemoteGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - characteristic->ReadRemoteCharacteristic( - base::Bind(&BluetoothLowEnergyEventRouter::OnValueSuccess, - weak_ptr_factory_.GetWeakPtr(), - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::WriteCharacteristicValue( - const Extension* extension, - const std::string& instance_id, - const std::vector<uint8_t>& value, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothRemoteGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - characteristic->WriteRemoteCharacteristic( - value, - callback, - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::StartCharacteristicNotifications( - bool persistent, - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - const std::string session_id = extension_id + instance_id; - - if (pending_session_calls_.count(session_id) != 0) { - error_callback.Run(kStatusErrorInProgress); - return; - } - - BluetoothLowEnergyNotifySession* session = - FindNotifySession(extension_id, instance_id); - if (session) { - if (session->GetSession()->IsActive()) { - VLOG(1) << "Application has already enabled notifications from " - << "characteristic: " << instance_id; - error_callback.Run(kStatusErrorAlreadyNotifying); - return; - } - - RemoveNotifySession(extension_id, instance_id); - } - - BluetoothRemoteGattCharacteristic* characteristic = - FindCharacteristicById(instance_id); - if (!characteristic) { - VLOG(1) << "Characteristic not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - characteristic->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this characteristic: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - pending_session_calls_.insert(session_id); - characteristic->StartNotifySession( - base::Bind(&BluetoothLowEnergyEventRouter::OnStartNotifySession, - weak_ptr_factory_.GetWeakPtr(), - persistent, - extension_id, - instance_id, - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnStartNotifySessionError, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - instance_id, - error_callback)); -} - -void BluetoothLowEnergyEventRouter::StopCharacteristicNotifications( - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - const std::string extension_id = extension->id(); - - BluetoothLowEnergyNotifySession* session = - FindNotifySession(extension_id, instance_id); - if (!session || !session->GetSession()->IsActive()) { - VLOG(1) << "Application has not enabled notifications from " - << "characteristic: " << instance_id; - error_callback.Run(kStatusErrorNotNotifying); - return; - } - - session->GetSession()->Stop( - base::Bind(&BluetoothLowEnergyEventRouter::OnStopNotifySession, - weak_ptr_factory_.GetWeakPtr(), - extension_id, - instance_id, - callback)); -} - -void BluetoothLowEnergyEventRouter::ReadDescriptorValue( - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothRemoteGattDescriptor* descriptor = FindDescriptorById(instance_id); - if (!descriptor) { - VLOG(1) << "Descriptor not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - descriptor->GetCharacteristic()->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this descriptor: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - descriptor->ReadRemoteDescriptor( - base::Bind(&BluetoothLowEnergyEventRouter::OnValueSuccess, - weak_ptr_factory_.GetWeakPtr(), - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::WriteDescriptorValue( - const Extension* extension, - const std::string& instance_id, - const std::vector<uint8_t>& value, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - BluetoothRemoteGattDescriptor* descriptor = FindDescriptorById(instance_id); - if (!descriptor) { - VLOG(1) << "Descriptor not found: " << instance_id; - error_callback.Run(kStatusErrorNotFound); - return; - } - - BluetoothPermissionRequest request( - descriptor->GetCharacteristic()->GetService()->GetUUID().value()); - if (!BluetoothManifestData::CheckRequest(extension, request)) { - VLOG(1) << "App has no permission to access this descriptor: " - << instance_id; - error_callback.Run(kStatusErrorPermissionDenied); - return; - } - - descriptor->WriteRemoteDescriptor( - value, - callback, - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), - error_callback)); -} - -void BluetoothLowEnergyEventRouter::SetAdapterForTesting( - device::BluetoothAdapter* adapter) { - adapter_ = adapter; - InitializeIdentifierMappings(); -} - -void BluetoothLowEnergyEventRouter::GattServiceAdded( - BluetoothAdapter* adapter, - BluetoothDevice* device, - BluetoothRemoteGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service added: " << service->GetIdentifier(); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) == - service_id_to_device_address_.end()); - - service_id_to_device_address_[service->GetIdentifier()] = - device->GetAddress(); -} - -void BluetoothLowEnergyEventRouter::GattServiceRemoved( - BluetoothAdapter* adapter, - BluetoothDevice* device, - BluetoothRemoteGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service removed: " << service->GetIdentifier(); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - DCHECK(device->GetAddress() == - service_id_to_device_address_[service->GetIdentifier()]); - service_id_to_device_address_.erase(service->GetIdentifier()); - - // Signal API event. - apibtle::Service api_service; - PopulateService(service, &api_service); - - std::unique_ptr<base::ListValue> args = - apibtle::OnServiceRemoved::Create(api_service); - std::unique_ptr<Event> event( - new Event(events::BLUETOOTH_LOW_ENERGY_ON_SERVICE_REMOVED, - apibtle::OnServiceRemoved::kEventName, std::move(args))); - EventRouter::Get(browser_context_)->BroadcastEvent(std::move(event)); -} - -void BluetoothLowEnergyEventRouter::GattDiscoveryCompleteForService( - BluetoothAdapter* adapter, - BluetoothRemoteGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service discovery complete: " << service->GetIdentifier(); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - // Signal the service added event here. - apibtle::Service api_service; - PopulateService(service, &api_service); - - std::unique_ptr<base::ListValue> args = - apibtle::OnServiceAdded::Create(api_service); - std::unique_ptr<Event> event( - new Event(events::BLUETOOTH_LOW_ENERGY_ON_SERVICE_ADDED, - apibtle::OnServiceAdded::kEventName, std::move(args))); - EventRouter::Get(browser_context_)->BroadcastEvent(std::move(event)); -} - -void BluetoothLowEnergyEventRouter::DeviceAddressChanged( - BluetoothAdapter* adapter, - BluetoothDevice* device, - const std::string& old_address) { - for (auto& iter : service_id_to_device_address_) { - if (iter.second == old_address) - service_id_to_device_address_[iter.first] = device->GetAddress(); - } -} - -void BluetoothLowEnergyEventRouter::GattServiceChanged( - BluetoothAdapter* adapter, - BluetoothRemoteGattService* service) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT service changed: " << service->GetIdentifier(); - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - // Signal API event. - apibtle::Service api_service; - PopulateService(service, &api_service); - - DispatchEventToExtensionsWithPermission( - events::BLUETOOTH_LOW_ENERGY_ON_SERVICE_CHANGED, - apibtle::OnServiceChanged::kEventName, service->GetUUID(), - "" /* characteristic_id */, - apibtle::OnServiceChanged::Create(api_service)); -} - -void BluetoothLowEnergyEventRouter::GattCharacteristicAdded( - BluetoothAdapter* adapter, - BluetoothRemoteGattCharacteristic* characteristic) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT characteristic added: " << characteristic->GetIdentifier(); - - BluetoothRemoteGattService* service = characteristic->GetService(); - DCHECK(service); - - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) == - chrc_id_to_service_id_.end()); - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - - chrc_id_to_service_id_[characteristic->GetIdentifier()] = - service->GetIdentifier(); -} - -void BluetoothLowEnergyEventRouter::GattCharacteristicRemoved( - BluetoothAdapter* adapter, - BluetoothRemoteGattCharacteristic* characteristic) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT characteristic removed: " << characteristic->GetIdentifier(); - - BluetoothRemoteGattService* service = characteristic->GetService(); - DCHECK(service); - - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) != - chrc_id_to_service_id_.end()); - DCHECK(service->GetIdentifier() == - chrc_id_to_service_id_[characteristic->GetIdentifier()]); - - chrc_id_to_service_id_.erase(characteristic->GetIdentifier()); -} - -void BluetoothLowEnergyEventRouter::GattDescriptorAdded( - BluetoothAdapter* adapter, - BluetoothRemoteGattDescriptor* descriptor) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT descriptor added: " << descriptor->GetIdentifier(); - - BluetoothRemoteGattCharacteristic* characteristic = - descriptor->GetCharacteristic(); - DCHECK(characteristic); - - DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) == - desc_id_to_chrc_id_.end()); - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) != - chrc_id_to_service_id_.end()); - - desc_id_to_chrc_id_[descriptor->GetIdentifier()] = - characteristic->GetIdentifier(); -} - -void BluetoothLowEnergyEventRouter::GattDescriptorRemoved( - BluetoothAdapter* adapter, - BluetoothRemoteGattDescriptor* descriptor) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT descriptor removed: " << descriptor->GetIdentifier(); - - BluetoothRemoteGattCharacteristic* characteristic = - descriptor->GetCharacteristic(); - DCHECK(characteristic); - - DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) != - desc_id_to_chrc_id_.end()); - DCHECK(characteristic->GetIdentifier() == - desc_id_to_chrc_id_[descriptor->GetIdentifier()]); - - desc_id_to_chrc_id_.erase(descriptor->GetIdentifier()); -} - -void BluetoothLowEnergyEventRouter::GattCharacteristicValueChanged( - BluetoothAdapter* adapter, - BluetoothRemoteGattCharacteristic* characteristic, - const std::vector<uint8_t>& value) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT characteristic value changed: " - << characteristic->GetIdentifier(); - - BluetoothRemoteGattService* service = characteristic->GetService(); - DCHECK(service); - - DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) != - service_id_to_device_address_.end()); - DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) != - chrc_id_to_service_id_.end()); - DCHECK(chrc_id_to_service_id_[characteristic->GetIdentifier()] == - service->GetIdentifier()); - - // Send the event; manually construct the arguments, instead of using - // apibtle::OnCharacteristicValueChanged::Create, as it doesn't convert - // lists of enums correctly. - apibtle::Characteristic api_characteristic; - PopulateCharacteristic(characteristic, &api_characteristic); - std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(apibtle::CharacteristicToValue(&api_characteristic)); - - DispatchEventToExtensionsWithPermission( - events::BLUETOOTH_LOW_ENERGY_ON_CHARACTERISTIC_VALUE_CHANGED, - apibtle::OnCharacteristicValueChanged::kEventName, service->GetUUID(), - characteristic->GetIdentifier(), std::move(args)); -} - -void BluetoothLowEnergyEventRouter::GattDescriptorValueChanged( - BluetoothAdapter* adapter, - BluetoothRemoteGattDescriptor* descriptor, - const std::vector<uint8_t>& value) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(adapter, adapter_.get()); - VLOG(2) << "GATT descriptor value changed: " << descriptor->GetIdentifier(); - - BluetoothRemoteGattCharacteristic* characteristic = - descriptor->GetCharacteristic(); - DCHECK(characteristic); - - DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) != - desc_id_to_chrc_id_.end()); - DCHECK(characteristic->GetIdentifier() == - desc_id_to_chrc_id_[descriptor->GetIdentifier()]); - - // Send the event; manually construct the arguments, instead of using - // apibtle::OnDescriptorValueChanged::Create, as it doesn't convert - // lists of enums correctly. - apibtle::Descriptor api_descriptor; - PopulateDescriptor(descriptor, &api_descriptor); - std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(apibtle::DescriptorToValue(&api_descriptor)); - - DispatchEventToExtensionsWithPermission( - events::BLUETOOTH_LOW_ENERGY_ON_DESCRIPTOR_VALUE_CHANGED, - apibtle::OnDescriptorValueChanged::kEventName, - characteristic->GetService()->GetUUID(), "" /* characteristic_id */, - std::move(args)); -} - -void BluetoothLowEnergyEventRouter::OnCharacteristicReadRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic, - int offset, - const Delegate::ValueCallback& value_callback, - const Delegate::ErrorCallback& error_callback) { - const std::string& service_id = characteristic->GetService()->GetIdentifier(); - if (service_id_to_extension_id_.find(service_id) == - service_id_to_extension_id_.end()) { - LOG(DFATAL) << "Service with ID " << service_id - << " does not belong to any extension."; - return; - } - - const std::string& extension_id = service_id_to_extension_id_.at(service_id); - apibtle::Request request; - request.request_id = - StoreSentRequest(extension_id, base::WrapUnique(new AttributeValueRequest( - value_callback, error_callback))); - PopulateDevice(device, &request); - DispatchEventToExtension( - extension_id, events::BLUETOOTH_LOW_ENERGY_ON_CHARACTERISTIC_READ_REQUEST, - apibtle::OnCharacteristicReadRequest::kEventName, - apibtle::OnCharacteristicReadRequest::Create( - request, characteristic->GetIdentifier())); -} - -void BluetoothLowEnergyEventRouter::OnCharacteristicWriteRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic, - const std::vector<uint8_t>& value, - int offset, - const base::Closure& callback, - const Delegate::ErrorCallback& error_callback) { - const std::string& service_id = characteristic->GetService()->GetIdentifier(); - if (service_id_to_extension_id_.find(service_id) == - service_id_to_extension_id_.end()) { - LOG(DFATAL) << "Service with ID " << service_id - << " does not belong to any extension."; - return; - } - - const std::string& extension_id = service_id_to_extension_id_.at(service_id); - - apibtle::Request request; - request.request_id = StoreSentRequest( - extension_id, - base::WrapUnique(new AttributeValueRequest(callback, error_callback))); - request.value = - base::WrapUnique(new std::vector<char>(value.begin(), value.end())); - PopulateDevice(device, &request); - DispatchEventToExtension( - extension_id, - events::BLUETOOTH_LOW_ENERGY_ON_CHARACTERISTIC_WRITE_REQUEST, - apibtle::OnCharacteristicWriteRequest::kEventName, - apibtle::OnCharacteristicWriteRequest::Create( - request, characteristic->GetIdentifier())); -} - -void BluetoothLowEnergyEventRouter::OnDescriptorReadRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattDescriptor* descriptor, - int offset, - const Delegate::ValueCallback& value_callback, - const Delegate::ErrorCallback& error_callback) { - const std::string& service_id = - descriptor->GetCharacteristic()->GetService()->GetIdentifier(); - if (service_id_to_extension_id_.find(service_id) == - service_id_to_extension_id_.end()) { - LOG(DFATAL) << "Service with ID " << service_id - << " does not belong to any extension."; - return; - } - - const std::string& extension_id = service_id_to_extension_id_.at(service_id); - - apibtle::Request request; - request.request_id = - StoreSentRequest(extension_id, base::WrapUnique(new AttributeValueRequest( - value_callback, error_callback))); - PopulateDevice(device, &request); - DispatchEventToExtension( - extension_id, - events::BLUETOOTH_LOW_ENERGY_ON_CHARACTERISTIC_WRITE_REQUEST, - apibtle::OnDescriptorReadRequest::kEventName, - apibtle::OnDescriptorReadRequest::Create(request, - descriptor->GetIdentifier())); -} - -void BluetoothLowEnergyEventRouter::OnDescriptorWriteRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattDescriptor* descriptor, - const std::vector<uint8_t>& value, - int offset, - const base::Closure& callback, - const Delegate::ErrorCallback& error_callback) { - const std::string& service_id = - descriptor->GetCharacteristic()->GetService()->GetIdentifier(); - if (service_id_to_extension_id_.find(service_id) == - service_id_to_extension_id_.end()) { - LOG(DFATAL) << "Service with ID " << service_id - << " does not belong to any extension."; - return; - } - - const std::string& extension_id = service_id_to_extension_id_.at(service_id); - - apibtle::Request request; - request.request_id = StoreSentRequest( - extension_id, - base::WrapUnique(new AttributeValueRequest(callback, error_callback))); - request.value = - base::WrapUnique(new std::vector<char>(value.begin(), value.end())); - PopulateDevice(device, &request); - DispatchEventToExtension( - extension_id, - events::BLUETOOTH_LOW_ENERGY_ON_CHARACTERISTIC_WRITE_REQUEST, - apibtle::OnDescriptorWriteRequest::kEventName, - apibtle::OnDescriptorWriteRequest::Create(request, - descriptor->GetIdentifier())); -} - -void BluetoothLowEnergyEventRouter::OnNotificationsStart( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic) {} - -void BluetoothLowEnergyEventRouter::OnNotificationsStop( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic) {} - -void BluetoothLowEnergyEventRouter::OnExtensionUnloaded( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UnloadedExtensionInfo::Reason reason) { - const std::string& app_id = extension->id(); - const auto& services = app_id_to_service_ids_.find(app_id); - if (services == app_id_to_service_ids_.end()) - return; - - // Find all services owned by this app and delete them. - for (const auto& service_id : services->second) { - device::BluetoothLocalGattService* service = - adapter_->GetGattService(service_id); - if (service) - service->Delete(); - } - app_id_to_service_ids_.erase(services); -} - -void BluetoothLowEnergyEventRouter::AddLocalCharacteristic( - const std::string& id, - const std::string& service_id) { - if (chrc_id_to_service_id_.find(id) != chrc_id_to_service_id_.end()) - VLOG(2) << "Local characteristic with id " << id - << " already exists. Replacing."; - chrc_id_to_service_id_[id] = service_id; -} - -device::BluetoothLocalGattCharacteristic* -BluetoothLowEnergyEventRouter::GetLocalCharacteristic( - const std::string& id) const { - if (chrc_id_to_service_id_.find(id) == chrc_id_to_service_id_.end()) { - VLOG(1) << "Characteristic with id " << id << " not found."; - return nullptr; - } - device::BluetoothLocalGattService* service = - adapter_->GetGattService(chrc_id_to_service_id_.at(id)); - if (!service) { - VLOG(1) << "Parent service of characteristic with id " << id - << " not found."; - return nullptr; - } - - return service->GetCharacteristic(id); -} - -void BluetoothLowEnergyEventRouter::AddServiceToApp( - const std::string& app_id, - const std::string& service_id) { - const auto& services = app_id_to_service_ids_.find(app_id); - if (services == app_id_to_service_ids_.end()) { - std::vector<std::string> service_ids; - service_ids.push_back(service_id); - app_id_to_service_ids_[app_id] = service_ids; - } else { - services->second.push_back(service_id); - } -} - -void BluetoothLowEnergyEventRouter::RemoveServiceFromApp( - const std::string& app_id, - const std::string& service_id) { - const auto& services = app_id_to_service_ids_.find(app_id); - if (services == app_id_to_service_ids_.end()) { - LOG(WARNING) << "No service mapping exists for app: " << app_id; - return; - } - - const auto& service = - find(services->second.begin(), services->second.end(), service_id); - if (service == services->second.end()) { - LOG(WARNING) << "Service:" << service_id - << " doesn't exist in app: " << app_id; - return; - } - - services->second.erase(service); -} - -void BluetoothLowEnergyEventRouter::RegisterGattService( - const Extension* extension, - const std::string& service_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - device::BluetoothLocalGattService* service = - adapter_->GetGattService(service_id); - if (!service) { - error_callback.Run(kStatusErrorInvalidServiceId); - return; - } - - service->Register( - base::Bind(&BluetoothLowEnergyEventRouter::OnRegisterGattServiceSuccess, - weak_ptr_factory_.GetWeakPtr(), service_id, extension->id(), - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), error_callback)); -} - -void BluetoothLowEnergyEventRouter::UnregisterGattService( - const Extension* extension, - const std::string& service_id, - const base::Closure& callback, - const ErrorCallback& error_callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(extension); - if (!adapter_.get()) { - VLOG(1) << "BluetoothAdapter not ready."; - error_callback.Run(kStatusErrorFailed); - return; - } - - device::BluetoothLocalGattService* service = - adapter_->GetGattService(service_id); - if (!service) { - error_callback.Run(kStatusErrorInvalidServiceId); - return; - } - - service->Unregister( - base::Bind(&BluetoothLowEnergyEventRouter::OnUnregisterGattServiceSuccess, - weak_ptr_factory_.GetWeakPtr(), service_id, extension->id(), - callback), - base::Bind(&BluetoothLowEnergyEventRouter::OnError, - weak_ptr_factory_.GetWeakPtr(), error_callback)); -} - -void BluetoothLowEnergyEventRouter::HandleRequestResponse( - const Extension* extension, - size_t request_id, - bool is_error, - const std::vector<uint8_t>& value) { - const auto& iter = requests_.find(extension->id()); - if (iter == requests_.end()) - return; - - RequestIdToRequestMap* request_id_map = iter->second.get(); - const auto& request_iter = request_id_map->find(request_id); - if (request_iter == request_id_map->end()) - return; - - std::unique_ptr<AttributeValueRequest> request = - std::move(request_iter->second); - // Request is being handled, delete it. - request_id_map->erase(request_iter); - - if (is_error) { - request->error_callback.Run(); - return; - } - - if (request->type == AttributeValueRequest::ATTRIBUTE_READ_REQUEST) { - request->value_callback.Run(value); - } else { - request->success_callback.Run(); - } -} - -void BluetoothLowEnergyEventRouter::OnGetAdapter( - const base::Closure& callback, - scoped_refptr<device::BluetoothAdapter> adapter) { - adapter_ = adapter; - - // Initialize instance ID mappings for all discovered GATT objects and add - // observers. - InitializeIdentifierMappings(); - adapter_->AddObserver(this); - - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::InitializeIdentifierMappings() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(service_id_to_device_address_.empty()); - DCHECK(chrc_id_to_service_id_.empty()); - - // Devices - BluetoothAdapter::DeviceList devices = adapter_->GetDevices(); - for (BluetoothAdapter::DeviceList::iterator iter = devices.begin(); - iter != devices.end(); - ++iter) { - BluetoothDevice* device = *iter; - - // Services - std::vector<BluetoothRemoteGattService*> services = - device->GetGattServices(); - for (std::vector<BluetoothRemoteGattService*>::iterator siter = - services.begin(); - siter != services.end(); ++siter) { - BluetoothRemoteGattService* service = *siter; - - const std::string& service_id = service->GetIdentifier(); - service_id_to_device_address_[service_id] = device->GetAddress(); - - // Characteristics - const std::vector<BluetoothRemoteGattCharacteristic*>& characteristics = - service->GetCharacteristics(); - for (std::vector<BluetoothRemoteGattCharacteristic*>::const_iterator - citer = characteristics.begin(); - citer != characteristics.end(); ++citer) { - BluetoothRemoteGattCharacteristic* characteristic = *citer; - - const std::string& chrc_id = characteristic->GetIdentifier(); - chrc_id_to_service_id_[chrc_id] = service_id; - - // Descriptors - const std::vector<BluetoothRemoteGattDescriptor*>& descriptors = - characteristic->GetDescriptors(); - for (std::vector<BluetoothRemoteGattDescriptor*>::const_iterator diter = - descriptors.begin(); - diter != descriptors.end(); ++diter) { - BluetoothRemoteGattDescriptor* descriptor = *diter; - - const std::string& desc_id = descriptor->GetIdentifier(); - desc_id_to_chrc_id_[desc_id] = chrc_id; - } - } - } - } -} - -void BluetoothLowEnergyEventRouter::DispatchEventToExtensionsWithPermission( - events::HistogramValue histogram_value, - const std::string& event_name, - const device::BluetoothUUID& uuid, - const std::string& characteristic_id, - std::unique_ptr<base::ListValue> args) { - // Obtain the listeners of |event_name|. The list can contain multiple - // entries for the same extension, so we keep track of the extensions that we - // already sent the event to, since we want the send an event to an extension - // only once. - BluetoothPermissionRequest request(uuid.value()); - std::set<std::string> handled_extensions; - const EventListenerMap::ListenerList listeners = - EventRouter::Get(browser_context_)->listeners().GetEventListenersByName( - event_name); - - for (EventListenerMap::ListenerList::const_iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter) { - const std::string extension_id = (*iter)->extension_id(); - if (handled_extensions.find(extension_id) != handled_extensions.end()) - continue; - - handled_extensions.insert(extension_id); - - const Extension* extension = - ExtensionRegistry::Get(browser_context_) - ->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING); - - // For all API methods, the "low_energy" permission check is handled by - // BluetoothLowEnergyExtensionFunction but for events we have to do the - // check here. - if (!BluetoothManifestData::CheckRequest(extension, request) || - !BluetoothManifestData::CheckLowEnergyPermitted(extension)) - continue; - - // If |event_name| is "onCharacteristicValueChanged", then send the - // event only if the extension has requested notifications from the - // related characteristic. - if (event_name == apibtle::OnCharacteristicValueChanged::kEventName && - !characteristic_id.empty() && - !FindNotifySession(extension_id, characteristic_id)) - continue; - - // Send the event. - std::unique_ptr<base::ListValue> args_copy(args->DeepCopy()); - std::unique_ptr<Event> event( - new Event(histogram_value, event_name, std::move(args_copy))); - EventRouter::Get(browser_context_) - ->DispatchEventToExtension(extension_id, std::move(event)); - } -} - -void BluetoothLowEnergyEventRouter::DispatchEventToExtension( - const std::string& extension_id, - events::HistogramValue histogram_value, - const std::string& event_name, - std::unique_ptr<base::ListValue> args) { - // For all API methods, the "low_energy" permission check is handled by - // BluetoothLowEnergyExtensionFunction but for events we have to do the - // check here. - const Extension* extension = - ExtensionRegistry::Get(browser_context_) - ->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING); - if (!extension || !BluetoothManifestData::CheckLowEnergyPermitted(extension)) - return; - - // Send the event. - std::unique_ptr<base::ListValue> args_copy(args->DeepCopy()); - std::unique_ptr<Event> event( - new Event(histogram_value, event_name, std::move(args_copy))); - EventRouter::Get(browser_context_) - ->DispatchEventToExtension(extension_id, std::move(event)); -} - -BluetoothRemoteGattService* BluetoothLowEnergyEventRouter::FindServiceById( - const std::string& instance_id) const { - InstanceIdMap::const_iterator iter = - service_id_to_device_address_.find(instance_id); - if (iter == service_id_to_device_address_.end()) { - VLOG(1) << "GATT service identifier unknown: " << instance_id; - return NULL; - } - - const std::string& address = iter->second; - - BluetoothDevice* device = adapter_->GetDevice(address); - if (!device) { - VLOG(1) << "Bluetooth device not found: " << address; - return NULL; - } - - BluetoothRemoteGattService* service = device->GetGattService(instance_id); - if (!service) { - VLOG(1) << "GATT service with ID \"" << instance_id - << "\" not found on device \"" << address << "\""; - return NULL; - } - - return service; -} - -BluetoothRemoteGattCharacteristic* -BluetoothLowEnergyEventRouter::FindCharacteristicById( - const std::string& instance_id) const { - InstanceIdMap::const_iterator iter = chrc_id_to_service_id_.find(instance_id); - if (iter == chrc_id_to_service_id_.end()) { - VLOG(1) << "GATT characteristic identifier unknown: " << instance_id; - return NULL; - } - - const std::string& service_id = iter->second; - - BluetoothRemoteGattService* service = FindServiceById(service_id); - if (!service) { - VLOG(1) << "Failed to obtain service for characteristic: " << instance_id; - return NULL; - } - - BluetoothRemoteGattCharacteristic* characteristic = - service->GetCharacteristic(instance_id); - if (!characteristic) { - VLOG(1) << "GATT characteristic with ID \"" << instance_id - << "\" not found on service \"" << service_id << "\""; - return NULL; - } - - return characteristic; -} - -BluetoothRemoteGattDescriptor* -BluetoothLowEnergyEventRouter::FindDescriptorById( - const std::string& instance_id) const { - InstanceIdMap::const_iterator iter = desc_id_to_chrc_id_.find(instance_id); - if (iter == desc_id_to_chrc_id_.end()) { - VLOG(1) << "GATT descriptor identifier unknown: " << instance_id; - return NULL; - } - - const std::string& chrc_id = iter->second; - BluetoothRemoteGattCharacteristic* chrc = FindCharacteristicById(chrc_id); - if (!chrc) { - VLOG(1) << "Failed to obtain characteristic for descriptor: " - << instance_id; - return NULL; - } - - BluetoothRemoteGattDescriptor* descriptor = chrc->GetDescriptor(instance_id); - if (!descriptor) { - VLOG(1) << "GATT descriptor with ID \"" << instance_id - << "\" not found on characteristic \"" << chrc_id << "\""; - return NULL; - } - - return descriptor; -} - -void BluetoothLowEnergyEventRouter::OnValueSuccess( - const base::Closure& callback, - const std::vector<uint8_t>& value) { - VLOG(2) << "Remote characteristic/descriptor value read successful."; - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnRegisterGattServiceSuccess( - const std::string& service_id, - const std::string& extension_id, - const base::Closure& callback) { - VLOG(2) << "Register GATT service successful."; - service_id_to_extension_id_[service_id] = extension_id; - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnUnregisterGattServiceSuccess( - const std::string& service_id, - const std::string& extension_id, - const base::Closure& callback) { - VLOG(2) << "Unregister GATT service successful."; - const auto& iter = service_id_to_extension_id_.find(service_id); - if (iter != service_id_to_extension_id_.end()) - service_id_to_extension_id_.erase(iter); - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnCreateGattConnection( - bool persistent, - const std::string& extension_id, - const std::string& device_address, - const base::Closure& callback, - std::unique_ptr<BluetoothGattConnection> connection) { - VLOG(2) << "GATT connection created."; - DCHECK(connection.get()); - DCHECK(!FindConnection(extension_id, device_address)); - DCHECK_EQ(device_address, connection->GetDeviceAddress()); - - const std::string connect_id = extension_id + device_address; - DCHECK_NE(0U, connecting_devices_.count(connect_id)); - - BluetoothLowEnergyConnection* conn = new BluetoothLowEnergyConnection( - persistent, extension_id, std::move(connection)); - ConnectionResourceManager* manager = - GetConnectionResourceManager(browser_context_); - manager->Add(conn); - - connecting_devices_.erase(connect_id); - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnError( - const ErrorCallback& error_callback, - BluetoothRemoteGattService::GattErrorCode error_code) { - VLOG(2) << "Remote characteristic/descriptor value read/write failed."; - - error_callback.Run(GattErrorToRouterError(error_code)); -} - -void BluetoothLowEnergyEventRouter::OnConnectError( - const std::string& extension_id, - const std::string& device_address, - const ErrorCallback& error_callback, - BluetoothDevice::ConnectErrorCode error_code) { - VLOG(2) << "Failed to create GATT connection: " << error_code; - - const std::string connect_id = extension_id + device_address; - DCHECK_NE(0U, connecting_devices_.count(connect_id)); - - connecting_devices_.erase(connect_id); - Status error_status = kStatusErrorFailed; - switch (error_code) { - case BluetoothDevice::ERROR_ATTRIBUTE_LENGTH_INVALID: - error_status = kStatusErrorAttributeLengthInvalid; - break; - case BluetoothDevice::ERROR_AUTH_CANCELED: - error_status = kStatusErrorCanceled; - break; - case BluetoothDevice::ERROR_AUTH_FAILED: - error_status = kStatusErrorAuthenticationFailed; - break; - case BluetoothDevice::ERROR_AUTH_REJECTED: - error_status = kStatusErrorAuthenticationFailed; - break; - case BluetoothDevice::ERROR_AUTH_TIMEOUT: - error_status = kStatusErrorTimeout; - break; - case BluetoothDevice::ERROR_CONNECTION_CONGESTED: - error_status = kStatusErrorConnectionCongested; - break; - case BluetoothDevice::ERROR_FAILED: - error_status = kStatusErrorFailed; - break; - case BluetoothDevice::ERROR_INPROGRESS: - error_status = kStatusErrorInProgress; - break; - case BluetoothDevice::ERROR_INSUFFICIENT_ENCRYPTION: - error_status = kStatusErrorInsufficientEncryption; - break; - case BluetoothDevice::ERROR_OFFSET_INVALID: - error_status = kStatusErrorOffsetInvalid; - break; - case BluetoothDevice::ERROR_READ_NOT_PERMITTED: - error_status = kStatusErrorPermissionDenied; - break; - case BluetoothDevice::ERROR_REQUEST_NOT_SUPPORTED: - error_status = kStatusErrorRequestNotSupported; - break; - case BluetoothDevice::ERROR_UNKNOWN: - error_status = kStatusErrorFailed; - break; - case BluetoothDevice::ERROR_UNSUPPORTED_DEVICE: - error_status = kStatusErrorUnsupportedDevice; - break; - case BluetoothDevice::ERROR_WRITE_NOT_PERMITTED: - error_status = kStatusErrorPermissionDenied; - break; - case BluetoothDevice::NUM_CONNECT_ERROR_CODES: - NOTREACHED(); - error_status = kStatusErrorInvalidArguments; - break; - } - - error_callback.Run(error_status); -} - -void BluetoothLowEnergyEventRouter::OnStartNotifySession( - bool persistent, - const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback, - std::unique_ptr<device::BluetoothGattNotifySession> session) { - VLOG(2) << "Value update session created for characteristic: " - << characteristic_id; - DCHECK(session.get()); - DCHECK(!FindNotifySession(extension_id, characteristic_id)); - DCHECK_EQ(characteristic_id, session->GetCharacteristicIdentifier()); - - const std::string session_id = extension_id + characteristic_id; - DCHECK_NE(0U, pending_session_calls_.count(session_id)); - - BluetoothLowEnergyNotifySession* resource = - new BluetoothLowEnergyNotifySession(persistent, extension_id, - std::move(session)); - - NotifySessionResourceManager* manager = - GetNotifySessionResourceManager(browser_context_); - manager->Add(resource); - - pending_session_calls_.erase(session_id); - callback.Run(); -} - -void BluetoothLowEnergyEventRouter::OnStartNotifySessionError( - const std::string& extension_id, - const std::string& characteristic_id, - const ErrorCallback& error_callback, - device::BluetoothRemoteGattService::GattErrorCode error_code) { - VLOG(2) << "Failed to create value update session for characteristic: " - << characteristic_id; - - const std::string session_id = extension_id + characteristic_id; - DCHECK_NE(0U, pending_session_calls_.count(session_id)); - - pending_session_calls_.erase(session_id); - error_callback.Run(GattErrorToRouterError(error_code)); -} - -void BluetoothLowEnergyEventRouter::OnStopNotifySession( - const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback) { - VLOG(2) << "Value update session terminated."; - - if (!RemoveNotifySession(extension_id, characteristic_id)) { - VLOG(1) << "The value update session was removed before Stop completed, " - << "id: " << extension_id - << ", characteristic: " << characteristic_id; - } - - callback.Run(); -} - -BluetoothLowEnergyConnection* BluetoothLowEnergyEventRouter::FindConnection( - const std::string& extension_id, - const std::string& device_address) { - ConnectionResourceManager* manager = - GetConnectionResourceManager(browser_context_); - - base::hash_set<int>* connection_ids = manager->GetResourceIds(extension_id); - if (!connection_ids) - return NULL; - - for (base::hash_set<int>::const_iterator iter = connection_ids->begin(); - iter != connection_ids->end(); - ++iter) { - extensions::BluetoothLowEnergyConnection* conn = - manager->Get(extension_id, *iter); - if (!conn) - continue; - - if (conn->GetConnection()->GetDeviceAddress() == device_address) - return conn; - } - - return NULL; -} - -bool BluetoothLowEnergyEventRouter::RemoveConnection( - const std::string& extension_id, - const std::string& device_address) { - ConnectionResourceManager* manager = - GetConnectionResourceManager(browser_context_); - - base::hash_set<int>* connection_ids = manager->GetResourceIds(extension_id); - if (!connection_ids) - return false; - - for (base::hash_set<int>::const_iterator iter = connection_ids->begin(); - iter != connection_ids->end(); - ++iter) { - extensions::BluetoothLowEnergyConnection* conn = - manager->Get(extension_id, *iter); - if (!conn || conn->GetConnection()->GetDeviceAddress() != device_address) - continue; - - manager->Remove(extension_id, *iter); - return true; - } - - return false; -} - -BluetoothLowEnergyNotifySession* -BluetoothLowEnergyEventRouter::FindNotifySession( - const std::string& extension_id, - const std::string& characteristic_id) { - NotifySessionResourceManager* manager = - GetNotifySessionResourceManager(browser_context_); - - base::hash_set<int>* ids = manager->GetResourceIds(extension_id); - if (!ids) - return NULL; - - for (base::hash_set<int>::const_iterator iter = ids->begin(); - iter != ids->end(); - ++iter) { - BluetoothLowEnergyNotifySession* session = - manager->Get(extension_id, *iter); - if (!session) - continue; - - if (session->GetSession()->GetCharacteristicIdentifier() == - characteristic_id) - return session; - } - - return NULL; -} - -bool BluetoothLowEnergyEventRouter::RemoveNotifySession( - const std::string& extension_id, - const std::string& characteristic_id) { - NotifySessionResourceManager* manager = - GetNotifySessionResourceManager(browser_context_); - - base::hash_set<int>* ids = manager->GetResourceIds(extension_id); - if (!ids) - return false; - - for (base::hash_set<int>::const_iterator iter = ids->begin(); - iter != ids->end(); - ++iter) { - BluetoothLowEnergyNotifySession* session = - manager->Get(extension_id, *iter); - if (!session || - session->GetSession()->GetCharacteristicIdentifier() != - characteristic_id) - continue; - - manager->Remove(extension_id, *iter); - return true; - } - - return false; -} - -size_t BluetoothLowEnergyEventRouter::StoreSentRequest( - const std::string& extension_id, - std::unique_ptr<AttributeValueRequest> request) { - // Either find or create a request_id -> request map for this extension. - RequestIdToRequestMap* request_id_map = nullptr; - const auto& iter = requests_.find(extension_id); - if (iter == requests_.end()) { - std::unique_ptr<RequestIdToRequestMap> new_request_id_map = - base::WrapUnique(new RequestIdToRequestMap); - request_id_map = new_request_id_map.get(); - requests_[extension_id] = std::move(new_request_id_map); - } else { - request_id_map = iter->second.get(); - } - - (*request_id_map)[++last_callback_request_id_] = std::move(request); - return last_callback_request_id_; -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h deleted file mode 100644 index a7e6c29a15b..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h +++ /dev/null @@ -1,588 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_EVENT_ROUTER_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_EVENT_ROUTER_H_ - -#include <cstddef> -#include <cstdint> -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/callback_forward.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/scoped_observer.h" -#include "chrome/common/extensions/api/bluetooth_low_energy.h" -#include "device/bluetooth/bluetooth_adapter.h" -#include "device/bluetooth/bluetooth_device.h" -#include "device/bluetooth/bluetooth_gatt_connection.h" -#include "device/bluetooth/bluetooth_gatt_notify_session.h" -#include "device/bluetooth/bluetooth_local_gatt_service.h" -#include "device/bluetooth/bluetooth_remote_gatt_service.h" -#include "device/bluetooth/bluetooth_uuid.h" -#include "extensions/browser/extension_event_histogram_value.h" -#include "extensions/browser/extension_registry_observer.h" - -namespace base { - -class ListValue; - -} // namespace base - -namespace content { - -class BrowserContext; - -} // namespace content - -namespace device { - -class BluetoothLocalGattCharacteristic; -class BluetoothLocalGattDescriptor; -class BluetoothRemoteGattCharacteristic; -class BluetoothRemoteGattDescriptor; - -} // namespace device - -namespace extensions { - -class BluetoothLowEnergyConnection; -class BluetoothLowEnergyNotifySession; -class Extension; -class ExtensionRegistry; - -// The BluetoothLowEnergyEventRouter is used by the bluetoothLowEnergy API to -// interface with the internal Bluetooth API in device/bluetooth. -class BluetoothLowEnergyEventRouter - : public device::BluetoothAdapter::Observer, - public device::BluetoothLocalGattService::Delegate, - public extensions::ExtensionRegistryObserver { - public: - struct AttributeValueRequest { - public: - enum RequestType { ATTRIBUTE_READ_REQUEST, ATTRIBUTE_WRITE_REQUEST }; - - AttributeValueRequest(const Delegate::ValueCallback& value_callback, - const Delegate::ErrorCallback& error_callback); - AttributeValueRequest(const base::Closure& success_callback, - const Delegate::ErrorCallback& error_callback); - ~AttributeValueRequest(); - - RequestType type; - Delegate::ValueCallback value_callback; - base::Closure success_callback; - Delegate::ErrorCallback error_callback; - - private: - DISALLOW_COPY_AND_ASSIGN(AttributeValueRequest); - }; - - explicit BluetoothLowEnergyEventRouter(content::BrowserContext* context); - ~BluetoothLowEnergyEventRouter() override; - - // Possible ways that an API method can fail or succeed. - enum Status { - kStatusSuccess = 0, - kStatusErrorAlreadyConnected, - kStatusErrorAlreadyNotifying, - kStatusErrorAttributeLengthInvalid, - kStatusErrorAuthenticationFailed, - kStatusErrorCanceled, - kStatusErrorConnectionCongested, - kStatusErrorFailed, - kStatusErrorGattNotSupported, - kStatusErrorHigherSecurity, - kStatusErrorInProgress, - kStatusErrorInsufficientAuthorization, - kStatusErrorInsufficientEncryption, - kStatusErrorInvalidArguments, - kStatusErrorInvalidLength, - kStatusErrorNotConnected, - kStatusErrorNotFound, - kStatusErrorNotNotifying, - kStatusErrorOffsetInvalid, - kStatusErrorPermissionDenied, - kStatusErrorRequestNotSupported, - kStatusErrorTimeout, - kStatusErrorUnsupportedDevice, - kStatusErrorInvalidServiceId, - }; - - // Error callback is used by asynchronous methods to report failures. - using ErrorCallback = base::Callback<void(Status)>; - - // Returns true if Bluetooth is supported on the current platform or if the - // internal |adapter_| instance has been initialized for testing. - bool IsBluetoothSupported() const; - - // Obtains a handle on the BluetoothAdapter and invokes |callback|. Returns - // false, if Bluetooth is not supported. Otherwise, asynchronously initializes - // it and invokes |callback|. Until the first successful call to this method, - // none of the methods in this class will succeed and no device::Bluetooth* - // API events will be observed. - bool InitializeAdapterAndInvokeCallback(const base::Closure& callback); - - // Returns true, if the BluetoothAdapter was initialized. - bool HasAdapter() const; - - // Creates a GATT connection to the device with address |device_address| for - // extension |extension|. The connection is kept alive until the extension is - // unloaded, the device is removed, or is disconnect by the host subsystem. - // |error_callback| is called with an error status in case of failure. If - // |persistent| is true, then the allocated connection resource is persistent - // across unloads. - void Connect(bool persistent, - const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Disconnects the currently open GATT connection of extension |extension| to - // device with address |device_address|. |error_callback| is called with an - // error status in case of failure, e.g. if the device is not found or the - // given - // extension does not have an open connection to the device. - void Disconnect(const Extension* extension, - const std::string& device_address, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Returns the list of api::bluetooth_low_energy::Service objects - // associated with the Bluetooth device with address |device_address| in - // |out_services|. - // Returns false, if no device with the given address is known. If the device - // is found but it has no GATT services, then returns true and leaves - // |out_services| empty. Returns true, on success. |out_services| must not - // be NULL. If it is non-empty, then its contents will be cleared. - typedef std::vector<api::bluetooth_low_energy::Service> ServiceList; - bool GetServices(const std::string& device_address, - ServiceList* out_services) const; - - // Populates |out_service| based on GATT service with instance ID - // |instance_id|. |out_service| must not be NULL. - Status GetService(const std::string& instance_id, - api::bluetooth_low_energy::Service* out_service) const; - - // Populates |out_services| with the list of GATT services that are included - // by the GATT service with instance ID |instance_id|. Returns false, if not - // GATT service with the given ID is known. If the given service has no - // included services, then |out_service| will be empty. |out_service| must not - // be NULL. If it is non-empty, then its contents will be cleared. - Status GetIncludedServices(const std::string& instance_id, - ServiceList* out_services) const; - - // Returns the list of api::bluetooth_low_energy::Characteristic objects - // associated with the GATT service with instance ID |instance_id| in - // |out_characteristics|. Returns false, if no service with the given instance - // ID is known. If the service is found but it has no characteristics, then - // returns true and leaves |out_characteristics| empty. - // |out_characteristics| must not be NULL and if it is non-empty, - // then its contents will be cleared. |extension| is the extension that made - // the call. - typedef std::vector<api::bluetooth_low_energy::Characteristic> - CharacteristicList; - Status GetCharacteristics(const Extension* extension, - const std::string& instance_id, - CharacteristicList* out_characteristics) const; - - // Populates |out_characteristic| based on GATT characteristic with instance - // ID |instance_id|. |out_characteristic| must not be NULL. |extension| is the - // extension that made the call. - Status GetCharacteristic( - const Extension* extension, - const std::string& instance_id, - api::bluetooth_low_energy::Characteristic* out_characteristic) const; - - // Returns the list of api::bluetooth_low_energy::Descriptor objects - // associated with the GATT characteristic with instance ID |instance_id| in - // |out_descriptors|. If the characteristic is found but it has no - // descriptors, then returns true and leaves |out_descriptors| empty. - // |out_descriptors| must not be NULL and if it is non-empty, - // then its contents will be cleared. |extension| is the extension that made - // the call. - typedef std::vector<api::bluetooth_low_energy::Descriptor> DescriptorList; - Status GetDescriptors(const Extension* extension, - const std::string& instance_id, - DescriptorList* out_descriptors) const; - - // Populates |out_descriptor| based on GATT characteristic descriptor with - // instance ID |instance_id|. |out_descriptor| must not be NULL. - // |extension| is the extension that made the call. - Status GetDescriptor( - const Extension* extension, - const std::string& instance_id, - api::bluetooth_low_energy::Descriptor* out_descriptor) const; - - // Sends a request to read the value of the characteristic with intance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void ReadCharacteristicValue(const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to write the value of the characteristic with instance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void WriteCharacteristicValue(const Extension* extension, - const std::string& instance_id, - const std::vector<uint8_t>& value, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to start characteristic notifications from characteristic - // with instance ID |instance_id|, for extension |extension|. Invokes - // |callback| on success and |error_callback| on failure. If |persistent| is - // true, then the allocated connection resource is persistent across unloads. - void StartCharacteristicNotifications(bool persistent, - const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to stop characteristic notifications from characteristic - // with instance ID |instance_id|, for extension |extension|. Invokes - // |callback| on success and |error_callback| on failure. - void StopCharacteristicNotifications(const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to read the value of the descriptor with instance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void ReadDescriptorValue(const Extension* extension, - const std::string& instance_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Sends a request to write the value of the descriptor with instance ID - // |instance_id|. Invokes |callback| on success and |error_callback| on - // failure. |extension| is the extension that made the call. - void WriteDescriptorValue(const Extension* extension, - const std::string& instance_id, - const std::vector<uint8_t>& value, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Initializes the adapter for testing. Used by unit tests only. - void SetAdapterForTesting(device::BluetoothAdapter* adapter); - - // device::BluetoothAdapter::Observer overrides. - void GattServiceAdded(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device, - device::BluetoothRemoteGattService* service) override; - void GattServiceRemoved(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device, - device::BluetoothRemoteGattService* service) override; - void GattDiscoveryCompleteForService( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattService* service) override; - void DeviceAddressChanged(device::BluetoothAdapter* adapter, - device::BluetoothDevice* device, - const std::string& old_address) override; - void GattServiceChanged(device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattService* service) override; - void GattCharacteristicAdded( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattCharacteristic* characteristic) override; - void GattCharacteristicRemoved( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattCharacteristic* characteristic) override; - void GattDescriptorAdded( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattDescriptor* descriptor) override; - void GattDescriptorRemoved( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattDescriptor* descriptor) override; - void GattCharacteristicValueChanged( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattCharacteristic* characteristic, - const std::vector<uint8_t>& value) override; - void GattDescriptorValueChanged( - device::BluetoothAdapter* adapter, - device::BluetoothRemoteGattDescriptor* descriptor, - const std::vector<uint8_t>& value) override; - - // device::BluetoothLocalGattService::Delegate overrides. - void OnCharacteristicReadRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic, - int offset, - const Delegate::ValueCallback& value_callback, - const Delegate::ErrorCallback& error_callback) override; - void OnCharacteristicWriteRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic, - const std::vector<uint8_t>& value, - int offset, - const base::Closure& callback, - const Delegate::ErrorCallback& error_callback) override; - void OnDescriptorReadRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattDescriptor* descriptor, - int offset, - const Delegate::ValueCallback& value_callback, - const Delegate::ErrorCallback& error_callback) override; - void OnDescriptorWriteRequest( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattDescriptor* descriptor, - const std::vector<uint8_t>& value, - int offset, - const base::Closure& callback, - const Delegate::ErrorCallback& error_callback) override; - void OnNotificationsStart( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic) override; - void OnNotificationsStop( - const device::BluetoothDevice* device, - const device::BluetoothLocalGattCharacteristic* characteristic) override; - - // extensions::ExtensionRegistryObserver overrides: - void OnExtensionUnloaded( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UnloadedExtensionInfo::Reason reason) override; - - // Adds a mapping for a local characteristic ID to its service ID - void AddLocalCharacteristic(const std::string& id, - const std::string& service_id); - // Returns a BluetoothGattCharacteristic by its ID |id|. - // Returns NULL, if the characteristic cannot be found. - device::BluetoothLocalGattCharacteristic* GetLocalCharacteristic( - const std::string& id) const; - - // Adds a mapping for a service_id to the id of the app that owns it. - void AddServiceToApp(const std::string& app_id, - const std::string& service_id); - - // Removes a mapping for a service_id to the id of the app that owns it. - void RemoveServiceFromApp(const std::string& app_id, - const std::string& service_id); - - // Register a local GATT service. - void RegisterGattService(const Extension* extension, - const std::string& service_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Unregister a local GATT service. - void UnregisterGattService(const Extension* extension, - const std::string& service_id, - const base::Closure& callback, - const ErrorCallback& error_callback); - - // Handle a response from the app for the given request id. - void HandleRequestResponse(const Extension* extension, - size_t request_id, - bool is_error, - const std::vector<uint8_t>& value); - - device::BluetoothAdapter* adapter() { return adapter_.get(); } - - private: - // Called by BluetoothAdapterFactory. - void OnGetAdapter(const base::Closure& callback, - scoped_refptr<device::BluetoothAdapter> adapter); - - // Initializes the identifier for all existing GATT objects and devices. - // Called by OnGetAdapter and SetAdapterForTesting. - void InitializeIdentifierMappings(); - - // Sends the event named |event_name| to all listeners of that event that - // have the Bluetooth UUID manifest permission for UUID |uuid| and the - // "low_energy" manifest permission, with |args| as the argument to that - // event. If the event involves a characteristic, then |characteristic_id| - // should be the instance ID of the involved characteristic. Otherwise, an - // empty string should be passed. - void DispatchEventToExtensionsWithPermission( - events::HistogramValue histogram_value, - const std::string& event_name, - const device::BluetoothUUID& uuid, - const std::string& characteristic_id, - std::unique_ptr<base::ListValue> args); - - void DispatchEventToExtension(const std::string& extension_id, - events::HistogramValue histogram_value, - const std::string& event_name, - std::unique_ptr<base::ListValue> args); - - // Returns a BluetoothRemoteGattService by its instance ID |instance_id|. - // Returns - // NULL, if the service cannot be found. - device::BluetoothRemoteGattService* FindServiceById( - const std::string& instance_id) const; - - // Returns a BluetoothRemoteGattCharacteristic by its instance ID - // |instance_id|. - // Returns NULL, if the characteristic cannot be found. - device::BluetoothRemoteGattCharacteristic* FindCharacteristicById( - const std::string& instance_id) const; - - // Returns a BluetoothRemoteGattDescriptor by its instance ID |instance_id|. - // Returns NULL, if the descriptor cannot be found. - device::BluetoothRemoteGattDescriptor* FindDescriptorById( - const std::string& instance_id) const; - - // Called by BluetoothRemoteGattCharacteristic and - // BluetoothRemoteGattDescriptor in - // response to ReadRemoteCharacteristic and ReadRemoteDescriptor. - void OnValueSuccess(const base::Closure& callback, - const std::vector<uint8_t>& value); - - // Called by BluetoothDevice in response to a call to CreateGattConnection. - void OnCreateGattConnection( - bool persistent, - const std::string& extension_id, - const std::string& device_address, - const base::Closure& callback, - std::unique_ptr<device::BluetoothGattConnection> connection); - - // Called by BluetoothGattService in response to Register(). - void OnRegisterGattServiceSuccess(const std::string& service_id, - const std::string& extension_id, - const base::Closure& callback); - - // Called by BluetoothGattService in response to Unregister(). - void OnUnregisterGattServiceSuccess(const std::string& service_id, - const std::string& extension_id, - const base::Closure& callback); - - // Called by BluetoothRemoteGattCharacteristic and - // BluetoothRemoteGattDescriptor in - // case of an error during the read/write operations. - void OnError(const ErrorCallback& error_callback, - device::BluetoothRemoteGattService::GattErrorCode error_code); - - // Called by BluetoothDevice in response to a call to CreateGattConnection. - void OnConnectError(const std::string& extension_id, - const std::string& device_address, - const ErrorCallback& error_callback, - device::BluetoothDevice::ConnectErrorCode error_code); - - // Called by BluetoothRemoteGattCharacteristic in response to a call to - // StartNotifySession. - void OnStartNotifySession( - bool persistent, - const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback, - std::unique_ptr<device::BluetoothGattNotifySession> session); - - // Called by BluetoothRemoteGattCharacteristic in response to a call to - // StartNotifySession. - void OnStartNotifySessionError( - const std::string& extension_id, - const std::string& characteristic_id, - const ErrorCallback& error_callback, - device::BluetoothRemoteGattService::GattErrorCode error_code); - - // Called by BluetoothGattNotifySession in response to a call to Stop. - void OnStopNotifySession(const std::string& extension_id, - const std::string& characteristic_id, - const base::Closure& callback); - - // Finds and returns a BluetoothLowEnergyConnection to device with address - // |device_address| from the managed API resources for extension with ID - // |extension_id|. - BluetoothLowEnergyConnection* FindConnection( - const std::string& extension_id, - const std::string& device_address); - - // Removes the connection to device with address |device_address| from the - // managed API resources for extension with ID |extension_id|. Returns false, - // if the connection could not be found. - bool RemoveConnection(const std::string& extension_id, - const std::string& device_address); - - // Finds and returns a BluetoothLowEnergyNotifySession associated with - // characteristic with instance ID |characteristic_id| from the managed API - // API resources for extension with ID |extension_id|. - BluetoothLowEnergyNotifySession* FindNotifySession( - const std::string& extension_id, - const std::string& characteristic_id); - - // Removes the notify session associated with characteristic with - // instance ID |characteristic_id| from the managed API resources for - // extension with ID |extension_id|. Returns false, if the session could - // not be found. - bool RemoveNotifySession(const std::string& extension_id, - const std::string& characteristic_id); - - // Stores a request associated with an app and returns the ID of the request. - // When an app sends a request to an app for getting/setting an attribute - // value, we store that request so when the response comes in, we know where - // to forward the results of the request. - size_t StoreSentRequest(const std::string& extension_id, - std::unique_ptr<AttributeValueRequest> request); - - // Mapping from instance ids to identifiers of owning instances. The keys are - // used to identify individual instances of GATT objects and are used by - // bluetoothLowEnergy API functions to obtain the correct GATT object to - // operate on. Instance IDs are string identifiers that are returned by the - // device/bluetooth API, by calling GetIdentifier() on the corresponding - // device::BluetoothGatt* instance. - // - // This mapping is necessary, as GATT object instances can only be obtained - // from the object that owns it, where raw pointers should not be cached. E.g. - // to obtain a device::BluetoothRemoteGattCharacteristic, it is necessary to - // obtain - // a pointer to the associated device::BluetoothDevice, and then to the - // device::BluetoothRemoteGattService that owns the characteristic. - using InstanceIdMap = std::map<std::string, std::string>; - InstanceIdMap service_id_to_device_address_; - InstanceIdMap chrc_id_to_service_id_; - InstanceIdMap desc_id_to_chrc_id_; - - // Map of which services are registered by which app. Used to route attribute - // read/write events. - InstanceIdMap service_id_to_extension_id_; - - // Pointer to the current BluetoothAdapter instance. This represents a local - // Bluetooth adapter of the system. - scoped_refptr<device::BluetoothAdapter> adapter_; - - // Set of extension ID + device addresses to which a connect/disconnect is - // currently pending. - std::set<std::string> connecting_devices_; - std::set<std::string> disconnecting_devices_; - - // Set of extension ID + characteristic ID to which a request to start a - // notify session is currently pending. - std::set<std::string> pending_session_calls_; - - using RequestIdToRequestMap = - std::map<size_t, std::unique_ptr<AttributeValueRequest>>; - using ExtensionToRequestsMap = - std::map<std::string, std::unique_ptr<RequestIdToRequestMap>>; - // Map of callback requests sent to the app for attribute value read/write - // requests. - ExtensionToRequestsMap requests_; - // The last request ID we used. - size_t last_callback_request_id_; - - // Map of locally hosted GATT service ids created by app_id. Used for cleanup. - std::map<std::string, std::vector<std::string>> app_id_to_service_ids_; - - // BrowserContext passed during initialization. - content::BrowserContext* browser_context_; - - // Listen to extension unloaded notification. - ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; - - // Note: This should remain the last member so it'll be destroyed and - // invalidate its weak pointers before any other members are destroyed. - base::WeakPtrFactory<BluetoothLowEnergyEventRouter> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyEventRouter); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_EVENT_ROUTER_H_ diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc deleted file mode 100644 index 714a5bffb7a..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h" - -#include "base/lazy_instance.h" - -namespace extensions { - -static base::LazyInstance<BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyNotifySession> > > g_factory = - LAZY_INSTANCE_INITIALIZER; - -template <> -BrowserContextKeyedAPIFactory< - ApiResourceManager<BluetoothLowEnergyNotifySession> >* -ApiResourceManager<BluetoothLowEnergyNotifySession>::GetFactoryInstance() { - return g_factory.Pointer(); -} - -BluetoothLowEnergyNotifySession::BluetoothLowEnergyNotifySession( - bool persistent, - const std::string& owner_extension_id, - std::unique_ptr<device::BluetoothGattNotifySession> session) - : ApiResource(owner_extension_id), - persistent_(persistent), - session_(session.release()) {} - -BluetoothLowEnergyNotifySession::~BluetoothLowEnergyNotifySession() { -} - -device::BluetoothGattNotifySession* -BluetoothLowEnergyNotifySession::GetSession() const { - return session_.get(); -} - -bool BluetoothLowEnergyNotifySession::IsPersistent() const { - return persistent_; -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h deleted file mode 100644 index b5a4cae5f0e..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_NOTIFY_SESSION_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_NOTIFY_SESSION_H_ - -#include <memory> -#include <string> - -#include "base/macros.h" -#include "device/bluetooth/bluetooth_gatt_notify_session.h" -#include "extensions/browser/api/api_resource.h" -#include "extensions/browser/api/api_resource_manager.h" - -namespace extensions { - -// An ApiResource wrapper for a device::BluetoothGattNotifySession -class BluetoothLowEnergyNotifySession : public ApiResource { - public: - explicit BluetoothLowEnergyNotifySession( - bool persistent, - const std::string& owner_extension_id, - std::unique_ptr<device::BluetoothGattNotifySession> session); - ~BluetoothLowEnergyNotifySession() override; - - // Returns a pointer to the underlying session object. - device::BluetoothGattNotifySession* GetSession() const; - - // ApiResource override. - bool IsPersistent() const override; - - // This resource should be managed on the UI thread. - static const content::BrowserThread::ID kThreadId = - content::BrowserThread::UI; - - private: - friend class ApiResourceManager<BluetoothLowEnergyNotifySession>; - static const char* service_name() { - return "BluetoothLowEnergyNotifySessionManager"; - } - - // True, if this resource should be persistent across suspends. - bool persistent_; - - // The session is owned by this instance and will automatically stop when - // deleted. - std::unique_ptr<device::BluetoothGattNotifySession> session_; - - DISALLOW_COPY_AND_ASSIGN(BluetoothLowEnergyNotifySession); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_BLUETOOTH_LOW_ENERGY_NOTIFY_SESSION_H_ diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/utils.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/utils.cc deleted file mode 100644 index 61befe6ed9f..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/utils.cc +++ /dev/null @@ -1,66 +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/extensions/api/bluetooth_low_energy/utils.h" - -#include <stddef.h> -#include <iterator> -#include <vector> - -#include "base/logging.h" - -namespace extensions { -namespace api { -namespace bluetooth_low_energy { - -namespace { - -// Converts a list of CharacteristicProperty to a base::ListValue of strings. -std::unique_ptr<base::ListValue> CharacteristicPropertiesToValue( - const std::vector<CharacteristicProperty> properties) { - std::unique_ptr<base::ListValue> property_list(new base::ListValue()); - for (std::vector<CharacteristicProperty>::const_iterator iter = - properties.begin(); - iter != properties.end(); - ++iter) - property_list->AppendString(ToString(*iter)); - return property_list; -} - -} // namespace - -std::unique_ptr<base::DictionaryValue> CharacteristicToValue( - Characteristic* from) { - // Copy the properties. Use Characteristic::ToValue to generate the result - // dictionary without the properties, to prevent json_schema_compiler from - // failing. - std::vector<CharacteristicProperty> properties = from->properties; - from->properties.clear(); - std::unique_ptr<base::DictionaryValue> to = from->ToValue(); - to->SetWithoutPathExpansion( - "properties", CharacteristicPropertiesToValue(properties).release()); - return to; -} - -std::unique_ptr<base::DictionaryValue> DescriptorToValue(Descriptor* from) { - if (!from->characteristic) - return from->ToValue(); - - // Copy the characteristic properties and set them later manually. - std::vector<CharacteristicProperty> properties = - from->characteristic->properties; - from->characteristic->properties.clear(); - std::unique_ptr<base::DictionaryValue> to = from->ToValue(); - - base::DictionaryValue* chrc_value = NULL; - to->GetDictionaryWithoutPathExpansion("characteristic", &chrc_value); - DCHECK(chrc_value); - chrc_value->SetWithoutPathExpansion( - "properties", CharacteristicPropertiesToValue(properties).release()); - return to; -} - -} // namespace bluetooth_low_energy -} // namespace api -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/utils.h b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/utils.h deleted file mode 100644 index 18821d7caf0..00000000000 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/utils.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_UTILS_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_UTILS_H_ - -#include <memory> - -#include "base/values.h" -#include "chrome/common/extensions/api/bluetooth_low_energy.h" - -namespace extensions { -namespace api { -namespace bluetooth_low_energy { - -// TODO(armansito): Remove these functions once the described bug is fixed. -// (See crbug.com/368368) - -// Converts a Characteristic to a base::Value. This function is necessary as -// json_schema_compiler::util::AddItemToList has no template specialization for -// user defined enums, which get treated as integers. This is because -// Characteristic contains a list of enum CharacteristicProperty. -std::unique_ptr<base::DictionaryValue> CharacteristicToValue( - Characteristic* from); - -// Converts a Descriptor to a base::Value. This function is necessary as a -// Descriptor embeds a Characteristic and that needs special handling as -// described above. -std::unique_ptr<base::DictionaryValue> DescriptorToValue(Descriptor* from); - -} // namespace bluetooth_low_energy -} // namespace api -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_BLUETOOTH_LOW_ENERGY_UTILS_H_ diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc index 30e14d6c483..bfe4f352c37 100644 --- a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc @@ -12,7 +12,6 @@ #include <vector> #include "base/lazy_instance.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -35,6 +34,7 @@ #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/bookmarks/managed/managed_bookmark_service.h" #include "components/prefs/pref_service.h" +#include "components/strings/grit/components_strings.h" #include "components/undo/bookmark_undo_service.h" #include "components/user_prefs/user_prefs.h" #include "content/public/browser/render_view_host.h" @@ -42,7 +42,6 @@ #include "content/public/browser/web_ui.h" #include "extensions/browser/extension_function_dispatcher.h" #include "extensions/browser/view_type_utils.h" -#include "grit/components_strings.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" @@ -158,7 +157,7 @@ bookmark_manager_private::BookmarkNodeData CreateApiBookmarkNodeData( if (node_data.same_profile) { std::vector<const BookmarkNode*> nodes = data.GetNodes( - BookmarkModelFactory::GetForProfile(profile), profile_path); + BookmarkModelFactory::GetForBrowserContext(profile), profile_path); for (size_t i = 0; i < nodes.size(); ++i) { node_data.elements.push_back( CreateNodeDataElementFromBookmarkNode(*nodes[i])); @@ -190,8 +189,8 @@ void BookmarkManagerPrivateEventRouter::DispatchEvent( const std::string& event_name, std::unique_ptr<base::ListValue> event_args) { EventRouter::Get(browser_context_) - ->BroadcastEvent(base::WrapUnique( - new Event(histogram_value, event_name, std::move(event_args)))); + ->BroadcastEvent(base::MakeUnique<Event>(histogram_value, event_name, + std::move(event_args))); } void BookmarkManagerPrivateEventRouter::BookmarkModelChanged() {} @@ -280,8 +279,7 @@ void BookmarkManagerPrivateAPI::OnListenerAdded( EventRouter::Get(browser_context_)->UnregisterObserver(this); event_router_.reset(new BookmarkManagerPrivateEventRouter( browser_context_, - BookmarkModelFactory::GetForProfile( - Profile::FromBrowserContext(browser_context_)))); + BookmarkModelFactory::GetForBrowserContext(browser_context_))); } BookmarkManagerPrivateDragEventRouter::BookmarkManagerPrivateDragEventRouter( @@ -400,7 +398,8 @@ bool BookmarkManagerPrivatePasteFunction::RunOnReady() { std::unique_ptr<Paste::Params> params(Paste::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* parent_node = GetNodeFromString(model, params->parent_id); if (!CanBeModified(parent_node)) return false; @@ -435,7 +434,8 @@ bool BookmarkManagerPrivateCanPasteFunction::RunOnReady() { return true; } - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* parent_node = GetNodeFromString(model, params->parent_id); if (!parent_node) { error_ = bookmark_keys::kNoParentError; @@ -454,7 +454,8 @@ bool BookmarkManagerPrivateSortChildrenFunction::RunOnReady() { SortChildren::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* parent_node = GetNodeFromString(model, params->parent_id); if (!CanBeModified(parent_node)) return false; @@ -552,7 +553,8 @@ bool BookmarkManagerPrivateStartDragFunction::RunOnReady() { std::unique_ptr<StartDrag::Params> params(StartDrag::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); std::vector<const BookmarkNode*> nodes; EXTENSION_FUNCTION_VALIDATE( GetNodesFromVector(model, params->id_list, &nodes)); @@ -578,7 +580,8 @@ bool BookmarkManagerPrivateDropFunction::RunOnReady() { std::unique_ptr<Drop::Params> params(Drop::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* drop_parent = GetNodeFromString(model, params->parent_id); if (!CanBeModified(drop_parent)) @@ -625,7 +628,8 @@ bool BookmarkManagerPrivateGetSubtreeFunction::RunOnReady() { const BookmarkNode* node = NULL; if (params->id.empty()) { - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); node = model->root_node(); } else { node = GetBookmarkNodeFromId(params->id); @@ -663,7 +667,8 @@ bool BookmarkManagerPrivateCreateWithMetaInfoFunction::RunOnReady() { CreateWithMetaInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* node = CreateBookmarkNode( model, params->bookmark, ¶ms->meta_info.additional_properties); if (!node) @@ -714,7 +719,8 @@ bool BookmarkManagerPrivateGetMetaInfoFunction::RunOnReady() { return true; } - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* node = model->root_node(); GetMetaInfo::Results::Value result; @@ -744,7 +750,8 @@ bool BookmarkManagerPrivateSetMetaInfoFunction::RunOnReady() { if (!CanBeModified(node)) return false; - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); if (model->is_permanent_node(node)) { error_ = bookmark_keys::kModifySpecialError; return false; @@ -769,7 +776,8 @@ bool BookmarkManagerPrivateUpdateMetaInfoFunction::RunOnReady() { if (!CanBeModified(node)) return false; - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); if (model->is_permanent_node(node)) { error_ = bookmark_keys::kModifySpecialError; return false; diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_apitest.cc b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_apitest.cc index 1ec66b72e41..c64ba831db1 100644 --- a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_apitest.cc @@ -35,7 +35,7 @@ using bookmarks::BookmarkNode; IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_BookmarkManager) { // Add managed bookmarks. Profile* profile = browser()->profile(); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile); + BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(profile); bookmarks::ManagedBookmarkService* managed = ManagedBookmarkServiceFactory::GetForProfile(profile); bookmarks::test::WaitForBookmarkModelToLoad(model); @@ -61,7 +61,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, BookmarkManagerEditDisabled) { // Provide some testing data here, since bookmark editing will be disabled // within the extension. - BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile); + BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(profile); bookmarks::test::WaitForBookmarkModelToLoad(model); const BookmarkNode* bar = model->bookmark_bar_node(); const BookmarkNode* folder = 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 392b95e4f7b..82aa4debff5 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 @@ -43,7 +43,7 @@ class ExtensionBookmarksTest : public testing::Test { void SetUp() override { profile_.CreateBookmarkModel(false); - model_ = BookmarkModelFactory::GetForProfile(&profile_); + model_ = BookmarkModelFactory::GetForBrowserContext(&profile_); managed_ = ManagedBookmarkServiceFactory::GetForProfile(&profile_); bookmarks::test::WaitForBookmarkModelToLoad(model_); diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc index 39fd91418f5..75fe94389b0 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc @@ -31,7 +31,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Bookmarks) { // Add test managed and supervised bookmarks to verify that the bookmarks API // can read them and can't modify them. Profile* profile = browser()->profile(); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile); + BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(profile); bookmarks::ManagedBookmarkService* managed = ManagedBookmarkServiceFactory::GetForProfile(profile); bookmarks::test::WaitForBookmarkModelToLoad(model); diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index a21f74a1cf9..a9e78ad8b92 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc @@ -96,7 +96,8 @@ base::FilePath GetDefaultFilepathForBookmarkExport() { } // namespace bool BookmarksFunction::RunAsync() { - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); if (!model->loaded()) { // Bookmarks are not ready yet. We'll wait. model->AddObserver(this); @@ -109,7 +110,7 @@ bool BookmarksFunction::RunAsync() { } BookmarkModel* BookmarksFunction::GetBookmarkModel() { - return BookmarkModelFactory::GetForProfile(GetProfile()); + return BookmarkModelFactory::GetForBrowserContext(GetProfile()); } ManagedBookmarkService* BookmarksFunction::GetManagedBookmarkService() { @@ -132,7 +133,7 @@ const BookmarkNode* BookmarksFunction::GetBookmarkNodeFromId( return NULL; const BookmarkNode* node = ::bookmarks::GetBookmarkNodeByID( - BookmarkModelFactory::GetForProfile(GetProfile()), id); + BookmarkModelFactory::GetForBrowserContext(GetProfile()), id); if (!node) error_ = keys::kNoNodeError; @@ -170,11 +171,11 @@ const BookmarkNode* BookmarksFunction::CreateBookmarkNode( base::string16 title; // Optional. if (details.title.get()) - title = base::UTF8ToUTF16(*details.title.get()); + title = base::UTF8ToUTF16(*details.title); std::string url_string; // Optional. if (details.url.get()) - url_string = *details.url.get(); + url_string = *details.url; GURL url(url_string); if (!url_string.empty() && !url.is_valid()) { @@ -245,7 +246,7 @@ void BookmarksFunction::RunAndSendResponse() { BookmarkEventRouter::BookmarkEventRouter(Profile* profile) : browser_context_(profile), - model_(BookmarkModelFactory::GetForProfile(profile)), + model_(BookmarkModelFactory::GetForBrowserContext(profile)), managed_(ManagedBookmarkServiceFactory::GetForProfile(profile)) { model_->AddObserver(this); } @@ -262,8 +263,8 @@ void BookmarkEventRouter::DispatchEvent( std::unique_ptr<base::ListValue> event_args) { EventRouter* event_router = EventRouter::Get(browser_context_); if (event_router) { - event_router->BroadcastEvent(base::WrapUnique(new extensions::Event( - histogram_value, event_name, std::move(event_args)))); + event_router->BroadcastEvent(base::MakeUnique<extensions::Event>( + histogram_value, event_name, std::move(event_args))); } } @@ -476,9 +477,8 @@ bool BookmarksGetRecentFunction::RunOnReady() { std::vector<const BookmarkNode*> nodes; ::bookmarks::GetMostRecentlyAddedEntries( - BookmarkModelFactory::GetForProfile(GetProfile()), - params->number_of_items, - &nodes); + BookmarkModelFactory::GetForBrowserContext(GetProfile()), + params->number_of_items, &nodes); std::vector<BookmarkTreeNode> tree_nodes; for (const BookmarkNode* node : nodes) { @@ -493,7 +493,7 @@ bool BookmarksGetRecentFunction::RunOnReady() { bool BookmarksGetTreeFunction::RunOnReady() { std::vector<BookmarkTreeNode> nodes; const BookmarkNode* node = - BookmarkModelFactory::GetForProfile(GetProfile())->root_node(); + BookmarkModelFactory::GetForBrowserContext(GetProfile())->root_node(); bookmark_api_helpers::AddNode(GetManagedBookmarkService(), node, &nodes, true); results_ = bookmarks::GetTree::Results::Create(nodes); @@ -527,10 +527,8 @@ bool BookmarksSearchFunction::RunOnReady() { query.word_phrase_query.reset( new base::string16(base::UTF8ToUTF16(*params->query.as_string))); ::bookmarks::GetBookmarksMatchingProperties( - BookmarkModelFactory::GetForProfile(GetProfile()), - query, - std::numeric_limits<int>::max(), - &nodes); + BookmarkModelFactory::GetForBrowserContext(GetProfile()), query, + std::numeric_limits<int>::max(), &nodes); } else { DCHECK(params->query.as_object); const bookmarks::Search::Params::Query::Object& object = @@ -545,10 +543,8 @@ bool BookmarksSearchFunction::RunOnReady() { if (object.title) query.title.reset(new base::string16(base::UTF8ToUTF16(*object.title))); ::bookmarks::GetBookmarksMatchingProperties( - BookmarkModelFactory::GetForProfile(GetProfile()), - query, - std::numeric_limits<int>::max(), - &nodes); + BookmarkModelFactory::GetForBrowserContext(GetProfile()), query, + std::numeric_limits<int>::max(), &nodes); } std::vector<BookmarkTreeNode> tree_nodes; @@ -607,7 +603,8 @@ bool BookmarksCreateFunction::RunOnReady() { bookmarks::Create::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); const BookmarkNode* node = CreateBookmarkNode(model, params->bookmark, NULL); if (!node) return false; @@ -639,7 +636,8 @@ bool BookmarksMoveFunction::RunOnReady() { if (!node) return false; - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); if (model->is_permanent_node(node)) { error_ = keys::kModifySpecialError; return false; @@ -717,7 +715,8 @@ bool BookmarksUpdateFunction::RunOnReady() { if (!CanBeModified(node)) return false; - BookmarkModel* model = BookmarkModelFactory::GetForProfile(GetProfile()); + BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(GetProfile()); if (model->is_permanent_node(node)) { error_ = keys::kModifySpecialError; return false; diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc b/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc index 5739710383d..10dd503680c 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc +++ b/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc @@ -6,14 +6,13 @@ #include <errno.h> +#include "base/files/file_descriptor_watcher_posix.h" #include "base/macros.h" #include "base/memory/free_deleter.h" -#include "base/message_loop/message_loop.h" #include "base/sys_info.h" #include "build/build_config.h" namespace extensions { -using base::MessageLoopForIO; namespace api { namespace braille_display_private { @@ -30,8 +29,7 @@ static const int kDefaultTtyChromeOS = 1; #endif } // namespace -class BrlapiConnectionImpl : public BrlapiConnection, - MessageLoopForIO::Watcher { +class BrlapiConnectionImpl : public BrlapiConnection { public: explicit BrlapiConnectionImpl(LibBrlapiLoader* loader) : libbrlapi_loader_(loader) {} @@ -47,19 +45,13 @@ class BrlapiConnectionImpl : public BrlapiConnection, bool WriteDots(const unsigned char* cells) override; int ReadKey(brlapi_keyCode_t* keyCode) override; - // MessageLoopForIO::Watcher - void OnFileCanReadWithoutBlocking(int fd) override { on_data_ready_.Run(); } - - void OnFileCanWriteWithoutBlocking(int fd) override {} - private: bool CheckConnected(); ConnectResult ConnectResultForError(); LibBrlapiLoader* libbrlapi_loader_; std::unique_ptr<brlapi_handle_t, base::FreeDeleter> handle_; - MessageLoopForIO::FileDescriptorWatcher fd_controller_; - OnDataReadyCallback on_data_ready_; + std::unique_ptr<base::FileDescriptorWatcher::Controller> fd_controller_; DISALLOW_COPY_AND_ASSIGN(BrlapiConnectionImpl); }; @@ -132,14 +124,8 @@ BrlapiConnection::ConnectResult BrlapiConnectionImpl::Connect( return CONNECT_ERROR_RETRY; } - if (!MessageLoopForIO::current()->WatchFileDescriptor( - fd, true, MessageLoopForIO::WATCH_READ, &fd_controller_, this)) { - LOG(ERROR) << "Couldn't watch file descriptor " << fd; - Disconnect(); - return CONNECT_ERROR_RETRY; - } - - on_data_ready_ = on_data_ready; + fd_controller_ = + base::FileDescriptorWatcher::WatchReadable(fd, on_data_ready); return CONNECT_SUCCESS; } @@ -148,7 +134,7 @@ void BrlapiConnectionImpl::Disconnect() { if (!handle_) { return; } - fd_controller_.StopWatchingFileDescriptor(); + fd_controller_.reset(); libbrlapi_loader_->brlapi__closeConnection( handle_.get()); handle_.reset(); diff --git a/chromium/chrome/browser/extensions/api/browser/browser_api.cc b/chromium/chrome/browser/extensions/api/browser/browser_api.cc index 78bd303fefe..205d583b013 100644 --- a/chromium/chrome/browser/extensions/api/browser/browser_api.cc +++ b/chromium/chrome/browser/extensions/api/browser/browser_api.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/browser/browser_api.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/common/extensions/api/browser.h" namespace extensions { namespace api { @@ -12,7 +13,7 @@ namespace api { BrowserOpenTabFunction::~BrowserOpenTabFunction() { } -bool BrowserOpenTabFunction::RunSync() { +ExtensionFunction::ResponseAction BrowserOpenTabFunction::Run() { std::unique_ptr<browser::OpenTab::Params> params( browser::OpenTab::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -24,12 +25,10 @@ bool BrowserOpenTabFunction::RunSync() { std::string error; std::unique_ptr<base::DictionaryValue> result( ExtensionTabUtil::OpenTab(this, options, &error)); - if (!result) { - SetError(error); - return false; - } + if (!result) + return RespondNow(Error(error)); - return true; + return RespondNow(NoArguments()); } } // namespace api diff --git a/chromium/chrome/browser/extensions/api/browser/browser_api.h b/chromium/chrome/browser/extensions/api/browser/browser_api.h index 634c568b384..80e8ec23e9e 100644 --- a/chromium/chrome/browser/extensions/api/browser/browser_api.h +++ b/chromium/chrome/browser/extensions/api/browser/browser_api.h @@ -5,20 +5,19 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_BROWSER_BROWSER_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_BROWSER_BROWSER_API_H_ -#include "chrome/browser/extensions/chrome_extension_function.h" -#include "chrome/common/extensions/api/browser.h" +#include "extensions/browser/extension_function.h" namespace extensions { namespace api { -class BrowserOpenTabFunction : public ChromeSyncExtensionFunction { +class BrowserOpenTabFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("browser.openTab", BROWSER_OPENTAB) protected: ~BrowserOpenTabFunction() override; - bool RunSync() override; + ResponseAction Run() override; }; } // namespace api 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 0e329e57d76..b15e0576bfe 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 @@ -21,6 +21,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" +#include "components/browsing_data/core/pref_names.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/error_utils.h" #include "extensions/common/extension.h" @@ -76,8 +77,7 @@ int MaskForKey(const char* key) { if (strcmp(key, extension_browsing_data_api_constants::kCacheKey) == 0) return BrowsingDataRemover::REMOVE_CACHE; if (strcmp(key, extension_browsing_data_api_constants::kCookiesKey) == 0) { - return BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_WEBRTC_IDENTITY; + return BrowsingDataRemover::REMOVE_COOKIES; } if (strcmp(key, extension_browsing_data_api_constants::kDownloadsKey) == 0) return BrowsingDataRemover::REMOVE_DOWNLOADS; @@ -123,8 +123,8 @@ bool IsRemovalPermitted(int removal_mask, PrefService* prefs) { } // namespace -bool BrowsingDataSettingsFunction::RunSync() { - PrefService* prefs = GetProfile()->GetPrefs(); +ExtensionFunction::ResponseAction BrowsingDataSettingsFunction::Run() { + prefs_ = Profile::FromBrowserContext(browser_context())->GetPrefs(); // Fill origin types. // The "cookies" and "hosted apps" UI checkboxes both map to @@ -135,20 +135,20 @@ bool BrowsingDataSettingsFunction::RunSync() { new base::DictionaryValue); origin_types->SetBoolean( extension_browsing_data_api_constants::kUnprotectedWebKey, - prefs->GetBoolean(prefs::kDeleteCookies)); + prefs_->GetBoolean(browsing_data::prefs::kDeleteCookies)); origin_types->SetBoolean( extension_browsing_data_api_constants::kProtectedWebKey, - prefs->GetBoolean(prefs::kDeleteHostedAppsData)); + prefs_->GetBoolean(browsing_data::prefs::kDeleteHostedAppsData)); origin_types->SetBoolean( extension_browsing_data_api_constants::kExtensionsKey, false); // Fill deletion time period. - int period_pref = prefs->GetInteger(prefs::kDeleteTimePeriod); - BrowsingDataRemover::TimePeriod period = - static_cast<BrowsingDataRemover::TimePeriod>(period_pref); + int period_pref = prefs_->GetInteger(browsing_data::prefs::kDeleteTimePeriod); + browsing_data::TimePeriod period = + static_cast<browsing_data::TimePeriod>(period_pref); double since = 0; - if (period != BrowsingDataRemover::EVERYTHING) { - base::Time time = BrowsingDataRemover::CalculateBeginDeleteTime(period); + if (period != browsing_data::ALL_TIME) { + base::Time time = browsing_data::CalculateBeginDeleteTime(period); since = time.ToJsTime(); } @@ -161,8 +161,9 @@ bool BrowsingDataSettingsFunction::RunSync() { std::unique_ptr<base::DictionaryValue> selected(new base::DictionaryValue); std::unique_ptr<base::DictionaryValue> permitted(new base::DictionaryValue); - bool delete_site_data = prefs->GetBoolean(prefs::kDeleteCookies) || - prefs->GetBoolean(prefs::kDeleteHostedAppsData); + bool delete_site_data = + prefs_->GetBoolean(browsing_data::prefs::kDeleteCookies) || + prefs_->GetBoolean(browsing_data::prefs::kDeleteHostedAppsData); SetDetails(selected.get(), permitted.get(), extension_browsing_data_api_constants::kAppCacheKey, @@ -193,24 +194,25 @@ bool BrowsingDataSettingsFunction::RunSync() { delete_site_data); SetDetails(selected.get(), permitted.get(), - extension_browsing_data_api_constants::kPluginDataKey, - delete_site_data && prefs->GetBoolean(prefs::kClearPluginLSODataEnabled)); + extension_browsing_data_api_constants::kPluginDataKey, + delete_site_data && + prefs_->GetBoolean(prefs::kClearPluginLSODataEnabled)); SetDetails(selected.get(), permitted.get(), extension_browsing_data_api_constants::kHistoryKey, - prefs->GetBoolean(prefs::kDeleteBrowsingHistory)); + prefs_->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory)); SetDetails(selected.get(), permitted.get(), extension_browsing_data_api_constants::kDownloadsKey, - prefs->GetBoolean(prefs::kDeleteDownloadHistory)); + prefs_->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory)); SetDetails(selected.get(), permitted.get(), extension_browsing_data_api_constants::kCacheKey, - prefs->GetBoolean(prefs::kDeleteCache)); + prefs_->GetBoolean(browsing_data::prefs::kDeleteCache)); SetDetails(selected.get(), permitted.get(), extension_browsing_data_api_constants::kFormDataKey, - prefs->GetBoolean(prefs::kDeleteFormData)); + prefs_->GetBoolean(browsing_data::prefs::kDeleteFormData)); SetDetails(selected.get(), permitted.get(), extension_browsing_data_api_constants::kPasswordsKey, - prefs->GetBoolean(prefs::kDeletePasswords)); + prefs_->GetBoolean(browsing_data::prefs::kDeletePasswords)); std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue); result->Set(extension_browsing_data_api_constants::kOptionsKey, @@ -219,8 +221,7 @@ bool BrowsingDataSettingsFunction::RunSync() { selected.release()); result->Set(extension_browsing_data_api_constants::kDataRemovalPermittedKey, permitted.release()); - SetResult(std::move(result)); - return true; + return RespondNow(OneArgument(std::move(result))); } void BrowsingDataSettingsFunction::SetDetails( @@ -228,8 +229,7 @@ void BrowsingDataSettingsFunction::SetDetails( base::DictionaryValue* permitted_dict, const char* data_type, bool is_selected) { - bool is_permitted = - IsRemovalPermitted(MaskForKey(data_type), GetProfile()->GetPrefs()); + bool is_permitted = IsRemovalPermitted(MaskForKey(data_type), prefs_); selected_dict->SetBoolean(data_type, is_selected && is_permitted); permitted_dict->SetBoolean(data_type, is_permitted); } @@ -272,7 +272,7 @@ bool BrowsingDataRemoverFunction::RunAsync() { base::Time::FromDoubleT(ms_since_epoch / 1000.0); removal_mask_ = GetRemovalMask(); - if (bad_message_) + if (bad_message()) return false; // Check for prohibited data types. @@ -314,6 +314,7 @@ void BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported( void BrowsingDataRemoverFunction::StartRemoving() { BrowsingDataRemover* remover = BrowsingDataRemoverFactory::GetForBrowserContext(GetProfile()); + // TODO(msramek): This restriction is no longer needed. Remove it. if (remover->is_removing()) { error_ = extension_browsing_data_api_constants::kOneAtATimeError; SendResponse(false); @@ -328,9 +329,9 @@ void BrowsingDataRemoverFunction::StartRemoving() { // we've generated above. We can use a raw pointer here, as the browsing data // remover is responsible for deleting itself once data removal is complete. observer_.Add(remover); - remover->Remove( + remover->RemoveAndReply( BrowsingDataRemover::TimeRange(remove_since_, base::Time::Max()), - removal_mask_, origin_type_mask_); + removal_mask_, origin_type_mask_, this); } int BrowsingDataRemoverFunction::ParseOriginTypeMask( @@ -380,7 +381,7 @@ int BrowsingDataRemoverFunction::ParseOriginTypeMask( int BrowsingDataRemoveFunction::GetRemovalMask() { base::DictionaryValue* data_to_remove; if (!args_->GetDictionary(1, &data_to_remove)) { - bad_message_ = true; + set_bad_message(true); return 0; } @@ -391,7 +392,7 @@ int BrowsingDataRemoveFunction::GetRemovalMask() { i.Advance()) { bool selected = false; if (!i.value().GetAsBoolean(&selected)) { - bad_message_ = true; + set_bad_message(true); return 0; } if (selected) @@ -411,8 +412,7 @@ int BrowsingDataRemoveCacheFunction::GetRemovalMask() { int BrowsingDataRemoveCookiesFunction::GetRemovalMask() { return BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_CHANNEL_IDS | - BrowsingDataRemover::REMOVE_WEBRTC_IDENTITY; + BrowsingDataRemover::REMOVE_CHANNEL_IDS; } int BrowsingDataRemoveDownloadsFunction::GetRemovalMask() { 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 4ef30c6b920..b4c7594af54 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 @@ -16,6 +16,7 @@ #include "chrome/browser/extensions/chrome_extension_function.h" class PluginPrefs; +class PrefService; namespace extension_browsing_data_api_constants { @@ -54,12 +55,12 @@ extern const char kOneAtATimeError[]; } // namespace extension_browsing_data_api_constants -class BrowsingDataSettingsFunction : public ChromeSyncExtensionFunction { +class BrowsingDataSettingsFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("browsingData.settings", BROWSINGDATA_SETTINGS) // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; protected: ~BrowsingDataSettingsFunction() override {} @@ -73,6 +74,8 @@ class BrowsingDataSettingsFunction : public ChromeSyncExtensionFunction { base::DictionaryValue* permitted_dict, const char* data_type, bool is_selected); + + PrefService* prefs_ = nullptr; }; // This serves as a base class from which the browsing data API removal 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 bd999e32b83..394a4f3b255 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 @@ -20,6 +20,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/browsing_data/core/pref_names.h" #include "components/prefs/pref_service.h" using extension_function_test_utils::RunFunctionAndReturnError; @@ -45,34 +46,22 @@ const char kRemoveEverythingArguments[] = class ExtensionBrowsingDataTest : public InProcessBrowserTest { public: - base::Time GetBeginTime() { - return called_with_details_->removal_begin; + const base::Time& GetBeginTime() { + return remover_->GetLastUsedBeginTime(); } int GetRemovalMask() { - return called_with_details_->removal_mask; + return remover_->GetLastUsedRemovalMask(); } int GetOriginTypeMask() { - return called_with_details_->origin_type_mask; + return remover_->GetLastUsedOriginTypeMask(); } protected: void SetUpOnMainThread() override { - called_with_details_.reset(new BrowsingDataRemover::NotificationDetails()); - callback_subscription_ = - BrowsingDataRemover::RegisterOnBrowsingDataRemovedCallback( - base::Bind(&ExtensionBrowsingDataTest::NotifyWithDetails, - base::Unretained(this))); - } - - // Callback for browsing data removal events. - void NotifyWithDetails( - const BrowsingDataRemover::NotificationDetails& details) { - // We're not taking ownership of the details object, but storing a copy of - // it locally. - called_with_details_.reset( - new BrowsingDataRemover::NotificationDetails(details)); + remover_ = + BrowsingDataRemoverFactory::GetForBrowserContext(browser()->profile()); } int GetAsMask(const base::DictionaryValue* dict, std::string path, @@ -129,9 +118,9 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { EXPECT_EQ(UNPROTECTED_WEB, GetOriginTypeMask()); } - void SetSinceAndVerify(BrowsingDataRemover::TimePeriod since_pref) { + void SetSinceAndVerify(browsing_data::TimePeriod since_pref) { PrefService* prefs = browser()->profile()->GetPrefs(); - prefs->SetInteger(prefs::kDeleteTimePeriod, since_pref); + prefs->SetInteger(browsing_data::prefs::kDeleteTimePeriod, since_pref); scoped_refptr<BrowsingDataSettingsFunction> function = new BrowsingDataSettingsFunction(); @@ -147,9 +136,8 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { EXPECT_TRUE(options->GetDouble("since", &since)); double expected_since = 0; - if (since_pref != BrowsingDataRemover::EVERYTHING) { - base::Time time = - BrowsingDataRemover::CalculateBeginDeleteTime(since_pref); + if (since_pref != browsing_data::ALL_TIME) { + base::Time time = CalculateBeginDeleteTime(since_pref); expected_since = time.ToJsTime(); } // Even a synchronous function takes nonzero time, but the difference @@ -164,20 +152,20 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { int expected_origin_type_mask, int expected_removal_mask) { PrefService* prefs = browser()->profile()->GetPrefs(); - prefs->SetBoolean(prefs::kDeleteCache, + prefs->SetBoolean(browsing_data::prefs::kDeleteCache, !!(data_type_flags & BrowsingDataRemover::REMOVE_CACHE)); - prefs->SetBoolean(prefs::kDeleteCookies, + prefs->SetBoolean(browsing_data::prefs::kDeleteCookies, !!(data_type_flags & BrowsingDataRemover::REMOVE_COOKIES)); - prefs->SetBoolean(prefs::kDeleteBrowsingHistory, + prefs->SetBoolean(browsing_data::prefs::kDeleteBrowsingHistory, !!(data_type_flags & BrowsingDataRemover::REMOVE_HISTORY)); - prefs->SetBoolean(prefs::kDeleteFormData, + prefs->SetBoolean(browsing_data::prefs::kDeleteFormData, !!(data_type_flags & BrowsingDataRemover::REMOVE_FORM_DATA)); - prefs->SetBoolean(prefs::kDeleteDownloadHistory, + prefs->SetBoolean(browsing_data::prefs::kDeleteDownloadHistory, !!(data_type_flags & BrowsingDataRemover::REMOVE_DOWNLOADS)); - prefs->SetBoolean(prefs::kDeleteHostedAppsData, + prefs->SetBoolean(browsing_data::prefs::kDeleteHostedAppsData, !!(data_type_flags & BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY)); - prefs->SetBoolean(prefs::kDeletePasswords, + prefs->SetBoolean(browsing_data::prefs::kDeletePasswords, !!(data_type_flags & BrowsingDataRemover::REMOVE_PASSWORDS)); prefs->SetBoolean(prefs::kClearPluginLSODataEnabled, !!(data_type_flags & BrowsingDataRemover::REMOVE_PLUGIN_DATA)); @@ -209,8 +197,7 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { BrowsingDataRemover::REMOVE_APPCACHE) | GetAsMask(data_to_remove, "cache", BrowsingDataRemover::REMOVE_CACHE) | GetAsMask(data_to_remove, "cookies", - BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_WEBRTC_IDENTITY) | + BrowsingDataRemover::REMOVE_COOKIES) | GetAsMask(data_to_remove, "downloads", BrowsingDataRemover::REMOVE_DOWNLOADS) | GetAsMask(data_to_remove, "fileSystems", @@ -257,10 +244,8 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { } private: - std::unique_ptr<BrowsingDataRemover::NotificationDetails> - called_with_details_; - - BrowsingDataRemover::CallbackSubscription callback_subscription_; + // Cached pointer to BrowsingDataRemover for access to testing methods. + BrowsingDataRemover* remover_; }; } // namespace @@ -320,16 +305,20 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, RemoveBrowsingDataAll) { EXPECT_EQ(base::Time::FromDoubleT(1.0), GetBeginTime()); EXPECT_EQ((BrowsingDataRemover::REMOVE_SITE_DATA | - BrowsingDataRemover::REMOVE_CACHE | - BrowsingDataRemover::REMOVE_DOWNLOADS | - BrowsingDataRemover::REMOVE_FORM_DATA | - BrowsingDataRemover::REMOVE_HISTORY | - BrowsingDataRemover::REMOVE_PASSWORDS) & - // TODO(benwells): implement clearing of site usage data via the browsing - // data API. https://crbug.com/500801. - ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & - // We can't remove plugin data inside a test profile. - ~BrowsingDataRemover::REMOVE_PLUGIN_DATA, GetRemovalMask()); + BrowsingDataRemover::REMOVE_CACHE | + BrowsingDataRemover::REMOVE_DOWNLOADS | + BrowsingDataRemover::REMOVE_FORM_DATA | + BrowsingDataRemover::REMOVE_HISTORY | + BrowsingDataRemover::REMOVE_PASSWORDS) & + // TODO(benwells): implement clearing of site usage data via the + // browsing data API. https://crbug.com/500801. + ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & + // TODO(dmurph): implement clearing of durable storage permission + // via the browsing data API. https://crbug.com/500801. + ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION & + // We can't remove plugin data inside a test profile. + ~BrowsingDataRemover::REMOVE_PLUGIN_DATA, + GetRemovalMask()); } IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, BrowsingDataOriginTypeMask) { @@ -365,8 +354,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, RunBrowsingDataRemoveWithKeyAndCompareRemovalMask( "cache", BrowsingDataRemover::REMOVE_CACHE); RunBrowsingDataRemoveWithKeyAndCompareRemovalMask( - "cookies", BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_WEBRTC_IDENTITY); + "cookies", BrowsingDataRemover::REMOVE_COOKIES); RunBrowsingDataRemoveWithKeyAndCompareRemovalMask( "downloads", BrowsingDataRemover::REMOVE_DOWNLOADS); RunBrowsingDataRemoveWithKeyAndCompareRemovalMask( @@ -400,7 +388,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, "{\"appcache\": true, \"cookies\": true, \"history\": true}", BrowsingDataRemover::REMOVE_APPCACHE | BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_WEBRTC_IDENTITY | BrowsingDataRemover::REMOVE_HISTORY); } @@ -408,13 +395,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, BrowsingDataRemovalInputFromSettings) { PrefService* prefs = browser()->profile()->GetPrefs(); - prefs->SetBoolean(prefs::kDeleteCache, true); - prefs->SetBoolean(prefs::kDeleteBrowsingHistory, true); - prefs->SetBoolean(prefs::kDeleteDownloadHistory, true); - prefs->SetBoolean(prefs::kDeleteCookies, false); - prefs->SetBoolean(prefs::kDeleteFormData, false); - prefs->SetBoolean(prefs::kDeleteHostedAppsData, false); - prefs->SetBoolean(prefs::kDeletePasswords, false); + prefs->SetBoolean(browsing_data::prefs::kDeleteCache, true); + prefs->SetBoolean(browsing_data::prefs::kDeleteBrowsingHistory, true); + prefs->SetBoolean(browsing_data::prefs::kDeleteDownloadHistory, true); + prefs->SetBoolean(browsing_data::prefs::kDeleteCookies, false); + prefs->SetBoolean(browsing_data::prefs::kDeleteFormData, false); + prefs->SetBoolean(browsing_data::prefs::kDeleteHostedAppsData, false); + prefs->SetBoolean(browsing_data::prefs::kDeletePasswords, false); prefs->SetBoolean(prefs::kClearPluginLSODataEnabled, false); int expected_mask = BrowsingDataRemover::REMOVE_CACHE | BrowsingDataRemover::REMOVE_DOWNLOADS | @@ -456,8 +443,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, ShortcutFunctionRemovalMask) { BrowsingDataRemover::REMOVE_CACHE); RunAndCompareRemovalMask<BrowsingDataRemoveCookiesFunction>( BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_CHANNEL_IDS | - BrowsingDataRemover::REMOVE_WEBRTC_IDENTITY); + BrowsingDataRemover::REMOVE_CHANNEL_IDS); RunAndCompareRemovalMask<BrowsingDataRemoveDownloadsFunction>( BrowsingDataRemover::REMOVE_DOWNLOADS); RunAndCompareRemovalMask<BrowsingDataRemoveFileSystemsFunction>( @@ -481,11 +467,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, ShortcutFunctionRemovalMask) { // Test the processing of the 'delete since' preference. IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSince) { - SetSinceAndVerify(BrowsingDataRemover::EVERYTHING); - SetSinceAndVerify(BrowsingDataRemover::LAST_HOUR); - SetSinceAndVerify(BrowsingDataRemover::LAST_DAY); - SetSinceAndVerify(BrowsingDataRemover::LAST_WEEK); - SetSinceAndVerify(BrowsingDataRemover::FOUR_WEEKS); + SetSinceAndVerify(browsing_data::ALL_TIME); + SetSinceAndVerify(browsing_data::LAST_HOUR); + SetSinceAndVerify(browsing_data::LAST_DAY); + SetSinceAndVerify(browsing_data::LAST_WEEK); + SetSinceAndVerify(browsing_data::FOUR_WEEKS); } IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionEmpty) { @@ -508,33 +494,37 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSimple) { // Test cookie and app data settings. IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSiteData) { - int site_data_no_usage = BrowsingDataRemover::REMOVE_SITE_DATA & - ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA; - int site_data_no_plugins = site_data_no_usage & - ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; + int site_data_no_durable_or_usage = + BrowsingDataRemover::REMOVE_SITE_DATA & + ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & + ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION; + int site_data_no_plugins_durable_usage = + site_data_no_durable_or_usage & ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_COOKIES, UNPROTECTED_WEB, - site_data_no_plugins); + site_data_no_plugins_durable_usage); SetPrefsAndVerifySettings( BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY, PROTECTED_WEB, - site_data_no_plugins); + site_data_no_plugins_durable_usage); SetPrefsAndVerifySettings( BrowsingDataRemover::REMOVE_COOKIES | BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY, PROTECTED_WEB | UNPROTECTED_WEB, - site_data_no_plugins); + site_data_no_plugins_durable_usage); SetPrefsAndVerifySettings( BrowsingDataRemover::REMOVE_COOKIES | BrowsingDataRemover::REMOVE_PLUGIN_DATA, UNPROTECTED_WEB, - site_data_no_usage); + site_data_no_durable_or_usage); } // Test an arbitrary assortment of settings. IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionAssorted) { - int site_data_no_plugins = BrowsingDataRemover::REMOVE_SITE_DATA & + int site_data_no_plugins_durable_usage = + BrowsingDataRemover::REMOVE_SITE_DATA & + ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION & ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; @@ -543,7 +533,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionAssorted) { BrowsingDataRemover::REMOVE_HISTORY | BrowsingDataRemover::REMOVE_DOWNLOADS, UNPROTECTED_WEB, - site_data_no_plugins | + site_data_no_plugins_durable_usage | BrowsingDataRemover::REMOVE_HISTORY | BrowsingDataRemover::REMOVE_DOWNLOADS); } diff --git a/chromium/chrome/browser/extensions/api/cast_devices_private/cast_devices_private_api.cc b/chromium/chrome/browser/extensions/api/cast_devices_private/cast_devices_private_api.cc index b40895c78d5..8537677e546 100644 --- a/chromium/chrome/browser/extensions/api/cast_devices_private/cast_devices_private_api.cc +++ b/chromium/chrome/browser/extensions/api/cast_devices_private/cast_devices_private_api.cc @@ -99,7 +99,7 @@ CastDevicesPrivateUpdateDevicesFunction::Run() { ConvertReceiverAndActivityType(device.receiver, device.activity.get())); } - auto listeners = CastDeviceUpdateListeners::Get(browser_context()); + auto* listeners = CastDeviceUpdateListeners::Get(browser_context()); listeners->NotifyCallbacks(devices); return RespondNow(NoArguments()); 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 6789ef843c4..848aa5cca59 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 @@ -31,6 +31,7 @@ #include "media/cast/test/utility/standalone_cast_environment.h" #include "net/base/net_errors.h" #include "net/base/rand_callback.h" +#include "net/log/net_log_source.h" #include "net/udp/udp_server_socket.h" #include "testing/gtest/include/gtest/gtest.h" @@ -345,7 +346,7 @@ class CastStreamingApiTestWithPixelOutput : public CastStreamingApiTest { #endif IN_PROC_BROWSER_TEST_F(CastStreamingApiTestWithPixelOutput, MAYBE_EndToEnd) { std::unique_ptr<net::UDPServerSocket> receive_socket( - new net::UDPServerSocket(NULL, net::NetLog::Source())); + new net::UDPServerSocket(NULL, net::NetLogSource())); receive_socket->AllowAddressReuse(); ASSERT_EQ(net::OK, receive_socket->Listen(GetFreeLocalPort())); net::IPEndPoint receiver_end_point; diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc index b70f29686d5..52697efe24c 100644 --- a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc +++ b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc @@ -47,6 +47,7 @@ #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/rand_callback.h" +#include "net/log/net_log_source.h" #include "net/udp/udp_server_socket.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/perf/perf_test.h" @@ -336,7 +337,7 @@ class CastV2PerformanceTest // Method: Bind a UDP socket on port 0, and then check which port the // operating system assigned to it. std::unique_ptr<net::UDPServerSocket> receive_socket( - new net::UDPServerSocket(NULL, net::NetLog::Source())); + new net::UDPServerSocket(NULL, net::NetLogSource())); receive_socket->AllowAddressReuse(); CHECK_EQ(net::OK, receive_socket->Listen( net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0))); 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 163e8985f9a..f4b3aa3c022 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 @@ -27,6 +27,7 @@ #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" +#include "components/policy/policy_constants.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/test_navigation_observer.h" @@ -36,7 +37,6 @@ #include "extensions/common/extension.h" #include "extensions/test/result_catcher.h" #include "net/test/spawned_test_server/spawned_test_server.h" -#include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" using testing::Return; @@ -185,7 +185,8 @@ IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, Basic) { nullptr /* no WebContents */); navigation_observer.StartWatchingNewWebContents(); ui_test_utils::NavigateToURLWithDisposition( - browser(), https_server.GetURL("client-cert"), NEW_FOREGROUND_TAB, + browser(), https_server.GetURL("client-cert"), + WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_NONE); content::WebContents* const https_contents = 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 b6bf8f9d974..0e02af7f010 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc @@ -8,10 +8,12 @@ #include "base/files/file_path.h" #include "base/memory/ptr_util.h" #include "build/build_config.h" +#include "chrome/browser/data_use_measurement/data_use_web_contents_observer.h" #include "chrome/browser/extensions/api/chrome_device_permissions_prompt.h" #include "chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h" #include "chrome/browser/extensions/api/declarative_content/default_content_predicate_evaluators.h" #include "chrome/browser/extensions/api/management/chrome_management_api_delegate.h" +#include "chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h" #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/api/web_request/chrome_extension_web_request_event_router_delegate.h" @@ -80,6 +82,8 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers( web_contents, std::unique_ptr<pdf::PDFWebContentsHelperClient>( new ChromePDFWebContentsHelperClient())); + data_use_measurement::DataUseWebContentsObserver::CreateForWebContents( + web_contents); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents); } @@ -98,13 +102,13 @@ ChromeExtensionsAPIClient::CreateExtensionOptionsGuestDelegate( std::unique_ptr<guest_view::GuestViewManagerDelegate> ChromeExtensionsAPIClient::CreateGuestViewManagerDelegate( content::BrowserContext* context) const { - return base::WrapUnique(new ChromeGuestViewManagerDelegate(context)); + return base::MakeUnique<ChromeGuestViewManagerDelegate>(context); } std::unique_ptr<MimeHandlerViewGuestDelegate> ChromeExtensionsAPIClient::CreateMimeHandlerViewGuestDelegate( MimeHandlerViewGuest* guest) const { - return base::WrapUnique(new ChromeMimeHandlerViewGuestDelegate()); + return base::MakeUnique<ChromeMimeHandlerViewGuestDelegate>(); } WebViewGuestDelegate* ChromeExtensionsAPIClient::CreateWebViewGuestDelegate( @@ -120,7 +124,7 @@ WebViewPermissionHelperDelegate* ChromeExtensionsAPIClient:: std::unique_ptr<WebRequestEventRouterDelegate> ChromeExtensionsAPIClient::CreateWebRequestEventRouterDelegate() const { - return base::WrapUnique(new ChromeExtensionWebRequestEventRouterDelegate()); + return base::MakeUnique<ChromeExtensionWebRequestEventRouterDelegate>(); } scoped_refptr<ContentRulesRegistry> @@ -138,13 +142,13 @@ ChromeExtensionsAPIClient::CreateContentRulesRegistry( std::unique_ptr<DevicePermissionsPrompt> ChromeExtensionsAPIClient::CreateDevicePermissionsPrompt( content::WebContents* web_contents) const { - return base::WrapUnique(new ChromeDevicePermissionsPrompt(web_contents)); + return base::MakeUnique<ChromeDevicePermissionsPrompt>(web_contents); } std::unique_ptr<VirtualKeyboardDelegate> ChromeExtensionsAPIClient::CreateVirtualKeyboardDelegate() const { #if defined(OS_CHROMEOS) - return base::WrapUnique(new ChromeVirtualKeyboardDelegate()); + return base::MakeUnique<ChromeVirtualKeyboardDelegate>(); #else return nullptr; #endif @@ -155,4 +159,10 @@ ManagementAPIDelegate* ChromeExtensionsAPIClient::CreateManagementAPIDelegate() return new ChromeManagementAPIDelegate; } +MetricsPrivateDelegate* ChromeExtensionsAPIClient::GetMetricsPrivateDelegate() { + if (!metrics_private_delegate_) + metrics_private_delegate_.reset(new ChromeMetricsPrivateDelegate()); + return metrics_private_delegate_.get(); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h index 101598f5fca..2d59b54ef2b 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h @@ -11,6 +11,8 @@ namespace extensions { +class ChromeMetricsPrivateDelegate; + // Extra support for extensions APIs in Chrome. class ChromeExtensionsAPIClient : public ExtensionsAPIClient { public: @@ -50,8 +52,11 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient { std::unique_ptr<VirtualKeyboardDelegate> CreateVirtualKeyboardDelegate() const override; ManagementAPIDelegate* CreateManagementAPIDelegate() const override; + MetricsPrivateDelegate* GetMetricsPrivateDelegate() override; private: + std::unique_ptr<ChromeMetricsPrivateDelegate> metrics_private_delegate_; + DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClient); }; diff --git a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc index fec43b8cfd0..7bcc6848f6f 100644 --- a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc +++ b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc @@ -21,19 +21,17 @@ namespace extensions { namespace command_line_private = api::command_line_private; -bool CommandLinePrivateHasSwitchFunction::RunSync() { +ExtensionFunction::ResponseAction CommandLinePrivateHasSwitchFunction::Run() { std::unique_ptr<command_line_private::HasSwitch::Params> params( command_line_private::HasSwitch::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - if (params->name.empty()) { - error_ = kEmptySwitchName; - return false; - } + if (params->name.empty()) + return RespondNow(Error(kEmptySwitchName)); - results_ = command_line_private::HasSwitch::Results::Create( - base::CommandLine::ForCurrentProcess()->HasSwitch(params->name)); - return true; + return RespondNow( + ArgumentList(command_line_private::HasSwitch::Results::Create( + base::CommandLine::ForCurrentProcess()->HasSwitch(params->name)))); } } // namespace extensions 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 423963e0662..4ab0dd1457e 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,14 +9,14 @@ namespace extensions { -class CommandLinePrivateHasSwitchFunction : public SyncExtensionFunction { +class CommandLinePrivateHasSwitchFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("commandLinePrivate.hasSwitch", COMMANDLINEPRIVATE_HASSWITCH) protected: ~CommandLinePrivateHasSwitchFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.cc b/chromium/chrome/browser/extensions/api/commands/command_service.cc index 950687493c5..960bf41cd64 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service.cc @@ -111,7 +111,7 @@ void MergeSuggestedKeyPrefs( ¤t_prefs)) { std::unique_ptr<base::DictionaryValue> new_prefs(current_prefs->DeepCopy()); new_prefs->MergeDictionary(suggested_key_prefs.get()); - suggested_key_prefs.reset(new_prefs.release()); + suggested_key_prefs = std::move(new_prefs); } extension_prefs->UpdateExtensionPref(extension_id, 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 9f1f6c17537..0f69acbf453 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc @@ -45,18 +45,18 @@ IN_PROC_BROWSER_TEST_F(CommandServiceTest, RemoveShortcutSurvivesUpdate) { EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); base::FilePath pem_path = test_data_dir_. AppendASCII("keybinding").AppendASCII("keybinding.pem"); - base::FilePath path_v1 = PackExtensionWithOptions( - test_data_dir_.AppendASCII("keybinding").AppendASCII("update") - .AppendASCII("v1"), - scoped_temp_dir.path().AppendASCII("v1.crx"), - pem_path, - base::FilePath()); - base::FilePath path_v2 = PackExtensionWithOptions( - test_data_dir_.AppendASCII("keybinding").AppendASCII("update") - .AppendASCII("v2"), - scoped_temp_dir.path().AppendASCII("v2.crx"), - pem_path, - base::FilePath()); + base::FilePath path_v1 = + PackExtensionWithOptions(test_data_dir_.AppendASCII("keybinding") + .AppendASCII("update") + .AppendASCII("v1"), + scoped_temp_dir.GetPath().AppendASCII("v1.crx"), + pem_path, base::FilePath()); + base::FilePath path_v2 = + PackExtensionWithOptions(test_data_dir_.AppendASCII("keybinding") + .AppendASCII("update") + .AppendASCII("v2"), + scoped_temp_dir.GetPath().AppendASCII("v2.crx"), + pem_path, base::FilePath()); ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> extension_service(); diff --git a/chromium/chrome/browser/extensions/api/commands/commands.cc b/chromium/chrome/browser/extensions/api/commands/commands.cc index 64c03e8e295..608d5db2dcb 100644 --- a/chromium/chrome/browser/extensions/api/commands/commands.cc +++ b/chromium/chrome/browser/extensions/api/commands/commands.cc @@ -12,9 +12,10 @@ namespace { -base::DictionaryValue* CreateCommandValue( - const extensions::Command& command, bool active) { - base::DictionaryValue* result = new base::DictionaryValue(); +std::unique_ptr<base::DictionaryValue> CreateCommandValue( + const extensions::Command& command, + bool active) { + std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); result->SetString("name", command.command_name()); result->SetString("description", command.description()); result->SetString("shortcut", @@ -25,11 +26,11 @@ base::DictionaryValue* CreateCommandValue( } // namespace -bool GetAllCommandsFunction::RunSync() { +ExtensionFunction::ResponseAction GetAllCommandsFunction::Run() { std::unique_ptr<base::ListValue> command_list(new base::ListValue()); extensions::CommandService* command_service = - extensions::CommandService::Get(GetProfile()); + extensions::CommandService::Get(browser_context()); extensions::Command browser_action; bool active = false; @@ -64,6 +65,5 @@ bool GetAllCommandsFunction::RunSync() { command_list->Append(CreateCommandValue(iter->second, active)); } - SetResult(std::move(command_list)); - return true; + return RespondNow(OneArgument(std::move(command_list))); } diff --git a/chromium/chrome/browser/extensions/api/commands/commands.h b/chromium/chrome/browser/extensions/api/commands/commands.h index 9aa38eae130..16b940fb965 100644 --- a/chromium/chrome/browser/extensions/api/commands/commands.h +++ b/chromium/chrome/browser/extensions/api/commands/commands.h @@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_COMMANDS_COMMANDS_H_ #define CHROME_BROWSER_EXTENSIONS_API_COMMANDS_COMMANDS_H_ -#include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" -class GetAllCommandsFunction : public ChromeSyncExtensionFunction { +class GetAllCommandsFunction : public UIThreadExtensionFunction { ~GetAllCommandsFunction() override {} - bool RunSync() 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 75351e80767..c5e4834a2f2 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 @@ -67,7 +67,8 @@ namespace extensions { namespace helpers = content_settings_helpers; namespace keys = content_settings_api_constants; -bool ContentSettingsContentSettingClearFunction::RunSync() { +ExtensionFunction::ResponseAction +ContentSettingsContentSettingClearFunction::Run() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -85,23 +86,21 @@ bool ContentSettingsContentSettingClearFunction::RunSync() { if (incognito) { // We don't check incognito permissions here, as an extension should be // always allowed to clear its own settings. - } else { + } else if (browser_context()->IsOffTheRecord()) { // Incognito profiles can't access regular mode ever, they only exist in // split mode. - if (GetProfile()->IsOffTheRecord()) { - error_ = keys::kIncognitoContextError; - return false; - } + return RespondNow(Error(keys::kIncognitoContextError)); } scoped_refptr<ContentSettingsStore> store = - ContentSettingsService::Get(GetProfile())->content_settings_store(); + ContentSettingsService::Get(browser_context())->content_settings_store(); store->ClearContentSettingsForExtension(extension_id(), scope); - return true; + return RespondNow(NoArguments()); } -bool ContentSettingsContentSettingGetFunction::RunSync() { +ExtensionFunction::ResponseAction +ContentSettingsContentSettingGetFunction::Run() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -110,18 +109,16 @@ bool ContentSettingsContentSettingGetFunction::RunSync() { GURL primary_url(params->details.primary_url); if (!primary_url.is_valid()) { - error_ = ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError, - params->details.primary_url); - return false; + return RespondNow( + Error(keys::kInvalidUrlError, params->details.primary_url)); } GURL secondary_url(primary_url); if (params->details.secondary_url.get()) { secondary_url = GURL(*params->details.secondary_url); if (!secondary_url.is_valid()) { - error_ = ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError, - *params->details.secondary_url); - return false; + return RespondNow( + Error(keys::kInvalidUrlError, *params->details.secondary_url)); } } @@ -132,27 +129,26 @@ bool ContentSettingsContentSettingGetFunction::RunSync() { bool incognito = false; if (params->details.incognito.get()) incognito = *params->details.incognito; - if (incognito && !include_incognito()) { - error_ = pref_keys::kIncognitoErrorMessage; - return false; - } + if (incognito && !include_incognito()) + return RespondNow(Error(pref_keys::kIncognitoErrorMessage)); HostContentSettingsMap* map; content_settings::CookieSettings* cookie_settings; + Profile* profile = Profile::FromBrowserContext(browser_context()); if (incognito) { - if (!GetProfile()->HasOffTheRecordProfile()) { + if (!profile->HasOffTheRecordProfile()) { // TODO(bauerb): Allow reading incognito content settings // outside of an incognito session. - error_ = keys::kIncognitoSessionOnlyError; - return false; + return RespondNow(Error(keys::kIncognitoSessionOnlyError)); } map = HostContentSettingsMapFactory::GetForProfile( - GetProfile()->GetOffTheRecordProfile()); - cookie_settings = CookieSettingsFactory::GetForProfile( - GetProfile()->GetOffTheRecordProfile()).get(); + profile->GetOffTheRecordProfile()); + cookie_settings = + CookieSettingsFactory::GetForProfile(profile->GetOffTheRecordProfile()) + .get(); } else { - map = HostContentSettingsMapFactory::GetForProfile(GetProfile()); - cookie_settings = CookieSettingsFactory::GetForProfile(GetProfile()).get(); + map = HostContentSettingsMapFactory::GetForProfile(profile); + cookie_settings = CookieSettingsFactory::GetForProfile(profile).get(); } ContentSetting setting; @@ -172,12 +168,11 @@ bool ContentSettingsContentSettingGetFunction::RunSync() { DCHECK(!setting_string.empty()); result->SetString(keys::kContentSettingKey, setting_string); - SetResult(std::move(result)); - - return true; + return RespondNow(OneArgument(std::move(result))); } -bool ContentSettingsContentSettingSetFunction::RunSync() { +ExtensionFunction::ResponseAction +ContentSettingsContentSettingSetFunction::Run() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -188,10 +183,8 @@ bool ContentSettingsContentSettingSetFunction::RunSync() { ContentSettingsPattern primary_pattern = helpers::ParseExtensionPattern(params->details.primary_pattern, &primary_error); - if (!primary_pattern.IsValid()) { - error_ = primary_error; - return false; - } + if (!primary_pattern.IsValid()) + return RespondNow(Error(primary_error)); ContentSettingsPattern secondary_pattern = ContentSettingsPattern::Wildcard(); if (params->details.secondary_pattern.get()) { @@ -199,10 +192,8 @@ bool ContentSettingsContentSettingSetFunction::RunSync() { secondary_pattern = helpers::ParseExtensionPattern(*params->details.secondary_pattern, &secondary_error); - if (!secondary_pattern.IsValid()) { - error_ = secondary_error; - return false; - } + if (!secondary_pattern.IsValid()) + return RespondNow(Error(secondary_error)); } std::string resource_identifier; @@ -243,11 +234,9 @@ bool ContentSettingsContentSettingSetFunction::RunSync() { NOTREACHED() << "No human-readable type name defined for this type."; } - error_ = base::StringPrintf( - kUnsupportedDefaultSettingError, - setting_str.c_str(), - readable_type_name.c_str()); - return false; + return RespondNow(Error(base::StringPrintf(kUnsupportedDefaultSettingError, + setting_str.c_str(), + readable_type_name.c_str()))); } ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; @@ -260,31 +249,27 @@ bool ContentSettingsContentSettingSetFunction::RunSync() { if (incognito) { // Regular profiles can't access incognito unless include_incognito is true. - if (!GetProfile()->IsOffTheRecord() && !include_incognito()) { - error_ = pref_keys::kIncognitoErrorMessage; - return false; - } + if (!browser_context()->IsOffTheRecord() && !include_incognito()) + return RespondNow(Error(pref_keys::kIncognitoErrorMessage)); } else { // Incognito profiles can't access regular mode ever, they only exist in // split mode. - if (GetProfile()->IsOffTheRecord()) { - error_ = keys::kIncognitoContextError; - return false; - } + if (browser_context()->IsOffTheRecord()) + return RespondNow(Error(keys::kIncognitoContextError)); } if (scope == kExtensionPrefsScopeIncognitoSessionOnly && - !GetProfile()->HasOffTheRecordProfile()) { - error_ = pref_keys::kIncognitoSessionOnlyErrorMessage; - return false; + !Profile::FromBrowserContext(browser_context()) + ->HasOffTheRecordProfile()) { + return RespondNow(Error(pref_keys::kIncognitoSessionOnlyErrorMessage)); } scoped_refptr<ContentSettingsStore> store = - ContentSettingsService::Get(GetProfile())->content_settings_store(); + ContentSettingsService::Get(browser_context())->content_settings_store(); store->SetExtensionContentSetting(extension_id(), primary_pattern, secondary_pattern, content_type, resource_identifier, setting, scope); - return true; + return RespondNow(NoArguments()); } bool ContentSettingsContentSettingGetResourceIdentifiersFunction::RunAsync() { 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 a4706d13cc9..95563d01ddc 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 @@ -17,7 +17,7 @@ struct WebPluginInfo; namespace extensions { class ContentSettingsContentSettingClearFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.clear", CONTENTSETTINGS_CLEAR) @@ -25,11 +25,11 @@ class ContentSettingsContentSettingClearFunction ~ContentSettingsContentSettingClearFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class ContentSettingsContentSettingGetFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.get", CONTENTSETTINGS_GET) @@ -37,11 +37,11 @@ class ContentSettingsContentSettingGetFunction ~ContentSettingsContentSettingGetFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class ContentSettingsContentSettingSetFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.set", CONTENTSETTINGS_SET) @@ -49,7 +49,7 @@ class ContentSettingsContentSettingSetFunction ~ContentSettingsContentSettingSetFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class ContentSettingsContentSettingGetResourceIdentifiersFunction diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc index 824000695ec..0ec344537a9 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc @@ -109,16 +109,6 @@ class ExtensionContentSettingsApiTest : public ExtensionApiTest { EXPECT_EQ(CONTENT_SETTING_ASK, map->GetContentSetting(example_url, example_url, - CONTENT_SETTINGS_TYPE_FULLSCREEN, - std::string())); - EXPECT_EQ(CONTENT_SETTING_ASK, - map->GetContentSetting(example_url, - example_url, - CONTENT_SETTINGS_TYPE_MOUSELOCK, - std::string())); - EXPECT_EQ(CONTENT_SETTING_ASK, - map->GetContentSetting(example_url, - example_url, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, @@ -164,12 +154,6 @@ class ExtensionContentSettingsApiTest : public ExtensionApiTest { CONTENT_SETTING_BLOCK, map->GetContentSetting( url, url, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); - EXPECT_EQ(CONTENT_SETTING_ALLOW, - map->GetContentSetting( - url, url, CONTENT_SETTINGS_TYPE_FULLSCREEN, std::string())); - EXPECT_EQ(CONTENT_SETTING_BLOCK, - map->GetContentSetting( - url, url, CONTENT_SETTINGS_TYPE_MOUSELOCK, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, map->GetContentSetting( url, url, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, std::string())); @@ -220,12 +204,6 @@ class ExtensionContentSettingsApiTest : public ExtensionApiTest { url, url, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, map->GetContentSetting( - url, url, CONTENT_SETTINGS_TYPE_FULLSCREEN, std::string())); - EXPECT_EQ(CONTENT_SETTING_ASK, - map->GetContentSetting( - url, url, CONTENT_SETTINGS_TYPE_MOUSELOCK, std::string())); - EXPECT_EQ(CONTENT_SETTING_ASK, - map->GetContentSetting( url, url, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, map->GetContentSetting( diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc index 46ca488ab9b..ec745236e3a 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc @@ -11,6 +11,7 @@ #include "base/debug/alias.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/values.h" @@ -52,7 +53,7 @@ ContentSettingsStore::ContentSettingsStore() { } ContentSettingsStore::~ContentSettingsStore() { - STLDeleteValues(&entries_); + base::STLDeleteValues(&entries_); } std::unique_ptr<RuleIterator> ContentSettingsStore::GetRuleIterator( @@ -62,34 +63,38 @@ std::unique_ptr<RuleIterator> ContentSettingsStore::GetRuleIterator( std::vector<std::unique_ptr<RuleIterator>> iterators; // Iterate the extensions based on install time (last installed extensions // first). - ExtensionEntryMap::const_reverse_iterator entry; + ExtensionEntryMap::const_reverse_iterator entry_it; // The individual |RuleIterators| shouldn't lock; pass |lock_| to the // |ConcatenationIterator| in a locked state. std::unique_ptr<base::AutoLock> auto_lock(new base::AutoLock(lock_)); - for (entry = entries_.rbegin(); entry != entries_.rend(); ++entry) { - if (!entry->second->enabled) + for (entry_it = entries_.rbegin(); entry_it != entries_.rend(); ++entry_it) { + auto* entry = entry_it->second; + if (!entry->enabled) continue; + std::unique_ptr<RuleIterator> rule_it; if (incognito) { - iterators.push_back( - entry->second->incognito_session_only_settings.GetRuleIterator( - type, - identifier, - NULL)); - iterators.push_back( - entry->second->incognito_persistent_settings.GetRuleIterator( - type, - identifier, - NULL)); + rule_it = entry->incognito_session_only_settings.GetRuleIterator( + type, identifier, nullptr); + if (rule_it) + iterators.push_back(std::move(rule_it)); + rule_it = entry->incognito_persistent_settings.GetRuleIterator( + type, identifier, nullptr); + if (rule_it) + iterators.push_back(std::move(rule_it)); } else { - iterators.push_back( - entry->second->settings.GetRuleIterator(type, identifier, NULL)); + rule_it = entry->settings.GetRuleIterator(type, identifier, nullptr); + if (rule_it) + iterators.push_back(std::move(rule_it)); } } - return std::unique_ptr<RuleIterator>( - new ConcatenationIterator(std::move(iterators), auto_lock.release())); + if (iterators.empty()) + return nullptr; + + return base::MakeUnique<ConcatenationIterator>(std::move(iterators), + auto_lock.release()); } void ContentSettingsStore::SetExtensionContentSetting( @@ -251,13 +256,17 @@ base::ListValue* ContentSettingsStore::GetSettingsForExtension( base::AutoLock lock(lock_); const OriginIdentifierValueMap* map = GetValueMap(extension_id, scope); if (!map) - return NULL; + return nullptr; + base::ListValue* settings = new base::ListValue(); - OriginIdentifierValueMap::EntryMap::const_iterator it; - for (it = map->begin(); it != map->end(); ++it) { - std::unique_ptr<RuleIterator> rule_iterator(map->GetRuleIterator( - it->first.content_type, it->first.resource_identifier, - NULL)); // We already hold the lock. + for (const auto& it : *map) { + const auto& key = it.first; + std::unique_ptr<RuleIterator> rule_iterator( + map->GetRuleIterator(key.content_type, key.resource_identifier, + nullptr)); // We already hold the lock. + if (!rule_iterator) + continue; + while (rule_iterator->HasNext()) { const Rule& rule = rule_iterator->Next(); std::unique_ptr<base::DictionaryValue> setting_dict( @@ -268,9 +277,9 @@ base::ListValue* ContentSettingsStore::GetSettingsForExtension( rule.secondary_pattern.ToString()); setting_dict->SetString( keys::kContentSettingsTypeKey, - helpers::ContentSettingsTypeToString(it->first.content_type)); + helpers::ContentSettingsTypeToString(key.content_type)); setting_dict->SetString(keys::kResourceIdentifierKey, - it->first.resource_identifier); + key.resource_identifier); ContentSetting content_setting = ValueToContentSetting(rule.value.get()); DCHECK_NE(CONTENT_SETTING_DEFAULT, content_setting); diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc index f138a764be5..9986d4e2436 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc @@ -60,21 +60,23 @@ ContentSetting GetContentSettingFromStore( store->GetRuleIterator(content_type, resource_identifier, incognito)); std::unique_ptr<base::Value> setting( content_settings::TestUtils::GetContentSettingValueAndPatterns( - rule_iterator.get(), primary_url, secondary_url, NULL, NULL)); + rule_iterator.get(), primary_url, secondary_url, nullptr, nullptr)); return content_settings::ValueToContentSetting(setting.get()); } -void GetSettingsForOneTypeFromStore( +std::vector<content_settings::Rule> GetSettingsForOneTypeFromStore( const ContentSettingsStore* store, ContentSettingsType content_type, const std::string& resource_identifier, - bool incognito, - std::vector<content_settings::Rule>* rules) { - rules->clear(); + bool incognito) { + std::vector<content_settings::Rule> rules; std::unique_ptr<content_settings::RuleIterator> rule_iterator( store->GetRuleIterator(content_type, resource_identifier, incognito)); - while (rule_iterator->HasNext()) - rules->push_back(rule_iterator->Next()); + if (rule_iterator) { + while (rule_iterator->HasNext()) + rules.push_back(rule_iterator->Next()); + } + return rules; } } // namespace @@ -194,10 +196,9 @@ TEST_F(ContentSettingsStoreTest, RegisterUnregister) { } TEST_F(ContentSettingsStoreTest, GetAllSettings) { - bool incognito = false; - std::vector<content_settings::Rule> rules; - GetSettingsForOneTypeFromStore( - store(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), incognito, &rules); + const bool incognito = false; + std::vector<content_settings::Rule> rules = GetSettingsForOneTypeFromStore( + store(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), incognito); ASSERT_EQ(0u, rules.size()); // Register first extension. @@ -213,8 +214,8 @@ TEST_F(ContentSettingsStoreTest, GetAllSettings) { CONTENT_SETTING_ALLOW, kExtensionPrefsScopeRegular); - GetSettingsForOneTypeFromStore( - store(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), incognito, &rules); + rules = GetSettingsForOneTypeFromStore(store(), CONTENT_SETTINGS_TYPE_COOKIES, + std::string(), incognito); ASSERT_EQ(1u, rules.size()); CheckRule(rules[0], pattern, pattern, CONTENT_SETTING_ALLOW); @@ -231,8 +232,8 @@ TEST_F(ContentSettingsStoreTest, GetAllSettings) { CONTENT_SETTING_BLOCK, kExtensionPrefsScopeRegular); - GetSettingsForOneTypeFromStore( - store(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), incognito, &rules); + rules = GetSettingsForOneTypeFromStore(store(), CONTENT_SETTINGS_TYPE_COOKIES, + std::string(), incognito); ASSERT_EQ(2u, rules.size()); // Rules appear in the reverse installation order of the extensions. CheckRule(rules[0], pattern_2, pattern_2, CONTENT_SETTING_BLOCK); @@ -241,16 +242,16 @@ TEST_F(ContentSettingsStoreTest, GetAllSettings) { // Disable first extension. store()->SetExtensionState(ext_id, false); - GetSettingsForOneTypeFromStore( - store(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), incognito, &rules); + rules = GetSettingsForOneTypeFromStore(store(), CONTENT_SETTINGS_TYPE_COOKIES, + std::string(), incognito); ASSERT_EQ(1u, rules.size()); CheckRule(rules[0], pattern_2, pattern_2, CONTENT_SETTING_BLOCK); // Uninstall second extension. store()->UnregisterExtension(ext_id_2); - GetSettingsForOneTypeFromStore( - store(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), incognito, &rules); + rules = GetSettingsForOneTypeFromStore(store(), CONTENT_SETTINGS_TYPE_COOKIES, + std::string(), incognito); ASSERT_EQ(0u, rules.size()); } diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc index 90b8849fca2..efe97dd7572 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc @@ -32,8 +32,8 @@ namespace Create = api::context_menus::Create; namespace Remove = api::context_menus::Remove; namespace Update = api::context_menus::Update; -bool ContextMenusCreateFunction::RunSync() { - MenuItem::Id id(GetProfile()->IsOffTheRecord(), +ExtensionFunction::ResponseAction ContextMenusCreateFunction::Run() { + MenuItem::Id id(browser_context()->IsOffTheRecord(), MenuItem::ExtensionKey(extension_id())); std::unique_ptr<Create::Params> params(Create::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -41,10 +41,8 @@ bool ContextMenusCreateFunction::RunSync() { if (params->create_properties.id.get()) { id.string_uid = *params->create_properties.id; } else { - if (BackgroundInfo::HasLazyBackgroundPage(extension())) { - error_ = kIdRequiredError; - return false; - } + if (BackgroundInfo::HasLazyBackgroundPage(extension())) + return RespondNow(Error(kIdRequiredError)); // The Generated Id is added by context_menus_custom_bindings.js. base::DictionaryValue* properties = NULL; @@ -53,12 +51,16 @@ bool ContextMenusCreateFunction::RunSync() { properties->GetInteger(helpers::kGeneratedIdKey, &id.uid)); } - return helpers::CreateMenuItem( - params->create_properties, GetProfile(), extension(), id, &error_); + std::string error; + if (!helpers::CreateMenuItem(params->create_properties, browser_context(), + extension(), id, &error)) { + return RespondNow(Error(error)); + } + return RespondNow(NoArguments()); } -bool ContextMenusUpdateFunction::RunSync() { - MenuItem::Id item_id(GetProfile()->IsOffTheRecord(), +ExtensionFunction::ResponseAction ContextMenusUpdateFunction::Run() { + MenuItem::Id item_id(browser_context()->IsOffTheRecord(), MenuItem::ExtensionKey(extension_id())); std::unique_ptr<Update::Params> params(Update::Params::Create(*args_)); @@ -70,17 +72,21 @@ bool ContextMenusUpdateFunction::RunSync() { else NOTREACHED(); - return helpers::UpdateMenuItem( - params->update_properties, GetProfile(), extension(), item_id, &error_); + std::string error; + if (!helpers::UpdateMenuItem(params->update_properties, browser_context(), + extension(), item_id, &error)) { + return RespondNow(Error(error)); + } + return RespondNow(NoArguments()); } -bool ContextMenusRemoveFunction::RunSync() { +ExtensionFunction::ResponseAction ContextMenusRemoveFunction::Run() { std::unique_ptr<Remove::Params> params(Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - MenuManager* manager = MenuManager::Get(GetProfile()); + MenuManager* manager = MenuManager::Get(browser_context()); - MenuItem::Id id(GetProfile()->IsOffTheRecord(), + MenuItem::Id id(browser_context()->IsOffTheRecord(), MenuItem::ExtensionKey(extension_id())); if (params->menu_item_id.as_string) id.string_uid = *params->menu_item_id.as_string; @@ -92,23 +98,22 @@ bool ContextMenusRemoveFunction::RunSync() { MenuItem* item = manager->GetItemById(id); // Ensure one extension can't remove another's menu items. if (!item || item->extension_id() != extension_id()) { - error_ = ErrorUtils::FormatErrorMessage( - helpers::kCannotFindItemError, helpers::GetIDString(id)); - return false; + return RespondNow( + Error(helpers::kCannotFindItemError, helpers::GetIDString(id))); } if (!manager->RemoveContextMenuItem(id)) - return false; + return RespondNow(Error("Cannot remove menu item.")); manager->WriteToStorage(extension(), id.extension_key); - return true; + return RespondNow(NoArguments()); } -bool ContextMenusRemoveAllFunction::RunSync() { - MenuManager* manager = MenuManager::Get(GetProfile()); +ExtensionFunction::ResponseAction ContextMenusRemoveAllFunction::Run() { + MenuManager* manager = MenuManager::Get(browser_context()); manager->RemoveAllContextItems(MenuItem::ExtensionKey(extension()->id())); manager->WriteToStorage(extension(), MenuItem::ExtensionKey(extension()->id())); - return true; + return RespondNow(NoArguments()); } } // namespace extensions 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 8c05e683a3c..78e00b7415c 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 @@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_CONTEXT_MENUS_CONTEXT_MENUS_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_CONTEXT_MENUS_CONTEXT_MENUS_API_H_ -#include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" namespace extensions { -class ContextMenusCreateFunction : public ChromeSyncExtensionFunction { +class ContextMenusCreateFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.create", CONTEXTMENUS_CREATE) @@ -17,10 +17,10 @@ class ContextMenusCreateFunction : public ChromeSyncExtensionFunction { ~ContextMenusCreateFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class ContextMenusUpdateFunction : public ChromeSyncExtensionFunction { +class ContextMenusUpdateFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.update", CONTEXTMENUS_UPDATE) @@ -28,10 +28,10 @@ class ContextMenusUpdateFunction : public ChromeSyncExtensionFunction { ~ContextMenusUpdateFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class ContextMenusRemoveFunction : public ChromeSyncExtensionFunction { +class ContextMenusRemoveFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.remove", CONTEXTMENUS_REMOVE) @@ -39,10 +39,10 @@ class ContextMenusRemoveFunction : public ChromeSyncExtensionFunction { ~ContextMenusRemoveFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class ContextMenusRemoveAllFunction : public ChromeSyncExtensionFunction { +class ContextMenusRemoveAllFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.removeAll", CONTEXTMENUS_REMOVEALL) @@ -50,7 +50,7 @@ class ContextMenusRemoveAllFunction : public ChromeSyncExtensionFunction { ~ContextMenusRemoveAllFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h index 29f2f17d875..4fc44ebaa25 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h @@ -8,8 +8,8 @@ #define CHROME_BROWSER_EXTENSIONS_API_CONTEXT_MENUS_CONTEXT_MENUS_API_HELPERS_H_ #include "chrome/browser/extensions/menu_manager.h" -#include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/context_menus.h" +#include "content/public/browser/browser_context.h" #include "extensions/common/error_utils.h" #include "extensions/common/manifest_handlers/background_info.h" @@ -62,14 +62,14 @@ MenuItem::Type GetType(extensions::api::context_menus::ItemType type, MenuItem::Type default_type); // Creates and adds a menu item from |create_properties|. -template<typename PropertyWithEnumT> +template <typename PropertyWithEnumT> bool CreateMenuItem(const PropertyWithEnumT& create_properties, - Profile* profile, + content::BrowserContext* browser_context, const Extension* extension, const MenuItem::Id& item_id, std::string* error) { bool is_webview = item_id.extension_key.webview_instance_id != 0; - MenuManager* menu_manager = MenuManager::Get(profile); + MenuManager* menu_manager = MenuManager::Get(browser_context); if (menu_manager->GetItemById(item_id)) { *error = ErrorUtils::FormatErrorMessage(kDuplicateIDError, @@ -141,8 +141,9 @@ bool CreateMenuItem(const PropertyWithEnumT& create_properties, // Parent id. bool success = true; - std::unique_ptr<MenuItem::Id> parent_id(GetParentId( - create_properties, profile->IsOffTheRecord(), item_id.extension_key)); + std::unique_ptr<MenuItem::Id> parent_id( + GetParentId(create_properties, browser_context->IsOffTheRecord(), + item_id.extension_key)); if (parent_id.get()) { MenuItem* parent = GetParent(*parent_id, menu_manager, error); if (!parent) @@ -160,15 +161,15 @@ bool CreateMenuItem(const PropertyWithEnumT& create_properties, } // Updates a menu item from |update_properties|. -template<typename PropertyWithEnumT> +template <typename PropertyWithEnumT> bool UpdateMenuItem(const PropertyWithEnumT& update_properties, - Profile* profile, + content::BrowserContext* browser_context, const Extension* extension, const MenuItem::Id& item_id, std::string* error) { bool radio_item_updated = false; bool is_webview = item_id.extension_key.webview_instance_id != 0; - MenuManager* menu_manager = MenuManager::Get(profile); + MenuManager* menu_manager = MenuManager::Get(browser_context); MenuItem* item = menu_manager->GetItemById(item_id); if (!item || item->extension_id() != extension->id()){ @@ -237,8 +238,9 @@ bool UpdateMenuItem(const PropertyWithEnumT& update_properties, // Parent id. MenuItem* parent = NULL; - std::unique_ptr<MenuItem::Id> parent_id(GetParentId( - update_properties, profile->IsOffTheRecord(), item_id.extension_key)); + std::unique_ptr<MenuItem::Id> parent_id( + GetParentId(update_properties, browser_context->IsOffTheRecord(), + item_id.extension_key)); if (parent_id.get()) { MenuItem* parent = GetParent(*parent_id, menu_manager, error); if (!parent || !menu_manager->ChangeParent(item->id(), &parent->id())) diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc index 889f10b0dd3..549dd0e6551 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -13,12 +13,12 @@ #include "base/bind.h" #include "base/json/json_writer.h" #include "base/lazy_instance.h" -#include "base/memory/linked_ptr.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/api/cookies/cookies_api_constants.h" #include "chrome/browser/extensions/api/cookies/cookies_helpers.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -143,27 +143,30 @@ void CookiesEventRouter::CookieChanged( // Map the internal cause to an external string. std::string cause; switch (details->cause) { - case net::CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT: + // Report an inserted cookie as an "explicit" change cause. All other causes + // only make sense for deletions. + case net::CookieStore::ChangeCause::INSERTED: + case net::CookieStore::ChangeCause::EXPLICIT: cause = keys::kExplicitChangeCause; break; - case net::CookieMonsterDelegate::CHANGE_COOKIE_OVERWRITE: + case net::CookieStore::ChangeCause::OVERWRITE: cause = keys::kOverwriteChangeCause; break; - case net::CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED: + case net::CookieStore::ChangeCause::EXPIRED: cause = keys::kExpiredChangeCause; break; - case net::CookieMonsterDelegate::CHANGE_COOKIE_EVICTED: + case net::CookieStore::ChangeCause::EVICTED: cause = keys::kEvictedChangeCause; break; - case net::CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED_OVERWRITE: + case net::CookieStore::ChangeCause::EXPIRED_OVERWRITE: cause = keys::kExpiredOverwriteChangeCause; break; - default: + case net::CookieStore::ChangeCause::UNKNOWN_DELETION: NOTREACHED(); } dict->SetString(keys::kCauseKey, cause); @@ -406,7 +409,7 @@ void CookiesSetFunction::SetCookieOnIOThread() { base::Time(), expiration_time, base::Time(), - parsed_args_->details.secure.get() ? *parsed_args_->details.secure.get() + parsed_args_->details.secure.get() ? *parsed_args_->details.secure : false, parsed_args_->details.http_only.get() ? *parsed_args_->details.http_only : false, @@ -526,14 +529,14 @@ void CookiesRemoveFunction::RespondOnUIThread() { SendResponse(true); } -bool CookiesGetAllCookieStoresFunction::RunSync() { - Profile* original_profile = GetProfile(); +ExtensionFunction::ResponseAction CookiesGetAllCookieStoresFunction::Run() { + Profile* original_profile = Profile::FromBrowserContext(browser_context()); DCHECK(original_profile); std::unique_ptr<base::ListValue> original_tab_ids(new base::ListValue()); Profile* incognito_profile = NULL; std::unique_ptr<base::ListValue> incognito_tab_ids; - if (include_incognito() && GetProfile()->HasOffTheRecordProfile()) { - incognito_profile = GetProfile()->GetOffTheRecordProfile(); + if (include_incognito() && original_profile->HasOffTheRecordProfile()) { + incognito_profile = original_profile->GetOffTheRecordProfile(); if (incognito_profile) incognito_tab_ids.reset(new base::ListValue()); } @@ -561,8 +564,8 @@ bool CookiesGetAllCookieStoresFunction::RunSync() { cookie_stores.push_back(cookies_helpers::CreateCookieStore( incognito_profile, incognito_tab_ids.release())); } - results_ = GetAllCookieStores::Results::Create(cookie_stores); - return true; + return RespondNow( + ArgumentList(GetAllCookieStores::Results::Create(cookie_stores))); } CookiesAPI::CookiesAPI(content::BrowserContext* context) diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h index c7764d54d5d..4dfa71cc76c 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h @@ -155,7 +155,7 @@ class CookiesRemoveFunction : public ChromeAsyncExtensionFunction { }; // Implements the cookies.getAllCookieStores() extension function. -class CookiesGetAllCookieStoresFunction : public ChromeSyncExtensionFunction { +class CookiesGetAllCookieStoresFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.getAllCookieStores", COOKIES_GETALLCOOKIESTORES) @@ -164,7 +164,7 @@ class CookiesGetAllCookieStoresFunction : public ChromeSyncExtensionFunction { ~CookiesGetAllCookieStoresFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class CookiesAPI : public BrowserContextKeyedAPI, public EventRouter::Observer { diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc index 0ca45694881..b5073942cf1 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc @@ -134,7 +134,9 @@ GURL GetURLFromCanonicalCookie(const net::CanonicalCookie& cookie) { const std::string scheme = cookie.IsSecure() ? url::kHttpsScheme : url::kHttpScheme; const std::string host = - domain_key.find('.') != 0 ? domain_key : domain_key.substr(1); + base::StartsWith(domain_key, ".", base::CompareCase::SENSITIVE) + ? domain_key.substr(1) + : domain_key; return GURL(scheme + url::kStandardSchemeSeparator + host + "/"); } diff --git a/chromium/chrome/browser/extensions/api/copresence/OWNERS b/chromium/chrome/browser/extensions/api/copresence/OWNERS deleted file mode 100644 index 5f781a66da0..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -rkc@chromium.org -ckehoe@chromium.org diff --git a/chromium/chrome/browser/extensions/api/copresence/copresence_api.cc b/chromium/chrome/browser/extensions/api/copresence/copresence_api.cc deleted file mode 100644 index a1eb781a444..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence/copresence_api.cc +++ /dev/null @@ -1,307 +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/extensions/api/copresence/copresence_api.h" - -#include <utility> - -#include "base/lazy_instance.h" -#include "chrome/browser/copresence/chrome_whispernet_client.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/services/gcm/gcm_profile_service_factory.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/extensions/api/copresence.h" -#include "chrome/common/extensions/manifest_handlers/copresence_manifest.h" -#include "chrome/common/pref_names.h" -#include "components/copresence/copresence_manager_impl.h" -#include "components/copresence/proto/data.pb.h" -#include "components/copresence/proto/enums.pb.h" -#include "components/copresence/proto/rpcs.pb.h" -#include "components/gcm_driver/gcm_profile_service.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/storage_partition.h" -#include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/common/extension.h" -#include "extensions/common/manifest_constants.h" - -using user_prefs::PrefRegistrySyncable; - -namespace extensions { - -namespace { - -base::LazyInstance<BrowserContextKeyedAPIFactory<CopresenceService>> - g_factory = LAZY_INSTANCE_INITIALIZER; - -const char kInvalidOperationsMessage[] = - "Invalid operation in operations array."; -const char kShuttingDownMessage[] = "Shutting down."; - -const std::string GetPrefName(bool authenticated) { - return authenticated ? prefs::kCopresenceAuthenticatedDeviceId - : prefs::kCopresenceAnonymousDeviceId; -} - -} // namespace - -namespace Execute = api::copresence::Execute; -namespace OnMessagesReceived = api::copresence::OnMessagesReceived; -namespace OnStatusUpdated = api::copresence::OnStatusUpdated; -namespace SetApiKey = api::copresence::SetApiKey; -namespace SetAuthToken = api::copresence::SetAuthToken; - -// Public functions. - -CopresenceService::CopresenceService(content::BrowserContext* context) - : is_shutting_down_(false), browser_context_(context) {} - -CopresenceService::~CopresenceService() {} - -void CopresenceService::Shutdown() { - is_shutting_down_ = true; - manager_.reset(); - whispernet_client_.reset(); -} - -copresence::CopresenceManager* CopresenceService::manager() { - if (!manager_ && !is_shutting_down_) - manager_.reset(new copresence::CopresenceManagerImpl(this)); - return manager_.get(); -} - -std::string CopresenceService::auth_token(const std::string& app_id) - const { - // This won't be const if we use map[] - const auto& key = auth_tokens_by_app_.find(app_id); - return key == auth_tokens_by_app_.end() ? std::string() : key->second; -} - -void CopresenceService::set_api_key(const std::string& app_id, - const std::string& api_key) { - DCHECK(!app_id.empty()); - api_keys_by_app_[app_id] = api_key; -} - -void CopresenceService::set_auth_token(const std::string& app_id, - const std::string& token) { - DCHECK(!app_id.empty()); - auth_tokens_by_app_[app_id] = token; -} - -void CopresenceService::set_manager_for_testing( - std::unique_ptr<copresence::CopresenceManager> manager) { - manager_ = std::move(manager); -} - -void CopresenceService::ResetState() { - DVLOG(2) << "Deleting copresence state"; - GetPrefService()->ClearPref(prefs::kCopresenceAuthenticatedDeviceId); - GetPrefService()->ClearPref(prefs::kCopresenceAnonymousDeviceId); - manager_ = nullptr; -} - -// static -void CopresenceService::RegisterProfilePrefs(PrefRegistrySyncable* registry) { - registry->RegisterStringPref(prefs::kCopresenceAuthenticatedDeviceId, - std::string()); - registry->RegisterStringPref(prefs::kCopresenceAnonymousDeviceId, - std::string()); -} - -// static -BrowserContextKeyedAPIFactory<CopresenceService>* -CopresenceService::GetFactoryInstance() { - return g_factory.Pointer(); -} - - -// Private functions. - -void CopresenceService::HandleMessages( - const std::string& /* app_id */, - const std::string& subscription_id, - const std::vector<copresence::Message>& messages) { - // TODO(ckehoe): Once the server starts sending back the app ids associated - // with subscriptions, use that instead of the apps_by_subs registry. - std::string app_id = apps_by_subscription_id_[subscription_id]; - - if (app_id.empty()) { - LOG(ERROR) << "Skipping message from unrecognized subscription " - << subscription_id; - return; - } - - int message_count = messages.size(); - std::vector<api::copresence::Message> api_messages(message_count); - - for (const copresence::Message& message : messages) { - api::copresence::Message api_message; - api_message.type = message.type().type(); - api_message.payload.assign(message.payload().begin(), - message.payload().end()); - api_messages.push_back(std::move(api_message)); - DVLOG(2) << "Dispatching message of type " << api_message.type << ":\n" - << message.payload(); - } - - // Send the messages to the client app. - std::unique_ptr<Event> event(new Event( - events::COPRESENCE_ON_MESSAGES_RECEIVED, OnMessagesReceived::kEventName, - OnMessagesReceived::Create(subscription_id, api_messages), - browser_context_)); - EventRouter::Get(browser_context_) - ->DispatchEventToExtension(app_id, std::move(event)); - DVLOG(2) << "Passed " << api_messages.size() << " messages to app \"" - << app_id << "\" for subscription \"" << subscription_id << "\""; -} - -void CopresenceService::HandleStatusUpdate( - copresence::CopresenceStatus status) { - DCHECK_EQ(copresence::AUDIO_FAIL, status); - std::unique_ptr<Event> event(new Event( - events::COPRESENCE_ON_STATUS_UPDATED, OnStatusUpdated::kEventName, - OnStatusUpdated::Create(api::copresence::STATUS_AUDIOFAILED), - browser_context_)); - EventRouter::Get(browser_context_)->BroadcastEvent(std::move(event)); - DVLOG(2) << "Sent Audio Failed status update."; -} - -net::URLRequestContextGetter* CopresenceService::GetRequestContext() const { - return content::BrowserContext::GetDefaultStoragePartition(browser_context_)-> - GetURLRequestContext(); -} - -std::string CopresenceService::GetPlatformVersionString() const { - return chrome::GetVersionString(); -} - -std::string -CopresenceService::GetAPIKey(const std::string& app_id) const { - // Check first if the app has set its key via the API. - const auto& key = api_keys_by_app_.find(app_id); - if (key != api_keys_by_app_.end()) - return key->second; - - // If no key was found, look in the manifest. - if (!app_id.empty()) { - const Extension* extension = ExtensionRegistry::Get(browser_context_) - ->GetExtensionById(app_id, ExtensionRegistry::ENABLED); - DCHECK(extension) << "Invalid extension ID"; - CopresenceManifestData* manifest_data = - static_cast<CopresenceManifestData*>( - extension->GetManifestData(manifest_keys::kCopresence)); - if (manifest_data) - return manifest_data->api_key; - } - - return std::string(); -} - -audio_modem::WhispernetClient* CopresenceService::GetWhispernetClient() { - if (!whispernet_client_ && !is_shutting_down_) - whispernet_client_.reset(new ChromeWhispernetClient(browser_context_)); - return whispernet_client_.get(); -} - -gcm::GCMDriver* CopresenceService::GetGCMDriver() { - gcm::GCMProfileService* gcm_service = - gcm::GCMProfileServiceFactory::GetForProfile(browser_context_); - return gcm_service ? gcm_service->driver() : nullptr; -} - -std::string CopresenceService::GetDeviceId(bool authenticated) { - std::string id = GetPrefService()->GetString(GetPrefName(authenticated)); - DVLOG(3) << "Retrieved device ID \"" << id << "\", " - << "authenticated = " << authenticated; - return id; -} - -void CopresenceService::SaveDeviceId(bool authenticated, - const std::string& device_id) { - DVLOG(3) << "Storing device ID \"" << device_id << "\", " - << "authenticated = " << authenticated; - if (device_id.empty()) - GetPrefService()->ClearPref(GetPrefName(authenticated)); - else - GetPrefService()->SetString(GetPrefName(authenticated), device_id); -} - -PrefService* CopresenceService::GetPrefService() { - return Profile::FromBrowserContext(browser_context_)->GetPrefs(); -} - -template <> -void -BrowserContextKeyedAPIFactory<CopresenceService>::DeclareFactoryDependencies() { - DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); -} - -// CopresenceExecuteFunction implementation. -ExtensionFunction::ResponseAction CopresenceExecuteFunction::Run() { - std::unique_ptr<Execute::Params> params(Execute::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - CopresenceService* service = - CopresenceService::GetFactoryInstance()->Get(browser_context()); - - // This can only happen if we're shutting down. In all other cases, if we - // don't have a manager, we'll create one. - if (!service->manager()) - return RespondNow(Error(kShuttingDownMessage)); - - // Each execute will correspond to one ReportRequest protocol buffer. - copresence::ReportRequest request; - if (!PrepareReportRequestProto(params->operations, - extension_id(), - &service->apps_by_subscription_id(), - &request)) { - return RespondNow(Error(kInvalidOperationsMessage)); - } - - service->manager()->ExecuteReportRequest( - request, - extension_id(), - service->auth_token(extension_id()), - base::Bind(&CopresenceExecuteFunction::SendResult, this)); - return RespondLater(); -} - -void CopresenceExecuteFunction::SendResult( - copresence::CopresenceStatus status) { - api::copresence::ExecuteStatus api_status = - (status == copresence::SUCCESS) ? api::copresence::EXECUTE_STATUS_SUCCESS - : api::copresence::EXECUTE_STATUS_FAILED; - Respond(ArgumentList(Execute::Results::Create(api_status))); -} - -// CopresenceSetApiKeyFunction implementation. -ExtensionFunction::ResponseAction CopresenceSetApiKeyFunction::Run() { - std::unique_ptr<SetApiKey::Params> params(SetApiKey::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - LOG(WARNING) << "copresence.setApiKey() is deprecated. " - << "Put the key in the manifest at copresence.api_key instead."; - - // The api key may be set to empty, to clear it. - CopresenceService::GetFactoryInstance()->Get(browser_context()) - ->set_api_key(extension_id(), params->api_key); - return RespondNow(NoArguments()); -} - -// CopresenceSetAuthTokenFunction implementation -ExtensionFunction::ResponseAction CopresenceSetAuthTokenFunction::Run() { - std::unique_ptr<SetAuthToken::Params> params( - SetAuthToken::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - // The token may be set to empty, to clear it. - CopresenceService::GetFactoryInstance()->Get(browser_context()) - ->set_auth_token(extension_id(), params->token); - return RespondNow(NoArguments()); -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/copresence/copresence_api.h b/chromium/chrome/browser/extensions/api/copresence/copresence_api.h deleted file mode 100644 index c6cbdcd73a6..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence/copresence_api.h +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_COPRESENCE_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_COPRESENCE_API_H_ - -#include <map> -#include <memory> -#include <string> -#include <vector> - -#include "base/macros.h" -#include "chrome/browser/extensions/api/copresence/copresence_translations.h" -#include "chrome/browser/extensions/chrome_extension_function.h" -#include "chrome/common/extensions/api/copresence.h" -#include "components/copresence/public/copresence_delegate.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" - -class ChromeWhispernetClient; - -namespace audio_modem { -class WhispernetClient; -} - -namespace copresence { -class CopresenceManager; -} - -namespace gcm { -class GCMDriver; -} - -namespace user_prefs { -class PrefRegistrySyncable; -} - -namespace extensions { - -class CopresenceService final : public BrowserContextKeyedAPI, - public copresence::CopresenceDelegate { - public: - explicit CopresenceService(content::BrowserContext* context); - ~CopresenceService() override; - - // BrowserContextKeyedAPI implementation. - static const bool kServiceHasOwnInstanceInIncognito = true; - void Shutdown() override; - - // These accessors will always return an object (except during shutdown). - // If the object doesn't exist, they will create one first. - copresence::CopresenceManager* manager(); - - // A registry containing the app id's associated with every subscription. - SubscriptionToAppMap& apps_by_subscription_id() { - return apps_by_subscription_id_; - } - - std::string auth_token(const std::string& app_id) const; - - void set_api_key(const std::string& app_id, - const std::string& api_key); - - void set_auth_token(const std::string& app_id, - const std::string& token); - - // Delete all current copresence data, including stored device IDs. - void ResetState(); - - // Manager override for testing. - void set_manager_for_testing( - std::unique_ptr<copresence::CopresenceManager> manager); - - // Registers the preference for saving our device IDs. - static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); - - // BrowserContextKeyedAPI implementation. - static BrowserContextKeyedAPIFactory<CopresenceService>* GetFactoryInstance(); - - private: - friend class BrowserContextKeyedAPIFactory<CopresenceService>; - - // CopresenceDelegate implementation - void HandleMessages(const std::string& app_id, - const std::string& subscription_id, - const std::vector<copresence::Message>& message) override; - void HandleStatusUpdate(copresence::CopresenceStatus status) override; - net::URLRequestContextGetter* GetRequestContext() const override; - std::string GetPlatformVersionString() const override; - std::string GetAPIKey(const std::string& app_id) const override; - audio_modem::WhispernetClient* GetWhispernetClient() override; - gcm::GCMDriver* GetGCMDriver() override; - std::string GetDeviceId(bool authenticated) override; - void SaveDeviceId(bool authenticated, const std::string& device_id) override; - - // BrowserContextKeyedAPI implementation. - static const char* service_name() { return "CopresenceService"; } - - PrefService* GetPrefService(); - - bool is_shutting_down_; - content::BrowserContext* const browser_context_; - - std::map<std::string, std::string> apps_by_subscription_id_; - - std::map<std::string, std::string> api_keys_by_app_; - std::map<std::string, std::string> auth_tokens_by_app_; - - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client_; - std::unique_ptr<copresence::CopresenceManager> manager_; - - DISALLOW_COPY_AND_ASSIGN(CopresenceService); -}; - -template <> -void BrowserContextKeyedAPIFactory< - CopresenceService>::DeclareFactoryDependencies(); - -class CopresenceExecuteFunction : public ChromeUIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresence.execute", COPRESENCE_EXECUTE); - - protected: - ~CopresenceExecuteFunction() override {} - ExtensionFunction::ResponseAction Run() override; - - private: - void SendResult(copresence::CopresenceStatus status); -}; - -// TODO(ckehoe): Remove this function. -class CopresenceSetApiKeyFunction : public ChromeUIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresence.setApiKey", COPRESENCE_SETAPIKEY); - - protected: - ~CopresenceSetApiKeyFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresenceSetAuthTokenFunction : public ChromeUIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresence.setAuthToken", - COPRESENCE_SETAUTHTOKEN); - - protected: - ~CopresenceSetAuthTokenFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_COPRESENCE_API_H_ diff --git a/chromium/chrome/browser/extensions/api/copresence/copresence_api_unittest.cc b/chromium/chrome/browser/extensions/api/copresence/copresence_api_unittest.cc deleted file mode 100644 index eacfe7a6fc5..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence/copresence_api_unittest.cc +++ /dev/null @@ -1,301 +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/extensions/api/copresence/copresence_api.h" - -#include <utility> - -#include "base/json/json_writer.h" -#include "base/memory/ptr_util.h" -#include "base/values.h" -#include "chrome/browser/extensions/extension_api_unittest.h" -#include "chrome/browser/extensions/extension_function_test_utils.h" -#include "components/copresence/proto/data.pb.h" -#include "components/copresence/proto/rpcs.pb.h" -#include "components/copresence/public/copresence_manager.h" - -using base::ListValue; -using copresence::AUDIO_CONFIGURATION_AUDIBLE; -using copresence::AUDIO_CONFIGURATION_UNKNOWN; -using copresence::BROADCAST_ONLY; -using copresence::CopresenceDelegate; -using copresence::CopresenceManager; -using copresence::FAIL; -using copresence::PublishedMessage; -using copresence::ReportRequest; -using copresence::SCAN_ONLY; -using copresence::Subscription; -using google::protobuf::RepeatedPtrField; - -namespace test_utils = extension_function_test_utils; - -namespace extensions { - -using api::copresence::Message; -using api::copresence::Operation; -using api::copresence::PublishOperation; -using api::copresence::Strategy; -using api::copresence::SubscribeOperation; -using api::copresence::UnpublishOperation; -using api::copresence::UnsubscribeOperation; - - -PublishOperation* CreatePublish(const std::string& id) { - PublishOperation* publish = new PublishOperation; - - publish->id = id; - publish->time_to_live_millis.reset(new int(1000)); - publish->message.type = "joke"; - std::string payload("Knock Knock!"); - publish->message.payload.assign(payload.begin(), payload.end()); - - return publish; -} - -SubscribeOperation* CreateSubscribe(const std::string& id) { - SubscribeOperation* subscribe = new SubscribeOperation; - - subscribe->id = id; - subscribe->time_to_live_millis.reset(new int(1000)); - subscribe->filter.type = "joke"; - - return subscribe; -} - -template <typename T> -bool GetOnly(const RepeatedPtrField<T>& things, T* out) { - if (things.size() != 1) - return false; - - *out = things.Get(0); - return true; -} - -class FakeCopresenceManager : public CopresenceManager { - public: - explicit FakeCopresenceManager(CopresenceDelegate* delegate) - : delegate_(delegate) {} - ~FakeCopresenceManager() override {} - - // CopresenceManager overrides. - copresence::CopresenceState* state() override { - NOTREACHED(); - return nullptr; - } - void ExecuteReportRequest( - const ReportRequest& request, - const std::string& app_id, - const std::string& /* auth_token */, - const copresence::StatusCallback& status_callback) override { - request_ = request; - app_id_ = app_id; - status_callback.Run(copresence::SUCCESS); - } - - CopresenceDelegate* delegate_; - - ReportRequest request_; - std::string app_id_; -}; - -class CopresenceApiUnittest : public ExtensionApiUnittest { - public: - CopresenceApiUnittest() {} - ~CopresenceApiUnittest() override {} - - void SetUp() override { - ExtensionApiUnittest::SetUp(); - - CopresenceService* service = - CopresenceService::GetFactoryInstance()->Get(profile()); - copresence_manager_ = new FakeCopresenceManager(service); - service->set_manager_for_testing( - base::WrapUnique<CopresenceManager>(copresence_manager_)); - } - - // Takes ownership of the operation_list. - bool ExecuteOperations(ListValue* operation_list) { - std::unique_ptr<ListValue> args_list(new ListValue); - args_list->Append(operation_list); - - scoped_refptr<UIThreadExtensionFunction> function = - new CopresenceExecuteFunction; - function->set_extension(extension()); - function->set_browser_context(profile()); - function->set_has_callback(true); - test_utils::RunFunction(function.get(), std::move(args_list), browser(), - test_utils::NONE); - return function->GetResultList(); - } - - bool ExecuteOperation(std::unique_ptr<Operation> operation) { - ListValue* operation_list = new ListValue; - operation_list->Append(operation->ToValue()); - return ExecuteOperations(operation_list); - } - - const ReportRequest& request_sent() const { - return copresence_manager_->request_; - } - - const std::string& app_id_sent() const { - return copresence_manager_->app_id_; - } - - void clear_app_id() { - copresence_manager_->app_id_.clear(); - } - - CopresenceDelegate* delegate() { - return copresence_manager_->delegate_; - } - - protected: - FakeCopresenceManager* copresence_manager_; -}; - -TEST_F(CopresenceApiUnittest, Publish) { - std::unique_ptr<PublishOperation> publish(CreatePublish("pub")); - publish->strategies.reset(new Strategy); - publish->strategies->only_broadcast.reset(new bool(true)); // Default - - std::unique_ptr<Operation> operation(new Operation); - operation->publish = std::move(publish); - - clear_app_id(); - EXPECT_TRUE(ExecuteOperation(std::move(operation))); - EXPECT_EQ(extension()->id(), app_id_sent()); - - PublishedMessage message; - ASSERT_TRUE(GetOnly( - request_sent().manage_messages_request().message_to_publish(), &message)); - EXPECT_EQ("pub", message.id()); - EXPECT_EQ(1000, message.access_policy().ttl_millis()); - EXPECT_EQ(copresence::NO_ACL_CHECK, message.access_policy().acl().acl_type()); - EXPECT_EQ("joke", message.message().type().type()); - EXPECT_EQ("Knock Knock!", message.message().payload()); - EXPECT_EQ(BROADCAST_ONLY, - message.token_exchange_strategy().broadcast_scan_configuration()); - EXPECT_EQ(AUDIO_CONFIGURATION_UNKNOWN, - message.token_exchange_strategy().audio_configuration()); -} - -TEST_F(CopresenceApiUnittest, Subscribe) { - std::unique_ptr<SubscribeOperation> subscribe(CreateSubscribe("sub")); - subscribe->strategies.reset(new Strategy); - subscribe->strategies->only_broadcast.reset(new bool(true)); // Not default - subscribe->strategies->audible.reset(new bool(true)); // Not default - - std::unique_ptr<Operation> operation(new Operation); - operation->subscribe = std::move(subscribe); - - clear_app_id(); - EXPECT_TRUE(ExecuteOperation(std::move(operation))); - EXPECT_EQ(extension()->id(), app_id_sent()); - - Subscription subscription; - ASSERT_TRUE(GetOnly( - request_sent().manage_subscriptions_request().subscription(), - &subscription)); - EXPECT_EQ("sub", subscription.id()); - EXPECT_EQ(1000, subscription.ttl_millis()); - EXPECT_EQ("joke", subscription.message_type().type()); - copresence::BroadcastScanConfiguration broadcast_scan = - subscription.token_exchange_strategy().broadcast_scan_configuration(); - EXPECT_EQ(BROADCAST_ONLY, broadcast_scan); - EXPECT_EQ(AUDIO_CONFIGURATION_AUDIBLE, - subscription.token_exchange_strategy().audio_configuration()); -} - -TEST_F(CopresenceApiUnittest, DefaultStrategies) { - std::unique_ptr<Operation> publish_operation(new Operation); - publish_operation->publish.reset(CreatePublish("pub")); - - std::unique_ptr<Operation> subscribe_operation(new Operation); - subscribe_operation->subscribe.reset(CreateSubscribe("sub")); - - ListValue* operation_list = new ListValue; - operation_list->Append(publish_operation->ToValue()); - operation_list->Append(subscribe_operation->ToValue()); - EXPECT_TRUE(ExecuteOperations(operation_list)); - - EXPECT_EQ(BROADCAST_ONLY, - request_sent().manage_messages_request().message_to_publish(0) - .token_exchange_strategy().broadcast_scan_configuration()); - EXPECT_EQ(SCAN_ONLY, - request_sent().manage_subscriptions_request().subscription(0) - .token_exchange_strategy().broadcast_scan_configuration()); -} - -TEST_F(CopresenceApiUnittest, LowPowerStrategy) { - std::unique_ptr<Operation> subscribe_operation(new Operation); - subscribe_operation->subscribe.reset(CreateSubscribe("sub")); - subscribe_operation->subscribe->strategies.reset(new Strategy); - subscribe_operation->subscribe->strategies->low_power.reset(new bool(true)); - - ListValue* operation_list = new ListValue; - operation_list->Append(subscribe_operation->ToValue()); - EXPECT_TRUE(ExecuteOperations(operation_list)); - - EXPECT_EQ(copresence::BROADCAST_SCAN_CONFIGURATION_UNKNOWN, - request_sent().manage_subscriptions_request().subscription(0) - .token_exchange_strategy().broadcast_scan_configuration()); -} - -TEST_F(CopresenceApiUnittest, UnPubSub) { - // First we need to create a publish and a subscribe to cancel. - std::unique_ptr<Operation> publish_operation(new Operation); - std::unique_ptr<Operation> subscribe_operation(new Operation); - publish_operation->publish.reset(CreatePublish("pub")); - subscribe_operation->subscribe.reset(CreateSubscribe("sub")); - ListValue* operation_list = new ListValue; - operation_list->Append(publish_operation->ToValue()); - operation_list->Append(subscribe_operation->ToValue()); - EXPECT_TRUE(ExecuteOperations(operation_list)); - - std::unique_ptr<Operation> unpublish_operation(new Operation); - unpublish_operation->unpublish.reset(new UnpublishOperation); - unpublish_operation->unpublish->unpublish_id = "pub"; - - std::unique_ptr<Operation> unsubscribe_operation(new Operation); - unsubscribe_operation->unsubscribe.reset(new UnsubscribeOperation); - unsubscribe_operation->unsubscribe->unsubscribe_id = "sub"; - - operation_list = new ListValue; - operation_list->Append(unpublish_operation->ToValue()); - operation_list->Append(unsubscribe_operation->ToValue()); - EXPECT_TRUE(ExecuteOperations(operation_list)); - - std::string unpublish_id; - ASSERT_TRUE(GetOnly( - request_sent().manage_messages_request().id_to_unpublish(), - &unpublish_id)); - EXPECT_EQ("pub", unpublish_id); - - std::string unsubscribe_id; - ASSERT_TRUE(GetOnly( - request_sent().manage_subscriptions_request().id_to_unsubscribe(), - &unsubscribe_id)); - EXPECT_EQ("sub", unsubscribe_id); -} - -TEST_F(CopresenceApiUnittest, BadId) { - std::unique_ptr<Operation> unsubscribe_operation(new Operation); - unsubscribe_operation->unsubscribe.reset(new UnsubscribeOperation); - unsubscribe_operation->unsubscribe->unsubscribe_id = "invalid id"; - - EXPECT_FALSE(ExecuteOperation(std::move(unsubscribe_operation))); -} - -TEST_F(CopresenceApiUnittest, MultipleOperations) { - std::unique_ptr<Operation> multi_operation(new Operation); - multi_operation->publish.reset(CreatePublish("pub")); - multi_operation->subscribe.reset(CreateSubscribe("sub")); - - EXPECT_FALSE(ExecuteOperation(std::move(multi_operation))); -} - -} // namespace extensions - -// TODO(ckehoe): add tests for auth tokens and api key functionality diff --git a/chromium/chrome/browser/extensions/api/copresence/copresence_translations.cc b/chromium/chrome/browser/extensions/api/copresence/copresence_translations.cc deleted file mode 100644 index 3537e2cd99b..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence/copresence_translations.cc +++ /dev/null @@ -1,234 +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/extensions/api/copresence/copresence_translations.h" - -#include "chrome/common/extensions/api/copresence.h" -#include "components/copresence/proto/data.pb.h" -#include "components/copresence/proto/enums.pb.h" -#include "components/copresence/proto/rpcs.pb.h" - -using copresence::AUDIO_CONFIGURATION_AUDIBLE; -using copresence::AUDIO_CONFIGURATION_UNKNOWN; -using copresence::BROADCAST_AND_SCAN; -using copresence::BROADCAST_ONLY; -using copresence::BROADCAST_SCAN_CONFIGURATION_UNKNOWN; -using copresence::BroadcastScanConfiguration; -using copresence::ReportRequest; -using copresence::SCAN_ONLY; -using copresence::TokenExchangeStrategy; - -using extensions::api::copresence::Strategy; - -namespace { - -const int kDefaultTimeToLiveMs = 5 * 60 * 1000; // 5 minutes. -const int kMaxTimeToLiveMs = 24 * 60 * 60 * 1000; // 24 hours. - -// Checks and returns the ttl provided by the user. If invalid, returns -1. -int SanitizeTtl(int* user_ttl) { - return !user_ttl - ? kDefaultTimeToLiveMs - : (*user_ttl <= 0 || *user_ttl > kMaxTimeToLiveMs ? -1 : *user_ttl); -} - -BroadcastScanConfiguration TranslateStrategy(const Strategy& strategy) { - bool only_broadcast = strategy.only_broadcast && *strategy.only_broadcast; - bool only_scan = strategy.only_scan && *strategy.only_scan; - - if (only_broadcast && only_scan) - return BROADCAST_AND_SCAN; - if (only_broadcast) - return BROADCAST_ONLY; - if (only_scan) - return SCAN_ONLY; - - return BROADCAST_SCAN_CONFIGURATION_UNKNOWN; -} - -// The strategy may be null (unspecified), so we pass it as a pointer. -void SetTokenExchangeStrategy(const Strategy* strategy, - BroadcastScanConfiguration default_config, - TokenExchangeStrategy* strategy_proto) { - if (strategy) { - BroadcastScanConfiguration config; - if (strategy->low_power && *(strategy->low_power)) { - config = BROADCAST_SCAN_CONFIGURATION_UNKNOWN; - } else { - config = TranslateStrategy(*strategy); - if (config == BROADCAST_SCAN_CONFIGURATION_UNKNOWN) - config = default_config; - } - - strategy_proto->set_broadcast_scan_configuration(config); - strategy_proto->set_audio_configuration( - strategy->audible && *strategy->audible ? AUDIO_CONFIGURATION_AUDIBLE - : AUDIO_CONFIGURATION_UNKNOWN); - } else { - strategy_proto->set_broadcast_scan_configuration(default_config); - strategy_proto->set_audio_configuration(AUDIO_CONFIGURATION_UNKNOWN); - } -} - -} // namespace - -namespace extensions { - -using api::copresence::Operation; - -// Adds a publish operation to the report request. Returns false if the -// publish operation was invalid. -bool AddPublishToRequest(const std::string& app_id, - const api::copresence::PublishOperation& publish, - ReportRequest* request) { - copresence::PublishedMessage* publish_proto = - request->mutable_manage_messages_request()->add_message_to_publish(); - publish_proto->mutable_access_policy()->mutable_acl()->set_acl_type( - copresence::NO_ACL_CHECK); - publish_proto->set_id(publish.id); - publish_proto->mutable_message()->mutable_type()->set_type( - publish.message.type); - publish_proto->mutable_message()->set_payload(publish.message.payload.data(), - publish.message.payload.size()); - - int ttl = SanitizeTtl(publish.time_to_live_millis.get()); - if (ttl < 0) - return false; - publish_proto->mutable_access_policy()->set_ttl_millis(ttl); - - SetTokenExchangeStrategy(publish.strategies.get(), - BROADCAST_ONLY, - publish_proto->mutable_token_exchange_strategy()); - - DVLOG(2) << "Publishing message of type " << publish.message.type << ":\n" - << std::string(publish.message.payload.begin(), - publish.message.payload.end()); - // TODO(ckehoe): Validate that required fields are non-empty, etc. - return true; -} - -// Adds an unpublish operation to the report request. Returns false if the -// publish id was invalid. -bool AddUnpublishToRequest(const std::string& publish_id, - ReportRequest* request) { - if (publish_id.empty()) - return false; - - request->mutable_manage_messages_request()->add_id_to_unpublish(publish_id); - DVLOG(2) << "Unpublishing message \"" << publish_id << "\""; - return true; -} - -// Adds a subscribe operation to the report request. Returns false if the -// subscription operation was invalid. -bool AddSubscribeToRequest( - const std::string& app_id, - const api::copresence::SubscribeOperation& subscription, - SubscriptionToAppMap* apps_by_subscription_id, - ReportRequest* request) { - // Associate the subscription id with the app id. - SubscriptionToAppMap::iterator previous_subscription = - apps_by_subscription_id->find(subscription.id); - if (previous_subscription == apps_by_subscription_id->end()) { - (*apps_by_subscription_id)[subscription.id] = app_id; - } else if (previous_subscription->second == app_id) { - VLOG(2) << "Overwriting subscription id \"" << subscription.id - << "\" for app \"" << app_id << "\""; - } else { - // A conflicting association exists already. - VLOG(1) << "Subscription id \"" << subscription.id - << "\" used by two apps: \"" << previous_subscription->second - << "\" and \"" << app_id << "\""; - return false; - } - - // Convert from IDL to server subscription format. - copresence::Subscription* subscription_proto = - request->mutable_manage_subscriptions_request()->add_subscription(); - subscription_proto->set_id(subscription.id); - int ttl = SanitizeTtl(subscription.time_to_live_millis.get()); - if (ttl < 0) - return false; - subscription_proto->set_ttl_millis(ttl); - - subscription_proto->mutable_message_type()->set_type( - subscription.filter.type); - - SetTokenExchangeStrategy( - subscription.strategies.get(), - SCAN_ONLY, - subscription_proto->mutable_token_exchange_strategy()); - - DVLOG(2) << "Subscribing for messages of type " << subscription.filter.type; - // TODO(ckehoe): Validate that required fields are non-empty, etc. - return true; -} - -// Adds an unpublish operation to the report request. Returns false if the -// subscription id was invalid. -bool AddUnsubscribeToRequest(const std::string& app_id, - const std::string& subscription_id, - SubscriptionToAppMap* apps_by_subscription_id, - ReportRequest* request) { - if (subscription_id.empty()) - return false; - - // Check that this subscription id belongs to this app. - SubscriptionToAppMap::iterator subscription = - apps_by_subscription_id->find(subscription_id); - if (subscription == apps_by_subscription_id->end()) { - LOG(ERROR) << "No such subscription \"" << subscription_id - << "\". Cannot unsubscribe."; - return false; - } else if (subscription->second != app_id) { - LOG(ERROR) << "Subscription \"" << subscription_id - << "\" does not belong to app \"" << app_id - << "\". Cannot unsubscribe."; - return false; - } else { - apps_by_subscription_id->erase(subscription); - } - - request->mutable_manage_subscriptions_request()->add_id_to_unsubscribe( - subscription_id); - DVLOG(2) << "Cancelling subscription \"" << subscription_id << "\" for app \"" - << app_id << "\""; - return true; -} - -bool PrepareReportRequestProto(const std::vector<Operation>& operations, - const std::string& app_id, - SubscriptionToAppMap* apps_by_subscription_id, - ReportRequest* request) { - for (const Operation& op : operations) { - // Verify our object has exactly one operation. - if (static_cast<int>(op.publish != nullptr) + - static_cast<int>(op.subscribe != nullptr) + - static_cast<int>(op.unpublish != nullptr) + - static_cast<int>(op.unsubscribe != nullptr) != - 1) { - return false; - } - - if (op.publish) { - if (!AddPublishToRequest(app_id, *(op.publish), request)) - return false; - } else if (op.subscribe) { - if (!AddSubscribeToRequest(app_id, *(op.subscribe), - apps_by_subscription_id, request)) - return false; - } else if (op.unpublish) { - if (!AddUnpublishToRequest(op.unpublish->unpublish_id, request)) - return false; - } else { // if (op.unsubscribe) - if (!AddUnsubscribeToRequest(app_id, op.unsubscribe->unsubscribe_id, - apps_by_subscription_id, request)) - return false; - } - } - - return true; -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/copresence/copresence_translations.h b/chromium/chrome/browser/extensions/api/copresence/copresence_translations.h deleted file mode 100644 index 4903c622c87..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence/copresence_translations.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_COPRESENCE_TRANSLATIONS_H_ -#define CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_COPRESENCE_TRANSLATIONS_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/macros.h" -#include "components/copresence/proto/enums.pb.h" - -namespace copresence { -class ReportRequest; -} - -namespace extensions { - -namespace api { -namespace copresence { -struct Operation; -struct PublishOperation; -struct SubscribeOperation; -} -} - -// A 1-1 map of of which app a subscription id belongs to. -// Key = subscription, value = app_id. -typedef std::map<std::string, std::string> SubscriptionToAppMap; - -// Returns report request protocol buffer containing all the operations in the -// given vector. If parsing any of the operations fails, we return false. -bool PrepareReportRequestProto( - const std::vector<api::copresence::Operation>& operations, - const std::string& app_id, - SubscriptionToAppMap* apps_by_subscription_id, - copresence::ReportRequest* request); - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_COPRESENCE_TRANSLATIONS_H_ diff --git a/chromium/chrome/browser/extensions/api/copresence_private/OWNERS b/chromium/chrome/browser/extensions/api/copresence_private/OWNERS deleted file mode 100644 index 5f781a66da0..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence_private/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -rkc@chromium.org -ckehoe@chromium.org diff --git a/chromium/chrome/browser/extensions/api/copresence_private/copresence_private_api.cc b/chromium/chrome/browser/extensions/api/copresence_private/copresence_private_api.cc deleted file mode 100644 index 4bdaf0f8301..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence_private/copresence_private_api.cc +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/copresence_private/copresence_private_api.h" - -#include <stddef.h> - -#include <map> -#include <string> -#include <vector> - -#include "base/guid.h" -#include "base/lazy_instance.h" -#include "chrome/browser/copresence/chrome_whispernet_client.h" -#include "chrome/common/extensions/api/copresence_private.h" -#include "content/public/browser/browser_thread.h" -#include "media/base/audio_bus.h" - -using audio_modem::WhispernetClient; -using content::BrowserThread; - -namespace extensions { - -namespace SendFound = api::copresence_private::SendFound; -namespace SendSamples = api::copresence_private::SendSamples; -namespace SendInitialized = api::copresence_private::SendInitialized; - -namespace { - -base::LazyInstance<BrowserContextKeyedAPIFactory<CopresencePrivateService>> - g_factory = LAZY_INSTANCE_INITIALIZER; - -void RunInitCallback(WhispernetClient* client, bool status) { - DCHECK(client); - audio_modem::SuccessCallback init_callback = - client->GetInitializedCallback(); - if (!init_callback.is_null()) - init_callback.Run(status); -} - -} // namespace - -CopresencePrivateService::CopresencePrivateService( - content::BrowserContext* context) - : initialized_(false) {} - -CopresencePrivateService::~CopresencePrivateService() {} - -const std::string CopresencePrivateService::RegisterWhispernetClient( - WhispernetClient* client) { - if (initialized_) - RunInitCallback(client, true); - - std::string id = base::GenerateGUID(); - whispernet_clients_[id] = client; - - return id; -} - -void CopresencePrivateService::OnWhispernetInitialized(bool success) { - if (success) - initialized_ = true; - - DVLOG(2) << "Notifying " << whispernet_clients_.size() - << " clients that initialization is complete."; - for (auto client_entry : whispernet_clients_) - RunInitCallback(client_entry.second, success); -} - -WhispernetClient* CopresencePrivateService::GetWhispernetClient( - const std::string& id) { - WhispernetClient* client = whispernet_clients_[id]; - DCHECK(client); - return client; -} - -// static -BrowserContextKeyedAPIFactory<CopresencePrivateService>* -CopresencePrivateService::GetFactoryInstance() { - return g_factory.Pointer(); -} - -template <> -void BrowserContextKeyedAPIFactory<CopresencePrivateService> - ::DeclareFactoryDependencies() { - DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); -} - - -// Copresence Private functions. - -// CopresenceSendFoundFunction implementation: -ExtensionFunction::ResponseAction CopresencePrivateSendFoundFunction::Run() { - std::unique_ptr<SendFound::Params> params(SendFound::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - WhispernetClient* whispernet_client = - CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) - ->GetWhispernetClient(params->client_id); - if (whispernet_client->GetTokensCallback().is_null()) - return RespondNow(NoArguments()); - - std::vector<audio_modem::AudioToken> tokens; - for (size_t i = 0; i < params->tokens.size(); ++i) { - tokens.push_back(audio_modem::AudioToken(params->tokens[i].token, - params->tokens[i].audible)); - } - whispernet_client->GetTokensCallback().Run(tokens); - return RespondNow(NoArguments()); -} - -// CopresenceSendEncodedFunction implementation: -ExtensionFunction::ResponseAction CopresencePrivateSendSamplesFunction::Run() { - std::unique_ptr<SendSamples::Params> params( - SendSamples::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - WhispernetClient* whispernet_client = - CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) - ->GetWhispernetClient(params->client_id); - if (whispernet_client->GetSamplesCallback().is_null()) - return RespondNow(NoArguments()); - - scoped_refptr<media::AudioBusRefCounted> samples = - media::AudioBusRefCounted::Create(1, // Mono - params->samples.size() / sizeof(float)); - - memcpy(samples->channel(0), params->samples.data(), params->samples.size()); - - whispernet_client->GetSamplesCallback().Run( - params->token.audible ? audio_modem::AUDIBLE : audio_modem::INAUDIBLE, - params->token.token, samples); - return RespondNow(NoArguments()); -} - -// CopresenceSendInitializedFunction implementation: -ExtensionFunction::ResponseAction -CopresencePrivateSendInitializedFunction::Run() { - std::unique_ptr<SendInitialized::Params> params( - SendInitialized::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) - ->OnWhispernetInitialized(params->success); - - return RespondNow(NoArguments()); -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/copresence_private/copresence_private_api.h b/chromium/chrome/browser/extensions/api/copresence_private/copresence_private_api.h deleted file mode 100644 index 3be29040c19..00000000000 --- a/chromium/chrome/browser/extensions/api/copresence_private/copresence_private_api.h +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_PRIVATE_COPRESENCE_PRIVATE_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_PRIVATE_COPRESENCE_PRIVATE_API_H_ - -#include <string> - -#include "base/macros.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/extension_function_histogram_value.h" - -namespace audio_modem { -class WhispernetClient; -} - -namespace extensions { - -class CopresencePrivateService final : public BrowserContextKeyedAPI { - public: - explicit CopresencePrivateService(content::BrowserContext* context); - ~CopresencePrivateService() override; - - // Registers a client to receive events from Whispernet. - const std::string - RegisterWhispernetClient(audio_modem::WhispernetClient* client); - - // Gets the whispernet client by ID. - audio_modem::WhispernetClient* GetWhispernetClient(const std::string& id); - - // Called from the whispernet_proxy extension when it has initialized. - void OnWhispernetInitialized(bool success); - - // BrowserContextKeyedAPI implementation. - static BrowserContextKeyedAPIFactory<CopresencePrivateService>* - GetFactoryInstance(); - - private: - friend class BrowserContextKeyedAPIFactory<CopresencePrivateService>; - - // BrowserContextKeyedAPI implementation. - static const bool kServiceRedirectedInIncognito = true; - static const char* service_name() { return "CopresencePrivateService"; } - - bool initialized_; - std::map<std::string, audio_modem::WhispernetClient*> whispernet_clients_; - - DISALLOW_COPY_AND_ASSIGN(CopresencePrivateService); -}; - -template<> -void BrowserContextKeyedAPIFactory<CopresencePrivateService> - ::DeclareFactoryDependencies(); - -class CopresencePrivateSendFoundFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendFound", - COPRESENCEPRIVATE_SENDFOUND); - - protected: - ~CopresencePrivateSendFoundFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresencePrivateSendSamplesFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendSamples", - COPRESENCEPRIVATE_SENDSAMPLES); - - protected: - ~CopresencePrivateSendSamplesFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresencePrivateSendDetectFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendDetect", - COPRESENCEPRIVATE_SENDDETECT); - - protected: - ~CopresencePrivateSendDetectFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresencePrivateSendInitializedFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendInitialized", - COPRESENCEPRIVATE_SENDINITIALIZED); - - protected: - ~CopresencePrivateSendInitializedFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_PRIVATE_COPRESENCE_PRIVATE_API_H_ diff --git a/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.cc b/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.cc index a2563e222b3..1f84f6a6f96 100644 --- a/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.cc +++ b/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.cc @@ -48,9 +48,9 @@ void DataReductionProxyGetDataUsageFunction::ReplyWithDataUsage( for (const auto& data_usage_bucket : *data_usage) { std::unique_ptr<base::ListValue> connection_usage_list( new base::ListValue()); - for (auto connection_usage : data_usage_bucket.connection_usage()) { + for (const auto& connection_usage : data_usage_bucket.connection_usage()) { std::unique_ptr<base::ListValue> site_usage_list(new base::ListValue()); - for (auto site_usage : connection_usage.site_usage()) { + for (const auto& site_usage : connection_usage.site_usage()) { std::unique_ptr<base::DictionaryValue> usage( new base::DictionaryValue()); usage->SetString("hostname", site_usage.hostname()); diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc index c20ff0fcd39..6242e561ef4 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc @@ -26,7 +26,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/devtools/devtools_target_impl.h" +#include "chrome/browser/devtools/chrome_devtools_manager_delegate.h" #include "chrome/browser/devtools/global_confirm_info_bar.h" #include "chrome/browser/extensions/api/debugger/debugger_api_constants.h" #include "chrome/browser/extensions/extension_service.h" @@ -109,7 +109,8 @@ class ExtensionDevToolsInfoBarDelegate : public ConfirmInfoBarDelegate { int GetButtons() const override; bool Cancel() override; - std::string client_name_; + private: + const base::string16 client_name_; base::Closure dismissed_callback_; DISALLOW_COPY_AND_ASSIGN(ExtensionDevToolsInfoBarDelegate); @@ -119,7 +120,7 @@ ExtensionDevToolsInfoBarDelegate::ExtensionDevToolsInfoBarDelegate( const base::Closure& dismissed_callback, const std::string& client_name) : ConfirmInfoBarDelegate(), - client_name_(client_name), + client_name_(base::UTF8ToUTF16(client_name)), dismissed_callback_(dismissed_callback) {} ExtensionDevToolsInfoBarDelegate::~ExtensionDevToolsInfoBarDelegate() { @@ -147,8 +148,7 @@ void ExtensionDevToolsInfoBarDelegate::InfoBarDismissed() { } base::string16 ExtensionDevToolsInfoBarDelegate::GetMessageText() const { - return l10n_util::GetStringFUTF16(IDS_DEV_TOOLS_INFOBAR_LABEL, - base::UTF8ToUTF16(client_name_)); + return l10n_util::GetStringFUTF16(IDS_DEV_TOOLS_INFOBAR_LABEL, client_name_); } int ExtensionDevToolsInfoBarDelegate::GetButtons() const { @@ -236,7 +236,7 @@ void ExtensionDevToolsInfoBar::Remove( void ExtensionDevToolsInfoBar::InfoBarDismissed() { std::map<ExtensionDevToolsClientHost*, base::Closure> copy = callbacks_; - for (const auto& pair: copy) + for (const auto& pair : copy) pair.second.Run(); } @@ -673,33 +673,36 @@ const char kTargetTitleField[] = "title"; const char kTargetAttachedField[] = "attached"; const char kTargetUrlField[] = "url"; const char kTargetFaviconUrlField[] = "faviconUrl"; -const char kTargetTypePage[] = "page"; -const char kTargetTypeBackgroundPage[] = "background_page"; -const char kTargetTypeWorker[] = "worker"; -const char kTargetTypeOther[] = "other"; const char kTargetTabIdField[] = "tabId"; const char kTargetExtensionIdField[] = "extensionId"; +const char kTargetTypeWorker[] = "worker"; -base::Value* SerializeTarget(const DevToolsTargetImpl& target) { - base::DictionaryValue* dictionary = new base::DictionaryValue(); - - dictionary->SetString(kTargetIdField, target.GetId()); - dictionary->SetString(kTargetTitleField, target.GetTitle()); - dictionary->SetBoolean(kTargetAttachedField, target.IsAttached()); - dictionary->SetString(kTargetUrlField, target.GetURL().spec()); - - std::string type = target.GetType(); - if (type == kTargetTypePage) { - dictionary->SetInteger(kTargetTabIdField, target.GetTabId()); - } else if (type == kTargetTypeBackgroundPage) { - dictionary->SetString(kTargetExtensionIdField, target.GetExtensionId()); - } else if (type != kTargetTypeWorker) { - // DevToolsTargetImpl may support more types than the debugger API. - type = kTargetTypeOther; +std::unique_ptr<base::DictionaryValue> SerializeTarget( + scoped_refptr<DevToolsAgentHost> host) { + std::unique_ptr<base::DictionaryValue> dictionary( + new base::DictionaryValue()); + dictionary->SetString(kTargetIdField, host->GetId()); + dictionary->SetString(kTargetTitleField, host->GetTitle()); + dictionary->SetBoolean(kTargetAttachedField, host->IsAttached()); + dictionary->SetString(kTargetUrlField, host->GetURL().spec()); + + std::string type = host->GetType(); + if (type == DevToolsAgentHost::kTypePage) { + int tab_id = + extensions::ExtensionTabUtil::GetTabId(host->GetWebContents()); + dictionary->SetInteger(kTargetTabIdField, tab_id); + } else if (type == ChromeDevToolsManagerDelegate::kTypeBackgroundPage) { + dictionary->SetString(kTargetExtensionIdField, host->GetURL().host()); } + + if (type == DevToolsAgentHost::kTypeServiceWorker || + type == DevToolsAgentHost::kTypeSharedWorker) { + type = kTargetTypeWorker; + } + dictionary->SetString(kTargetTypeField, type); - GURL favicon_url = target.GetFaviconURL(); + GURL favicon_url = host->GetFaviconURL(); if (favicon_url.is_valid()) dictionary->SetString(kTargetFaviconUrlField, favicon_url.spec()); @@ -715,7 +718,7 @@ DebuggerGetTargetsFunction::~DebuggerGetTargetsFunction() { } bool DebuggerGetTargetsFunction::RunAsync() { - std::vector<DevToolsTargetImpl*> list = DevToolsTargetImpl::EnumerateAll(); + content::DevToolsAgentHost::List list = DevToolsAgentHost::GetOrCreateAll(); content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, @@ -724,11 +727,10 @@ bool DebuggerGetTargetsFunction::RunAsync() { } void DebuggerGetTargetsFunction::SendTargetList( - const std::vector<DevToolsTargetImpl*>& target_list) { + const content::DevToolsAgentHost::List& target_list) { std::unique_ptr<base::ListValue> result(new base::ListValue()); for (size_t i = 0; i < target_list.size(); ++i) - result->Append(SerializeTarget(*target_list[i])); - STLDeleteContainerPointers(target_list.begin(), target_list.end()); + result->Append(SerializeTarget(target_list[i])); SetResult(std::move(result)); SendResponse(true); } diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.h b/chromium/chrome/browser/extensions/api/debugger/debugger_api.h index af2d98f1472..c9e7ef0cd39 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.h +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.h @@ -13,19 +13,17 @@ #include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/common/extensions/api/debugger.h" +#include "content/public/browser/devtools_agent_host.h" using extensions::api::debugger::Debuggee; // Base debugger function. -class DevToolsTargetImpl; - namespace base { class DictionaryValue; } namespace content { -class DevToolsAgentHost; class WebContents; } @@ -104,7 +102,7 @@ class DebuggerGetTargetsFunction : public DebuggerFunction { bool RunAsync() override; private: - void SendTargetList(const std::vector<DevToolsTargetImpl*>& target_list); + void SendTargetList(const content::DevToolsAgentHost::List& target_list); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc index 810b4df4f03..68f7410f909 100644 --- a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc @@ -123,7 +123,7 @@ class DeclarativeApiTest : public ExtensionApiTest { base::Bind( &RulesRegistry::GetAllRules, rules_registry, extension_id, &rules)); scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get())); + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO).get())); EXPECT_TRUE(io_helper->Run()); return rules.size(); } 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 404e32251a3..e8798fd378a 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 @@ -14,7 +14,6 @@ #include "chrome/browser/extensions/test_extension_environment.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/common/extensions/extension_test_util.h" -#include "chrome/common/extensions/features/feature_channel.h" #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -25,6 +24,7 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/value_store/testing_value_store.h" #include "extensions/common/extension.h" +#include "extensions/common/features/feature_channel.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/permissions/permissions_data.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc index 54127c05eec..c5b2f3d705d 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc @@ -20,6 +20,7 @@ #include "extensions/browser/api/declarative/rules_registry_service.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" +#include "extensions/common/extension_id.h" namespace extensions { @@ -135,7 +136,7 @@ void ChromeContentRulesRegistry::DidNavigateMainFrame( content::WebContents* contents, const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { - if (ContainsKey(active_rules_, contents)) { + if (base::ContainsKey(active_rules_, contents)) { EvaluationScope evaluation_scope(this); for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator : evaluators_) @@ -179,9 +180,8 @@ ChromeContentRulesRegistry::CreateRule( // Note: |api_rule| may contain tags, but these are ignored. - return base::WrapUnique(new ContentRule(extension, std::move(conditions), - std::move(actions), - *api_rule.priority)); + return base::MakeUnique<ContentRule>(extension, std::move(conditions), + std::move(actions), *api_rule.priority); } bool ChromeContentRulesRegistry::ManagingRulesForBrowserContext( @@ -320,7 +320,7 @@ std::string ChromeContentRulesRegistry::RemoveRulesImpl( // Remove the ContentRule from active_rules_. for (auto& tab_rules_pair : active_rules_) { - if (ContainsKey(tab_rules_pair.second, rule)) { + if (base::ContainsKey(tab_rules_pair.second, rule)) { ContentAction::ApplyInfo apply_info = {rule->extension, browser_context(), tab_rules_pair.first, rule->priority}; @@ -362,14 +362,14 @@ std::string ChromeContentRulesRegistry::RemoveAllRulesImpl( void ChromeContentRulesRegistry::EvaluateConditionsForTab( content::WebContents* tab) { std::set<const ContentRule*> matching_rules = GetMatchingRules(tab); - if (matching_rules.empty() && !ContainsKey(active_rules_, tab)) + if (matching_rules.empty() && !base::ContainsKey(active_rules_, tab)) return; std::set<const ContentRule*>& prev_matching_rules = active_rules_[tab]; for (const ContentRule* rule : matching_rules) { ContentAction::ApplyInfo apply_info = {rule->extension, browser_context(), tab, rule->priority}; - if (!ContainsKey(prev_matching_rules, rule)) { + if (!base::ContainsKey(prev_matching_rules, rule)) { for (const std::unique_ptr<const ContentAction>& action : rule->actions) action->Apply(apply_info); } else { @@ -378,7 +378,7 @@ void ChromeContentRulesRegistry::EvaluateConditionsForTab( } } for (const ContentRule* rule : prev_matching_rules) { - if (!ContainsKey(matching_rules, rule)) { + if (!base::ContainsKey(matching_rules, rule)) { ContentAction::ApplyInfo apply_info = {rule->extension, browser_context(), tab, rule->priority}; for (const std::unique_ptr<const ContentAction>& action : rule->actions) diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h index b4e674a1d7a..f8f52063b12 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h @@ -23,7 +23,7 @@ #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "extensions/browser/api/declarative_content/content_rules_registry.h" -#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" namespace content { class BrowserContext; diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc index 47e503e59e6..7dff9dea1ea 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc @@ -57,7 +57,7 @@ class TestPredicateEvaluator : public ContentPredicateEvaluator { const base::Value& value, std::string* error) override { RequestEvaluationIfSpecified(); - return base::WrapUnique(new TestPredicate(this)); + return base::MakeUnique<TestPredicate>(this); } void TrackPredicates( diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc b/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc index 72d2aaa7db1..6da57a16b91 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc @@ -331,7 +331,7 @@ RequestContentScript::RequestContentScript( RequestContentScript::~RequestContentScript() { DCHECK(master_); - master_->RemoveScript(script_); + master_->RemoveScript(UserScriptIDPair(script_.id(), script_.host_id())); } void RequestContentScript::InitScript(const HostID& host_id, @@ -347,7 +347,7 @@ void RequestContentScript::InitScript(const HostID& host_id, it != script_data.css_file_names.end(); ++it) { GURL url = extension->GetResourceURL(*it); ExtensionResource resource = extension->GetResource(*it); - script_.css_scripts().push_back(UserScript::File( + script_.css_scripts().push_back(base::MakeUnique<UserScript::File>( resource.extension_root(), resource.relative_path(), url)); } for (std::vector<std::string>::const_iterator it = @@ -355,11 +355,16 @@ void RequestContentScript::InitScript(const HostID& host_id, it != script_data.js_file_names.end(); ++it) { GURL url = extension->GetResourceURL(*it); ExtensionResource resource = extension->GetResource(*it); - script_.js_scripts().push_back(UserScript::File( + script_.js_scripts().push_back(base::MakeUnique<UserScript::File>( resource.extension_root(), resource.relative_path(), url)); } } +void RequestContentScript::AddScript() { + DCHECK(master_); + master_->AddScript(UserScript::CopyMetadataFrom(script_)); +} + void RequestContentScript::Apply(const ApplyInfo& apply_info) const { InstructRenderProcessToInject(apply_info.tab, apply_info.extension); } diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_action.h b/chromium/chrome/browser/extensions/api/declarative_content/content_action.h index cfd6925e100..6b5d0dd3b0e 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_action.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_action.h @@ -104,10 +104,7 @@ class RequestContentScript : public ContentAction { const Extension* extension, const ScriptData& script_data); - void AddScript() { - DCHECK(master_); - master_->AddScript(script_); - } + void AddScript(); void InstructRenderProcessToInject(content::WebContents* contents, const Extension* extension) const; diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc index 25f94ac58ee..cc2363c7173 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc @@ -145,9 +145,9 @@ void DeclarativeContentApiTest::CheckIncognito(IncognitoMode mode, ExtensionTestMessageListener ready("ready", false); ExtensionTestMessageListener ready_incognito("ready (split)", false); - const Extension* extension = is_enabled_in_incognito ? - LoadExtensionIncognito(ext_dir_.unpacked_path()) : - LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = + is_enabled_in_incognito ? LoadExtensionIncognito(ext_dir_.UnpackedPath()) + : LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); Browser* incognito_browser = CreateIncognitoBrowser(); @@ -207,7 +207,7 @@ void DeclarativeContentApiTest::CheckBookmarkEvents(bool match_is_bookmarked) { browser()->tab_strip_model()->GetWebContentsAt(0); const int tab_id = ExtensionTabUtil::GetTabId(tab); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get( browser()->profile())->GetPageAction(*extension); @@ -230,7 +230,7 @@ void DeclarativeContentApiTest::CheckBookmarkEvents(bool match_is_bookmarked) { // Check rule evaluation on add/remove bookmark. bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForProfile(browser()->profile()); + BookmarkModelFactory::GetForBrowserContext(browser()->profile()); const bookmarks::BookmarkNode* node = bookmark_model->AddURL(bookmark_model->other_node(), 0, base::ASCIIToUTF16("title"), @@ -278,7 +278,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_Overview) { " });\n" "});\n"); ExtensionTestMessageListener ready("ready", false); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get(browser()->profile())-> @@ -358,7 +358,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ReusedActionInstance) { " });\n" "});\n"); ExtensionTestMessageListener ready("ready", false); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get(browser()->profile()) @@ -380,7 +380,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ReusedActionInstance) { IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, RulesEvaluatedOnAddRemove) { ext_dir_.WriteManifest(kDeclarativeContentManifest); ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get(browser()->profile())-> @@ -450,7 +450,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, RulesAddedFromManifest) { " }]\n" "}\n"; ext_dir_.WriteManifest(manifest); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get(browser()->profile()) @@ -509,7 +509,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kIncognitoSpecificBackground); ExtensionTestMessageListener ready("ready", false); - const Extension* extension = LoadExtensionIncognito(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtensionIncognito(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); ASSERT_TRUE(ready.WaitUntilSatisfied()); @@ -599,7 +599,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, MAYBE_UninstallWhileActivePageAction) { ext_dir_.WriteManifest(kDeclarativeContentManifest); ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const std::string extension_id = extension->id(); const ExtensionAction* page_action = ExtensionActionManager::Get( @@ -658,7 +658,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ASSERT_TRUE(content::ExecuteScript( tab, "document.body.innerHTML = '<span class=\"foo\">';")); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get( browser()->profile())->GetPageAction(*extension); @@ -716,7 +716,7 @@ class ShowPageActionWithoutPageActionTest : public DeclarativeContentApiTest { ext_dir_.WriteManifest(manifest_without_page_action); ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const char kScript[] = @@ -799,7 +799,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, "function Return(obj) {\n" " window.domAutomationController.send('' + obj);\n" "}\n"); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); EXPECT_EQ("input[type=\"password\"]", @@ -876,7 +876,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, // trigger OnExtensionLoaded. ext_dir_.WriteManifest(kDeclarativeContentManifest); ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers); - ASSERT_TRUE(LoadExtension(ext_dir_.unpacked_path())); + ASSERT_TRUE(LoadExtension(ext_dir_.UnpackedPath())); } // https://crbug.com/501225 @@ -884,7 +884,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, PendingWebContentsClearedOnRemoveRules) { ext_dir_.WriteManifest(kDeclarativeContentManifest); ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get( browser()->profile())->GetPageAction(*extension); @@ -943,7 +943,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers); // Load the extension, add a rule, then uninstall the extension. - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const std::string kAddTestRule = @@ -967,7 +967,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ASSERT_EQ(base::ASCIIToUTF16(""), error); // Reload the extension, then add and remove a rule. - extension = LoadExtension(ext_dir_.unpacked_path()); + extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); EXPECT_EQ("add_rule", diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc index 745b331c22b..82c25da9420 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc @@ -234,7 +234,7 @@ void DeclarativeContentCssConditionTracker::OnWebContentsNavigation( content::WebContents* contents, const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { - DCHECK(ContainsKey(per_web_contents_tracker_, contents)); + DCHECK(base::ContainsKey(per_web_contents_tracker_, contents)); per_web_contents_tracker_[contents]->OnWebContentsNavigation(details, params); } @@ -250,7 +250,7 @@ bool DeclarativeContentCssConditionTracker::EvaluatePredicate( loc->second->matching_css_selectors(); for (const std::string& predicate_css_selector : typed_predicate->css_selectors()) { - if (!ContainsKey(matching_css_selectors, predicate_css_selector)) + if (!base::ContainsKey(matching_css_selectors, predicate_css_selector)) return false; } @@ -304,7 +304,7 @@ InstructRenderProcessIfManagingBrowserContext( void DeclarativeContentCssConditionTracker::DeletePerWebContentsTracker( content::WebContents* contents) { - DCHECK(ContainsKey(per_web_contents_tracker_, contents)); + DCHECK(base::ContainsKey(per_web_contents_tracker_, contents)); per_web_contents_tracker_.erase(contents); } diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc index ac22f8d7b32..884a756aec3 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc @@ -11,7 +11,6 @@ #include "base/values.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/extensions/api/declarative_content/content_constants.h" -#include "chrome/browser/profiles/profile.h" #include "components/bookmarks/browser/bookmark_model.h" #include "content/public/browser/web_contents.h" #include "extensions/common/permissions/permissions_data.h" @@ -111,7 +110,7 @@ BookmarkAddedForUrl(const GURL& url) { void DeclarativeContentIsBookmarkedConditionTracker::PerWebContentsTracker:: BookmarkRemovedForUrls(const std::set<GURL>& urls) { - if (ContainsKey(urls, web_contents()->GetVisibleURL())) { + if (base::ContainsKey(urls, web_contents()->GetVisibleURL())) { is_url_bookmarked_ = false; request_evaluation_.Run(web_contents()); } @@ -130,8 +129,8 @@ UpdateState(bool request_evaluation_if_unchanged) { bool DeclarativeContentIsBookmarkedConditionTracker::PerWebContentsTracker:: IsCurrentUrlBookmarked() { bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForProfile( - Profile::FromBrowserContext(web_contents()->GetBrowserContext())); + BookmarkModelFactory::GetForBrowserContext( + web_contents()->GetBrowserContext()); // BookmarkModel can be null during unit test execution. return bookmark_model && bookmark_model->IsBookmarked(web_contents()->GetVisibleURL()); @@ -153,7 +152,7 @@ DeclarativeContentIsBookmarkedConditionTracker(content::BrowserContext* context, extensive_bookmark_changes_in_progress_(0), scoped_bookmarks_observer_(this) { bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForProfile(Profile::FromBrowserContext(context)); + BookmarkModelFactory::GetForBrowserContext(context); // Can be null during unit test execution. if (bookmark_model) scoped_bookmarks_observer_.Add(bookmark_model); @@ -203,7 +202,7 @@ void DeclarativeContentIsBookmarkedConditionTracker::OnWebContentsNavigation( content::WebContents* contents, const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { - DCHECK(ContainsKey(per_web_contents_tracker_, contents)); + DCHECK(base::ContainsKey(per_web_contents_tracker_, contents)); per_web_contents_tracker_[contents]->UpdateState(true); } @@ -275,7 +274,7 @@ DeclarativeContentIsBookmarkedConditionTracker::GroupedBookmarkChangesEnded( void DeclarativeContentIsBookmarkedConditionTracker::DeletePerWebContentsTracker( content::WebContents* contents) { - DCHECK(ContainsKey(per_web_contents_tracker_, contents)); + DCHECK(base::ContainsKey(per_web_contents_tracker_, contents)); per_web_contents_tracker_.erase(contents); } diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc index 69eabb12fcd..44fcb66672e 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc @@ -82,7 +82,7 @@ class DeclarativeContentIsBookmarkedConditionTrackerTest // ContentPredicateEvaluator::Delegate: void RequestEvaluation(content::WebContents* contents) override { - EXPECT_FALSE(ContainsKey(evaluation_requests_, contents)); + EXPECT_FALSE(base::ContainsKey(evaluation_requests_, contents)); evaluation_requests_.insert(contents); } @@ -100,8 +100,8 @@ class DeclarativeContentIsBookmarkedConditionTrackerTest DeclarativeContentIsBookmarkedConditionTrackerTest() { profile()->CreateBookmarkModel(true); bookmarks::test::WaitForBookmarkModelToLoad( - BookmarkModelFactory::GetForProfile(profile())); - bookmark_model_ = BookmarkModelFactory::GetForProfile(profile()); + BookmarkModelFactory::GetForBrowserContext(profile())); + bookmark_model_ = BookmarkModelFactory::GetForBrowserContext(profile()); tracker_.reset(new DeclarativeContentIsBookmarkedConditionTracker( profile(), &delegate_)); diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc index 5866146fde6..e6271fe0957 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc @@ -194,7 +194,7 @@ void DeclarativeContentPageUrlConditionTracker::OnWebContentsNavigation( content::WebContents* contents, const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { - DCHECK(ContainsKey(per_web_contents_tracker_, contents)); + DCHECK(base::ContainsKey(per_web_contents_tracker_, contents)); per_web_contents_tracker_[contents]->UpdateMatchesForCurrentUrl(true); } @@ -208,8 +208,8 @@ bool DeclarativeContentPageUrlConditionTracker::EvaluatePredicate( DCHECK(loc != per_web_contents_tracker_.end()); const std::set<url_matcher::URLMatcherConditionSet::ID>& web_contents_id_matches = loc->second->matches(); - return ContainsKey(web_contents_id_matches, - typed_predicate->url_matcher_condition_set()->id()); + return base::ContainsKey(web_contents_id_matches, + typed_predicate->url_matcher_condition_set()->id()); } bool DeclarativeContentPageUrlConditionTracker::IsEmpty() const { @@ -218,7 +218,7 @@ bool DeclarativeContentPageUrlConditionTracker::IsEmpty() const { void DeclarativeContentPageUrlConditionTracker::DeletePerWebContentsTracker( content::WebContents* contents) { - DCHECK(ContainsKey(per_web_contents_tracker_, contents)); + DCHECK(base::ContainsKey(per_web_contents_tracker_, contents)); per_web_contents_tracker_.erase(contents); } diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc index ef8dad962ab..a719121d030 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc @@ -39,7 +39,7 @@ class DeclarativeContentPageUrlConditionTrackerTest // ContentPredicateEvaluator::Delegate: void RequestEvaluation(content::WebContents* contents) override { - EXPECT_FALSE(ContainsKey(evaluation_requests_, contents)); + EXPECT_FALSE(base::ContainsKey(evaluation_requests_, contents)); evaluation_requests_.insert(contents); } diff --git a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc index efd41cb75ea..ffa680bbcd2 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc @@ -177,11 +177,11 @@ testing::AssertionResult RequestContentScriptAPITest::CreateAndLoadExtension( dir->WriteFile(FILE_PATH_LITERAL("script.js"), kContentScriptSource); - const Extension* extension = LoadExtension(dir->unpacked_path()); + const Extension* extension = LoadExtension(dir->UnpackedPath()); if (!extension) return testing::AssertionFailure() << "Failed to load extension."; - test_extension_dir_.reset(dir.release()); + test_extension_dir_ = std::move(dir); extension_ = extension; // Wait for rules to be setup before navigating to trigger script injection. diff --git a/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc index a1936a2a4a3..5a91c7c006c 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc @@ -7,8 +7,8 @@ #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/extensions/features/feature_channel.h" #include "components/version_info/version_info.h" +#include "extensions/common/features/feature_channel.h" #include "extensions/test/extension_test_message_listener.h" #include "ui/gfx/image/image.h" @@ -72,7 +72,7 @@ IN_PROC_BROWSER_TEST_F(SetIconAPITest, Overview) { " });\n" "});\n"); ExtensionTestMessageListener ready("ready", false); - const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + const Extension* extension = LoadExtension(ext_dir_.UnpackedPath()); ASSERT_TRUE(extension); const ExtensionAction* page_action = ExtensionActionManager::Get(browser()->profile())-> 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 ef9c1b27b85..474367a592a 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 @@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/memory/linked_ptr.h" #include "base/message_loop/message_loop.h" +#include "base/run_loop.h" #include "base/stl_util.h" #include "base/test/values_test_util.h" #include "base/values.h" @@ -93,7 +94,7 @@ class WebRequestRulesRegistryTest : public testing::Test { void TearDown() override { // Make sure that deletion traits of all registries are executed. - message_loop_.RunUntilIdle(); + base::RunLoop().RunUntilIdle(); } // Returns a rule that roughly matches http://*.example.com and @@ -288,8 +289,10 @@ TEST_F(WebRequestRulesRegistryTest, AddRulesImpl) { for (std::set<const WebRequestRule*>::const_iterator it = matches.begin(); it != matches.end(); ++it) matches_ids.insert((*it)->id()); - EXPECT_TRUE(ContainsKey(matches_ids, std::make_pair(kExtensionId, kRuleId1))); - EXPECT_TRUE(ContainsKey(matches_ids, std::make_pair(kExtensionId, kRuleId2))); + EXPECT_TRUE( + base::ContainsKey(matches_ids, std::make_pair(kExtensionId, kRuleId1))); + EXPECT_TRUE( + base::ContainsKey(matches_ids, std::make_pair(kExtensionId, kRuleId2))); GURL foobar_url("http://www.foobar.com"); std::unique_ptr<net::URLRequest> foobar_request( diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc index d28c49f6ad9..e6f28293e37 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc @@ -12,7 +12,7 @@ #include "build/build_config.h" #include "chrome/browser/extensions/api/desktop_capture/desktop_capture_api.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/media/fake_desktop_media_list.h" +#include "chrome/browser/media/webrtc/fake_desktop_media_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" @@ -173,10 +173,6 @@ class DesktopCaptureApiTest : public ExtensionApiTest { #define MAYBE_ChooseDesktopMedia ChooseDesktopMedia #endif IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) { - // For tabshare, we need to turn on the flag. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - extensions::switches::kEnableTabForDesktopShare); - // Each element in the following array corresponds to one test in // chrome/test/data/extensions/api_test/desktop_capture/test.js . TestFlags test_flags[] = { diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc index 82d24612d6c..049a56b160d 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc @@ -12,12 +12,11 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/media/desktop_media_list_ash.h" -#include "chrome/browser/media/desktop_streams_registry.h" -#include "chrome/browser/media/media_capture_devices_dispatcher.h" -#include "chrome/browser/media/native_desktop_media_list.h" -#include "chrome/browser/media/tab_desktop_media_list.h" -#include "chrome/common/channel_info.h" +#include "chrome/browser/media/webrtc/desktop_media_list_ash.h" +#include "chrome/browser/media/webrtc/desktop_streams_registry.h" +#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" +#include "chrome/browser/media/webrtc/native_desktop_media_list.h" +#include "chrome/browser/media/webrtc/tab_desktop_media_list.h" #include "components/version_info/version_info.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -98,20 +97,9 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( break; case api::desktop_capture::DESKTOP_CAPTURE_SOURCE_TYPE_TAB: - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - extensions::switches::kEnableTabForDesktopShare)) { - show_tabs = true; - } else if (base::CommandLine::ForCurrentProcess()->HasSwitch( + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( extensions::switches::kDisableTabForDesktopShare)) { - show_tabs = false; - } else { - const version_info::Channel channel = chrome::GetChannel(); - if ((channel == version_info::Channel::STABLE) || - (channel == version_info::Channel::BETA)) { - show_tabs = false; - } else { - show_tabs = true; - } + show_tabs = true; } break; @@ -145,8 +133,8 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( // Create a screens list. if (show_screens) { #if defined(USE_ASH) - screen_list = base::WrapUnique( - new DesktopMediaListAsh(DesktopMediaListAsh::SCREENS)); + screen_list = + base::MakeUnique<DesktopMediaListAsh>(DesktopMediaListAsh::SCREENS); #endif if (!screen_list) { webrtc::DesktopCaptureOptions options = @@ -155,16 +143,16 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( std::unique_ptr<webrtc::ScreenCapturer> screen_capturer( webrtc::ScreenCapturer::Create(options)); - screen_list = base::WrapUnique( - new NativeDesktopMediaList(std::move(screen_capturer), nullptr)); + screen_list = base::MakeUnique<NativeDesktopMediaList>( + std::move(screen_capturer), nullptr); } } // Create a windows list. if (show_windows) { #if defined(USE_ASH) - window_list = base::WrapUnique( - new DesktopMediaListAsh(DesktopMediaListAsh::WINDOWS)); + window_list = + base::MakeUnique<DesktopMediaListAsh>(DesktopMediaListAsh::WINDOWS); #endif if (!window_list) { webrtc::DesktopCaptureOptions options = @@ -173,13 +161,13 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( std::unique_ptr<webrtc::WindowCapturer> window_capturer( webrtc::WindowCapturer::Create(options)); - window_list = base::WrapUnique( - new NativeDesktopMediaList(nullptr, std::move(window_capturer))); + window_list = base::MakeUnique<NativeDesktopMediaList>( + nullptr, std::move(window_capturer)); } } if (show_tabs) - tab_list = base::WrapUnique(new TabDesktopMediaList()); + tab_list = base::MakeUnique<TabDesktopMediaList>(); DCHECK(screen_list || window_list || tab_list); @@ -252,13 +240,14 @@ DesktopCaptureCancelChooseDesktopMediaFunctionBase:: DesktopCaptureCancelChooseDesktopMediaFunctionBase:: ~DesktopCaptureCancelChooseDesktopMediaFunctionBase() {} -bool DesktopCaptureCancelChooseDesktopMediaFunctionBase::RunSync() { +ExtensionFunction::ResponseAction +DesktopCaptureCancelChooseDesktopMediaFunctionBase::Run() { int request_id; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id)); DesktopCaptureRequestsRegistry::GetInstance()->CancelRequest( render_frame_host()->GetProcess()->GetID(), request_id); - return true; + return RespondNow(NoArguments()); } DesktopCaptureRequestsRegistry::DesktopCaptureRequestsRegistry() {} 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 db005559ea8..38b803d2b15 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 @@ -11,8 +11,8 @@ #include "base/macros.h" #include "base/memory/singleton.h" #include "chrome/browser/extensions/chrome_extension_function.h" -#include "chrome/browser/media/desktop_media_list.h" -#include "chrome/browser/media/desktop_media_picker.h" +#include "chrome/browser/media/webrtc/desktop_media_list.h" +#include "chrome/browser/media/webrtc/desktop_media_picker.h" #include "chrome/common/extensions/api/desktop_capture.h" #include "content/public/browser/web_contents_observer.h" #include "url/gurl.h" @@ -77,7 +77,7 @@ class DesktopCaptureChooseDesktopMediaFunctionBase }; class DesktopCaptureCancelChooseDesktopMediaFunctionBase - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DesktopCaptureCancelChooseDesktopMediaFunctionBase(); @@ -86,7 +86,7 @@ class DesktopCaptureCancelChooseDesktopMediaFunctionBase private: // ExtensionFunction overrides. - bool RunSync() override; + ResponseAction Run() override; }; class DesktopCaptureRequestsRegistry { 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 8059b165500..02cf2f17dff 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 @@ -29,6 +29,7 @@ #include "chrome/browser/extensions/extension_ui_util.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/install_verifier.h" +#include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/extensions/shared_module_service.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/extensions/updater/extension_updater.h" @@ -642,8 +643,14 @@ DeveloperPrivateUpdateExtensionConfigurationFunction::Run() { extension->id(), *update.error_collection); } if (update.run_on_all_urls) { - util::SetAllowedScriptingOnAllUrls( - extension->id(), browser_context(), *update.run_on_all_urls); + ScriptingPermissionsModifier modifier(browser_context(), extension); + if (!modifier.CanAffectExtension( + extension->permissions_data()->active_permissions()) && + !modifier.HasAffectedExtension()) { + return RespondNow( + Error("Cannot modify all urls of extension: " + extension->id())); + } + modifier.SetAllowedOnAllUrls(*update.run_on_all_urls); } if (update.show_action_button) { ExtensionActionAPI::Get(browser_context())->SetBrowserActionVisibility( @@ -1156,10 +1163,10 @@ void DeveloperPrivateChoosePathFunction::FileSelectionCanceled() { DeveloperPrivateChoosePathFunction::~DeveloperPrivateChoosePathFunction() {} -bool DeveloperPrivateIsProfileManagedFunction::RunSync() { - SetResult( - base::MakeUnique<base::FundamentalValue>(GetProfile()->IsSupervised())); - return true; +ExtensionFunction::ResponseAction +DeveloperPrivateIsProfileManagedFunction::Run() { + return RespondNow(OneArgument(base::MakeUnique<base::FundamentalValue>( + Profile::FromBrowserContext(browser_context())->IsSupervised()))); } DeveloperPrivateIsProfileManagedFunction:: 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 25d2a5d479c..ecc6b05ddd3 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 @@ -445,7 +445,7 @@ class DeveloperPrivatePackDirectoryFunction }; class DeveloperPrivateIsProfileManagedFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("developerPrivate.isProfileManaged", DEVELOPERPRIVATE_ISPROFILEMANAGED); @@ -454,7 +454,7 @@ class DeveloperPrivateIsProfileManagedFunction ~DeveloperPrivateIsProfileManagedFunction() override; // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class DeveloperPrivateLoadDirectoryFunction 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 8f881fe7c4b..5961e214069 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 @@ -16,6 +16,7 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/extensions/extension_util.h" +#include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/extensions/unpacked_installer.h" @@ -44,13 +45,24 @@ namespace extensions { namespace { std::unique_ptr<KeyedService> BuildAPI(content::BrowserContext* context) { - return base::WrapUnique(new DeveloperPrivateAPI(context)); + return base::MakeUnique<DeveloperPrivateAPI>(context); } std::unique_ptr<KeyedService> BuildEventRouter( content::BrowserContext* profile) { - return base::WrapUnique( - new EventRouter(profile, ExtensionPrefs::Get(profile))); + return base::MakeUnique<EventRouter>(profile, ExtensionPrefs::Get(profile)); +} + +bool HasAllUrlsPermission(const Extension* extension, + content::BrowserContext* context) { + return ScriptingPermissionsModifier(context, extension).IsAllowedOnAllUrls(); +} + +bool HasPrefsPermission(bool (*has_pref)(const std::string&, + content::BrowserContext*), + content::BrowserContext* context, + const std::string& id) { + return has_pref(id, context); } } // namespace @@ -74,10 +86,9 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestBase { const Extension* LoadSimpleExtension(); // Tests modifying the extension's configuration. - void TestExtensionPrefSetting( - bool (*has_pref)(const std::string&, content::BrowserContext*), - const std::string& key, - const std::string& extension_id); + void TestExtensionPrefSetting(const base::Callback<bool()>& has_pref, + const std::string& key, + const std::string& extension_id); testing::AssertionResult TestPackExtensionFunction( const base::ListValue& args, @@ -95,7 +106,7 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestBase { std::unique_ptr<TestBrowserWindow> browser_window_; std::unique_ptr<Browser> browser_; - ScopedVector<TestExtensionDir> test_extension_dirs_; + std::vector<std::unique_ptr<TestExtensionDir>> test_extension_dirs_; DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateApiUnitTest); }; @@ -104,7 +115,7 @@ bool DeveloperPrivateApiUnitTest::RunFunction( const scoped_refptr<UIThreadExtensionFunction>& function, const base::ListValue& args) { return extension_function_test_utils::RunFunction( - function.get(), base::WrapUnique(args.DeepCopy()), browser(), + function.get(), args.CreateDeepCopy(), browser(), extension_function_test_utils::NONE); } @@ -117,8 +128,8 @@ const Extension* DeveloperPrivateApiUnitTest::LoadUnpackedExtension() { " \"permissions\": [\"*://*/*\"]" "}"; - test_extension_dirs_.push_back(new TestExtensionDir); - TestExtensionDir* dir = test_extension_dirs_.back(); + test_extension_dirs_.push_back(base::MakeUnique<TestExtensionDir>()); + TestExtensionDir* dir = test_extension_dirs_.back().get(); dir->WriteManifest(kManifest); // TODO(devlin): We should extract out methods to load an unpacked extension @@ -127,9 +138,9 @@ const Extension* DeveloperPrivateApiUnitTest::LoadUnpackedExtension() { TestExtensionRegistryObserver registry_observer(registry()); scoped_refptr<UnpackedInstaller> installer( UnpackedInstaller::Create(service())); - installer->Load(dir->unpacked_path()); + installer->Load(dir->UnpackedPath()); base::FilePath extension_path = - base::MakeAbsoluteFilePath(dir->unpacked_path()); + base::MakeAbsoluteFilePath(dir->UnpackedPath()); const Extension* extension = nullptr; do { extension = registry_observer.WaitForExtensionLoaded(); @@ -161,33 +172,43 @@ const Extension* DeveloperPrivateApiUnitTest::LoadSimpleExtension() { } void DeveloperPrivateApiUnitTest::TestExtensionPrefSetting( - bool (*has_pref)(const std::string&, content::BrowserContext*), + const base::Callback<bool()>& has_pref, const std::string& key, const std::string& extension_id) { scoped_refptr<UIThreadExtensionFunction> function( new api::DeveloperPrivateUpdateExtensionConfigurationFunction()); - base::ListValue args; - base::DictionaryValue* parameters = new base::DictionaryValue(); - parameters->SetString("extensionId", extension_id); - parameters->SetBoolean(key, true); - args.Append(parameters); - - EXPECT_FALSE(has_pref(extension_id, profile())) << key; - - EXPECT_FALSE(RunFunction(function, args)) << key; - EXPECT_EQ(std::string("This action requires a user gesture."), - function->GetError()); - - ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - function = new api::DeveloperPrivateUpdateExtensionConfigurationFunction(); - EXPECT_TRUE(RunFunction(function, args)) << key; - EXPECT_TRUE(has_pref(extension_id, profile())) << key; - - parameters->SetBoolean(key, false); - function = new api::DeveloperPrivateUpdateExtensionConfigurationFunction(); - EXPECT_TRUE(RunFunction(function, args)) << key; - EXPECT_FALSE(has_pref(extension_id, profile())) << key; + EXPECT_FALSE(has_pref.Run()) << key; + + { + auto parameters = base::MakeUnique<base::DictionaryValue>(); + parameters->SetString("extensionId", extension_id); + parameters->SetBoolean(key, true); + + base::ListValue args; + args.Append(std::move(parameters)); + EXPECT_FALSE(RunFunction(function, args)) << key; + EXPECT_EQ("This action requires a user gesture.", function->GetError()); + + ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; + function = new api::DeveloperPrivateUpdateExtensionConfigurationFunction(); + EXPECT_TRUE(RunFunction(function, args)) << key; + EXPECT_TRUE(has_pref.Run()) << key; + } + + { + auto parameters = base::MakeUnique<base::DictionaryValue>(); + parameters->SetString("extensionId", extension_id); + parameters->SetBoolean(key, false); + + base::ListValue args; + args.Append(std::move(parameters)); + + ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; + function = new api::DeveloperPrivateUpdateExtensionConfigurationFunction(); + EXPECT_TRUE(RunFunction(function, args)) << key; + EXPECT_FALSE(has_pref.Run()) << key; + } } testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction( @@ -253,12 +274,18 @@ TEST_F(DeveloperPrivateApiUnitTest, FeatureSwitch::scripts_require_action(), true); // Sadly, we need a "real" directory here, because toggling prefs causes // a reload (which needs a path). - std::string id = LoadUnpackedExtension()->id(); + const Extension* extension = LoadUnpackedExtension(); + const std::string& id = extension->id(); - TestExtensionPrefSetting(&util::IsIncognitoEnabled, "incognitoAccess", id); - TestExtensionPrefSetting(&util::AllowFileAccess, "fileAccess", id); TestExtensionPrefSetting( - &util::AllowedScriptingOnAllUrls, "runOnAllUrls", id); + base::Bind(&HasPrefsPermission, &util::IsIncognitoEnabled, profile(), id), + "incognitoAccess", id); + TestExtensionPrefSetting( + base::Bind(&HasPrefsPermission, &util::AllowFileAccess, profile(), id), + "fileAccess", id); + TestExtensionPrefSetting( + base::Bind(&HasAllUrlsPermission, extension, profile()), "runOnAllUrls", + id); } // Test developerPrivate.reload. @@ -286,11 +313,12 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivatePackFunction) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath root_path = data_dir().AppendASCII("good_unpacked"); - ASSERT_TRUE(base::CopyDirectory(root_path, temp_dir.path(), true)); + ASSERT_TRUE(base::CopyDirectory(root_path, temp_dir.GetPath(), true)); - base::FilePath temp_root_path = temp_dir.path().Append(root_path.BaseName()); - base::FilePath crx_path = temp_dir.path().AppendASCII("good_unpacked.crx"); - base::FilePath pem_path = temp_dir.path().AppendASCII("good_unpacked.pem"); + base::FilePath temp_root_path = + temp_dir.GetPath().Append(root_path.BaseName()); + base::FilePath crx_path = temp_dir.GetPath().AppendASCII("good_unpacked.crx"); + base::FilePath pem_path = temp_dir.GetPath().AppendASCII("good_unpacked.pem"); EXPECT_FALSE(base::PathExists(crx_path)) << "crx should not exist before the test is run!"; diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_mangle.h b/chromium/chrome/browser/extensions/api/developer_private/developer_private_mangle.h index c3d4b5e4112..5c25c0c46da 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_mangle.h +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_mangle.h @@ -5,8 +5,6 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_DEVELOPER_PRIVATE_DEVELOPER_PRIVATE_MANGLE_H_ #define CHROME_BROWSER_EXTENSIONS_API_DEVELOPER_PRIVATE_DEVELOPER_PRIVATE_MANGLE_H_ -#include "base/memory/linked_ptr.h" - namespace extensions { namespace api { diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc index c2288a616c2..7f30bef5e2b 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc @@ -466,7 +466,7 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper( if (error_console_enabled) { const ErrorList& errors = error_console_->GetErrorsForExtension(extension.id()); - for (const ExtensionError* error : errors) { + for (const auto& error : errors) { switch (error->type()) { case ExtensionError::MANIFEST_ERROR: info->manifest_errors.push_back(ConstructManifestError( @@ -526,8 +526,7 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper( permissions_modifier.CanAffectExtension( extension.permissions_data()->active_permissions())) || permissions_modifier.HasAffectedExtension(); - info->run_on_all_urls.is_active = - util::AllowedScriptingOnAllUrls(extension.id(), browser_context_); + info->run_on_all_urls.is_active = permissions_modifier.IsAllowedOnAllUrls(); // Runtime warnings. std::vector<std::string> warnings = diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc index ba72f7d6799..30d379c8708 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc @@ -21,6 +21,7 @@ #include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/permissions_updater.h" +#include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/developer_private.h" #include "chrome/common/pref_names.h" @@ -395,7 +396,9 @@ TEST_F(ExtensionInfoGeneratorUnitTest, ExtensionInfoRunOnAllUrls) { EXPECT_FALSE(info->run_on_all_urls.is_active); // Give the extension all urls. - util::SetAllowedScriptingOnAllUrls(all_urls_extension->id(), profile(), true); + ScriptingPermissionsModifier permissions_modifier(profile(), + all_urls_extension); + permissions_modifier.SetAllowedOnAllUrls(true); // Now the extension should both want and have all urls. info = GenerateExtensionInfo(all_urls_extension->id()); @@ -408,8 +411,7 @@ TEST_F(ExtensionInfoGeneratorUnitTest, ExtensionInfoRunOnAllUrls) { EXPECT_FALSE(info->run_on_all_urls.is_active); // Revoke the first extension's permissions. - util::SetAllowedScriptingOnAllUrls( - all_urls_extension->id(), profile(), false); + permissions_modifier.SetAllowedOnAllUrls(false); // Turn off the switch and load another extension (so permissions are // re-initialized). @@ -423,7 +425,7 @@ TEST_F(ExtensionInfoGeneratorUnitTest, ExtensionInfoRunOnAllUrls) { // If we grant the extension all urls, then the checkbox should still be // there, since it has an explicitly-set user preference. - util::SetAllowedScriptingOnAllUrls(all_urls_extension->id(), profile(), true); + permissions_modifier.SetAllowedOnAllUrls(true); info = GenerateExtensionInfo(all_urls_extension->id()); EXPECT_TRUE(info->run_on_all_urls.is_enabled); EXPECT_TRUE(info->run_on_all_urls.is_active); diff --git a/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h b/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h index f904c372c8d..07e6e52128e 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h +++ b/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h @@ -8,7 +8,6 @@ #include <vector> #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "extensions/common/view_type.h" class Profile; diff --git a/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.cc b/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.cc index 5fd7528cf38..fe8425b2681 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.cc @@ -8,7 +8,7 @@ #include "apps/app_load_service.h" #include "apps/saved_files_service.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/apps/app_info_dialog.h" #include "content/public/browser/web_contents.h" diff --git a/chromium/chrome/browser/extensions/api/dial/dial_api.cc b/chromium/chrome/browser/extensions/api/dial/dial_api.cc index 30eac215513..6f43b17aaf0 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_api.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_api.cc @@ -39,7 +39,7 @@ namespace dial = api::dial; DialAPI::DialAPI(Profile* profile) : RefcountedKeyedService( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)), profile_(profile) { EventRouter::Get(profile) ->RegisterObserver(this, dial::OnDeviceList::kEventName); diff --git a/chromium/chrome/browser/extensions/api/dial/dial_registry.cc b/chromium/chrome/browser/extensions/api/dial/dial_registry.cc index 1c502d7c39e..f3cbe46ef07 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_registry.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_registry.cc @@ -6,6 +6,7 @@ #include <memory> +#include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" @@ -16,9 +17,11 @@ #include "chrome/browser/extensions/api/dial/dial_service.h" #include "chrome/common/extensions/api/dial.h" #include "components/net_log/chrome_net_log.h" +#include "content/public/browser/browser_thread.h" using base::Time; using base::TimeDelta; +using content::BrowserThread; using net::NetworkChangeNotifier; namespace extensions { @@ -35,18 +38,19 @@ DialRegistry::DialRegistry(Observer* dial_api, expiration_delta_(expiration), max_devices_(max_devices), dial_api_(dial_api) { - DCHECK(max_devices_ > 0); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_GT(max_devices_, 0U); NetworkChangeNotifier::AddNetworkChangeObserver(this); } DialRegistry::~DialRegistry() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); NetworkChangeNotifier::RemoveNetworkChangeObserver(this); } -DialService* DialRegistry::CreateDialService() { +std::unique_ptr<DialService> DialRegistry::CreateDialService() { DCHECK(g_browser_process->net_log()); - return new DialServiceImpl(g_browser_process->net_log()); + return base::MakeUnique<DialServiceImpl>(g_browser_process->net_log()); } void DialRegistry::ClearDialService() { @@ -58,7 +62,7 @@ base::Time DialRegistry::Now() const { } void DialRegistry::OnListenerAdded() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (++num_listeners_ == 1) { VLOG(2) << "Listener added; starting periodic discovery."; StartPeriodicDiscovery(); @@ -70,8 +74,8 @@ void DialRegistry::OnListenerAdded() { } void DialRegistry::OnListenerRemoved() { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(num_listeners_ > 0); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_GT(num_listeners_, 0); if (--num_listeners_ == 0) { VLOG(2) << "Listeners removed; stopping periodic discovery."; StopPeriodicDiscovery(); @@ -96,11 +100,11 @@ bool DialRegistry::ReadyToDiscover() { } bool DialRegistry::DiscoverNow() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!ReadyToDiscover()) { return false; } - if (!dial_.get()) { + if (!dial_) { dial_api_->OnDialError(DIAL_UNKNOWN); return false; } @@ -118,11 +122,11 @@ bool DialRegistry::DiscoverNow() { } void DialRegistry::StartPeriodicDiscovery() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!ReadyToDiscover() || dial_.get()) + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!ReadyToDiscover() || dial_) return; - dial_.reset(CreateDialService()); + dial_ = CreateDialService(); dial_->AddObserver(this); DoDiscovery(); repeating_timer_.Start(FROM_HERE, @@ -132,15 +136,15 @@ void DialRegistry::StartPeriodicDiscovery() { } void DialRegistry::DoDiscovery() { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dial_.get()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK(dial_); VLOG(2) << "About to discover!"; dial_->Discover(); } void DialRegistry::StopPeriodicDiscovery() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!dial_.get()) + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!dial_) return; repeating_timer_.Stop(); @@ -149,20 +153,23 @@ void DialRegistry::StopPeriodicDiscovery() { } bool DialRegistry::PruneExpiredDevices() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); bool pruned_device = false; - DeviceByLabelMap::iterator i = device_by_label_map_.begin(); - while (i != device_by_label_map_.end()) { - linked_ptr<DialDeviceData> device = i->second; + DeviceByLabelMap::iterator it = device_by_label_map_.begin(); + while (it != device_by_label_map_.end()) { + auto* device = it->second; if (IsDeviceExpired(*device)) { VLOG(2) << "Device " << device->label() << " expired, removing"; - const size_t num_erased_by_id = - device_by_id_map_.erase(device->device_id()); - DCHECK_EQ(num_erased_by_id, 1u); - device_by_label_map_.erase(i++); + + // Make a copy of the device ID here since |device| will be destroyed + // during erase(). + std::string device_id = device->device_id(); + const size_t num_erased_by_id = device_by_id_map_.erase(device_id); + DCHECK_EQ(1U, num_erased_by_id); + device_by_label_map_.erase(it++); pruned_device = true; } else { - ++i; + ++it; } } return pruned_device; @@ -187,7 +194,7 @@ bool DialRegistry::IsDeviceExpired(const DialDeviceData& device) const { } void DialRegistry::Clear() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); device_by_id_map_.clear(); device_by_label_map_.clear(); registry_generation_++; @@ -204,9 +211,9 @@ void DialRegistry::MaybeSendEvent() { void DialRegistry::SendEvent() { DeviceList device_list; - for (DeviceByLabelMap::const_iterator i = device_by_label_map_.begin(); - i != device_by_label_map_.end(); i++) { - device_list.push_back(*(i->second)); + for (DeviceByLabelMap::const_iterator it = device_by_label_map_.begin(); + it != device_by_label_map_.end(); ++it) { + device_list.push_back(*(it->second)); } dial_api_->OnDialDeviceEvent(device_list); @@ -215,23 +222,23 @@ void DialRegistry::SendEvent() { } std::string DialRegistry::NextLabel() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); return base::IntToString(++label_count_); } void DialRegistry::OnDiscoveryRequest(DialService* service) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); MaybeSendEvent(); } void DialRegistry::OnDeviceDiscovered(DialService* service, const DialDeviceData& device) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); // Adds |device| to our list of devices or updates an existing device, unless // |device| is a duplicate. Returns true if the list was modified and // increments the list generation. - linked_ptr<DialDeviceData> device_data(new DialDeviceData(device)); + auto device_data = base::MakeUnique<DialDeviceData>(device); DCHECK(!device_data->device_id().empty()); DCHECK(device_data->label().empty()); @@ -246,7 +253,7 @@ void DialRegistry::OnDeviceDiscovered(DialService* service, // track if there were any API visible changes. did_modify_list = lookup_result->second->UpdateFrom(*device_data); } else { - did_modify_list = MaybeAddDevice(device_data); + did_modify_list = MaybeAddDevice(std::move(device_data)); } if (did_modify_list) @@ -256,23 +263,23 @@ void DialRegistry::OnDeviceDiscovered(DialService* service, << ", generation = " << registry_generation_; } -bool DialRegistry::MaybeAddDevice( - const linked_ptr<DialDeviceData>& device_data) { - DCHECK(thread_checker_.CalledOnValidThread()); +bool DialRegistry::MaybeAddDevice(std::unique_ptr<DialDeviceData> device_data) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (device_by_id_map_.size() == max_devices_) { VLOG(1) << "Maximum registry size reached. Cannot add device."; return false; } device_data->set_label(NextLabel()); - device_by_id_map_[device_data->device_id()] = device_data; - device_by_label_map_[device_data->label()] = device_data; - VLOG(2) << "Added device, id = " << device_data->device_id() - << ", label = " << device_data->label(); + DialDeviceData* device_data_ptr = device_data.get(); + device_by_id_map_[device_data_ptr->device_id()] = std::move(device_data); + device_by_label_map_[device_data_ptr->label()] = device_data_ptr; + VLOG(2) << "Added device, id = " << device_data_ptr->device_id() + << ", label = " << device_data_ptr->label(); return true; } void DialRegistry::OnDiscoveryFinished(DialService* service) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (PruneExpiredDevices()) registry_generation_++; MaybeSendEvent(); @@ -280,7 +287,7 @@ void DialRegistry::OnDiscoveryFinished(DialService* service) { void DialRegistry::OnError(DialService* service, const DialService::DialServiceErrorCode& code) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); switch (code) { case DialService::DIAL_SERVICE_SOCKET_ERROR: dial_api_->OnDialError(DIAL_SOCKET_ERROR); @@ -299,7 +306,7 @@ void DialRegistry::OnNetworkChanged( NetworkChangeNotifier::ConnectionType type) { switch (type) { case NetworkChangeNotifier::CONNECTION_NONE: - if (dial_.get()) { + if (dial_) { VLOG(2) << "Lost connection, shutting down discovery and clearing" << " list."; dial_api_->OnDialError(DIAL_NETWORK_DISCONNECTED); @@ -319,7 +326,7 @@ void DialRegistry::OnNetworkChanged( case NetworkChangeNotifier::CONNECTION_WIFI: case NetworkChangeNotifier::CONNECTION_UNKNOWN: case NetworkChangeNotifier::CONNECTION_BLUETOOTH: - if (!dial_.get()) { + if (!dial_) { VLOG(2) << "Connection detected, restarting discovery."; StartPeriodicDiscovery(); } diff --git a/chromium/chrome/browser/extensions/api/dial/dial_registry.h b/chromium/chrome/browser/extensions/api/dial/dial_registry.h index 2ddca1ad58d..784aa78aaad 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_registry.h +++ b/chromium/chrome/browser/extensions/api/dial/dial_registry.h @@ -8,15 +8,14 @@ #include <stddef.h> #include <map> +#include <memory> #include <string> #include <vector> #include "base/containers/hash_tables.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ref_counted.h" -#include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "chrome/browser/extensions/api/dial/dial_service.h" @@ -28,10 +27,11 @@ namespace extensions { // Keeps track of devices that have responded to discovery requests and notifies // the observer with an updated, complete set of active devices. The registry's // observer (i.e., the Dial API) owns the registry instance. +// DialRegistry lives on the IO thread. class DialRegistry : public DialService::Observer, public net::NetworkChangeNotifier::NetworkChangeObserver { public: - typedef std::vector<DialDeviceData> DeviceList; + using DeviceList = std::vector<DialDeviceData>; enum DialErrorCode { DIAL_NO_LISTENERS = 0, @@ -74,20 +74,19 @@ class DialRegistry : public DialService::Observer, protected: // Returns a new instance of the DIAL service. Overridden by tests. - virtual DialService* CreateDialService(); + virtual std::unique_ptr<DialService> CreateDialService(); virtual void ClearDialService(); // Returns the current time. Overridden by tests. virtual base::Time Now() const; - protected: // The DIAL service. Periodic discovery is active when this is not NULL. std::unique_ptr<DialService> dial_; private: - typedef base::hash_map<std::string, linked_ptr<DialDeviceData> > - DeviceByIdMap; - typedef std::map<std::string, linked_ptr<DialDeviceData> > DeviceByLabelMap; + using DeviceByIdMap = + base::hash_map<std::string, std::unique_ptr<DialDeviceData>>; + using DeviceByLabelMap = std::map<std::string, DialDeviceData*>; // DialService::Observer: void OnDiscoveryRequest(DialService* service) override; @@ -119,7 +118,7 @@ class DialRegistry : public DialService::Observer, // Attempts to add a newly discovered device to the registry. Returns true if // successful. - bool MaybeAddDevice(const linked_ptr<DialDeviceData>& device_data); + bool MaybeAddDevice(std::unique_ptr<DialDeviceData> device_data); // Remove devices from the registry that have expired, i.e. not responded // after some time. Returns true if the registry was modified. @@ -152,9 +151,9 @@ class DialRegistry : public DialService::Observer, int label_count_; // Registry parameters - base::TimeDelta refresh_interval_delta_; - base::TimeDelta expiration_delta_; - size_t max_devices_; + const base::TimeDelta refresh_interval_delta_; + const base::TimeDelta expiration_delta_; + const size_t max_devices_; // A map used to track known devices by their device_id. DeviceByIdMap device_by_id_map_; @@ -170,9 +169,6 @@ class DialRegistry : public DialService::Observer, // DIAL API owns this DIAL registry. Observer* const dial_api_; - // Thread checker. - base::ThreadChecker thread_checker_; - FRIEND_TEST_ALL_PREFIXES(DialRegistryTest, TestAddRemoveListeners); FRIEND_TEST_ALL_PREFIXES(DialRegistryTest, TestNoDevicesDiscovered); FRIEND_TEST_ALL_PREFIXES(DialRegistryTest, TestDevicesDiscovered); diff --git a/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc b/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc index a9c1753d890..8a28d0996d0 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc @@ -4,12 +4,12 @@ #include <stddef.h> -#include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/extensions/api/dial/dial_device_data.h" #include "chrome/browser/extensions/api/dial/dial_registry.h" #include "chrome/browser/extensions/api/dial/dial_service.h" #include "chrome/test/base/testing_profile.h" +#include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -25,6 +25,8 @@ namespace extensions { class MockDialObserver : public DialRegistry::Observer { public: + ~MockDialObserver() override {} + MOCK_METHOD1(OnDialDeviceEvent, void(const DialRegistry::DeviceList& devices)); MOCK_METHOD1(OnDialError, void(DialRegistry::DialErrorCode type)); @@ -32,7 +34,7 @@ class MockDialObserver : public DialRegistry::Observer { class MockDialService : public DialService { public: - virtual ~MockDialService() {} + ~MockDialService() override {} MOCK_METHOD0(Discover, bool()); MOCK_METHOD1(AddObserver, void(DialService::Observer*)); @@ -42,18 +44,17 @@ class MockDialService : public DialService { class MockDialRegistry : public DialRegistry { public: - MockDialRegistry(Observer *dial_api, + MockDialRegistry(Observer* dial_api, const base::TimeDelta& refresh_interval, const base::TimeDelta& expiration, const size_t max_devices) - : DialRegistry(dial_api, refresh_interval, expiration, max_devices) { - time_ = Time::Now(); - } + : DialRegistry(dial_api, refresh_interval, expiration, max_devices), + time_(Time::Now()) {} ~MockDialRegistry() override { // Don't let the DialRegistry delete this. DialService* tmp = dial_.release(); - if (tmp != NULL) + if (tmp) CHECK_EQ(&mock_service_, tmp); } @@ -62,13 +63,14 @@ class MockDialRegistry : public DialRegistry { return mock_service_; } - // Set to mock out the current time. - Time time_; + void set_time(Time time) { time_ = time; } protected: base::Time Now() const override { return time_; } - DialService* CreateDialService() override { return &mock_service_; } + std::unique_ptr<DialService> CreateDialService() override { + return base::WrapUnique(&mock_service_); + } void ClearDialService() override { // Release the pointer but don't delete the object because the test owns it. @@ -77,23 +79,34 @@ class MockDialRegistry : public DialRegistry { private: MockDialService mock_service_; + + // Set to mock out the current time. + Time time_; }; class DialRegistryTest : public testing::Test { public: DialRegistryTest() - : first_device_("first", GURL("http://127.0.0.1/dd.xml"), Time::Now()), + : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + first_device_("first", GURL("http://127.0.0.1/dd.xml"), Time::Now()), second_device_("second", GURL("http://127.0.0.2/dd.xml"), Time::Now()), third_device_("third", GURL("http://127.0.0.3/dd.xml"), Time::Now()) { - registry_.reset(new MockDialRegistry(&mock_observer_, - TimeDelta::FromSeconds(1000), - TimeDelta::FromSeconds(10), - 10)); + registry_ = base::MakeUnique<MockDialRegistry>( + &mock_observer_, TimeDelta::FromSeconds(1000), + TimeDelta::FromSeconds(10), 10); list_with_first_device_.push_back(first_device_); list_with_second_device_.push_back(second_device_); } protected: + void SetListenerExpectations() { + EXPECT_CALL(registry_->mock_service(), + AddObserver(A<DialService::Observer*>())); + EXPECT_CALL(registry_->mock_service(), + RemoveObserver(A<DialService::Observer*>())); + } + + content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<MockDialRegistry> registry_; MockDialObserver mock_observer_; const DialDeviceData first_device_; @@ -103,17 +116,6 @@ class DialRegistryTest : public testing::Test { const DialRegistry::DeviceList empty_list_; DialRegistry::DeviceList list_with_first_device_; DialRegistry::DeviceList list_with_second_device_; - - // Must instantiate a MessageLoop for the thread, as the registry starts a - // RepeatingTimer when there are listeners. - base::MessageLoop message_loop_; - - void SetListenerExpectations() { - EXPECT_CALL(registry_->mock_service(), - AddObserver(A<DialService::Observer*>())); - EXPECT_CALL(registry_->mock_service(), - RemoveObserver(A<DialService::Observer*>())); - } }; TEST_F(DialRegistryTest, TestAddRemoveListeners) { @@ -138,8 +140,8 @@ TEST_F(DialRegistryTest, TestNoDevicesDiscovered) { EXPECT_CALL(registry_->mock_service(), Discover()); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } @@ -157,14 +159,14 @@ TEST_F(DialRegistryTest, TestDevicesDiscovered) { EXPECT_CALL(mock_observer_, OnDialDeviceEvent(expected_list2)); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->DoDiscovery(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, second_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, second_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } @@ -183,16 +185,16 @@ TEST_F(DialRegistryTest, TestDevicesDiscoveredWithTwoListeners) { EXPECT_CALL(mock_observer_, OnDialDeviceEvent(expected_list2)); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerAdded(); registry_->DoDiscovery(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, second_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, second_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); registry_->OnListenerRemoved(); } @@ -207,15 +209,15 @@ TEST_F(DialRegistryTest, TestDeviceExpires) { EXPECT_CALL(mock_observer_, OnDialDeviceEvent(empty_list_)); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDiscoveryFinished(nullptr); - registry_->time_ = Time::Now() + TimeDelta::FromSeconds(30); + registry_->set_time(Time::Now() + TimeDelta::FromSeconds(30)); registry_->DoDiscovery(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } @@ -240,25 +242,25 @@ TEST_F(DialRegistryTest, TestExpiredDeviceIsRediscovered) { EXPECT_CALL(registry_->mock_service(), Discover()); EXPECT_CALL(mock_observer_, OnDialDeviceEvent(list_with_first_device_)); - registry_->time_ = discovery_times[0]; + registry_->set_time(discovery_times[0]); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDiscoveryFinished(nullptr); // Will expire "first" device as it is not discovered this time. - registry_->time_ = discovery_times[1]; + registry_->set_time(discovery_times[1]); registry_->DoDiscovery(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDiscoveryFinished(nullptr); // "first" device is rediscovered 30 seconds later. We pass a device object // with a newer discovery time so it is not pruned immediately. - registry_->time_ = discovery_times[2]; + registry_->set_time(discovery_times[2]); registry_->DoDiscovery(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, rediscovered_device); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, rediscovered_device); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } @@ -278,10 +280,10 @@ TEST_F(DialRegistryTest, TestRemovingListenerDoesNotClearList) { RemoveObserver(A<DialService::Observer*>())); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDeviceDiscovered(NULL, second_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDeviceDiscovered(nullptr, second_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); // Removing and adding a listener again fires an event with the current device @@ -294,8 +296,8 @@ TEST_F(DialRegistryTest, TestRemovingListenerDoesNotClearList) { RemoveObserver(A<DialService::Observer*>())); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } @@ -311,14 +313,14 @@ TEST_F(DialRegistryTest, TestNetworkEventConnectionLost) { EXPECT_CALL(mock_observer_, OnDialDeviceEvent(empty_list_)); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnNetworkChanged(net::NetworkChangeNotifier::CONNECTION_NONE); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } @@ -350,26 +352,26 @@ TEST_F(DialRegistryTest, TestNetworkEventConnectionRestored) { EXPECT_CALL(mock_observer_, OnDialDeviceEvent(expected_list3)); registry_->OnListenerAdded(); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, first_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, first_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnNetworkChanged(net::NetworkChangeNotifier::CONNECTION_NONE); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDiscoveryFinished(nullptr); registry_->OnNetworkChanged(net::NetworkChangeNotifier::CONNECTION_WIFI); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, second_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, second_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnNetworkChanged(net::NetworkChangeNotifier::CONNECTION_ETHERNET); - registry_->OnDiscoveryRequest(NULL); - registry_->OnDeviceDiscovered(NULL, third_device_); - registry_->OnDiscoveryFinished(NULL); + registry_->OnDiscoveryRequest(nullptr); + registry_->OnDeviceDiscovered(nullptr, third_device_); + registry_->OnDiscoveryFinished(nullptr); registry_->OnListenerRemoved(); } diff --git a/chromium/chrome/browser/extensions/api/dial/dial_service.cc b/chromium/chrome/browser/extensions/api/dial/dial_service.cc index 9b7043ff80b..06c7398d3cd 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_service.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_service.cc @@ -13,6 +13,7 @@ #include "base/callback.h" #include "base/location.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/rand_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" @@ -31,7 +32,10 @@ #include "net/base/network_interfaces.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" +#include "net/log/net_log.h" +#include "net/log/net_log_source_type.h" #include "url/gurl.h" + #if defined(OS_CHROMEOS) #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" @@ -87,7 +91,7 @@ const int kDialRecvBufferSize = 1500; // Gets a specific header from |headers| and puts it in |value|. bool GetHeader(HttpResponseHeaders* headers, const char* name, std::string* value) { - return headers->EnumerateHeader(NULL, std::string(name), value); + return headers->EnumerateHeader(nullptr, std::string(name), value); } // Returns the request string. @@ -109,25 +113,11 @@ std::string BuildRequest() { version_info::GetVersionNumber().c_str(), version_info::GetOSType().c_str())); // 1500 is a good MTU value for most Ethernet LANs. - DCHECK(request.size() <= 1500); + DCHECK_LE(request.size(), 1500U); return request; } -#if !defined(OS_CHROMEOS) -void GetNetworkListOnFileThread( - const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, - const base::Callback<void(const NetworkInterfaceList& networks)>& cb) { - NetworkInterfaceList list; - bool success = net::GetNetworkList( - &list, net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES); - if (!success) - VLOG(1) << "Could not retrieve network list!"; - - task_runner->PostTask(FROM_HERE, base::Bind(cb, list)); -} - -#else - +#if defined(OS_CHROMEOS) // Finds the IP address of the preferred interface of network type |type| // to bind the socket and inserts the address into |bind_address_list|. This // ChromeOS version can prioritize wifi and ethernet interfaces. @@ -143,7 +133,16 @@ void InsertBestBindAddressChromeOS(const chromeos::NetworkTypePattern& type, bind_address_list->push_back(bind_ip_address); } } -#endif // !defined(OS_CHROMEOS) +#else +NetworkInterfaceList GetNetworkListOnFileThread() { + NetworkInterfaceList list; + bool success = + net::GetNetworkList(&list, net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES); + if (!success) + VLOG(1) << "Could not retrieve network list!"; + return list; +} +#endif // defined(OS_CHROMEOS) } // namespace @@ -156,25 +155,24 @@ DialServiceImpl::DialSocket::DialSocket( on_error_cb_(on_error_cb), is_writing_(false), is_reading_(false) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); } DialServiceImpl::DialSocket::~DialSocket() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); } bool DialServiceImpl::DialSocket::CreateAndBindSocket( const IPAddress& bind_ip_address, net::NetLog* net_log, - net::NetLog::Source net_log_source) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(!socket_.get()); + net::NetLogSource net_log_source) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK(!socket_); DCHECK(bind_ip_address.IsIPv4()); net::RandIntCallback rand_cb = base::Bind(&base::RandInt); - socket_.reset(new UDPSocket(net::DatagramSocket::RANDOM_BIND, - rand_cb, - net_log, - net_log_source)); + socket_ = base::MakeUnique<UDPSocket>(net::DatagramSocket::RANDOM_BIND, + rand_cb, net_log, net_log_source); // 0 means bind a random port net::IPEndPoint address(bind_ip_address, 0); @@ -186,8 +184,6 @@ bool DialServiceImpl::DialSocket::CreateAndBindSocket( return false; } - DCHECK(socket_.get()); - recv_buffer_ = new IOBufferWithSize(kDialRecvBufferSize); return ReadSocket(); } @@ -195,7 +191,7 @@ bool DialServiceImpl::DialSocket::CreateAndBindSocket( void DialServiceImpl::DialSocket::SendOneRequest( const net::IPEndPoint& send_address, const scoped_refptr<net::StringIOBuffer>& send_buffer) { - if (!socket_.get()) { + if (!socket_) { VLOG(1) << "Socket not connected."; return; } @@ -219,13 +215,13 @@ void DialServiceImpl::DialSocket::SendOneRequest( } bool DialServiceImpl::DialSocket::IsClosed() { - DCHECK(thread_checker_.CalledOnValidThread()); - return !socket_.get(); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + return !socket_; } bool DialServiceImpl::DialSocket::CheckResult(const char* operation, int result) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); VLOG(2) << "Operation " << operation << " result " << result; if (result < net::OK && result != net::ERR_IO_PENDING) { Close(); @@ -238,7 +234,7 @@ bool DialServiceImpl::DialSocket::CheckResult(const char* operation, } void DialServiceImpl::DialSocket::Close() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); is_reading_ = false; is_writing_ = false; socket_.reset(); @@ -246,7 +242,7 @@ void DialServiceImpl::DialSocket::Close() { void DialServiceImpl::DialSocket::OnSocketWrite(int send_buffer_size, int result) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); is_writing_ = false; if (!CheckResult("OnSocketWrite", result)) return; @@ -258,8 +254,8 @@ void DialServiceImpl::DialSocket::OnSocketWrite(int send_buffer_size, } bool DialServiceImpl::DialSocket::ReadSocket() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!socket_.get()) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!socket_) { VLOG(1) << "Socket not connected."; return false; } @@ -290,7 +286,7 @@ bool DialServiceImpl::DialSocket::ReadSocket() { } void DialServiceImpl::DialSocket::OnSocketRead(int result) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); is_reading_ = false; if (!CheckResult("OnSocketRead", result)) return; @@ -302,7 +298,7 @@ void DialServiceImpl::DialSocket::OnSocketRead(int result) { } void DialServiceImpl::DialSocket::HandleResponse(int bytes_read) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_GT(bytes_read, 0); if (bytes_read > kDialRecvBufferSize) { VLOG(1) << bytes_read << " > " << kDialRecvBufferSize << "!?"; @@ -380,45 +376,46 @@ bool DialServiceImpl::DialSocket::ParseResponse( } DialServiceImpl::DialServiceImpl(net::NetLog* net_log) - : discovery_active_(false), + : net_log_(net_log), + discovery_active_(false), num_requests_sent_(0), max_requests_(kDialMaxRequests), finish_delay_(TimeDelta::FromMilliseconds((kDialMaxRequests - 1) * kDialRequestIntervalMillis) + TimeDelta::FromSeconds(kDialResponseTimeoutSecs)), request_interval_( - TimeDelta::FromMilliseconds(kDialRequestIntervalMillis)) { + TimeDelta::FromMilliseconds(kDialRequestIntervalMillis)), + weak_factory_(this) { IPAddress address; bool success = address.AssignFromIPLiteral(kDialRequestAddress); DCHECK(success); send_address_ = net::IPEndPoint(address, kDialRequestPort); send_buffer_ = new StringIOBuffer(BuildRequest()); - net_log_ = net_log; - net_log_source_.type = net::NetLog::SOURCE_UDP_SOCKET; + net_log_source_.type = net::NetLogSourceType::UDP_SOCKET; net_log_source_.id = net_log_->NextID(); } DialServiceImpl::~DialServiceImpl() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); } void DialServiceImpl::AddObserver(Observer* observer) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); observer_list_.AddObserver(observer); } void DialServiceImpl::RemoveObserver(Observer* observer) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); observer_list_.RemoveObserver(observer); } bool DialServiceImpl::HasObserver(const Observer* observer) const { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); return observer_list_.HasObserver(observer); } bool DialServiceImpl::Discover() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (discovery_active_) { VLOG(2) << "Discovery is already active - returning."; return false; @@ -432,7 +429,7 @@ bool DialServiceImpl::Discover() { } void DialServiceImpl::StartDiscovery() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(discovery_active_); if (HasOpenSockets()) { VLOG(2) << "Calling StartDiscovery() with open sockets. Returning."; @@ -451,17 +448,16 @@ void DialServiceImpl::StartDiscovery() { DiscoverOnAddresses(chrome_os_address_list); #else - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&GetNetworkListOnFileThread, - base::ThreadTaskRunnerHandle::Get(), - base::Bind(&DialServiceImpl::SendNetworkList, AsWeakPtr()))); + BrowserThread::PostTaskAndReplyWithResult( + BrowserThread::FILE, FROM_HERE, base::Bind(&GetNetworkListOnFileThread), + base::Bind(&DialServiceImpl::SendNetworkList, + weak_factory_.GetWeakPtr())); #endif } void DialServiceImpl::SendNetworkList(const NetworkInterfaceList& networks) { - DCHECK(thread_checker_.CalledOnValidThread()); - typedef std::pair<uint32_t, net::AddressFamily> InterfaceIndexAddressFamily; + DCHECK_CURRENTLY_ON(BrowserThread::IO); + using InterfaceIndexAddressFamily = std::pair<uint32_t, net::AddressFamily>; std::set<InterfaceIndexAddressFamily> interface_index_addr_family_seen; net::IPAddressList ip_addresses; @@ -533,16 +529,16 @@ void DialServiceImpl::BindAndAddSocket(const IPAddress& bind_ip_address) { std::unique_ptr<DialServiceImpl::DialSocket> DialServiceImpl::CreateDialSocket() { - std::unique_ptr<DialServiceImpl::DialSocket> dial_socket( - new DialServiceImpl::DialSocket( - base::Bind(&DialServiceImpl::NotifyOnDiscoveryRequest, AsWeakPtr()), - base::Bind(&DialServiceImpl::NotifyOnDeviceDiscovered, AsWeakPtr()), - base::Bind(&DialServiceImpl::NotifyOnError, AsWeakPtr()))); - return dial_socket; + return base::MakeUnique<DialServiceImpl::DialSocket>( + base::Bind(&DialServiceImpl::NotifyOnDiscoveryRequest, + weak_factory_.GetWeakPtr()), + base::Bind(&DialServiceImpl::NotifyOnDeviceDiscovered, + weak_factory_.GetWeakPtr()), + base::Bind(&DialServiceImpl::NotifyOnError, weak_factory_.GetWeakPtr())); } void DialServiceImpl::SendOneRequest() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (num_requests_sent_ == max_requests_) { VLOG(2) << "Reached max requests; stopping request timer."; request_timer_.Stop(); @@ -558,7 +554,7 @@ void DialServiceImpl::SendOneRequest() { } void DialServiceImpl::NotifyOnDiscoveryRequest() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); // If discovery is inactive, no reason to notify observers. if (!discovery_active_) { VLOG(2) << "Request sent after discovery finished. Ignoring."; @@ -581,7 +577,7 @@ void DialServiceImpl::NotifyOnDiscoveryRequest() { void DialServiceImpl::NotifyOnDeviceDiscovered( const DialDeviceData& device_data) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!discovery_active_) { VLOG(2) << "Got response after discovery finished. Ignoring."; return; @@ -591,7 +587,7 @@ void DialServiceImpl::NotifyOnDeviceDiscovered( } void DialServiceImpl::NotifyOnError() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); // TODO(imcheng): Modify upstream so that the device list is not cleared // when it could still potentially discover devices on other sockets. FOR_EACH_OBSERVER(Observer, observer_list_, @@ -601,7 +597,7 @@ void DialServiceImpl::NotifyOnError() { } void DialServiceImpl::FinishDiscovery() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(discovery_active_); VLOG(2) << "Discovery finished."; // Close all open sockets. diff --git a/chromium/chrome/browser/extensions/api/dial/dial_service.h b/chromium/chrome/browser/extensions/api/dial/dial_service.h index a9878904525..fa9809e8f6e 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_service.h +++ b/chromium/chrome/browser/extensions/api/dial/dial_service.h @@ -13,16 +13,16 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" -#include "base/threading/thread_checker.h" #include "base/timer/timer.h" #include "net/base/ip_address.h" -#include "net/log/net_log.h" +#include "net/log/net_log_source.h" #include "net/udp/udp_socket.h" namespace net { -class IPEndPoint; class IOBuffer; +class IPEndPoint; class StringIOBuffer; +class NetLog; struct NetworkInterface; } @@ -96,8 +96,8 @@ class DialService { // associated with a single discovery cycle into its own |DiscoveryOperation| // object. This would also simplify lifetime of the object w.r.t. DialRegistry; // the Registry would not need to create/destroy the Service on demand. -class DialServiceImpl : public DialService, - public base::SupportsWeakPtr<DialServiceImpl> { +// DialServiceImpl lives on the IO thread. +class DialServiceImpl : public DialService { public: explicit DialServiceImpl(net::NetLog* net_log); ~DialServiceImpl() override; @@ -110,6 +110,7 @@ class DialServiceImpl : public DialService, private: // Represents a socket binding to a single network interface. + // DialSocket lives on the IO thread. class DialSocket { public: // TODO(imcheng): Consider writing a DialSocket::Delegate interface that @@ -125,7 +126,7 @@ class DialServiceImpl : public DialService, // |bind_ip_address|. bool CreateAndBindSocket(const net::IPAddress& bind_ip_address, net::NetLog* net_log, - net::NetLog::Source net_log_source); + net::NetLogSource net_log_source); // Sends a single discovery request |send_buffer| to |send_address| // over the socket. @@ -175,9 +176,6 @@ class DialServiceImpl : public DialService, // The source of of the last socket read. net::IPEndPoint recv_address_; - // Thread checker. - base::ThreadChecker thread_checker_; - // The callback to be invoked when a discovery request was made. base::Closure discovery_request_cb_; @@ -244,10 +242,10 @@ class DialServiceImpl : public DialService, std::vector<std::unique_ptr<DialSocket>> dial_sockets_; // The NetLog for this service. - net::NetLog* net_log_; + net::NetLog* const net_log_; // The NetLog source for this service. - net::NetLog::Source net_log_source_; + net::NetLogSource net_log_source_; // The multicast address:port for search requests. net::IPEndPoint send_address_; @@ -281,8 +279,7 @@ class DialServiceImpl : public DialService, // List of observers. base::ObserverList<Observer> observer_list_; - // Thread checker. - base::ThreadChecker thread_checker_; + base::WeakPtrFactory<DialServiceImpl> weak_factory_; friend class DialServiceTest; FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestSendMultipleRequests); diff --git a/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc b/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc index 75a48fdae37..090ae6e98b2 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc @@ -10,8 +10,9 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" #include "chrome/browser/extensions/api/dial/dial_device_data.h" +#include "content/public/test/test_browser_thread_bundle.h" #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/base/network_interfaces.h" @@ -40,6 +41,8 @@ namespace extensions { class MockObserver : public DialService::Observer { public: + ~MockObserver() override {} + MOCK_METHOD1(OnDiscoveryRequest, void(DialService*)); MOCK_METHOD2(OnDeviceDiscovered, void(DialService*, const DialDeviceData&)); MOCK_METHOD1(OnDiscoveryFinished, void(DialService*)); @@ -50,12 +53,14 @@ class MockObserver : public DialService::Observer { class DialServiceTest : public testing::Test { public: DialServiceTest() - : mock_ip_(net::IPAddress::IPv4AllZeros()), + : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + mock_ip_(net::IPAddress::IPv4AllZeros()), dial_service_(&test_net_log_) { dial_service_.AddObserver(&mock_observer_); dial_socket_ = dial_service_.CreateDialSocket(); } protected: + content::TestBrowserThreadBundle thread_bundle_; net::TestNetLog test_net_log_; net::IPAddress mock_ip_; DialServiceImpl dial_service_; @@ -64,7 +69,6 @@ class DialServiceTest : public testing::Test { }; TEST_F(DialServiceTest, TestSendMultipleRequests) { - base::MessageLoopForIO loop; // Setting the finish delay to zero disables the timer that invokes // FinishDiscovery(). dial_service_.finish_delay_ = TimeDelta::FromSeconds(0); @@ -76,12 +80,11 @@ TEST_F(DialServiceTest, TestSendMultipleRequests) { dial_service_.BindAndAddSocket(mock_ip_); EXPECT_EQ(1u, dial_service_.dial_sockets_.size()); dial_service_.SendOneRequest(); - loop.RunUntilIdle(); + base::RunLoop().RunUntilIdle(); dial_service_.FinishDiscovery(); } TEST_F(DialServiceTest, TestMultipleNetworkInterfaces) { - base::MessageLoopForIO loop; // Setting the finish delay to zero disables the timer that invokes // FinishDiscovery(). dial_service_.finish_delay_ = TimeDelta::FromSeconds(0); @@ -132,7 +135,7 @@ TEST_F(DialServiceTest, TestMultipleNetworkInterfaces) { dial_service_.SendNetworkList(interface_list); EXPECT_EQ(3u, dial_service_.dial_sockets_.size()); - loop.RunUntilIdle(); + base::RunLoop().RunUntilIdle(); dial_service_.FinishDiscovery(); } @@ -162,7 +165,7 @@ TEST_F(DialServiceTest, TestOnDeviceDiscovered) { OnDeviceDiscovered(A<DialService*>(), expected_device)) .Times(1); dial_socket_->OnSocketRead(response_size); -}; +} TEST_F(DialServiceTest, TestOnDiscoveryFinished) { dial_service_.discovery_active_ = true; diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc index c256e11d5bb..5e4ebbbd2e9 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc @@ -23,7 +23,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string16.h" @@ -44,6 +44,7 @@ #include "chrome/browser/download/download_shelf.h" #include "chrome/browser/download/download_stats.h" #include "chrome/browser/download/drag_download_item.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/icon_loader.h" #include "chrome/browser/icon_manager.h" #include "chrome/browser/platform_util.h" @@ -173,6 +174,8 @@ const char kTotalBytesKey[] = "totalBytes"; const char kTotalBytesLessKey[] = "totalBytesLess"; const char kUrlKey[] = "url"; const char kUrlRegexKey[] = "urlRegex"; +const char kFinalUrlKey[] = "finalUrl"; +const char kFinalUrlRegexKey[] = "finalUrlRegex"; // Note: Any change to the danger type strings, should be accompanied by a // corresponding change to downloads.json. @@ -248,12 +251,15 @@ std::string TimeToISO8601(const base::Time& t) { std::unique_ptr<base::DictionaryValue> DownloadItemToJSON( DownloadItem* download_item, - Profile* profile) { + content::BrowserContext* browser_context) { base::DictionaryValue* json = new base::DictionaryValue(); json->SetBoolean(kExistsKey, !download_item->GetFileExternallyRemoved()); json->SetInteger(kIdKey, download_item->GetId()); const GURL& url = download_item->GetOriginalUrl(); json->SetString(kUrlKey, (url.is_valid() ? url.spec() : std::string())); + const GURL& finalUrl = download_item->GetURL(); + json->SetString(kFinalUrlKey, + (finalUrl.is_valid() ? finalUrl.spec() : std::string())); const GURL& referrer = download_item->GetReferrerUrl(); json->SetString(kReferrerUrlKey, (referrer.is_valid() ? referrer.spec() : std::string())); @@ -267,7 +273,7 @@ std::unique_ptr<base::DictionaryValue> DownloadItemToJSON( json->SetString(kStartTimeKey, TimeToISO8601(download_item->GetStartTime())); json->SetDouble(kBytesReceivedKey, download_item->GetReceivedBytes()); json->SetDouble(kTotalBytesKey, download_item->GetTotalBytes()); - json->SetBoolean(kIncognitoKey, profile->IsOffTheRecord()); + json->SetBoolean(kIncognitoKey, browser_context->IsOffTheRecord()); if (download_item->GetState() == DownloadItem::INTERRUPTED) { json->SetString(kErrorKey, content::DownloadInterruptReasonToString( @@ -292,7 +298,7 @@ std::unique_ptr<base::DictionaryValue> DownloadItemToJSON( // language. This won't work if the extension was uninstalled, so the name // might be the wrong language. const Extension* extension = - ExtensionRegistry::Get(profile) + ExtensionRegistry::Get(browser_context) ->GetExtensionById(by_ext->id(), ExtensionRegistry::EVERYTHING); if (extension) json->SetString(kByExtensionNameKey, extension->name()); @@ -375,8 +381,10 @@ void InitFilterTypeMap(FilterTypeMap* filter_types_ptr) { filter_types[kTotalBytesGreaterKey] = DownloadQuery::FILTER_TOTAL_BYTES_GREATER; filter_types[kTotalBytesLessKey] = DownloadQuery::FILTER_TOTAL_BYTES_LESS; - filter_types[kUrlKey] = DownloadQuery::FILTER_URL; - filter_types[kUrlRegexKey] = DownloadQuery::FILTER_URL_REGEX; + filter_types[kUrlKey] = DownloadQuery::FILTER_ORIGINAL_URL; + filter_types[kUrlRegexKey] = DownloadQuery::FILTER_ORIGINAL_URL_REGEX; + filter_types[kFinalUrlKey] = DownloadQuery::FILTER_URL; + filter_types[kFinalUrlRegexKey] = DownloadQuery::FILTER_URL_REGEX; } typedef base::hash_map<std::string, DownloadQuery::SortType> SortTypeMap; @@ -393,7 +401,8 @@ void InitSortTypeMap(SortTypeMap* sorter_types_ptr) { sorter_types[kStartTimeKey] = DownloadQuery::SORT_START_TIME; sorter_types[kStateKey] = DownloadQuery::SORT_STATE; sorter_types[kTotalBytesKey] = DownloadQuery::SORT_TOTAL_BYTES; - sorter_types[kUrlKey] = DownloadQuery::SORT_URL; + sorter_types[kUrlKey] = DownloadQuery::SORT_ORIGINAL_URL; + sorter_types[kFinalUrlKey] = DownloadQuery::SORT_URL; } bool IsNotTemporaryDownloadFilter(const DownloadItem& download_item) { @@ -404,11 +413,11 @@ bool IsNotTemporaryDownloadFilter(const DownloadItem& download_item) { // the off-record DownloadManager if one exists and is requested via // |include_incognito|. This should work regardless of whether |profile| is // original or incognito. -void GetManagers( - Profile* profile, - bool include_incognito, - DownloadManager** manager, - DownloadManager** incognito_manager) { +void GetManagers(content::BrowserContext* context, + bool include_incognito, + DownloadManager** manager, + DownloadManager** incognito_manager) { + Profile* profile = Profile::FromBrowserContext(context); *manager = BrowserContext::GetDownloadManager(profile->GetOriginalProfile()); if (profile->HasOffTheRecordProfile() && (include_incognito || @@ -420,10 +429,12 @@ void GetManagers( } } -DownloadItem* GetDownload(Profile* profile, bool include_incognito, int id) { +DownloadItem* GetDownload(content::BrowserContext* context, + bool include_incognito, + int id) { DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; - GetManagers(profile, include_incognito, &manager, &incognito_manager); + GetManagers(context, include_incognito, &manager, &incognito_manager); DownloadItem* download_item = manager->GetDownload(id); if (!download_item && incognito_manager) download_item = incognito_manager->GetDownload(id); @@ -505,11 +516,11 @@ void RunDownloadQuery( size_t limit = 1000; if (query_in.limit.get()) { - if (*query_in.limit.get() < 0) { + if (*query_in.limit < 0) { *error = errors::kInvalidQueryLimit; return; } - limit = *query_in.limit.get(); + limit = *query_in.limit; } if (limit > 0) { query_out.Limit(limit); @@ -536,13 +547,13 @@ void RunDownloadQuery( query_out.AddFilter(danger_type); } if (query_in.order_by.get()) { - CompileDownloadQueryOrderBy(*query_in.order_by.get(), error, &query_out); + CompileDownloadQueryOrderBy(*query_in.order_by, error, &query_out); if (!error->empty()) return; } std::unique_ptr<base::DictionaryValue> query_in_value(query_in.ToValue()); - for (base::DictionaryValue::Iterator query_json_field(*query_in_value.get()); + for (base::DictionaryValue::Iterator query_json_field(*query_in_value); !query_json_field.IsAtEnd(); query_json_field.Advance()) { FilterTypeMap::const_iterator filter_type = filter_types.Get().find(query_json_field.key()); @@ -556,9 +567,9 @@ void RunDownloadQuery( DownloadQuery::DownloadVector all_items; if (query_in.id.get()) { - DownloadItem* download_item = manager->GetDownload(*query_in.id.get()); + DownloadItem* download_item = manager->GetDownload(*query_in.id); if (!download_item && incognito_manager) - download_item = incognito_manager->GetDownload(*query_in.id.get()); + download_item = incognito_manager->GetDownload(*query_in.id); if (download_item) all_items.push_back(download_item); } else { @@ -617,7 +628,7 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { } } - const base::DictionaryValue& json() const { return *json_.get(); } + const base::DictionaryValue& json() const { return *json_; } void set_json(std::unique_ptr<base::DictionaryValue> json_item) { json_ = std::move(json_item); } @@ -906,6 +917,7 @@ bool InvalidId(DownloadItem* valid_item, std::string* message_out) { bool IsDownloadDeltaField(const std::string& field) { return ((field == kUrlKey) || + (field == kFinalUrlKey) || (field == kFilenameKey) || (field == kDangerKey) || (field == kMimeKey) || @@ -981,7 +993,7 @@ bool DownloadsDownloadFunction::RunAsync() { kFilenameKey, &filename16)); creator_suggested_filename = base::FilePath(filename16); #elif defined(OS_POSIX) - creator_suggested_filename = base::FilePath(*options.filename.get()); + creator_suggested_filename = base::FilePath(*options.filename); #endif if (!net::IsSafePortableRelativePath(creator_suggested_filename)) { error_ = errors::kInvalidFilename; @@ -990,7 +1002,7 @@ bool DownloadsDownloadFunction::RunAsync() { } if (options.save_as.get()) - download_params->set_prompt(*options.save_as.get()); + download_params->set_prompt(*options.save_as); if (options.headers.get()) { for (const downloads::HeaderNameValuePair& name_value : *options.headers) { @@ -1015,7 +1027,7 @@ bool DownloadsDownloadFunction::RunAsync() { if (!method_string.empty()) download_params->set_method(method_string); if (options.body.get()) - download_params->set_post_body(*options.body.get()); + download_params->set_post_body(*options.body); download_params->set_callback(base::Bind( &DownloadsDownloadFunction::OnStarted, this, creator_suggested_filename, options.conflict_action)); @@ -1036,7 +1048,7 @@ void DownloadsDownloadFunction::OnStarted( DownloadItem* item, content::DownloadInterruptReason interrupt_reason) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - VLOG(1) << __FUNCTION__ << " " << item << " " << interrupt_reason; + VLOG(1) << __func__ << " " << item << " " << interrupt_reason; if (item) { DCHECK_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason); SetResult(base::MakeUnique<base::FundamentalValue>( @@ -1067,13 +1079,14 @@ DownloadsSearchFunction::DownloadsSearchFunction() {} DownloadsSearchFunction::~DownloadsSearchFunction() {} -bool DownloadsSearchFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsSearchFunction::Run() { std::unique_ptr<downloads::Search::Params> params( downloads::Search::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; - GetManagers(GetProfile(), include_incognito(), &manager, &incognito_manager); + GetManagers(browser_context(), include_incognito(), &manager, + &incognito_manager); ExtensionDownloadsEventRouter* router = DownloadServiceFactory::GetForBrowserContext( manager->GetBrowserContext())->GetExtensionEventRouter(); @@ -1085,13 +1098,10 @@ bool DownloadsSearchFunction::RunSync() { incognito_router->CheckForHistoryFilesRemoval(); } DownloadQuery::DownloadVector results; - RunDownloadQuery(params->query, - manager, - incognito_manager, - &error_, - &results); - if (!error_.empty()) - return false; + std::string error; + RunDownloadQuery(params->query, manager, incognito_manager, &error, &results); + if (!error.empty()) + return RespondNow(Error(error)); std::unique_ptr<base::ListValue> json_results(new base::ListValue()); for (DownloadManager::DownloadVector::const_iterator it = results.begin(); @@ -1100,105 +1110,106 @@ bool DownloadsSearchFunction::RunSync() { uint32_t download_id = download_item->GetId(); bool off_record = ((incognito_manager != NULL) && (incognito_manager->GetDownload(download_id) != NULL)); - std::unique_ptr<base::DictionaryValue> json_item(DownloadItemToJSON( - *it, off_record ? GetProfile()->GetOffTheRecordProfile() - : GetProfile()->GetOriginalProfile())); + Profile* profile = Profile::FromBrowserContext(browser_context()); + std::unique_ptr<base::DictionaryValue> json_item( + DownloadItemToJSON(*it, off_record ? profile->GetOffTheRecordProfile() + : profile->GetOriginalProfile())); json_results->Append(std::move(json_item)); } - SetResult(std::move(json_results)); RecordApiFunctions(DOWNLOADS_FUNCTION_SEARCH); - return true; + return RespondNow(OneArgument(std::move(json_results))); } DownloadsPauseFunction::DownloadsPauseFunction() {} DownloadsPauseFunction::~DownloadsPauseFunction() {} -bool DownloadsPauseFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsPauseFunction::Run() { std::unique_ptr<downloads::Pause::Params> params( downloads::Pause::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); - if (InvalidId(download_item, &error_) || + GetDownload(browser_context(), include_incognito(), params->download_id); + std::string error; + if (InvalidId(download_item, &error) || Fault(download_item->GetState() != DownloadItem::IN_PROGRESS, - errors::kNotInProgress, &error_)) - return false; + errors::kNotInProgress, &error)) { + return RespondNow(Error(error)); + } // If the item is already paused, this is a no-op and the operation will // silently succeed. download_item->Pause(); RecordApiFunctions(DOWNLOADS_FUNCTION_PAUSE); - return true; + return RespondNow(NoArguments()); } DownloadsResumeFunction::DownloadsResumeFunction() {} DownloadsResumeFunction::~DownloadsResumeFunction() {} -bool DownloadsResumeFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsResumeFunction::Run() { std::unique_ptr<downloads::Resume::Params> params( downloads::Resume::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); - if (InvalidId(download_item, &error_) || + GetDownload(browser_context(), include_incognito(), params->download_id); + std::string error; + if (InvalidId(download_item, &error) || Fault(download_item->IsPaused() && !download_item->CanResume(), - errors::kNotResumable, &error_)) - return false; + errors::kNotResumable, &error)) { + return RespondNow(Error(error)); + } // Note that if the item isn't paused, this will be a no-op, and the extension // call will seem successful. download_item->Resume(); RecordApiFunctions(DOWNLOADS_FUNCTION_RESUME); - return true; + return RespondNow(NoArguments()); } DownloadsCancelFunction::DownloadsCancelFunction() {} DownloadsCancelFunction::~DownloadsCancelFunction() {} -bool DownloadsCancelFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsCancelFunction::Run() { std::unique_ptr<downloads::Resume::Params> params( downloads::Resume::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); + GetDownload(browser_context(), include_incognito(), params->download_id); if (download_item && (download_item->GetState() == DownloadItem::IN_PROGRESS)) download_item->Cancel(true); // |download_item| can be NULL if the download ID was invalid or if the // download is not currently active. Either way, it's not a failure. RecordApiFunctions(DOWNLOADS_FUNCTION_CANCEL); - return true; + return RespondNow(NoArguments()); } DownloadsEraseFunction::DownloadsEraseFunction() {} DownloadsEraseFunction::~DownloadsEraseFunction() {} -bool DownloadsEraseFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsEraseFunction::Run() { std::unique_ptr<downloads::Erase::Params> params( downloads::Erase::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; - GetManagers(GetProfile(), include_incognito(), &manager, &incognito_manager); + GetManagers(browser_context(), include_incognito(), &manager, + &incognito_manager); DownloadQuery::DownloadVector results; - RunDownloadQuery(params->query, - manager, - incognito_manager, - &error_, - &results); - if (!error_.empty()) - return false; + std::string error; + RunDownloadQuery(params->query, manager, incognito_manager, &error, &results); + if (!error.empty()) + return RespondNow(Error(error)); std::unique_ptr<base::ListValue> json_results(new base::ListValue()); for (DownloadManager::DownloadVector::const_iterator it = results.begin(); it != results.end(); ++it) { json_results->AppendInteger(static_cast<int>((*it)->GetId())); (*it)->Remove(); } - SetResult(std::move(json_results)); RecordApiFunctions(DOWNLOADS_FUNCTION_ERASE); - return true; + return RespondNow(OneArgument(std::move(json_results))); } DownloadsRemoveFileFunction::DownloadsRemoveFileFunction() { @@ -1212,7 +1223,7 @@ bool DownloadsRemoveFileFunction::RunAsync() { downloads::RemoveFile::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); + GetDownload(browser_context(), include_incognito(), params->download_id); if (InvalidId(download_item, &error_) || Fault((download_item->GetState() != DownloadItem::COMPLETE), errors::kNotComplete, &error_) || @@ -1250,7 +1261,7 @@ bool DownloadsAcceptDangerFunction::RunAsync() { void DownloadsAcceptDangerFunction::PromptOrWait(int download_id, int retries) { DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), download_id); + GetDownload(browser_context(), include_incognito(), download_id); content::WebContents* web_contents = dispatcher()->GetVisibleWebContents(); if (InvalidId(download_item, &error_) || Fault(download_item->GetState() != DownloadItem::IN_PROGRESS, @@ -1292,7 +1303,7 @@ void DownloadsAcceptDangerFunction::DangerPromptCallback( int download_id, DownloadDangerPrompt::Action action) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), download_id); + GetDownload(browser_context(), include_incognito(), download_id); if (InvalidId(download_item, &error_) || Fault(download_item->GetState() != DownloadItem::IN_PROGRESS, errors::kNotInProgress, &error_)) @@ -1314,74 +1325,79 @@ DownloadsShowFunction::DownloadsShowFunction() {} DownloadsShowFunction::~DownloadsShowFunction() {} -bool DownloadsShowFunction::RunAsync() { +ExtensionFunction::ResponseAction DownloadsShowFunction::Run() { std::unique_ptr<downloads::Show::Params> params( downloads::Show::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); - if (InvalidId(download_item, &error_)) - return false; + GetDownload(browser_context(), include_incognito(), params->download_id); + std::string error; + if (InvalidId(download_item, &error)) + return RespondNow(Error(error)); download_item->ShowDownloadInShell(); RecordApiFunctions(DOWNLOADS_FUNCTION_SHOW); - return true; + return RespondNow(NoArguments()); } DownloadsShowDefaultFolderFunction::DownloadsShowDefaultFolderFunction() {} DownloadsShowDefaultFolderFunction::~DownloadsShowDefaultFolderFunction() {} -bool DownloadsShowDefaultFolderFunction::RunAsync() { +ExtensionFunction::ResponseAction DownloadsShowDefaultFolderFunction::Run() { DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; - GetManagers(GetProfile(), include_incognito(), &manager, &incognito_manager); + GetManagers(browser_context(), include_incognito(), &manager, + &incognito_manager); platform_util::OpenItem( - GetProfile(), DownloadPrefs::FromDownloadManager(manager)->DownloadPath(), + Profile::FromBrowserContext(browser_context()), + DownloadPrefs::FromDownloadManager(manager)->DownloadPath(), platform_util::OPEN_FOLDER, platform_util::OpenOperationCallback()); RecordApiFunctions(DOWNLOADS_FUNCTION_SHOW_DEFAULT_FOLDER); - return true; + return RespondNow(NoArguments()); } DownloadsOpenFunction::DownloadsOpenFunction() {} DownloadsOpenFunction::~DownloadsOpenFunction() {} -bool DownloadsOpenFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsOpenFunction::Run() { std::unique_ptr<downloads::Open::Params> params( downloads::Open::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); - if (InvalidId(download_item, &error_) || - Fault(!user_gesture(), errors::kUserGesture, &error_) || + GetDownload(browser_context(), include_incognito(), params->download_id); + std::string error; + if (InvalidId(download_item, &error) || + Fault(!user_gesture(), errors::kUserGesture, &error) || Fault(download_item->GetState() != DownloadItem::COMPLETE, - errors::kNotComplete, - &error_) || + errors::kNotComplete, &error) || Fault(!extension()->permissions_data()->HasAPIPermission( APIPermission::kDownloadsOpen), - errors::kOpenPermission, - &error_)) - return false; + errors::kOpenPermission, &error)) { + return RespondNow(Error(error)); + } download_item->OpenDownload(); RecordApiFunctions(DOWNLOADS_FUNCTION_OPEN); - return true; + return RespondNow(NoArguments()); } DownloadsDragFunction::DownloadsDragFunction() {} DownloadsDragFunction::~DownloadsDragFunction() {} -bool DownloadsDragFunction::RunAsync() { +ExtensionFunction::ResponseAction DownloadsDragFunction::Run() { std::unique_ptr<downloads::Drag::Params> params( downloads::Drag::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); + GetDownload(browser_context(), include_incognito(), params->download_id); content::WebContents* web_contents = dispatcher()->GetVisibleWebContents(); - if (InvalidId(download_item, &error_) || - Fault(!web_contents, errors::kInvisibleContext, &error_)) - return false; + std::string error; + if (InvalidId(download_item, &error) || + Fault(!web_contents, errors::kInvisibleContext, &error)) { + return RespondNow(Error(error)); + } RecordApiFunctions(DOWNLOADS_FUNCTION_DRAG); gfx::Image* icon = g_browser_process->icon_manager()->LookupIconFromFilepath( download_item->GetTargetFilePath(), IconLoader::NORMAL); @@ -1392,27 +1408,28 @@ bool DownloadsDragFunction::RunAsync() { base::MessageLoop::current()); DragDownloadItem(download_item, icon, view); } - return true; + return RespondNow(NoArguments()); } DownloadsSetShelfEnabledFunction::DownloadsSetShelfEnabledFunction() {} DownloadsSetShelfEnabledFunction::~DownloadsSetShelfEnabledFunction() {} -bool DownloadsSetShelfEnabledFunction::RunSync() { +ExtensionFunction::ResponseAction DownloadsSetShelfEnabledFunction::Run() { std::unique_ptr<downloads::SetShelfEnabled::Params> params( downloads::SetShelfEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); + // TODO(devlin): Solve this with the feature system. if (!extension()->permissions_data()->HasAPIPermission( APIPermission::kDownloadsShelf)) { - error_ = download_extension_errors::kShelfPermission; - return false; + return RespondNow(Error(download_extension_errors::kShelfPermission)); } RecordApiFunctions(DOWNLOADS_FUNCTION_SET_SHELF_ENABLED); DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; - GetManagers(GetProfile(), include_incognito(), &manager, &incognito_manager); + GetManagers(browser_context(), include_incognito(), &manager, + &incognito_manager); DownloadService* service = NULL; DownloadService* incognito_service = NULL; if (manager) { @@ -1446,11 +1463,10 @@ bool DownloadsSetShelfEnabledFunction::RunSync() { if (params->enabled && ((manager && !service->IsShelfEnabled()) || (incognito_manager && !incognito_service->IsShelfEnabled()))) { - error_ = download_extension_errors::kShelfDisabled; - return false; + return RespondNow(Error(download_extension_errors::kShelfDisabled)); } - return true; + return RespondNow(NoArguments()); } DownloadsGetFileIconFunction::DownloadsGetFileIconFunction() @@ -1473,9 +1489,9 @@ bool DownloadsGetFileIconFunction::RunAsync() { params->options.get(); int icon_size = kDefaultIconSize; if (options && options->size.get()) - icon_size = *options->size.get(); + icon_size = *options->size; DownloadItem* download_item = - GetDownload(GetProfile(), include_incognito(), params->download_id); + GetDownload(browser_context(), include_incognito(), params->download_id); if (InvalidId(download_item, &error_) || Fault(download_item->GetTargetFilePath().empty(), errors::kEmptyFile, &error_)) @@ -1593,14 +1609,14 @@ void ExtensionDownloadsEventRouter::OnDeterminingFilename( } data->BeginFilenameDetermination(no_change, change); bool any_determiners = false; - base::DictionaryValue* json = DownloadItemToJSON( - item, profile_).release(); + std::unique_ptr<base::DictionaryValue> json = + DownloadItemToJSON(item, profile_); json->SetString(kFilenameKey, suggested_path.LossyDisplayName()); DispatchEvent(events::DOWNLOADS_ON_DETERMINING_FILENAME, downloads::OnDeterminingFilename::kEventName, false, base::Bind(&OnDeterminingFilenameWillDispatchCallback, &any_determiners, data), - json); + std::move(json)); if (!any_determiners) { data->ClearPendingDeterminers(); if (!data->creator_suggested_filename().empty() || @@ -1761,7 +1777,8 @@ void ExtensionDownloadsEventRouter::OnDownloadCreated( std::unique_ptr<base::DictionaryValue> json_item( DownloadItemToJSON(download_item, profile_)); DispatchEvent(events::DOWNLOADS_ON_CREATED, downloads::OnCreated::kEventName, - true, Event::WillDispatchCallback(), json_item->DeepCopy()); + true, Event::WillDispatchCallback(), + json_item->CreateDeepCopy()); if (!ExtensionDownloadsEventRouterData::Get(download_item) && (router->HasEventListener(downloads::OnChanged::kEventName) || router->HasEventListener( @@ -1798,8 +1815,8 @@ void ExtensionDownloadsEventRouter::OnDownloadUpdated( // the bytesReceived field, if the field has changed from the previous old // json, set the differences in the |delta| object and remember that something // significant changed. - for (base::DictionaryValue::Iterator iter(*new_json.get()); - !iter.IsAtEnd(); iter.Advance()) { + for (base::DictionaryValue::Iterator iter(*new_json); !iter.IsAtEnd(); + iter.Advance()) { new_fields.insert(iter.key()); if (IsDownloadDeltaField(iter.key())) { const base::Value* old_value = NULL; @@ -1832,7 +1849,7 @@ void ExtensionDownloadsEventRouter::OnDownloadUpdated( if (changed) { DispatchEvent(events::DOWNLOADS_ON_CHANGED, downloads::OnChanged::kEventName, true, - Event::WillDispatchCallback(), delta.release()); + Event::WillDispatchCallback(), std::move(delta)); data->OnChangedFired(); } data->set_json(std::move(new_json)); @@ -1843,10 +1860,10 @@ void ExtensionDownloadsEventRouter::OnDownloadRemoved( DCHECK_CURRENTLY_ON(BrowserThread::UI); if (download_item->IsTemporary()) return; - DispatchEvent( - events::DOWNLOADS_ON_ERASED, downloads::OnErased::kEventName, true, - Event::WillDispatchCallback(), - new base::FundamentalValue(static_cast<int>(download_item->GetId()))); + DispatchEvent(events::DOWNLOADS_ON_ERASED, downloads::OnErased::kEventName, + true, Event::WillDispatchCallback(), + base::MakeUnique<base::FundamentalValue>( + static_cast<int>(download_item->GetId()))); } void ExtensionDownloadsEventRouter::DispatchEvent( @@ -1854,12 +1871,12 @@ void ExtensionDownloadsEventRouter::DispatchEvent( const std::string& event_name, bool include_incognito, const Event::WillDispatchCallback& will_dispatch_callback, - base::Value* arg) { + std::unique_ptr<base::Value> arg) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!EventRouter::Get(profile_)) return; std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(arg); + args->Append(std::move(arg)); std::string json_args; base::JSONWriter::Write(*args, &json_args); std::unique_ptr<Event> event( diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h index e634017b3ef..6ad08a15c0d 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_DOWNLOADS_DOWNLOADS_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_DOWNLOADS_DOWNLOADS_API_H_ +#include <memory> #include <set> #include <string> @@ -111,11 +112,11 @@ class DownloadsDownloadFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsDownloadFunction); }; -class DownloadsSearchFunction : public ChromeSyncExtensionFunction { +class DownloadsSearchFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.search", DOWNLOADS_SEARCH) DownloadsSearchFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsSearchFunction() override; @@ -124,11 +125,11 @@ class DownloadsSearchFunction : public ChromeSyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsSearchFunction); }; -class DownloadsPauseFunction : public ChromeSyncExtensionFunction { +class DownloadsPauseFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.pause", DOWNLOADS_PAUSE) DownloadsPauseFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsPauseFunction() override; @@ -137,11 +138,11 @@ class DownloadsPauseFunction : public ChromeSyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsPauseFunction); }; -class DownloadsResumeFunction : public ChromeSyncExtensionFunction { +class DownloadsResumeFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.resume", DOWNLOADS_RESUME) DownloadsResumeFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsResumeFunction() override; @@ -150,11 +151,11 @@ class DownloadsResumeFunction : public ChromeSyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsResumeFunction); }; -class DownloadsCancelFunction : public ChromeSyncExtensionFunction { +class DownloadsCancelFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.cancel", DOWNLOADS_CANCEL) DownloadsCancelFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsCancelFunction() override; @@ -163,11 +164,11 @@ class DownloadsCancelFunction : public ChromeSyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsCancelFunction); }; -class DownloadsEraseFunction : public ChromeSyncExtensionFunction { +class DownloadsEraseFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.erase", DOWNLOADS_ERASE) DownloadsEraseFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsEraseFunction() override; @@ -215,11 +216,11 @@ class DownloadsAcceptDangerFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsAcceptDangerFunction); }; -class DownloadsShowFunction : public ChromeAsyncExtensionFunction { +class DownloadsShowFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.show", DOWNLOADS_SHOW) DownloadsShowFunction(); - bool RunAsync() override; + ResponseAction Run() override; protected: ~DownloadsShowFunction() override; @@ -228,12 +229,12 @@ class DownloadsShowFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsShowFunction); }; -class DownloadsShowDefaultFolderFunction : public ChromeAsyncExtensionFunction { +class DownloadsShowDefaultFolderFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION( "downloads.showDefaultFolder", DOWNLOADS_SHOWDEFAULTFOLDER) DownloadsShowDefaultFolderFunction(); - bool RunAsync() override; + ResponseAction Run() override; protected: ~DownloadsShowDefaultFolderFunction() override; @@ -242,11 +243,11 @@ class DownloadsShowDefaultFolderFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsShowDefaultFolderFunction); }; -class DownloadsOpenFunction : public ChromeSyncExtensionFunction { +class DownloadsOpenFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.open", DOWNLOADS_OPEN) DownloadsOpenFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsOpenFunction() override; @@ -255,12 +256,12 @@ class DownloadsOpenFunction : public ChromeSyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsOpenFunction); }; -class DownloadsSetShelfEnabledFunction : public ChromeSyncExtensionFunction { +class DownloadsSetShelfEnabledFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.setShelfEnabled", DOWNLOADS_SETSHELFENABLED) DownloadsSetShelfEnabledFunction(); - bool RunSync() override; + ResponseAction Run() override; protected: ~DownloadsSetShelfEnabledFunction() override; @@ -269,11 +270,11 @@ class DownloadsSetShelfEnabledFunction : public ChromeSyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsSetShelfEnabledFunction); }; -class DownloadsDragFunction : public ChromeAsyncExtensionFunction { +class DownloadsDragFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.drag", DOWNLOADS_DRAG) DownloadsDragFunction(); - bool RunAsync() override; + ResponseAction Run() override; protected: ~DownloadsDragFunction() override; @@ -388,7 +389,7 @@ class ExtensionDownloadsEventRouter const std::string& event_name, bool include_incognito, const extensions::Event::WillDispatchCallback& will_dispatch_callback, - base::Value* json_arg); + std::unique_ptr<base::Value> json_arg); // extensions::ExtensionRegistryObserver. void OnExtensionUnloaded( 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 cede2fe2616..5d1cfcf59e6 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc @@ -95,12 +95,10 @@ class DownloadsEventsListener : public content::NotificationObserver { registrar_.Remove(this, extensions::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT, content::NotificationService::AllSources()); - STLDeleteElements(&events_); + base::STLDeleteElements(&events_); } - void ClearEvents() { - STLDeleteElements(&events_); - } + void ClearEvents() { base::STLDeleteElements(&events_); } class Event { public: @@ -208,7 +206,7 @@ class DownloadsEventsListener : public content::NotificationObserver { waiting_for_.reset(new Event(profile, event_name, json_args, base::Time())); for (std::deque<Event*>::const_iterator iter = events_.begin(); iter != events_.end(); ++iter) { - if ((*iter)->Satisfies(*waiting_for_.get())) { + if ((*iter)->Satisfies(*waiting_for_)) { return true; } } @@ -382,7 +380,7 @@ class DownloadExtensionTest : public ExtensionApiTest { std::string GetFilename(const char* path) { std::string result = - downloads_directory_.path().AppendASCII(path).AsUTF8Unsafe(); + downloads_directory_.GetPath().AppendASCII(path).AsUTF8Unsafe(); #if defined(OS_WIN) for (std::string::size_type next = result.find("\\"); next != std::string::npos; @@ -499,7 +497,8 @@ class DownloadExtensionTest : public ExtensionApiTest { CreateDownloadObserver(1)); GURL finish_url(net::URLRequestSlowDownloadJob::kFinishDownloadUrl); ui_test_utils::NavigateToURLWithDisposition( - current_browser(), finish_url, NEW_FOREGROUND_TAB, + current_browser(), finish_url, + WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); observer->WaitForFinished(); EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); @@ -571,7 +570,7 @@ class DownloadExtensionTest : public ExtensionApiTest { } const base::FilePath& downloads_directory() { - return downloads_directory_.path(); + return downloads_directory_.GetPath(); } DownloadsEventsListener* events_listener() { return events_listener_.get(); } @@ -592,8 +591,7 @@ class DownloadExtensionTest : public ExtensionApiTest { void CreateAndSetDownloadsDirectory() { ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir()); current_browser()->profile()->GetPrefs()->SetFilePath( - prefs::kDownloadDefaultDirectory, - downloads_directory_.path()); + prefs::kDownloadDefaultDirectory, downloads_directory_.GetPath()); } base::ScopedTempDir downloads_directory_; @@ -1087,6 +1085,34 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, ASSERT_EQ(1UL, result_list->GetSize()); } +#if !defined(OS_CHROMEOS) +IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, + DownloadsShowFunction) { + ScopedCancellingItem item(CreateSlowTestDownload()); + ASSERT_TRUE(item.get()); + + RunFunction(new DownloadsShowFunction(), DownloadItemIdAsArgList(item.get())); +} + +IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, + DownloadsShowDefaultFolderFunction) { + ScopedCancellingItem item(CreateSlowTestDownload()); + ASSERT_TRUE(item.get()); + + RunFunction(new DownloadsShowDefaultFolderFunction(), + DownloadItemIdAsArgList(item.get())); +} + +IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, + DownloadsDragFunction) { + ScopedCancellingItem item(CreateSlowTestDownload()); + ASSERT_TRUE(item.get()); + + RunFunction(new DownloadsDragFunction(), DownloadItemIdAsArgList(item.get())); +} +#endif + + // Test the |filenameRegex| parameter for search(). IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchFilenameRegex) { @@ -1518,7 +1544,9 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, " \"incognito\": false," " \"mime\": \"text/plain\"," " \"paused\": false," + " \"finalUrl\": \"%s\"," " \"url\": \"%s\"}]", + download_url.c_str(), download_url.c_str()))); ASSERT_TRUE( WaitFor(downloads::OnChanged::kEventName, @@ -1536,6 +1564,57 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, result_id))); } +// Test that we can start a download that gets redirected and that the correct +// sequence of events is fired for it. +IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, + DownloadExtensionTest_Download_Redirect) { + LoadExtension("downloads_split"); + ASSERT_TRUE(StartEmbeddedTestServer()); + GURL download_final_url(embedded_test_server()->GetURL("/slow?0")); + GURL download_url(embedded_test_server()->GetURL( + "/server-redirect?" + download_final_url.spec())); + + GoOnTheRecord(); + + // Start downloading a file. + std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( + new DownloadsDownloadFunction(), + base::StringPrintf("[{\"url\": \"%s\"}]", download_url.spec().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()); + ASSERT_EQ(GetExtensionURL(), item->GetSiteUrl().spec()); + + ASSERT_TRUE(WaitFor(downloads::OnCreated::kEventName, + base::StringPrintf( + "[{\"danger\": \"safe\"," + " \"incognito\": false," + " \"mime\": \"text/plain\"," + " \"paused\": false," + " \"finalUrl\": \"%s\"," + " \"url\": \"%s\"}]", + download_final_url.spec().c_str(), + download_url.spec().c_str()))); + ASSERT_TRUE( + WaitFor(downloads::OnChanged::kEventName, + base::StringPrintf("[{\"id\": %d," + " \"filename\": {" + " \"previous\": \"\"," + " \"current\": \"%s\"}}]", + result_id, GetFilename("slow.txt").c_str()))); + ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, + base::StringPrintf( + "[{\"id\": %d," + " \"state\": {" + " \"previous\": \"in_progress\"," + " \"current\": \"complete\"}}]", + result_id))); +} + // Test that we can start a download from an incognito context, and that the // download knows that it's incognito. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, @@ -3956,8 +4035,7 @@ IN_PROC_BROWSER_TEST_F( ui_test_utils::NavigateToURLWithDisposition( current_browser(), GURL(net::URLRequestSlowDownloadJob::kUnknownSizeUrl), - CURRENT_TAB, - ui_test_utils::BROWSER_TEST_NONE); + WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE); observer->WaitForFinished(); EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS)); DownloadManager::DownloadVector items; @@ -3996,7 +4074,7 @@ IN_PROC_BROWSER_TEST_F( ui_test_utils::NavigateToURLWithDisposition( current_browser(), GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl), - NEW_BACKGROUND_TAB, + WindowOpenDisposition::NEW_BACKGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Errors caught before filename determination are delayed until after diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc index d45b936fe88..1dfdc65b71a 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc @@ -109,8 +109,8 @@ class DownloadsApiUnitTest : public ExtensionApiUnittest { std::unique_ptr<KeyedService> DownloadsApiUnitTest::TestingDownloadServiceFactory( content::BrowserContext* browser_context) { - return base::WrapUnique( - new TestDownloadService(Profile::FromBrowserContext(browser_context))); + return base::MakeUnique<TestDownloadService>( + Profile::FromBrowserContext(browser_context)); } // Tests that Number/double properties in query are parsed correctly. diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc index f00088faae7..8a199fa4746 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc @@ -137,7 +137,7 @@ EasyUnlockPrivateGetStringsFunction::EasyUnlockPrivateGetStringsFunction() { EasyUnlockPrivateGetStringsFunction::~EasyUnlockPrivateGetStringsFunction() { } -bool EasyUnlockPrivateGetStringsFunction::RunSync() { +ExtensionFunction::ResponseAction EasyUnlockPrivateGetStringsFunction::Run() { std::unique_ptr<base::DictionaryValue> strings(new base::DictionaryValue); #if defined(OS_CHROMEOS) @@ -359,8 +359,7 @@ bool EasyUnlockPrivateGetStringsFunction::RunSync() { l10n_util::GetStringUTF16( IDS_EASY_UNLOCK_SETUP_ERROR_CONNECTING_TO_PHONE)); - SetResult(std::move(strings)); - return true; + return RespondNow(OneArgument(std::move(strings))); } EasyUnlockPrivatePerformECDHKeyAgreementFunction:: @@ -534,18 +533,18 @@ EasyUnlockPrivateUpdateScreenlockStateFunction:: EasyUnlockPrivateUpdateScreenlockStateFunction:: ~EasyUnlockPrivateUpdateScreenlockStateFunction() {} -bool EasyUnlockPrivateUpdateScreenlockStateFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateUpdateScreenlockStateFunction::Run() { std::unique_ptr<easy_unlock_private::UpdateScreenlockState::Params> params( easy_unlock_private::UpdateScreenlockState::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); Profile* profile = Profile::FromBrowserContext(browser_context()); if (EasyUnlockService::Get(profile)->UpdateScreenlockState( - ToScreenlockState(params->state))) - return true; - - SetError("Not allowed"); - return false; + ToScreenlockState(params->state))) { + return RespondNow(NoArguments()); + } + return RespondNow(Error("Not allowed")); } EasyUnlockPrivateSetPermitAccessFunction:: @@ -556,7 +555,8 @@ EasyUnlockPrivateSetPermitAccessFunction:: ~EasyUnlockPrivateSetPermitAccessFunction() { } -bool EasyUnlockPrivateSetPermitAccessFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetPermitAccessFunction::Run() { std::unique_ptr<easy_unlock_private::SetPermitAccess::Params> params( easy_unlock_private::SetPermitAccess::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -564,8 +564,7 @@ bool EasyUnlockPrivateSetPermitAccessFunction::RunSync() { Profile* profile = Profile::FromBrowserContext(browser_context()); EasyUnlockService::Get(profile) ->SetPermitAccess(*params->permit_access.ToValue()); - - return true; + return RespondNow(NoArguments()); } EasyUnlockPrivateGetPermitAccessFunction:: @@ -576,23 +575,25 @@ EasyUnlockPrivateGetPermitAccessFunction:: ~EasyUnlockPrivateGetPermitAccessFunction() { } -bool EasyUnlockPrivateGetPermitAccessFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateGetPermitAccessFunction::Run() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( proximity_auth::switches::kEnableBluetoothLowEnergyDiscovery)) { - ReturnPermitAccessForExperiment(); - return true; + return GetPermitAccessForExperiment(); } Profile* profile = Profile::FromBrowserContext(browser_context()); const base::DictionaryValue* permit_value = EasyUnlockService::Get(profile)->GetPermitAccess(); + if (permit_value) { std::unique_ptr<easy_unlock_private::PermitRecord> permit = easy_unlock_private::PermitRecord::FromValue(*permit_value); - results_ = easy_unlock_private::GetPermitAccess::Results::Create(*permit); + return RespondNow(ArgumentList( + easy_unlock_private::GetPermitAccess::Results::Create(*permit))); } - return true; + return RespondNow(NoArguments()); } void EasyUnlockPrivateGetPermitAccessFunction::GetKeyPairForExperiment( @@ -611,15 +612,14 @@ void EasyUnlockPrivateGetPermitAccessFunction::GetKeyPairForExperiment( user_private_key); } -void EasyUnlockPrivateGetPermitAccessFunction:: - ReturnPermitAccessForExperiment() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateGetPermitAccessFunction::GetPermitAccessForExperiment() { // Check that we are inside a user session. Profile* profile = Profile::FromBrowserContext(browser_context()); EasyUnlockService* easy_unlock_service = EasyUnlockService::Get(profile); if (easy_unlock_service->GetType() != EasyUnlockService::TYPE_REGULAR) { - SetError("This function must be called inside a user session."); - SendResponse(true); - return; + return RespondNow( + Error("This function must be called inside a user session.")); } std::string b64_public_key, b64_private_key; @@ -640,9 +640,7 @@ void EasyUnlockPrivateGetPermitAccessFunction:: << "chrome.easyUnlockPrivate.getPermitAccess:\n" << " id: " << b64_public_key; - std::unique_ptr<easy_unlock_private::PermitRecord> result = - easy_unlock_private::PermitRecord::FromValue(*permit_access); - results_ = easy_unlock_private::GetPermitAccess::Results::Create(*result); + return RespondNow(OneArgument(std::move(permit_access))); } EasyUnlockPrivateClearPermitAccessFunction:: @@ -653,10 +651,11 @@ EasyUnlockPrivateClearPermitAccessFunction:: ~EasyUnlockPrivateClearPermitAccessFunction() { } -bool EasyUnlockPrivateClearPermitAccessFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateClearPermitAccessFunction::Run() { Profile* profile = Profile::FromBrowserContext(browser_context()); EasyUnlockService::Get(profile)->ClearPermitAccess(); - return true; + return RespondNow(NoArguments()); } EasyUnlockPrivateSetRemoteDevicesFunction:: @@ -667,7 +666,8 @@ EasyUnlockPrivateSetRemoteDevicesFunction:: ~EasyUnlockPrivateSetRemoteDevicesFunction() { } -bool EasyUnlockPrivateSetRemoteDevicesFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetRemoteDevicesFunction::Run() { std::unique_ptr<easy_unlock_private::SetRemoteDevices::Params> params( easy_unlock_private::SetRemoteDevices::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -685,7 +685,7 @@ bool EasyUnlockPrivateSetRemoteDevicesFunction::RunSync() { EasyUnlockService::Get(profile)->SetRemoteDevices(devices); } - return true; + return RespondNow(NoArguments()); } EasyUnlockPrivateGetRemoteDevicesFunction:: @@ -876,7 +876,8 @@ EasyUnlockPrivateTrySignInSecretFunction:: ~EasyUnlockPrivateTrySignInSecretFunction() { } -bool EasyUnlockPrivateTrySignInSecretFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateTrySignInSecretFunction::Run() { std::unique_ptr<easy_unlock_private::TrySignInSecret::Params> params( easy_unlock_private::TrySignInSecret::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -884,7 +885,7 @@ bool EasyUnlockPrivateTrySignInSecretFunction::RunSync() { Profile* profile = Profile::FromBrowserContext(browser_context()); EasyUnlockService::Get(profile)->FinalizeSignin(std::string( params->sign_in_secret.begin(), params->sign_in_secret.end())); - return true; + return RespondNow(NoArguments()); } EasyUnlockPrivateGetUserInfoFunction::EasyUnlockPrivateGetUserInfoFunction() { @@ -893,7 +894,7 @@ EasyUnlockPrivateGetUserInfoFunction::EasyUnlockPrivateGetUserInfoFunction() { EasyUnlockPrivateGetUserInfoFunction::~EasyUnlockPrivateGetUserInfoFunction() { } -bool EasyUnlockPrivateGetUserInfoFunction::RunSync() { +ExtensionFunction::ResponseAction EasyUnlockPrivateGetUserInfoFunction::Run() { EasyUnlockService* service = EasyUnlockService::Get(Profile::FromBrowserContext(browser_context())); std::vector<easy_unlock_private::UserInfo> users; @@ -916,8 +917,8 @@ bool EasyUnlockPrivateGetUserInfoFunction::RunSync() { proximity_auth::switches::kEnableBluetoothLowEnergyDiscovery); users.push_back(std::move(user)); } - results_ = easy_unlock_private::GetUserInfo::Results::Create(users); - return true; + return RespondNow( + ArgumentList(easy_unlock_private::GetUserInfo::Results::Create(users))); } EasyUnlockPrivateGetConnectionInfoFunction:: @@ -971,12 +972,11 @@ EasyUnlockPrivateShowErrorBubbleFunction:: ~EasyUnlockPrivateShowErrorBubbleFunction() { } -bool EasyUnlockPrivateShowErrorBubbleFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateShowErrorBubbleFunction::Run() { content::WebContents* web_contents = GetAssociatedWebContents(); - if (!web_contents) { - SetError("A foreground app window is required."); - return true; - } + if (!web_contents) + return RespondNow(Error("A foreground app window is required.")); std::unique_ptr<easy_unlock_private::ShowErrorBubble::Params> params( easy_unlock_private::ShowErrorBubble::Params::Create(*args_)); @@ -986,8 +986,7 @@ bool EasyUnlockPrivateShowErrorBubbleFunction::RunSync() { params->link_range.end < 0 || base::saturated_cast<size_t>(params->link_range.end) > params->message.size()) { - SetError("Invalid link range."); - return true; + return RespondNow(Error("Invalid link range.")); } #if defined(TOOLKIT_VIEWS) @@ -1000,10 +999,10 @@ bool EasyUnlockPrivateShowErrorBubbleFunction::RunSync() { base::UTF8ToUTF16(params->message), gfx::Range(params->link_range.start, params->link_range.end), GURL(params->link_target), anchor_rect, web_contents); + return RespondNow(NoArguments()); #else - SetError("Not supported on non-Views platforms."); + return RespondNow(Error("Not supported on non-Views platforms.")); #endif - return true; } EasyUnlockPrivateHideErrorBubbleFunction:: @@ -1014,13 +1013,14 @@ EasyUnlockPrivateHideErrorBubbleFunction:: ~EasyUnlockPrivateHideErrorBubbleFunction() { } -bool EasyUnlockPrivateHideErrorBubbleFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateHideErrorBubbleFunction::Run() { #if defined(TOOLKIT_VIEWS) HideProximityAuthErrorBubble(); + return RespondNow(NoArguments()); #else - SetError("Not supported on non-Views platforms."); + return RespondNow(Error("Not supported on non-Views platforms.")); #endif - return true; } EasyUnlockPrivateSetAutoPairingResultFunction:: @@ -1031,7 +1031,8 @@ EasyUnlockPrivateSetAutoPairingResultFunction:: ~EasyUnlockPrivateSetAutoPairingResultFunction() { } -bool EasyUnlockPrivateSetAutoPairingResultFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetAutoPairingResultFunction::Run() { std::unique_ptr<easy_unlock_private::SetAutoPairingResult::Params> params = easy_unlock_private::SetAutoPairingResult::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params); @@ -1044,13 +1045,13 @@ bool EasyUnlockPrivateSetAutoPairingResultFunction::RunSync() { EasyUnlockService::Get(profile) ->SetAutoPairingResult(params->result.success, error_message); - return true; + return RespondNow(NoArguments()); } EasyUnlockPrivateFindSetupConnectionFunction:: EasyUnlockPrivateFindSetupConnectionFunction() : bluetooth_throttler_(new proximity_auth::BluetoothThrottlerImpl( - base::WrapUnique(new base::DefaultTickClock()))) {} + base::MakeUnique<base::DefaultTickClock>())) {} EasyUnlockPrivateFindSetupConnectionFunction:: ~EasyUnlockPrivateFindSetupConnectionFunction() { @@ -1111,18 +1112,18 @@ EasyUnlockPrivateSetupConnectionStatusFunction:: EasyUnlockPrivateSetupConnectionStatusFunction:: ~EasyUnlockPrivateSetupConnectionStatusFunction() {} -bool EasyUnlockPrivateSetupConnectionStatusFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetupConnectionStatusFunction::Run() { std::unique_ptr<easy_unlock_private::SetupConnectionStatus::Params> params = easy_unlock_private::SetupConnectionStatus::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params); api::easy_unlock_private::ConnectionStatus status = GetConnectionManager(browser_context()) ->ConnectionStatus(extension(), params->connection_id); - results_ = - easy_unlock_private::SetupConnectionStatus::Results::Create(status); if (status == api::easy_unlock_private::CONNECTION_STATUS_NONE) - SetError("Invalid connectionId"); - return true; + return RespondNow(Error("Invalid connectionId")); + return RespondNow(ArgumentList( + easy_unlock_private::SetupConnectionStatus::Results::Create(status))); } EasyUnlockPrivateSetupConnectionDisconnectFunction:: @@ -1131,16 +1132,17 @@ EasyUnlockPrivateSetupConnectionDisconnectFunction:: EasyUnlockPrivateSetupConnectionDisconnectFunction:: ~EasyUnlockPrivateSetupConnectionDisconnectFunction() {} -bool EasyUnlockPrivateSetupConnectionDisconnectFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetupConnectionDisconnectFunction::Run() { std::unique_ptr<easy_unlock_private::SetupConnectionDisconnect::Params> params = easy_unlock_private::SetupConnectionDisconnect::Params::Create( *args_); EXTENSION_FUNCTION_VALIDATE(params); - bool success = GetConnectionManager(browser_context()) - ->Disconnect(extension(), params->connection_id); - if (!success) - SetError("Invalid connectionId."); - return true; + if (!GetConnectionManager(browser_context()) + ->Disconnect(extension(), params->connection_id)) { + return RespondNow(Error("Invalid connectionId.")); + } + return RespondNow(NoArguments()); } EasyUnlockPrivateSetupConnectionSendFunction:: @@ -1149,16 +1151,17 @@ EasyUnlockPrivateSetupConnectionSendFunction:: EasyUnlockPrivateSetupConnectionSendFunction:: ~EasyUnlockPrivateSetupConnectionSendFunction() {} -bool EasyUnlockPrivateSetupConnectionSendFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetupConnectionSendFunction::Run() { std::unique_ptr<easy_unlock_private::SetupConnectionSend::Params> params = easy_unlock_private::SetupConnectionSend::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params); std::string payload(params->data.begin(), params->data.end()); - bool success = GetConnectionManager(browser_context()) - ->SendMessage(extension(), params->connection_id, payload); - if (!success) - SetError("Invalid connectionId."); - return true; + if (!GetConnectionManager(browser_context()) + ->SendMessage(extension(), params->connection_id, payload)) { + return RespondNow(Error("Invalid connectionId.")); + } + return RespondNow(NoArguments()); } EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction:: @@ -1167,7 +1170,8 @@ EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction:: EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction:: ~EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction() {} -bool EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction::RunSync() { +ExtensionFunction::ResponseAction +EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction::Run() { std::unique_ptr<easy_unlock_private::SetupConnectionGetDeviceAddress::Params> params = easy_unlock_private::SetupConnectionGetDeviceAddress::Params::Create( @@ -1176,12 +1180,11 @@ bool EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction::RunSync() { std::string device_address = GetConnectionManager(browser_context()) ->GetDeviceAddress(extension(), params->connection_id); - results_ = - easy_unlock_private::SetupConnectionGetDeviceAddress::Results::Create( - device_address); if (device_address.empty()) - SetError("Invalid connectionId."); - return true; + return RespondNow(Error("Invalid connectionId.")); + return RespondNow(ArgumentList( + easy_unlock_private::SetupConnectionGetDeviceAddress::Results::Create( + device_address))); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h index b658bfb1e64..91b95f6aa99 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h @@ -74,15 +74,15 @@ class EasyUnlockPrivateAPI : public BrowserContextKeyedAPI { // TODO(tbarzic): Replace SyncExtensionFunction/AsyncExtensionFunction overrides // with UIThreadExtensionFunction throughout the file. -class EasyUnlockPrivateGetStringsFunction : public SyncExtensionFunction { +class EasyUnlockPrivateGetStringsFunction : public UIThreadExtensionFunction { public: EasyUnlockPrivateGetStringsFunction(); protected: ~EasyUnlockPrivateGetStringsFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; private: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.getStrings", @@ -209,14 +209,14 @@ class EasyUnlockPrivateConnectToBluetoothServiceInsecurelyFunction }; class EasyUnlockPrivateUpdateScreenlockStateFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: EasyUnlockPrivateUpdateScreenlockStateFunction(); protected: ~EasyUnlockPrivateUpdateScreenlockStateFunction() override; - bool RunSync() override; + ResponseAction Run() override; private: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.updateScreenlockState", @@ -225,7 +225,8 @@ class EasyUnlockPrivateUpdateScreenlockStateFunction DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateUpdateScreenlockStateFunction); }; -class EasyUnlockPrivateSetPermitAccessFunction : public SyncExtensionFunction { +class EasyUnlockPrivateSetPermitAccessFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.setPermitAccess", EASYUNLOCKPRIVATE_SETPERMITACCESS) @@ -234,13 +235,14 @@ class EasyUnlockPrivateSetPermitAccessFunction : public SyncExtensionFunction { private: ~EasyUnlockPrivateSetPermitAccessFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateSetPermitAccessFunction); }; -class EasyUnlockPrivateGetPermitAccessFunction : public SyncExtensionFunction { +class EasyUnlockPrivateGetPermitAccessFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.getPermitAccess", EASYUNLOCKPRIVATE_GETPERMITACCESS) @@ -255,18 +257,18 @@ class EasyUnlockPrivateGetPermitAccessFunction : public SyncExtensionFunction { std::string* user_private_key); private: - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; // Instead of returning the value set by easyUnlockPrivate.setPermitAccess, // return the permit access used by the native CryptAuthEnrollmentManager. - void ReturnPermitAccessForExperiment(); + ResponseAction GetPermitAccessForExperiment(); DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateGetPermitAccessFunction); }; class EasyUnlockPrivateClearPermitAccessFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.clearPermitAccess", EASYUNLOCKPRIVATE_CLEARPERMITACCESS) @@ -275,13 +277,14 @@ class EasyUnlockPrivateClearPermitAccessFunction private: ~EasyUnlockPrivateClearPermitAccessFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateClearPermitAccessFunction); }; -class EasyUnlockPrivateSetRemoteDevicesFunction : public SyncExtensionFunction { +class EasyUnlockPrivateSetRemoteDevicesFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.setRemoteDevices", EASYUNLOCKPRIVATE_SETREMOTEDEVICES) @@ -290,8 +293,8 @@ class EasyUnlockPrivateSetRemoteDevicesFunction : public SyncExtensionFunction { private: ~EasyUnlockPrivateSetRemoteDevicesFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateSetRemoteDevicesFunction); }; @@ -361,8 +364,8 @@ class EasyUnlockPrivateGetSignInChallengeFunction : DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateGetSignInChallengeFunction); }; -class EasyUnlockPrivateTrySignInSecretFunction : - public SyncExtensionFunction { +class EasyUnlockPrivateTrySignInSecretFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.trySignInSecret", EASYUNLOCKPRIVATE_TRYSIGNINSECRET) @@ -371,13 +374,13 @@ class EasyUnlockPrivateTrySignInSecretFunction : private: ~EasyUnlockPrivateTrySignInSecretFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateTrySignInSecretFunction); }; -class EasyUnlockPrivateGetUserInfoFunction : public SyncExtensionFunction { +class EasyUnlockPrivateGetUserInfoFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.getUserInfo", EASYUNLOCKPRIVATE_GETUSERINFO) @@ -386,8 +389,8 @@ class EasyUnlockPrivateGetUserInfoFunction : public SyncExtensionFunction { private: ~EasyUnlockPrivateGetUserInfoFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateGetUserInfoFunction); }; @@ -411,7 +414,8 @@ class EasyUnlockPrivateGetConnectionInfoFunction DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateGetConnectionInfoFunction); }; -class EasyUnlockPrivateShowErrorBubbleFunction : public SyncExtensionFunction { +class EasyUnlockPrivateShowErrorBubbleFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.showErrorBubble", EASYUNLOCKPRIVATE_SHOWERRORBUBBLE) @@ -420,13 +424,14 @@ class EasyUnlockPrivateShowErrorBubbleFunction : public SyncExtensionFunction { private: ~EasyUnlockPrivateShowErrorBubbleFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateShowErrorBubbleFunction); }; -class EasyUnlockPrivateHideErrorBubbleFunction : public SyncExtensionFunction { +class EasyUnlockPrivateHideErrorBubbleFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.hideErrorBubble", EASYUNLOCKPRIVATE_HIDEERRORBUBBLE) @@ -435,14 +440,14 @@ class EasyUnlockPrivateHideErrorBubbleFunction : public SyncExtensionFunction { private: ~EasyUnlockPrivateHideErrorBubbleFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateHideErrorBubbleFunction); }; class EasyUnlockPrivateSetAutoPairingResultFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.setAutoPairingResult", EASYUNLOCKPRIVATE_SETAUTOPAIRINGRESULT) @@ -451,8 +456,8 @@ class EasyUnlockPrivateSetAutoPairingResultFunction private: ~EasyUnlockPrivateSetAutoPairingResultFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateSetAutoPairingResultFunction); }; @@ -492,7 +497,7 @@ class EasyUnlockPrivateFindSetupConnectionFunction }; class EasyUnlockPrivateSetupConnectionStatusFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.setupConnectionStatus", EASYUNLOCKPRIVATE_SETUPCONNECTIONSTATUS) @@ -501,14 +506,14 @@ class EasyUnlockPrivateSetupConnectionStatusFunction private: ~EasyUnlockPrivateSetupConnectionStatusFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateSetupConnectionStatusFunction); }; class EasyUnlockPrivateSetupConnectionDisconnectFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.setupConnectionDisconnect", EASYUNLOCKPRIVATE_SETUPCONNECTIONDISCONNECT) @@ -517,14 +522,14 @@ class EasyUnlockPrivateSetupConnectionDisconnectFunction private: ~EasyUnlockPrivateSetupConnectionDisconnectFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateSetupConnectionDisconnectFunction); }; class EasyUnlockPrivateSetupConnectionSendFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("easyUnlockPrivate.setupConnectionSend", EASYUNLOCKPRIVATE_SETUPCONNECTIONSEND) @@ -533,14 +538,14 @@ class EasyUnlockPrivateSetupConnectionSendFunction private: ~EasyUnlockPrivateSetupConnectionSendFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateSetupConnectionSendFunction); }; class EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION( "easyUnlockPrivate.setupConnectionGetDeviceAddress", @@ -550,8 +555,8 @@ class EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction private: ~EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction() override; - // SyncExtensionFunction: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN( EasyUnlockPrivateSetupConnectionGetDeviceAddressFunction); diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc index e03f63dfb78..bf6a85b225a 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc @@ -135,8 +135,7 @@ class EasyUnlockPrivateApiTest : public extensions::ExtensionApiUnittest { chromeos::DBusThreadManager::Initialize(); bluez::BluezDBusManager::Initialize( chromeos::DBusThreadManager::Get()->GetSystemBus(), - chromeos::DBusThreadManager::Get()->IsUsingStub( - chromeos::DBusClientBundle::BLUETOOTH)); + chromeos::DBusThreadManager::Get()->IsUsingFakes()); client_ = chromeos::DBusThreadManager::Get()->GetEasyUnlockClient(); extensions::ExtensionApiUnittest::SetUp(); @@ -307,8 +306,8 @@ TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage_EmptyOptions) { std::unique_ptr<base::ListValue> args(new base::ListValue); args->Append(StringToBinaryValue("PAYLOAD")); args->Append(StringToBinaryValue("KEY")); - base::DictionaryValue* options = new base::DictionaryValue(); - args->Append(options); + auto options = base::MakeUnique<base::DictionaryValue>(); + args->Append(std::move(options)); ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), @@ -414,8 +413,8 @@ TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage_EmptyOptions) { std::unique_ptr<base::ListValue> args(new base::ListValue); args->Append(StringToBinaryValue("MESSAGE")); args->Append(StringToBinaryValue("KEY")); - base::DictionaryValue* options = new base::DictionaryValue(); - args->Append(options); + auto options = base::MakeUnique<base::DictionaryValue>(); + args->Append(std::move(options)); ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), @@ -517,8 +516,8 @@ std::unique_ptr<KeyedService> FakeEventRouterFactoryFunction( content::BrowserContext* profile) { std::unique_ptr<extensions::TestExtensionPrefs> extension_prefs( new extensions::TestExtensionPrefs(base::ThreadTaskRunnerHandle::Get())); - return base::WrapUnique(new FakeEventRouter(static_cast<Profile*>(profile), - std::move(extension_prefs))); + return base::MakeUnique<FakeEventRouter>(static_cast<Profile*>(profile), + std::move(extension_prefs)); } TEST_F(EasyUnlockPrivateApiTest, AutoPairing) { diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc index a11dfb8282b..285ccc0d263 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc @@ -98,7 +98,7 @@ bool EasyUnlockPrivateConnectionManager::SendMessage( const std::string& payload) { Connection* connection = GetConnection(extension->id(), connection_id); if (connection && connection->IsConnected()) { - connection->SendMessage(base::WrapUnique(new WireMessage(payload))); + connection->SendMessage(base::MakeUnique<WireMessage>(payload)); return true; } return false; @@ -153,7 +153,7 @@ void EasyUnlockPrivateConnectionManager::DispatchConnectionEvent( events::HistogramValue histogram_value, const Connection* connection, std::unique_ptr<base::ListValue> args) { - const EventListenerMap::ListenerList listeners = + const EventListenerMap::ListenerList& listeners = EventRouter::Get(browser_context_) ->listeners() .GetEventListenersByName(event_name); @@ -163,7 +163,7 @@ void EasyUnlockPrivateConnectionManager::DispatchConnectionEvent( std::unique_ptr<base::ListValue> args_copy(args->DeepCopy()); int connection_index = 0; args_copy->Set(connection_index, - base::WrapUnique(new base::FundamentalValue(connection_id))); + base::MakeUnique<base::FundamentalValue>(connection_id)); std::unique_ptr<Event> event( new Event(histogram_value, event_name, std::move(args_copy))); EventRouter::Get(browser_context_) diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc index 9c665300146..329d1cccfee 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc @@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/affiliation_test_helper.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h" -#include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h" +#include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/net/url_request_mock_util.h" #include "chrome/test/base/ui_test_utils.h" @@ -15,6 +16,7 @@ #include "chromeos/login/user_names.h" #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" +#include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" #include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" @@ -25,7 +27,6 @@ #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/test/result_catcher.h" #include "net/test/url_request/url_request_mock_http_job.h" -#include "policy/policy_constants.h" namespace { @@ -96,8 +97,8 @@ class EnterpriseDeviceAttributesTest : affiliated_account_id_.GetUserEmail(), user_affiliation_ids); // Set up fake install attributes. - std::unique_ptr<policy::StubEnterpriseInstallAttributes> attributes( - new policy::StubEnterpriseInstallAttributes()); + std::unique_ptr<chromeos::StubInstallAttributes> attributes = + base::MakeUnique<chromeos::StubInstallAttributes>(); attributes->SetRegistrationUser(affiliated_account_id_.GetUserEmail()); policy::BrowserPolicyConnectorChromeOS::SetInstallAttributesForTesting( 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 aaf68c6bfcb..fe4603665fd 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 @@ -124,7 +124,7 @@ void EnterprisePlatformKeysGetCertificatesFunction::OnGotCertificates( } std::unique_ptr<base::ListValue> results(new base::ListValue()); - results->Append(client_certs.release()); + results->Append(std::move(client_certs)); Respond(ArgumentList(std::move(results))); } 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 68d0a23a1f4..01e847957bb 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 @@ -13,8 +13,8 @@ #include "base/values.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" -#include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" +#include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/browser.h" @@ -210,11 +210,8 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { - scoped_refptr<ExtensionFunction> function_owner(function); - // Without a callback the function will not generate a result. - function->set_has_callback(true); utils::RunFunction(function, std::move(args), browser, utils::NONE); - EXPECT_FALSE(function->GetResultList()) << "Did not expect a result"; + EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type()); return function->GetError(); } @@ -243,7 +240,7 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { NiceMock<chromeos::attestation::MockAttestationFlow> mock_attestation_flow_; chromeos::ScopedCrosSettingsTestHelper settings_helper_; scoped_refptr<extensions::Extension> extension_; - policy::StubEnterpriseInstallAttributes stub_install_attributes_; + chromeos::StubInstallAttributes stub_install_attributes_; TestingProfileManager profile_manager_; // fake_user_manager_ is owned by user_manager_enabler_. chromeos::FakeChromeUserManager* fake_user_manager_; @@ -415,7 +412,7 @@ class EPKChallengeUserKeyTest : public EPKChallengeKeyTestBase { std::unique_ptr<base::ListValue> CreateArgsInternal(bool register_key) { std::unique_ptr<base::ListValue> args(new base::ListValue); args->Append(base::BinaryValue::CreateWithCopiedBuffer("challenge", 9)); - args->Append(new base::FundamentalValue(register_key)); + args->AppendBoolean(register_key); return args; } diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc index 7728d91e361..3adc4ec10df 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc @@ -29,6 +29,7 @@ #include "components/policy/core/browser/browser_policy_connector.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 "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_manager.h" @@ -50,7 +51,6 @@ #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "net/test/url_request/url_request_mock_http_job.h" -#include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" 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 ac2fbd1a68b..64ad488fd0b 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 @@ -15,9 +15,9 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/attestation/attestation_ca_client.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" -#include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" +#include "chrome/browser/chromeos/settings/install_attributes.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager_factory.h" @@ -98,7 +98,7 @@ EPKPChallengeKeyBase::EPKPChallengeKeyBase( chromeos::CryptohomeClient* cryptohome_client, cryptohome::AsyncMethodCaller* async_caller, chromeos::attestation::AttestationFlow* attestation_flow, - policy::EnterpriseInstallAttributes* install_attributes) : + chromeos::InstallAttributes* install_attributes) : cryptohome_client_(cryptohome_client), async_caller_(async_caller), attestation_flow_(attestation_flow), @@ -158,7 +158,7 @@ AccountId EPKPChallengeKeyBase::GetAccountId() const { return user->GetAccountId(); } -bool EPKPChallengeKeyBase::IsUserManaged() const { +bool EPKPChallengeKeyBase::IsUserAffiliated() const { const user_manager::User* const user = user_manager::UserManager::Get()->FindUser(GetAccountId()); @@ -299,7 +299,7 @@ EPKPChallengeMachineKey::EPKPChallengeMachineKey( chromeos::CryptohomeClient* cryptohome_client, cryptohome::AsyncMethodCaller* async_caller, chromeos::attestation::AttestationFlow* attestation_flow, - policy::EnterpriseInstallAttributes* install_attributes) : + chromeos::InstallAttributes* install_attributes) : EPKPChallengeKeyBase(cryptohome_client, async_caller, attestation_flow, @@ -329,8 +329,7 @@ void EPKPChallengeMachineKey::Run( return; } - // Check if the user domain is the same as the enrolled enterprise domain. - if (!IsUserManaged()) { + if (!IsUserAffiliated()) { callback_.Run(false, kUserNotManaged); return; } @@ -414,7 +413,7 @@ EPKPChallengeUserKey::EPKPChallengeUserKey( chromeos::CryptohomeClient* cryptohome_client, cryptohome::AsyncMethodCaller* async_caller, chromeos::attestation::AttestationFlow* attestation_flow, - policy::EnterpriseInstallAttributes* install_attributes) : + chromeos::InstallAttributes* install_attributes) : EPKPChallengeKeyBase(cryptohome_client, async_caller, attestation_flow, @@ -451,8 +450,7 @@ void EPKPChallengeUserKey::Run(scoped_refptr<UIThreadExtensionFunction> caller, } if (IsEnterpriseDevice()) { - // Check if the user domain is the same as the enrolled enterprise domain. - if (!IsUserManaged()) { + if (!IsUserAffiliated()) { callback_.Run(false, kUserNotManaged); return; } 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 074bdde6441..0c7d484c533 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 @@ -27,16 +27,13 @@ class Profile; namespace chromeos { class CryptohomeClient; +class InstallAttributes; } namespace cryptohome { class AsyncMethodCaller; } -namespace policy { -class EnterpriseInstallAttributes; -} - namespace user_prefs { class PrefRegistrySyncable; } @@ -72,7 +69,7 @@ class EPKPChallengeKeyBase { chromeos::CryptohomeClient* cryptohome_client, cryptohome::AsyncMethodCaller* async_caller, chromeos::attestation::AttestationFlow* attestation_flow, - policy::EnterpriseInstallAttributes* install_attributes); + chromeos::InstallAttributes* install_attributes); virtual ~EPKPChallengeKeyBase(); // Returns a trusted value from CroSettings indicating if the device @@ -86,8 +83,9 @@ class EPKPChallengeKeyBase { // Returns true if the extension is white-listed in the user policy. bool IsExtensionWhitelisted() const; - // Returns true if the user is enterprise managed. - bool IsUserManaged() const; + // Returns true if the user is managed and is affiliated with the domain the + // device is enrolled to. + bool IsUserAffiliated() const; // Returns the enterprise domain the device is enrolled to. std::string GetEnterpriseDomain() const; @@ -160,7 +158,7 @@ class EPKPChallengeKeyBase { bool success, const std::string& pem_certificate_chain); - policy::EnterpriseInstallAttributes* install_attributes_; + chromeos::InstallAttributes* install_attributes_; }; class EPKPChallengeMachineKey : public EPKPChallengeKeyBase { @@ -173,7 +171,7 @@ class EPKPChallengeMachineKey : public EPKPChallengeKeyBase { chromeos::CryptohomeClient* cryptohome_client, cryptohome::AsyncMethodCaller* async_caller, chromeos::attestation::AttestationFlow* attestation_flow, - policy::EnterpriseInstallAttributes* install_attributes); + chromeos::InstallAttributes* install_attributes); ~EPKPChallengeMachineKey() override; // Asynchronously run the flow to challenge a machine key in the |caller| @@ -208,7 +206,7 @@ class EPKPChallengeUserKey : public EPKPChallengeKeyBase { chromeos::CryptohomeClient* cryptohome_client, cryptohome::AsyncMethodCaller* async_caller, chromeos::attestation::AttestationFlow* attestation_flow, - policy::EnterpriseInstallAttributes* install_attributes); + chromeos::InstallAttributes* install_attributes); ~EPKPChallengeUserKey() override; static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); 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 ff4f99b6bb0..b3c78fbe3ca 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 @@ -13,8 +13,8 @@ #include "base/values.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" -#include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" +#include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/browser.h" @@ -219,7 +219,7 @@ class EPKPChallengeKeyTestBase : public BrowserWithTestWindowTest { NiceMock<chromeos::attestation::MockAttestationFlow> mock_attestation_flow_; chromeos::ScopedCrosSettingsTestHelper settings_helper_; scoped_refptr<extensions::Extension> extension_; - policy::StubEnterpriseInstallAttributes stub_install_attributes_; + chromeos::StubInstallAttributes stub_install_attributes_; TestingProfileManager profile_manager_; // fake_user_manager_ is owned by user_manager_enabler_. chromeos::FakeChromeUserManager* fake_user_manager_; diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc index 8cc23994ef6..e71b6037c51 100644 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc @@ -19,7 +19,7 @@ typedef ExtensionApiUnittest ExperienceSamplingPrivateTest; TEST_F(ExperienceSamplingPrivateTest, GetBrowserInfoTest) { // Start with an empty FieldTrialList. std::unique_ptr<base::FieldTrialList> trial_list( - new base::FieldTrialList(NULL)); + new base::FieldTrialList(nullptr)); std::unique_ptr<base::DictionaryValue> result(RunFunctionAndReturnDictionary( new ExperienceSamplingPrivateGetBrowserInfoFunction(), "[]")); ASSERT_TRUE(result->HasKey("variations")); 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 0ae5d37aee4..7b2e7dd11dd 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 @@ -22,12 +22,17 @@ #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/extensions/extension_process_policy.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/content_browser_test_utils.h" +#include "content/public/test/download_test_observer.h" +#include "content/public/test/test_utils.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/notification_types.h" @@ -36,9 +41,9 @@ #include "extensions/common/feature_switch.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" -#include "grit/theme_resources.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gmock/include/gmock/gmock.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" @@ -106,7 +111,7 @@ class BrowserActionApiTest : public ExtensionApiTest { return browser_action_test_util_.get(); } - bool OpenPopup(int index) { + WebContents* OpenPopup(int index) { ResultCatcher catcher; content::WindowedNotificationObserver popup_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, @@ -114,7 +119,13 @@ class BrowserActionApiTest : public ExtensionApiTest { GetBrowserActionsBar()->Press(index); popup_observer.Wait(); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - return GetBrowserActionsBar()->HasPopup(); + + if (!GetBrowserActionsBar()->HasPopup()) + return nullptr; + + const auto& source = static_cast<const content::Source<WebContents>&>( + popup_observer.source()); + return source.ptr(); } ExtensionAction* GetBrowserAction(const Extension& extension) { @@ -722,7 +733,7 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionPopupWithIframe) { extensions::ProcessManager::Get(browser()->profile()); std::set<content::RenderFrameHost*> frame_hosts = manager->GetRenderFrameHostsForExtension(extension->id()); - for (auto host : frame_hosts) { + for (auto* host : frame_hosts) { if (host->GetFrameName() == "child_frame") { frame_host = host; break; @@ -766,7 +777,7 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionOpenPopupOnPopup) { // Open a new web popup window. chrome::NavigateParams params(browser(), GURL("http://www.google.com/"), ui::PAGE_TRANSITION_LINK); - params.disposition = NEW_POPUP; + params.disposition = WindowOpenDisposition::NEW_POPUP; params.window_action = chrome::NavigateParams::SHOW_WINDOW; ui_test_utils::NavigateToURL(¶ms); Browser* popup_browser = params.browser; @@ -795,5 +806,217 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionOpenPopupOnPopup) { EXPECT_TRUE(catcher.GetNextResult()) << message_; } +class NavigatingExtensionPopupBrowserTest : public BrowserActionApiTest { + public: + const Extension& popup_extension() { return *popup_extension_; } + const Extension& other_extension() { return *other_extension_; } + + void SetUpOnMainThread() override { + BrowserActionApiTest::SetUpOnMainThread(); + + host_resolver()->AddRule("*", "127.0.0.1"); + ASSERT_TRUE(embedded_test_server()->Start()); + + // Load an extension with a pop-up. + ASSERT_TRUE(popup_extension_ = LoadExtension(test_data_dir_.AppendASCII( + "browser_action/popup_with_form"))); + + // Load another extension (that we can try navigating to). + ASSERT_TRUE(other_extension_ = LoadExtension(test_data_dir_.AppendASCII( + "browser_action/popup_with_iframe"))); + } + + enum ExpectedNavigationStatus { + EXPECTING_NAVIGATION_SUCCESS, + EXPECTING_NAVIGATION_FAILURE, + }; + + void TestPopupNavigationViaGet( + const GURL& target_url, + ExpectedNavigationStatus expected_navigation_status) { + std::string navigation_starting_script = + "window.location = '" + target_url.spec() + "';\n"; + TestPopupNavigation(target_url, expected_navigation_status, + navigation_starting_script); + } + + void TestPopupNavigationViaPost( + const GURL& target_url, + ExpectedNavigationStatus expected_navigation_status) { + std::string navigation_starting_script = + "var form = document.getElementById('form');\n" + "form.action = '" + target_url.spec() + "';\n" + "form.submit();\n"; + TestPopupNavigation(target_url, expected_navigation_status, + navigation_starting_script); + } + + private: + void TestPopupNavigation(const GURL& target_url, + ExpectedNavigationStatus expected_navigation_status, + std::string navigation_starting_script) { + // Were there any failures so far (e.g. in SetUpOnMainThread)? + ASSERT_FALSE(HasFailure()); + + // Simulate a click on the browser action to open the popup. + WebContents* popup = OpenPopup(0); + ASSERT_TRUE(popup); + GURL popup_url = popup_extension().GetResourceURL("popup.html"); + EXPECT_EQ(popup_url, popup->GetLastCommittedURL()); + + // Note that the |setTimeout| call below is needed to make sure + // ExecuteScriptAndExtractBool returns *after* a scheduled navigation has + // already started. + std::string script_to_execute = + navigation_starting_script + + "setTimeout(\n" + " function() { window.domAutomationController.send(true); },\n" + " 0);\n"; + + // Try to navigate the pop-up. + bool ignored_script_result = false; + content::WebContentsDestroyedWatcher popup_destruction_watcher(popup); + EXPECT_TRUE(ExecuteScriptAndExtractBool(popup, script_to_execute, + &ignored_script_result)); + popup = popup_destruction_watcher.web_contents(); + + // Verify if the popup navigation succeeded or failed as expected. + if (!popup) { + // If navigation ends up in a tab, then the tab will be focused and + // therefore the popup will be closed, destroying associated WebContents - + // don't do any verification in this case. + ADD_FAILURE() << "Navigation should not close extension pop-up"; + } else { + // If the extension popup is still opened, then wait until there is no + // load in progress, and verify whether the navigation succeeded or not. + WaitForLoadStop(popup); + if (expected_navigation_status == EXPECTING_NAVIGATION_SUCCESS) { + EXPECT_EQ(target_url, popup->GetLastCommittedURL()) + << "Navigation to " << target_url + << " should succeed in an extension pop-up"; + } else { + EXPECT_NE(target_url, popup->GetLastCommittedURL()) + << "Navigation to " << target_url + << " should fail in an extension pop-up"; + EXPECT_THAT( + popup->GetLastCommittedURL(), + ::testing::AnyOf(::testing::Eq(popup_url), + ::testing::Eq(GURL("chrome-extension://invalid")), + ::testing::Eq(GURL("about:blank")))); + } + + // Close the pop-up. + EXPECT_TRUE(GetBrowserActionsBar()->HidePopup()); + popup_destruction_watcher.Wait(); + } + + // Make sure that the web navigation did not succeed somewhere outside of + // the extension popup (as it might if ExtensionViewHost::OpenURLFromTab + // forwards the navigation to Browser::OpenURL [which doesn't specify a + // source WebContents]). + TabStripModel* tabs = browser()->tab_strip_model(); + for (int i = 0; i < tabs->count(); i++) { + WebContents* tab_contents = tabs->GetWebContentsAt(i); + WaitForLoadStop(tab_contents); + EXPECT_NE(target_url, tab_contents->GetLastCommittedURL()) + << "Navigating an extension pop-up should not affect tabs."; + } + } + + const Extension* popup_extension_; + const Extension* other_extension_; +}; + +// Tests that an extension pop-up cannot be navigated to a web page. +IN_PROC_BROWSER_TEST_F(NavigatingExtensionPopupBrowserTest, Webpage) { + GURL web_url(embedded_test_server()->GetURL("foo.com", "/title1.html")); + + // With and without --isolate-extension the GET request will be blocked in + // ExtensionViewHost::OpenURLFromTab (which silently drops navigations with + // CURRENT_TAB disposition). + TestPopupNavigationViaGet(web_url, EXPECTING_NAVIGATION_FAILURE); + + // POST requests don't go through ExtensionViewHost::OpenURLFromTab. + // + // Without --isolate-extensions, there is no process transfer to isolate + // extensions into separate processes and therefore + // 1) navigating a popup extension to a webpage will succeed (because + // ExtensionViewHost::ShouldTransferNavigation won't get called when there + // is no transfer), + // 2) the webpage will stay in the same renderer process. + // This behavior is okay without --isolate-extensions (where webpages and + // extensions can coexist in the same process in other scenarios) - therefore + // no test verification is needed in this case. + // + // With --isolate-extensions the navigation should be blocked by + // ExtensionViewHost::ShouldTransferNavigation. Test verification is + // important in --isolate-extensions mode, because this mode is all about + // isolating extensions and webpages into separate processes and therefore we + // need to ensure the behavior described above doesn't occur (i.e. that + // instead the webpage navigation in an extension popup fails). + if (extensions::IsIsolateExtensionsEnabled()) + TestPopupNavigationViaPost(web_url, EXPECTING_NAVIGATION_FAILURE); +} + +// Tests that an extension pop-up can be navigated to another page +// in the same extension. +IN_PROC_BROWSER_TEST_F(NavigatingExtensionPopupBrowserTest, + PageInSameExtension) { + GURL other_page_in_same_extension = + popup_extension().GetResourceURL("other_page.html"); + TestPopupNavigationViaGet(other_page_in_same_extension, + EXPECTING_NAVIGATION_SUCCESS); + TestPopupNavigationViaPost(other_page_in_same_extension, + EXPECTING_NAVIGATION_SUCCESS); +} + +// Tests that an extension pop-up cannot be navigated to a page +// in another extension. +IN_PROC_BROWSER_TEST_F(NavigatingExtensionPopupBrowserTest, + PageInOtherExtension) { + GURL other_extension_url = other_extension().GetResourceURL("other.html"); + TestPopupNavigationViaGet(other_extension_url, EXPECTING_NAVIGATION_FAILURE); + TestPopupNavigationViaPost(other_extension_url, EXPECTING_NAVIGATION_FAILURE); +} + +// Tests that navigating an extension pop-up to a http URI that returns +// Content-Disposition: attachment; filename=... +// works: No navigation, but download shelf visible + download goes through. +// +// Note - there is no "...ViaGet" flavour of this test, because we don't care +// (yet) if GET succeeds with the download or not (it probably should succeed +// for consistency with POST, but it always failed in M54 and before). After +// abandoing ShouldFork/OpenURL for all methods (not just for POST) [see comment +// about https://crbug.com/646261 in ChromeContentRendererClient::ShouldFork] +// GET should automagically start working for downloads. +// TODO(lukasza): https://crbug.com/650694: Add a "Get" flavour of the test once +// the download works both for GET and POST requests. +IN_PROC_BROWSER_TEST_F(NavigatingExtensionPopupBrowserTest, DownloadViaPost) { + content::DownloadTestObserverTerminal downloads_observer( + content::BrowserContext::GetDownloadManager(browser()->profile()), + 1, // == wait_count (only waiting for "download-test3.gif"). + content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); + + // Navigate to a URL that replies with + // Content-Disposition: attachment; filename=... + // header. + GURL download_url( + embedded_test_server()->GetURL("foo.com", "/download-test3.gif")); + TestPopupNavigationViaPost(download_url, EXPECTING_NAVIGATION_FAILURE); + + // Verify that "download-test3.gif got downloaded. + downloads_observer.WaitForFinished(); + EXPECT_EQ(0u, downloads_observer.NumDangerousDownloadsSeen()); + EXPECT_EQ(1u, downloads_observer.NumDownloadsSeenInState( + content::DownloadItem::COMPLETE)); + + // The test verification below is applicable only to scenarios where the + // download shelf is supported - on ChromeOS, instead of the download shelf, + // there is a download notification in the right-bottom corner of the screen. +#if !defined(OS_CHROMEOS) + EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); +#endif +} + } // namespace } // namespace extensions 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 009343c5d6d..35b9de583a7 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 @@ -97,10 +97,10 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TestOpenPopup) { content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); // Open a new window. - new_browser = chrome::FindBrowserWithWebContents( - browser()->OpenURL(content::OpenURLParams( - GURL("about:"), content::Referrer(), NEW_WINDOW, - ui::PAGE_TRANSITION_TYPED, false))); + new_browser = chrome::FindBrowserWithWebContents(browser()->OpenURL( + content::OpenURLParams(GURL("about:"), content::Referrer(), + WindowOpenDisposition::NEW_WINDOW, + ui::PAGE_TRANSITION_TYPED, false))); // Hide all the buttons to test that it opens even when the browser action // is in the overflow bucket. ToolbarActionsModel::Get(profile())->SetVisibleIconCount(0); @@ -257,7 +257,14 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, BrowserClickClosesPopup1) { } // Test that the extension popup is closed when the browser window is clicked. -IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, BrowserClickClosesPopup2) { +#if defined(OS_WIN) +// Flaky on Windows: http://crbug.com/639130 +#define MAYBE_BrowserClickClosesPopup2 DISABLED_BrowserClickClosesPopup2 +#else +#define MAYBE_BrowserClickClosesPopup2 BrowserClickClosesPopup2 +#endif +IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, + MAYBE_BrowserClickClosesPopup2) { if (!ShouldRunPopupTest()) return; @@ -371,7 +378,7 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, // Create a new browser window to prevent the message loop from terminating. browser()->OpenURL(content::OpenURLParams(GURL("about:"), content::Referrer(), - NEW_WINDOW, + WindowOpenDisposition::NEW_WINDOW, ui::PAGE_TRANSITION_TYPED, false)); // Forcibly closing the browser HWND should not cause a crash. diff --git a/chromium/chrome/browser/extensions/api/feedback_private/OWNERS b/chromium/chrome/browser/extensions/api/feedback_private/OWNERS index 604b3e566e5..13e3b599939 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/OWNERS +++ b/chromium/chrome/browser/extensions/api/feedback_private/OWNERS @@ -1,2 +1,2 @@ -rkc@chromium.org afakhry@chromium.org +steel@chromium.org diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc index 57796e86041..58a93349b3c 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc @@ -20,13 +20,14 @@ #include "chrome/browser/extensions/api/feedback_private/feedback_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/ui/simple_message_box.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/grit/generated_resources.h" #include "components/feedback/tracing_manager.h" #include "components/signin/core/browser/signin_manager.h" +#include "components/strings/grit/components_strings.h" #include "content/public/browser/user_metrics.h" #include "extensions/browser/event_router.h" -#include "grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "url/url_util.h" @@ -121,14 +122,19 @@ void FeedbackPrivateAPI::RequestFeedbackForFlow( if (browser_context_ && EventRouter::Get(browser_context_)) { FeedbackInfo info; info.description = description_template; - info.category_tag = base::WrapUnique(new std::string(category_tag)); - info.page_url = base::WrapUnique(new std::string(page_url.spec())); + info.category_tag = base::MakeUnique<std::string>(category_tag); + info.page_url = base::MakeUnique<std::string>(page_url.spec()); info.system_information.reset(new SystemInformationList); // The manager is only available if tracing is enabled. if (TracingManager* manager = TracingManager::Get()) { info.trace_id.reset(new int(manager->RequestTrace())); } info.flow = flow; +#if defined(OS_MACOSX) + info.use_system_window_frame = true; +#else + info.use_system_window_frame = false; +#endif std::unique_ptr<base::ListValue> args = feedback_private::OnFeedbackRequested::Create(info); @@ -147,12 +153,13 @@ void FeedbackPrivateAPI::RequestFeedbackForFlow( // static base::Closure* FeedbackPrivateGetStringsFunction::test_callback_ = NULL; -bool FeedbackPrivateGetStringsFunction::RunSync() { +ExtensionFunction::ResponseAction FeedbackPrivateGetStringsFunction::Run() { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); #define SET_STRING(id, idr) \ dict->SetString(id, l10n_util::GetStringUTF16(idr)) SET_STRING("page-title", IDS_FEEDBACK_REPORT_PAGE_TITLE); + SET_STRING("additionalInfo", IDS_FEEDBACK_ADDITIONAL_INFO_LABEL); SET_STRING("page-url", IDS_FEEDBACK_REPORT_URL_LABEL); SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL); SET_STRING("user-email", IDS_FEEDBACK_USER_EMAIL_LABEL); @@ -197,21 +204,19 @@ bool FeedbackPrivateGetStringsFunction::RunSync() { const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, dict.get()); - SetResult(std::move(dict)); if (test_callback_ && !test_callback_->is_null()) test_callback_->Run(); - return true; + return RespondNow(OneArgument(std::move(dict))); } -bool FeedbackPrivateGetUserEmailFunction::RunSync() { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(GetProfile()); - SetResult(base::MakeUnique<base::StringValue>( +ExtensionFunction::ResponseAction FeedbackPrivateGetUserEmailFunction::Run() { + SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); + return RespondNow(OneArgument(base::MakeUnique<base::StringValue>( signin_manager ? signin_manager->GetAuthenticatedAccountInfo().email - : std::string())); - return true; + : std::string()))); } bool FeedbackPrivateGetSystemInformationFunction::RunAsync() { @@ -234,43 +239,37 @@ void FeedbackPrivateGetSystemInformationFunction::OnCompleted( bool FeedbackPrivateSendFeedbackFunction::RunAsync() { std::unique_ptr<feedback_private::SendFeedback::Params> params( feedback_private::SendFeedback::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); + EXTENSION_FUNCTION_VALIDATE(params); const FeedbackInfo &feedback_info = params->feedback; - std::string attached_file_uuid; - if (feedback_info.attached_file_blob_uuid.get() && - !feedback_info.attached_file_blob_uuid->empty()) - attached_file_uuid = *feedback_info.attached_file_blob_uuid; - - std::string screenshot_uuid; - if (feedback_info.screenshot_blob_uuid.get() && - !feedback_info.screenshot_blob_uuid->empty()) - screenshot_uuid = *feedback_info.screenshot_blob_uuid; - // Populate feedback data. scoped_refptr<FeedbackData> feedback_data(new FeedbackData()); feedback_data->set_context(GetProfile()); feedback_data->set_description(feedback_info.description); - if (feedback_info.category_tag.get()) - feedback_data->set_category_tag(*feedback_info.category_tag.get()); - if (feedback_info.page_url.get()) - feedback_data->set_page_url(*feedback_info.page_url.get()); - if (feedback_info.email.get()) - feedback_data->set_user_email(*feedback_info.email.get()); - - if (!attached_file_uuid.empty()) { + if (feedback_info.product_id) + feedback_data->set_product_id(*feedback_info.product_id); + if (feedback_info.category_tag) + feedback_data->set_category_tag(*feedback_info.category_tag); + if (feedback_info.page_url) + feedback_data->set_page_url(*feedback_info.page_url); + if (feedback_info.email) + feedback_data->set_user_email(*feedback_info.email); + if (feedback_info.trace_id) + feedback_data->set_trace_id(*feedback_info.trace_id); + + if (feedback_info.attached_file_blob_uuid && + !feedback_info.attached_file_blob_uuid->empty()) { feedback_data->set_attached_filename( - StripFakepath((*feedback_info.attached_file.get()).name)); - feedback_data->set_attached_file_uuid(attached_file_uuid); + StripFakepath((*feedback_info.attached_file).name)); + feedback_data->set_attached_file_uuid( + *feedback_info.attached_file_blob_uuid); } - if (!screenshot_uuid.empty()) - feedback_data->set_screenshot_uuid(screenshot_uuid); - - if (feedback_info.trace_id.get()) { - feedback_data->set_trace_id(*feedback_info.trace_id.get()); + if (feedback_info.screenshot_blob_uuid && + !feedback_info.screenshot_blob_uuid->empty()) { + feedback_data->set_screenshot_uuid(*feedback_info.screenshot_blob_uuid); } std::unique_ptr<FeedbackData::SystemLogsMap> sys_logs( @@ -307,6 +306,14 @@ void FeedbackPrivateSendFeedbackFunction::OnCompleted( success ? feedback_private::STATUS_SUCCESS : feedback_private::STATUS_DELAYED); SendResponse(true); + + if (!success) { + // Sending the feedback has been delayed as the user is offline. Show a + // message box to indicate that. + chrome::ShowWarningMessageBox( + nullptr, l10n_util::GetStringUTF16(IDS_FEEDBACK_OFFLINE_DIALOG_TITLE), + l10n_util::GetStringUTF16(IDS_FEEDBACK_OFFLINE_DIALOG_TEXT)); + } } AsyncExtensionFunction::ResponseAction diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h index b3c7d6104ef..d8b10a8152b 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h @@ -50,7 +50,7 @@ class FeedbackPrivateAPI : public BrowserContextKeyedAPI { }; // Feedback strings. -class FeedbackPrivateGetStringsFunction : public ChromeSyncExtensionFunction { +class FeedbackPrivateGetStringsFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getStrings", FEEDBACKPRIVATE_GETSTRINGS) @@ -63,21 +63,21 @@ class FeedbackPrivateGetStringsFunction : public ChromeSyncExtensionFunction { protected: ~FeedbackPrivateGetStringsFunction() override {} - // SyncExtensionFunction overrides. - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; private: static base::Closure* test_callback_; }; -class FeedbackPrivateGetUserEmailFunction : public ChromeSyncExtensionFunction { +class FeedbackPrivateGetUserEmailFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getUserEmail", FEEDBACKPRIVATE_GETUSEREMAIL); protected: ~FeedbackPrivateGetUserEmailFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class FeedbackPrivateGetSystemInformationFunction diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc index 18c46b8f3ea..e63daf14528 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc @@ -13,6 +13,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_content_client.h" #include "content/public/browser/browser_thread.h" +#include "net/base/network_change_notifier.h" using content::BrowserThread; using extensions::api::feedback_private::SystemInformation; @@ -134,9 +135,12 @@ void FeedbackService::CompleteSendFeedback( // filled - the object will manage sending of the actual report. feedback_data->OnFeedbackPageDataComplete(); + // Sending the feedback will be delayed if the user is offline. + const bool result = !net::NetworkChangeNotifier::IsOffline(); + // TODO(rkc): Change this once we have FeedbackData/Util refactored to // report the status of the report being sent. - callback.Run(true); + callback.Run(result); } } diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h index 5becf7ad8db..9ada1947668 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h @@ -11,7 +11,6 @@ #include "base/callback.h" #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/extensions/blob_reader.h" #include "chrome/browser/feedback/system_logs/scrubbed_system_logs_fetcher.h" @@ -30,7 +29,12 @@ using SystemInformationList = // the pieces are available. class FeedbackService : public base::SupportsWeakPtr<FeedbackService> { public: + // Callback invoked when the feedback report is ready to be sent. + // True will be passed to indicate that it is being successfully sent now, + // and false to indicate that it will be delayed (usually due to being + // offline). using SendFeedbackCallback = base::Callback<void(bool)>; + using GetSystemInformationCallback = base::Callback<void(const SystemInformationList&)>; diff --git a/chromium/chrome/browser/extensions/api/file_handlers/mime_util_unittest.cc b/chromium/chrome/browser/extensions/api/file_handlers/mime_util_unittest.cc index defec7fc285..d7aefe9df0f 100644 --- a/chromium/chrome/browser/extensions/api/file_handlers/mime_util_unittest.cc +++ b/chromium/chrome/browser/extensions/api/file_handlers/mime_util_unittest.cc @@ -56,7 +56,7 @@ class FileHandlersMimeUtilTest : public testing::Test { void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); file_system_context_ = - content::CreateFileSystemContextForTesting(NULL, data_dir_.path()); + content::CreateFileSystemContextForTesting(NULL, data_dir_.GetPath()); EXPECT_TRUE(base::CreateTemporaryFile(&html_mime_file_path_)); const std::string kSampleContent = "<html><body></body></html>"; diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_api.cc b/chromium/chrome/browser/extensions/api/file_system/file_system_api.cc index e241caa364d..0a6d7931591 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_system_api.cc +++ b/chromium/chrome/browser/extensions/api/file_system/file_system_api.cc @@ -17,7 +17,6 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/strings/string_util.h" @@ -75,7 +74,6 @@ #include "chrome/browser/extensions/api/file_system/request_file_system_dialog_view.h" #include "chrome/browser/extensions/api/file_system/request_file_system_notification.h" #include "chrome/browser/ui/simple_message_box.h" -#include "components/prefs/testing_pref_service.h" #include "components/user_manager/user_manager.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_registry.h" @@ -196,7 +194,7 @@ bool GetFileTypesFromAcceptOption( return false; if (accept_option.description.get()) - *description = base::UTF8ToUTF16(*accept_option.description.get()); + *description = base::UTF8ToUTF16(*accept_option.description); else if (description_id) *description = l10n_util::GetStringUTF16(description_id); @@ -320,10 +318,10 @@ void DispatchVolumeListChangeEvent(Profile* profile) { continue; event_router->DispatchEventToExtension( extension->id(), - base::WrapUnique(new Event( + base::MakeUnique<Event>( events::FILE_SYSTEM_ON_VOLUME_LIST_CHANGED, api::file_system::OnVolumeListChanged::kEventName, - api::file_system::OnVolumeListChanged::Create(event_args)))); + api::file_system::OnVolumeListChanged::Create(event_args))); } } @@ -442,7 +440,7 @@ void ConsentProviderDelegate::ShowDialog( } RequestFileSystemDialogView::ShowDialog(web_contents, extension, volume, - writable, base::Bind(callback)); + writable, callback); } void ConsentProviderDelegate::ShowNotification( @@ -461,7 +459,7 @@ bool ConsentProviderDelegate::IsAutoLaunched(const Extension& extension) { bool ConsentProviderDelegate::IsWhitelistedComponent( const Extension& extension) { - for (const auto& whitelisted_id : kRequestFileSystemComponentWhitelist) { + for (auto* whitelisted_id : kRequestFileSystemComponentWhitelist) { if (extension.id().compare(whitelisted_id) == 0) return true; } @@ -476,21 +474,23 @@ bool ConsentProviderDelegate::IsWhitelistedComponent( using file_system_api::ConsentProvider; #endif -bool FileSystemGetDisplayPathFunction::RunSync() { +ExtensionFunction::ResponseAction FileSystemGetDisplayPathFunction::Run() { std::string filesystem_name; std::string filesystem_path; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name)); EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path)); base::FilePath file_path; + std::string error; if (!app_file_handler_util::ValidateFileEntryAndGetPath( filesystem_name, filesystem_path, - render_frame_host()->GetProcess()->GetID(), &file_path, &error_)) - return false; + render_frame_host()->GetProcess()->GetID(), &file_path, &error)) { + return RespondNow(Error(error)); + } file_path = path_util::PrettifyPath(file_path); - SetResult(base::MakeUnique<base::StringValue>(file_path.value())); - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::StringValue>(file_path.value()))); } FileSystemEntryFunction::FileSystemEntryFunction() @@ -613,17 +613,15 @@ void FileSystemGetWritableEntryFunction::SetIsDirectoryOnFileThread() { } } -bool FileSystemIsWritableEntryFunction::RunSync() { +ExtensionFunction::ResponseAction FileSystemIsWritableEntryFunction::Run() { std::string filesystem_name; std::string filesystem_path; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name)); EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path)); std::string filesystem_id; - if (!storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id)) { - error_ = app_file_handler_util::kInvalidParameters; - return false; - } + if (!storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id)) + return RespondNow(Error(app_file_handler_util::kInvalidParameters)); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); @@ -631,8 +629,8 @@ bool FileSystemIsWritableEntryFunction::RunSync() { bool is_writable = policy->CanReadWriteFileSystem(renderer_id, filesystem_id); - SetResult(base::MakeUnique<base::FundamentalValue>(is_writable)); - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(is_writable))); } // Handles showing a dialog to the user to ask for the filename for a file to @@ -1194,13 +1192,12 @@ void FileSystemRetainEntryFunction::RetainFileEntry( SendResponse(true); } -bool FileSystemIsRestorableFunction::RunSync() { +ExtensionFunction::ResponseAction FileSystemIsRestorableFunction::Run() { std::string entry_id; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &entry_id)); - SetResult(base::MakeUnique<base::FundamentalValue>( - SavedFilesService::Get(GetProfile()) - ->IsRegistered(extension_->id(), entry_id))); - return true; + return RespondNow(OneArgument(base::MakeUnique<base::FundamentalValue>( + SavedFilesService::Get(Profile::FromBrowserContext(browser_context())) + ->IsRegistered(extension_->id(), entry_id)))); } bool FileSystemRestoreEntryFunction::RunAsync() { @@ -1231,22 +1228,19 @@ bool FileSystemRestoreEntryFunction::RunAsync() { return true; } -bool FileSystemObserveDirectoryFunction::RunSync() { +ExtensionFunction::ResponseAction FileSystemObserveDirectoryFunction::Run() { NOTIMPLEMENTED(); - error_ = kUnknownIdError; - return false; + return RespondNow(Error(kUnknownIdError)); } -bool FileSystemUnobserveEntryFunction::RunSync() { +ExtensionFunction::ResponseAction FileSystemUnobserveEntryFunction::Run() { NOTIMPLEMENTED(); - error_ = kUnknownIdError; - return false; + return RespondNow(Error(kUnknownIdError)); } -bool FileSystemGetObservedEntriesFunction::RunSync() { +ExtensionFunction::ResponseAction FileSystemGetObservedEntriesFunction::Run() { NOTIMPLEMENTED(); - error_ = kUnknownIdError; - return false; + return RespondNow(Error(kUnknownIdError)); } #if !defined(OS_CHROMEOS) @@ -1336,13 +1330,11 @@ void FileSystemRequestFileSystemFunction::OnConsentReceived( switch (result) { case ConsentProvider::CONSENT_REJECTED: - SetError(kSecurityError); - SendResponse(false); + Respond(Error(kSecurityError)); return; case ConsentProvider::CONSENT_IMPOSSIBLE: - SetError(kConsentImpossible); - SendResponse(false); + Respond(Error(kConsentImpossible)); return; case ConsentProvider::CONSENT_GRANTED: @@ -1350,8 +1342,7 @@ void FileSystemRequestFileSystemFunction::OnConsentReceived( } if (!volume.get()) { - SetError(kVolumeNotFoundError); - SendResponse(false); + Respond(Error(kVolumeNotFoundError)); return; } @@ -1366,8 +1357,7 @@ void FileSystemRequestFileSystemFunction::OnConsentReceived( base::FilePath virtual_path; if (!backend->GetVirtualPath(volume->mount_path(), &virtual_path)) { - SetError(kSecurityError); - SendResponse(false); + Respond(Error(kSecurityError)); return; } @@ -1390,8 +1380,7 @@ void FileSystemRequestFileSystemFunction::OnConsentReceived( std::string() /* file_system_id */, original_url.path(), ®ister_name); if (file_system_id.empty()) { - SetError(kSecurityError); - SendResponse(false); + Respond(Error(kSecurityError)); return; } @@ -1426,8 +1415,7 @@ void FileSystemRequestFileSystemFunction::OnConsentReceived( dict->SetString("file_system_id", file_system_id); dict->SetString("file_system_path", register_name); - SetResult(std::move(dict)); - SendResponse(true); + Respond(OneArgument(std::move(dict))); } FileSystemGetVolumeListFunction::FileSystemGetVolumeListFunction() diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_api.h b/chromium/chrome/browser/extensions/api/file_system/file_system_api.h index 75113b61cb8..740c44706c1 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_system_api.h +++ b/chromium/chrome/browser/extensions/api/file_system/file_system_api.h @@ -143,14 +143,14 @@ class ConsentProviderDelegate : public ConsentProvider::DelegateInterface { } // namespace file_system_api -class FileSystemGetDisplayPathFunction : public ChromeSyncExtensionFunction { +class FileSystemGetDisplayPathFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.getDisplayPath", FILESYSTEM_GETDISPLAYPATH) protected: ~FileSystemGetDisplayPathFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class FileSystemEntryFunction : public ChromeAsyncExtensionFunction { @@ -206,14 +206,14 @@ class FileSystemGetWritableEntryFunction : public FileSystemEntryFunction { base::FilePath path_; }; -class FileSystemIsWritableEntryFunction : public ChromeSyncExtensionFunction { +class FileSystemIsWritableEntryFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.isWritableEntry", FILESYSTEM_ISWRITABLEENTRY) protected: ~FileSystemIsWritableEntryFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class FileSystemChooseEntryFunction : public FileSystemEntryFunction { @@ -299,13 +299,13 @@ class FileSystemRetainEntryFunction : public ChromeAsyncExtensionFunction { std::unique_ptr<base::File::Info> file_info); }; -class FileSystemIsRestorableFunction : public ChromeSyncExtensionFunction { +class FileSystemIsRestorableFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.isRestorable", FILESYSTEM_ISRESTORABLE) protected: ~FileSystemIsRestorableFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; class FileSystemRestoreEntryFunction : public FileSystemEntryFunction { @@ -317,35 +317,34 @@ class FileSystemRestoreEntryFunction : public FileSystemEntryFunction { bool RunAsync() override; }; -class FileSystemObserveDirectoryFunction : public ChromeSyncExtensionFunction { +class FileSystemObserveDirectoryFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.observeDirectory", FILESYSTEM_OBSERVEDIRECTORY) protected: ~FileSystemObserveDirectoryFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class FileSystemUnobserveEntryFunction : public ChromeSyncExtensionFunction { +class FileSystemUnobserveEntryFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.unobserveEntry", FILESYSTEM_UNOBSERVEENTRY) protected: ~FileSystemUnobserveEntryFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class FileSystemGetObservedEntriesFunction - : public ChromeSyncExtensionFunction { +class FileSystemGetObservedEntriesFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.getObservedEntries", FILESYSTEM_GETOBSERVEDENTRIES); protected: ~FileSystemGetObservedEntriesFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; #if !defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc index 00f08257ec6..3a3b841e71e 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc +++ b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc @@ -90,9 +90,10 @@ class FileSystemApiTest : public PlatformAppBrowserTest { return base::FilePath(); } FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest( - "test_temp", temp_dir_.path()); + "test_temp", temp_dir_.GetPath()); - base::FilePath destination = temp_dir_.path().AppendASCII(destination_name); + base::FilePath destination = + temp_dir_.GetPath().AppendASCII(destination_name); if (copy_gold) { base::FilePath source = test_root_folder_.AppendASCII("gold.txt"); EXPECT_TRUE(base::CopyFile(source, destination)); @@ -108,13 +109,13 @@ class FileSystemApiTest : public PlatformAppBrowserTest { return std::vector<base::FilePath>(); } FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest( - "test_temp", temp_dir_.path()); + "test_temp", temp_dir_.GetPath()); std::vector<base::FilePath> result; for (std::vector<std::string>::const_iterator it = destination_names.begin(); it != destination_names.end(); ++it) { - base::FilePath destination = temp_dir_.path().AppendASCII(*it); + base::FilePath destination = temp_dir_.GetPath().AppendASCII(*it); if (copy_gold) { base::FilePath source = test_root_folder_.AppendASCII("gold.txt"); EXPECT_TRUE(base::CopyFile(source, destination)); diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc index 20c7bda8b0a..ecab8750f53 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc @@ -160,7 +160,7 @@ class FileSystemApiTestForDrive : public PlatformAppBrowserTest { integration_service_ = new drive::DriveIntegrationService( profile, NULL, fake_drive_service_, std::string(), - test_cache_root_.path(), NULL); + test_cache_root_.GetPath(), NULL); return integration_service_; } @@ -244,7 +244,7 @@ class FileSystemApiTestForRequestFileSystem : public PlatformAppBrowserTest { void CreateTestingFileSystem(const std::string& mount_point_name, bool read_only) { const base::FilePath mount_point_path = - temp_dir_.path().Append(mount_point_name); + temp_dir_.GetPath().Append(mount_point_name); ASSERT_TRUE(base::CreateDirectory(mount_point_path)); ASSERT_TRUE( base::CreateDirectory(mount_point_path.Append(kChildDirectory))); @@ -493,7 +493,7 @@ IN_PROC_BROWSER_TEST_F(FileSystemApiTestForRequestFileSystem, profile(), extensions::api::file_system::OnVolumeListChanged::kEventName, kTestingExtensionId, base::Bind(&FileSystemApiTestForRequestFileSystem::MountFakeVolume, - this)); + base::Unretained(this))); ASSERT_TRUE(RunPlatformAppTest("api_test/file_system/on_volume_list_changed")) << message_; diff --git a/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc b/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc index 7c910362a70..ad6bd8a334c 100644 --- a/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc +++ b/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc @@ -113,10 +113,10 @@ RequestFileSystemNotification::~RequestFileSystemNotification() { void RequestFileSystemNotification::Show( std::unique_ptr<Notification> notification) { - pending_notification_.reset(notification.release()); + pending_notification_ = std::move(notification); // If the extension icon is not known yet, then defer showing the notification // until it is (from SetAppImage). - if (!extension_icon_.get()) + if (!extension_icon_) return; pending_notification_->set_icon(*extension_icon_.get()); diff --git a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc index c05bcfaeebf..9d60a6ce23c 100644 --- a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc +++ b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc @@ -180,11 +180,11 @@ void FontSettingsEventRouter::OnFontNamePrefChanged( font_name = MaybeGetLocalizedFontName(font_name); base::ListValue args; - base::DictionaryValue* dict = new base::DictionaryValue(); - args.Append(dict); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString(kFontIdKey, font_name); dict->SetString(kGenericFamilyKey, generic_family); dict->SetString(kScriptKey, script); + args.Append(std::move(dict)); extensions::preference_helpers::DispatchEventToExtensions( profile_, events::FONT_SETTINGS_ON_FONT_CHANGED, @@ -202,9 +202,9 @@ void FontSettingsEventRouter::OnFontPrefChanged( CHECK(pref); base::ListValue args; - base::DictionaryValue* dict = new base::DictionaryValue(); - args.Append(dict); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->Set(key, pref->GetValue()->DeepCopy()); + args.Append(std::move(dict)); extensions::preference_helpers::DispatchEventToExtensions( profile_, histogram_value, event_name, &args, @@ -227,11 +227,10 @@ FontSettingsAPI::GetFactoryInstance() { return g_factory.Pointer(); } -bool FontSettingsClearFontFunction::RunSync() { - if (GetProfile()->IsOffTheRecord()) { - error_ = kSetFromIncognitoError; - return false; - } +ExtensionFunction::ResponseAction FontSettingsClearFontFunction::Run() { + Profile* profile = Profile::FromBrowserContext(browser_context()); + if (profile->IsOffTheRecord()) + return RespondNow(Error(kSetFromIncognitoError)); std::unique_ptr<fonts::ClearFont::Params> params( fonts::ClearFont::Params::Create(*args_)); @@ -241,15 +240,14 @@ bool FontSettingsClearFontFunction::RunSync() { params->details.script); // Ensure |pref_path| really is for a registered per-script font pref. - EXTENSION_FUNCTION_VALIDATE( - GetProfile()->GetPrefs()->FindPreference(pref_path)); + EXTENSION_FUNCTION_VALIDATE(profile->GetPrefs()->FindPreference(pref_path)); - PreferenceAPI::Get(GetProfile())->RemoveExtensionControlledPref( + PreferenceAPI::Get(profile)->RemoveExtensionControlledPref( extension_id(), pref_path, kExtensionPrefsScopeRegular); - return true; + return RespondNow(NoArguments()); } -bool FontSettingsGetFontFunction::RunSync() { +ExtensionFunction::ResponseAction FontSettingsGetFontFunction::Run() { std::unique_ptr<fonts::GetFont::Params> params( fonts::GetFont::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -257,7 +255,8 @@ bool FontSettingsGetFontFunction::RunSync() { std::string pref_path = GetFontNamePrefPath(params->details.generic_family, params->details.script); - PrefService* prefs = GetProfile()->GetPrefs(); + Profile* profile = Profile::FromBrowserContext(browser_context()); + PrefService* prefs = profile->GetPrefs(); const PrefService::Preference* pref = prefs->FindPreference(pref_path); @@ -270,21 +269,19 @@ bool FontSettingsGetFontFunction::RunSync() { // getting level of control. const bool kIncognito = false; std::string level_of_control = - extensions::preference_helpers::GetLevelOfControl( - GetProfile(), extension_id(), pref_path, kIncognito); + extensions::preference_helpers::GetLevelOfControl(profile, extension_id(), + pref_path, kIncognito); std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); result->SetString(kFontIdKey, font_name); result->SetString(kLevelOfControlKey, level_of_control); - SetResult(std::move(result)); - return true; + return RespondNow(OneArgument(std::move(result))); } -bool FontSettingsSetFontFunction::RunSync() { - if (GetProfile()->IsOffTheRecord()) { - error_ = kSetFromIncognitoError; - return false; - } +ExtensionFunction::ResponseAction FontSettingsSetFontFunction::Run() { + Profile* profile = Profile::FromBrowserContext(browser_context()); + if (profile->IsOffTheRecord()) + return RespondNow(Error(kSetFromIncognitoError)); std::unique_ptr<fonts::SetFont::Params> params( fonts::SetFont::Params::Create(*args_)); @@ -294,15 +291,12 @@ bool FontSettingsSetFontFunction::RunSync() { params->details.script); // Ensure |pref_path| really is for a registered font pref. - EXTENSION_FUNCTION_VALIDATE( - GetProfile()->GetPrefs()->FindPreference(pref_path)); + EXTENSION_FUNCTION_VALIDATE(profile->GetPrefs()->FindPreference(pref_path)); - PreferenceAPI::Get(GetProfile())->SetExtensionControlledPref( - extension_id(), - pref_path, - kExtensionPrefsScopeRegular, + PreferenceAPI::Get(profile)->SetExtensionControlledPref( + extension_id(), pref_path, kExtensionPrefsScopeRegular, new base::StringValue(params->details.font_id)); - return true; + return RespondNow(NoArguments()); } bool FontSettingsGetFontListFunction::RunAsync() { @@ -351,19 +345,19 @@ bool FontSettingsGetFontListFunction::CopyFontsToResult( return true; } -bool ClearFontPrefExtensionFunction::RunSync() { - if (GetProfile()->IsOffTheRecord()) { - error_ = kSetFromIncognitoError; - return false; - } +ExtensionFunction::ResponseAction ClearFontPrefExtensionFunction::Run() { + Profile* profile = Profile::FromBrowserContext(browser_context()); + if (profile->IsOffTheRecord()) + return RespondNow(Error(kSetFromIncognitoError)); - PreferenceAPI::Get(GetProfile())->RemoveExtensionControlledPref( + PreferenceAPI::Get(profile)->RemoveExtensionControlledPref( extension_id(), GetPrefName(), kExtensionPrefsScopeRegular); - return true; + return RespondNow(NoArguments()); } -bool GetFontPrefExtensionFunction::RunSync() { - PrefService* prefs = GetProfile()->GetPrefs(); +ExtensionFunction::ResponseAction GetFontPrefExtensionFunction::Run() { + Profile* profile = Profile::FromBrowserContext(browser_context()); + PrefService* prefs = profile->GetPrefs(); const PrefService::Preference* pref = prefs->FindPreference(GetPrefName()); EXTENSION_FUNCTION_VALIDATE(pref); @@ -373,20 +367,18 @@ bool GetFontPrefExtensionFunction::RunSync() { std::string level_of_control = extensions::preference_helpers::GetLevelOfControl( - GetProfile(), extension_id(), GetPrefName(), kIncognito); + profile, extension_id(), GetPrefName(), kIncognito); std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); result->Set(GetKey(), pref->GetValue()->DeepCopy()); result->SetString(kLevelOfControlKey, level_of_control); - SetResult(std::move(result)); - return true; + return RespondNow(OneArgument(std::move(result))); } -bool SetFontPrefExtensionFunction::RunSync() { - if (GetProfile()->IsOffTheRecord()) { - error_ = kSetFromIncognitoError; - return false; - } +ExtensionFunction::ResponseAction SetFontPrefExtensionFunction::Run() { + Profile* profile = Profile::FromBrowserContext(browser_context()); + if (profile->IsOffTheRecord()) + return RespondNow(Error(kSetFromIncognitoError)); base::DictionaryValue* details = NULL; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); @@ -394,12 +386,10 @@ bool SetFontPrefExtensionFunction::RunSync() { base::Value* value; EXTENSION_FUNCTION_VALIDATE(details->Get(GetKey(), &value)); - PreferenceAPI::Get(GetProfile()) - ->SetExtensionControlledPref(extension_id(), - GetPrefName(), - kExtensionPrefsScopeRegular, - value->DeepCopy()); - return true; + PreferenceAPI::Get(profile)->SetExtensionControlledPref( + extension_id(), GetPrefName(), kExtensionPrefsScopeRegular, + value->DeepCopy()); + return RespondNow(NoArguments()); } const char* FontSettingsClearDefaultFontSizeFunction::GetPrefName() { 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 4f62fc187a9..964535c887f 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 @@ -99,7 +99,7 @@ class FontSettingsAPI : public BrowserContextKeyedAPI { }; // fontSettings.clearFont API function. -class FontSettingsClearFontFunction : public ChromeSyncExtensionFunction { +class FontSettingsClearFontFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.clearFont", FONTSETTINGS_CLEARFONT) @@ -109,11 +109,11 @@ class FontSettingsClearFontFunction : public ChromeSyncExtensionFunction { ~FontSettingsClearFontFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // fontSettings.getFont API function. -class FontSettingsGetFontFunction : public ChromeSyncExtensionFunction { +class FontSettingsGetFontFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.getFont", FONTSETTINGS_GETFONT) @@ -121,11 +121,11 @@ class FontSettingsGetFontFunction : public ChromeSyncExtensionFunction { ~FontSettingsGetFontFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // fontSettings.setFont API function. -class FontSettingsSetFontFunction : public ChromeSyncExtensionFunction { +class FontSettingsSetFontFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.setFont", FONTSETTINGS_SETFONT) @@ -133,7 +133,7 @@ class FontSettingsSetFontFunction : public ChromeSyncExtensionFunction { ~FontSettingsSetFontFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // fontSettings.getFontList API function. @@ -154,12 +154,12 @@ class FontSettingsGetFontListFunction : public ChromeAsyncExtensionFunction { }; // Base class for extension API functions that clear a browser font pref. -class ClearFontPrefExtensionFunction : public ChromeSyncExtensionFunction { +class ClearFontPrefExtensionFunction : public UIThreadExtensionFunction { protected: ~ClearFontPrefExtensionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; // Implementations should return the name of the preference to clear, like // "webkit.webprefs.default_font_size". @@ -167,12 +167,12 @@ class ClearFontPrefExtensionFunction : public ChromeSyncExtensionFunction { }; // Base class for extension API functions that get a browser font pref. -class GetFontPrefExtensionFunction : public ChromeSyncExtensionFunction { +class GetFontPrefExtensionFunction : public UIThreadExtensionFunction { protected: ~GetFontPrefExtensionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; // Implementations should return the name of the preference to get, like // "webkit.webprefs.default_font_size". @@ -184,12 +184,12 @@ class GetFontPrefExtensionFunction : public ChromeSyncExtensionFunction { }; // Base class for extension API functions that set a browser font pref. -class SetFontPrefExtensionFunction : public ChromeSyncExtensionFunction { +class SetFontPrefExtensionFunction : public UIThreadExtensionFunction { protected: ~SetFontPrefExtensionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; // Implementations should return the name of the preference to set, like // "webkit.webprefs.default_font_size". diff --git a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter.cc b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter.cc index 68f2298deb4..0a4fb718a9c 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter.cc +++ b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter.cc @@ -29,7 +29,7 @@ class PrivetV3ContextGetter::CertVerifier : public net::CertVerifier { net::CertVerifyResult* verify_result, const net::CompletionCallback& callback, std::unique_ptr<Request>* out_req, - const net::BoundNetLog& net_log) override { + const net::NetLogWithSource& net_log) override { verify_result->Reset(); verify_result->verified_cert = params.certificate(); diff --git a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc index 6d3d6cd9979..a749c1abdf8 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc +++ b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc @@ -33,7 +33,7 @@ class PrivetV3ContextGetterTest : public testing::Test, void SetUp() override { context_getter_ = new extensions::PrivetV3ContextGetter( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)); + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); } void OnURLFetchComplete(const net::URLFetcher* source) override { diff --git a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.cc b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.cc index 5dfa456aa8a..adf66eb114f 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.cc +++ b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.cc @@ -10,6 +10,7 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -356,8 +357,8 @@ void PrivetV3Session::OnPairingConfirmDone( } std::string auth_code(hmac.DigestLength(), ' '); - if (!hmac.Sign(session_id_, - reinterpret_cast<unsigned char*>(string_as_array(&auth_code)), + if (!hmac.Sign(session_id_, reinterpret_cast<unsigned char*>( + base::string_as_array(&auth_code)), auth_code.size())) { LOG(FATAL) << "Signing failed"; return callback.Run(Result::STATUS_SESSIONERROR); @@ -486,7 +487,7 @@ net::URLFetcher* PrivetV3Session::CreateFetcher( FetcherDelegate* fetcher = new FetcherDelegate(weak_ptr_factory_.GetWeakPtr(), callback); if (!orphaned) - fetchers_.push_back(fetcher); + fetchers_.push_back(base::WrapUnique(fetcher)); net::URLFetcher* url_fetcher = fetcher->CreateURLFetcher(url, request_type, orphaned); url_fetcher->SetLoadFlags(url_fetcher->GetLoadFlags() | @@ -500,7 +501,14 @@ net::URLFetcher* PrivetV3Session::CreateFetcher( } void PrivetV3Session::DeleteFetcher(const FetcherDelegate* fetcher) { - fetchers_.erase(std::find(fetchers_.begin(), fetchers_.end(), fetcher)); + for (std::vector<std::unique_ptr<FetcherDelegate>>::iterator iter = + fetchers_.begin(); + iter != fetchers_.end(); ++iter) { + if (iter->get() == fetcher) { + fetchers_.erase(iter); + break; + } + } } void PrivetV3Session::Cancel() { diff --git a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.h b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.h index f653959bfda..8a29a5f27c0 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.h +++ b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session.h @@ -13,7 +13,6 @@ #include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "chrome/common/extensions/api/gcd_private.h" #include "net/url_request/url_fetcher.h" @@ -125,7 +124,7 @@ class PrivetV3Session { bool use_https_ = false; // List of fetches to cancel when session is destroyed. - ScopedVector<FetcherDelegate> fetchers_; + std::vector<std::unique_ptr<FetcherDelegate>> fetchers_; // Intercepts POST requests. Used by tests only. base::Callback<void(const base::DictionaryValue&)> on_post_data_; diff --git a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session_unittest.cc b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session_unittest.cc index 77f6e2f122d..e60d8b003ca 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session_unittest.cc +++ b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_session_unittest.cc @@ -232,8 +232,9 @@ TEST_F(PrivetV3SessionTest, Pairing) { const std::string& key = spake.GetUnverifiedKey(); EXPECT_TRUE(hmac.Init(key)); std::string signature(hmac.DigestLength(), ' '); - EXPECT_TRUE(hmac.Sign(fingerprint, reinterpret_cast<unsigned char*>( - string_as_array(&signature)), + EXPECT_TRUE(hmac.Sign(fingerprint, + reinterpret_cast<unsigned char*>( + base::string_as_array(&signature)), signature.size())); std::string signature_base64; diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc index c58cf8f26a4..3cc048c4a5c 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc @@ -12,7 +12,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "chrome/browser/profiles/profile.h" diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc index 04bb253c0d6..f2379ca236d 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc @@ -11,7 +11,7 @@ #include "chrome/browser/services/gcm/gcm_profile_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" -#include "components/browser_sync/common/browser_sync_switches.h" +#include "components/browser_sync/browser_sync_switches.h" #include "extensions/test/result_catcher.h" using extensions::ResultCatcher; diff --git a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc index 6b87899b4ad..61aac818a5b 100644 --- a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc +++ b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc @@ -133,8 +133,7 @@ void HotwordPrivateEventService::OnMicrophoneStateChanged(bool enabled) { void HotwordPrivateEventService::SignalEvent( events::HistogramValue histogram_value, const std::string& event_name) { - SignalEvent(histogram_value, event_name, - base::WrapUnique(new base::ListValue())); + SignalEvent(histogram_value, event_name, base::MakeUnique<base::ListValue>()); } void HotwordPrivateEventService::SignalEvent( @@ -150,49 +149,55 @@ void HotwordPrivateEventService::SignalEvent( router->BroadcastEvent(std::move(event)); } -bool HotwordPrivateSetEnabledFunction::RunSync() { +ExtensionFunction::ResponseAction HotwordPrivateSetEnabledFunction::Run() { std::unique_ptr<api::hotword_private::SetEnabled::Params> params( api::hotword_private::SetEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - PrefService* prefs = GetProfile()->GetPrefs(); + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); prefs->SetBoolean(prefs::kHotwordSearchEnabled, params->state); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateSetAudioLoggingEnabledFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateSetAudioLoggingEnabledFunction::Run() { std::unique_ptr<api::hotword_private::SetAudioLoggingEnabled::Params> params( api::hotword_private::SetAudioLoggingEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); // TODO(kcarattini): Sync the chrome pref with the account-level // Audio History setting. - PrefService* prefs = GetProfile()->GetPrefs(); + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, params->state); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction::Run() { std::unique_ptr<api::hotword_private::SetHotwordAlwaysOnSearchEnabled::Params> params( api::hotword_private::SetHotwordAlwaysOnSearchEnabled::Params::Create( *args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - PrefService* prefs = GetProfile()->GetPrefs(); + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, params->state); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateGetStatusFunction::RunSync() { +ExtensionFunction::ResponseAction HotwordPrivateGetStatusFunction::Run() { std::unique_ptr<api::hotword_private::GetStatus::Params> params( api::hotword_private::GetStatus::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); api::hotword_private::StatusDetails result; + Profile* profile = Profile::FromBrowserContext(browser_context()); HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); + HotwordServiceFactory::GetForProfile(profile); if (!hotword_service) { result.available = false; result.always_on_available = false; @@ -218,28 +223,29 @@ bool HotwordPrivateGetStatusFunction::RunSync() { HotwordService::IsHotwordHardwareAvailable(); } - PrefService* prefs = GetProfile()->GetPrefs(); + PrefService* prefs = profile->GetPrefs(); result.enabled_set = prefs->HasPrefPath(prefs::kHotwordSearchEnabled); - SetResult(result.ToValue()); - return true; + return RespondNow(OneArgument(result.ToValue())); } -bool HotwordPrivateSetHotwordSessionStateFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateSetHotwordSessionStateFunction::Run() { std::unique_ptr<api::hotword_private::SetHotwordSessionState::Params> params( api::hotword_private::SetHotwordSessionState::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); + HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); if (hotword_service && hotword_service->client() && !hotword_service->IsTraining()) hotword_service->client()->OnHotwordStateChanged(params->started); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateNotifyHotwordRecognitionFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateNotifyHotwordRecognitionFunction::Run() { std::unique_ptr<api::hotword_private::NotifyHotwordRecognition::Params> params(api::hotword_private::NotifyHotwordRecognition::Params::Create( *args_)); @@ -256,8 +262,9 @@ bool HotwordPrivateNotifyHotwordRecognitionFunction::RunSync() { preamble->sample_data.swap(params->log->buffer); } + Profile* profile = Profile::FromBrowserContext(browser_context()); HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); + HotwordServiceFactory::GetForProfile(profile); if (hotword_service) { if (hotword_service->IsTraining()) { hotword_service->NotifyHotwordTriggered(); @@ -266,77 +273,80 @@ bool HotwordPrivateNotifyHotwordRecognitionFunction::RunSync() { } else if (hotword_service->IsAlwaysOnEnabled()) { AppListService* app_list_service = AppListService::Get(); CHECK(app_list_service); - app_list_service->ShowForVoiceSearch(GetProfile(), preamble); + app_list_service->ShowForVoiceSearch(profile, preamble); } } - return true; + + return RespondNow(NoArguments()); } -bool HotwordPrivateGetLaunchStateFunction::RunSync() { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); +ExtensionFunction::ResponseAction HotwordPrivateGetLaunchStateFunction::Run() { + HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); if (!hotword_service) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; + return RespondNow( + Error(hotword_private_constants::kHotwordServiceUnavailable)); } api::hotword_private::LaunchState result; result.launch_mode = hotword_service->GetHotwordAudioVerificationLaunchMode(); - SetResult(result.ToValue()); - return true; + return RespondNow(OneArgument(result.ToValue())); } -bool HotwordPrivateStartTrainingFunction::RunSync() { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); +ExtensionFunction::ResponseAction HotwordPrivateStartTrainingFunction::Run() { + HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); if (!hotword_service) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; + return RespondNow( + Error(hotword_private_constants::kHotwordServiceUnavailable)); } hotword_service->StartTraining(); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateFinalizeSpeakerModelFunction::RunSync() { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); +ExtensionFunction::ResponseAction +HotwordPrivateFinalizeSpeakerModelFunction::Run() { + HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); if (!hotword_service) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; + return RespondNow( + Error(hotword_private_constants::kHotwordServiceUnavailable)); } hotword_service->FinalizeSpeakerModel(); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateNotifySpeakerModelSavedFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateNotifySpeakerModelSavedFunction::Run() { HotwordPrivateEventService* event_service = BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get( - GetProfile()); + Profile::FromBrowserContext(browser_context())); if (!event_service) { - error_ = hotword_private_constants::kHotwordEventServiceUnavailable; - return false; + return RespondNow( + Error(hotword_private_constants::kHotwordEventServiceUnavailable)); } event_service->OnSpeakerModelSaved(); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateStopTrainingFunction::RunSync() { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); +ExtensionFunction::ResponseAction HotwordPrivateStopTrainingFunction::Run() { + HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); if (!hotword_service) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; + return RespondNow( + Error(hotword_private_constants::kHotwordServiceUnavailable)); } hotword_service->StopTraining(); - return true; + return RespondNow(NoArguments()); } -bool HotwordPrivateGetLocalizedStringsFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateGetLocalizedStringsFunction::Run() { #if defined(OS_CHROMEOS) base::string16 device_type = ash::GetChromeOSDeviceName(); #else @@ -455,8 +465,7 @@ bool HotwordPrivateGetLocalizedStringsFunction::RunSync() { const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, localized_strings.get()); - SetResult(std::move(localized_strings)); - return true; + return RespondNow(OneArgument(std::move(localized_strings))); } bool HotwordPrivateSetAudioHistoryEnabledFunction::RunAsync() { @@ -512,19 +521,20 @@ void HotwordPrivateGetAudioHistoryEnabledFunction::SetResultAndSendResponse( SendResponse(true); } -bool HotwordPrivateSpeakerModelExistsResultFunction::RunSync() { +ExtensionFunction::ResponseAction +HotwordPrivateSpeakerModelExistsResultFunction::Run() { std::unique_ptr<api::hotword_private::SpeakerModelExistsResult::Params> params(api::hotword_private::SpeakerModelExistsResult::Params::Create( *args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); + HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context())); if (!hotword_service) - return false; + return RespondNow(Error(kUnknownErrorDoNotUse)); hotword_service->SpeakerModelExistsComplete(params->exists); - return true; + return RespondNow(NoArguments()); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.h b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.h index 39423ad4fd9..1f3862460a8 100644 --- a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.h +++ b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_api.h @@ -60,8 +60,7 @@ class HotwordPrivateEventService : public BrowserContextKeyedAPI { PrefChangeRegistrar pref_change_registrar_; }; - -class HotwordPrivateSetEnabledFunction : public ChromeSyncExtensionFunction { +class HotwordPrivateSetEnabledFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setEnabled", HOTWORDPRIVATE_SETENABLED) @@ -70,11 +69,11 @@ class HotwordPrivateSetEnabledFunction : public ChromeSyncExtensionFunction { ~HotwordPrivateSetEnabledFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class HotwordPrivateSetAudioLoggingEnabledFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setAudioLoggingEnabled", HOTWORDPRIVATE_SETAUDIOLOGGINGENABLED) @@ -83,11 +82,11 @@ class HotwordPrivateSetAudioLoggingEnabledFunction ~HotwordPrivateSetAudioLoggingEnabledFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setHotwordAlwaysOnSearchEnabled", HOTWORDPRIVATE_SETHOTWORDALWAYSONSEARCHENABLED) @@ -96,10 +95,10 @@ class HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction ~HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class HotwordPrivateGetStatusFunction : public ChromeSyncExtensionFunction { +class HotwordPrivateGetStatusFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getStatus", HOTWORDPRIVATE_GETSTATUS) @@ -108,11 +107,11 @@ class HotwordPrivateGetStatusFunction : public ChromeSyncExtensionFunction { ~HotwordPrivateGetStatusFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class HotwordPrivateSetHotwordSessionStateFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setHotwordSessionState", HOTWORDPRIVATE_SETHOTWORDSESSIONSTATE); @@ -121,11 +120,11 @@ class HotwordPrivateSetHotwordSessionStateFunction ~HotwordPrivateSetHotwordSessionStateFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class HotwordPrivateNotifyHotwordRecognitionFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.notifyHotwordRecognition", HOTWORDPRIVATE_NOTIFYHOTWORDRECOGNITION); @@ -134,11 +133,10 @@ class HotwordPrivateNotifyHotwordRecognitionFunction ~HotwordPrivateNotifyHotwordRecognitionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class HotwordPrivateGetLaunchStateFunction : - public ChromeSyncExtensionFunction { +class HotwordPrivateGetLaunchStateFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getLaunchState", HOTWORDPRIVATE_GETLAUNCHSTATE) @@ -147,11 +145,10 @@ class HotwordPrivateGetLaunchStateFunction : ~HotwordPrivateGetLaunchStateFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class HotwordPrivateStartTrainingFunction : - public ChromeSyncExtensionFunction { +class HotwordPrivateStartTrainingFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.startTraining", HOTWORDPRIVATE_STARTTRAINING) @@ -160,11 +157,11 @@ class HotwordPrivateStartTrainingFunction : ~HotwordPrivateStartTrainingFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class HotwordPrivateFinalizeSpeakerModelFunction : - public ChromeSyncExtensionFunction { +class HotwordPrivateFinalizeSpeakerModelFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.finalizeSpeakerModel", HOTWORDPRIVATE_FINALIZESPEAKERMODEL) @@ -173,11 +170,11 @@ class HotwordPrivateFinalizeSpeakerModelFunction : ~HotwordPrivateFinalizeSpeakerModelFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class HotwordPrivateNotifySpeakerModelSavedFunction : - public ChromeSyncExtensionFunction { +class HotwordPrivateNotifySpeakerModelSavedFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.notifySpeakerModelSaved", HOTWORDPRIVATE_NOTIFYSPEAKERMODELSAVED) @@ -186,11 +183,10 @@ class HotwordPrivateNotifySpeakerModelSavedFunction : ~HotwordPrivateNotifySpeakerModelSavedFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class HotwordPrivateStopTrainingFunction : - public ChromeSyncExtensionFunction { +class HotwordPrivateStopTrainingFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.stopTraining", HOTWORDPRIVATE_STOPTRAINING) @@ -199,11 +195,11 @@ class HotwordPrivateStopTrainingFunction : ~HotwordPrivateStopTrainingFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class HotwordPrivateGetLocalizedStringsFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getLocalizedStrings", HOTWORDPRIVATE_GETLOCALIZEDSTRINGS) @@ -212,7 +208,7 @@ class HotwordPrivateGetLocalizedStringsFunction ~HotwordPrivateGetLocalizedStringsFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class HotwordPrivateSetAudioHistoryEnabledFunction @@ -245,8 +241,8 @@ class HotwordPrivateGetAudioHistoryEnabledFunction void SetResultAndSendResponse(bool success, bool new_enabled_value); }; -class HotwordPrivateSpeakerModelExistsResultFunction : - public ChromeSyncExtensionFunction { +class HotwordPrivateSpeakerModelExistsResultFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hotwordPrivate.speakerModelExistsResult", HOTWORDPRIVATE_SPEAKERMODELEXISTSRESULT) @@ -255,7 +251,7 @@ class HotwordPrivateSpeakerModelExistsResultFunction : ~HotwordPrivateSpeakerModelExistsResultFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc index 2d44d9b2cf0..3c89ec4410a 100644 --- a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc @@ -104,8 +104,7 @@ class MockHotwordService : public HotwordService { } static std::unique_ptr<KeyedService> Build(content::BrowserContext* profile) { - return base::WrapUnique( - new MockHotwordService(static_cast<Profile*>(profile))); + return base::MakeUnique<MockHotwordService>(static_cast<Profile*>(profile)); } LaunchMode GetHotwordAudioVerificationLaunchMode() override { diff --git a/chromium/chrome/browser/extensions/api/i18n/i18n_api.cc b/chromium/chrome/browser/extensions/api/i18n/i18n_api.cc index f95797475b0..ce22beb3588 100644 --- a/chromium/chrome/browser/extensions/api/i18n/i18n_api.cc +++ b/chromium/chrome/browser/extensions/api/i18n/i18n_api.cc @@ -27,9 +27,10 @@ static const char kEmptyAcceptLanguagesError[] = "accept-languages is empty."; } -bool I18nGetAcceptLanguagesFunction::RunSync() { - std::string accept_languages = - GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages); +ExtensionFunction::ResponseAction I18nGetAcceptLanguagesFunction::Run() { + std::string accept_languages = Profile::FromBrowserContext(browser_context()) + ->GetPrefs() + ->GetString(prefs::kAcceptLanguages); // Currently, there are 2 ways to set browser's accept-languages: through UI // or directly modify the preference file. The accept-languages set through // UI is guranteed to be valid, and the accept-languages string returned from @@ -40,23 +41,19 @@ bool I18nGetAcceptLanguagesFunction::RunSync() { // of the language code) on accept-languages set through editing preference // file directly. So, here, we're adding extra checks to be resistant to // crashes caused by data corruption. - if (accept_languages.empty()) { - error_ = kEmptyAcceptLanguagesError; - return false; - } + if (accept_languages.empty()) + return RespondNow(Error(kEmptyAcceptLanguagesError)); std::vector<std::string> languages = base::SplitString( accept_languages, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); languages.erase(std::remove(languages.begin(), languages.end(), ""), languages.end()); - if (languages.empty()) { - error_ = kEmptyAcceptLanguagesError; - return false; - } + if (languages.empty()) + return RespondNow(Error(kEmptyAcceptLanguagesError)); - results_ = GetAcceptLanguages::Results::Create(languages); - return true; + return RespondNow( + ArgumentList(GetAcceptLanguages::Results::Create(languages))); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/i18n/i18n_api.h b/chromium/chrome/browser/extensions/api/i18n/i18n_api.h index 5863aaacf22..5576a36339f 100644 --- a/chromium/chrome/browser/extensions/api/i18n/i18n_api.h +++ b/chromium/chrome/browser/extensions/api/i18n/i18n_api.h @@ -5,16 +5,13 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H_ -#include "chrome/browser/extensions/chrome_extension_function.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" - -class Profile; +#include "extensions/browser/extension_function.h" namespace extensions { -class I18nGetAcceptLanguagesFunction : public ChromeSyncExtensionFunction { +class I18nGetAcceptLanguagesFunction : public UIThreadExtensionFunction { ~I18nGetAcceptLanguagesFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("i18n.getAcceptLanguages", I18N_GETACCEPTLANGUAGES) }; diff --git a/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc b/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc index df1680949db..db534d2d268 100644 --- a/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc +++ b/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc @@ -24,20 +24,17 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, I18NUpdate) { base::ScopedTempDir extension_dir; ASSERT_TRUE(extension_dir.CreateUniqueTempDir()); base::CopyFile( - test_data_dir_.AppendASCII("i18nUpdate") - .AppendASCII("manifest.json"), - extension_dir.path().AppendASCII("manifest.json")); + test_data_dir_.AppendASCII("i18nUpdate").AppendASCII("manifest.json"), + extension_dir.GetPath().AppendASCII("manifest.json")); base::CopyFile( - test_data_dir_.AppendASCII("i18nUpdate") - .AppendASCII("contentscript.js"), - extension_dir.path().AppendASCII("contentscript.js")); + test_data_dir_.AppendASCII("i18nUpdate").AppendASCII("contentscript.js"), + extension_dir.GetPath().AppendASCII("contentscript.js")); base::CopyDirectory( - test_data_dir_.AppendASCII("i18nUpdate") - .AppendASCII("_locales"), - extension_dir.path().AppendASCII("_locales"), - true); + test_data_dir_.AppendASCII("i18nUpdate").AppendASCII("_locales"), + extension_dir.GetPath().AppendASCII("_locales"), true); - const extensions::Extension* extension = LoadExtension(extension_dir.path()); + const extensions::Extension* extension = + LoadExtension(extension_dir.GetPath()); extensions::ResultCatcher catcher; @@ -53,9 +50,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, I18NUpdate) { // Change messages.json file and reload extension. base::CopyFile( - test_data_dir_.AppendASCII("i18nUpdate") - .AppendASCII("messages2.json"), - extension_dir.path().AppendASCII("_locales/en/messages.json")); + test_data_dir_.AppendASCII("i18nUpdate").AppendASCII("messages2.json"), + extension_dir.GetPath().AppendASCII("_locales/en/messages.json")); ReloadExtension(extension->id()); // Check that the i18n message is also changed. diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api.cc b/chromium/chrome/browser/extensions/api/identity/identity_api.cc index b6bce398f01..e4c15c1f896 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_api.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_api.cc @@ -928,18 +928,17 @@ IdentityRemoveCachedAuthTokenFunction:: ~IdentityRemoveCachedAuthTokenFunction() { } -bool IdentityRemoveCachedAuthTokenFunction::RunSync() { - if (GetProfile()->IsOffTheRecord()) { - error_ = identity_constants::kOffTheRecord; - return false; - } +ExtensionFunction::ResponseAction IdentityRemoveCachedAuthTokenFunction::Run() { + if (Profile::FromBrowserContext(browser_context())->IsOffTheRecord()) + return RespondNow(Error(identity_constants::kOffTheRecord)); std::unique_ptr<identity::RemoveCachedAuthToken::Params> params( identity::RemoveCachedAuthToken::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - IdentityAPI::GetFactoryInstance()->Get(GetProfile())->EraseCachedToken( - extension()->id(), params->details.token); - return true; + IdentityAPI::GetFactoryInstance() + ->Get(browser_context()) + ->EraseCachedToken(extension()->id(), params->details.token); + return RespondNow(NoArguments()); } IdentityLaunchWebAuthFlowFunction::IdentityLaunchWebAuthFlowFunction() {} diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api.h b/chromium/chrome/browser/extensions/api/identity/identity_api.h index bf5d77f6d1f..303885c6a07 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_api.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_api.h @@ -318,8 +318,7 @@ class IdentityGetProfileUserInfoFunction ExtensionFunction::ResponseAction Run() override; }; -class IdentityRemoveCachedAuthTokenFunction - : public ChromeSyncExtensionFunction { +class IdentityRemoveCachedAuthTokenFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.removeCachedAuthToken", EXPERIMENTAL_IDENTITY_REMOVECACHEDAUTHTOKEN) @@ -328,8 +327,8 @@ class IdentityRemoveCachedAuthTokenFunction protected: ~IdentityRemoveCachedAuthTokenFunction() override; - // SyncExtensionFunction implementation: - bool RunSync() override; + // ExtensionFunction: + ResponseAction Run() override; }; class IdentityLaunchWebAuthFlowFunction : public ChromeAsyncExtensionFunction, diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc index c6d1abd972f..06d8037fab1 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc @@ -19,7 +19,7 @@ #include "chrome/browser/chromeos/login/users/mock_user_manager.h" #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" -#include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h" +#include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "extensions/common/extension_builder.h" #endif #include "chrome/browser/extensions/api/identity/identity_api.h" @@ -78,45 +78,6 @@ namespace utils = extension_function_test_utils; static const char kAccessToken[] = "auth_token"; static const char kExtensionId[] = "ext_id"; -// This helps us be able to wait until an UIThreadExtensionFunction calls -// SendResponse. -class SendResponseDelegate - : public UIThreadExtensionFunction::DelegateForTests { - public: - SendResponseDelegate() : should_post_quit_(false) {} - - virtual ~SendResponseDelegate() {} - - void set_should_post_quit(bool should_quit) { - should_post_quit_ = should_quit; - } - - bool HasResponse() { - return response_.get() != NULL; - } - - bool GetResponse() { - EXPECT_TRUE(HasResponse()); - return *response_.get(); - } - - void OnSendResponse(UIThreadExtensionFunction* function, - bool success, - bool bad_message) override { - ASSERT_FALSE(bad_message); - ASSERT_FALSE(HasResponse()); - response_.reset(new bool); - *response_ = success; - if (should_post_quit_) { - base::MessageLoopForUI::current()->QuitWhenIdle(); - } - } - - private: - std::unique_ptr<bool> response_; - bool should_post_quit_; -}; - class AsyncExtensionBrowserTest : public ExtensionBrowserTest { protected: // Asynchronous function runner allows tests to manipulate the browser window @@ -124,8 +85,7 @@ class AsyncExtensionBrowserTest : public ExtensionBrowserTest { void RunFunctionAsync( UIThreadExtensionFunction* function, const std::string& args) { - response_delegate_.reset(new SendResponseDelegate); - function->set_test_delegate(response_delegate_.get()); + response_delegate_.reset(new api_test_utils::SendResponseHelper(function)); std::unique_ptr<base::ListValue> parsed_args(utils::ParseList(args)); EXPECT_TRUE(parsed_args.get()) << "Could not parse extension function arguments: " << args; @@ -144,7 +104,8 @@ class AsyncExtensionBrowserTest : public ExtensionBrowserTest { std::string WaitForError(UIThreadExtensionFunction* function) { RunMessageLoopUntilResponse(); - EXPECT_FALSE(function->GetResultList()) << "Did not expect a result"; + CHECK(function->response_type()); + EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type()); return function->GetError(); } @@ -162,16 +123,11 @@ class AsyncExtensionBrowserTest : public ExtensionBrowserTest { private: void RunMessageLoopUntilResponse() { - // If the RunAsync of |function| didn't already call SendResponse, run the - // message loop until they do. - if (!response_delegate_->HasResponse()) { - response_delegate_->set_should_post_quit(true); - content::RunMessageLoop(); - } - EXPECT_TRUE(response_delegate_->HasResponse()); + response_delegate_->WaitForResponse(); + EXPECT_TRUE(response_delegate_->has_response()); } - std::unique_ptr<SendResponseDelegate> response_delegate_; + std::unique_ptr<api_test_utils::SendResponseHelper> response_delegate_; }; class TestHangOAuth2MintTokenFlow : public OAuth2MintTokenFlow { @@ -313,7 +269,7 @@ class FakeGetAuthTokenFunction : public IdentityGetAuthTokenFunction { void set_mint_token_result(TestOAuth2MintTokenFlow::ResultType result_type) { set_mint_token_flow( - base::WrapUnique(new TestOAuth2MintTokenFlow(result_type, this))); + base::MakeUnique<TestOAuth2MintTokenFlow>(result_type, this)); } void set_scope_ui_failure(GaiaWebAuthFlow::Failure failure) { @@ -626,7 +582,7 @@ class IdentityGetProfileUserInfoFunctionTest : public IdentityTestWithSignin { func->set_extension(test_util::CreateEmptyExtension(kExtensionId).get()); std::unique_ptr<base::Value> value( utils::RunFunctionAndReturnSingleResult(func.get(), "[]", browser())); - return api::identity::ProfileUserInfo::FromValue(*value.get()); + return api::identity::ProfileUserInfo::FromValue(*value); } std::unique_ptr<api::identity::ProfileUserInfo> @@ -636,7 +592,7 @@ class IdentityGetProfileUserInfoFunctionTest : public IdentityTestWithSignin { func->set_extension(CreateExtensionWithEmailPermission()); std::unique_ptr<base::Value> value( utils::RunFunctionAndReturnSingleResult(func.get(), "[]", browser())); - return api::identity::ProfileUserInfo::FromValue(*value.get()); + return api::identity::ProfileUserInfo::FromValue(*value); } private: @@ -1249,8 +1205,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoninteractiveShutdown) { scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction()); func->set_extension(extension.get()); - func->set_mint_token_flow( - base::WrapUnique(new TestHangOAuth2MintTokenFlow())); + func->set_mint_token_flow(base::MakeUnique<TestHangOAuth2MintTokenFlow>()); RunFunctionAsync(func.get(), "[{\"interactive\": false}]"); // After the request is canceled, the function will complete. @@ -1570,8 +1525,8 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesDefault) { const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest(); EXPECT_EQ(2ul, token_key->scopes.size()); - EXPECT_TRUE(ContainsKey(token_key->scopes, "scope1")); - EXPECT_TRUE(ContainsKey(token_key->scopes, "scope2")); + EXPECT_TRUE(base::ContainsKey(token_key->scopes, "scope1")); + EXPECT_TRUE(base::ContainsKey(token_key->scopes, "scope2")); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmpty) { @@ -1599,7 +1554,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmail) { const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest(); EXPECT_EQ(1ul, token_key->scopes.size()); - EXPECT_TRUE(ContainsKey(token_key->scopes, "email")); + EXPECT_TRUE(base::ContainsKey(token_key->scopes, "email")); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmailFooBar) { @@ -1616,9 +1571,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmailFooBar) { const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest(); EXPECT_EQ(3ul, token_key->scopes.size()); - EXPECT_TRUE(ContainsKey(token_key->scopes, "email")); - EXPECT_TRUE(ContainsKey(token_key->scopes, "foo")); - EXPECT_TRUE(ContainsKey(token_key->scopes, "bar")); + EXPECT_TRUE(base::ContainsKey(token_key->scopes, "email")); + EXPECT_TRUE(base::ContainsKey(token_key->scopes, "foo")); + EXPECT_TRUE(base::ContainsKey(token_key->scopes, "bar")); } @@ -1640,8 +1595,8 @@ class GetAuthTokenFunctionPublicSessionTest : public GetAuthTokenFunctionTest { // Set up fake install attributes to make the device appeared as // enterprise-managed. - std::unique_ptr<policy::StubEnterpriseInstallAttributes> attributes( - new policy::StubEnterpriseInstallAttributes()); + std::unique_ptr<chromeos::StubInstallAttributes> attributes + = base::MakeUnique<chromeos::StubInstallAttributes>(); attributes->SetDomain("example.com"); attributes->SetRegistrationUser("user@example.com"); policy::BrowserPolicyConnectorChromeOS::SetInstallAttributesForTesting( diff --git a/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc b/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc index ed8e89961fb..74825eb1738 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc @@ -73,8 +73,8 @@ void IdentityMintRequestQueue::RequestCancel( bool IdentityMintRequestQueue::empty(IdentityMintRequestQueue::MintType type, const ExtensionTokenKey& key) { RequestQueueMap& request_queue_map = GetRequestQueueMap(type); - return !ContainsKey(request_queue_map, key) || - (request_queue_map.find(key))->second.empty(); + return !base::ContainsKey(request_queue_map, key) || + (request_queue_map.find(key))->second.empty(); } IdentityMintRequestQueue::RequestQueueMap& diff --git a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc index 4ed98ae02e2..c6c84168512 100644 --- a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc +++ b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc @@ -18,9 +18,11 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/identity_private.h" #include "chrome/common/extensions/extension_constants.h" +#include "chrome/grit/browser_resources.h" #include "components/guest_view/browser/guest_view_base.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" @@ -32,7 +34,7 @@ #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_system.h" -#include "grit/browser_resources.h" +#include "net/http/http_response_headers.h" #include "url/gurl.h" using content::RenderViewHost; @@ -55,6 +57,7 @@ WebAuthFlow::WebAuthFlow( provider_url_(provider_url), mode_(mode), embedded_window_created_(false) { + TRACE_EVENT_ASYNC_BEGIN0("identity", "WebAuthFlow", this); } WebAuthFlow::~WebAuthFlow() { @@ -71,6 +74,7 @@ WebAuthFlow::~WebAuthFlow() { if (app_window_ && app_window_->web_contents()) app_window_->web_contents()->Close(); } + TRACE_EVENT_ASYNC_END0("identity", "WebAuthFlow", this); } void WebAuthFlow::Start() { @@ -177,33 +181,7 @@ void WebAuthFlow::RenderProcessGone(base::TerminationStatus status) { delegate_->OnAuthFlowFailure(WebAuthFlow::WINDOW_CLOSED); } -void WebAuthFlow::DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) { - if (!render_frame_host->GetParent()) - BeforeUrlLoaded(validated_url); -} - -void WebAuthFlow::DidFailProvisionalLoad( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) { - TRACE_EVENT_ASYNC_STEP_PAST1("identity", - "WebAuthFlow", - this, - "DidFailProvisionalLoad", - "error_code", - error_code); - if (delegate_) - delegate_->OnAuthFlowFailure(LOAD_FAILED); -} - void WebAuthFlow::DidGetRedirectForResourceRequest( - content::RenderFrameHost* render_frame_host, const content::ResourceRedirectDetails& details) { BeforeUrlLoaded(details.new_url); } @@ -218,10 +196,32 @@ void WebAuthFlow::DidStopLoading() { AfterUrlLoaded(); } -void WebAuthFlow::DidNavigateMainFrame( - const content::LoadCommittedDetails& details, - const content::FrameNavigateParams& params) { - if (delegate_ && details.http_status_code >= 400) +void WebAuthFlow::DidStartNavigation( + content::NavigationHandle* navigation_handle) { + if (navigation_handle->IsInMainFrame()) + BeforeUrlLoaded(navigation_handle->GetURL()); +} + +void WebAuthFlow::DidFinishNavigation( + content::NavigationHandle* navigation_handle) { + bool failed = false; + + if (navigation_handle->GetNetErrorCode() != net::OK) { + failed = true; + TRACE_EVENT_ASYNC_STEP_PAST1("identity", "WebAuthFlow", this, + "DidFinishNavigationFailure", "error_code", + navigation_handle->GetNetErrorCode()); + } else if (navigation_handle->IsInMainFrame() && + navigation_handle->GetResponseHeaders() && + navigation_handle->GetResponseHeaders()->response_code() >= 400) { + failed = true; + TRACE_EVENT_ASYNC_STEP_PAST1( + "identity", "WebAuthFlow", this, "DidFinishNavigationFailure", + "response_code", + navigation_handle->GetResponseHeaders()->response_code()); + } + + if (failed && delegate_) delegate_->OnAuthFlowFailure(LOAD_FAILED); } diff --git a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h index a5d49653028..0f61451cbc6 100644 --- a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h +++ b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h @@ -103,24 +103,14 @@ class WebAuthFlow : public content::NotificationObserver, // WebContentsObserver implementation. void DidStopLoading() override; - void DidNavigateMainFrame( - const content::LoadCommittedDetails& details, - const content::FrameNavigateParams& params) override; void RenderProcessGone(base::TerminationStatus status) override; - void DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) override; - void DidFailProvisionalLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) override; void DidGetRedirectForResourceRequest( - content::RenderFrameHost* render_frame_host, const content::ResourceRedirectDetails& details) override; void TitleWasSet(content::NavigationEntry* entry, bool explicit_set) override; + void DidStartNavigation( + content::NavigationHandle* navigation_handle) override; + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; void BeforeUrlLoaded(const GURL& url); void AfterUrlLoaded(); diff --git a/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc b/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc index 7b341530d74..1864fd8e3c5 100644 --- a/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc +++ b/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc @@ -26,22 +26,20 @@ std::unique_ptr<base::ListValue> CopyBinaryValueToIntegerList( } // namespace -bool IdltestSendArrayBufferFunction::RunSync() { +ExtensionFunction::ResponseAction IdltestSendArrayBufferFunction::Run() { BinaryValue* input = NULL; EXTENSION_FUNCTION_VALIDATE(args_ != NULL && args_->GetBinary(0, &input)); - SetResult(CopyBinaryValueToIntegerList(input)); - return true; + return RespondNow(OneArgument(CopyBinaryValueToIntegerList(input))); } -bool IdltestSendArrayBufferViewFunction::RunSync() { +ExtensionFunction::ResponseAction IdltestSendArrayBufferViewFunction::Run() { BinaryValue* input = NULL; EXTENSION_FUNCTION_VALIDATE(args_ != NULL && args_->GetBinary(0, &input)); - SetResult(CopyBinaryValueToIntegerList(input)); - return true; + return RespondNow(OneArgument(CopyBinaryValueToIntegerList(input))); } -bool IdltestGetArrayBufferFunction::RunSync() { +ExtensionFunction::ResponseAction IdltestGetArrayBufferFunction::Run() { std::string hello = "hello world"; - SetResult(BinaryValue::CreateWithCopiedBuffer(hello.c_str(), hello.size())); - return true; + return RespondNow(OneArgument( + BinaryValue::CreateWithCopiedBuffer(hello.c_str(), hello.size()))); } diff --git a/chromium/chrome/browser/extensions/api/idltest/idltest_api.h b/chromium/chrome/browser/extensions/api/idltest/idltest_api.h index 587664e310c..48b5e9d7d6c 100644 --- a/chromium/chrome/browser/extensions/api/idltest/idltest_api.h +++ b/chromium/chrome/browser/extensions/api/idltest/idltest_api.h @@ -7,32 +7,32 @@ #include "extensions/browser/extension_function.h" -class IdltestSendArrayBufferFunction : public SyncExtensionFunction { +class IdltestSendArrayBufferFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.sendArrayBuffer", IDLTEST_SENDARRAYBUFFER) protected: ~IdltestSendArrayBufferFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class IdltestSendArrayBufferViewFunction : public SyncExtensionFunction { +class IdltestSendArrayBufferViewFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.sendArrayBufferView", IDLTEST_SENDARRAYBUFFERVIEW) protected: ~IdltestSendArrayBufferViewFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; -class IdltestGetArrayBufferFunction : public SyncExtensionFunction { +class IdltestGetArrayBufferFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.getArrayBuffer", IDLTEST_GETARRAYBUFFER) protected: ~IdltestGetArrayBufferFunction() override {} - bool RunSync() override; + ResponseAction Run() override; }; #endif // CHROME_BROWSER_EXTENSIONS_API_IDLTEST_IDLTEST_API_H_ diff --git a/chromium/chrome/browser/extensions/api/idltest/idltest_apitest.cc b/chromium/chrome/browser/extensions/api/idltest/idltest_apitest.cc index eb564da36b0..a81cb23da8f 100644 --- a/chromium/chrome/browser/extensions/api/idltest/idltest_apitest.cc +++ b/chromium/chrome/browser/extensions/api/idltest/idltest_apitest.cc @@ -3,8 +3,8 @@ // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/common/extensions/features/feature_channel.h" #include "components/version_info/version_info.h" +#include "extensions/common/features/feature_channel.h" #include "extensions/common/switches.h" class ExtensionIdltestApiTest : public ExtensionApiTest { 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 b1ee49bbf72..687389f7c8e 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 @@ -26,7 +26,7 @@ DestroyPartitionsOperation::DestroyPartitionsOperation( DestroyPartitionsOperation::~DestroyPartitionsOperation() {} void DestroyPartitionsOperation::StartImpl() { - if (!base::CreateTemporaryFileInDir(temp_dir_.path(), &image_path_)) { + if (!base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_path_)) { Error(error::kTempFileError); return; } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc index 6310bc6c6eb..1e39db96e4f 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc @@ -177,9 +177,8 @@ void ImageWriterPrivateListRemovableStorageDevicesFunction::OnDeviceListReady( scoped_refptr<StorageDeviceList> device_list, bool success) { if (success) { - results_ = - image_writer_api::ListRemovableStorageDevices::Results::Create( - device_list.get()->data); + results_ = image_writer_api::ListRemovableStorageDevices::Results::Create( + device_list->data); SendResponse(true); } else { error_ = image_writer::error::kDeviceListError; diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc index 4ae134eea80..f0af83d84ed 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc @@ -115,9 +115,11 @@ IN_PROC_BROWSER_TEST_F(ImageWriterPrivateApiTest, TestWriteFromFile) { #if !defined(OS_CHROMEOS) test_utils_.GetUtilityClient()->SetWriteCallback(base::Bind( - &ImageWriterPrivateApiTest::ImageWriterUtilityClientCall, this)); + &ImageWriterPrivateApiTest::ImageWriterUtilityClientCall, + base::Unretained(this))); test_utils_.GetUtilityClient()->SetVerifyCallback(base::Bind( - &ImageWriterPrivateApiTest::ImageWriterUtilityClientCall, this)); + &ImageWriterPrivateApiTest::ImageWriterUtilityClientCall, + base::Unretained(this))); #endif ASSERT_TRUE(RunPlatformAppTest("image_writer_private/write_from_file")) 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 491cb44e9db..1d8d74d8672 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc @@ -125,7 +125,8 @@ void Operation::Unzip(const base::Closure& continuation) { // zip_reader_. zip::ZipReader::EntryInfo* entry_info = zip_reader_->current_entry_info(); if (entry_info) { - image_path_ = temp_dir_.path().Append(entry_info->file_path().BaseName()); + image_path_ = + temp_dir_.GetPath().Append(entry_info->file_path().BaseName()); } else { Error(error::kTempDirError); return; 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 42243af3740..60d25a6760f 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 @@ -12,7 +12,6 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" -#include "base/stl_util.h" #include "chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h" #include "chrome/browser/extensions/api/image_writer_private/operation.h" #include "chrome/common/extensions/api/image_writer_private.h" @@ -91,7 +90,6 @@ class OperationManager : public BrowserContextKeyedAPI, static OperationManager* Get(content::BrowserContext* context); 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 8c54eddd364..22297d93d21 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 @@ -43,7 +43,7 @@ class FakeEventRouter : public extensions::EventRouter { // FakeEventRouter factory function std::unique_ptr<KeyedService> FakeEventRouterFactoryFunction( content::BrowserContext* context) { - return base::WrapUnique(new FakeEventRouter(static_cast<Profile*>(context))); + return base::MakeUnique<FakeEventRouter>(static_cast<Profile*>(context)); } namespace { 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 57753610fab..3b7ffbef270 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 @@ -160,10 +160,10 @@ void ImageWriterTestUtils::SetUp() { void ImageWriterTestUtils::SetUp(bool is_browser_test) { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), - &test_image_path_)); - ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), - &test_device_path_)); + ASSERT_TRUE( + base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &test_image_path_)); + ASSERT_TRUE( + base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &test_device_path_)); ASSERT_TRUE(FillFile(test_image_path_, kImagePattern, kTestFileSize)); ASSERT_TRUE(FillFile(test_device_path_, kDevicePattern, kTestFileSize)); @@ -217,7 +217,7 @@ void ImageWriterTestUtils::TearDown() { } const base::FilePath& ImageWriterTestUtils::GetTempDir() { - return temp_dir_.path(); + return temp_dir_.GetPath(); } const base::FilePath& ImageWriterTestUtils::GetImagePath() { 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 8c6f94539df..911d93893de 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 @@ -58,14 +58,14 @@ void WriteFromUrlOperation::GetDownloadTarget( } if (url_.ExtractFileName().empty()) { - if (!base::CreateTemporaryFileInDir(temp_dir_.path(), &image_path_)) { + if (!base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_path_)) { Error(error::kTempFileError); return; } } else { base::FilePath file_name = base::FilePath::FromUTF8Unsafe(url_.ExtractFileName()); - image_path_ = temp_dir_.path().Append(file_name); + image_path_ = temp_dir_.GetPath().Append(file_name); } BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation); @@ -88,8 +88,7 @@ void WriteFromUrlOperation::Download(const base::Closure& continuation) { url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SaveResponseToFileAtPath( - image_path_, - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)); + image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)); AddCleanUpFunction( base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this)); @@ -109,7 +108,8 @@ void WriteFromUrlOperation::OnURLFetchUploadProgress( void WriteFromUrlOperation::OnURLFetchDownloadProgress( const net::URLFetcher* source, int64_t current, - int64_t total) { + int64_t total, + int64_t current_network_bytes) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (IsCancelled()) { 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 ce94db07829..99013ce54d2 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 @@ -56,7 +56,8 @@ class WriteFromUrlOperation : public Operation, public net::URLFetcherDelegate { void OnURLFetchComplete(const net::URLFetcher* source) override; void OnURLFetchDownloadProgress(const net::URLFetcher* source, int64_t current, - int64_t total) override; + int64_t total, + int64_t current_network_bytes) override; void OnURLFetchUploadProgress(const net::URLFetcher* source, int64_t current, int64_t total) override; 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 afb463905a2..ca70690c292 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 @@ -77,7 +77,7 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase { // Turn on interception and set up our dummy file. get_interceptor_.reset(new GetInterceptor( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))); get_interceptor_->SetResponse(GURL(kTestImageUrl), diff --git a/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_api.cc b/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_api.cc index e85b190cece..870613d80e3 100644 --- a/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_api.cc +++ b/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_api.cc @@ -116,14 +116,10 @@ InlineInstallPrivateInstallFunction::Run() { return RespondNow(CreateResponse("Already installed", webstore_install::OTHER_ERROR)); - scoped_refptr<Installer> installer = - new Installer( - params->id, - source_url_, - Profile::FromBrowserContext(browser_context()), - base::Bind( - &InlineInstallPrivateInstallFunction::InstallerCallback, - this)); + scoped_refptr<Installer> installer = new Installer( + params->id, source_url(), Profile::FromBrowserContext(browser_context()), + base::Bind(&InlineInstallPrivateInstallFunction::InstallerCallback, + this)); installer->BeginInstall(); return RespondLater(); 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 c95a9b3ab5e..e1969b3423d 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 @@ -174,14 +174,12 @@ bool ImeObserver::ShouldForwardKeyEvent() const { // the key events, and therefore, all key events will be eaten. // This is for error-tolerance, and it means that onKeyEvent will never wake // up lazy background page. - const extensions::EventListenerMap::ListenerList& listener_list = + const extensions::EventListenerMap::ListenerList& listeners = extensions::EventRouter::Get(profile_) ->listeners() .GetEventListenersByName(input_ime::OnKeyEvent::kEventName); - for (extensions::EventListenerMap::ListenerList::const_iterator it = - listener_list.begin(); - it != listener_list.end(); ++it) { - if ((*it)->extension_id() == extension_id_ && !(*it)->IsLazy()) + for (const std::unique_ptr<extensions::EventListener>& listener : listeners) { + if (listener->extension_id() == extension_id_ && !listener->IsLazy()) return true; } return false; @@ -285,7 +283,6 @@ ExtensionFunction::ResponseAction InputImeKeyEventHandledFunction::Run() { } ExtensionFunction::ResponseAction InputImeSetCompositionFunction::Run() { - bool success = false; InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = @@ -320,17 +317,21 @@ ExtensionFunction::ResponseAction InputImeSetCompositionFunction::Run() { params.selection_start ? *params.selection_start : params.cursor; int selection_end = params.selection_end ? *params.selection_end : params.cursor; - success = engine->SetComposition(params.context_id, params.text.c_str(), - selection_start, selection_end, - params.cursor, segments, &error_); + std::string error; + if (!engine->SetComposition(params.context_id, params.text.c_str(), + selection_start, selection_end, params.cursor, + segments, &error)) { + std::unique_ptr<base::ListValue> results = + base::MakeUnique<base::ListValue>(); + results->Append(base::MakeUnique<base::FundamentalValue>(false)); + return RespondNow(ErrorWithArguments(std::move(results), error)); + } } - std::unique_ptr<base::ListValue> output = - SetComposition::Results::Create(success); - return RespondNow(ArgumentList(std::move(output))); + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(true))); } ExtensionFunction::ResponseAction InputImeCommitTextFunction::Run() { - bool success = false; InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = @@ -339,12 +340,16 @@ ExtensionFunction::ResponseAction InputImeCommitTextFunction::Run() { std::unique_ptr<CommitText::Params> parent_params( CommitText::Params::Create(*args_)); const CommitText::Params::Parameters& params = parent_params->parameters; - success = - engine->CommitText(params.context_id, params.text.c_str(), &error_); + std::string error; + if (!engine->CommitText(params.context_id, params.text.c_str(), &error)) { + std::unique_ptr<base::ListValue> results = + base::MakeUnique<base::ListValue>(); + results->Append(base::MakeUnique<base::FundamentalValue>(false)); + return RespondNow(ErrorWithArguments(std::move(results), error)); + } } - std::unique_ptr<base::ListValue> output = - CommitText::Results::Create(success); - return RespondNow(ArgumentList(std::move(output))); + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(true))); } ExtensionFunction::ResponseAction InputImeSendKeyEventsFunction::Run() { 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 2febca83c21..6069e113960 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 @@ -5,6 +5,8 @@ #include "chrome/browser/extensions/api/input_ime/input_ime_api.h" #include <stddef.h> + +#include <memory> #include <utility> #include "base/macros.h" @@ -160,14 +162,14 @@ class ImeObserverChromeOS : public ui::ImeObserver { return; // Note: this is a private API event. - base::ListValue* bounds_list = new base::ListValue(); + auto bounds_list = base::MakeUnique<base::ListValue>(); for (size_t i = 0; i < bounds.size(); ++i) { - base::DictionaryValue* bounds_value = new base::DictionaryValue(); + auto bounds_value = base::MakeUnique<base::DictionaryValue>(); bounds_value->SetInteger("x", bounds[i].x()); bounds_value->SetInteger("y", bounds[i].y()); bounds_value->SetInteger("w", bounds[i].width()); bounds_value->SetInteger("h", bounds[i].height()); - bounds_list->Append(bounds_value); + bounds_list->Append(std::move(bounds_value)); } if (bounds_list->GetSize() <= 0) @@ -179,7 +181,7 @@ class ImeObserverChromeOS : public ui::ImeObserver { base::Value* first_value = NULL; if (bounds_list->Get(0, &first_value)) args->Append(first_value->DeepCopy()); - args->Append(bounds_list); + args->Append(std::move(bounds_list)); DispatchEventToExtension( extensions::events::INPUT_METHOD_PRIVATE_ON_COMPOSITION_BOUNDS_CHANGED, @@ -357,12 +359,12 @@ InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( : nullptr; } -bool InputImeClearCompositionFunction::RunSync() { +ExtensionFunction::ResponseAction InputImeClearCompositionFunction::Run() { InputMethodEngine* engine = GetActiveEngine( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { - SetResult(base::MakeUnique<base::FundamentalValue>(false)); - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(false))); } std::unique_ptr<ClearComposition::Params> parent_params( @@ -370,9 +372,13 @@ bool InputImeClearCompositionFunction::RunSync() { const ClearComposition::Params::Parameters& params = parent_params->parameters; - SetResult(base::MakeUnique<base::FundamentalValue>( - engine->ClearComposition(params.context_id, &error_))); - return true; + std::string error; + bool success = engine->ClearComposition(params.context_id, &error); + std::unique_ptr<base::ListValue> results = + base::MakeUnique<base::ListValue>(); + results->Append(base::MakeUnique<base::FundamentalValue>(success)); + return RespondNow(success ? ArgumentList(std::move(results)) + : ErrorWithArguments(std::move(results), error)); } bool InputImeHideInputViewFunction::RunAsync() { @@ -385,7 +391,8 @@ bool InputImeHideInputViewFunction::RunAsync() { return true; } -bool InputImeSetCandidateWindowPropertiesFunction::RunSync() { +ExtensionFunction::ResponseAction +InputImeSetCandidateWindowPropertiesFunction::Run() { std::unique_ptr<SetCandidateWindowProperties::Params> parent_params( SetCandidateWindowProperties::Params::Create(*args_)); const SetCandidateWindowProperties::Params::Parameters& @@ -397,17 +404,20 @@ bool InputImeSetCandidateWindowPropertiesFunction::RunSync() { event_router ? event_router->GetEngine(extension_id(), params.engine_id) : nullptr; if (!engine) { - SetResult(base::MakeUnique<base::FundamentalValue>(false)); - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(false))); } const SetCandidateWindowProperties::Params::Parameters::Properties& properties = params.properties; + std::string error; if (properties.visible && - !engine->SetCandidateWindowVisible(*properties.visible, &error_)) { - SetResult(base::MakeUnique<base::FundamentalValue>(false)); - return true; + !engine->SetCandidateWindowVisible(*properties.visible, &error)) { + std::unique_ptr<base::ListValue> results = + base::MakeUnique<base::ListValue>(); + results->Append(base::MakeUnique<base::FundamentalValue>(false)); + return RespondNow(ErrorWithArguments(std::move(results), error)); } InputMethodEngine::CandidateWindowProperty properties_out = @@ -452,17 +462,16 @@ bool InputImeSetCandidateWindowPropertiesFunction::RunSync() { engine->SetCandidateWindowProperty(properties_out); } - SetResult(base::MakeUnique<base::FundamentalValue>(true)); - - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(true))); } -bool InputImeSetCandidatesFunction::RunSync() { +ExtensionFunction::ResponseAction InputImeSetCandidatesFunction::Run() { InputMethodEngine* engine = GetActiveEngine( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { - SetResult(base::MakeUnique<base::FundamentalValue>(true)); - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(true))); } std::unique_ptr<SetCandidates::Params> parent_params( @@ -485,17 +494,22 @@ bool InputImeSetCandidatesFunction::RunSync() { } } - SetResult(base::MakeUnique<base::FundamentalValue>( - engine->SetCandidates(params.context_id, candidates_out, &error_))); - return true; + std::string error; + bool success = + engine->SetCandidates(params.context_id, candidates_out, &error); + std::unique_ptr<base::ListValue> results = + base::MakeUnique<base::ListValue>(); + results->Append(base::MakeUnique<base::FundamentalValue>(success)); + return RespondNow(success ? ArgumentList(std::move(results)) + : ErrorWithArguments(std::move(results), error)); } -bool InputImeSetCursorPositionFunction::RunSync() { +ExtensionFunction::ResponseAction InputImeSetCursorPositionFunction::Run() { InputMethodEngine* engine = GetActiveEngine( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { - SetResult(base::MakeUnique<base::FundamentalValue>(false)); - return true; + return RespondNow( + OneArgument(base::MakeUnique<base::FundamentalValue>(false))); } std::unique_ptr<SetCursorPosition::Params> parent_params( @@ -503,12 +517,17 @@ bool InputImeSetCursorPositionFunction::RunSync() { const SetCursorPosition::Params::Parameters& params = parent_params->parameters; - SetResult(base::MakeUnique<base::FundamentalValue>(engine->SetCursorPosition( - params.context_id, params.candidate_id, &error_))); - return true; + std::string error; + bool success = + engine->SetCursorPosition(params.context_id, params.candidate_id, &error); + std::unique_ptr<base::ListValue> results = + base::MakeUnique<base::ListValue>(); + results->Append(base::MakeUnique<base::FundamentalValue>(success)); + return RespondNow(success ? ArgumentList(std::move(results)) + : ErrorWithArguments(std::move(results), error)); } -bool InputImeSetMenuItemsFunction::RunSync() { +ExtensionFunction::ResponseAction InputImeSetMenuItemsFunction::Run() { std::unique_ptr<SetMenuItems::Params> parent_params( SetMenuItems::Params::Create(*args_)); const SetMenuItems::Params::Parameters& params = @@ -519,10 +538,8 @@ bool InputImeSetMenuItemsFunction::RunSync() { InputMethodEngine* engine = event_router ? event_router->GetEngine(extension_id(), params.engine_id) : nullptr; - if (!engine) { - error_ = kErrorEngineNotAvailable; - return false; - } + if (!engine) + return RespondNow(Error(kErrorEngineNotAvailable)); std::vector<chromeos::input_method::InputMethodManager::MenuItem> items_out; for (const input_ime::MenuItem& item_in : params.items) { @@ -531,11 +548,11 @@ bool InputImeSetMenuItemsFunction::RunSync() { } if (!engine->SetMenuItems(items_out)) - error_ = kErrorSetMenuItemsFail; - return true; + return RespondNow(Error(kErrorSetMenuItemsFail)); + return RespondNow(NoArguments()); } -bool InputImeUpdateMenuItemsFunction::RunSync() { +ExtensionFunction::ResponseAction InputImeUpdateMenuItemsFunction::Run() { std::unique_ptr<UpdateMenuItems::Params> parent_params( UpdateMenuItems::Params::Create(*args_)); const UpdateMenuItems::Params::Parameters& params = @@ -546,10 +563,8 @@ bool InputImeUpdateMenuItemsFunction::RunSync() { InputMethodEngine* engine = event_router ? event_router->GetEngine(extension_id(), params.engine_id) : nullptr; - if (!engine) { - error_ = kErrorEngineNotAvailable; - return false; - } + if (!engine) + return RespondNow(Error(kErrorEngineNotAvailable)); std::vector<chromeos::input_method::InputMethodManager::MenuItem> items_out; for (const input_ime::MenuItem& item_in : params.items) { @@ -558,11 +573,11 @@ bool InputImeUpdateMenuItemsFunction::RunSync() { } if (!engine->UpdateMenuItems(items_out)) - error_ = kErrorUpdateMenuItemsFail; - return true; + return RespondNow(Error(kErrorUpdateMenuItemsFail)); + return RespondNow(NoArguments()); } -bool InputImeDeleteSurroundingTextFunction::RunSync() { +ExtensionFunction::ResponseAction InputImeDeleteSurroundingTextFunction::Run() { std::unique_ptr<DeleteSurroundingText::Params> parent_params( DeleteSurroundingText::Params::Create(*args_)); const DeleteSurroundingText::Params::Parameters& params = @@ -573,14 +588,13 @@ bool InputImeDeleteSurroundingTextFunction::RunSync() { InputMethodEngine* engine = event_router ? event_router->GetEngine(extension_id(), params.engine_id) : nullptr; - if (!engine) { - error_ = kErrorEngineNotAvailable; - return false; - } + if (!engine) + return RespondNow(Error(kErrorEngineNotAvailable)); + std::string error; engine->DeleteSurroundingText(params.context_id, params.offset, params.length, - &error_); - return true; + &error); + return RespondNow(error.empty() ? NoArguments() : Error(error)); } ExtensionFunction::ResponseAction 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 4516d682bea..7960ef8e48a 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 SyncExtensionFunction { +class InputImeClearCompositionFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.clearComposition", INPUT_IME_CLEARCOMPOSITION) @@ -30,11 +30,11 @@ class InputImeClearCompositionFunction : public SyncExtensionFunction { ~InputImeClearCompositionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class InputImeSetCandidateWindowPropertiesFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCandidateWindowProperties", INPUT_IME_SETCANDIDATEWINDOWPROPERTIES) @@ -43,10 +43,10 @@ class InputImeSetCandidateWindowPropertiesFunction ~InputImeSetCandidateWindowPropertiesFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class InputImeSetCandidatesFunction : public SyncExtensionFunction { +class InputImeSetCandidatesFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCandidates", INPUT_IME_SETCANDIDATES) @@ -54,10 +54,10 @@ class InputImeSetCandidatesFunction : public SyncExtensionFunction { ~InputImeSetCandidatesFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class InputImeSetCursorPositionFunction : public SyncExtensionFunction { +class InputImeSetCursorPositionFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCursorPosition", INPUT_IME_SETCURSORPOSITION) @@ -66,10 +66,10 @@ class InputImeSetCursorPositionFunction : public SyncExtensionFunction { ~InputImeSetCursorPositionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class InputImeSetMenuItemsFunction : public SyncExtensionFunction { +class InputImeSetMenuItemsFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setMenuItems", INPUT_IME_SETMENUITEMS) @@ -77,10 +77,10 @@ class InputImeSetMenuItemsFunction : public SyncExtensionFunction { ~InputImeSetMenuItemsFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class InputImeUpdateMenuItemsFunction : public SyncExtensionFunction { +class InputImeUpdateMenuItemsFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.updateMenuItems", INPUT_IME_UPDATEMENUITEMS) @@ -89,10 +89,10 @@ class InputImeUpdateMenuItemsFunction : public SyncExtensionFunction { ~InputImeUpdateMenuItemsFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class InputImeDeleteSurroundingTextFunction : public SyncExtensionFunction { +class InputImeDeleteSurroundingTextFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.deleteSurroundingText", INPUT_IME_DELETESURROUNDINGTEXT) @@ -100,7 +100,7 @@ class InputImeDeleteSurroundingTextFunction : public SyncExtensionFunction { ~InputImeDeleteSurroundingTextFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class InputImeHideInputViewFunction : public AsyncExtensionFunction { 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 89df5e6dd73..8d8778b812a 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 @@ -12,7 +12,6 @@ #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" @@ -356,15 +355,16 @@ ExtensionFunction::ResponseAction InputImeCreateWindowFunction::Run() { if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); + std::string error; int frame_id = engine->CreateImeWindow( extension(), render_frame_host(), options.url.get() ? *options.url : url::kAboutBlankURL, options.window_type == input_ime::WINDOW_TYPE_FOLLOWCURSOR ? ui::ImeWindow::FOLLOW_CURSOR : ui::ImeWindow::NORMAL, - bounds, &error_); + bounds, &error); if (!frame_id) - return RespondNow(Error(error_)); + return RespondNow(Error(error)); std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); result->Set("frameId", new base::FundamentalValue(frame_id)); diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc b/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc index 63a4674329d..26fcb689540 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc @@ -23,18 +23,6 @@ using extensions::ResultCatcher; namespace extensions { -namespace { - -std::unique_ptr<KeyedService> BuildFakeGCMProfileService( - content::BrowserContext* context) { - std::unique_ptr<gcm::FakeGCMProfileService> service( - new gcm::FakeGCMProfileService(Profile::FromBrowserContext(context))); - service->SetDriverForTesting(new instance_id::FakeGCMDriverForInstanceID()); - return std::move(service); -} - -} // namespace - class InstanceIDApiTest : public ExtensionApiTest { public: InstanceIDApiTest(); @@ -51,7 +39,7 @@ InstanceIDApiTest::InstanceIDApiTest() { void InstanceIDApiTest::SetUpOnMainThread() { gcm::GCMProfileServiceFactory::GetInstance()->SetTestingFactory( - browser()->profile(), &BuildFakeGCMProfileService); + browser()->profile(), &gcm::FakeGCMProfileService::Build); ExtensionApiTest::SetUpOnMainThread(); } 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 167a6aee70b..6e24dec8138 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 @@ -13,7 +13,6 @@ #include <vector> #include "base/i18n/rtl.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/strings/string16.h" #include "base/strings/string_split.h" @@ -31,7 +30,7 @@ #include "chrome/browser/translate/translate_service.h" #include "chrome/common/extensions/api/language_settings_private.h" #include "chrome/common/pref_names.h" -#include "chrome/common/spellcheck_common.h" +#include "components/spellcheck/common/spellcheck_common.h" #include "components/translate/core/browser/translate_download_manager.h" #include "third_party/icu/source/i18n/unicode/coll.h" #include "ui/base/l10n/l10n_util.h" @@ -201,7 +200,7 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() { // Get the list of spell check languages and convert to a set. std::vector<std::string> spellcheck_languages; - chrome::spellcheck_common::SpellCheckLanguages(&spellcheck_languages); + spellcheck::SpellCheckLanguages(&spellcheck_languages); const std::unordered_set<std::string> spellcheck_language_set( spellcheck_languages.begin(), spellcheck_languages.end()); @@ -245,26 +244,70 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() { return RespondNow(OneArgument(std::move(language_list))); } -LanguageSettingsPrivateSetLanguageListFunction:: - LanguageSettingsPrivateSetLanguageListFunction() - : chrome_details_(this) { -} +LanguageSettingsPrivateEnableLanguageFunction:: + LanguageSettingsPrivateEnableLanguageFunction() + : chrome_details_(this) {} + +LanguageSettingsPrivateEnableLanguageFunction:: + ~LanguageSettingsPrivateEnableLanguageFunction() {} + +ExtensionFunction::ResponseAction +LanguageSettingsPrivateEnableLanguageFunction::Run() { + std::unique_ptr<language_settings_private::EnableLanguage::Params> + parameters = + language_settings_private::EnableLanguage::Params::Create(*args_); + EXTENSION_FUNCTION_VALIDATE(parameters.get()); + const std::string& language_code = parameters->language_code; + + std::unique_ptr<translate::TranslatePrefs> translate_prefs = + ChromeTranslateClient::CreateTranslatePrefs( + chrome_details_.GetProfile()->GetPrefs()); + + std::vector<std::string> languages; + translate_prefs->GetLanguageList(&languages); -LanguageSettingsPrivateSetLanguageListFunction:: - ~LanguageSettingsPrivateSetLanguageListFunction() { + if (std::find(languages.begin(), languages.end(), language_code) != + languages.end()) { + LOG(ERROR) << "Language " << language_code << " already enabled"; + return RespondNow(NoArguments()); + } + + languages.push_back(parameters->language_code); + translate_prefs->UpdateLanguageList(languages); + + return RespondNow(NoArguments()); } +LanguageSettingsPrivateDisableLanguageFunction:: + LanguageSettingsPrivateDisableLanguageFunction() + : chrome_details_(this) {} + +LanguageSettingsPrivateDisableLanguageFunction:: + ~LanguageSettingsPrivateDisableLanguageFunction() {} + ExtensionFunction::ResponseAction -LanguageSettingsPrivateSetLanguageListFunction::Run() { - std::unique_ptr<language_settings_private::SetLanguageList::Params> +LanguageSettingsPrivateDisableLanguageFunction::Run() { + std::unique_ptr<language_settings_private::DisableLanguage::Params> parameters = - language_settings_private::SetLanguageList::Params::Create(*args_); + language_settings_private::DisableLanguage::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); + const std::string& language_code = parameters->language_code; std::unique_ptr<translate::TranslatePrefs> translate_prefs = ChromeTranslateClient::CreateTranslatePrefs( chrome_details_.GetProfile()->GetPrefs()); - translate_prefs->UpdateLanguageList(parameters->language_codes); + + std::vector<std::string> languages; + translate_prefs->GetLanguageList(&languages); + + auto it = std::find(languages.begin(), languages.end(), language_code); + if (it == languages.end()) { + LOG(ERROR) << "Language " << language_code << " not enabled"; + return RespondNow(NoArguments()); + } + + languages.erase(it); + translate_prefs->UpdateLanguageList(languages); return RespondNow(NoArguments()); } 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 e1007160dc5..662298d6e7d 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 @@ -30,16 +30,16 @@ class LanguageSettingsPrivateGetLanguageListFunction DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateGetLanguageListFunction); }; -// Implements the languageSettingsPrivate.setLanguageList method. -class LanguageSettingsPrivateSetLanguageListFunction +// Implements the languageSettingsPrivate.enableLanguage method. +class LanguageSettingsPrivateEnableLanguageFunction : public UIThreadExtensionFunction { public: - LanguageSettingsPrivateSetLanguageListFunction(); - DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.setLanguageList", - LANGUAGESETTINGSPRIVATE_SETLANGUAGELIST) + LanguageSettingsPrivateEnableLanguageFunction(); + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.enableLanguage", + LANGUAGESETTINGSPRIVATE_ENABLELANGUAGE) protected: - ~LanguageSettingsPrivateSetLanguageListFunction() override; + ~LanguageSettingsPrivateEnableLanguageFunction() override; // ExtensionFunction overrides. ResponseAction Run() override; @@ -47,7 +47,27 @@ class LanguageSettingsPrivateSetLanguageListFunction private: ChromeExtensionFunctionDetails chrome_details_; - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateSetLanguageListFunction); + DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateEnableLanguageFunction); +}; + +// Implements the languageSettingsPrivate.disableLanguage method. +class LanguageSettingsPrivateDisableLanguageFunction + : public UIThreadExtensionFunction { + public: + LanguageSettingsPrivateDisableLanguageFunction(); + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.disableLanguage", + LANGUAGESETTINGSPRIVATE_DISABLELANGUAGE) + + protected: + ~LanguageSettingsPrivateDisableLanguageFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + ChromeExtensionFunctionDetails chrome_details_; + + DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateDisableLanguageFunction); }; // Implements the languageSettingsPrivate.getSpellcheckDictionaryStatuses diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc index 98c99563597..e04cfb041b1 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc @@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/memory/linked_ptr.h" #include "base/memory/scoped_vector.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" @@ -19,8 +18,8 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/spellchecker/spellcheck_factory.h" #include "chrome/browser/spellchecker/spellcheck_service.h" -#include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" +#include "components/spellcheck/browser/pref_names.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/notification_source.h" @@ -182,7 +181,7 @@ void LanguageSettingsPrivateDelegate::RefreshDictionaries( const ScopedVector<SpellcheckHunspellDictionary>& dictionaries( service->GetHunspellDictionaries()); - for (const auto& dictionary: dictionaries) { + for (auto* dictionary : dictionaries) { hunspell_dictionaries_.push_back(dictionary->AsWeakPtr()); if (should_listen) dictionary->AddObserver(this); @@ -210,9 +209,11 @@ void LanguageSettingsPrivateDelegate:: // Update and observe the hunspell dictionaries. RefreshDictionaries(listening_spellcheck_, should_listen); // Observe the dictionaries preference. - pref_change_registrar_.Add(prefs::kSpellCheckDictionaries, base::Bind( - &LanguageSettingsPrivateDelegate::OnSpellcheckDictionariesChanged, - base::Unretained(this))); + pref_change_registrar_.Add( + spellcheck::prefs::kSpellCheckDictionaries, + base::Bind( + &LanguageSettingsPrivateDelegate::OnSpellcheckDictionariesChanged, + base::Unretained(this))); // Observe the dictionary of custom words. if (custom_dictionary_) custom_dictionary_->AddObserver(this); @@ -220,7 +221,7 @@ void LanguageSettingsPrivateDelegate:: // Stop observing any dictionaries that still exist. RemoveDictionaryObservers(); hunspell_dictionaries_.clear(); - pref_change_registrar_.Remove(prefs::kSpellCheckDictionaries); + pref_change_registrar_.Remove(spellcheck::prefs::kSpellCheckDictionaries); if (custom_dictionary_) custom_dictionary_->RemoveObserver(this); } diff --git a/chromium/chrome/browser/extensions/api/log_private/log_private_api.h b/chromium/chrome/browser/extensions/api/log_private/log_private_api.h index 4ea5c34936e..b67ff4ae0f6 100644 --- a/chromium/chrome/browser/extensions/api/log_private/log_private_api.h +++ b/chromium/chrome/browser/extensions/api/log_private/log_private_api.h @@ -79,13 +79,18 @@ class LogPrivateAPI : public BrowserContextKeyedAPI, friend class BrowserContextKeyedAPIFactory<LogPrivateAPI>; void Initialize(); + + void RegisterTempFileOnFileResourceSequence( + const std::string& owner_extension_id, + const base::FilePath& file_path); + // ExtensionRegistryObserver implementation. void OnExtensionUnloaded(content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionInfo::Reason reason) override; // NetLog::ThreadSafeObserver implementation: - void OnAddEntry(const net::NetLog::Entry& entry) override; + void OnAddEntry(const net::NetLogEntry& entry) override; void PostPendingEntries(); void AddEntriesOnUI(std::unique_ptr<base::ListValue> value); diff --git a/chromium/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc b/chromium/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc index b767c1bad7a..227a38e0db1 100644 --- a/chromium/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc @@ -14,6 +14,7 @@ #include "base/json/json_writer.h" #include "base/lazy_instance.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/download/download_prefs.h" @@ -34,6 +35,7 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/granted_file_entry.h" +#include "net/log/net_log_entry.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/system_logs/debug_log_writer.h" @@ -61,11 +63,16 @@ scoped_refptr<base::SequencedTaskRunner> GetSequencedTaskRunner() { base::SequencedWorkerPool::BLOCK_SHUTDOWN); } +#if DCHECK_IS_ON() +base::LazyInstance<base::SequenceChecker>::Leaky + g_file_resource_sequence_checker = LAZY_INSTANCE_INITIALIZER; +#endif + // Checks if we are running on sequenced task runner thread. -bool IsRunningOnSequenceThread() { - base::SequencedWorkerPool* pool = content::BrowserThread::GetBlockingPool(); - return pool->IsRunningSequenceOnCurrentThread( - pool->GetNamedSequenceToken(FileResource::kSequenceToken)); +void AssertCurrentlyOnFileResourceSequence() { +#if DCHECK_IS_ON() + DCHECK(g_file_resource_sequence_checker.Get().CalledOnValidSequence()); +#endif } std::unique_ptr<LogParser> CreateLogParser(const std::string& log_type) { @@ -114,7 +121,7 @@ void CleanUpLeftoverLogs(bool is_primary_profile, LOG(WARNING) << "Deleting " << app_logs_dir.value(); LOG(WARNING) << "Deleting " << logs_dumps.value(); - DCHECK(IsRunningOnSequenceThread()); + AssertCurrentlyOnFileResourceSequence(); base::DeleteFile(logs_dumps, true); // App-specific logs are stored in /home/chronos/user/log/apps directory that @@ -193,17 +200,10 @@ void LogPrivateAPI::StopAllWatches(const std::string& extension_id, void LogPrivateAPI::RegisterTempFile(const std::string& owner_extension_id, const base::FilePath& file_path) { - if (!IsRunningOnSequenceThread()) { - GetSequencedTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&LogPrivateAPI::RegisterTempFile, - base::Unretained(this), - owner_extension_id, - file_path)); - return; - } - - log_file_resources_.Add(new FileResource(owner_extension_id, file_path)); + GetSequencedTaskRunner()->PostTask( + FROM_HERE, + base::Bind(&LogPrivateAPI::RegisterTempFileOnFileResourceSequence, + base::Unretained(this), owner_extension_id, file_path)); } static base::LazyInstance<BrowserContextKeyedAPIFactory<LogPrivateAPI> > @@ -215,7 +215,7 @@ LogPrivateAPI::GetFactoryInstance() { return g_factory.Pointer(); } -void LogPrivateAPI::OnAddEntry(const net::NetLog::Entry& entry) { +void LogPrivateAPI::OnAddEntry(const net::NetLogEntry& entry) { // We could receive events on whatever thread they happen to be generated, // since we are only interested in network events, we should ignore any // other thread than BrowserThread::IO. @@ -259,7 +259,7 @@ void LogPrivateAPI::AddEntriesOnUI(std::unique_ptr<base::ListValue> value) { void LogPrivateAPI::CreateTempNetLogFile(const std::string& owner_extension_id, base::ScopedFILE* file) { - DCHECK(IsRunningOnSequenceThread()); + AssertCurrentlyOnFileResourceSequence(); // Create app-specific subdirectory in session logs folder. base::FilePath app_log_dir = GetAppLogDirectory().Append(owner_extension_id); @@ -278,7 +278,7 @@ void LogPrivateAPI::CreateTempNetLogFile(const std::string& owner_extension_id, return; } - RegisterTempFile(owner_extension_id, file_path); + RegisterTempFileOnFileResourceSequence(owner_extension_id, file_path); return file->reset(file_ptr); } @@ -388,6 +388,13 @@ void LogPrivateAPI::Initialize() { GetLogDumpDirectory(browser_context_))); } +void LogPrivateAPI::RegisterTempFileOnFileResourceSequence( + const std::string& owner_extension_id, + const base::FilePath& file_path) { + AssertCurrentlyOnFileResourceSequence(); + log_file_resources_.Add(new FileResource(owner_extension_id, file_path)); +} + void LogPrivateAPI::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, @@ -531,13 +538,13 @@ void LogPrivateDumpLogsFunction::OnStoreLogsCompleted( log_path, false); - base::DictionaryValue* entry = new base::DictionaryValue(); + auto entry = base::MakeUnique<base::DictionaryValue>(); entry->SetString("fileSystemId", file_entry.filesystem_id); entry->SetString("baseName", file_entry.registered_name); entry->SetString("id", file_entry.id); entry->SetBoolean("isDirectory", false); base::ListValue* entry_list = new base::ListValue(); - entry_list->Append(entry); + entry_list->Append(std::move(entry)); response->Set("entries", entry_list); response->SetBoolean("multiple", false); SetResult(std::move(response)); diff --git a/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc index 1cb54030ade..47f29ab538d 100644 --- a/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc @@ -32,14 +32,13 @@ class TestDebugDaemonClient : public chromeos::FakeDebugDaemonClient { ~TestDebugDaemonClient() override {} void DumpDebugLogs(bool is_compressed, - base::File file, - scoped_refptr<base::TaskRunner> task_runner, + int file_descriptor, const GetDebugLogsCallback& callback) override { - base::File* file_param = new base::File(std::move(file)); - task_runner->PostTaskAndReply( - FROM_HERE, - base::Bind( - &GenerateTestLogDumpFile, test_file_, base::Owned(file_param)), + // dup() is needed as the file descriptor will be closed on the client side. + base::File* file_param = new base::File(dup(file_descriptor)); + content::BrowserThread::PostBlockingPoolTaskAndReply( + FROM_HERE, base::Bind(&GenerateTestLogDumpFile, test_file_, + base::Owned(file_param)), base::Bind(callback, true)); } diff --git a/chromium/chrome/browser/extensions/api/log_private/syslog_parser_unittest.cc b/chromium/chrome/browser/extensions/api/log_private/syslog_parser_unittest.cc index d980c5316bb..35bd6918568 100644 --- a/chromium/chrome/browser/extensions/api/log_private/syslog_parser_unittest.cc +++ b/chromium/chrome/browser/extensions/api/log_private/syslog_parser_unittest.cc @@ -5,7 +5,6 @@ #include <string> #include <vector> -#include "base/memory/linked_ptr.h" #include "chrome/browser/extensions/api/log_private/filter_handler.h" #include "chrome/browser/extensions/api/log_private/log_parser.h" #include "chrome/browser/extensions/api/log_private/syslog_parser.h" diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc index be98cdb9b0b..6e0998c35d2 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 @@ -61,7 +61,7 @@ class ManagementSetEnabledFunctionInstallPromptDelegate OnInstallPromptDone, weak_factory_.GetWeakPtr()), extension, nullptr, - base::WrapUnique(new ExtensionInstallPrompt::Prompt(type)), + base::MakeUnique<ExtensionInstallPrompt::Prompt>(type), ExtensionInstallPrompt::GetDefaultShowDialogCallback()); } ~ManagementSetEnabledFunctionInstallPromptDelegate() override {} @@ -171,7 +171,7 @@ ChromeManagementAPIDelegate::ChromeManagementAPIDelegate() { ChromeManagementAPIDelegate::~ChromeManagementAPIDelegate() { } -bool ChromeManagementAPIDelegate::LaunchAppFunctionDelegate( +void ChromeManagementAPIDelegate::LaunchAppFunctionDelegate( const extensions::Extension* extension, content::BrowserContext* context) const { // Look at prefs to find the right launch container. @@ -179,13 +179,12 @@ bool ChromeManagementAPIDelegate::LaunchAppFunctionDelegate( // returned. extensions::LaunchContainer launch_container = GetLaunchContainer(extensions::ExtensionPrefs::Get(context), extension); - OpenApplication(AppLaunchParams( - Profile::FromBrowserContext(context), extension, launch_container, - NEW_FOREGROUND_TAB, extensions::SOURCE_MANAGEMENT_API)); + OpenApplication(AppLaunchParams(Profile::FromBrowserContext(context), + extension, launch_container, + WindowOpenDisposition::NEW_FOREGROUND_TAB, + extensions::SOURCE_MANAGEMENT_API)); extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_EXTENSION_API, extension->GetType()); - - return true; } GURL ChromeManagementAPIDelegate::GetFullLaunchURL( @@ -228,7 +227,7 @@ ChromeManagementAPIDelegate::SetEnabledFunctionDelegate( std::unique_ptr<extensions::RequirementsChecker> ChromeManagementAPIDelegate::CreateRequirementsChecker() const { - return base::WrapUnique(new extensions::ChromeRequirementsChecker()); + return base::MakeUnique<extensions::ChromeRequirementsChecker>(); } std::unique_ptr<extensions::UninstallDialogDelegate> @@ -243,13 +242,13 @@ ChromeManagementAPIDelegate::UninstallFunctionDelegate( bool ChromeManagementAPIDelegate::CreateAppShortcutFunctionDelegate( extensions::ManagementCreateAppShortcutFunction* function, - const extensions::Extension* extension) const { + const extensions::Extension* extension, + std::string* error) const { Browser* browser = chrome::FindBrowserWithProfile( Profile::FromBrowserContext(function->browser_context())); if (!browser) { // Shouldn't happen if we have user gesture. - function->SetError( - extension_management_api_constants::kNoBrowserToCreateShortcut); + *error = extension_management_api_constants::kNoBrowserToCreateShortcut; return false; } 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 7af6ca901b8..87c41c06728 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 @@ -20,7 +20,7 @@ class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate { ~ChromeManagementAPIDelegate() override; // ManagementAPIDelegate. - bool LaunchAppFunctionDelegate( + void LaunchAppFunctionDelegate( const extensions::Extension* extension, content::BrowserContext* context) const override; GURL GetFullLaunchURL(const extensions::Extension* extension) const override; @@ -44,7 +44,8 @@ class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate { bool show_programmatic_uninstall_ui) const override; bool CreateAppShortcutFunctionDelegate( extensions::ManagementCreateAppShortcutFunction* function, - const extensions::Extension* extension) const override; + const extensions::Extension* extension, + std::string* error) const override; std::unique_ptr<extensions::AppForLinkDelegate> GenerateAppForLinkFunctionDelegate( extensions::ManagementGenerateAppForLinkFunction* function, 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 663566748dc..d8673d79204 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc @@ -184,13 +184,11 @@ class ExtensionManagementApiEscalationTest : AppendASCII("permissions_increase").AppendASCII("permissions.pem"); base::FilePath path_v1 = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"), - scoped_temp_dir_.path().AppendASCII("permissions1.crx"), - pem_path, + scoped_temp_dir_.GetPath().AppendASCII("permissions1.crx"), pem_path, base::FilePath()); base::FilePath path_v2 = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"), - scoped_temp_dir_.path().AppendASCII("permissions2.crx"), - pem_path, + scoped_temp_dir_.GetPath().AppendASCII("permissions2.crx"), pem_path, base::FilePath()); ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> 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 9fd8a426b00..26b4f6a73aa 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc @@ -14,6 +14,7 @@ #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/test_browser_window.h" +#include "content/public/test/web_contents_tester.h" #include "extensions/browser/api/management/management_api.h" #include "extensions/browser/api/management/management_api_constants.h" #include "extensions/browser/event_router_factory.h" @@ -35,13 +36,13 @@ namespace { std::unique_ptr<KeyedService> BuildManagementApi( content::BrowserContext* context) { - return base::WrapUnique(new ManagementAPI(context)); + return base::MakeUnique<ManagementAPI>(context); } std::unique_ptr<KeyedService> BuildEventRouter( content::BrowserContext* profile) { - return base::WrapUnique( - new extensions::EventRouter(profile, ExtensionPrefs::Get(profile))); + return base::MakeUnique<extensions::EventRouter>( + profile, ExtensionPrefs::Get(profile)); } } // namespace @@ -280,6 +281,8 @@ TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlacklisted) { // permission increase. TEST_F(ManagementApiUnitTest, SetEnabledAfterIncreasedPermissions) { ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); + std::unique_ptr<content::WebContents> web_contents( + content::WebContentsTester::CreateTestWebContents(profile(), nullptr)); base::FilePath base_path = data_dir().AppendASCII("permissions_increase"); base::FilePath pem_path = base_path.AppendASCII("permissions.pem"); @@ -309,7 +312,7 @@ TEST_F(ManagementApiUnitTest, SetEnabledAfterIncreasedPermissions) { // Due to a permission increase, prefs will contain escalation information. EXPECT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id)); - auto enable_extension_via_management_api = [this]( + auto enable_extension_via_management_api = [this, &web_contents]( const std::string& extension_id, bool use_user_gesture, bool accept_dialog, bool expect_success) { ScopedTestDialogAutoConfirm auto_confirm( @@ -320,6 +323,8 @@ TEST_F(ManagementApiUnitTest, SetEnabledAfterIncreasedPermissions) { gesture.reset(new ExtensionFunction::ScopedUserGestureForTests); scoped_refptr<ManagementSetEnabledFunction> function( new ManagementSetEnabledFunction()); + function->set_browser_context(profile()); + function->SetRenderFrameHost(web_contents->GetMainFrame()); base::ListValue args; args.AppendString(extension_id); args.AppendBoolean(true); diff --git a/chromium/chrome/browser/extensions/api/management/management_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_apitest.cc index 760a7fb345e..281ebe37432 100644 --- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc @@ -46,11 +46,6 @@ Browser* FindOtherBrowser(Browser* browser) { class ExtensionManagementApiTest : public ExtensionApiTest { public: - void SetUpCommandLine(base::CommandLine* command_line) override { - ExtensionApiTest::SetUpCommandLine(command_line); - command_line->AppendSwitch(switches::kEnablePanels); - } - virtual void LoadExtensions() { base::FilePath basedir = test_data_dir_.AppendASCII("management"); diff --git a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc index 95651faab16..a9632d57f45 100644 --- a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc @@ -24,6 +24,7 @@ #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" +#include "components/policy/policy_constants.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" @@ -38,7 +39,6 @@ #include "extensions/browser/updater/extension_downloader.h" #include "extensions/test/extension_test_message_listener.h" #include "net/url_request/test_url_request_interceptor.h" -#include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" using content::BrowserThread; @@ -292,7 +292,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); @@ -336,8 +336,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { ASSERT_EQ("2.0", extension->VersionString()); ASSERT_TRUE(notification_listener.started()); ASSERT_TRUE(notification_listener.finished()); - ASSERT_TRUE(ContainsKey(notification_listener.updates(), - "ogjcoiohnmldgjemafoockdghcjciccf")); + ASSERT_TRUE(base::ContainsKey(notification_listener.updates(), + "ogjcoiohnmldgjemafoockdghcjciccf")); notification_listener.Reset(); // Now try doing an update to version 3, which has been incorrectly @@ -352,8 +352,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { ASSERT_TRUE(WaitForExtensionInstallError()); ASSERT_TRUE(notification_listener.started()); ASSERT_TRUE(notification_listener.finished()); - ASSERT_TRUE(ContainsKey(notification_listener.updates(), - "ogjcoiohnmldgjemafoockdghcjciccf")); + ASSERT_TRUE(base::ContainsKey(notification_listener.updates(), + "ogjcoiohnmldgjemafoockdghcjciccf")); // Make sure the extension state is the same as before. ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); @@ -382,7 +382,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); @@ -436,8 +436,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, listener2.WaitUntilSatisfied(); ASSERT_TRUE(notification_listener.started()); ASSERT_TRUE(notification_listener.finished()); - ASSERT_TRUE(ContainsKey(notification_listener.updates(), - "ogjcoiohnmldgjemafoockdghcjciccf")); + ASSERT_TRUE(base::ContainsKey(notification_listener.updates(), + "ogjcoiohnmldgjemafoockdghcjciccf")); notification_listener.Reset(); } @@ -451,7 +451,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); @@ -547,7 +547,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); @@ -628,7 +628,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); diff --git a/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry_unittest.cc b/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry_unittest.cc index c112d4987e5..a95e68a2078 100644 --- a/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry_unittest.cc +++ b/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry_unittest.cc @@ -31,7 +31,7 @@ class TestDnsSdRegistry : public DnsSdRegistry { if (service_data_map_.find(service_type) == service_data_map_.end()) return 0; - return service_data_map_[service_type].get()->GetListenerCount(); + return service_data_map_[service_type]->GetListenerCount(); } MockDnsSdDeviceLister* GetLister(const std::string& service_type) { diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc b/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc index 7cf70265a1f..93613c74bb4 100644 --- a/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc +++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api.cc @@ -66,7 +66,7 @@ void MDnsAPI::SetDnsSdRegistryForTesting( std::unique_ptr<DnsSdRegistry> dns_sd_registry) { dns_sd_registry_ = std::move(dns_sd_registry); if (dns_sd_registry_.get()) - dns_sd_registry_.get()->AddObserver(this); + dns_sd_registry_->AddObserver(this); } void MDnsAPI::ForceDiscovery() { diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc b/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc index 962fde4e0ff..1158bb2d835 100644 --- a/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc @@ -10,7 +10,6 @@ #include <utility> #include <vector> -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_service_test_base.h" @@ -44,10 +43,8 @@ void AddEventListener( extensions::EventListenerMap::ListenerList* listener_list) { std::unique_ptr<base::DictionaryValue> filter(new base::DictionaryValue); filter->SetString(kEventFilterServiceTypeKey, service_type); - listener_list->push_back(make_linked_ptr( - EventListener::ForExtension(kEventFilterServiceTypeKey, extension_id, - nullptr, std::move(filter)) - .release())); + listener_list->push_back(EventListener::ForExtension( + kEventFilterServiceTypeKey, extension_id, nullptr, std::move(filter))); } class NullDelegate : public EventListenerMap::Delegate { @@ -73,18 +70,18 @@ class MockedMDnsAPI : public MDnsAPI { std::unique_ptr<KeyedService> MockedMDnsAPITestingFactoryFunction( content::BrowserContext* context) { - return base::WrapUnique(new MockedMDnsAPI(context)); + return base::MakeUnique<MockedMDnsAPI>(context); } std::unique_ptr<KeyedService> MDnsAPITestingFactoryFunction( content::BrowserContext* context) { - return base::WrapUnique(new MDnsAPI(context)); + return base::MakeUnique<MDnsAPI>(context); } std::unique_ptr<KeyedService> BuildEventRouter( content::BrowserContext* context) { - return base::WrapUnique( - new extensions::EventRouter(context, ExtensionPrefs::Get(context))); + return base::MakeUnique<extensions::EventRouter>( + context, ExtensionPrefs::Get(context)); } // For ExtensionService interface when it requires a path that is not used. @@ -129,8 +126,8 @@ class MockEventRouter : public EventRouter { std::unique_ptr<KeyedService> MockEventRouterFactoryFunction( content::BrowserContext* context) { - return base::WrapUnique( - new MockEventRouter(context, ExtensionPrefs::Get(context))); + return base::MakeUnique<MockEventRouter>(context, + ExtensionPrefs::Get(context)); } class EventServiceListSizeMatcher @@ -376,7 +373,7 @@ TEST_F(MDnsAPITest, ExtensionRespectsWhitelist) { scoped_refptr<extensions::Extension> extension = CreateExtension("Dinosaur networker", false, kExtId); ExtensionRegistry::Get(browser_context())->AddEnabled(extension); - ASSERT_EQ(Manifest::TYPE_EXTENSION, extension.get()->GetType()); + ASSERT_EQ(Manifest::TYPE_EXTENSION, extension->GetType()); // There is a whitelist of mdns service types extensions may access, which // includes "_testing._tcp.local" and exludes "_trex._tcp.local" @@ -426,7 +423,7 @@ TEST_F(MDnsAPITest, PlatformAppsNotSubjectToWhitelist) { scoped_refptr<extensions::Extension> extension = CreateExtension("Dinosaur networker", true, kExtId); ExtensionRegistry::Get(browser_context())->AddEnabled(extension); - ASSERT_TRUE(extension.get()->is_platform_app()); + ASSERT_TRUE(extension->is_platform_app()); base::DictionaryValue filter; filter.SetString(kEventFilterServiceTypeKey, "_trex._tcp.local"); diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc index e51dd435588..8d52332152d 100644 --- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc +++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc @@ -108,14 +108,14 @@ class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest { if (!temp_dir.CreateUniqueTempDir()) return false; - if (!base::CopyDirectory(from_dir, temp_dir.path(), true)) + if (!base::CopyDirectory(from_dir, temp_dir.GetPath(), true)) return false; base::FilePath common_js_path( GetCommonDataDir().AppendASCII("common_injected.js")); - base::FilePath inject_js_path( - temp_dir.path().AppendASCII(extension_name) - .AppendASCII("common_injected.js")); + base::FilePath inject_js_path(temp_dir.GetPath() + .AppendASCII(extension_name) + .AppendASCII("common_injected.js")); if (!base::CopyFile(common_js_path, inject_js_path)) return false; @@ -126,7 +126,7 @@ class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest { custom_arg = json_string.c_str(); } - base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.path()); + base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.GetPath()); bool result = RunPlatformAppTestWithArg(extension_name, custom_arg); content::RunAllPendingInMessageLoop(); // avoid race on exit in registry. return result; @@ -170,8 +170,8 @@ class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest { MediaGalleriesPreferences* preferences = GetAndInitializePreferences(); MediaGalleryPrefInfo gallery_info; - ASSERT_FALSE(preferences->LookUpGalleryByPath(fake_gallery_temp_dir_.path(), - &gallery_info)); + ASSERT_FALSE(preferences->LookUpGalleryByPath( + fake_gallery_temp_dir_.GetPath(), &gallery_info)); MediaGalleryPrefId id = preferences->AddGallery( gallery_info.device_id, gallery_info.path, @@ -199,7 +199,7 @@ class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest { ASSERT_TRUE(base::CopyFile( source_path, - fake_gallery_temp_dir_.path().Append(source_path.BaseName()))); + fake_gallery_temp_dir_.GetPath().Append(source_path.BaseName()))); } #if defined(OS_WIN) || defined(OS_MACOSX) @@ -304,9 +304,9 @@ IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppPpapiTest, SendFilesystem) { ASSERT_TRUE(extension); extensions::ResultCatcher catcher; - AppLaunchParams params(browser()->profile(), extension, - extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW, - extensions::SOURCE_TEST); + AppLaunchParams params( + browser()->profile(), extension, extensions::LAUNCH_CONTAINER_NONE, + WindowOpenDisposition::NEW_WINDOW, extensions::SOURCE_TEST); params.command_line = *base::CommandLine::ForCurrentProcess(); OpenApplication(params); @@ -426,8 +426,8 @@ IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, base::ScopedTempDir custom_picasa_app_data_root; ASSERT_TRUE(custom_picasa_app_data_root.CreateUniqueTempDir()); ensure_media_directories_exists()->SetCustomPicasaAppDataPath( - custom_picasa_app_data_root.path()); - PopulatePicasaTestData(custom_picasa_app_data_root.path()); + custom_picasa_app_data_root.GetPath()); + PopulatePicasaTestData(custom_picasa_app_data_root.GetPath()); base::ListValue custom_args; custom_args.AppendInteger(test_jpg_size()); diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc index 0a209503948..5c0a5003d55 100644 --- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc +++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc @@ -110,7 +110,7 @@ class MediaGalleriesGalleryWatchApiTest : public ExtensionApiTest { bool AddNewFileInTestGallery() { base::FilePath gallery_file = - test_gallery_.path().Append(FILE_PATH_LITERAL("test1.txt")); + test_gallery_.GetPath().Append(FILE_PATH_LITERAL("test1.txt")); std::string content("new content"); int write_size = base::WriteFile(gallery_file, content.c_str(), content.length()); @@ -147,8 +147,8 @@ class MediaGalleriesGalleryWatchApiTest : public ExtensionApiTest { ASSERT_TRUE(test_gallery_.CreateUniqueTempDir()); MediaGalleryPrefInfo gallery_info; - ASSERT_FALSE( - preferences->LookUpGalleryByPath(test_gallery_.path(), &gallery_info)); + ASSERT_FALSE(preferences->LookUpGalleryByPath(test_gallery_.GetPath(), + &gallery_info)); MediaGalleryPrefId id = preferences->AddGallery(gallery_info.device_id, gallery_info.path, diff --git a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc index 6a544a50ff6..2e7f5952750 100644 --- a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc +++ b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc @@ -216,19 +216,19 @@ void ExtensionMessagePort::DispatchOnConnect( info.guest_process_id = guest_process_id; info.guest_render_frame_routing_id = guest_render_frame_routing_id; - SendToPort(base::WrapUnique(new ExtensionMsg_DispatchOnConnect( - MSG_ROUTING_NONE, port_id_, channel_name, source, info, tls_channel_id))); + SendToPort(base::MakeUnique<ExtensionMsg_DispatchOnConnect>( + MSG_ROUTING_NONE, port_id_, channel_name, source, info, tls_channel_id)); } void ExtensionMessagePort::DispatchOnDisconnect( const std::string& error_message) { - SendToPort(base::WrapUnique(new ExtensionMsg_DispatchOnDisconnect( - MSG_ROUTING_NONE, port_id_, error_message))); + SendToPort(base::MakeUnique<ExtensionMsg_DispatchOnDisconnect>( + MSG_ROUTING_NONE, port_id_, error_message)); } void ExtensionMessagePort::DispatchOnMessage(const Message& message) { - SendToPort(base::WrapUnique(new ExtensionMsg_DeliverMessage( - MSG_ROUTING_NONE, port_id_, opener_tab_id_, message))); + SendToPort(base::MakeUnique<ExtensionMsg_DeliverMessage>( + MSG_ROUTING_NONE, port_id_, opener_tab_id_, message)); } void ExtensionMessagePort::IncrementLazyKeepaliveCount() { @@ -304,7 +304,7 @@ void ExtensionMessagePort::SendToPort(std::unique_ptr<IPC::Message> msg) { return; } for (content::RenderFrameHost* rfh : frames_) { - IPC::Message* msg_copy = new IPC::Message(*msg.get()); + IPC::Message* msg_copy = new IPC::Message(*msg); msg_copy->set_routing_id(rfh->GetRoutingID()); rfh->Send(msg_copy); } diff --git a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc index 5fcf6184d79..f361ab5819d 100644 --- a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc +++ b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc @@ -242,10 +242,10 @@ void IncognitoConnectability::OnInteractiveResponse( break; } - DCHECK(ContainsKey(pending_origins_, make_pair(extension_id, origin))); + DCHECK(base::ContainsKey(pending_origins_, make_pair(extension_id, origin))); PendingOrigin& pending_origin = pending_origins_[make_pair(extension_id, origin)]; - DCHECK(ContainsKey(pending_origin, infobar_manager)); + DCHECK(base::ContainsKey(pending_origin, infobar_manager)); std::vector<base::Callback<void(bool)>> callbacks; if (response == ScopedAlertTracker::INTERACTIVE) { diff --git a/chromium/chrome/browser/extensions/api/messaging/message_service.cc b/chromium/chrome/browser/extensions/api/messaging/message_service.cc index 92af5069b93..5b4c3829bff 100644 --- a/chromium/chrome/browser/extensions/api/messaging/message_service.cc +++ b/chromium/chrome/browser/extensions/api/messaging/message_service.cc @@ -14,8 +14,8 @@ #include "base/json/json_writer.h" #include "base/lazy_instance.h" #include "base/macros.h" -#include "base/metrics/histogram.h" -#include "base/stl_util.h" +#include "base/memory/ptr_util.h" +#include "base/metrics/histogram_macros.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/messaging/extension_message_port.h" #include "chrome/browser/extensions/api/messaging/incognito_connectability.h" @@ -233,7 +233,6 @@ MessageService::MessageService(BrowserContext* context) MessageService::~MessageService() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - STLDeleteContainerPairSecondPointers(channels_.begin(), channels_.end()); channels_.clear(); } @@ -477,7 +476,7 @@ void MessageService::OpenChannelToNativeApp( // Keep the opener alive until the channel is closed. channel->opener->IncrementLazyKeepaliveCount(); - AddChannel(channel.release(), receiver_port_id); + AddChannel(std::move(channel), receiver_port_id); #else // !(defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)) const char kNativeMessagingNotSupportedError[] = "Native Messaging is not supported on this platform."; @@ -588,10 +587,12 @@ void MessageService::OpenChannelImpl(BrowserContext* browser_context, return; } - MessageChannel* channel(new MessageChannel()); + std::unique_ptr<MessageChannel> channel_ptr = + base::MakeUnique<MessageChannel>(); + MessageChannel* channel = channel_ptr.get(); channel->opener.reset(opener.release()); channel->receiver.reset(params->receiver.release()); - AddChannel(channel, params->receiver_port_id); + AddChannel(std::move(channel_ptr), params->receiver_port_id); // TODO(robwu): Could |guest_process_id| and |guest_render_frame_routing_id| // be removed? In the past extension message routing was process-based, but @@ -652,12 +653,13 @@ void MessageService::OpenChannelImpl(BrowserContext* browser_context, channel->receiver->IncrementLazyKeepaliveCount(); } -void MessageService::AddChannel(MessageChannel* channel, int receiver_port_id) { +void MessageService::AddChannel(std::unique_ptr<MessageChannel> channel, + int receiver_port_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int channel_id = GET_CHANNEL_ID(receiver_port_id); CHECK(channels_.find(channel_id) == channels_.end()); - channels_[channel_id] = channel; + channels_[channel_id] = std::move(channel); pending_lazy_background_page_channels_.erase(channel_id); } @@ -726,7 +728,7 @@ void MessageService::CloseChannelImpl( bool notify_other_port) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - MessageChannel* channel = channel_iter->second; + std::unique_ptr<MessageChannel> channel = std::move(channel_iter->second); // Remove from map to make sure that it is impossible for CloseChannelImpl to // run twice for the same channel. channels_.erase(channel_iter); @@ -741,8 +743,6 @@ void MessageService::CloseChannelImpl( // Balance the IncrementLazyKeepaliveCount() in OpenChannelImpl. channel->opener->DecrementLazyKeepaliveCount(); channel->receiver->DecrementLazyKeepaliveCount(); - - delete channel; } void MessageService::PostMessage(int source_port_id, const Message& message) { @@ -757,7 +757,7 @@ void MessageService::PostMessage(int source_port_id, const Message& message) { return; } - DispatchMessage(source_port_id, iter->second, message); + DispatchMessage(source_port_id, iter->second.get(), message); } void MessageService::EnqueuePendingMessage(int source_port_id, @@ -772,8 +772,9 @@ void MessageService::EnqueuePendingMessage(int source_port_id, PendingMessage(source_port_id, message)); // A channel should only be holding pending messages because it is in one // of these states. - DCHECK(!ContainsKey(pending_tls_channel_id_channels_, channel_id)); - DCHECK(!ContainsKey(pending_lazy_background_page_channels_, channel_id)); + DCHECK(!base::ContainsKey(pending_tls_channel_id_channels_, channel_id)); + DCHECK( + !base::ContainsKey(pending_lazy_background_page_channels_, channel_id)); return; } PendingChannelMap::iterator pending_for_tls_channel_id = @@ -783,7 +784,8 @@ void MessageService::EnqueuePendingMessage(int source_port_id, PendingMessage(source_port_id, message)); // A channel should only be holding pending messages because it is in one // of these states. - DCHECK(!ContainsKey(pending_lazy_background_page_channels_, channel_id)); + DCHECK( + !base::ContainsKey(pending_lazy_background_page_channels_, channel_id)); return; } EnqueuePendingMessageForLazyBackgroundLoad(source_port_id, @@ -1016,7 +1018,8 @@ void MessageService::DispatchPendingMessages(const PendingMessagesQueue& queue, MessageChannelMap::iterator channel_iter = channels_.find(channel_id); if (channel_iter != channels_.end()) { for (const PendingMessage& message : queue) { - DispatchMessage(message.first, channel_iter->second, message.second); + DispatchMessage(message.first, channel_iter->second.get(), + message.second); } } } diff --git a/chromium/chrome/browser/extensions/api/messaging/message_service.h b/chromium/chrome/browser/extensions/api/messaging/message_service.h index fa641f3be4a..2c6b52d0b24 100644 --- a/chromium/chrome/browser/extensions/api/messaging/message_service.h +++ b/chromium/chrome/browser/extensions/api/messaging/message_service.h @@ -185,21 +185,21 @@ class MessageService : public BrowserContextKeyedAPI { struct OpenChannelParams; // A map of channel ID to its channel object. - typedef std::map<int, MessageChannel*> MessageChannelMap; + using MessageChannelMap = std::map<int, std::unique_ptr<MessageChannel>>; - typedef std::pair<int, Message> PendingMessage; - typedef std::vector<PendingMessage> PendingMessagesQueue; + using PendingMessage = std::pair<int, Message>; + using PendingMessagesQueue = std::vector<PendingMessage>; // A set of channel IDs waiting to complete opening, and any pending messages // queued to be sent on those channels. - typedef std::map<int, PendingMessagesQueue> PendingChannelMap; + using PendingChannelMap = std::map<int, PendingMessagesQueue>; // A map of channel ID to information about the extension that is waiting // for that channel to open. Used for lazy background pages. - typedef std::string ExtensionID; - typedef std::pair<content::BrowserContext*, ExtensionID> - PendingLazyBackgroundPageChannel; - typedef std::map<int, PendingLazyBackgroundPageChannel> - PendingLazyBackgroundPageChannelMap; + using ExtensionID = std::string; + using PendingLazyBackgroundPageChannel = + std::pair<content::BrowserContext*, ExtensionID>; + using PendingLazyBackgroundPageChannelMap = + std::map<int, PendingLazyBackgroundPageChannel>; // Common implementation for opening a channel configured by |params|. // @@ -226,7 +226,8 @@ class MessageService : public BrowserContextKeyedAPI { // Have MessageService take ownership of |channel|, and remove any pending // channels with the same id. - void AddChannel(MessageChannel* channel, int receiver_port_id); + void AddChannel(std::unique_ptr<MessageChannel> channel, + int receiver_port_id); // If the channel is being opened from an incognito tab the user must allow // the connection. 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 da51abd3faa..031aa73aec5 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 @@ -18,7 +18,6 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/arc/arc_support_host.h" -#include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h" #include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/constants.h" @@ -96,19 +95,19 @@ struct BuiltInHost { std::unique_ptr<NativeMessageHost> CreateIt2MeHost() { std::unique_ptr<remoting::It2MeHostFactory> host_factory( new remoting::It2MeHostFactory()); - host_factory->set_policy_service(g_browser_process->policy_service()); std::unique_ptr<remoting::ChromotingHostContext> context = remoting::ChromotingHostContext::CreateForChromeOS( make_scoped_refptr(g_browser_process->system_request_context()), - content::BrowserThread::GetMessageLoopProxyForThread( + content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO), - content::BrowserThread::GetMessageLoopProxyForThread( + content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI), - content::BrowserThread::GetMessageLoopProxyForThread( + content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::FILE)); std::unique_ptr<NativeMessageHost> host( - new remoting::It2MeNativeMessagingHost(std::move(context), - std::move(host_factory))); + new remoting::It2MeNativeMessagingHost( + /*needs_elevation=*/false, g_browser_process->policy_service(), + std::move(context), std::move(host_factory))); return host; } 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 681ec348fef..7d4304e31ee 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 @@ -58,7 +58,7 @@ NativeMessageProcessHost::NativeMessageProcessHost( weak_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_ = content::BrowserThread::GetMessageLoopProxyForThread( + task_runner_ = content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO); } @@ -199,17 +199,6 @@ NativeMessageProcessHost::task_runner() const { return task_runner_; } -#if defined(OS_POSIX) -void NativeMessageProcessHost::OnFileCanReadWithoutBlocking(int fd) { - DCHECK_EQ(fd, read_file_); - DoRead(); -} - -void NativeMessageProcessHost::OnFileCanWriteWithoutBlocking(int fd) { - NOTREACHED(); -} -#endif // !defined(OS_POSIX) - void NativeMessageProcessHost::ReadNowForTesting() { DoRead(); } @@ -225,9 +214,9 @@ void NativeMessageProcessHost::WaitRead() { // would always be consuming one thread in the thread pool. On Windows // FileStream uses overlapped IO, so that optimization isn't necessary there. #if defined(OS_POSIX) - base::MessageLoopForIO::current()->WatchFileDescriptor( - read_file_, false /* persistent */, - base::MessageLoopForIO::WATCH_READ, &read_watcher_, this); + read_controller_ = base::FileDescriptorWatcher::WatchReadable( + read_file_, + base::Bind(&NativeMessageProcessHost::DoRead, base::Unretained(this))); #else // defined(OS_POSIX) DoRead(); #endif // defined(!OS_POSIX) @@ -236,6 +225,10 @@ void NativeMessageProcessHost::WaitRead() { void NativeMessageProcessHost::DoRead() { DCHECK(task_runner_->BelongsToCurrentThread()); +#if defined(OS_POSIX) + read_controller_.reset(); +#endif + while (!closed_ && !read_pending_) { read_buffer_ = new net::IOBuffer(kReadBufferSize); int result = diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h index cefb070d42d..547878be3a5 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h @@ -11,13 +11,17 @@ #include "base/files/file.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/memory/weak_ptr.h" #include "base/process/process.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/messaging/native_process_launcher.h" #include "extensions/browser/api/messaging/native_message_host.h" #include "ui/gfx/native_widget_types.h" +#if defined(OS_POSIX) +#include "base/files/file_descriptor_watcher_posix.h" +#endif + namespace net { class DrainableIOBuffer; @@ -35,11 +39,7 @@ namespace extensions { // This class must only be created, called, and deleted on the IO thread. // Public methods typically accept callbacks which will be invoked on the UI // thread. -class NativeMessageProcessHost : -#if defined(OS_POSIX) - public base::MessageLoopForIO::Watcher, -#endif // !defined(OS_POSIX) - public NativeMessageHost { +class NativeMessageProcessHost : public NativeMessageHost { public: ~NativeMessageProcessHost() override; @@ -54,12 +54,6 @@ class NativeMessageProcessHost : void Start(Client* client) override; scoped_refptr<base::SingleThreadTaskRunner> task_runner() const override; -#if defined(OS_POSIX) - // MessageLoopForIO::Watcher interface - void OnFileCanReadWithoutBlocking(int fd) override; - void OnFileCanWriteWithoutBlocking(int fd) override; -#endif // !defined(OS_POSIX) - // Try and read a single message from |read_file_|. This should only be called // in unittests when you know there is data in the file. void ReadNowForTesting(); @@ -117,7 +111,7 @@ class NativeMessageProcessHost : #if defined(OS_POSIX) base::PlatformFile read_file_; - base::MessageLoopForIO::FileDescriptorWatcher read_watcher_; + std::unique_ptr<base::FileDescriptorWatcher::Controller> read_controller_; #endif // !defined(OS_POSIX) // Write stream. 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 15e94958cc5..4d8cf88d382 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 @@ -28,13 +28,17 @@ #include "build/build_config.h" #include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h" #include "chrome/browser/extensions/api/messaging/native_process_launcher.h" -#include "chrome/common/extensions/features/feature_channel.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 "extensions/common/extension.h" +#include "extensions/common/features/feature_channel.h" #include "testing/gtest/include/gtest/gtest.h" +#if defined(OS_POSIX) +#include "base/files/file_descriptor_watcher_posix.h" +#endif + #if defined(OS_WIN) #include <windows.h> #include "base/win/scoped_handle.h" @@ -102,6 +106,9 @@ class NativeMessagingTest : public ::testing::Test, NativeMessagingTest() : current_channel_(version_info::Channel::DEV), thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), +#if defined(OS_POSIX) + file_descriptor_watcher_(base::MessageLoopForIO::current()), +#endif channel_closed_(false) {} void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } @@ -145,7 +152,7 @@ class NativeMessagingTest : public ::testing::Test, base::FilePath CreateTempFileWithMessage(const std::string& message) { base::FilePath filename; - if (!base::CreateTemporaryFileInDir(temp_dir_.path(), &filename)) + if (!base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &filename)) return base::FilePath(); std::string message_with_header = FormatMessage(message); @@ -164,6 +171,11 @@ class NativeMessagingTest : public ::testing::Test, std::unique_ptr<NativeMessageHost> native_message_host_; std::unique_ptr<base::RunLoop> run_loop_; content::TestBrowserThreadBundle thread_bundle_; +#if defined(OS_POSIX) + // Required to watch a file descriptor from NativeMessageProcessHost. + base::FileDescriptorWatcher file_descriptor_watcher_; +#endif + std::string last_message_; std::unique_ptr<base::DictionaryValue> last_message_parsed_; bool channel_closed_; @@ -171,7 +183,7 @@ class NativeMessagingTest : public ::testing::Test, // Read a single message from a local file. TEST_F(NativeMessagingTest, SingleSendMessageRead) { - base::FilePath temp_output_file = temp_dir_.path().AppendASCII("output"); + base::FilePath temp_output_file = temp_dir_.GetPath().AppendASCII("output"); base::FilePath temp_input_file = CreateTempFileWithMessage(kTestMessage); ASSERT_FALSE(temp_input_file.empty()); @@ -198,7 +210,7 @@ TEST_F(NativeMessagingTest, SingleSendMessageRead) { // Tests sending a single message. The message should get written to // |temp_file| and should match the contents of single_message_request.msg. TEST_F(NativeMessagingTest, SingleSendMessageWrite) { - base::FilePath temp_output_file = temp_dir_.path().AppendASCII("output"); + base::FilePath temp_output_file = temp_dir_.GetPath().AppendASCII("output"); base::File read_file; #if defined(OS_WIN) diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc index 1600a20ee98..41707f36c35 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc @@ -28,7 +28,7 @@ class NativeMessagingHostManifestTest : public ::testing::Test { public: void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - manifest_path_ = temp_dir_.path().AppendASCII("test.json"); + manifest_path_ = temp_dir_.GetPath().AppendASCII("test.json"); } protected: diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc index 48ebebc7138..fee82b6c469 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc @@ -11,9 +11,9 @@ #include "chrome/browser/extensions/external_policy_loader.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/policy_constants.h" #include "components/prefs/pref_value_map.h" -#include "grit/components_strings.h" -#include "policy/policy_constants.h" +#include "components/strings/grit/components_strings.h" namespace extensions { @@ -69,10 +69,9 @@ bool NativeMessagingHostListPolicyHandler::CheckAndGetList( entry != list_value->end(); ++entry) { std::string name; if (!(*entry)->GetAsString(&name)) { - errors->AddError(policy_name(), - entry - list_value->begin(), + errors->AddError(policy_name(), entry - list_value->begin(), IDS_POLICY_TYPE_ERROR, - ValueTypeToString(base::Value::TYPE_STRING)); + base::Value::GetTypeName(base::Value::TYPE_STRING)); continue; } if (!(allow_wildcards_ && name == "*") && diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc index a5078456c6f..806cd753217 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc @@ -8,8 +8,8 @@ #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" +#include "components/policy/policy_constants.h" #include "components/prefs/pref_value_map.h" -#include "policy/policy_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc index 0c694477a62..085f6c1d05e 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc @@ -82,7 +82,7 @@ void ScopedTestNativeMessagingHost::RegisterTestHost(bool user_level) { path_override_.reset(new base::ScopedPathOverride( user_level ? chrome::DIR_USER_NATIVE_MESSAGING : chrome::DIR_NATIVE_MESSAGING, - temp_dir_.path())); + temp_dir_.GetPath())); #endif #if defined(OS_POSIX) @@ -91,10 +91,10 @@ void ScopedTestNativeMessagingHost::RegisterTestHost(bool user_level) { base::FilePath host_path = test_user_data_dir.AppendASCII("echo.bat"); #endif ASSERT_NO_FATAL_FAILURE(WriteTestNativeHostManifest( - temp_dir_.path(), kHostName, host_path, user_level)); + temp_dir_.GetPath(), kHostName, host_path, user_level)); ASSERT_NO_FATAL_FAILURE(WriteTestNativeHostManifest( - temp_dir_.path(), kBinaryMissingHostName, + temp_dir_.GetPath(), kBinaryMissingHostName, test_user_data_dir.AppendASCII("missing_nm_binary.exe"), user_level)); } 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 f297d989967..e5ceaffe041 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc @@ -13,8 +13,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" +#include "base/strings/stringprintf.h" #include "base/threading/sequenced_worker_pool.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h" @@ -30,12 +29,6 @@ namespace extensions { namespace { -#if defined(OS_WIN) -// Name of the command line switch used to pass handle of the native view to -// the native messaging host. -const char kParentWindowSwitchName[] = "parent-window"; -#endif // defined(OS_WIN) - // Default implementation on NativeProcessLauncher interface. class NativeProcessLauncherImpl : public NativeProcessLauncher { public: @@ -190,13 +183,16 @@ void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool( } base::CommandLine command_line(host_path); + // Note: The origin must be the first argument, so do not use AppendSwitch* + // hereafter because CommandLine inserts these switches before the other + // arguments. command_line.AppendArg(origin.spec()); // Pass handle of the native view window to the native messaging host. This // way the host will be able to create properly focused UI windows. #if defined(OS_WIN) - command_line.AppendSwitchASCII(kParentWindowSwitchName, - base::Int64ToString(window_handle_)); + command_line.AppendArg( + base::StringPrintf("--parent-window=%d", window_handle_)); #endif // !defined(OS_WIN) base::Process process; diff --git a/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.cc b/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.cc new file mode 100644 index 00000000000..9771932b73b --- /dev/null +++ b/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.cc @@ -0,0 +1,15 @@ +// 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/extensions/api/metrics_private/chrome_metrics_private_delegate.h" + +#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" + +namespace extensions { + +bool ChromeMetricsPrivateDelegate::IsCrashReportingEnabled() { + return ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled(); +} + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h b/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h new file mode 100644 index 00000000000..eb2c605383b --- /dev/null +++ b/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h @@ -0,0 +1,27 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_METRICS_PRIVATE_CHROME_METRICS_PRIVATE_DELEGATE_H_ +#define CHROME_BROWSER_EXTENSIONS_API_METRICS_PRIVATE_CHROME_METRICS_PRIVATE_DELEGATE_H_ + +#include "base/macros.h" +#include "extensions/browser/api/metrics_private/metrics_private_delegate.h" + +namespace extensions { + +class ChromeMetricsPrivateDelegate : public MetricsPrivateDelegate { + public: + ChromeMetricsPrivateDelegate() {} + ~ChromeMetricsPrivateDelegate() override {} + + // MetricsPrivateDelegate: + bool IsCrashReportingEnabled() override; + + private: + DISALLOW_COPY_AND_ASSIGN(ChromeMetricsPrivateDelegate); +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_METRICS_PRIVATE_CHROME_METRICS_PRIVATE_DELEGATE_H_ diff --git a/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc b/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc index 83b6a7fad5c..86a41a6063f 100644 --- a/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc +++ b/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc @@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/metrics/field_trial.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/metrics/statistics_recorder.h" #include "base/test/user_action_tester.h" #include "chrome/browser/extensions/extension_apitest.h" diff --git a/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.cc b/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.cc index 191c7978a58..f761f5a9fc3 100644 --- a/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.cc +++ b/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.cc @@ -10,20 +10,18 @@ #include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" -#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/common/extensions/api/metrics_private.h" #include "components/variations/variations_associated_data.h" #include "content/public/browser/user_metrics.h" +#include "extensions/browser/api/extensions_api_client.h" +#include "extensions/browser/api/metrics_private/metrics_private_delegate.h" #include "extensions/common/extension.h" namespace extensions { -namespace GetIsCrashReportingEnabled = - api::metrics_private::GetIsCrashReportingEnabled; namespace GetVariationParams = api::metrics_private::GetVariationParams; -namespace GetFieldTrial = api::metrics_private::GetFieldTrial; namespace RecordUserAction = api::metrics_private::RecordUserAction; namespace RecordValue = api::metrics_private::RecordValue; namespace RecordSparseValue = api::metrics_private::RecordSparseValue; @@ -42,48 +40,53 @@ const size_t kMaxBuckets = 10000; // We don't ever want more than these many // and would cause crazy memory usage } // namespace -bool MetricsPrivateGetIsCrashReportingEnabledFunction::RunSync() { - SetResult(base::MakeUnique<base::FundamentalValue>( - ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled())); - return true; +ExtensionFunction::ResponseAction +MetricsPrivateGetIsCrashReportingEnabledFunction::Run() { + MetricsPrivateDelegate* delegate = + ExtensionsAPIClient::Get()->GetMetricsPrivateDelegate(); + return RespondNow(OneArgument(base::MakeUnique<base::FundamentalValue>( + delegate && delegate->IsCrashReportingEnabled()))); } -bool MetricsPrivateGetFieldTrialFunction::RunSync() { +ExtensionFunction::ResponseAction MetricsPrivateGetFieldTrialFunction::Run() { std::string name; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &name)); - SetResult(base::MakeUnique<base::StringValue>( - base::FieldTrialList::FindFullName(name))); - return true; + return RespondNow(OneArgument(base::MakeUnique<base::StringValue>( + base::FieldTrialList::FindFullName(name)))); } -bool MetricsPrivateGetVariationParamsFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateGetVariationParamsFunction::Run() { std::unique_ptr<GetVariationParams::Params> params( GetVariationParams::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); GetVariationParams::Results::Params result; + std::unique_ptr<base::DictionaryValue> dict; if (variations::GetVariationParams(params->name, &result.additional_properties)) { - SetResult(result.ToValue()); + dict = result.ToValue(); } - return true; + return RespondNow(dict ? OneArgument(std::move(dict)) : NoArguments()); } -bool MetricsPrivateRecordUserActionFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateRecordUserActionFunction::Run() { std::unique_ptr<RecordUserAction::Params> params( RecordUserAction::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); content::RecordComputedAction(params->name); - return true; + return RespondNow(NoArguments()); } -bool MetricsHistogramHelperFunction::RecordValue( - const std::string& name, - base::HistogramType type, - int min, int max, size_t buckets, - int sample) { +void MetricsHistogramHelperFunction::RecordValue(const std::string& name, + base::HistogramType type, + int min, + int max, + size_t buckets, + int sample) { // Make sure toxic values don't get to internal code. // Fix for maximums min = std::min(min, INT_MAX - 3); @@ -112,10 +115,9 @@ bool MetricsHistogramHelperFunction::RecordValue( // that data for this API. An error message will be logged. if (counter) counter->Add(sample); - return true; } -bool MetricsPrivateRecordValueFunction::RunSync() { +ExtensionFunction::ResponseAction MetricsPrivateRecordValueFunction::Run() { std::unique_ptr<RecordValue::Params> params( RecordValue::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -125,78 +127,89 @@ bool MetricsPrivateRecordValueFunction::RunSync() { base::HistogramType histogram_type(type == "histogram-linear" ? base::LINEAR_HISTOGRAM : base::HISTOGRAM); - return RecordValue(params->metric.metric_name, histogram_type, - params->metric.min, params->metric.max, - params->metric.buckets, params->value); + RecordValue(params->metric.metric_name, histogram_type, params->metric.min, + params->metric.max, params->metric.buckets, params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordSparseValueFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateRecordSparseValueFunction::Run() { std::unique_ptr<RecordSparseValue::Params> params( RecordSparseValue::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); // This particular UMA_HISTOGRAM_ macro is okay for // non-runtime-constant strings. UMA_HISTOGRAM_SPARSE_SLOWLY(params->metric_name, params->value); - return true; + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordPercentageFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateRecordPercentageFunction::Run() { std::unique_ptr<RecordPercentage::Params> params( RecordPercentage::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - return RecordValue(params->metric_name, base::LINEAR_HISTOGRAM, - 1, 101, 102, params->value); + RecordValue(params->metric_name, base::LINEAR_HISTOGRAM, 1, 101, 102, + params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordCountFunction::RunSync() { +ExtensionFunction::ResponseAction MetricsPrivateRecordCountFunction::Run() { std::unique_ptr<RecordCount::Params> params( RecordCount::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - return RecordValue(params->metric_name, base::HISTOGRAM, - 1, 1000000, 50, params->value); + RecordValue(params->metric_name, base::HISTOGRAM, 1, 1000000, 50, + params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordSmallCountFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateRecordSmallCountFunction::Run() { std::unique_ptr<RecordSmallCount::Params> params( RecordSmallCount::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - return RecordValue(params->metric_name, base::HISTOGRAM, - 1, 100, 50, params->value); + RecordValue(params->metric_name, base::HISTOGRAM, 1, 100, 50, params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordMediumCountFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateRecordMediumCountFunction::Run() { std::unique_ptr<RecordMediumCount::Params> params( RecordMediumCount::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - return RecordValue(params->metric_name, base::HISTOGRAM, - 1, 10000, 50, params->value); + RecordValue(params->metric_name, base::HISTOGRAM, 1, 10000, 50, + params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordTimeFunction::RunSync() { +ExtensionFunction::ResponseAction MetricsPrivateRecordTimeFunction::Run() { std::unique_ptr<RecordTime::Params> params( RecordTime::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); static const int kTenSecMs = 10 * 1000; - return RecordValue(params->metric_name, base::HISTOGRAM, - 1, kTenSecMs, 50, params->value); + RecordValue(params->metric_name, base::HISTOGRAM, 1, kTenSecMs, 50, + params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordMediumTimeFunction::RunSync() { +ExtensionFunction::ResponseAction +MetricsPrivateRecordMediumTimeFunction::Run() { std::unique_ptr<RecordMediumTime::Params> params( RecordMediumTime::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); static const int kThreeMinMs = 3 * 60 * 1000; - return RecordValue(params->metric_name, base::HISTOGRAM, - 1, kThreeMinMs, 50, params->value); + RecordValue(params->metric_name, base::HISTOGRAM, 1, kThreeMinMs, 50, + params->value); + return RespondNow(NoArguments()); } -bool MetricsPrivateRecordLongTimeFunction::RunSync() { +ExtensionFunction::ResponseAction MetricsPrivateRecordLongTimeFunction::Run() { std::unique_ptr<RecordLongTime::Params> params( RecordLongTime::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); static const int kOneHourMs = 60 * 60 * 1000; - return RecordValue(params->metric_name, base::HISTOGRAM, - 1, kOneHourMs, 50, params->value); + RecordValue(params->metric_name, base::HISTOGRAM, 1, kOneHourMs, 50, + params->value); + return RespondNow(NoArguments()); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.h b/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.h index e16ca4f6bbf..21e1e7ba7fb 100644 --- a/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.h +++ b/chromium/chrome/browser/extensions/api/metrics_private/metrics_private_api.h @@ -15,7 +15,7 @@ namespace extensions { class MetricsPrivateGetIsCrashReportingEnabledFunction - : public SyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.getIsCrashReportingEnabled", METRICSPRIVATE_GETISCRASHRECORDINGENABLED) @@ -24,10 +24,10 @@ class MetricsPrivateGetIsCrashReportingEnabledFunction ~MetricsPrivateGetIsCrashReportingEnabledFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class MetricsPrivateGetFieldTrialFunction : public SyncExtensionFunction { +class MetricsPrivateGetFieldTrialFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.getFieldTrial", METRICSPRIVATE_GETFIELDTRIAL) @@ -36,10 +36,11 @@ class MetricsPrivateGetFieldTrialFunction : public SyncExtensionFunction { ~MetricsPrivateGetFieldTrialFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class MetricsPrivateGetVariationParamsFunction : public SyncExtensionFunction { +class MetricsPrivateGetVariationParamsFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.getVariationParams", METRICSPRIVATE_GETVARIATIONPARAMS) @@ -48,10 +49,11 @@ class MetricsPrivateGetVariationParamsFunction : public SyncExtensionFunction { ~MetricsPrivateGetVariationParamsFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class MetricsPrivateRecordUserActionFunction : public SyncExtensionFunction { +class MetricsPrivateRecordUserActionFunction + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.recordUserAction", METRICSPRIVATE_RECORDUSERACTION) @@ -60,16 +62,18 @@ class MetricsPrivateRecordUserActionFunction : public SyncExtensionFunction { ~MetricsPrivateRecordUserActionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; -class MetricsHistogramHelperFunction : public SyncExtensionFunction { +class MetricsHistogramHelperFunction : public UIThreadExtensionFunction { protected: ~MetricsHistogramHelperFunction() override {} - virtual bool RecordValue(const std::string& name, - base::HistogramType type, - int min, int max, size_t buckets, - int sample); + void RecordValue(const std::string& name, + base::HistogramType type, + int min, + int max, + size_t buckets, + int sample); }; class MetricsPrivateRecordValueFunction @@ -82,7 +86,7 @@ class MetricsPrivateRecordValueFunction ~MetricsPrivateRecordValueFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordSparseValueFunction @@ -95,7 +99,7 @@ class MetricsPrivateRecordSparseValueFunction ~MetricsPrivateRecordSparseValueFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordPercentageFunction @@ -108,7 +112,7 @@ class MetricsPrivateRecordPercentageFunction ~MetricsPrivateRecordPercentageFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordCountFunction @@ -121,7 +125,7 @@ class MetricsPrivateRecordCountFunction ~MetricsPrivateRecordCountFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordSmallCountFunction @@ -134,7 +138,7 @@ class MetricsPrivateRecordSmallCountFunction ~MetricsPrivateRecordSmallCountFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordMediumCountFunction @@ -147,7 +151,7 @@ class MetricsPrivateRecordMediumCountFunction ~MetricsPrivateRecordMediumCountFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordTimeFunction : public MetricsHistogramHelperFunction { @@ -159,7 +163,7 @@ class MetricsPrivateRecordTimeFunction : public MetricsHistogramHelperFunction { ~MetricsPrivateRecordTimeFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordMediumTimeFunction @@ -172,7 +176,7 @@ class MetricsPrivateRecordMediumTimeFunction ~MetricsPrivateRecordMediumTimeFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class MetricsPrivateRecordLongTimeFunction @@ -185,7 +189,7 @@ class MetricsPrivateRecordLongTimeFunction ~MetricsPrivateRecordLongTimeFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/module/module.cc b/chromium/chrome/browser/extensions/api/module/module.cc index 7bd4f26599a..d98c2a05ad8 100644 --- a/chromium/chrome/browser/extensions/api/module/module.cc +++ b/chromium/chrome/browser/extensions/api/module/module.cc @@ -37,29 +37,30 @@ std::string GetUpdateURLData(const ExtensionPrefs* prefs, } // namespace extension -bool ExtensionSetUpdateUrlDataFunction::RunSync() { +ExtensionFunction::ResponseAction ExtensionSetUpdateUrlDataFunction::Run() { std::string data; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &data)); if (ManifestURL::UpdatesFromGallery(extension())) { - return false; + return RespondNow(Error(kUnknownErrorDoNotUse)); } - ExtensionPrefs::Get(GetProfile())->UpdateExtensionPref( - extension_id(), extension::kUpdateURLData, new base::StringValue(data)); - return true; + ExtensionPrefs::Get(browser_context()) + ->UpdateExtensionPref(extension_id(), extension::kUpdateURLData, + new base::StringValue(data)); + return RespondNow(NoArguments()); } -bool ExtensionIsAllowedIncognitoAccessFunction::RunSync() { - SetResult(base::MakeUnique<base::FundamentalValue>( - util::IsIncognitoEnabled(extension_id(), GetProfile()))); - return true; +ExtensionFunction::ResponseAction +ExtensionIsAllowedIncognitoAccessFunction::Run() { + return RespondNow(OneArgument(base::MakeUnique<base::FundamentalValue>( + util::IsIncognitoEnabled(extension_id(), browser_context())))); } -bool ExtensionIsAllowedFileSchemeAccessFunction::RunSync() { - SetResult(base::MakeUnique<base::FundamentalValue>( - util::AllowFileAccess(extension_id(), GetProfile()))); - return true; +ExtensionFunction::ResponseAction +ExtensionIsAllowedFileSchemeAccessFunction::Run() { + return RespondNow(OneArgument(base::MakeUnique<base::FundamentalValue>( + util::AllowFileAccess(extension_id(), browser_context())))); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/module/module.h b/chromium/chrome/browser/extensions/api/module/module.h index c35249941c3..de81de0d8a8 100644 --- a/chromium/chrome/browser/extensions/api/module/module.h +++ b/chromium/chrome/browser/extensions/api/module/module.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_MODULE_MODULE_H_ #define CHROME_BROWSER_EXTENSIONS_API_MODULE_MODULE_H_ -#include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" namespace extensions { class ExtensionPrefs; @@ -16,7 +16,7 @@ std::string GetUpdateURLData(const ExtensionPrefs* prefs, const std::string& extension_id); } // namespace extension -class ExtensionSetUpdateUrlDataFunction : public ChromeSyncExtensionFunction { +class ExtensionSetUpdateUrlDataFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.setUpdateUrlData", EXTENSION_SETUPDATEURLDATA) @@ -25,11 +25,11 @@ class ExtensionSetUpdateUrlDataFunction : public ChromeSyncExtensionFunction { ~ExtensionSetUpdateUrlDataFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class ExtensionIsAllowedIncognitoAccessFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.isAllowedIncognitoAccess", EXTENSION_ISALLOWEDINCOGNITOACCESS) @@ -38,11 +38,11 @@ class ExtensionIsAllowedIncognitoAccessFunction ~ExtensionIsAllowedIncognitoAccessFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class ExtensionIsAllowedFileSchemeAccessFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.isAllowedFileSchemeAccess", EXTENSION_ISALLOWEDFILESCHEMEACCESS) @@ -51,7 +51,7 @@ class ExtensionIsAllowedFileSchemeAccessFunction ~ExtensionIsAllowedFileSchemeAccessFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc index be74629c87c..02d6d1abc93 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc @@ -98,7 +98,7 @@ class TestDelegate : public NetworkingPrivateDelegate { network->SetString(::onc::network_config::kType, ::onc::network_config::kEthernet); network->SetString(::onc::network_config::kGUID, kGuid); - result->Append(network.release()); + result->Append(std::move(network)); success_callback.Run(std::move(result)); } } 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 e8a14b65ecc..740406b8872 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 @@ -35,6 +35,7 @@ #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" +#include "components/policy/policy_constants.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_observer.h" @@ -46,7 +47,6 @@ #include "extensions/browser/api/networking_private/networking_private_delegate_factory.h" #include "extensions/browser/notification_types.h" #include "extensions/common/switches.h" -#include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/cros_system_api/dbus/service_constants.h" diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.cc index e97cd3c649a..9d4b6c56017 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.cc @@ -22,8 +22,8 @@ NetworkingPrivateUIDelegateFactoryImpl:: std::unique_ptr<NetworkingPrivateDelegate::UIDelegate> NetworkingPrivateUIDelegateFactoryImpl::CreateDelegate() { #if defined(OS_CHROMEOS) - return base::WrapUnique( - new chromeos::extensions::NetworkingPrivateUIDelegateChromeOS()); + return base::MakeUnique< + chromeos::extensions::NetworkingPrivateUIDelegateChromeOS>(); #else return nullptr; #endif diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_verify_delegate_factory_impl.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_verify_delegate_factory_impl.cc index eb8bd3d3c49..036b5d29b5a 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_verify_delegate_factory_impl.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_verify_delegate_factory_impl.cc @@ -21,7 +21,7 @@ NetworkingPrivateVerifyDelegateFactoryImpl:: std::unique_ptr<NetworkingPrivateDelegate::VerifyDelegate> NetworkingPrivateVerifyDelegateFactoryImpl::CreateDelegate() { #if defined(OS_CHROMEOS) || defined(OS_WIN) || defined(OS_MACOSX) - return base::WrapUnique(new CryptoVerifyImpl()); + return base::MakeUnique<CryptoVerifyImpl>(); #else return nullptr; #endif diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc index 215c9833793..44fc3e2126e 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc @@ -9,6 +9,7 @@ #include <utility> #include "base/callback.h" +#include "base/feature_list.h" #include "base/guid.h" #include "base/macros.h" #include "base/memory/ptr_util.h" @@ -31,6 +32,9 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" +#include "extensions/browser/app_window/app_window.h" +#include "extensions/browser/app_window/app_window_registry.h" +#include "extensions/browser/app_window/native_app_window.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" @@ -46,10 +50,16 @@ #include "ui/message_center/notifier_settings.h" #include "url/gurl.h" +using message_center::NotifierId; + namespace extensions { namespace notifications = api::notifications; +const base::Feature kAllowFullscreenAppNotificationsFeature{ + "FSNotificationsApp", base::FEATURE_DISABLED_BY_DEFAULT +}; + namespace { const char kMissingRequiredPropertiesForCreateNotification[] = @@ -188,6 +198,34 @@ class NotificationsApiDelegate : public NotificationDelegate { std::string id() const override { return scoped_id_; } + // Should only display when fullscreen if this app is the source of the + // fullscreen window. + bool ShouldDisplayOverFullscreen() const override { + AppWindowRegistry::AppWindowList windows = AppWindowRegistry::Get( + api_function_->GetProfile())->GetAppWindowsForApp(extension_id_); + for (const auto& window : windows) { + // Window must be fullscreen and visible + if (window->IsFullscreen() && window->GetBaseWindow()->IsActive()) { + bool enabled = base::FeatureList::IsEnabled( + kAllowFullscreenAppNotificationsFeature); + if (enabled) { + UMA_HISTOGRAM_ENUMERATION("Notifications.Display_Fullscreen.Shown", + NotifierId::APPLICATION, + NotifierId::SIZE); + } else { + UMA_HISTOGRAM_ENUMERATION( + "Notifications.Display_Fullscreen.Suppressed", + NotifierId::APPLICATION, + NotifierId::SIZE); + + } + return enabled; + } + } + + return false; + } + private: ~NotificationsApiDelegate() override {} diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.h b/chromium/chrome/browser/extensions/api/notifications/notifications_api.h index fd85025d830..d7bb4b712c7 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.h +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.h @@ -7,6 +7,7 @@ #include <string> +#include "base/feature_list.h" #include "base/memory/ref_counted.h" #include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/common/extensions/api/notifications.h" @@ -17,6 +18,8 @@ class Notification; namespace extensions { +extern const base::Feature kAllowFullscreenAppNotificationsFeature; + class NotificationsApiFunction : public ChromeAsyncExtensionFunction { public: // Whether the current extension and channel allow the API. Public for diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc index 426eea9aa2e..b03ea5d26f6 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc @@ -5,6 +5,8 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" +#include "chrome/browser/apps/app_browsertest_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/notifications/notifications_api.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -12,17 +14,32 @@ #include "chrome/browser/notifications/notification.h" #include "chrome/browser/notifications/notification_ui_manager.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" #include "content/public/test/test_utils.h" #include "extensions/browser/api/test/test_api.h" +#include "extensions/browser/app_window/app_window.h" +#include "extensions/browser/app_window/app_window_registry.h" +#include "extensions/browser/app_window/native_app_window.h" #include "extensions/browser/notification_types.h" #include "extensions/common/features/feature.h" #include "extensions/common/test_util.h" +#include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "ui/message_center/message_center.h" #include "ui/message_center/notification_list.h" #include "ui/message_center/notifier_settings.h" +#if defined(OS_MACOSX) +#include "base/mac/mac_util.h" +#include "ui/base/test/scoped_fake_nswindow_fullscreen.h" +#endif + +using extensions::AppWindow; +using extensions::AppWindowRegistry; using extensions::Extension; using extensions::ResultCatcher; @@ -81,9 +98,14 @@ class UserGestureCatcher : public content::NotificationObserver { bool waiting_; }; +enum class WindowState { + FULLSCREEN, + NORMAL +}; + class NotificationsApiTest : public ExtensionApiTest { public: - const extensions::Extension* LoadExtensionAndWait( + const Extension* LoadExtensionAndWait( const std::string& test_name) { base::FilePath extdir = test_data_dir_.AppendASCII(test_name); content::WindowedNotificationObserver page_created( @@ -96,6 +118,42 @@ class NotificationsApiTest : public ExtensionApiTest { return extension; } + const Extension* LoadAppWithWindowState( + const std::string& test_name, WindowState window_state) { + const char* window_state_string = NULL; + switch (window_state) { + case WindowState::FULLSCREEN: + window_state_string = "fullscreen"; + break; + case WindowState::NORMAL: + window_state_string = "normal"; + break; + } + const std::string& create_window_options = base::StringPrintf( + "{\"state\":\"%s\"}", window_state_string); + base::FilePath extdir = test_data_dir_.AppendASCII(test_name); + const extensions::Extension* extension = LoadExtension(extdir); + EXPECT_TRUE(extension); + + ExtensionTestMessageListener launched_listener("launched", true); + LaunchPlatformApp(extension); + EXPECT_TRUE(launched_listener.WaitUntilSatisfied()); + launched_listener.Reply(create_window_options); + + return extension; + } + + AppWindow* GetFirstAppWindow(const std::string& app_id) { + AppWindowRegistry::AppWindowList app_windows = AppWindowRegistry::Get( + browser()->profile())->GetAppWindowsForApp(app_id); + + AppWindowRegistry::const_iterator iter = app_windows.begin(); + if (iter != app_windows.end()) + return *iter; + + return NULL; + } + protected: std::string GetNotificationIdFromDelegateId(const std::string& delegate_id) { return g_browser_process->notification_ui_manager() @@ -105,6 +163,27 @@ class NotificationsApiTest : public ExtensionApiTest { g_browser_process->profile_manager()->GetLastUsedProfile())) ->id(); } + + void LaunchPlatformApp(const Extension* extension) { + OpenApplication(AppLaunchParams( + browser()->profile(), extension, extensions::LAUNCH_CONTAINER_NONE, + WindowOpenDisposition::NEW_WINDOW, extensions::SOURCE_TEST)); + } + + void EnableFullscreenNotifications() { + feature_list_.InitWithFeatures({ + features::kPreferHtmlOverPlugins, + extensions::kAllowFullscreenAppNotificationsFeature}, {}); + } + + void DisableFullscreenNotifications() { + feature_list_.InitWithFeatures( + {features::kPreferHtmlOverPlugins}, + {extensions::kAllowFullscreenAppNotificationsFeature}); + } + + private: + base::test::ScopedFeatureList feature_list_; }; } // namespace @@ -302,3 +381,145 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestRequireInteraction) { EXPECT_TRUE(notification->never_timeout()); } + +IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestShouldDisplayNormal) { + EnableFullscreenNotifications(); + ExtensionTestMessageListener notification_created_listener("created", false); + const Extension* extension = LoadAppWithWindowState( + "notifications/api/basic_app", WindowState::NORMAL); + ASSERT_TRUE(extension) << message_; + ASSERT_TRUE(notification_created_listener.WaitUntilSatisfied()); + + // We start by making sure the window is actually focused. + ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( + GetFirstAppWindow(extension->id())->GetNativeWindow())); + + const message_center::NotificationList::Notifications& notifications = + g_browser_process->message_center()->GetVisibleNotifications(); + ASSERT_EQ(1u, notifications.size()); + message_center::Notification* notification = *(notifications.begin()); + // If the app hasn't created a fullscreen window, then its notifications + // shouldn't be displayed when a window is fullscreen. + ASSERT_FALSE(notification->delegate()->ShouldDisplayOverFullscreen()); +} + +IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestShouldDisplayFullscreen) { +#if defined(OS_MACOSX) + ui::test::ScopedFakeNSWindowFullscreen fake_fullscreen; +#endif + EnableFullscreenNotifications(); + ExtensionTestMessageListener notification_created_listener("created", false); + const Extension* extension = LoadAppWithWindowState( + "notifications/api/basic_app", WindowState::FULLSCREEN); + ASSERT_TRUE(extension) << message_; + ASSERT_TRUE(notification_created_listener.WaitUntilSatisfied()); + + // We start by making sure the window is actually focused. + ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( + GetFirstAppWindow(extension->id())->GetNativeWindow())); + + ASSERT_TRUE(GetFirstAppWindow(extension->id())->IsFullscreen()) + << "Not Fullscreen"; + ASSERT_TRUE(GetFirstAppWindow(extension->id())->GetBaseWindow()->IsActive()) + << "Not Active"; + + const message_center::NotificationList::Notifications& notifications = + g_browser_process->message_center()->GetVisibleNotifications(); + ASSERT_EQ(1u, notifications.size()); + message_center::Notification* notification = *(notifications.begin()); + // If the app has created a fullscreen window, then its notifications should + // be displayed when a window is fullscreen. + ASSERT_TRUE(notification->delegate()->ShouldDisplayOverFullscreen()); +} + +IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestShouldDisplayFullscreenOff) { +#if defined(OS_MACOSX) + ui::test::ScopedFakeNSWindowFullscreen fake_fullscreen; +#endif + DisableFullscreenNotifications(); + ExtensionTestMessageListener notification_created_listener("created", false); + const Extension* extension = LoadAppWithWindowState( + "notifications/api/basic_app", WindowState::FULLSCREEN); + ASSERT_TRUE(extension) << message_; + ASSERT_TRUE(notification_created_listener.WaitUntilSatisfied()); + + // We start by making sure the window is actually focused. + ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( + GetFirstAppWindow(extension->id())->GetNativeWindow())); + + ASSERT_TRUE(GetFirstAppWindow(extension->id())->IsFullscreen()) + << "Not Fullscreen"; + ASSERT_TRUE(GetFirstAppWindow(extension->id())->GetBaseWindow()->IsActive()) + << "Not Active"; + + const message_center::NotificationList::Notifications& notifications = + g_browser_process->message_center()->GetVisibleNotifications(); + ASSERT_EQ(1u, notifications.size()); + message_center::Notification* notification = *(notifications.begin()); + // When the experiment flag is off, then ShouldDisplayOverFullscreen should + // return false. + ASSERT_FALSE(notification->delegate()->ShouldDisplayOverFullscreen()); +} + +// The Fake OSX fullscreen window doesn't like drawing a second fullscreen +// window when another is visible. +#if !defined(OS_MACOSX) +IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestShouldDisplayMultiFullscreen) { + // Start a fullscreen app, and then start another fullscreen app on top of the + // first. Notifications from the first should not be displayed because it is + // not the app actually displaying on the screen. + EnableFullscreenNotifications(); + ExtensionTestMessageListener notification_created_listener("created", false); + const Extension* extension1 = LoadAppWithWindowState( + "notifications/api/basic_app", WindowState::FULLSCREEN); + ASSERT_TRUE(extension1) << message_; + + ExtensionTestMessageListener window_visible_listener("visible", false); + const Extension* extension2 = LoadAppWithWindowState( + "notifications/api/other_app", WindowState::FULLSCREEN); + ASSERT_TRUE(extension2) << message_; + + ASSERT_TRUE(notification_created_listener.WaitUntilSatisfied()); + ASSERT_TRUE(window_visible_listener.WaitUntilSatisfied()); + + // We start by making sure the window is actually focused. + ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( + GetFirstAppWindow(extension2->id())->GetNativeWindow())); + + const message_center::NotificationList::Notifications& notifications = + g_browser_process->message_center()->GetVisibleNotifications(); + ASSERT_EQ(1u, notifications.size()); + message_center::Notification* notification = *(notifications.begin()); + // The first app window is superseded by the second window, so its + // notification shouldn't be displayed. + ASSERT_FALSE(notification->delegate()->ShouldDisplayOverFullscreen()); +} +#endif + +// Verify that a notification is actually displayed when the app window that +// creates it is fullscreen with the fullscreen notification flag turned on. +IN_PROC_BROWSER_TEST_F(NotificationsApiTest, + TestShouldDisplayPopupNotification) { +#if defined(OS_MACOSX) + ui::test::ScopedFakeNSWindowFullscreen fake_fullscreen; +#endif + EnableFullscreenNotifications(); + ExtensionTestMessageListener notification_created_listener("created", false); + const Extension* extension = LoadAppWithWindowState( + "notifications/api/basic_app", WindowState::FULLSCREEN); + ASSERT_TRUE(extension) << message_; + ASSERT_TRUE(notification_created_listener.WaitUntilSatisfied()); + + // We start by making sure the window is actually focused. + ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( + GetFirstAppWindow(extension->id())->GetNativeWindow())); + + ASSERT_TRUE(GetFirstAppWindow(extension->id())->IsFullscreen()) + << "Not Fullscreen"; + ASSERT_TRUE(GetFirstAppWindow(extension->id())->GetBaseWindow()->IsActive()) + << "Not Active"; + + const message_center::NotificationList::PopupNotifications notifications = + g_browser_process->message_center()->GetPopupNotifications(); + ASSERT_EQ(1u, notifications.size()); +} diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc index 04ab949662f..5212b3588e7 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc @@ -105,9 +105,9 @@ std::string GetTemplateURLStringForExtension(const std::string& extension_id) { // static void ExtensionOmniboxEventRouter::OnInputStarted( Profile* profile, const std::string& extension_id) { - std::unique_ptr<Event> event(new Event( + std::unique_ptr<Event> event = base::MakeUnique<Event>( events::OMNIBOX_ON_INPUT_STARTED, omnibox::OnInputStarted::kEventName, - base::WrapUnique(new base::ListValue()))); + base::MakeUnique<base::ListValue>()); event->restrict_to_browser_context = profile; EventRouter::Get(profile) ->DispatchEventToExtension(extension_id, std::move(event)); @@ -126,9 +126,9 @@ bool ExtensionOmniboxEventRouter::OnInputChanged( args->Set(0, new base::StringValue(input)); args->Set(1, new base::FundamentalValue(suggest_id)); - std::unique_ptr<Event> event(new Event(events::OMNIBOX_ON_INPUT_CHANGED, - omnibox::OnInputChanged::kEventName, - std::move(args))); + std::unique_ptr<Event> event = base::MakeUnique<Event>( + events::OMNIBOX_ON_INPUT_CHANGED, omnibox::OnInputChanged::kEventName, + std::move(args)); event->restrict_to_browser_context = profile; event_router->DispatchEventToExtension(extension_id, std::move(event)); return true; @@ -152,16 +152,16 @@ void ExtensionOmniboxEventRouter::OnInputEntered( std::unique_ptr<base::ListValue> args(new base::ListValue()); args->Set(0, new base::StringValue(input)); - if (disposition == NEW_FOREGROUND_TAB) + if (disposition == WindowOpenDisposition::NEW_FOREGROUND_TAB) args->Set(1, new base::StringValue(kForegroundTabDisposition)); - else if (disposition == NEW_BACKGROUND_TAB) + else if (disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) args->Set(1, new base::StringValue(kBackgroundTabDisposition)); else args->Set(1, new base::StringValue(kCurrentTabDisposition)); - std::unique_ptr<Event> event(new Event(events::OMNIBOX_ON_INPUT_ENTERED, - omnibox::OnInputEntered::kEventName, - std::move(args))); + std::unique_ptr<Event> event = base::MakeUnique<Event>( + events::OMNIBOX_ON_INPUT_ENTERED, omnibox::OnInputEntered::kEventName, + std::move(args)); event->restrict_to_browser_context = profile; EventRouter::Get(profile) ->DispatchEventToExtension(extension_id, std::move(event)); @@ -175,9 +175,9 @@ void ExtensionOmniboxEventRouter::OnInputEntered( // static void ExtensionOmniboxEventRouter::OnInputCancelled( Profile* profile, const std::string& extension_id) { - std::unique_ptr<Event> event(new Event( + std::unique_ptr<Event> event = base::MakeUnique<Event>( events::OMNIBOX_ON_INPUT_CANCELLED, omnibox::OnInputCancelled::kEventName, - base::WrapUnique(new base::ListValue()))); + base::MakeUnique<base::ListValue>()); event->restrict_to_browser_context = profile; EventRouter::Get(profile) ->DispatchEventToExtension(extension_id, std::move(event)); @@ -284,33 +284,35 @@ void BrowserContextKeyedAPIFactory<OmniboxAPI>::DeclareFactoryDependencies() { DependsOn(TemplateURLServiceFactory::GetInstance()); } -bool OmniboxSendSuggestionsFunction::RunSync() { +ExtensionFunction::ResponseAction OmniboxSendSuggestionsFunction::Run() { std::unique_ptr<SendSuggestions::Params> params( SendSuggestions::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); content::NotificationService::current()->Notify( extensions::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY, - content::Source<Profile>(GetProfile()->GetOriginalProfile()), + content::Source<Profile>( + Profile::FromBrowserContext(browser_context())->GetOriginalProfile()), content::Details<SendSuggestions::Params>(params.get())); - return true; + return RespondNow(NoArguments()); } -bool OmniboxSetDefaultSuggestionFunction::RunSync() { +ExtensionFunction::ResponseAction OmniboxSetDefaultSuggestionFunction::Run() { std::unique_ptr<SetDefaultSuggestion::Params> params( SetDefaultSuggestion::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - if (SetOmniboxDefaultSuggestion( - GetProfile(), extension_id(), params->suggestion)) { + Profile* profile = Profile::FromBrowserContext(browser_context()); + if (SetOmniboxDefaultSuggestion(profile, extension_id(), + params->suggestion)) { content::NotificationService::current()->Notify( extensions::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED, - content::Source<Profile>(GetProfile()->GetOriginalProfile()), + content::Source<Profile>(profile->GetOriginalProfile()), content::NotificationService::NoDetails()); } - return true; + return RespondNow(NoArguments()); } // This function converts style information populated by the JSON schema @@ -368,7 +370,7 @@ void ApplyDefaultSuggestionForExtensionKeyword( const TemplateURL* keyword, const base::string16& remaining_input, AutocompleteMatch* match) { - DCHECK(keyword->GetType() == TemplateURL::OMNIBOX_API_EXTENSION); + DCHECK(keyword->type() == TemplateURL::OMNIBOX_API_EXTENSION); std::unique_ptr<omnibox::SuggestResult> suggestion( GetOmniboxDefaultSuggestion(profile, keyword->GetExtensionId())); diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h index d49ecc1f280..09678937945 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h @@ -73,7 +73,7 @@ class ExtensionOmniboxEventRouter { DISALLOW_COPY_AND_ASSIGN(ExtensionOmniboxEventRouter); }; -class OmniboxSendSuggestionsFunction : public ChromeSyncExtensionFunction { +class OmniboxSendSuggestionsFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("omnibox.sendSuggestions", OMNIBOX_SENDSUGGESTIONS) @@ -81,7 +81,7 @@ class OmniboxSendSuggestionsFunction : public ChromeSyncExtensionFunction { ~OmniboxSendSuggestionsFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; class OmniboxAPI : public BrowserContextKeyedAPI, @@ -150,7 +150,7 @@ class OmniboxAPI : public BrowserContextKeyedAPI, template <> void BrowserContextKeyedAPIFactory<OmniboxAPI>::DeclareFactoryDependencies(); -class OmniboxSetDefaultSuggestionFunction : public ChromeSyncExtensionFunction { +class OmniboxSetDefaultSuggestionFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("omnibox.setDefaultSuggestion", OMNIBOX_SETDEFAULTSUGGESTION) @@ -159,7 +159,7 @@ class OmniboxSetDefaultSuggestionFunction : public ChromeSyncExtensionFunction { ~OmniboxSetDefaultSuggestionFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // If the extension has set a custom default suggestion via diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc index f33ce975034..c32c60ea407 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc @@ -177,7 +177,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, OnInputEntered) { ASCIIToUTF16("keyword command"), base::string16::npos, std::string(), GURL(), OmniboxEventProto::NTP, true, false, true, true, false, ChromeAutocompleteSchemeClassifier(profile))); - omnibox_view->model()->AcceptInput(CURRENT_TAB, false); + omnibox_view->model()->AcceptInput(WindowOpenDisposition::CURRENT_TAB, false); WaitForAutocompleteDone(autocomplete_controller); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); @@ -192,7 +192,8 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, OnInputEntered) { ASCIIToUTF16("keyword newtab"), base::string16::npos, std::string(), GURL(), OmniboxEventProto::NTP, true, false, true, true, false, ChromeAutocompleteSchemeClassifier(profile))); - omnibox_view->model()->AcceptInput(NEW_FOREGROUND_TAB, false); + omnibox_view->model()->AcceptInput(WindowOpenDisposition::NEW_FOREGROUND_TAB, + false); WaitForAutocompleteDone(autocomplete_controller); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); 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 e1c962ceda3..1e7c549d533 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 @@ -106,10 +106,8 @@ void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreated(bool success) { // Setup a ShareableFileReference so the temporary file gets deleted // once it is no longer used. mhtml_file_ = ShareableFileReference::GetOrCreate( - mhtml_path_, - ShareableFileReference::DELETE_ON_FINAL_RELEASE, - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE) - .get()); + mhtml_path_, ShareableFileReference::DELETE_ON_FINAL_RELEASE, + BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get()); } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, 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 04936a17cf4..7ec270b1d33 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 @@ -8,7 +8,6 @@ #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/observer_list.h" #include "base/strings/utf_string_conversions.h" diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc index ef8ff5a5f13..0a8222f08af 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc @@ -239,9 +239,8 @@ bool PermissionsRequestFunction::RunAsync() { install_ui_.reset(new ExtensionInstallPrompt(GetAssociatedWebContents())); install_ui_->ShowDialog( base::Bind(&PermissionsRequestFunction::OnInstallPromptDone, this), - extension(), nullptr, - base::WrapUnique(new ExtensionInstallPrompt::Prompt( - ExtensionInstallPrompt::PERMISSIONS_PROMPT)), + extension(), nullptr, base::MakeUnique<ExtensionInstallPrompt::Prompt>( + ExtensionInstallPrompt::PERMISSIONS_PROMPT), requested_permissions_->Clone(), ExtensionInstallPrompt::GetDefaultShowDialogCallback()); } diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc index 8d6af879c89..7632c69265f 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.cc @@ -146,8 +146,8 @@ std::unique_ptr<const PermissionSet> UnpackPermissionSet( } } - return base::WrapUnique( - new PermissionSet(apis, manifest_permissions, origins, URLPatternSet())); + return base::MakeUnique<PermissionSet>(apis, manifest_permissions, origins, + URLPatternSet()); } } // namespace permissions_api_helpers diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc index bab711a96d4..3de54c783ac 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc @@ -79,8 +79,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) { // Test functions and APIs that are always allowed (even if you ask for no // permissions). -// Disabled: http://crbug.com/125193 -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_AlwaysAllowed) { +IN_PROC_BROWSER_TEST_F(ExtensionApiTest, AlwaysAllowed) { ASSERT_TRUE(RunExtensionTest("permissions/always_allowed")) << message_; } 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 0dc0b512fcf..6b79c87a04d 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 @@ -21,6 +21,7 @@ #include "chrome/browser/profiles/profile.h" #include "chromeos/chromeos_switches.h" #include "chromeos/login/user_names.h" +#include "components/policy/policy_constants.h" #include "components/signin/core/account_id/account_id.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" @@ -33,7 +34,6 @@ #include "net/cert/test_root_certs.h" #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" -#include "policy/policy_constants.h" namespace { @@ -396,7 +396,7 @@ IN_PROC_BROWSER_TEST_P(ManagedWithoutPermissionPlatformKeysTest, // To verify that the user is not prompted for any certificate selection, // set up a delegate that fails on any invocation. GetPlatformKeysService()->SetSelectDelegate( - base::WrapUnique(new TestSelectDelegate(net::CertificateList()))); + base::MakeUnique<TestSelectDelegate>(net::CertificateList())); ASSERT_TRUE(RunExtensionTest("managedProfile")) << message_; } @@ -433,7 +433,7 @@ IN_PROC_BROWSER_TEST_P(ManagedWithPermissionPlatformKeysTest, certs.push_back(client_cert1_); GetPlatformKeysService()->SetSelectDelegate( - base::WrapUnique(new TestSelectDelegate(certs))); + base::MakeUnique<TestSelectDelegate>(certs)); ASSERT_TRUE(RunExtensionTest("corporateKeyWithPermissionTests")) << message_; } @@ -444,7 +444,7 @@ IN_PROC_BROWSER_TEST_P(ManagedWithPermissionPlatformKeysTest, // As the profile is managed, the user must not be able to grant any // certificate permission. Set up a delegate that fails on any invocation. GetPlatformKeysService()->SetSelectDelegate( - base::WrapUnique(new TestSelectDelegate(net::CertificateList()))); + base::MakeUnique<TestSelectDelegate>(net::CertificateList())); ASSERT_TRUE(RunExtensionTest("policyDoesGrantAccessToNonCorporateKey")) << message_; 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 be8ad64d8ef..42e21020c3d 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 @@ -17,7 +17,7 @@ #include "net/cert/cert_verifier.h" #include "net/cert/cert_verify_result.h" #include "net/cert/x509_certificate.h" -#include "net/log/net_log.h" +#include "net/log/net_log_with_source.h" #include "net/ssl/ssl_config_service.h" namespace extensions { @@ -176,7 +176,7 @@ void VerifyTrustAPI::IOPart::Verify(std::unique_ptr<Params> params, return; } - if (!ContainsKey(extension_to_verifier_, extension_id)) { + if (!base::ContainsKey(extension_to_verifier_, extension_id)) { extension_to_verifier_[extension_id] = make_linked_ptr(net::CertVerifier::CreateDefault().release()); } @@ -184,7 +184,7 @@ void VerifyTrustAPI::IOPart::Verify(std::unique_ptr<Params> params, std::unique_ptr<net::CertVerifyResult> verify_result( new net::CertVerifyResult); - std::unique_ptr<net::BoundNetLog> net_log(new net::BoundNetLog); + std::unique_ptr<net::NetLogWithSource> net_log(new net::NetLogWithSource); const int flags = 0; std::string ocsp_response; diff --git a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc index 3dc56c12f95..a612d302aaf 100644 --- a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc +++ b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.cc @@ -22,15 +22,15 @@ DirectSettingFunctionBase::DirectSettingFunctionBase() {} DirectSettingFunctionBase::~DirectSettingFunctionBase() {} PrefService* DirectSettingFunctionBase::GetPrefService() { - return GetProfile()->GetPrefs(); + return Profile::FromBrowserContext(browser_context())->GetPrefs(); } GetDirectSettingFunction::GetDirectSettingFunction() {} -bool GetDirectSettingFunction::RunSync() { +ExtensionFunction::ResponseAction GetDirectSettingFunction::Run() { std::string pref_key; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key)); - EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(GetProfile()) + EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(browser_context()) ->IsPreferenceOnWhitelist(pref_key)); const PrefService::Preference* preference = @@ -40,19 +40,17 @@ bool GetDirectSettingFunction::RunSync() { std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue); result->Set(preference_api_constants::kValue, value->DeepCopy()); - SetResult(std::move(result)); - - return true; + return RespondNow(OneArgument(std::move(result))); } GetDirectSettingFunction::~GetDirectSettingFunction() {} SetDirectSettingFunction::SetDirectSettingFunction() {} -bool SetDirectSettingFunction::RunSync() { +ExtensionFunction::ResponseAction SetDirectSettingFunction::Run() { std::string pref_key; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key)); - EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(GetProfile()) + EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(browser_context()) ->IsPreferenceOnWhitelist(pref_key)); base::DictionaryValue* details = NULL; @@ -71,21 +69,21 @@ bool SetDirectSettingFunction::RunSync() { pref_service->Set(pref_key.c_str(), *value); - return true; + return RespondNow(NoArguments()); } SetDirectSettingFunction::~SetDirectSettingFunction() {} ClearDirectSettingFunction::ClearDirectSettingFunction() {} -bool ClearDirectSettingFunction::RunSync() { +ExtensionFunction::ResponseAction ClearDirectSettingFunction::Run() { std::string pref_key; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key)); - EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(GetProfile()) + EXTENSION_FUNCTION_VALIDATE(ChromeDirectSettingAPI::Get(browser_context()) ->IsPreferenceOnWhitelist(pref_key)); GetPrefService()->ClearPref(pref_key.c_str()); - return true; + return RespondNow(NoArguments()); } ClearDirectSettingFunction::~ClearDirectSettingFunction() {} diff --git a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h index f373e2218e4..c58cab26e96 100644 --- a/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h +++ b/chromium/chrome/browser/extensions/api/preference/chrome_direct_setting.h @@ -7,7 +7,7 @@ #include "base/lazy_instance.h" #include "base/macros.h" -#include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" class PrefService; @@ -15,7 +15,7 @@ namespace extensions { namespace chromedirectsetting { // Base class to host instance method helpers. -class DirectSettingFunctionBase : public ChromeSyncExtensionFunction { +class DirectSettingFunctionBase : public UIThreadExtensionFunction { protected: DirectSettingFunctionBase(); ~DirectSettingFunctionBase() override; @@ -39,7 +39,7 @@ class GetDirectSettingFunction : public DirectSettingFunctionBase { protected: // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; private: ~GetDirectSettingFunction() override; @@ -55,7 +55,7 @@ class SetDirectSettingFunction : public DirectSettingFunctionBase { protected: // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; private: ~SetDirectSettingFunction() override; @@ -71,7 +71,7 @@ class ClearDirectSettingFunction : public DirectSettingFunctionBase { protected: // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; private: ~ClearDirectSettingFunction() override; diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.cc b/chromium/chrome/browser/extensions/api/preference/preference_api.cc index faafcaed7ba..89d11d66c0d 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_api.cc @@ -7,12 +7,13 @@ #include <stddef.h> #include <map> +#include <memory> #include <utility> #include "base/lazy_instance.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/singleton.h" -#include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "build/build_config.h" @@ -31,6 +32,7 @@ #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_service.h" #include "components/proxy_config/proxy_config_pref_names.h" +#include "components/spellcheck/browser/pref_names.h" #include "components/translate/core/common/translate_pref_names.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" @@ -116,7 +118,7 @@ PrefMappingEntry kPrefMapping[] = { APIPermission::kPrivacy}, {"searchSuggestEnabled", prefs::kSearchSuggestEnabled, APIPermission::kPrivacy, APIPermission::kPrivacy}, - {"spellingServiceEnabled", prefs::kSpellCheckUseSpellingService, + {"spellingServiceEnabled", spellcheck::prefs::kSpellCheckUseSpellingService, APIPermission::kPrivacy, APIPermission::kPrivacy}, {"thirdPartyCookiesAllowed", prefs::kBlockThirdPartyCookies, APIPermission::kPrivacy, APIPermission::kPrivacy}, @@ -132,6 +134,8 @@ PrefMappingEntry kPrefMapping[] = { APIPermission::kPrivacy, APIPermission::kPrivacy}, {"webRTCIPHandlingPolicy", prefs::kWebRTCIPHandlingPolicy, APIPermission::kPrivacy, APIPermission::kPrivacy}, + {"webRTCUDPPortRange", prefs::kWebRTCUDPPortRange, APIPermission::kPrivacy, + APIPermission::kPrivacy}, #endif // accessibilityFeatures.animationPolicy is available for // all platforms but the others from accessibilityFeatures @@ -261,10 +265,9 @@ class PrefMapping { PrefTransformerInterface* FindTransformerForBrowserPref( const std::string& browser_pref) { - std::map<std::string, PrefTransformerInterface*>::iterator it = - transformers_.find(browser_pref); + auto it = transformers_.find(browser_pref); if (it != transformers_.end()) - return it->second; + return it->second.get(); else return identity_transformer_.get(); } @@ -290,23 +293,22 @@ class PrefMapping { DCHECK_EQ(arraysize(kPrefMapping), mapping_.size()); DCHECK_EQ(arraysize(kPrefMapping), event_mapping_.size()); RegisterPrefTransformer(proxy_config::prefs::kProxy, - new ProxyPrefTransformer()); + base::MakeUnique<ProxyPrefTransformer>()); RegisterPrefTransformer(prefs::kBlockThirdPartyCookies, - new InvertBooleanTransformer()); + base::MakeUnique<InvertBooleanTransformer>()); RegisterPrefTransformer(prefs::kNetworkPredictionOptions, - new NetworkPredictionTransformer()); + base::MakeUnique<NetworkPredictionTransformer>()); } ~PrefMapping() { - STLDeleteContainerPairSecondPointers(transformers_.begin(), - transformers_.end()); } - void RegisterPrefTransformer(const std::string& browser_pref, - PrefTransformerInterface* transformer) { + void RegisterPrefTransformer( + const std::string& browser_pref, + std::unique_ptr<PrefTransformerInterface> transformer) { DCHECK_EQ(0u, transformers_.count(browser_pref)) << "Trying to register pref transformer for " << browser_pref << " twice"; - transformers_[browser_pref] = transformer; + transformers_[browser_pref] = std::move(transformer); } struct PrefMapData { @@ -340,7 +342,8 @@ class PrefMapping { PrefMap event_mapping_; // Mapping from browser pref keys to transformers. - std::map<std::string, PrefTransformerInterface*> transformers_; + std::map<std::string, std::unique_ptr<PrefTransformerInterface>> + transformers_; std::unique_ptr<PrefTransformerInterface> identity_transformer_; @@ -378,8 +381,6 @@ void PreferenceEventRouter::OnPrefChanged(PrefService* pref_service, DCHECK(rv); base::ListValue args; - base::DictionaryValue* dict = new base::DictionaryValue(); - args.Append(dict); const PrefService::Preference* pref = pref_service->FindPreference(browser_pref.c_str()); CHECK(pref); @@ -393,12 +394,14 @@ void PreferenceEventRouter::OnPrefChanged(PrefService* pref_service, return; } + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->Set(keys::kValue, transformed_value); if (incognito) { ExtensionPrefs* ep = ExtensionPrefs::Get(profile_); dict->SetBoolean(keys::kIncognitoSpecific, ep->HasIncognitoPrefValue(browser_pref)); } + args.Append(std::move(dict)); // TODO(kalman): Have a histogram value for each pref type. // This isn't so important for the current use case of these @@ -734,7 +737,7 @@ bool SetPreferenceFunction::RunSync() { transformer->ExtensionToBrowserPref(value, &error, &bad_message)); if (!browser_pref_value) { error_ = error; - bad_message_ = bad_message; + set_bad_message(bad_message); return false; } EXTENSION_FUNCTION_VALIDATE(browser_pref_value->GetType() == pref->GetType()); @@ -746,7 +749,7 @@ bool SetPreferenceFunction::RunSync() { if (!extensionPrefValue) { error_ = ErrorUtils::FormatErrorMessage(kConversionErrorMessage, pref->name()); - bad_message_ = true; + set_bad_message(true); return false; } diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc index 3527bf905ca..e43d5df24e9 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc @@ -16,7 +16,7 @@ #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/task_management/task_manager_interface.h" +#include "chrome/browser/task_manager/task_manager_interface.h" #include "chrome/common/extensions/api/processes.h" #include "content/public/browser/browser_child_process_host.h" #include "content/public/browser/child_process_data.h" @@ -43,17 +43,17 @@ base::LazyInstance<BrowserContextKeyedAPIFactory<ProcessesAPI>> int64_t GetRefreshTypesFlagOnlyEssentialData() { // This is the only non-optional data in the Process as defined by the API in // processes.idl. - return task_management::REFRESH_TYPE_NACL; + return task_manager::REFRESH_TYPE_NACL; } // This does not include memory. The memory refresh flag will only be added once // a listener to OnUpdatedWithMemory event is added. int64_t GetRefreshTypesForProcessOptionalData() { - return task_management::REFRESH_TYPE_CPU | - task_management::REFRESH_TYPE_NETWORK_USAGE | - task_management::REFRESH_TYPE_SQLITE_MEMORY | - task_management::REFRESH_TYPE_V8_MEMORY | - task_management::REFRESH_TYPE_WEBCACHE_STATS; + return task_manager::REFRESH_TYPE_CPU | + task_manager::REFRESH_TYPE_NETWORK_USAGE | + task_manager::REFRESH_TYPE_SQLITE_MEMORY | + task_manager::REFRESH_TYPE_V8_MEMORY | + task_manager::REFRESH_TYPE_WEBCACHE_STATS; } std::unique_ptr<api::processes::Cache> CreateCacheData( @@ -65,37 +65,37 @@ std::unique_ptr<api::processes::Cache> CreateCacheData( } api::processes::ProcessType GetProcessType( - task_management::Task::Type task_type) { + task_manager::Task::Type task_type) { switch (task_type) { - case task_management::Task::BROWSER: + case task_manager::Task::BROWSER: return api::processes::PROCESS_TYPE_BROWSER; - case task_management::Task::RENDERER: + case task_manager::Task::RENDERER: return api::processes::PROCESS_TYPE_RENDERER; - case task_management::Task::EXTENSION: - case task_management::Task::GUEST: + case task_manager::Task::EXTENSION: + case task_manager::Task::GUEST: return api::processes::PROCESS_TYPE_EXTENSION; - case task_management::Task::PLUGIN: + case task_manager::Task::PLUGIN: return api::processes::PROCESS_TYPE_PLUGIN; - case task_management::Task::WORKER: + case task_manager::Task::WORKER: return api::processes::PROCESS_TYPE_WORKER; - case task_management::Task::NACL: + case task_manager::Task::NACL: return api::processes::PROCESS_TYPE_NACL; - case task_management::Task::UTILITY: + case task_manager::Task::UTILITY: return api::processes::PROCESS_TYPE_UTILITY; - case task_management::Task::GPU: + case task_manager::Task::GPU: return api::processes::PROCESS_TYPE_GPU; - case task_management::Task::UNKNOWN: - case task_management::Task::ARC: - case task_management::Task::SANDBOX_HELPER: - case task_management::Task::ZYGOTE: + case task_manager::Task::UNKNOWN: + case task_manager::Task::ARC: + case task_manager::Task::SANDBOX_HELPER: + case task_manager::Task::ZYGOTE: return api::processes::PROCESS_TYPE_OTHER; } @@ -108,8 +108,8 @@ api::processes::ProcessType GetProcessType( // optional fields in |api::processes::Process| except for |private_memory|, // which should be filled later if needed. void FillProcessData( - task_management::TaskId id, - task_management::TaskManagerInterface* task_manager, + task_manager::TaskId id, + task_manager::TaskManagerInterface* task_manager, bool include_optional, api::processes::Process* out_process) { DCHECK(out_process); @@ -121,7 +121,7 @@ void FillProcessData( out_process->nacl_debug_port = task_manager->GetNaClDebugStubPort(id); // Collect the tab IDs of all the tasks sharing this renderer if any. - const task_management::TaskIdList tasks_on_process = + const task_manager::TaskIdList tasks_on_process = task_manager->GetIdsOfTasksSharingSameProcess(id); for (const auto& task_id : tasks_on_process) { api::processes::TaskInfo task_info; @@ -171,8 +171,8 @@ void FillProcessData( //////////////////////////////////////////////////////////////////////////////// ProcessesEventRouter::ProcessesEventRouter(content::BrowserContext* context) - : task_management::TaskManagerObserver(base::TimeDelta::FromSeconds(1), - task_management::REFRESH_TYPE_NONE), + : task_manager::TaskManagerObserver(base::TimeDelta::FromSeconds(1), + task_manager::REFRESH_TYPE_NONE), browser_context_(context), listeners_(0) { } @@ -185,7 +185,7 @@ void ProcessesEventRouter::ListenerAdded() { if (listeners_++ == 0) { // The first listener to be added. - task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this); + task_manager::TaskManagerInterface::GetTaskManager()->AddObserver(this); } } @@ -194,12 +194,12 @@ void ProcessesEventRouter::ListenerRemoved() { if (--listeners_ == 0) { // Last listener to be removed. - task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver( + task_manager::TaskManagerInterface::GetTaskManager()->RemoveObserver( this); } } -void ProcessesEventRouter::OnTaskAdded(task_management::TaskId id) { +void ProcessesEventRouter::OnTaskAdded(task_manager::TaskId id) { if (!HasEventListeners(api::processes::OnCreated::kEventName)) return; @@ -217,7 +217,7 @@ void ProcessesEventRouter::OnTaskAdded(task_management::TaskId id) { api::processes::OnCreated::Create(process)); } -void ProcessesEventRouter::OnTaskToBeRemoved(task_management::TaskId id) { +void ProcessesEventRouter::OnTaskToBeRemoved(task_manager::TaskId id) { if (!HasEventListeners(api::processes::OnExited::kEventName)) return; @@ -237,7 +237,7 @@ void ProcessesEventRouter::OnTaskToBeRemoved(task_management::TaskId id) { } void ProcessesEventRouter::OnTasksRefreshedWithBackgroundCalculations( - const task_management::TaskIdList& task_ids) { + const task_manager::TaskIdList& task_ids) { const bool has_on_updated_listeners = HasEventListeners(api::processes::OnUpdated::kEventName); const bool has_on_updated_with_memory_listeners = @@ -308,7 +308,7 @@ void ProcessesEventRouter::OnTasksRefreshedWithBackgroundCalculations( } } -void ProcessesEventRouter::OnTaskUnresponsive(task_management::TaskId id) { +void ProcessesEventRouter::OnTaskUnresponsive(task_manager::TaskId id) { if (!HasEventListeners(api::processes::OnUnresponsive::kEventName)) return; @@ -341,7 +341,7 @@ bool ProcessesEventRouter::HasEventListeners( } bool ProcessesEventRouter::ShouldReportOnCreatedOrOnExited( - task_management::TaskId id, + task_manager::TaskId id, int* out_child_process_host_id) const { // Is it the first task to be created or the last one to be removed? if (observed_task_manager()->GetNumberOfTasksOnSameProcess(id) != 1) @@ -362,7 +362,7 @@ bool ProcessesEventRouter::ShouldReportOnCreatedOrOnExited( } void ProcessesEventRouter::UpdateRefreshTypesFlagsBasedOnListeners() { - int64_t refresh_types = task_management::REFRESH_TYPE_NONE; + int64_t refresh_types = task_manager::REFRESH_TYPE_NONE; if (HasEventListeners(api::processes::OnCreated::kEventName) || HasEventListeners(api::processes::OnUnresponsive::kEventName)) { refresh_types |= GetRefreshTypesFlagOnlyEssentialData(); @@ -372,7 +372,7 @@ void ProcessesEventRouter::UpdateRefreshTypesFlagsBasedOnListeners() { refresh_types |= GetRefreshTypesForProcessOptionalData(); if (HasEventListeners(api::processes::OnUpdatedWithMemory::kEventName)) - refresh_types |= task_management::REFRESH_TYPE_MEMORY; + refresh_types |= task_manager::REFRESH_TYPE_MEMORY; SetRefreshTypesFlags(refresh_types); } @@ -558,7 +558,7 @@ ProcessesTerminateFunction::TerminateIfAllowed(base::ProcessHandle handle) { //////////////////////////////////////////////////////////////////////////////// ProcessesGetProcessInfoFunction::ProcessesGetProcessInfoFunction() - : task_management::TaskManagerObserver( + : task_manager::TaskManagerObserver( base::TimeDelta::FromSeconds(1), GetRefreshTypesFlagOnlyEssentialData()) { } @@ -574,7 +574,7 @@ ExtensionFunction::ResponseAction ProcessesGetProcessInfoFunction::Run() { include_memory_ = params->include_memory; if (include_memory_) - AddRefreshType(task_management::REFRESH_TYPE_MEMORY); + AddRefreshType(task_manager::REFRESH_TYPE_MEMORY); // Keep this object alive until the first of either OnTasksRefreshed() or // OnTasksRefreshedWithBackgroundCalculations() is received depending on @@ -583,13 +583,13 @@ ExtensionFunction::ResponseAction ProcessesGetProcessInfoFunction::Run() { // The task manager needs to be enabled for this function. // Start observing the task manager and wait for the next refresh event. - task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this); + task_manager::TaskManagerInterface::GetTaskManager()->AddObserver(this); return RespondLater(); } void ProcessesGetProcessInfoFunction::OnTasksRefreshed( - const task_management::TaskIdList& task_ids) { + const task_manager::TaskIdList& task_ids) { // Memory is background calculated and will be ready when // OnTasksRefreshedWithBackgroundCalculations() is invoked. if (include_memory_) @@ -600,7 +600,7 @@ void ProcessesGetProcessInfoFunction::OnTasksRefreshed( void ProcessesGetProcessInfoFunction::OnTasksRefreshedWithBackgroundCalculations( - const task_management::TaskIdList& task_ids) { + const task_manager::TaskIdList& task_ids) { if (!include_memory_) return; @@ -610,7 +610,7 @@ ProcessesGetProcessInfoFunction::OnTasksRefreshedWithBackgroundCalculations( ProcessesGetProcessInfoFunction::~ProcessesGetProcessInfoFunction() {} void ProcessesGetProcessInfoFunction::GatherDataAndRespond( - const task_management::TaskIdList& task_ids) { + const task_manager::TaskIdList& task_ids) { // If there are no process IDs specified, it means we need to return all of // the ones we know of. const bool specific_processes_requested = !process_host_ids_.empty(); @@ -682,7 +682,7 @@ void ProcessesGetProcessInfoFunction::GatherDataAndRespond( api::processes::GetProcessInfo::Results::Create(processes))); // Stop observing the task manager, and balance the AddRef() in Run(). - task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(this); + task_manager::TaskManagerInterface::GetTaskManager()->RemoveObserver(this); Release(); } diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.h b/chromium/chrome/browser/extensions/api/processes/processes_api.h index 9b0a32a42f1..1950e1e6884 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.h +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.h @@ -8,7 +8,7 @@ #include <vector> #include "base/macros.h" -#include "chrome/browser/task_management/task_manager_observer.h" +#include "chrome/browser/task_manager/task_manager_observer.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_event_histogram_value.h" @@ -20,7 +20,7 @@ namespace extensions { // Observes the Task Manager and routes the notifications as events to the // extension system. -class ProcessesEventRouter : public task_management::TaskManagerObserver { +class ProcessesEventRouter : public task_manager::TaskManagerObserver { public: explicit ProcessesEventRouter(content::BrowserContext* context); ~ProcessesEventRouter() override; @@ -31,13 +31,13 @@ class ProcessesEventRouter : public task_management::TaskManagerObserver { // Called when an extension process with a listener exits or removes it. void ListenerRemoved(); - // task_management::TaskManagerObserver: - void OnTaskAdded(task_management::TaskId id) override; - void OnTaskToBeRemoved(task_management::TaskId id) override; - void OnTasksRefreshed(const task_management::TaskIdList& task_ids) override {} + // task_manager::TaskManagerObserver: + void OnTaskAdded(task_manager::TaskId id) override; + void OnTaskToBeRemoved(task_manager::TaskId id) override; + void OnTasksRefreshed(const task_manager::TaskIdList& task_ids) override {} void OnTasksRefreshedWithBackgroundCalculations( - const task_management::TaskIdList& task_ids) override; - void OnTaskUnresponsive(task_management::TaskId id) override; + const task_manager::TaskIdList& task_ids) override; + void OnTaskUnresponsive(task_manager::TaskId id) override; private: friend class ::ProcessesApiTest; @@ -53,7 +53,7 @@ class ProcessesEventRouter : public task_management::TaskManagerObserver { // Returns true if the task with the given |id| should be reported as created // or removed. |out_child_process_host_id| will be filled with the valid ID of // the process to report in the event. - bool ShouldReportOnCreatedOrOnExited(task_management::TaskId id, + bool ShouldReportOnCreatedOrOnExited(task_manager::TaskId id, int* out_child_process_host_id) const; // Updates the requested task manager refresh types flags depending on what @@ -159,19 +159,19 @@ class ProcessesTerminateFunction : public UIThreadExtensionFunction { // details corresponding to the process IDs supplied as input. class ProcessesGetProcessInfoFunction : public UIThreadExtensionFunction, - public task_management::TaskManagerObserver { + public task_manager::TaskManagerObserver { public: ProcessesGetProcessInfoFunction(); // UIThreadExtensionFunction: ExtensionFunction::ResponseAction Run() override; - // task_management::TaskManagerObserver: - void OnTaskAdded(task_management::TaskId id) override {} - void OnTaskToBeRemoved(task_management::TaskId id) override {} - void OnTasksRefreshed(const task_management::TaskIdList& task_ids) override; + // task_manager::TaskManagerObserver: + void OnTaskAdded(task_manager::TaskId id) override {} + void OnTaskToBeRemoved(task_manager::TaskId id) override {} + void OnTasksRefreshed(const task_manager::TaskIdList& task_ids) override; void OnTasksRefreshedWithBackgroundCalculations( - const task_management::TaskIdList& task_ids) override; + const task_manager::TaskIdList& task_ids) override; DECLARE_EXTENSION_FUNCTION("processes.getProcessInfo", PROCESSES_GETPROCESSINFO); @@ -185,7 +185,7 @@ class ProcessesGetProcessInfoFunction : // This function will be called by either OnTasksRefreshed() or // OnTasksRefreshedWithBackgroundCalculations() depending on whether memory is // requested. - void GatherDataAndRespond(const task_management::TaskIdList& task_ids); + void GatherDataAndRespond(const task_manager::TaskIdList& task_ids); std::vector<int> process_host_ids_; bool include_memory_ = false; diff --git a/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc b/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc index 074d1ebbeb8..d75a4065760 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc @@ -5,7 +5,7 @@ #include "base/command_line.h" #include "chrome/browser/extensions/api/processes/processes_api.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/task_management/task_manager_interface.h" +#include "chrome/browser/task_manager/task_manager_interface.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_window.h" @@ -27,13 +27,8 @@ class ProcessesApiTest : public ExtensionApiTest { }; -// This test is flaky on Win7 Tests (dbg)(1). https://crbug.com/598445 -#if defined(OS_WIN) -#define MAYBE_Processes DISABLED_Processes -#else -#define MAYBE_Processes Processes -#endif -IN_PROC_BROWSER_TEST_F(ProcessesApiTest, MAYBE_Processes) { +// This test is flaky. https://crbug.com/598445 +IN_PROC_BROWSER_TEST_F(ProcessesApiTest, DISABLED_Processes) { ASSERT_TRUE(RunExtensionTest("processes/api")) << message_; } @@ -61,11 +56,11 @@ IN_PROC_BROWSER_TEST_F(ProcessesApiTest, ProcessesApiListeners) { ASSERT_TRUE(listener2.WaitUntilSatisfied()); // The memory refresh type must be enabled now. - const task_management::TaskManagerInterface* task_manager = - task_management::TaskManagerInterface::GetTaskManager(); + const task_manager::TaskManagerInterface* task_manager = + task_manager::TaskManagerInterface::GetTaskManager(); EXPECT_EQ(2, GetListenersCount()); EXPECT_TRUE(task_manager->IsResourceRefreshEnabled( - task_management::REFRESH_TYPE_MEMORY)); + task_manager::REFRESH_TYPE_MEMORY)); // Unload the extensions and make sure the listeners count is updated. UnloadExtension(extension2->id()); diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc index b89d3b87fa1..f22e8b3d513 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc @@ -78,7 +78,7 @@ bool GetProxyModeFromExtensionPref(const base::DictionaryValue* proxy_config, bool GetPacMandatoryFromExtensionPref(const base::DictionaryValue* proxy_config, bool* out, std::string* error, - bool* bad_message){ + bool* bad_message) { const base::DictionaryValue* pac_dict = NULL; proxy_config->GetDictionary(keys::kProxyConfigPacScript, &pac_dict); if (!pac_dict) @@ -475,7 +475,7 @@ base::DictionaryValue* CreatePacScriptDict( return NULL; } - if (pac_url.find("data") == 0) { + if (base::StartsWith(pac_url, "data", base::CompareCase::SENSITIVE)) { std::string pac_data; if (!CreatePACScriptFromDataURL(pac_url, &pac_data)) { LOG(ERROR) << "Cannot decode base64-encoded PAC data URL: " << pac_url; diff --git a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc index 3e2e73453c7..434f1bd2115 100644 --- a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc +++ b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc @@ -11,7 +11,7 @@ #include "base/lazy_instance.h" #include "base/location.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -262,7 +262,7 @@ void ChromeRuntimeAPIDelegate::OpenURL(const GURL& uninstall_url) { chrome::NavigateParams params( browser, uninstall_url, ui::PAGE_TRANSITION_CLIENT_REDIRECT); - params.disposition = NEW_FOREGROUND_TAB; + params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; params.user_gesture = false; chrome::Navigate(¶ms); } @@ -337,9 +337,10 @@ void ChromeRuntimeAPIDelegate::Observe( const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_UPDATE_FOUND, type); - using UpdateDetails = const std::pair<std::string, Version>; + using UpdateDetails = const std::pair<std::string, base::Version>; const std::string& id = content::Details<UpdateDetails>(details)->first; - const Version& version = content::Details<UpdateDetails>(details)->second; + const base::Version& version = + content::Details<UpdateDetails>(details)->second; if (version.IsValid()) { CallUpdateCallbacks( id, UpdateCheckResult(true, kUpdateFound, version.GetString())); diff --git a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc index 8c710717591..7205a5f0ccb 100644 --- a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc +++ b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc @@ -64,7 +64,7 @@ class TestEventRouter : public EventRouter { std::unique_ptr<KeyedService> TestEventRouterFactoryFunction( content::BrowserContext* context) { - return base::WrapUnique(new TestEventRouter(context)); + return base::MakeUnique<TestEventRouter>(context); } // This class lets us intercept extension update checks and respond as if diff --git a/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.cc b/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.cc index b9f5212178e..4504d3c9240 100644 --- a/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.cc +++ b/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.cc @@ -4,6 +4,7 @@ #include "chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h" +#include <memory> #include <utility> #include "base/lazy_instance.h" @@ -119,14 +120,14 @@ void ScreenlockPrivateEventRouter::OnScreenDidLock( proximity_auth::ScreenlockBridge::LockHandler::ScreenType screen_type) { DispatchEvent(events::SCREENLOCK_PRIVATE_ON_CHANGED, screenlock::OnChanged::kEventName, - new base::FundamentalValue(true)); + base::MakeUnique<base::FundamentalValue>(true)); } void ScreenlockPrivateEventRouter::OnScreenDidUnlock( proximity_auth::ScreenlockBridge::LockHandler::ScreenType screen_type) { DispatchEvent(events::SCREENLOCK_PRIVATE_ON_CHANGED, screenlock::OnChanged::kEventName, - new base::FundamentalValue(false)); + base::MakeUnique<base::FundamentalValue>(false)); } void ScreenlockPrivateEventRouter::OnFocusedUserChanged( @@ -135,10 +136,10 @@ void ScreenlockPrivateEventRouter::OnFocusedUserChanged( void ScreenlockPrivateEventRouter::DispatchEvent( events::HistogramValue histogram_value, const std::string& event_name, - base::Value* arg) { + std::unique_ptr<base::Value> arg) { std::unique_ptr<base::ListValue> args(new base::ListValue()); if (arg) - args->Append(arg); + args->Append(std::move(arg)); std::unique_ptr<Event> event( new Event(histogram_value, event_name, std::move(args))); EventRouter::Get(browser_context_)->BroadcastEvent(std::move(event)); diff --git a/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h b/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h index ee2ff051818..b08d043a087 100644 --- a/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h +++ b/chromium/chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_SCREENLOCK_PRIVATE_SCREENLOCK_PRIVATE_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_SCREENLOCK_PRIVATE_SCREENLOCK_PRIVATE_API_H_ +#include <memory> #include <string> #include "base/macros.h" @@ -88,7 +89,7 @@ class ScreenlockPrivateEventRouter void DispatchEvent(events::HistogramValue histogram_value, const std::string& event_name, - base::Value* arg); + std::unique_ptr<base::Value> arg); content::BrowserContext* browser_context_; DISALLOW_COPY_AND_ASSIGN(ScreenlockPrivateEventRouter); diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc index e9e9d73158b..b568021ab66 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc @@ -30,7 +30,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_live_tab_context.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "components/browser_sync/browser/profile_sync_service.h" +#include "components/browser_sync/profile_sync_service.h" #include "components/sessions/content/content_live_tab.h" #include "components/sync_sessions/open_tabs_ui_delegate.h" #include "components/sync_sessions/synced_session.h" @@ -44,6 +44,8 @@ namespace extensions { +namespace { + namespace GetRecentlyClosed = api::sessions::GetRecentlyClosed; namespace GetDevices = api::sessions::GetDevices; namespace Restore = api::sessions::Restore; @@ -61,8 +63,8 @@ const char kRestoreInIncognitoError[] = // Comparator function for use with std::sort that will sort sessions by // descending modified_time (i.e., most recent first). -bool SortSessionsByRecency(const sync_driver::SyncedSession* s1, - const sync_driver::SyncedSession* s2) { +bool SortSessionsByRecency(const sync_sessions::SyncedSession* s1, + const sync_sessions::SyncedSession* s2) { return s1->modified_time > s2->modified_time; } @@ -79,7 +81,7 @@ tabs::Tab CreateTabModelHelper( const std::string& session_id, int index, bool pinned, - int selected_index, + bool active, const Extension* extension) { tabs::Tab tab_struct; @@ -98,12 +100,7 @@ tabs::Tab CreateTabModelHelper( } tab_struct.index = index; tab_struct.pinned = pinned; - // Note: |selected_index| from the sync sessions model is what we call - // "active" in extensions terminology. "selected" is deprecated because it's - // not clear whether it means "active" (user can see) or "highlighted" (user - // has highlighted, since you can select tabs without bringing them into the - // foreground). - tab_struct.active = index == selected_index; + tab_struct.active = active; ExtensionTabUtil::ScrubTabForExtension(extension, nullptr, &tab_struct); return tab_struct; } @@ -140,64 +137,54 @@ std::unique_ptr<api::sessions::Session> CreateSessionModelHelper( return session_struct; } -bool is_tab_entry(const sessions::TabRestoreService::Entry* entry) { - return entry->type == sessions::TabRestoreService::TAB; +bool is_window_entry(const sessions::TabRestoreService::Entry& entry) { + return entry.type == sessions::TabRestoreService::WINDOW; } -bool is_window_entry(const sessions::TabRestoreService::Entry* entry) { - return entry->type == sessions::TabRestoreService::WINDOW; -} +} // namespace tabs::Tab SessionsGetRecentlyClosedFunction::CreateTabModel( const sessions::TabRestoreService::Tab& tab, - int session_id, - int selected_index) { + bool active) { return CreateTabModelHelper(GetProfile(), tab.navigations[tab.current_navigation_index], - base::IntToString(session_id), - tab.tabstrip_index, - tab.pinned, - selected_index, - extension()); + base::IntToString(tab.id), tab.tabstrip_index, + tab.pinned, active, extension()); } std::unique_ptr<windows::Window> SessionsGetRecentlyClosedFunction::CreateWindowModel( - const sessions::TabRestoreService::Window& window, - int session_id) { + const sessions::TabRestoreService::Window& window) { DCHECK(!window.tabs.empty()); - std::unique_ptr<std::vector<tabs::Tab>> tabs(new std::vector<tabs::Tab>()); - for (size_t i = 0; i < window.tabs.size(); ++i) { - tabs->push_back(CreateTabModel(window.tabs[i], window.tabs[i].id, - window.selected_tab_index)); - } + auto tabs = base::MakeUnique<std::vector<tabs::Tab>>(); + for (const auto& tab : window.tabs) + tabs->push_back( + CreateTabModel(*tab, tab->tabstrip_index == window.selected_tab_index)); - return CreateWindowModelHelper(std::move(tabs), base::IntToString(session_id), + return CreateWindowModelHelper(std::move(tabs), base::IntToString(window.id), windows::WINDOW_TYPE_NORMAL, windows::WINDOW_STATE_NORMAL); } std::unique_ptr<api::sessions::Session> SessionsGetRecentlyClosedFunction::CreateSessionModel( - const sessions::TabRestoreService::Entry* entry) { + const sessions::TabRestoreService::Entry& entry) { std::unique_ptr<tabs::Tab> tab; std::unique_ptr<windows::Window> window; - switch (entry->type) { + switch (entry.type) { case sessions::TabRestoreService::TAB: tab.reset(new tabs::Tab(CreateTabModel( - *static_cast<const sessions::TabRestoreService::Tab*>(entry), - entry->id, -1))); + static_cast<const sessions::TabRestoreService::Tab&>(entry), false))); break; case sessions::TabRestoreService::WINDOW: window = CreateWindowModel( - *static_cast<const sessions::TabRestoreService::Window*>(entry), - entry->id); + static_cast<const sessions::TabRestoreService::Window&>(entry)); break; default: NOTREACHED(); } - return CreateSessionModelHelper(entry->timestamp.ToTimeT(), std::move(tab), + return CreateSessionModelHelper(entry.timestamp.ToTimeT(), std::move(tab), std::move(window)); } @@ -227,9 +214,8 @@ bool SessionsGetRecentlyClosedFunction::RunSync() { // List of entries. They are ordered from most to least recent. // We prune the list to contain max 25 entries at any time and removes // uninteresting entries. - for (const sessions::TabRestoreService::Entry* entry : - tab_restore_service->entries()) { - result.push_back(std::move(*CreateSessionModel(entry))); + for (const auto& entry : tab_restore_service->entries()) { + result.push_back(std::move(*CreateSessionModel(*entry))); } results_ = GetRecentlyClosed::Results::Create(result); @@ -240,16 +226,11 @@ tabs::Tab SessionsGetDevicesFunction::CreateTabModel( const std::string& session_tag, const sessions::SessionTab& tab, int tab_index, - int selected_index) { + bool active) { std::string session_id = SessionId(session_tag, tab.tab_id.id()).ToString(); return CreateTabModelHelper( - GetProfile(), - tab.navigations[tab.normalized_navigation_index()], - session_id, - tab_index, - tab.pinned, - selected_index, - extension()); + GetProfile(), tab.navigations[tab.normalized_navigation_index()], + session_id, tab_index, tab.pinned, active, extension()); } std::unique_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel( @@ -261,7 +242,7 @@ std::unique_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel( // from most recent to least recent. std::vector<const sessions::SessionTab*> tabs_in_window; for (size_t i = 0; i < window.tabs.size(); ++i) { - const sessions::SessionTab* tab = window.tabs[i]; + const sessions::SessionTab* tab = window.tabs[i].get(); if (tab->navigations.empty()) continue; const sessions::SerializedNavigationEntry& current_navigation = @@ -278,7 +259,7 @@ std::unique_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel( std::unique_ptr<std::vector<tabs::Tab>> tabs(new std::vector<tabs::Tab>()); for (size_t i = 0; i < tabs_in_window.size(); ++i) { tabs->push_back(CreateTabModel(session_tag, *tabs_in_window[i], i, - window.selected_tab_index)); + window.selected_tab_index == (int)i)); } std::string session_id = @@ -342,7 +323,7 @@ SessionsGetDevicesFunction::CreateSessionModel( } api::sessions::Device SessionsGetDevicesFunction::CreateDeviceModel( - const sync_driver::SyncedSession* session) { + const sync_sessions::SyncedSession* session) { int max_results = api::sessions::MAX_SESSION_RESULTS; // Already validated in RunAsync(). std::unique_ptr<GetDevices::Params> params( @@ -354,8 +335,7 @@ api::sessions::Device SessionsGetDevicesFunction::CreateDeviceModel( device_struct.info = session->session_name; device_struct.device_name = session->session_name; - for (sync_driver::SyncedSession::SyncedWindowMap::const_iterator it = - session->windows.begin(); + for (auto it = session->windows.begin(); it != session->windows.end() && static_cast<int>(device_struct.sessions.size()) < max_results; ++it) { @@ -368,7 +348,7 @@ api::sessions::Device SessionsGetDevicesFunction::CreateDeviceModel( } bool SessionsGetDevicesFunction::RunSync() { - ProfileSyncService* service = + browser_sync::ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile()); if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) { // Sync not enabled. @@ -377,8 +357,9 @@ bool SessionsGetDevicesFunction::RunSync() { return true; } - sync_driver::OpenTabsUIDelegate* open_tabs = service->GetOpenTabsUIDelegate(); - std::vector<const sync_driver::SyncedSession*> sessions; + sync_sessions::OpenTabsUIDelegate* open_tabs = + service->GetOpenTabsUIDelegate(); + std::vector<const sync_sessions::SyncedSession*> sessions; if (!(open_tabs && open_tabs->GetAllForeignSessions(&sessions))) { results_ = GetDevices::Results::Create(std::vector<api::sessions::Device>()); @@ -420,8 +401,8 @@ void SessionsRestoreFunction::SetResultRestoredTab( bool SessionsRestoreFunction::SetResultRestoredWindow(int window_id) { WindowController* controller = NULL; - if (!windows_util::GetWindowFromWindowID(this, window_id, 0, &controller)) { - // error_ is set by GetWindowFromWindowId function call. + if (!windows_util::GetWindowFromWindowID(this, window_id, 0, &controller, + &error_)) { return false; } std::unique_ptr<base::DictionaryValue> window_value( @@ -437,14 +418,15 @@ bool SessionsRestoreFunction::SetResultRestoredWindow(int window_id) { bool SessionsRestoreFunction::RestoreMostRecentlyClosed(Browser* browser) { sessions::TabRestoreService* tab_restore_service = TabRestoreServiceFactory::GetForProfile(GetProfile()); - sessions::TabRestoreService::Entries entries = tab_restore_service->entries(); + const sessions::TabRestoreService::Entries& entries = + tab_restore_service->entries(); if (entries.empty()) { SetError(kNoRecentlyClosedSessionsError); return false; } - bool is_window = is_window_entry(entries.front()); + bool is_window = is_window_entry(*entries.front()); sessions::LiveTabContext* context = BrowserLiveTabContext::FindContextForWebContents( browser->tab_strip_model()->GetActiveWebContents()); @@ -467,7 +449,8 @@ bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id, Browser* browser) { sessions::TabRestoreService* tab_restore_service = TabRestoreServiceFactory::GetForProfile(GetProfile()); - sessions::TabRestoreService::Entries entries = tab_restore_service->entries(); + const sessions::TabRestoreService::Entries& entries = + tab_restore_service->entries(); if (entries.empty()) { SetInvalidIdError(session_id.ToString()); @@ -476,12 +459,11 @@ bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id, // Check if the recently closed list contains an entry with the provided id. bool is_window = false; - for (sessions::TabRestoreService::Entries::iterator it = entries.begin(); - it != entries.end(); ++it) { - if ((*it)->id == session_id.id()) { - // The only time a full window is being restored is if the entry ID + for (const auto& entry : entries) { + if (entry->id == session_id.id()) { + // A full window is being restored only if the entry ID // matches the provided ID and the entry type is Window. - is_window = is_window_entry(*it); + is_window = is_window_entry(*entry); break; } } @@ -490,7 +472,8 @@ bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id, BrowserLiveTabContext::FindContextForWebContents( browser->tab_strip_model()->GetActiveWebContents()); std::vector<sessions::LiveTab*> restored_tabs = - tab_restore_service->RestoreEntryById(context, session_id.id(), UNKNOWN); + tab_restore_service->RestoreEntryById(context, session_id.id(), + WindowOpenDisposition::UNKNOWN); // If the ID is invalid, restored_tabs will be empty. if (restored_tabs.empty()) { SetInvalidIdError(session_id.ToString()); @@ -512,13 +495,14 @@ bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id, bool SessionsRestoreFunction::RestoreForeignSession(const SessionId& session_id, Browser* browser) { - ProfileSyncService* service = + browser_sync::ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile()); if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) { SetError(kSessionSyncError); return false; } - sync_driver::OpenTabsUIDelegate* open_tabs = service->GetOpenTabsUIDelegate(); + sync_sessions::OpenTabsUIDelegate* open_tabs = + service->GetOpenTabsUIDelegate(); if (!open_tabs) { SetError(kSessionSyncError); return false; @@ -532,8 +516,8 @@ bool SessionsRestoreFunction::RestoreForeignSession(const SessionId& session_id, content::WebContents* contents = tab_strip->GetActiveWebContents(); content::WebContents* tab_contents = - SessionRestore::RestoreForeignSessionTab(contents, *tab, - NEW_FOREGROUND_TAB); + SessionRestore::RestoreForeignSessionTab( + contents, *tab, WindowOpenDisposition::NEW_FOREGROUND_TAB); SetResultRestoredTab(tab_contents); return true; } @@ -612,9 +596,9 @@ SessionsEventRouter::~SessionsEventRouter() { void SessionsEventRouter::TabRestoreServiceChanged( sessions::TabRestoreService* service) { std::unique_ptr<base::ListValue> args(new base::ListValue()); - EventRouter::Get(profile_)->BroadcastEvent(base::WrapUnique( - new Event(events::SESSIONS_ON_CHANGED, - api::sessions::OnChanged::kEventName, std::move(args)))); + EventRouter::Get(profile_)->BroadcastEvent(base::MakeUnique<Event>( + events::SESSIONS_ON_CHANGED, api::sessions::OnChanged::kEventName, + std::move(args))); } void SessionsEventRouter::TabRestoreServiceDestroyed( diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h index cd1afeb4eef..6f8480581b6 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h @@ -19,7 +19,7 @@ class Profile; -namespace sync_driver { +namespace sync_sessions { struct SyncedSession; } @@ -36,13 +36,11 @@ class SessionsGetRecentlyClosedFunction : public ChromeSyncExtensionFunction { private: api::tabs::Tab CreateTabModel(const sessions::TabRestoreService::Tab& tab, - int session_id, - int selected_index); + bool active); std::unique_ptr<api::windows::Window> CreateWindowModel( - const sessions::TabRestoreService::Window& window, - int session_id); + const sessions::TabRestoreService::Window& window); std::unique_ptr<api::sessions::Session> CreateSessionModel( - const sessions::TabRestoreService::Entry* entry); + const sessions::TabRestoreService::Entry& entry); }; class SessionsGetDevicesFunction : public ChromeSyncExtensionFunction { @@ -55,7 +53,7 @@ class SessionsGetDevicesFunction : public ChromeSyncExtensionFunction { api::tabs::Tab CreateTabModel(const std::string& session_tag, const sessions::SessionTab& tab, int tab_index, - int selected_index); + bool active); std::unique_ptr<api::windows::Window> CreateWindowModel( const sessions::SessionWindow& window, const std::string& session_tag); @@ -63,7 +61,7 @@ class SessionsGetDevicesFunction : public ChromeSyncExtensionFunction { const sessions::SessionWindow& window, const std::string& session_tag); api::sessions::Device CreateDeviceModel( - const sync_driver::SyncedSession* session); + const sync_sessions::SyncedSession* session); }; class SessionsRestoreFunction : public ChromeSyncExtensionFunction { diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc index ef3e5cb24a4..b510b29b875 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc @@ -25,16 +25,16 @@ #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" -#include "components/browser_sync/browser/profile_sync_service.h" -#include "components/browser_sync/browser/profile_sync_service_mock.h" -#include "components/sync_driver/local_device_info_provider_mock.h" -#include "components/sync_driver/sync_api_component_factory_mock.h" +#include "components/browser_sync/profile_sync_service.h" +#include "components/browser_sync/profile_sync_service_mock.h" +#include "components/sync/api/attachments/attachment_id.h" +#include "components/sync/api/fake_sync_change_processor.h" +#include "components/sync/api/sync_error_factory_mock.h" +#include "components/sync/core/attachments/attachment_service_proxy_for_test.h" +#include "components/sync/device_info/local_device_info_provider_mock.h" +#include "components/sync/driver/sync_api_component_factory_mock.h" #include "components/sync_sessions/sessions_sync_manager.h" #include "extensions/browser/api_test_utils.h" -#include "sync/api/attachments/attachment_id.h" -#include "sync/api/fake_sync_change_processor.h" -#include "sync/api/sync_error_factory_mock.h" -#include "sync/internal_api/public/attachments/attachment_service_proxy_for_test.h" #if defined(OS_CHROMEOS) #include "chromeos/chromeos_switches.h" @@ -182,20 +182,21 @@ void ExtensionSessionsTest::SetUpOnMainThread() { std::unique_ptr<KeyedService> ExtensionSessionsTest::BuildProfileSyncService( content::BrowserContext* context) { - std::unique_ptr<SyncApiComponentFactoryMock> factory( - new SyncApiComponentFactoryMock()); + std::unique_ptr<syncer::SyncApiComponentFactoryMock> factory( + new syncer::SyncApiComponentFactoryMock()); factory->SetLocalDeviceInfoProvider( - std::unique_ptr<sync_driver::LocalDeviceInfoProvider>( - new sync_driver::LocalDeviceInfoProviderMock( + std::unique_ptr<syncer::LocalDeviceInfoProvider>( + new syncer::LocalDeviceInfoProviderMock( kSessionTags[0], "machine name", "Chromium 10k", "Chrome 10k", sync_pb::SyncEnums_DeviceType_TYPE_LINUX, "device_id"))); Profile* profile = static_cast<Profile*>(context); - ProfileSyncServiceMock* sync_service = - new ProfileSyncServiceMock(CreateProfileSyncServiceParamsForTest( - base::WrapUnique(new browser_sync::ChromeSyncClient(profile)), - profile)); + browser_sync::ProfileSyncServiceMock* sync_service = + new browser_sync::ProfileSyncServiceMock( + CreateProfileSyncServiceParamsForTest( + base::MakeUnique<browser_sync::ChromeSyncClient>(profile), + profile)); static_cast<browser_sync::ChromeSyncClient*>(sync_service->GetSyncClient()) ->SetSyncApiComponentFactoryForTesting(std::move(factory)); return base::WrapUnique(sync_service); @@ -211,9 +212,10 @@ void ExtensionSessionsTest::CreateTestProfileSyncService() { Profile* profile = Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS); profile_manager->RegisterTestingProfile(profile, true, false); - ProfileSyncServiceMock* service = static_cast<ProfileSyncServiceMock*>( - ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( - profile, &ExtensionSessionsTest::BuildProfileSyncService)); + browser_sync::ProfileSyncServiceMock* service = + static_cast<browser_sync::ProfileSyncServiceMock*>( + ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( + profile, &ExtensionSessionsTest::BuildProfileSyncService)); syncer::ModelTypeSet preferred_types; preferred_types.Put(syncer::SESSIONS); @@ -264,7 +266,7 @@ void ExtensionSessionsTest::CreateSessionModels() { initial_data.push_back(syncer::SyncData::CreateRemoteData( 1, entity, base::Time(), syncer::AttachmentIdList(), syncer::AttachmentServiceProxyForTest::Create(), - browser_sync::SessionsSyncManager::TagHashFromSpecifics( + sync_sessions::SessionsSyncManager::TagHashFromSpecifics( entity.session()))); for (size_t i = 0; i < tabs.size(); i++) { sync_pb::EntitySpecifics entity; @@ -272,7 +274,7 @@ void ExtensionSessionsTest::CreateSessionModels() { initial_data.push_back(syncer::SyncData::CreateRemoteData( i + 2, entity, base::Time(), syncer::AttachmentIdList(), syncer::AttachmentServiceProxyForTest::Create(), - browser_sync::SessionsSyncManager::TagHashFromSpecifics( + sync_sessions::SessionsSyncManager::TagHashFromSpecifics( entity.session()))); } } diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc index 56b8ae0cd9b..8ffa9275392 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc @@ -8,6 +8,7 @@ #include <utility> #include "base/lazy_instance.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/api/preference/preference_api.h" #include "chrome/browser/prefs/session_startup_pref.h" @@ -43,80 +44,80 @@ std::string SubstituteInstallParam(std::string str, } // Find the prepopulated search engine with the given id. -bool GetPrepopulatedSearchProvider(PrefService* prefs, - int prepopulated_id, - TemplateURLData* data) { - DCHECK(data); +std::unique_ptr<TemplateURLData> GetPrepopulatedSearchProvider( + PrefService* prefs, + int prepopulated_id) { size_t default_index; - ScopedVector<TemplateURLData> engines = + std::vector<std::unique_ptr<TemplateURLData>> engines = TemplateURLPrepopulateData::GetPrepopulatedEngines(prefs, &default_index); - for (ScopedVector<TemplateURLData>::iterator i = engines.begin(); - i != engines.end(); - ++i) { - if ((*i)->prepopulate_id == prepopulated_id) { - *data = **i; - return true; - } + for (auto& engine : engines) { + if (engine->prepopulate_id == prepopulated_id) + return std::move(engine); } - return false; + return nullptr; } -TemplateURLData ConvertSearchProvider( +std::unique_ptr<TemplateURLData> ConvertSearchProvider( PrefService* prefs, const ChromeSettingsOverrides::Search_provider& search_provider, const std::string& install_parameter) { - TemplateURLData data; + std::unique_ptr<TemplateURLData> data; if (search_provider.prepopulated_id) { - if (!GetPrepopulatedSearchProvider(prefs, *search_provider.prepopulated_id, - &data)) { + data = + GetPrepopulatedSearchProvider(prefs, *search_provider.prepopulated_id); + if (!data) { VLOG(1) << "Settings Overrides API can't recognize prepopulated_id=" << *search_provider.prepopulated_id; } } + if (!data) + data = base::MakeUnique<TemplateURLData>(); + if (search_provider.name) - data.SetShortName(base::UTF8ToUTF16(*search_provider.name)); + data->SetShortName(base::UTF8ToUTF16(*search_provider.name)); if (search_provider.keyword) - data.SetKeyword(base::UTF8ToUTF16(*search_provider.keyword)); - data.SetURL(SubstituteInstallParam(search_provider.search_url, - install_parameter)); + data->SetKeyword(base::UTF8ToUTF16(*search_provider.keyword)); + data->SetURL( + SubstituteInstallParam(search_provider.search_url, install_parameter)); if (search_provider.suggest_url) { - data.suggestions_url = + data->suggestions_url = SubstituteInstallParam(*search_provider.suggest_url, install_parameter); } if (search_provider.instant_url) { - data.instant_url = + data->instant_url = SubstituteInstallParam(*search_provider.instant_url, install_parameter); } if (search_provider.image_url) { - data.image_url = + data->image_url = SubstituteInstallParam(*search_provider.image_url, install_parameter); } if (search_provider.search_url_post_params) - data.search_url_post_params = *search_provider.search_url_post_params; + data->search_url_post_params = *search_provider.search_url_post_params; if (search_provider.suggest_url_post_params) - data.suggestions_url_post_params = *search_provider.suggest_url_post_params; + data->suggestions_url_post_params = + *search_provider.suggest_url_post_params; if (search_provider.instant_url_post_params) - data.instant_url_post_params = *search_provider.instant_url_post_params; + data->instant_url_post_params = *search_provider.instant_url_post_params; if (search_provider.image_url_post_params) - data.image_url_post_params = *search_provider.image_url_post_params; + data->image_url_post_params = *search_provider.image_url_post_params; if (search_provider.favicon_url) { - data.favicon_url = GURL(SubstituteInstallParam(*search_provider.favicon_url, - install_parameter)); + data->favicon_url = GURL(SubstituteInstallParam( + *search_provider.favicon_url, install_parameter)); } - data.safe_for_autoreplace = false; + data->safe_for_autoreplace = false; if (search_provider.encoding) { - data.input_encodings.clear(); - data.input_encodings.push_back(*search_provider.encoding); + data->input_encodings.clear(); + data->input_encodings.push_back(*search_provider.encoding); } - data.date_created = base::Time(); - data.last_modified = base::Time(); - data.prepopulate_id = 0; + data->date_created = base::Time(); + data->last_modified = base::Time(); + data->prepopulate_id = 0; if (search_provider.alternate_urls) { - data.alternate_urls.clear(); + data->alternate_urls.clear(); for (size_t i = 0; i < search_provider.alternate_urls->size(); ++i) { if (!search_provider.alternate_urls->at(i).empty()) - data.alternate_urls.push_back(SubstituteInstallParam( + data->alternate_urls.push_back(SubstituteInstallParam( search_provider.alternate_urls->at(i), install_parameter)); } } @@ -267,18 +268,20 @@ void SettingsOverridesAPI::RegisterSearchProvider( const SettingsOverrides* settings = SettingsOverrides::Get(extension); DCHECK(settings); DCHECK(settings->search_engine); - std::unique_ptr<TemplateURL::AssociatedExtensionInfo> info( - new TemplateURL::AssociatedExtensionInfo( - TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION, extension->id())); + auto info = + base::MakeUnique<TemplateURL::AssociatedExtensionInfo>(extension->id()); info->wants_to_be_default_engine = settings->search_engine->is_default; + ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_); info->install_time = prefs->GetInstallTime(extension->id()); std::string install_parameter = prefs->GetInstallParam(extension->id()); - TemplateURLData data = ConvertSearchProvider( + std::unique_ptr<TemplateURLData> data = ConvertSearchProvider( profile_->GetPrefs(), *settings->search_engine, install_parameter); - data.show_in_default_list = info->wants_to_be_default_engine; - url_service_->AddExtensionControlledTURL(new TemplateURL(data), - std::move(info)); + data->show_in_default_list = info->wants_to_be_default_engine; + auto turl = base::MakeUnique<TemplateURL>( + *data, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION); + + url_service_->AddExtensionControlledTURL(std::move(turl), std::move(info)); } template <> 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 e465f593b70..d03d2e622d8 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 @@ -10,12 +10,12 @@ #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" -#include "chrome/common/extensions/features/feature_channel.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h" #include "components/version_info/version_info.h" +#include "extensions/common/features/feature_channel.h" namespace { @@ -69,7 +69,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, OverrideSettings) { EXPECT_TRUE(VerifyTemplateURLServiceLoad(url_service)); TemplateURL* default_provider = url_service->GetDefaultSearchProvider(); ASSERT_TRUE(default_provider); - EXPECT_EQ(TemplateURL::NORMAL, default_provider->GetType()); + EXPECT_EQ(TemplateURL::NORMAL, default_provider->type()); #if defined(OS_MACOSX) // On Mac, this API is limited to trunk. @@ -92,7 +92,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, OverrideSettings) { startup_pref.urls); TemplateURL* extension_provider = url_service->GetDefaultSearchProvider(); EXPECT_EQ(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION, - extension_provider->GetType()); + extension_provider->type()); EXPECT_EQ(base::ASCIIToUTF16("name.de"), extension_provider->short_name()); EXPECT_EQ(base::ASCIIToUTF16("keyword.de"), extension_provider->keyword()); EXPECT_EQ("http://www.foo.de/s?q={searchTerms}&id=10", 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 9c41a1eaeb3..e64b8ece704 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -67,6 +67,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["bookmark_bar.show_on_all_tabs"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["browser.custom_chrome_frame"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["browser.show_home_button"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; @@ -113,6 +115,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)["profile.password_manager_enabled"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["credentials_enable_autosignin"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["safebrowsing.enabled"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["safebrowsing.extended_reporting_enabled"] = @@ -241,6 +245,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["cros.metrics.reportingEnabled"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["cros.device.allow_bluetooth"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["cros.device.attestation_for_content_protection_enabled"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["settings.internet.wake_on_wifi_darkconnect"] = @@ -248,6 +254,16 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { (*s_whitelist)["settings.enable_screen_lock"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + // Time zone settings. + (*s_whitelist)["settings.resolve_timezone_by_geolocation"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + + // Ash settings. + (*s_whitelist)["settings.enable_stylus_tools"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["settings.launch_palette_on_eject_event"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + // Input method settings. (*s_whitelist)["settings.language.preload_engines"] = settings_private::PrefType::PREF_TYPE_STRING; @@ -259,6 +275,12 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["settings.touchpad.natural_scroll"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["settings.touchpad.sensitivity2"] = + settings_private::PrefType::PREF_TYPE_NUMBER; + (*s_whitelist)["settings.mouse.primary_right"] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["settings.mouse.sensitivity2"] = + settings_private::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)["settings.language.xkb_remap_search_key_to"] = settings_private::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)["settings.language.xkb_remap_control_key_to"] = @@ -286,6 +308,7 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)["hardware_acceleration_mode.enabled"] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)["proxy"] = settings_private::PrefType::PREF_TYPE_DICTIONARY; #endif #if defined(GOOGLE_CHROME_BUILD) @@ -323,7 +346,7 @@ std::unique_ptr<settings_private::PrefObject> PrefsUtil::GetCrosSettingsPref( #if defined(OS_CHROMEOS) const base::Value* value = CrosSettings::Get()->GetPref(name); - DCHECK(value); + DCHECK(value) << "Pref not found: " << name; pref_object->key = name; pref_object->type = GetType(name, value->GetType()); pref_object->value.reset(value->DeepCopy()); diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.cc index 726df26e337..7a76483e9b7 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.cc @@ -6,18 +6,17 @@ #include <memory> -#include "base/memory/scoped_vector.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h" #include "chrome/browser/profiles/profile.h" #include "components/crx_file/id_util.h" -#include "components/sync_driver/device_info.h" +#include "components/sync/device_info/device_info.h" using base::DictionaryValue; using base::Value; -using sync_driver::DeviceInfo; +using syncer::DeviceInfo; namespace extensions { @@ -69,16 +68,15 @@ std::string GetRandomId( } void CreateMappingForUnmappedDevices( - std::vector<DeviceInfo*>* device_info, + const std::vector<std::unique_ptr<DeviceInfo>>& device_info, base::DictionaryValue* value) { - for (unsigned int i = 0; i < device_info->size(); ++i) { - DeviceInfo* device = (*device_info)[i]; + for (const std::unique_ptr<DeviceInfo>& device : device_info) { std::string local_id = GetPublicIdFromGUID(*value, device->guid()); // If the device does not have a local id, set one. if (local_id.empty()) { - local_id = GetRandomId(*value, device_info->size()); + local_id = GetRandomId(*value, device_info.size()); value->SetString(local_id, device->guid()); } device->set_public_id(local_id); @@ -91,14 +89,11 @@ std::unique_ptr<DeviceInfo> GetDeviceInfoForClientId( Profile* profile) { DCHECK(crx_file::id_util::IdIsValid(extension_id)) << extension_id << " is not valid"; - ScopedVector<DeviceInfo> devices = GetAllSignedInDevices(extension_id, - profile); - for (ScopedVector<DeviceInfo>::iterator it = devices.begin(); - it != devices.end(); - ++it) { - if ((*it)->guid() == client_id) { - std::unique_ptr<DeviceInfo> device(*it); - devices.weak_erase(it); + std::vector<std::unique_ptr<DeviceInfo>> devices = + GetAllSignedInDevices(extension_id, profile); + for (auto& iter : devices) { + if (iter->guid() == client_id) { + std::unique_ptr<DeviceInfo> device = std::move(iter); return device; } } diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h b/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h index 69a8dfabb86..d04a662c693 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h @@ -14,9 +14,9 @@ namespace base { class DictionaryValue; } // namespace base -namespace sync_driver { +namespace syncer { class DeviceInfo; -} // namespace sync_driver +} // namespace syncer class Profile; @@ -45,12 +45,12 @@ std::string GetGUIDFromPublicId( // The dictionary would have the public id as the key and the // device guid as the value. void CreateMappingForUnmappedDevices( - std::vector<sync_driver::DeviceInfo*>* device_info, + const std::vector<std::unique_ptr<syncer::DeviceInfo>>& device_info, base::DictionaryValue* value); // Gets the device info for a given client id. If the device is not found // the returned pointer would be null. -std::unique_ptr<sync_driver::DeviceInfo> GetDeviceInfoForClientId( +std::unique_ptr<syncer::DeviceInfo> GetDeviceInfoForClientId( const std::string& client_id, const std::string& extension_id, Profile* profile); diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc index aa887edf0e3..83f7d3ad682 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/id_mapping_helper_unittest.cc @@ -8,13 +8,13 @@ #include <string> #include "base/guid.h" -#include "base/memory/scoped_vector.h" +#include "base/memory/ptr_util.h" #include "base/values.h" -#include "components/sync_driver/device_info.h" +#include "components/sync/device_info/device_info.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using sync_driver::DeviceInfo; +using syncer::DeviceInfo; namespace extensions { bool VerifyDictionary( @@ -30,25 +30,19 @@ bool VerifyDictionary( } TEST(IdMappingHelperTest, SetIdsForDevices) { - ScopedVector<DeviceInfo> devices; - - devices.push_back(new DeviceInfo(base::GenerateGUID(), - "abc Device", - "XYZ v1", - "XYZ SyncAgent v1", - sync_pb::SyncEnums_DeviceType_TYPE_LINUX, - "device_id1")); - - devices.push_back(new DeviceInfo(base::GenerateGUID(), - "def Device", - "XYZ v1", - "XYZ SyncAgent v1", - sync_pb::SyncEnums_DeviceType_TYPE_LINUX, - "device_id2")); + std::vector<std::unique_ptr<DeviceInfo>> devices; + + devices.push_back(base::MakeUnique<DeviceInfo>( + base::GenerateGUID(), "abc Device", "XYZ v1", "XYZ SyncAgent v1", + sync_pb::SyncEnums_DeviceType_TYPE_LINUX, "device_id1")); + + devices.push_back(base::MakeUnique<DeviceInfo>( + base::GenerateGUID(), "def Device", "XYZ v1", "XYZ SyncAgent v1", + sync_pb::SyncEnums_DeviceType_TYPE_LINUX, "device_id2")); base::DictionaryValue dictionary; - CreateMappingForUnmappedDevices(&(devices.get()), &dictionary); + CreateMappingForUnmappedDevices(devices, &dictionary); std::string public_id1 = devices[0]->public_id(); std::string public_id2 = devices[1]->public_id(); @@ -59,14 +53,11 @@ TEST(IdMappingHelperTest, SetIdsForDevices) { EXPECT_NE(public_id1, public_id2); // Now add a third device. - devices.push_back(new DeviceInfo(base::GenerateGUID(), - "ghi Device", - "XYZ v1", - "XYZ SyncAgent v1", - sync_pb::SyncEnums_DeviceType_TYPE_LINUX, - "device_id3")); - - CreateMappingForUnmappedDevices(&(devices.get()), &dictionary); + devices.push_back(base::MakeUnique<DeviceInfo>( + base::GenerateGUID(), "ghi Device", "XYZ v1", "XYZ SyncAgent v1", + sync_pb::SyncEnums_DeviceType_TYPE_LINUX, "device_id3")); + + CreateMappingForUnmappedDevices(devices, &dictionary); // Now make sure the existing ids are not changed. EXPECT_EQ(public_id1, devices[0]->public_id()); diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc index 5145d00a8a4..c1023b80edf 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc @@ -7,21 +7,20 @@ #include <memory> #include <utility> -#include "base/memory/scoped_vector.h" #include "base/values.h" #include "chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/common/extensions/api/signed_in_devices.h" -#include "components/browser_sync/browser/profile_sync_service.h" -#include "components/sync_driver/device_info_tracker.h" -#include "components/sync_driver/local_device_info_provider.h" +#include "components/browser_sync/profile_sync_service.h" +#include "components/sync/device_info/device_info_tracker.h" +#include "components/sync/device_info/local_device_info_provider.h" #include "extensions/browser/extension_prefs.h" using base::DictionaryValue; -using sync_driver::DeviceInfo; -using sync_driver::DeviceInfoTracker; -using sync_driver::LocalDeviceInfoProvider; +using syncer::DeviceInfo; +using syncer::DeviceInfoTracker; +using syncer::LocalDeviceInfoProvider; namespace extensions { @@ -54,12 +53,13 @@ const base::DictionaryValue* GetIdMappingDictionary( // Helper routine to get all signed in devices. The helper takes in // the pointers for |DeviceInfoTracker| and |Extensionprefs|. This // makes it easier to test by passing mock values for these pointers. -ScopedVector<DeviceInfo> GetAllSignedInDevices( +std::vector<std::unique_ptr<DeviceInfo>> GetAllSignedInDevices( const std::string& extension_id, DeviceInfoTracker* device_tracker, ExtensionPrefs* extension_prefs) { DCHECK(device_tracker); - ScopedVector<DeviceInfo> devices = device_tracker->GetAllDeviceInfo(); + std::vector<std::unique_ptr<DeviceInfo>> devices = + device_tracker->GetAllDeviceInfo(); const base::DictionaryValue* mapping_dictionary = GetIdMappingDictionary( extension_prefs, extension_id); @@ -70,8 +70,7 @@ ScopedVector<DeviceInfo> GetAllSignedInDevices( std::unique_ptr<base::DictionaryValue> editable_mapping_dictionary( mapping_dictionary->DeepCopy()); - CreateMappingForUnmappedDevices(&(devices.get()), - editable_mapping_dictionary.get()); + CreateMappingForUnmappedDevices(devices, editable_mapping_dictionary.get()); // Write into |ExtensionPrefs| which will get persisted in disk. extension_prefs->UpdateExtensionPref(extension_id, @@ -80,7 +79,7 @@ ScopedVector<DeviceInfo> GetAllSignedInDevices( return devices; } -ScopedVector<DeviceInfo> GetAllSignedInDevices( +std::vector<std::unique_ptr<DeviceInfo>> GetAllSignedInDevices( const std::string& extension_id, Profile* profile) { // Get the device tracker and extension prefs pointers @@ -90,7 +89,7 @@ ScopedVector<DeviceInfo> GetAllSignedInDevices( DCHECK(device_tracker); if (!device_tracker->IsSyncing()) { // Devices are not sync'ing. - return ScopedVector<DeviceInfo>(); + return std::vector<std::unique_ptr<DeviceInfo>>(); } ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile); @@ -100,7 +99,8 @@ ScopedVector<DeviceInfo> GetAllSignedInDevices( std::unique_ptr<DeviceInfo> GetLocalDeviceInfo(const std::string& extension_id, Profile* profile) { - ProfileSyncService* pss = ProfileSyncServiceFactory::GetForProfile(profile); + browser_sync::ProfileSyncService* pss = + ProfileSyncServiceFactory::GetForProfile(profile); if (!pss) { return std::unique_ptr<DeviceInfo>(); } @@ -131,16 +131,13 @@ bool SignedInDevicesGetFunction::RunSync() { return true; } - ScopedVector<DeviceInfo> devices = + std::vector<std::unique_ptr<DeviceInfo>> devices = GetAllSignedInDevices(extension_id(), GetProfile()); std::unique_ptr<base::ListValue> result(new base::ListValue()); - for (ScopedVector<DeviceInfo>::const_iterator it = devices.begin(); - it != devices.end(); - ++it) { - result->Append((*it)->ToValue()); - } + for (const std::unique_ptr<DeviceInfo>& device : devices) + result->Append(device->ToValue()); SetResult(std::move(result)); return true; 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 1d1c092233a..264600c4b9c 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 @@ -5,22 +5,22 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_SIGNED_IN_DEVICES_SIGNED_IN_DEVICES_API_H__ #define CHROME_BROWSER_EXTENSIONS_API_SIGNED_IN_DEVICES_SIGNED_IN_DEVICES_API_H__ +#include <memory> #include <string> #include <vector> -#include "base/memory/scoped_vector.h" #include "chrome/browser/extensions/chrome_extension_function.h" -namespace sync_driver { -class DeviceInfo; -class DeviceInfoTracker; -} // namespace sync_driver +class Profile; namespace extensions { class ExtensionPrefs; } // namespace extensions -class Profile; +namespace syncer { +class DeviceInfo; +class DeviceInfoTracker; +} // namespace syncer namespace extensions { @@ -28,13 +28,13 @@ namespace extensions { // filled with the list of devices associated with the account signed into this // |profile|. This function needs the |extension_id| because the // public device ids are set per extension. -ScopedVector<sync_driver::DeviceInfo> GetAllSignedInDevices( +std::vector<std::unique_ptr<syncer::DeviceInfo>> GetAllSignedInDevices( const std::string& extension_id, Profile* profile); -ScopedVector<sync_driver::DeviceInfo> GetAllSignedInDevices( +std::vector<std::unique_ptr<syncer::DeviceInfo>> GetAllSignedInDevices( const std::string& extension_id, - sync_driver::DeviceInfoTracker* device_tracker, + syncer::DeviceInfoTracker* device_tracker, ExtensionPrefs* extension_prefs); class SignedInDevicesGetFunction : public ChromeSyncExtensionFunction { 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 6dac6686c77..21a1e42aa2c 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 @@ -17,17 +17,17 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" -#include "components/browser_sync/browser/profile_sync_service_mock.h" +#include "components/browser_sync/profile_sync_service_mock.h" #include "components/prefs/pref_service.h" -#include "components/sync_driver/device_info.h" -#include "components/sync_driver/device_info_tracker.h" +#include "components/sync/device_info/device_info.h" +#include "components/sync/device_info/device_info_tracker.h" #include "content/public/test/test_browser_thread_bundle.h" #include "extensions/common/extension.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using sync_driver::DeviceInfo; -using sync_driver::DeviceInfoTracker; +using syncer::DeviceInfo; +using syncer::DeviceInfoTracker; using testing::Return; namespace extensions { @@ -44,23 +44,19 @@ class MockDeviceInfoTracker : public DeviceInfoTracker { return std::unique_ptr<DeviceInfo>(); } - static DeviceInfo* CloneDeviceInfo(const DeviceInfo* device_info) { - return new DeviceInfo(device_info->guid(), - device_info->client_name(), - device_info->chrome_version(), - device_info->sync_user_agent(), - device_info->device_type(), - device_info->signin_scoped_device_id()); + static std::unique_ptr<DeviceInfo> CloneDeviceInfo( + const DeviceInfo& device_info) { + return base::MakeUnique<DeviceInfo>( + device_info.guid(), device_info.client_name(), + device_info.chrome_version(), device_info.sync_user_agent(), + device_info.device_type(), device_info.signin_scoped_device_id()); } - ScopedVector<DeviceInfo> GetAllDeviceInfo() const override { - ScopedVector<DeviceInfo> list; + std::vector<std::unique_ptr<DeviceInfo>> GetAllDeviceInfo() const override { + std::vector<std::unique_ptr<DeviceInfo>> list; - for (std::vector<const DeviceInfo*>::const_iterator iter = devices_.begin(); - iter != devices_.end(); - ++iter) { - list.push_back(CloneDeviceInfo(*iter)); - } + for (const DeviceInfo* device : devices_) + list.push_back(CloneDeviceInfo(*device)); return list; } @@ -109,8 +105,8 @@ TEST(SignedInDevicesAPITest, GetSignedInDevices) { device_tracker.Add(&device_info1); device_tracker.Add(&device_info2); - ScopedVector<DeviceInfo> output1 = GetAllSignedInDevices( - extension_test.get()->id(), &device_tracker, extension_prefs.prefs()); + std::vector<std::unique_ptr<DeviceInfo>> output1 = GetAllSignedInDevices( + extension_test->id(), &device_tracker, extension_prefs.prefs()); std::string public_id1 = output1[0]->public_id(); std::string public_id2 = output1[1]->public_id(); @@ -130,8 +126,8 @@ TEST(SignedInDevicesAPITest, GetSignedInDevices) { device_tracker.Add(&device_info3); - ScopedVector<DeviceInfo> output2 = GetAllSignedInDevices( - extension_test.get()->id(), &device_tracker, extension_prefs.prefs()); + std::vector<std::unique_ptr<DeviceInfo>> output2 = GetAllSignedInDevices( + extension_test->id(), &device_tracker, extension_prefs.prefs()); EXPECT_EQ(output2[0]->public_id(), public_id1); EXPECT_EQ(output2[1]->public_id(), public_id2); @@ -142,8 +138,8 @@ TEST(SignedInDevicesAPITest, GetSignedInDevices) { EXPECT_NE(public_id3, public_id2); } -class ProfileSyncServiceMockForExtensionTests: - public ProfileSyncServiceMock { +class ProfileSyncServiceMockForExtensionTests + : public browser_sync::ProfileSyncServiceMock { public: explicit ProfileSyncServiceMockForExtensionTests(Profile* p) : ProfileSyncServiceMock(CreateProfileSyncServiceParamsForTest(p)) {} @@ -155,8 +151,8 @@ class ProfileSyncServiceMockForExtensionTests: std::unique_ptr<KeyedService> CreateProfileSyncServiceMock( content::BrowserContext* context) { - return base::WrapUnique(new ProfileSyncServiceMockForExtensionTests( - Profile::FromBrowserContext(context))); + return base::MakeUnique<ProfileSyncServiceMockForExtensionTests>( + Profile::FromBrowserContext(context)); } class ExtensionSignedInDevicesTest : public ExtensionApiUnittest { @@ -254,8 +250,8 @@ TEST_F(ExtensionSignedInDevicesTest, DeviceInfoTrackerNotInitialized) { .WillOnce(Return(&device_tracker)); EXPECT_CALL(*pss_mock, Shutdown()); - ScopedVector<DeviceInfo> output = GetAllSignedInDevices( - extension()->id(), profile()); + std::vector<std::unique_ptr<DeviceInfo>> output = + GetAllSignedInDevices(extension()->id(), profile()); EXPECT_TRUE(output.empty()); } diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.cc index ecb7a823c53..ab3864f80fd 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.cc @@ -10,21 +10,20 @@ #include <vector> #include "base/lazy_instance.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/scoped_vector.h" +#include "base/memory/ptr_util.h" #include "base/values.h" #include "chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/common/extensions/api/signed_in_devices.h" -#include "components/browser_sync/browser/profile_sync_service.h" -#include "components/sync_driver/device_info.h" +#include "components/browser_sync/profile_sync_service.h" +#include "components/sync/device_info/device_info.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" -using sync_driver::DeviceInfo; +using syncer::DeviceInfo; namespace extensions { namespace { @@ -44,7 +43,8 @@ SignedInDevicesChangeObserver::SignedInDevicesChangeObserver( const std::string& extension_id, Profile* profile) : extension_id_(extension_id), profile_(profile) { - ProfileSyncService* pss = ProfileSyncServiceFactory::GetForProfile(profile_); + browser_sync::ProfileSyncService* pss = + ProfileSyncServiceFactory::GetForProfile(profile_); if (pss) { DCHECK(pss->GetDeviceInfoTracker()); pss->GetDeviceInfoTracker()->AddObserver(this); @@ -52,7 +52,8 @@ SignedInDevicesChangeObserver::SignedInDevicesChangeObserver( } SignedInDevicesChangeObserver::~SignedInDevicesChangeObserver() { - ProfileSyncService* pss = ProfileSyncServiceFactory::GetForProfile(profile_); + browser_sync::ProfileSyncService* pss = + ProfileSyncServiceFactory::GetForProfile(profile_); if (pss) { DCHECK(pss->GetDeviceInfoTracker()); pss->GetDeviceInfoTracker()->RemoveObserver(this); @@ -62,11 +63,11 @@ SignedInDevicesChangeObserver::~SignedInDevicesChangeObserver() { void SignedInDevicesChangeObserver::OnDeviceInfoChange() { // There is a change in the list of devices. Get all devices and send them to // the listener. - ScopedVector<DeviceInfo> devices = GetAllSignedInDevices(extension_id_, - profile_); + std::vector<std::unique_ptr<DeviceInfo>> devices = + GetAllSignedInDevices(extension_id_, profile_); std::vector<api::signed_in_devices::DeviceInfo> args; - for (const DeviceInfo* info : devices) { + for (const std::unique_ptr<DeviceInfo>& info : devices) { api::signed_in_devices::DeviceInfo api_device; FillDeviceInfo(*info, &api_device); args.push_back(std::move(api_device)); @@ -123,19 +124,16 @@ SignedInDevicesManager::~SignedInDevicesManager() { void SignedInDevicesManager::OnListenerAdded( const EventListenerInfo& details) { - for (ScopedVector<SignedInDevicesChangeObserver>::const_iterator it = - change_observers_.begin(); - it != change_observers_.end(); - ++it) { - if ((*it)->extension_id() == details.extension_id) { + for (const std::unique_ptr<SignedInDevicesChangeObserver>& observer : + change_observers_) { + if (observer->extension_id() == details.extension_id) { DCHECK(false) <<"OnListenerAded fired twice for same extension"; return; } } - change_observers_.push_back(new SignedInDevicesChangeObserver( - details.extension_id, - profile_)); + change_observers_.push_back(base::MakeUnique<SignedInDevicesChangeObserver>( + details.extension_id, profile_)); } void SignedInDevicesManager::OnListenerRemoved( @@ -145,10 +143,9 @@ void SignedInDevicesManager::OnListenerRemoved( void SignedInDevicesManager::RemoveChangeObserverForExtension( const std::string& extension_id) { - for (ScopedVector<SignedInDevicesChangeObserver>::iterator it = - change_observers_.begin(); - it != change_observers_.end(); - ++it) { + for (std::vector<std::unique_ptr<SignedInDevicesChangeObserver>>::iterator + it = change_observers_.begin(); + it != change_observers_.end(); ++it) { if ((*it)->extension_id() == extension_id) { change_observers_.erase(it); return; diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h index bc5cacb620d..2ed5be0a07a 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h @@ -5,13 +5,14 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_SIGNED_IN_DEVICES_SIGNED_IN_DEVICES_MANAGER_H__ #define CHROME_BROWSER_EXTENSIONS_API_SIGNED_IN_DEVICES_SIGNED_IN_DEVICES_MANAGER_H__ +#include <memory> #include <string> +#include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_vector.h" #include "base/scoped_observer.h" -#include "components/sync_driver/device_info_tracker.h" +#include "components/sync/device_info/device_info_tracker.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_registry_observer.h" @@ -39,7 +40,7 @@ struct EventListenerInfo; // public ids for devices(public ids for a device, is not the same for // all extensions). class SignedInDevicesChangeObserver - : public sync_driver::DeviceInfoTracker::Observer { + : public syncer::DeviceInfoTracker::Observer { public: SignedInDevicesChangeObserver(const std::string& extension_id, Profile* profile); @@ -91,7 +92,7 @@ class SignedInDevicesManager : public BrowserContextKeyedAPI, void RemoveChangeObserverForExtension(const std::string& extension_id); Profile* const profile_; - ScopedVector<SignedInDevicesChangeObserver> change_observers_; + std::vector<std::unique_ptr<SignedInDevicesChangeObserver>> change_observers_; // Listen to extension unloaded notification. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> diff --git a/chromium/chrome/browser/extensions/api/socket/combined_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/combined_socket_unittest.cc index 72b37c34e06..e6d2595d487 100644 --- a/chromium/chrome/browser/extensions/api/socket/combined_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/combined_socket_unittest.cc @@ -24,14 +24,14 @@ std::unique_ptr<T> CreateTestSocket( template <> std::unique_ptr<TCPSocket> CreateTestSocket( std::unique_ptr<MockTCPClientSocket> stream) { - return base::WrapUnique( - new TCPSocket(std::move(stream), "fake id", true /* is_connected */)); + return base::MakeUnique<TCPSocket>(std::move(stream), "fake id", + true /* is_connected */); } template <> std::unique_ptr<TLSSocket> CreateTestSocket( std::unique_ptr<MockTCPClientSocket> stream) { - return base::WrapUnique(new TLSSocket(std::move(stream), "fake id")); + return base::MakeUnique<TLSSocket>(std::move(stream), "fake id"); } class CombinedSocketTest : public testing::Test { diff --git a/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h b/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h index ec8847262b4..595d2685234 100644 --- a/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h +++ b/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h @@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_SOCKET_MOCK_TCP_CLIENT_SOCKET_H_ #define CHROME_BROWSER_EXTENSIONS_API_SOCKET_MOCK_TCP_CLIENT_SOCKET_H_ +#include "net/log/net_log_source.h" +#include "net/log/net_log_with_source.h" #include "net/socket/tcp_client_socket.h" #include "testing/gmock/include/gmock/gmock.h" @@ -26,7 +28,7 @@ class MockTCPClientSocket : public net::TCPClientSocket { MOCK_CONST_METHOD0(IsConnectedAndIdle, bool()); MOCK_CONST_METHOD1(GetPeerAddress, int(net::IPEndPoint*)); MOCK_CONST_METHOD1(GetLocalAddress, int(net::IPEndPoint*)); - MOCK_CONST_METHOD0(NetLog, const net::BoundNetLog&()); + MOCK_CONST_METHOD0(NetLog, const net::NetLogWithSource&()); MOCK_METHOD0(SetSubresourceSpeculation, void()); MOCK_METHOD0(SetOmniboxSpeculation, void()); MOCK_CONST_METHOD0(WasEverUsed, bool()); @@ -51,7 +53,7 @@ MockTCPClientSocket::MockTCPClientSocket() : TCPClientSocket(net::AddressList(), nullptr, nullptr, - net::NetLog::Source()) {} + net::NetLogSource()) {} MockTCPClientSocket::~MockTCPClientSocket() {} } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/socket/socket_api_unittest.cc b/chromium/chrome/browser/extensions/api/socket/socket_api_unittest.cc index 5157fd1fa25..c174cc6b44c 100644 --- a/chromium/chrome/browser/extensions/api/socket/socket_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/socket_api_unittest.cc @@ -21,7 +21,7 @@ namespace extensions { std::unique_ptr<KeyedService> ApiResourceManagerTestFactory( content::BrowserContext* context) { - return base::WrapUnique(new ApiResourceManager<Socket>(context)); + return base::MakeUnique<ApiResourceManager<Socket>>(context); } class SocketUnitTest : public ExtensionApiUnittest { diff --git a/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc index 892778d32f1..dd435b25afb 100644 --- a/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc @@ -11,6 +11,7 @@ #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/rand_callback.h" +#include "net/log/net_log_source.h" #include "net/socket/tcp_client_socket.h" #include "net/socket/tcp_server_socket.h" #include "testing/gmock/include/gmock/gmock.h" @@ -25,7 +26,7 @@ namespace extensions { class MockTCPSocket : public net::TCPClientSocket { public: explicit MockTCPSocket(const net::AddressList& address_list) - : net::TCPClientSocket(address_list, NULL, NULL, net::NetLog::Source()) {} + : net::TCPClientSocket(address_list, NULL, NULL, net::NetLogSource()) {} MOCK_METHOD3(Read, int(net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback)); @@ -43,7 +44,7 @@ class MockTCPSocket : public net::TCPClientSocket { class MockTCPServerSocket : public net::TCPServerSocket { public: - MockTCPServerSocket() : net::TCPServerSocket(NULL, net::NetLog::Source()) {} + MockTCPServerSocket() : net::TCPServerSocket(NULL, net::NetLogSource()) {} MOCK_METHOD2(Listen, int(const net::IPEndPoint& address, int backlog)); MOCK_METHOD2(Accept, int(std::unique_ptr<net::StreamSocket>* socket, diff --git a/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc index a305c9480b7..1b5663a653c 100644 --- a/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc @@ -17,6 +17,9 @@ #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/rand_callback.h" +#include "net/log/net_log_source.h" +#include "net/log/net_log_with_source.h" +#include "net/socket/next_proto.h" #include "net/socket/ssl_client_socket.h" #include "net/socket/tcp_client_socket.h" #include "testing/gmock/include/gmock/gmock.h" @@ -50,11 +53,13 @@ class MockSSLClientSocket : public net::SSLClientSocket { MOCK_CONST_METHOD0(IsConnectedAndIdle, bool()); MOCK_CONST_METHOD1(GetPeerAddress, int(net::IPEndPoint*)); MOCK_CONST_METHOD1(GetLocalAddress, int(net::IPEndPoint*)); - MOCK_CONST_METHOD0(NetLog, const net::BoundNetLog&()); + MOCK_CONST_METHOD0(NetLog, const net::NetLogWithSource&()); MOCK_METHOD0(SetSubresourceSpeculation, void()); MOCK_METHOD0(SetOmniboxSpeculation, void()); MOCK_CONST_METHOD0(WasEverUsed, bool()); MOCK_CONST_METHOD0(UsingTCPFastOpen, bool()); + MOCK_CONST_METHOD0(WasNpnNegotiated, bool()); + MOCK_CONST_METHOD0(GetNegotiatedProtocol, net::NextProto()); MOCK_METHOD1(GetSSLInfo, bool(net::SSLInfo*)); MOCK_CONST_METHOD1(GetConnectionAttempts, void(net::ConnectionAttempts*)); MOCK_METHOD0(ClearConnectionAttempts, void()); @@ -67,13 +72,13 @@ class MockSSLClientSocket : public net::SSLClientSocket { unsigned char*, unsigned int)); MOCK_METHOD1(GetSSLCertRequestInfo, void(net::SSLCertRequestInfo*)); - MOCK_CONST_METHOD1(GetNextProto, - net::SSLClientSocket::NextProtoStatus(std::string*)); MOCK_CONST_METHOD0(GetUnverifiedServerCertificateChain, scoped_refptr<net::X509Certificate>()); MOCK_CONST_METHOD0(GetChannelIDService, net::ChannelIDService*()); - MOCK_METHOD2(GetSignedEKMForTokenBinding, - net::Error(crypto::ECPrivateKey*, std::vector<uint8_t>*)); + MOCK_METHOD3(GetTokenBindingSignature, + net::Error(crypto::ECPrivateKey*, + net::TokenBindingType, + std::vector<uint8_t>*)); MOCK_CONST_METHOD0(GetChannelIDKey, crypto::ECPrivateKey*()); bool IsConnected() const override { return true; } @@ -84,7 +89,7 @@ class MockSSLClientSocket : public net::SSLClientSocket { class MockTCPSocket : public net::TCPClientSocket { public: explicit MockTCPSocket(const net::AddressList& address_list) - : net::TCPClientSocket(address_list, NULL, NULL, net::NetLog::Source()) {} + : net::TCPClientSocket(address_list, NULL, NULL, net::NetLogSource()) {} MOCK_METHOD3(Read, int(net::IOBuffer* buf, 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 3061d846e2f..9c4e5213872 100644 --- a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc @@ -10,6 +10,7 @@ #include "base/location.h" #include "base/macros.h" +#include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_task_runner_handle.h" @@ -93,32 +94,31 @@ TEST(UDPSocketUnitTest, TestUDPMulticastLoopbackMode) { socket.Connect(CreateAddressList(kGroup, 13333), base::Bind(&OnConnected)); } -static void QuitMessageLoop() { - base::MessageLoopForIO::current()->QuitNow(); -} - // Send a test multicast packet every second. // Once the target socket received the packet, the message loop will exit. -static void SendMulticastPacket(UDPSocket* src, int result) { +static void SendMulticastPacket(const base::Closure& quit_run_loop, + UDPSocket* src, + int result) { if (result == 0) { scoped_refptr<net::IOBuffer> data = new net::WrappedIOBuffer(test_message); src->Write(data, test_message_length, base::Bind(&OnSendCompleted)); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, base::Bind(&SendMulticastPacket, src, result), + FROM_HERE, base::Bind(&SendMulticastPacket, quit_run_loop, src, result), base::TimeDelta::FromSeconds(1)); } else { - QuitMessageLoop(); + quit_run_loop.Run(); FAIL() << "Failed to connect to multicast address. Error code: " << result; } } -static void OnMulticastReadCompleted(bool *packet_received, +static void OnMulticastReadCompleted(const base::Closure& quit_run_loop, + bool* packet_received, int count, scoped_refptr<net::IOBuffer> io_buffer) { EXPECT_EQ(test_message_length, count); EXPECT_EQ(0, strncmp(io_buffer->data(), test_message, test_message_length)); *packet_received = true; - QuitMessageLoop(); + quit_run_loop.Run(); } TEST(UDPSocketUnitTest, TestUDPMulticastRecv) { @@ -129,21 +129,24 @@ TEST(UDPSocketUnitTest, TestUDPMulticastRecv) { UDPSocket dest("abcdefghijklmnopqrst"); UDPSocket src("abcdefghijklmnopqrst"); + base::RunLoop run_loop; + // Receiver EXPECT_EQ(0, dest.Bind("0.0.0.0", kPort)); EXPECT_EQ(0, dest.JoinGroup(kGroup)); - dest.Read(1024, base::Bind(&OnMulticastReadCompleted, &packet_received)); + dest.Read(1024, base::Bind(&OnMulticastReadCompleted, run_loop.QuitClosure(), + &packet_received)); // Sender EXPECT_EQ(0, src.SetMulticastTimeToLive(0)); src.Connect(CreateAddressList(kGroup, kPort), - base::Bind(&SendMulticastPacket, &src)); + base::Bind(&SendMulticastPacket, run_loop.QuitClosure(), &src)); // If not received within the test action timeout, quit the message loop. - io_loop.task_runner()->PostDelayedTask( - FROM_HERE, base::Bind(&QuitMessageLoop), TestTimeouts::action_timeout()); + io_loop.task_runner()->PostDelayedTask(FROM_HERE, run_loop.QuitClosure(), + TestTimeouts::action_timeout()); - io_loop.Run(); + run_loop.Run(); EXPECT_TRUE(packet_received) << "Failed to receive from multicast address"; } diff --git a/chromium/chrome/browser/extensions/api/sockets_tcp_server/sockets_tcp_server_api_unittest.cc b/chromium/chrome/browser/extensions/api/sockets_tcp_server/sockets_tcp_server_api_unittest.cc index 38add751841..7801b0d81ef 100644 --- a/chromium/chrome/browser/extensions/api/sockets_tcp_server/sockets_tcp_server_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/sockets_tcp_server/sockets_tcp_server_api_unittest.cc @@ -23,13 +23,13 @@ namespace api { static std::unique_ptr<KeyedService> ApiResourceManagerTestFactory( content::BrowserContext* context) { - return base::WrapUnique(new ApiResourceManager<ResumableTCPSocket>(context)); + return base::MakeUnique<ApiResourceManager<ResumableTCPSocket>>(context); } static std::unique_ptr<KeyedService> ApiResourceManagerTestServerFactory( content::BrowserContext* context) { - return base::WrapUnique( - new ApiResourceManager<ResumableTCPServerSocket>(context)); + return base::MakeUnique<ApiResourceManager<ResumableTCPServerSocket>>( + context); } class SocketsTcpServerUnitTest : public ExtensionApiUnittest { 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 6b9e759880d..e8757e20e45 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 @@ -51,8 +51,8 @@ class MutablePolicyValueStore : public PolicyValueStore { : PolicyValueStore( kTestExtensionId, make_scoped_refptr(new SettingsObserverList()), - base::WrapUnique( - new LeveldbValueStore(kDatabaseUMAClientName, path))) {} + base::MakeUnique<LeveldbValueStore>(kDatabaseUMAClientName, path)) { + } ~MutablePolicyValueStore() override {} WriteResult Set(WriteOptions options, @@ -103,8 +103,8 @@ class PolicyValueStoreTest : public testing::Test { observers_->AddObserver(&observer_); store_.reset(new PolicyValueStore( kTestExtensionId, observers_, - base::WrapUnique(new LeveldbValueStore(kDatabaseUMAClientName, - scoped_temp_dir_.path())))); + base::MakeUnique<LeveldbValueStore>(kDatabaseUMAClientName, + scoped_temp_dir_.GetPath()))); } void TearDown() override { @@ -129,7 +129,7 @@ TEST_F(PolicyValueStoreTest, DontProvideRecommendedPolicies) { expected.CreateDeepCopy(), nullptr); policies.Set("may", policy::POLICY_LEVEL_RECOMMENDED, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, - base::WrapUnique(new base::FundamentalValue(456)), nullptr); + base::MakeUnique<base::FundamentalValue>(456), nullptr); store_->SetCurrentPolicy(policies); ValueStore::ReadResult result = store_->Get(); ASSERT_TRUE(result->status().ok()); diff --git a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.cc b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.cc index 1ca5ded22d2..6819f6fbe16 100644 --- a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.cc +++ b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.cc @@ -8,10 +8,10 @@ #include "base/json/json_reader.h" #include "base/json/json_writer.h" -#include "sync/api/sync_data.h" -#include "sync/protocol/app_setting_specifics.pb.h" -#include "sync/protocol/extension_setting_specifics.pb.h" -#include "sync/protocol/sync.pb.h" +#include "components/sync/api/sync_data.h" +#include "components/sync/protocol/app_setting_specifics.pb.h" +#include "components/sync/protocol/extension_setting_specifics.pb.h" +#include "components/sync/protocol/sync.pb.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h index ee922913010..fd843fbdab2 100644 --- a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h +++ b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h @@ -9,9 +9,8 @@ #include <string> #include "base/macros.h" -#include "base/memory/scoped_vector.h" #include "base/values.h" -#include "sync/api/sync_change.h" +#include "components/sync/api/sync_change.h" namespace syncer { class SyncData; @@ -68,7 +67,7 @@ class SettingSyncData { DISALLOW_COPY_AND_ASSIGN(SettingSyncData); }; -typedef ScopedVector<SettingSyncData> SettingSyncDataList; +using SettingSyncDataList = std::vector<std::unique_ptr<SettingSyncData>>; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc index 10b897bc291..3eb1437be2e 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc @@ -25,19 +25,19 @@ #include "components/policy/core/common/schema.h" #include "components/policy/core/common/schema_map.h" #include "components/policy/core/common/schema_registry.h" +#include "components/sync/api/fake_sync_change_processor.h" +#include "components/sync/api/sync_change.h" +#include "components/sync/api/sync_change_processor.h" +#include "components/sync/api/sync_change_processor_wrapper_for_test.h" +#include "components/sync/api/sync_error_factory.h" +#include "components/sync/api/sync_error_factory_mock.h" +#include "components/sync/api/syncable_service.h" #include "extensions/browser/api/storage/settings_namespace.h" #include "extensions/browser/api/storage/storage_frontend.h" #include "extensions/browser/extension_system.h" #include "extensions/common/value_builder.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" -#include "sync/api/fake_sync_change_processor.h" -#include "sync/api/sync_change.h" -#include "sync/api/sync_change_processor.h" -#include "sync/api/sync_change_processor_wrapper_for_test.h" -#include "sync/api/sync_error_factory.h" -#include "sync/api/sync_error_factory_mock.h" -#include "sync/api/syncable_service.h" #include "testing/gmock/include/gmock/gmock.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc index 96ef468619a..62bb164c0f5 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc @@ -4,11 +4,11 @@ #include "chrome/browser/extensions/api/storage/settings_sync_processor.h" #include "chrome/browser/extensions/api/storage/settings_sync_util.h" +#include "components/sync/api/sync_change_processor.h" +#include "components/sync/api/sync_data.h" +#include "components/sync/protocol/extension_setting_specifics.pb.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/storage/settings_namespace.h" -#include "sync/api/sync_change_processor.h" -#include "sync/api/sync_data.h" -#include "sync/protocol/extension_setting_specifics.pb.h" using content::BrowserThread; diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h index 19007941897..93e6349f0f3 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h @@ -9,8 +9,8 @@ #include <string> #include "base/macros.h" +#include "components/sync/api/sync_error.h" #include "extensions/browser/value_store/value_store_change.h" -#include "sync/api/sync_error.h" namespace syncer { class SyncChangeProcessor; 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 7bfce10e2c7..2bd06676574 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc @@ -11,7 +11,6 @@ #include "base/files/scoped_temp_dir.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" -#include "base/memory/linked_ptr.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -21,6 +20,10 @@ #include "chrome/browser/extensions/api/storage/sync_value_store_cache.h" #include "chrome/browser/extensions/api/storage/syncable_settings_storage.h" #include "chrome/test/base/testing_profile.h" +#include "components/sync/api/sync_change_processor.h" +#include "components/sync/api/sync_change_processor_wrapper_for_test.h" +#include "components/sync/api/sync_error_factory.h" +#include "components/sync/api/sync_error_factory_mock.h" #include "content/public/test/test_browser_thread.h" #include "extensions/browser/api/storage/settings_test_util.h" #include "extensions/browser/api/storage/storage_frontend.h" @@ -31,10 +34,6 @@ #include "extensions/browser/value_store/test_value_store_factory.h" #include "extensions/browser/value_store/testing_value_store.h" #include "extensions/common/manifest.h" -#include "sync/api/sync_change_processor.h" -#include "sync/api/sync_change_processor_wrapper_for_test.h" -#include "sync/api/sync_error_factory.h" -#include "sync/api/sync_error_factory_mock.h" #include "testing/gtest/include/gtest/gtest.h" using base::DictionaryValue; @@ -54,7 +53,7 @@ const ValueStore::WriteOptions DEFAULTS = ValueStore::DEFAULTS; // More saving typing. Maps extension IDs to a list of sync changes for that // extension. using SettingSyncDataMultimap = - std::map<std::string, linked_ptr<SettingSyncDataList>>; + std::map<std::string, std::unique_ptr<SettingSyncDataList>>; // Gets the pretty-printed JSON for a value. static std::string GetJson(const base::Value& value) { @@ -120,7 +119,7 @@ class MockSyncChangeProcessor : public syncer::SyncChangeProcessor { } for (syncer::SyncChangeList::const_iterator it = change_list.begin(); it != change_list.end(); ++it) { - changes_.push_back(new SettingSyncData(*it)); + changes_.push_back(base::MakeUnique<SettingSyncData>(*it)); } return syncer::SyncError(); } @@ -146,11 +145,9 @@ class MockSyncChangeProcessor : public syncer::SyncChangeProcessor { SettingSyncData* GetOnlyChange(const std::string& extension_id, const std::string& key) { std::vector<SettingSyncData*> matching_changes; - for (SettingSyncDataList::iterator it = changes_.begin(); - it != changes_.end(); ++it) { - if ((*it)->extension_id() == extension_id && (*it)->key() == key) { - matching_changes.push_back(*it); - } + for (const std::unique_ptr<SettingSyncData>& change : changes_) { + if (change->extension_id() == extension_id && change->key() == key) + matching_changes.push_back(change.get()); } if (matching_changes.empty()) { ADD_FAILURE() << "No matching changes for " << extension_id << "/" << @@ -171,12 +168,12 @@ class MockSyncChangeProcessor : public syncer::SyncChangeProcessor { std::unique_ptr<KeyedService> MockExtensionSystemFactoryFunction( content::BrowserContext* context) { - return base::WrapUnique(new MockExtensionSystem(context)); + return base::MakeUnique<MockExtensionSystem>(context); } std::unique_ptr<KeyedService> BuildEventRouter( content::BrowserContext* profile) { - return base::WrapUnique(new extensions::EventRouter(profile, nullptr)); + return base::MakeUnique<extensions::EventRouter>(profile, nullptr); } } // namespace @@ -193,7 +190,7 @@ class ExtensionSettingsSyncTest : public testing::Test { void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - profile_.reset(new TestingProfile(temp_dir_.path())); + profile_.reset(new TestingProfile(temp_dir_.GetPath())); storage_factory_->Reset(); frontend_ = StorageFrontend::CreateForTesting(storage_factory_, profile_.get()); @@ -240,12 +237,12 @@ class ExtensionSettingsSyncTest : public testing::Test { SettingSyncDataMultimap as_map; for (syncer::SyncDataList::iterator it = as_list.begin(); it != as_list.end(); ++it) { - SettingSyncData* sync_data = new SettingSyncData(*it); - linked_ptr<SettingSyncDataList>& list_for_extension = + std::unique_ptr<SettingSyncData> sync_data(new SettingSyncData(*it)); + std::unique_ptr<SettingSyncDataList>& list_for_extension = as_map[sync_data->extension_id()]; - if (!list_for_extension.get()) + if (!list_for_extension) list_for_extension.reset(new SettingSyncDataList()); - list_for_extension->push_back(sync_data); + list_for_extension->push_back(std::move(sync_data)); } return as_map; } @@ -288,7 +285,7 @@ TEST_F(ExtensionSettingsSyncTest, NoDataDoesNotInvokeSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); AddExtensionAndGetStorage("s2", type); EXPECT_EQ(0u, GetAllSyncData(model_type).size()); @@ -329,7 +326,7 @@ TEST_F(ExtensionSettingsSyncTest, InSyncDataDoesNotInvokeSync) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); // Already in sync, so no changes. EXPECT_EQ(0u, sync_processor_->changes().size()); @@ -366,7 +363,7 @@ TEST_F(ExtensionSettingsSyncTest, LocalDataWithNoSyncDataIsPushedToSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); // All settings should have been pushed to sync. EXPECT_EQ(2u, sync_processor_->changes().size()); @@ -404,7 +401,7 @@ TEST_F(ExtensionSettingsSyncTest, AnySyncDataOverwritesLocalData) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); expected1.Set("foo", value1.DeepCopy()); expected2.Set("bar", value2.DeepCopy()); @@ -446,7 +443,7 @@ TEST_F(ExtensionSettingsSyncTest, ProcessSyncChanges) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); expected2.Set("bar", value2.DeepCopy()); // Make sync add some settings. @@ -520,7 +517,7 @@ TEST_F(ExtensionSettingsSyncTest, PushToSync) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); // Add something locally. storage1->Set(DEFAULTS, "bar", value2); @@ -658,7 +655,7 @@ TEST_F(ExtensionSettingsSyncTest, ExtensionAndAppSettingsSyncSeparately) { ->MergeDataAndStartSyncing( syncer::EXTENSION_SETTINGS, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); GetSyncableService(syncer::EXTENSION_SETTINGS)-> StopSyncing(syncer::EXTENSION_SETTINGS); EXPECT_EQ(0u, sync_processor_->changes().size()); @@ -673,7 +670,7 @@ TEST_F(ExtensionSettingsSyncTest, ExtensionAndAppSettingsSyncSeparately) { GetSyncableService(syncer::APP_SETTINGS) ->MergeDataAndStartSyncing( syncer::APP_SETTINGS, sync_data, std::move(app_settings_delegate_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); GetSyncableService(syncer::APP_SETTINGS)-> StopSyncing(syncer::APP_SETTINGS); EXPECT_EQ(0u, sync_processor_->changes().size()); @@ -704,7 +701,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); } GetExisting("bad")->set_status_code(ValueStore::OK); @@ -820,7 +817,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); // Local settings will have been pushed to sync, since it's empty (in this // test; presumably it wouldn't be live, since we've been getting changes). @@ -888,7 +885,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingProcessChangesDisablesSync) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); } EXPECT_EQ(0u, sync_processor_->changes().size()); @@ -989,7 +986,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingGetAllSyncDataDoesntStopSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_processor_->GetOnlyChange("good", "foo")->change_type()); @@ -1028,7 +1025,7 @@ TEST_F(ExtensionSettingsSyncTest, FailureToReadChangesToPushDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); GetExisting("bad")->set_status_code(ValueStore::OK); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, @@ -1078,7 +1075,7 @@ TEST_F(ExtensionSettingsSyncTest, FailureToReadChangesToPushDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_processor_->GetOnlyChange("good", "foo")->change_type()); @@ -1119,7 +1116,7 @@ TEST_F(ExtensionSettingsSyncTest, FailureToPushLocalStateDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); sync_processor_->set_fail_all_requests(false); // Changes from good will be send to sync, changes from bad won't. @@ -1162,7 +1159,7 @@ TEST_F(ExtensionSettingsSyncTest, FailureToPushLocalStateDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_processor_->GetOnlyChange("good", "foo")->change_type()); @@ -1197,7 +1194,7 @@ TEST_F(ExtensionSettingsSyncTest, FailureToPushLocalChangeDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); // bad will fail to send changes. good->Set(DEFAULTS, "foo", fooValue); @@ -1249,7 +1246,7 @@ TEST_F(ExtensionSettingsSyncTest, FailureToPushLocalChangeDisablesSync) { ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_processor_->GetOnlyChange("good", "foo")->change_type()); @@ -1286,7 +1283,7 @@ TEST_F(ExtensionSettingsSyncTest, ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); // Large local change rejected and doesn't get sent out. ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); @@ -1329,7 +1326,7 @@ TEST_F(ExtensionSettingsSyncTest, Dots) { GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, sync_data_list, std::move(sync_processor_wrapper_), - base::WrapUnique(new syncer::SyncErrorFactoryMock())); + base::MakeUnique<syncer::SyncErrorFactoryMock>()); } // Test dots in keys that come from sync. @@ -1350,7 +1347,7 @@ TEST_F(ExtensionSettingsSyncTest, Dots) { storage->Set(DEFAULTS, "key.with.spot", *string_value); ASSERT_EQ(1u, sync_processor_->changes().size()); - SettingSyncData* sync_data = sync_processor_->changes()[0]; + SettingSyncData* sync_data = sync_processor_->changes()[0].get(); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_data->change_type()); EXPECT_EQ("ext", sync_data->extension_id()); EXPECT_EQ("key.with.spot", sync_data->key()); diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc index ccd9a446635..e29718c43f4 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc @@ -7,11 +7,11 @@ #include "base/json/json_writer.h" #include "base/values.h" #include "chrome/browser/extensions/api/storage/sync_value_store_cache.h" +#include "components/sync/protocol/app_setting_specifics.pb.h" +#include "components/sync/protocol/extension_setting_specifics.pb.h" +#include "components/sync/protocol/sync.pb.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/storage/storage_frontend.h" -#include "sync/protocol/app_setting_specifics.pb.h" -#include "sync/protocol/extension_setting_specifics.pb.h" -#include "sync/protocol/sync.pb.h" using content::BrowserThread; diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h index b4cbced0da2..ef702581162 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h @@ -5,8 +5,8 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_STORAGE_SETTINGS_SYNC_UTIL_H_ #define CHROME_BROWSER_EXTENSIONS_API_STORAGE_SETTINGS_SYNC_UTIL_H_ -#include "sync/api/sync_change.h" -#include "sync/api/sync_data.h" +#include "components/sync/api/sync_change.h" +#include "components/sync/api/sync_data.h" namespace base { class Value; diff --git a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc index ad544162011..21f9747ab56 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc +++ b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc @@ -11,8 +11,8 @@ #include "chrome/browser/extensions/api/storage/settings_sync_processor.h" #include "chrome/browser/extensions/api/storage/settings_sync_util.h" #include "chrome/browser/extensions/api/storage/syncable_settings_storage.h" +#include "components/sync/api/sync_error_factory.h" #include "content/public/browser/browser_thread.h" -#include "sync/api/sync_error_factory.h" using content::BrowserThread; @@ -31,7 +31,7 @@ void AddAllSyncData(const std::string& extension_id, } std::unique_ptr<base::DictionaryValue> EmptyDictionaryValue() { - return base::WrapUnique(new base::DictionaryValue()); + return base::MakeUnique<base::DictionaryValue>(); } ValueStoreFactory::ModelType ToFactoryModelType(syncer::ModelType sync_type) { diff --git a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h index a0f5ddbe843..9a854d9c14a 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h +++ b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h @@ -15,10 +15,10 @@ #include "base/macros.h" #include "base/memory/linked_ptr.h" #include "base/memory/ref_counted.h" +#include "components/sync/api/syncable_service.h" #include "extensions/browser/api/storage/settings_observer.h" #include "extensions/browser/api/storage/settings_storage_quota_enforcer.h" #include "extensions/browser/value_store/value_store_factory.h" -#include "sync/api/syncable_service.h" namespace syncer { class SyncErrorFactory; diff --git a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc index 13dbc4618a9..0a440ee84f6 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc +++ b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc @@ -11,6 +11,7 @@ #include "content/public/browser/browser_thread.h" #include "extensions/browser/value_store/value_store_factory.h" #include "extensions/common/api/storage.h" +#include "extensions/common/extension.h" using content::BrowserThread; diff --git a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h index ab0bbaad927..94f53b27a9b 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h +++ b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h @@ -10,9 +10,9 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "components/sync/api/syncable_service.h" #include "extensions/browser/api/storage/settings_observer.h" #include "extensions/browser/api/storage/value_store_cache.h" -#include "sync/api/syncable_service.h" namespace base { class FilePath; 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 1626ff30e59..102e2b343cc 100644 --- a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc +++ b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc @@ -6,13 +6,14 @@ #include <utility> +#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/api/storage/settings_sync_processor.h" #include "chrome/browser/extensions/api/storage/settings_sync_util.h" +#include "components/sync/api/sync_data.h" +#include "components/sync/protocol/extension_setting_specifics.pb.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/storage/settings_namespace.h" -#include "sync/api/sync_data.h" -#include "sync/protocol/extension_setting_specifics.pb.h" using content::BrowserThread; @@ -219,13 +220,13 @@ syncer::SyncError SyncableSettingsStorage::OverwriteLocalSettingsWithSync( // Sync and local values are the same, no changes to send. } else { // Sync value is different, update local setting with new value. - changes->push_back(new SettingSyncData( + changes->push_back(base::MakeUnique<SettingSyncData>( syncer::SyncChange::ACTION_UPDATE, extension_id_, it.key(), std::move(sync_value))); } } else { // Not synced, delete local setting. - changes->push_back(new SettingSyncData( + changes->push_back(base::MakeUnique<SettingSyncData>( syncer::SyncChange::ACTION_DELETE, extension_id_, it.key(), std::unique_ptr<base::Value>(new base::DictionaryValue()))); } @@ -238,7 +239,7 @@ syncer::SyncError SyncableSettingsStorage::OverwriteLocalSettingsWithSync( std::string key = base::DictionaryValue::Iterator(*sync_state).key(); std::unique_ptr<base::Value> value; CHECK(sync_state->RemoveWithoutPathExpansion(key, &value)); - changes->push_back(new SettingSyncData( + changes->push_back(base::MakeUnique<SettingSyncData>( syncer::SyncChange::ACTION_ADD, extension_id_, key, std::move(value))); } @@ -268,11 +269,10 @@ syncer::SyncError SyncableSettingsStorage::ProcessSyncChanges( std::vector<syncer::SyncError> errors; ValueStoreChangeList changes; - for (SettingSyncDataList::iterator it = sync_changes->begin(); - it != sync_changes->end(); ++it) { - DCHECK_EQ(extension_id_, (*it)->extension_id()); - const std::string& key = (*it)->key(); - std::unique_ptr<base::Value> change_value = (*it)->PassValue(); + for (const std::unique_ptr<SettingSyncData>& sync_change : *sync_changes) { + DCHECK_EQ(extension_id_, sync_change->extension_id()); + const std::string& key = sync_change->key(); + std::unique_ptr<base::Value> change_value = sync_change->PassValue(); std::unique_ptr<base::Value> current_value; { @@ -292,7 +292,7 @@ syncer::SyncError SyncableSettingsStorage::ProcessSyncChanges( syncer::SyncError error; - switch ((*it)->change_type()) { + switch (sync_change->change_type()) { case syncer::SyncChange::ACTION_ADD: if (!current_value.get()) { error = OnSyncAdd(key, std::move(change_value), &changes); diff --git a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h index 24456e15f6e..c903f23b4fa 100644 --- a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h +++ b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h @@ -17,10 +17,10 @@ #include "base/observer_list_threadsafe.h" #include "base/values.h" #include "chrome/browser/extensions/api/storage/setting_sync_data.h" +#include "components/sync/api/sync_change.h" +#include "components/sync/api/syncable_service.h" #include "extensions/browser/api/storage/settings_observer.h" #include "extensions/browser/value_store/value_store.h" -#include "sync/api/sync_change.h" -#include "sync/api/syncable_service.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc index 7b8b6b7c568..199a16323ef 100644 --- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc +++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc @@ -11,8 +11,10 @@ #include "base/values.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/common/extensions/api/streams_private.h" +#include "content/public/browser/render_frame_host.h" #include "content/public/browser/stream_handle.h" #include "content/public/browser/stream_info.h" +#include "content/public/browser/web_contents.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_function_registry.h" #include "extensions/browser/extension_registry.h" @@ -65,11 +67,11 @@ StreamsPrivateAPI::~StreamsPrivateAPI() { void StreamsPrivateAPI::ExecuteMimeTypeHandler( const std::string& extension_id, - content::WebContents* web_contents, std::unique_ptr<content::StreamInfo> stream, const std::string& view_id, int64_t expected_content_size, bool embedded, + int frame_tree_node_id, int render_process_id, int render_frame_id) { const Extension* extension = ExtensionRegistry::Get(browser_context_) @@ -78,6 +80,17 @@ void StreamsPrivateAPI::ExecuteMimeTypeHandler( if (!extension) return; + content::WebContents* web_contents = nullptr; + if (frame_tree_node_id != -1) { + web_contents = + content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); + } else { + web_contents = content::WebContents::FromRenderFrameHost( + content::RenderFrameHost::FromID(render_process_id, render_frame_id)); + } + if (!web_contents) + return; + MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension); // If the mime handler uses MimeHandlerViewGuest, the MimeHandlerViewGuest // will take ownership of the stream. Otherwise, store the stream handle in @@ -85,12 +98,12 @@ void StreamsPrivateAPI::ExecuteMimeTypeHandler( if (handler->HasPlugin()) { GURL handler_url(Extension::GetBaseURLFromExtensionId(extension_id).spec() + handler->handler_url()); - auto tab_id = ExtensionTabUtil::GetTabId(web_contents); + int tab_id = ExtensionTabUtil::GetTabId(web_contents); std::unique_ptr<StreamContainer> stream_container(new StreamContainer( std::move(stream), tab_id, embedded, handler_url, extension_id)); MimeHandlerStreamManager::Get(browser_context_) - ->AddStream(view_id, std::move(stream_container), render_process_id, - render_frame_id); + ->AddStream(view_id, std::move(stream_container), frame_tree_node_id, + render_process_id, render_frame_id); return; } // Create the event's arguments value. 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 d1c22433f99..e2e2ab84aa3 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 @@ -39,12 +39,17 @@ class StreamsPrivateAPI : public BrowserContextKeyedAPI, // should be |expected_content_size| bytes long. 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. void ExecuteMimeTypeHandler(const std::string& extension_id, - content::WebContents* web_contents, std::unique_ptr<content::StreamInfo> stream, const std::string& view_id, int64_t expected_content_size, bool embedded, + int frame_tree_node_id, int render_process_id, int render_frame_id); diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc index 69da0316c20..64cba600a48 100644 --- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc @@ -158,7 +158,7 @@ class StreamsPrivateApiTest : public ExtensionApiTest { // Setup default downloads directory to the scoped tmp directory created for // the test. browser()->profile()->GetPrefs()->SetFilePath( - prefs::kDownloadDefaultDirectory, downloads_dir_.path()); + prefs::kDownloadDefaultDirectory, downloads_dir_.GetPath()); // Ensure there are no prompts for download during the test. browser()->profile()->GetPrefs()->SetBoolean( prefs::kPromptForDownload, false); @@ -380,7 +380,7 @@ IN_PROC_BROWSER_TEST_F(StreamsPrivateApiTest, DirectDownload) { // The download's target file path. base::FilePath target_path = - downloads_dir_.path().Append(FILE_PATH_LITERAL("download_target.txt")); + downloads_dir_.GetPath().Append(FILE_PATH_LITERAL("download_target.txt")); // Set the downloads parameters. content::WebContents* web_contents = diff --git a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.cc b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.cc index 0fdc9a6b63c..c89dad722b3 100644 --- a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.cc +++ b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.cc @@ -275,8 +275,7 @@ void SyncFileSystemGetFileStatusesFunction::DidGetFileStatus( std::unique_ptr<base::ListValue> status_array(new base::ListValue()); for (URLToStatusMap::iterator it = file_sync_statuses_.begin(); it != file_sync_statuses_.end(); ++it) { - base::DictionaryValue* dict = new base::DictionaryValue(); - status_array->Append(dict); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); storage::FileSystemURL url = it->first; SyncStatusCode file_error = it->second.first; @@ -290,6 +289,8 @@ void SyncFileSystemGetFileStatusesFunction::DidGetFileStatus( if (file_error == sync_file_system::SYNC_STATUS_OK) continue; dict->SetString("error", ErrorToString(file_error)); + + status_array->Append(std::move(dict)); } SetResult(std::move(status_array)); diff --git a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc index 460a83055ed..5a059fd104c 100644 --- a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc @@ -102,7 +102,7 @@ class SyncFileSystemTest : public extensions::PlatformAppBrowserTest, remote_service_ = new drive_backend::SyncEngine( base::ThreadTaskRunnerHandle::Get(), // ui_task_runner MakeSequencedTaskRunner(), MakeSequencedTaskRunner(), - content::BrowserThread::GetBlockingPool(), base_dir_.path(), + content::BrowserThread::GetBlockingPool(), base_dir_.GetPath(), NULL, // task_logger NULL, // notification_manager extension_service, diff --git a/chromium/chrome/browser/extensions/api/system_private/system_private_api.cc b/chromium/chrome/browser/extensions/api/system_private/system_private_api.cc index ff98c4b1753..d128aa24734 100644 --- a/chromium/chrome/browser/extensions/api/system_private/system_private_api.cc +++ b/chromium/chrome/browser/extensions/api/system_private/system_private_api.cc @@ -4,6 +4,7 @@ #include "chrome/browser/extensions/api/system_private/system_private_api.h" +#include <memory> #include <utility> #include "base/macros.h" @@ -54,10 +55,10 @@ const char kUpdatingState[] = "Updating"; // Dispatches an extension event with |argument| void DispatchEvent(extensions::events::HistogramValue histogram_value, const std::string& event_name, - base::Value* argument) { + std::unique_ptr<base::Value> argument) { std::unique_ptr<base::ListValue> list_args(new base::ListValue()); if (argument) { - list_args->Append(argument); + list_args->Append(std::move(argument)); } g_browser_process->extension_event_router_forwarder() ->BroadcastEventToRenderers(histogram_value, event_name, @@ -70,18 +71,19 @@ namespace extensions { namespace system_private = api::system_private; -bool SystemPrivateGetIncognitoModeAvailabilityFunction::RunSync() { - PrefService* prefs = GetProfile()->GetPrefs(); +ExtensionFunction::ResponseAction +SystemPrivateGetIncognitoModeAvailabilityFunction::Run() { + PrefService* prefs = + Profile::FromBrowserContext(browser_context())->GetPrefs(); int value = prefs->GetInteger(prefs::kIncognitoModeAvailability); EXTENSION_FUNCTION_VALIDATE( value >= 0 && value < static_cast<int>(arraysize(kIncognitoModeAvailabilityStrings))); - SetResult(base::MakeUnique<base::StringValue>( - kIncognitoModeAvailabilityStrings[value])); - return true; + return RespondNow(OneArgument(base::MakeUnique<base::StringValue>( + kIncognitoModeAvailabilityStrings[value]))); } -bool SystemPrivateGetUpdateStatusFunction::RunSync() { +ExtensionFunction::ResponseAction SystemPrivateGetUpdateStatusFunction::Run() { std::string state; double download_progress = 0; #if defined(OS_CHROMEOS) @@ -135,43 +137,43 @@ bool SystemPrivateGetUpdateStatusFunction::RunSync() { state = kNotAvailableState; } #endif + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString(kStateKey, state); dict->SetDouble(kDownloadProgressKey, download_progress); - SetResult(std::move(dict)); - - return true; + return RespondNow(OneArgument(std::move(dict))); } -bool SystemPrivateGetApiKeyFunction::RunSync() { - SetResult(base::MakeUnique<base::StringValue>(google_apis::GetAPIKey())); - return true; +ExtensionFunction::ResponseAction SystemPrivateGetApiKeyFunction::Run() { + return RespondNow(OneArgument( + base::MakeUnique<base::StringValue>(google_apis::GetAPIKey()))); } void DispatchVolumeChangedEvent(double volume, bool is_volume_muted) { - base::DictionaryValue* dict = new base::DictionaryValue(); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetDouble(kVolumeKey, volume); dict->SetBoolean(kIsVolumeMutedKey, is_volume_muted); DispatchEvent(extensions::events::SYSTEM_PRIVATE_ON_VOLUME_CHANGED, - system_private::OnVolumeChanged::kEventName, dict); + system_private::OnVolumeChanged::kEventName, std::move(dict)); } void DispatchBrightnessChangedEvent(int brightness, bool user_initiated) { - base::DictionaryValue* dict = new base::DictionaryValue(); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger(kBrightnessKey, brightness); dict->SetBoolean(kUserInitiatedKey, user_initiated); DispatchEvent(extensions::events::SYSTEM_PRIVATE_ON_BRIGHTNESS_CHANGED, - system_private::OnBrightnessChanged::kEventName, dict); + system_private::OnBrightnessChanged::kEventName, + std::move(dict)); } void DispatchScreenUnlockedEvent() { DispatchEvent(extensions::events::SYSTEM_PRIVATE_ON_SCREEN_UNLOCKED, - system_private::OnScreenUnlocked::kEventName, NULL); + system_private::OnScreenUnlocked::kEventName, nullptr); } void DispatchWokeUpEvent() { DispatchEvent(extensions::events::SYSTEM_PRIVATE_ON_WOKE_UP, - system_private::OnWokeUp::kEventName, NULL); + system_private::OnWokeUp::kEventName, nullptr); } } // namespace extensions 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 30d23069125..27e7265233a 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 @@ -8,12 +8,12 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_SYSTEM_PRIVATE_SYSTEM_PRIVATE_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_SYSTEM_PRIVATE_SYSTEM_PRIVATE_API_H_ -#include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" namespace extensions { class SystemPrivateGetIncognitoModeAvailabilityFunction - : public ChromeSyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getIncognitoModeAvailability", SYSTEMPRIVATE_GETINCOGNITOMODEAVAILABILITY) @@ -22,12 +22,11 @@ class SystemPrivateGetIncognitoModeAvailabilityFunction ~SystemPrivateGetIncognitoModeAvailabilityFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // API function which returns the status of system update. -class SystemPrivateGetUpdateStatusFunction - : public ChromeSyncExtensionFunction { +class SystemPrivateGetUpdateStatusFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getUpdateStatus", SYSTEMPRIVATE_GETUPDATESTATUS) @@ -36,11 +35,11 @@ class SystemPrivateGetUpdateStatusFunction ~SystemPrivateGetUpdateStatusFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // API function which returns the Google API key. -class SystemPrivateGetApiKeyFunction : public SyncExtensionFunction { +class SystemPrivateGetApiKeyFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getApiKey", SYSTEMPRIVATE_GETAPIKEY) @@ -48,7 +47,7 @@ class SystemPrivateGetApiKeyFunction : public SyncExtensionFunction { ~SystemPrivateGetApiKeyFunction() override {} // ExtensionFunction: - bool RunSync() override; + ResponseAction Run() override; }; // Dispatches systemPrivate.onBrightnessChanged event for extensions. diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc index ddc31cf1854..f50fdf9c3cb 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc @@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/extensions/api/tab_capture/tab_capture_registry.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/web_contents_sizer.h" @@ -57,15 +58,24 @@ OffscreenTab* OffscreenTabsOwner::OpenNewTab( if (tabs_.size() >= kMaxOffscreenTabsPerExtension) return nullptr; // Maximum number of offscreen tabs reached. - tabs_.push_back(new OffscreenTab(this)); + // OffscreenTab cannot be created with MakeUnique<OffscreenTab> since the + // constructor is protected. So create it separately, and then move it to + // |tabs_| below. + std::unique_ptr<OffscreenTab> offscreen_tab(new OffscreenTab(this)); + tabs_.push_back(std::move(offscreen_tab)); tabs_.back()->Start(start_url, initial_size, optional_presentation_id); - return tabs_.back(); + return tabs_.back().get(); } void OffscreenTabsOwner::DestroyTab(OffscreenTab* tab) { - const auto it = std::find(tabs_.begin(), tabs_.end(), tab); - if (it != tabs_.end()) - tabs_.erase(it); + for (std::vector<std::unique_ptr<OffscreenTab>>::iterator iter = + tabs_.begin(); + iter != tabs_.end(); ++iter) { + if (iter->get() == tab) { + tabs_.erase(iter); + break; + } + } } OffscreenTab::OffscreenTab(OffscreenTabsOwner* owner) @@ -98,7 +108,8 @@ void OffscreenTab::Start(const GURL& start_url, // Set initial size, if specified. if (!initial_size.IsEmpty()) - ResizeWebContents(offscreen_tab_web_contents_.get(), initial_size); + ResizeWebContents(offscreen_tab_web_contents_.get(), + gfx::Rect(initial_size)); // Mute audio output. When tab capture starts, the audio will be // automatically unmuted, but will be captured into the MediaStream. @@ -227,7 +238,7 @@ void OffscreenTab::EnterFullscreenModeForTab(WebContents* contents, contents->GetRenderWidgetHostView()->GetViewBounds().size(); if (contents->GetCapturerCount() >= 0 && !contents->GetPreferredSize().IsEmpty()) { - ResizeWebContents(contents, contents->GetPreferredSize()); + ResizeWebContents(contents, gfx::Rect(contents->GetPreferredSize())); } } @@ -237,7 +248,7 @@ void OffscreenTab::ExitFullscreenModeForTab(WebContents* contents) { if (!in_fullscreen_mode()) return; - ResizeWebContents(contents, non_fullscreen_size_); + ResizeWebContents(contents, gfx::Rect(non_fullscreen_size_)); non_fullscreen_size_ = gfx::Size(); } diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h index 712c1172bc1..e6393192a06 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h @@ -11,7 +11,6 @@ #include <vector> #include "base/macros.h" -#include "base/memory/scoped_vector.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "content/public/browser/web_contents_delegate.h" @@ -75,7 +74,7 @@ class OffscreenTabsOwner explicit OffscreenTabsOwner(content::WebContents* extension_web_contents); content::WebContents* const extension_web_contents_; - ScopedVector<OffscreenTab> tabs_; + std::vector<std::unique_ptr<OffscreenTab>> tabs_; DISALLOW_COPY_AND_ASSIGN(OffscreenTabsOwner); }; 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 9d3b30c4830..1afbe59eb3e 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 @@ -274,7 +274,7 @@ bool TabCaptureGetCapturedTabsFunction::RunSync() { return true; } -bool TabCaptureCaptureOffscreenTabFunction::RunSync() { +ExtensionFunction::ResponseAction TabCaptureCaptureOffscreenTabFunction::Run() { std::unique_ptr<TabCapture::CaptureOffscreenTab::Params> params = TabCapture::CaptureOffscreenTab::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params); @@ -291,21 +291,15 @@ bool TabCaptureCaptureOffscreenTabFunction::RunSync() { arraysize(kChromecastExtensionIds)) || SimpleFeature::IsIdInArray(extension()->id(), kMediaRouterExtensionIds, arraysize(kMediaRouterExtensionIds)); - if (!is_whitelisted_extension) { - error_ = kNotWhitelistedForOffscreenTabApi; - return false; - } + if (!is_whitelisted_extension) + return RespondNow(Error(kNotWhitelistedForOffscreenTabApi)); const GURL start_url(params->start_url); - if (!IsAcceptableOffscreenTabUrl(start_url)) { - SetError(kInvalidStartUrl); - return false; - } + if (!IsAcceptableOffscreenTabUrl(start_url)) + return RespondNow(Error(kInvalidStartUrl)); - if (!OptionsSpecifyAudioOrVideo(params->options)) { - SetError(kNoAudioOrVideo); - return false; - } + if (!OptionsSpecifyAudioOrVideo(params->options)) + return RespondNow(Error(kNoAudioOrVideo)); content::WebContents* const extension_web_contents = GetSenderWebContents(); EXTENSION_FUNCTION_VALIDATE(extension_web_contents); @@ -315,17 +309,14 @@ bool TabCaptureCaptureOffscreenTabFunction::RunSync() { DetermineInitialSize(params->options), (is_whitelisted_extension && params->options.presentation_id) ? *params->options.presentation_id : std::string()); - if (!offscreen_tab) { - SetError(kTooManyOffscreenTabs); - return false; - } + if (!offscreen_tab) + return RespondNow(Error(kTooManyOffscreenTabs)); if (!TabCaptureRegistry::Get(browser_context())->AddRequest( offscreen_tab->web_contents(), extension()->id(), true)) { // TODO(miu): Allow multiple consumers of single tab capture. // http://crbug.com/535336 - SetError(kCapturingSameOffscreenTab); - return false; + return RespondNow(Error(kCapturingSameOffscreenTab)); } FilterDeprecatedGoogConstraints(¶ms->options); AddMediaStreamSourceConstraints(offscreen_tab->web_contents(), @@ -335,10 +326,7 @@ bool TabCaptureCaptureOffscreenTabFunction::RunSync() { // the custom JS bindings in the extension's render process to complete the // request. See the comment at end of TabCaptureCaptureFunction::RunSync() // for more details. - std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); - result->MergeDictionary(params->options.ToValue().get()); - SetResult(std::move(result)); - return true; + return RespondNow(OneArgument(params->options.ToValue())); } // static 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 884c7111577..8e9675f1c61 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 @@ -45,7 +45,7 @@ class TabCaptureGetCapturedTabsFunction : public ChromeSyncExtensionFunction { bool RunSync() final; }; -class TabCaptureCaptureOffscreenTabFunction : public SyncExtensionFunction { +class TabCaptureCaptureOffscreenTabFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.captureOffscreenTab", TABCAPTURE_CAPTUREOFFSCREENTAB) @@ -59,7 +59,7 @@ class TabCaptureCaptureOffscreenTabFunction : public SyncExtensionFunction { ~TabCaptureCaptureOffscreenTabFunction() final {} // ExtensionFunction: - bool RunSync() final; + ResponseAction Run() final; }; } // namespace extensions 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 fb7e8e6487c..ffd167bf2e2 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 @@ -56,7 +56,7 @@ class TabCaptureApiTest : public ExtensionApiTest { content::SimulateMouseClick( browser()->tab_strip_model()->GetActiveWebContents(), 0, - blink::WebMouseEvent::ButtonLeft); + blink::WebMouseEvent::Button::Left); } }; @@ -240,7 +240,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) { EXPECT_TRUE(listener.WaitUntilSatisfied()); content::OpenURLParams params(GURL("about:blank"), content::Referrer(), - NEW_FOREGROUND_TAB, + WindowOpenDisposition::NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false); content::WebContents* web_contents = browser()->OpenURL(params); @@ -276,7 +276,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) { // Open a new tab and make sure capture is denied. EXPECT_TRUE(before_open_tab.WaitUntilSatisfied()); content::OpenURLParams params(GURL("http://google.com"), content::Referrer(), - NEW_FOREGROUND_TAB, + WindowOpenDisposition::NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false); content::WebContents* web_contents = browser()->OpenURL(params); before_open_tab.Reply(""); @@ -356,7 +356,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GrantForChromePages) { // Open a tab on a chrome:// page and make sure we can capture. content::OpenURLParams params(GURL("chrome://version"), content::Referrer(), - NEW_FOREGROUND_TAB, + WindowOpenDisposition::NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false); content::WebContents* web_contents = browser()->OpenURL(params); const Extension* extension = ExtensionRegistry::Get( diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc index 42909a29d67..c415de6e71d 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc @@ -8,6 +8,7 @@ #include "base/lazy_instance.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/values.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -24,8 +25,8 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" -#include "ui/aura/window.h" -#include "ui/aura/window_observer.h" +#include "ui/aura/window.h" // nogncheck +#include "ui/aura/window_observer.h" // nogncheck #endif using content::BrowserThread; @@ -272,7 +273,7 @@ void TabCaptureRegistry::GetCapturedTabs( DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(list_of_capture_info); list_of_capture_info->Clear(); - for (const LiveRequest* request : requests_) { + for (const std::unique_ptr<LiveRequest>& request : requests_) { if (request->is_anonymous() || !request->is_verified() || request->extension_id() != extension_id) continue; @@ -287,7 +288,8 @@ void TabCaptureRegistry::OnExtensionUnloaded( const Extension* extension, UnloadedExtensionInfo::Reason reason) { // Cleanup all the requested media streams for this extension. - for (ScopedVector<LiveRequest>::iterator it = requests_.begin(); + for (std::vector<std::unique_ptr<LiveRequest>>::iterator it = + requests_.begin(); it != requests_.end();) { if ((*it)->extension_id() == extension->id()) { it = requests_.erase(it); @@ -313,8 +315,8 @@ bool TabCaptureRegistry::AddRequest(content::WebContents* target_contents, } } - requests_.push_back( - new LiveRequest(target_contents, extension_id, is_anonymous, this)); + requests_.push_back(base::MakeUnique<LiveRequest>( + target_contents, extension_id, is_anonymous, this)); return true; } @@ -436,31 +438,31 @@ void TabCaptureRegistry::DispatchStatusChangeEvent( TabCaptureRegistry::LiveRequest* TabCaptureRegistry::FindRequest( const content::WebContents* target_contents) const { - for (ScopedVector<LiveRequest>::const_iterator it = requests_.begin(); - it != requests_.end(); ++it) { - if ((*it)->web_contents() == target_contents) - return *it; + for (const auto& request : requests_) { + if (request->web_contents() == target_contents) + return request.get(); } - return NULL; + return nullptr; } TabCaptureRegistry::LiveRequest* TabCaptureRegistry::FindRequest( int original_target_render_process_id, int original_target_render_frame_id) const { - for (ScopedVector<LiveRequest>::const_iterator it = requests_.begin(); - it != requests_.end(); ++it) { - if ((*it)->WasOriginallyTargettingRenderFrameID( + for (const std::unique_ptr<LiveRequest>& request : requests_) { + if (request->WasOriginallyTargettingRenderFrameID( original_target_render_process_id, - original_target_render_frame_id)) - return *it; + original_target_render_frame_id)) { + return request.get(); + } } - return NULL; + return nullptr; } void TabCaptureRegistry::KillRequest(LiveRequest* request) { - for (ScopedVector<LiveRequest>::iterator it = requests_.begin(); + for (std::vector<std::unique_ptr<LiveRequest>>::iterator it = + requests_.begin(); it != requests_.end(); ++it) { - if ((*it) == request) { + if (it->get() == request) { requests_.erase(it); return; } diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h index 5698fed0ec2..f0eb9057df5 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h @@ -10,9 +10,8 @@ #include <vector> #include "base/macros.h" -#include "base/memory/scoped_vector.h" #include "base/scoped_observer.h" -#include "chrome/browser/media/media_capture_devices_dispatcher.h" +#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" #include "chrome/common/extensions/api/tab_capture.h" #include "content/public/browser/media_request_state.h" #include "extensions/browser/browser_context_keyed_api_factory.h" @@ -110,7 +109,7 @@ class TabCaptureRegistry : public BrowserContextKeyedAPI, void KillRequest(LiveRequest* request); content::BrowserContext* const browser_context_; - ScopedVector<LiveRequest> requests_; + std::vector<std::unique_ptr<LiveRequest>> requests_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observer_; diff --git a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc index 38e717924b0..6831e346d51 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc +++ b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc @@ -51,23 +51,18 @@ AppWindowController::CreateWindowValueWithTabs( const Extension* extension) const { std::unique_ptr<base::DictionaryValue> result = CreateWindowValue(); - base::DictionaryValue* tab_value = CreateTabValue(extension, 0); + std::unique_ptr<base::DictionaryValue> tab_value = + CreateTabObject(extension, 0)->ToValue(); if (!tab_value) return result; base::ListValue* tab_list = new base::ListValue(); - tab_list->Append(tab_value); + tab_list->Append(std::move(tab_value)); result->Set(tabs_constants::kTabsKey, tab_list); return result; } -base::DictionaryValue* AppWindowController::CreateTabValue( - const Extension* extension, - int tab_index) const { - return CreateTabObject(extension, tab_index)->ToValue().release(); -} - std::unique_ptr<api::tabs::Tab> AppWindowController::CreateTabObject( const extensions::Extension* extension, int tab_index) const { diff --git a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h index d7a868cd602..7f829741012 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h +++ b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h @@ -31,8 +31,6 @@ class AppWindowController : public WindowController { std::string GetWindowTypeText() const override; std::unique_ptr<base::DictionaryValue> CreateWindowValueWithTabs( const Extension* extension) const override; - base::DictionaryValue* CreateTabValue(const Extension* extension, - int tab_index) const override; std::unique_ptr<api::tabs::Tab> CreateTabObject( const extensions::Extension* extension, int tab_index) const override; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc index c6dc4863414..28d77b098a3 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -26,6 +26,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/api/tabs/windows_util.h" @@ -34,6 +35,7 @@ #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/extensions/window_controller.h" #include "chrome/browser/extensions/window_controller_list.h" +#include "chrome/browser/memory/tab_manager.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_tab_helper.h" @@ -46,7 +48,6 @@ #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/panels/panel_manager.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/tabs/tab_utils.h" #include "chrome/browser/ui/window_sizer/window_sizer.h" @@ -95,9 +96,8 @@ #include "ui/base/ui_base_types.h" #if defined(USE_ASH) -#include "ash/common/ash_switches.h" -#include "chrome/browser/extensions/api/tabs/ash_panel_contents.h" -#include "extensions/browser/app_window/app_window_registry.h" +#include "chrome/browser/extensions/api/tabs/ash_panel_contents.h" // nogncheck +#include "extensions/browser/app_window/app_window_registry.h" // nogncheck #endif using content::BrowserThread; @@ -133,7 +133,7 @@ class ApiParameterExtractor { WindowController::TypeFilter type_filters() { if (params_->get_info.get() && params_->get_info->window_types.get()) return WindowController::GetFilterFromWindowTypes( - *params_->get_info->window_types.get()); + *params_->get_info->window_types); return WindowController::kNoWindowFilter; } @@ -141,50 +141,39 @@ class ApiParameterExtractor { T* params_; }; -bool GetBrowserFromWindowID(ChromeUIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(const ChromeExtensionFunctionDetails& details, int window_id, - Browser** browser) { - std::string error; - Browser* result; - result = - ExtensionTabUtil::GetBrowserFromWindowID(function, window_id, &error); - if (!result) { - function->SetError(error); + Browser** browser, + std::string* error) { + Browser* result = nullptr; + result = ExtensionTabUtil::GetBrowserFromWindowID(details, window_id, error); + if (!result) return false; - } *browser = result; return true; } -bool GetBrowserFromWindowID(ChromeExtensionFunctionDetails* details, +bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, int window_id, - Browser** browser) { - std::string error; - Browser* result; - result = - ExtensionTabUtil::GetBrowserFromWindowID(*details, window_id, &error); - if (!result) { - details->function()->SetError(error); - return false; - } - - *browser = result; - return true; + Browser** browser, + std::string* error) { + return GetBrowserFromWindowID(ChromeExtensionFunctionDetails(function), + window_id, browser, error); } // |error_message| can optionally be passed in and will be set with an // appropriate message if the tab cannot be found by id. bool GetTabById(int tab_id, - Profile* profile, + content::BrowserContext* context, bool include_incognito, Browser** browser, TabStripModel** tab_strip, content::WebContents** contents, int* tab_index, std::string* error_message) { - if (ExtensionTabUtil::GetTabById(tab_id, profile, include_incognito, - browser, tab_strip, contents, tab_index)) { + if (ExtensionTabUtil::GetTabById(tab_id, context, include_incognito, browser, + tab_strip, contents, tab_index)) { return true; } @@ -207,7 +196,7 @@ template <typename T> void AssignOptionalValue(const std::unique_ptr<T>& source, std::unique_ptr<T>& destination) { if (source.get()) { - destination.reset(new T(*source.get())); + destination.reset(new T(*source)); } } @@ -286,45 +275,49 @@ void ZoomModeToZoomSettings(ZoomController::ZoomMode zoom_mode, // Windows --------------------------------------------------------------------- -bool WindowsGetFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsGetFunction::Run() { std::unique_ptr<windows::Get::Params> params( windows::Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::Get::Params> extractor(params.get()); - WindowController* controller; - if (!windows_util::GetWindowFromWindowID( - this, params->window_id, extractor.type_filters(), &controller)) { - return false; + WindowController* controller = nullptr; + std::string error; + if (!windows_util::GetWindowFromWindowID(this, params->window_id, + extractor.type_filters(), + &controller, &error)) { + return RespondNow(Error(error)); } - if (extractor.populate_tabs()) - SetResult(controller->CreateWindowValueWithTabs(extension())); - else - SetResult(controller->CreateWindowValue()); - return true; + std::unique_ptr<base::DictionaryValue> windows = + extractor.populate_tabs() + ? controller->CreateWindowValueWithTabs(extension()) + : controller->CreateWindowValue(); + return RespondNow(OneArgument(std::move(windows))); } -bool WindowsGetCurrentFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsGetCurrentFunction::Run() { std::unique_ptr<windows::GetCurrent::Params> params( windows::GetCurrent::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::GetCurrent::Params> extractor(params.get()); - WindowController* controller; + WindowController* controller = nullptr; + std::string error; if (!windows_util::GetWindowFromWindowID( this, extension_misc::kCurrentWindowId, extractor.type_filters(), - &controller)) { - return false; + &controller, &error)) { + return RespondNow(Error(error)); } - if (extractor.populate_tabs()) - SetResult(controller->CreateWindowValueWithTabs(extension())); - else - SetResult(controller->CreateWindowValue()); - return true; + + std::unique_ptr<base::DictionaryValue> windows = + extractor.populate_tabs() + ? controller->CreateWindowValueWithTabs(extension()) + : controller->CreateWindowValue(); + return RespondNow(OneArgument(std::move(windows))); } -bool WindowsGetLastFocusedFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsGetLastFocusedFunction::Run() { std::unique_ptr<windows::GetLastFocused::Params> params( windows::GetLastFocused::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -334,7 +327,7 @@ bool WindowsGetLastFocusedFunction::RunSync() { // The WindowControllerList should contain a list of application, // browser and devtools windows. WindowController* controller = nullptr; - for (auto iter : WindowControllerList::GetInstance()->windows()) { + for (auto* iter : WindowControllerList::GetInstance()->windows()) { if (windows_util::CanOperateOnWindow(this, iter, extractor.type_filters())) { controller = iter; @@ -342,18 +335,17 @@ bool WindowsGetLastFocusedFunction::RunSync() { break; // Use focused window. } } - if (!controller) { - error_ = keys::kNoLastFocusedWindowError; - return false; - } - if (extractor.populate_tabs()) - SetResult(controller->CreateWindowValueWithTabs(extension())); - else - SetResult(controller->CreateWindowValue()); - return true; + if (!controller) + return RespondNow(Error(keys::kNoLastFocusedWindowError)); + + std::unique_ptr<base::DictionaryValue> windows = + extractor.populate_tabs() + ? controller->CreateWindowValueWithTabs(extension()) + : controller->CreateWindowValue(); + return RespondNow(OneArgument(std::move(windows))); } -bool WindowsGetAllFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsGetAllFunction::Run() { std::unique_ptr<windows::GetAll::Params> params( windows::GetAll::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -373,27 +365,26 @@ bool WindowsGetAllFunction::RunSync() { else window_list->Append((*iter)->CreateWindowValue()); } - SetResult(std::move(window_list)); - return true; + + return RespondNow(OneArgument(std::move(window_list))); } bool WindowsCreateFunction::ShouldOpenIncognitoWindow( const windows::Create::Params::CreateData* create_data, - std::vector<GURL>* urls, bool* is_error) { - *is_error = false; + std::vector<GURL>* urls, + std::string* error) { + Profile* profile = Profile::FromBrowserContext(browser_context()); const IncognitoModePrefs::Availability incognito_availability = - IncognitoModePrefs::GetAvailability(GetProfile()->GetPrefs()); + IncognitoModePrefs::GetAvailability(profile->GetPrefs()); bool incognito = false; if (create_data && create_data->incognito) { incognito = *create_data->incognito; if (incognito && incognito_availability == IncognitoModePrefs::DISABLED) { - error_ = keys::kIncognitoModeIsDisabled; - *is_error = true; + *error = keys::kIncognitoModeIsDisabled; return false; } if (!incognito && incognito_availability == IncognitoModePrefs::FORCED) { - error_ = keys::kIncognitoModeIsForced; - *is_error = true; + *error = keys::kIncognitoModeIsForced; return false; } } else if (incognito_availability == IncognitoModePrefs::FORCED) { @@ -404,10 +395,10 @@ bool WindowsCreateFunction::ShouldOpenIncognitoWindow( // Remove all URLs that are not allowed in an incognito session. Note that a // ChromeOS guest session is not considered incognito in this case. - if (incognito && !GetProfile()->IsGuestSession()) { + if (incognito && !profile->IsGuestSession()) { std::string first_url_erased; for (size_t i = 0; i < urls->size();) { - if (chrome::IsURLAllowedInIncognito((*urls)[i], GetProfile())) { + if (chrome::IsURLAllowedInIncognito((*urls)[i], profile)) { i++; } else { if (first_url_erased.empty()) @@ -416,16 +407,15 @@ bool WindowsCreateFunction::ShouldOpenIncognitoWindow( } } if (urls->empty() && !first_url_erased.empty()) { - error_ = ErrorUtils::FormatErrorMessage( + *error = ErrorUtils::FormatErrorMessage( keys::kURLsNotAllowedInIncognitoError, first_url_erased); - *is_error = true; return false; } } return incognito; } -bool WindowsCreateFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { std::unique_ptr<windows::Create::Params> params( windows::Create::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); @@ -448,70 +438,57 @@ bool WindowsCreateFunction::RunSync() { for (std::vector<std::string>::iterator i = url_strings.begin(); i != url_strings.end(); ++i) { GURL url = ExtensionTabUtil::ResolvePossiblyRelativeURL(*i, extension()); - if (!url.is_valid()) { - error_ = ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError, *i); - return false; - } + if (!url.is_valid()) + return RespondNow(Error(keys::kInvalidUrlError, *i)); // Don't let the extension crash the browser or renderers. - if (ExtensionTabUtil::IsKillURL(url)) { - error_ = keys::kNoCrashBrowserError; - return false; - } + if (ExtensionTabUtil::IsKillURL(url)) + return RespondNow(Error(keys::kNoCrashBrowserError)); urls.push_back(url); } } // Decide whether we are opening a normal window or an incognito window. - bool is_error = true; + std::string error; bool open_incognito_window = - ShouldOpenIncognitoWindow(create_data, &urls, &is_error); - if (is_error) - return false; // error_ member is set inside of ShouldOpenIncognitoWindow. + ShouldOpenIncognitoWindow(create_data, &urls, &error); + if (!error.empty()) + return RespondNow(Error(error)); - Profile* window_profile = GetProfile(); - if (open_incognito_window) - window_profile = window_profile->GetOffTheRecordProfile(); + Profile* calling_profile = Profile::FromBrowserContext(browser_context()); + Profile* window_profile = open_incognito_window + ? calling_profile->GetOffTheRecordProfile() + : calling_profile; // Look for optional tab id. if (create_data && create_data->tab_id) { // Find the tab. |source_tab_strip| and |tab_index| will later be used to // move the tab into the created window. Browser* source_browser = nullptr; - if (!GetTabById(*create_data->tab_id, - GetProfile(), - include_incognito(), - &source_browser, - &source_tab_strip, - nullptr, - &tab_index, - &error_)) - return false; - - if (!source_browser->window()->IsTabStripEditable()) { - error_ = keys::kTabStripNotEditableError; - return false; + if (!GetTabById(*create_data->tab_id, calling_profile, include_incognito(), + &source_browser, &source_tab_strip, nullptr, &tab_index, + &error)) { + return RespondNow(Error(error)); } - if (source_browser->profile() != window_profile) { - error_ = keys::kCanOnlyMoveTabsWithinSameProfileError; - return false; - } - } + if (!source_browser->window()->IsTabStripEditable()) + return RespondNow(Error(keys::kTabStripNotEditableError)); - if (!IsValidStateForWindowsCreateFunction(create_data)) { - error_ = keys::kInvalidWindowStateError; - return false; + if (source_browser->profile() != window_profile) + return RespondNow(Error(keys::kCanOnlyMoveTabsWithinSameProfileError)); } + if (!IsValidStateForWindowsCreateFunction(create_data)) + return RespondNow(Error(keys::kInvalidWindowStateError)); + Browser::Type window_type = Browser::TYPE_TABBED; - bool create_panel = false; - // panel_create_mode only applies if create_panel = true - PanelManager::CreateMode panel_create_mode = PanelManager::CREATE_AS_DOCKED; +#if defined(USE_ASH) + bool create_ash_panel = false; + bool saw_focus_key = false; +#endif // defined(USE_ASH) gfx::Rect window_bounds; bool focused = true; - bool saw_focus_key = false; std::string extension_id; if (create_data) { @@ -522,35 +499,39 @@ bool WindowsCreateFunction::RunSync() { window_type = Browser::TYPE_POPUP; extension_id = extension()->id(); break; + case windows::CREATE_TYPE_PANEL: case windows::CREATE_TYPE_DETACHED_PANEL: { extension_id = extension()->id(); - bool use_panels = PanelManager::ShouldUsePanels(extension_id); - if (use_panels) { - create_panel = true; -#if !defined(USE_ASH) - // Non-ash supports both docked and detached panel types. - if (create_data->type == windows::CREATE_TYPE_DETACHED_PANEL) { - panel_create_mode = PanelManager::CREATE_AS_DETACHED; +#if defined(USE_ASH) + // Only ChromeOS' version of chrome.windows.create would create a panel + // window. It is whitelisted to Hangouts extension for limited time until + // it transitioned to other types of windows. + for (const char* id : extension_misc::kHangoutsExtensionIds) { + if (extension_id == id) { + create_ash_panel = true; + break; } -#endif // USE_ASH - } else { - window_type = Browser::TYPE_POPUP; } +#endif // defined(USE_ASH) + // Everything else gets POPUP instead of PANEL. + // TODO(dimich): Eventually, remove the 'panel' values form valid + // window.create parameters. However, this is a more breaking change, so + // for now simply treat it as a POPUP. + window_type = Browser::TYPE_POPUP; break; } + case windows::CREATE_TYPE_NONE: case windows::CREATE_TYPE_NORMAL: break; default: - error_ = keys::kInvalidWindowTypeError; - return false; + return RespondNow(Error(keys::kInvalidWindowTypeError)); } // Initialize default window bounds according to window type. if (window_type == Browser::TYPE_TABBED || - window_type == Browser::TYPE_POPUP || - create_panel) { + window_type == Browser::TYPE_POPUP) { // Try to position the new browser relative to its originating // browser window. The call offsets the bounds by kWindowTilePixels // (defined in WindowSizer to be 10). @@ -559,16 +540,10 @@ bool WindowsCreateFunction::RunSync() { // GetBrowserWindowBounds will default to saved "default" values for // the app. ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT; - WindowSizer::GetBrowserWindowBoundsAndShowState(std::string(), - gfx::Rect(), - GetCurrentBrowser(), - &window_bounds, - &show_state); - } - - if (create_panel && PanelManager::CREATE_AS_DETACHED == panel_create_mode) { - window_bounds.set_origin( - PanelManager::GetInstance()->GetDefaultDetachedPanelOrigin()); + WindowSizer::GetBrowserWindowBoundsAndShowState( + std::string(), gfx::Rect(), + ChromeExtensionFunctionDetails(this).GetCurrentBrowser(), + &window_bounds, &show_state); } // Any part of the bounds can optionally be set by the caller. @@ -586,15 +561,17 @@ bool WindowsCreateFunction::RunSync() { if (create_data->focused) { focused = *create_data->focused; +#if defined(USE_ASH) saw_focus_key = true; +#endif } } - if (create_panel) { +#if defined(USE_ASH) + if (create_ash_panel) { if (urls.empty()) urls.push_back(GURL(chrome::kChromeUINewTabURL)); -#if defined(USE_ASH) AppWindow::CreateParams create_params; create_params.window_type = AppWindow::WINDOW_TYPE_V1_PANEL; create_params.window_key = extension_id; @@ -609,34 +586,13 @@ bool WindowsCreateFunction::RunSync() { WindowControllerList::GetInstance()->FindWindowById( app_window->session_id().id()); if (!window_controller) - return false; - SetResult(window_controller->CreateWindowValueWithTabs(extension())); - return true; -#else - std::string title = - web_app::GenerateApplicationNameFromExtensionId(extension_id); - content::SiteInstance* source_site_instance = - render_frame_host()->GetSiteInstance(); - // Note: Panels ignore all but the first url provided. - Panel* panel = PanelManager::GetInstance()->CreatePanel( - title, window_profile, urls[0], source_site_instance, window_bounds, - panel_create_mode); - - // Unlike other window types, Panels do not take focus by default. - if (!saw_focus_key || !focused) - panel->ShowInactive(); - else - panel->Show(); - - SetResult(panel->extension_window_controller()->CreateWindowValueWithTabs( - extension())); - return true; -#endif + return RespondNow(Error(kUnknownErrorDoNotUse)); + return RespondNow( + OneArgument(window_controller->CreateWindowValueWithTabs(extension()))); } +#endif // defined(USE_ASH) // Create a new BrowserWindow. - if (create_panel) - window_type = Browser::TYPE_POPUP; Browser::CreateParams create_params(window_type, window_profile); if (extension_id.empty()) { create_params.initial_bounds = window_bounds; @@ -656,14 +612,10 @@ bool WindowsCreateFunction::RunSync() { for (const GURL& url : urls) { chrome::NavigateParams navigate_params(new_window, url, ui::PAGE_TRANSITION_LINK); - navigate_params.disposition = NEW_FOREGROUND_TAB; + navigate_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; navigate_params.source_site_instance = render_frame_host()->GetSiteInstance(); chrome::Navigate(&navigate_params); - if (create_panel) { - TabHelper::FromWebContents(navigate_params.target_contents) - ->SetExtensionAppIconById(extension_id); - } } WebContents* contents = NULL; @@ -686,10 +638,6 @@ bool WindowsCreateFunction::RunSync() { } chrome::SelectNumberedTab(new_window, 0); - // Unlike other window types, Panels do not take focus by default. - if (!saw_focus_key && create_panel) - focused = false; - if (focused) new_window->window()->Show(); else @@ -697,28 +645,30 @@ bool WindowsCreateFunction::RunSync() { WindowController* controller = new_window->extension_window_controller(); + std::unique_ptr<base::Value> result; if (new_window->profile()->IsOffTheRecord() && - !GetProfile()->IsOffTheRecord() && !include_incognito()) { + !browser_context()->IsOffTheRecord() && !include_incognito()) { // Don't expose incognito windows if extension itself works in non-incognito // profile and CanCrossIncognito isn't allowed. - SetResult(base::Value::CreateNullValue()); + result = base::Value::CreateNullValue(); } else { - SetResult(controller->CreateWindowValueWithTabs(extension())); + result = controller->CreateWindowValueWithTabs(extension()); } - return true; + return RespondNow(OneArgument(std::move(result))); } -bool WindowsUpdateFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { std::unique_ptr<windows::Update::Params> params( windows::Update::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); WindowController* controller; + std::string error; if (!windows_util::GetWindowFromWindowID( this, params->window_id, WindowController::GetAllWindowFilter(), - &controller)) { - return false; + &controller, &error)) { + return RespondNow(Error(error)); } ui::WindowShowState show_state = @@ -780,8 +730,7 @@ bool WindowsUpdateFunction::RunSync() { if (show_state == ui::SHOW_STATE_MINIMIZED || show_state == ui::SHOW_STATE_MAXIMIZED || show_state == ui::SHOW_STATE_FULLSCREEN) { - error_ = keys::kInvalidWindowStateError; - return false; + return RespondNow(Error(keys::kInvalidWindowStateError)); } // TODO(varkha): Updating bounds during a drag can cause problems and a more // general solution is needed. See http://crbug.com/251813 . @@ -790,16 +739,13 @@ bool WindowsUpdateFunction::RunSync() { if (params->update_info.focused) { if (*params->update_info.focused) { - if (show_state == ui::SHOW_STATE_MINIMIZED) { - error_ = keys::kInvalidWindowStateError; - return false; - } + if (show_state == ui::SHOW_STATE_MINIMIZED) + return RespondNow(Error(keys::kInvalidWindowStateError)); controller->window()->Activate(); } else { if (show_state == ui::SHOW_STATE_MAXIMIZED || show_state == ui::SHOW_STATE_FULLSCREEN) { - error_ = keys::kInvalidWindowStateError; - return false; + return RespondNow(Error(keys::kInvalidWindowStateError)); } controller->window()->Deactivate(); } @@ -808,36 +754,35 @@ bool WindowsUpdateFunction::RunSync() { if (params->update_info.draw_attention) controller->window()->FlashFrame(*params->update_info.draw_attention); - SetResult(controller->CreateWindowValue()); - - return true; + return RespondNow(OneArgument(controller->CreateWindowValue())); } -bool WindowsRemoveFunction::RunSync() { +ExtensionFunction::ResponseAction WindowsRemoveFunction::Run() { std::unique_ptr<windows::Remove::Params> params( windows::Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - WindowController* controller; + WindowController* controller = nullptr; + std::string error; if (!windows_util::GetWindowFromWindowID(this, params->window_id, WindowController::kNoWindowFilter, - &controller)) { - return false; + &controller, &error)) { + return RespondNow(Error(error)); } WindowController::Reason reason; if (!controller->CanClose(&reason)) { - if (reason == WindowController::REASON_NOT_EDITABLE) - error_ = keys::kTabStripNotEditableError; - return false; + return RespondNow(Error(reason == WindowController::REASON_NOT_EDITABLE + ? keys::kTabStripNotEditableError + : kUnknownErrorDoNotUse)); } controller->window()->Close(); - return true; + return RespondNow(NoArguments()); } // Tabs ------------------------------------------------------------------------ -bool TabsGetSelectedFunction::RunSync() { +ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() { // windowId defaults to "current" window. int window_id = extension_misc::kCurrentWindowId; @@ -848,21 +793,20 @@ bool TabsGetSelectedFunction::RunSync() { window_id = *params->window_id; Browser* browser = NULL; - if (!GetBrowserFromWindowID(this, window_id, &browser)) - return false; + std::string error; + if (!GetBrowserFromWindowID(this, window_id, &browser, &error)) + return RespondNow(Error(error)); TabStripModel* tab_strip = browser->tab_strip_model(); WebContents* contents = tab_strip->GetActiveWebContents(); - if (!contents) { - error_ = keys::kNoSelectedTabError; - return false; - } - results_ = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, tab_strip, tab_strip->active_index(), extension())); - return true; + if (!contents) + return RespondNow(Error(keys::kNoSelectedTabError)); + return RespondNow(ArgumentList( + tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( + contents, tab_strip, tab_strip->active_index(), extension())))); } -bool TabsGetAllInWindowFunction::RunSync() { +ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { std::unique_ptr<tabs::GetAllInWindow::Params> params( tabs::GetAllInWindow::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -872,15 +816,15 @@ bool TabsGetAllInWindowFunction::RunSync() { window_id = *params->window_id; Browser* browser = NULL; - if (!GetBrowserFromWindowID(this, window_id, &browser)) - return false; - - SetResult(ExtensionTabUtil::CreateTabList(browser, extension())); + std::string error; + if (!GetBrowserFromWindowID(this, window_id, &browser, &error)) + return RespondNow(Error(error)); - return true; + return RespondNow( + OneArgument(ExtensionTabUtil::CreateTabList(browser, extension()))); } -bool TabsQueryFunction::RunSync() { +ExtensionFunction::ResponseAction TabsQueryFunction::Run() { std::unique_ptr<tabs::Query::Params> params( tabs::Query::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -898,9 +842,10 @@ bool TabsQueryFunction::RunSync() { // It is o.k. to use URLPattern::SCHEME_ALL here because this function does // not grant access to the content of the tabs, only to seeing their URLs // and meta data. + std::string error; if (!url_patterns.Populate(url_pattern_strings, URLPattern::SCHEME_ALL, - true, &error_)) { - return false; + true, &error)) { + return RespondNow(Error(error)); } } @@ -921,17 +866,19 @@ bool TabsQueryFunction::RunSync() { window_type = tabs::ToString(params->query_info.window_type); std::unique_ptr<base::ListValue> result(new base::ListValue()); + Profile* profile = Profile::FromBrowserContext(browser_context()); Browser* last_active_browser = - chrome::FindAnyBrowser(GetProfile(), include_incognito()); - Browser* current_browser = GetCurrentBrowser(); + chrome::FindAnyBrowser(profile, include_incognito()); + Browser* current_browser = + ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); for (auto* browser : *BrowserList::GetInstance()) { - if (!GetProfile()->IsSameProfile(browser->profile())) + if (!profile->IsSameProfile(browser->profile())) continue; if (!browser->window()) continue; - if (!include_incognito() && GetProfile() != browser->profile()) + if (!include_incognito() && profile != browser->profile()) continue; if (!browser->extension_window_controller()->IsVisibleToExtension( @@ -966,6 +913,7 @@ bool TabsQueryFunction::RunSync() { TabStripModel* tab_strip = browser->tab_strip_model(); for (int i = 0; i < tab_strip->count(); ++i) { WebContents* web_contents = tab_strip->GetWebContentsAt(i); + memory::TabManager* tab_manager = g_browser_process->GetTabManager(); if (index > -1 && i != index) continue; @@ -990,6 +938,16 @@ bool TabsQueryFunction::RunSync() { continue; } + if (!MatchesBool(params->query_info.discarded.get(), + tab_manager->IsTabDiscarded(web_contents))) { + continue; + } + + if (!MatchesBool(params->query_info.auto_discardable.get(), + tab_manager->IsTabAutoDiscardable(web_contents))) { + continue; + } + if (!MatchesBool(params->query_info.muted.get(), web_contents->IsAudioMuted())) { continue; @@ -1029,11 +987,10 @@ bool TabsQueryFunction::RunSync() { } } - SetResult(std::move(result)); - return true; + return RespondNow(OneArgument(std::move(result))); } -bool TabsCreateFunction::RunSync() { +ExtensionFunction::ResponseAction TabsCreateFunction::Run() { std::unique_ptr<tabs::Create::Params> params( tabs::Create::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -1052,19 +1009,15 @@ bool TabsCreateFunction::RunSync() { std::string error; std::unique_ptr<base::DictionaryValue> result( ExtensionTabUtil::OpenTab(this, options, &error)); - if (!result) { - SetError(error); - return false; - } + if (!result) + return RespondNow(Error(error)); // Return data about the newly created tab. - if (has_callback()) { - SetResult(std::move(result)); - } - return true; + return RespondNow(has_callback() ? OneArgument(std::move(result)) + : NoArguments()); } -bool TabsDuplicateFunction::RunSync() { +ExtensionFunction::ResponseAction TabsDuplicateFunction::Run() { std::unique_ptr<tabs::Duplicate::Params> params( tabs::Duplicate::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -1073,20 +1026,15 @@ bool TabsDuplicateFunction::RunSync() { Browser* browser = NULL; TabStripModel* tab_strip = NULL; int tab_index = -1; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - &browser, - &tab_strip, - NULL, - &tab_index, - &error_)) { - return false; + std::string error; + if (!GetTabById(tab_id, browser_context(), include_incognito(), &browser, + &tab_strip, NULL, &tab_index, &error)) { + return RespondNow(Error(error)); } WebContents* new_contents = chrome::DuplicateTabAt(browser, tab_index); if (!has_callback()) - return true; + return RespondNow(NoArguments()); // Duplicated tab may not be in the same window as the original, so find // the window and the tab. @@ -1096,17 +1044,15 @@ bool TabsDuplicateFunction::RunSync() { &new_tab_strip, &new_tab_index); if (!new_tab_strip || new_tab_index == -1) { - return false; + return RespondNow(Error(kUnknownErrorDoNotUse)); } - // Return data about the newly created tab. - results_ = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - new_contents, new_tab_strip, new_tab_index, extension())); - - return true; + return RespondNow(ArgumentList( + tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( + new_contents, new_tab_strip, new_tab_index, extension())))); } -bool TabsGetFunction::RunSync() { +ExtensionFunction::ResponseAction TabsGetFunction::Run() { std::unique_ptr<tabs::Get::Params> params(tabs::Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->tab_id; @@ -1114,35 +1060,32 @@ bool TabsGetFunction::RunSync() { TabStripModel* tab_strip = NULL; WebContents* contents = NULL; int tab_index = -1; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - NULL, - &tab_strip, - &contents, - &tab_index, - &error_)) - return false; + std::string error; + if (!GetTabById(tab_id, browser_context(), include_incognito(), NULL, + &tab_strip, &contents, &tab_index, &error)) { + return RespondNow(Error(error)); + } - results_ = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, tab_strip, tab_index, extension())); - return true; + return RespondNow(ArgumentList( + tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( + contents, tab_strip, tab_index, extension())))); } -bool TabsGetCurrentFunction::RunSync() { +ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { DCHECK(dispatcher()); // Return the caller, if it's a tab. If not the result isn't an error but an // empty tab (hence returning true). WebContents* caller_contents = GetSenderWebContents(); - if (caller_contents && ExtensionTabUtil::GetTabId(caller_contents) >= 0) - results_ = tabs::Get::Results::Create( + std::unique_ptr<base::ListValue> results; + if (caller_contents && ExtensionTabUtil::GetTabId(caller_contents) >= 0) { + results = tabs::Get::Results::Create( *ExtensionTabUtil::CreateTabObject(caller_contents, extension())); - - return true; + } + return RespondNow(results ? ArgumentList(std::move(results)) : NoArguments()); } -bool TabsHighlightFunction::RunSync() { +ExtensionFunction::ResponseAction TabsHighlightFunction::Run() { std::unique_ptr<tabs::Highlight::Params> params( tabs::Highlight::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -1153,8 +1096,9 @@ bool TabsHighlightFunction::RunSync() { window_id = *params->highlight_info.window_id; Browser* browser = NULL; - if (!GetBrowserFromWindowID(this, window_id, &browser)) - return false; + std::string error; + if (!GetBrowserFromWindowID(this, window_id, &browser, &error)) + return RespondNow(Error(error)); TabStripModel* tabstrip = browser->tab_strip_model(); ui::ListSelectionModel selection; @@ -1164,40 +1108,39 @@ bool TabsHighlightFunction::RunSync() { std::vector<int>& tab_indices = *params->highlight_info.tabs.as_integers; // Create a new selection model as we read the list of tab indices. for (size_t i = 0; i < tab_indices.size(); ++i) { - if (!HighlightTab(tabstrip, &selection, &active_index, tab_indices[i])) - return false; + if (!HighlightTab(tabstrip, &selection, &active_index, tab_indices[i], + &error)) { + return RespondNow(Error(error)); + } } } else { EXTENSION_FUNCTION_VALIDATE(params->highlight_info.tabs.as_integer); - if (!HighlightTab(tabstrip, - &selection, - &active_index, - *params->highlight_info.tabs.as_integer)) { - return false; + if (!HighlightTab(tabstrip, &selection, &active_index, + *params->highlight_info.tabs.as_integer, &error)) { + return RespondNow(Error(error)); } } // Make sure they actually specified tabs to select. - if (selection.empty()) { - error_ = keys::kNoHighlightedTabError; - return false; - } + if (selection.empty()) + return RespondNow(Error(keys::kNoHighlightedTabError)); selection.set_active(active_index); browser->tab_strip_model()->SetSelectionFromModel(selection); - SetResult(browser->extension_window_controller()->CreateWindowValueWithTabs( - extension())); - return true; + return RespondNow(OneArgument( + browser->extension_window_controller()->CreateWindowValueWithTabs( + extension()))); } bool TabsHighlightFunction::HighlightTab(TabStripModel* tabstrip, ui::ListSelectionModel* selection, int* active_index, - int index) { + int index, + std::string* error) { // Make sure the index is in range. if (!tabstrip->ContainsIndex(index)) { - error_ = ErrorUtils::FormatErrorMessage( - keys::kTabIndexNotFoundError, base::IntToString(index)); + *error = ErrorUtils::FormatErrorMessage(keys::kTabIndexNotFoundError, + base::IntToString(index)); return false; } @@ -1237,14 +1180,8 @@ bool TabsUpdateFunction::RunAsync() { int tab_index = -1; TabStripModel* tab_strip = NULL; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - NULL, - &tab_strip, - &contents, - &tab_index, - &error_)) { + if (!GetTabById(tab_id, browser_context(), include_incognito(), NULL, + &tab_strip, &contents, &tab_index, &error_)) { return false; } @@ -1316,18 +1253,20 @@ bool TabsUpdateFunction::RunAsync() { int opener_id = *params->update_properties.opener_tab_id; WebContents* opener_contents = NULL; - if (!ExtensionTabUtil::GetTabById(opener_id, - GetProfile(), - include_incognito(), - NULL, - NULL, - &opener_contents, - NULL)) + if (!ExtensionTabUtil::GetTabById(opener_id, browser_context(), + include_incognito(), nullptr, nullptr, + &opener_contents, nullptr)) return false; tab_strip->SetOpenerOfWebContentsAt(tab_index, opener_contents); } + if (params->update_properties.auto_discardable.get()) { + bool state = *params->update_properties.auto_discardable; + g_browser_process->GetTabManager()->SetTabAutoDiscardableState(contents, + state); + } + if (!is_async) { PopulateResult(); SendResponse(true); @@ -1377,20 +1316,32 @@ bool TabsUpdateFunction::UpdateURL(const std::string &url_string, ScriptExecutor::SINGLE_FRAME, ExtensionApiFrameIdMap::kTopFrameId, ScriptExecutor::DONT_MATCH_ABOUT_BLANK, UserScript::DOCUMENT_IDLE, ScriptExecutor::MAIN_WORLD, ScriptExecutor::DEFAULT_PROCESS, GURL(), - GURL(), user_gesture_, ScriptExecutor::NO_RESULT, + GURL(), user_gesture(), ScriptExecutor::NO_RESULT, base::Bind(&TabsUpdateFunction::OnExecuteCodeFinished, this)); *is_async = true; return true; } - web_contents_->GetController().LoadURL( - url, content::Referrer(), ui::PAGE_TRANSITION_LINK, std::string()); + bool use_renderer_initiated = false; + // For the PDF extension, treat it as renderer-initiated so that it does not + // show in the omnibox until it commits. This avoids URL spoofs since urls + // can be opened on behalf of untrusted content. + // TODO(devlin|nasko): Make this the default for all extensions. + if (extension() && extension()->id() == extension_misc::kPdfExtensionId) + use_renderer_initiated = true; + NavigationController::LoadURLParams load_params(url); + load_params.is_renderer_initiated = use_renderer_initiated; + web_contents_->GetController().LoadURLWithParams(load_params); // The URL of a tab contents never actually changes to a JavaScript URL, so // this check only makes sense in other cases. - if (!url.SchemeIs(url::kJavaScriptScheme)) - DCHECK_EQ(url.spec(), web_contents_->GetURL().spec()); + if (!url.SchemeIs(url::kJavaScriptScheme)) { + // The URL should be present in the pending entry, though it may not be + // visible in the omnibox until it commits. + DCHECK_EQ( + url, web_contents_->GetController().GetPendingEntry()->GetVirtualURL()); + } return true; } @@ -1414,7 +1365,7 @@ void TabsUpdateFunction::OnExecuteCodeFinished( SendResponse(error.empty()); } -bool TabsMoveFunction::RunSync() { +ExtensionFunction::ResponseAction TabsMoveFunction::Run() { std::unique_ptr<tabs::Move::Params> params( tabs::Move::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -1424,66 +1375,61 @@ bool TabsMoveFunction::RunSync() { std::unique_ptr<base::ListValue> tab_values(new base::ListValue()); size_t num_tabs = 0; + std::string error; if (params->tab_ids.as_integers) { std::vector<int>& tab_ids = *params->tab_ids.as_integers; num_tabs = tab_ids.size(); for (size_t i = 0; i < tab_ids.size(); ++i) { - if (!MoveTab(tab_ids[i], &new_index, i, tab_values.get(), window_id)) - return false; + if (!MoveTab(tab_ids[i], &new_index, i, tab_values.get(), window_id, + &error)) { + return RespondNow(Error(error)); + } } } else { EXTENSION_FUNCTION_VALIDATE(params->tab_ids.as_integer); num_tabs = 1; - if (!MoveTab(*params->tab_ids.as_integer, - &new_index, - 0, - tab_values.get(), - window_id)) { - return false; + if (!MoveTab(*params->tab_ids.as_integer, &new_index, 0, tab_values.get(), + window_id, &error)) { + return RespondNow(Error(error)); } } + // TODO(devlin): It's weird that whether or not the method provides a callback + // can determine its success (as we return errors below). if (!has_callback()) - return true; + return RespondNow(NoArguments()); - if (num_tabs == 0) { - error_ = "No tabs given."; - return false; - } else if (num_tabs == 1) { + if (num_tabs == 0) + return RespondNow(Error("No tabs given.")); + if (num_tabs == 1) { std::unique_ptr<base::Value> value; - CHECK(tab_values.get()->Remove(0, &value)); - SetResult(std::move(value)); - } else { - // Only return the results as an array if there are multiple tabs. - SetResult(std::move(tab_values)); + CHECK(tab_values->Remove(0, &value)); + return RespondNow(OneArgument(std::move(value))); } - return true; + // Return the results as an array if there are multiple tabs. + return RespondNow(OneArgument(std::move(tab_values))); } bool TabsMoveFunction::MoveTab(int tab_id, int* new_index, int iteration, base::ListValue* tab_values, - int* window_id) { + int* window_id, + std::string* error) { Browser* source_browser = NULL; TabStripModel* source_tab_strip = NULL; WebContents* contents = NULL; int tab_index = -1; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - &source_browser, - &source_tab_strip, - &contents, - &tab_index, - &error_)) { + if (!GetTabById(tab_id, browser_context(), include_incognito(), + &source_browser, &source_tab_strip, &contents, &tab_index, + error)) { return false; } // Don't let the extension move the tab if the user is dragging tabs. if (!source_browser->window()->IsTabStripEditable()) { - error_ = keys::kTabStripNotEditableError; + *error = keys::kTabStripNotEditableError; return false; } @@ -1493,21 +1439,21 @@ bool TabsMoveFunction::MoveTab(int tab_id, if (window_id) { Browser* target_browser = NULL; - if (!GetBrowserFromWindowID(this, *window_id, &target_browser)) + if (!GetBrowserFromWindowID(this, *window_id, &target_browser, error)) return false; if (!target_browser->window()->IsTabStripEditable()) { - error_ = keys::kTabStripNotEditableError; + *error = keys::kTabStripNotEditableError; return false; } if (!target_browser->is_type_tabbed()) { - error_ = keys::kCanOnlyMoveTabsWithinNormalWindowsError; + *error = keys::kCanOnlyMoveTabsWithinNormalWindowsError; return false; } if (target_browser->profile() != source_browser->profile()) { - error_ = keys::kCanOnlyMoveTabsWithinSameProfileError; + *error = keys::kCanOnlyMoveTabsWithinSameProfileError; return false; } @@ -1518,8 +1464,8 @@ bool TabsMoveFunction::MoveTab(int tab_id, WebContents* web_contents = source_tab_strip->DetachWebContentsAt(tab_index); if (!web_contents) { - error_ = ErrorUtils::FormatErrorMessage( - keys::kTabNotFoundError, base::IntToString(tab_id)); + *error = ErrorUtils::FormatErrorMessage(keys::kTabNotFoundError, + base::IntToString(tab_id)); return false; } @@ -1562,7 +1508,7 @@ bool TabsMoveFunction::MoveTab(int tab_id, return true; } -bool TabsReloadFunction::RunSync() { +ExtensionFunction::ResponseAction TabsReloadFunction::Run() { std::unique_ptr<tabs::Reload::Params> params( tabs::Reload::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -1577,28 +1523,22 @@ bool TabsReloadFunction::RunSync() { // If |tab_id| is specified, look for it. Otherwise default to selected tab // in the current window. + Browser* current_browser = + ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); if (!params->tab_id.get()) { - Browser* browser = GetCurrentBrowser(); - if (!browser) { - error_ = keys::kNoCurrentWindowError; - return false; - } + if (!current_browser) + return RespondNow(Error(keys::kNoCurrentWindowError)); - if (!ExtensionTabUtil::GetDefaultTab(browser, &web_contents, NULL)) - return false; + if (!ExtensionTabUtil::GetDefaultTab(current_browser, &web_contents, NULL)) + return RespondNow(Error(kUnknownErrorDoNotUse)); } else { int tab_id = *params->tab_id; Browser* browser = NULL; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - &browser, - NULL, - &web_contents, - NULL, - &error_)) { - return false; + std::string error; + if (!GetTabById(tab_id, browser_context(), include_incognito(), &browser, + NULL, &web_contents, NULL, &error)) { + return RespondNow(Error(error)); } } @@ -1606,54 +1546,50 @@ bool TabsReloadFunction::RunSync() { // This does as same as Browser::ReloadInternal. NavigationEntry* entry = web_contents->GetController().GetVisibleEntry(); GURL reload_url = entry ? entry->GetURL() : GURL(url::kAboutBlankURL); - OpenURLParams params(reload_url, Referrer(), CURRENT_TAB, + OpenURLParams params(reload_url, Referrer(), + WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_RELOAD, false); - GetCurrentBrowser()->OpenURL(params); + current_browser->OpenURL(params); } else if (bypass_cache) { web_contents->GetController().ReloadBypassingCache(true); } else { web_contents->GetController().Reload(true); } - return true; + return RespondNow(NoArguments()); } -bool TabsRemoveFunction::RunSync() { +ExtensionFunction::ResponseAction TabsRemoveFunction::Run() { std::unique_ptr<tabs::Remove::Params> params( tabs::Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); + std::string error; if (params->tab_ids.as_integers) { std::vector<int>& tab_ids = *params->tab_ids.as_integers; for (size_t i = 0; i < tab_ids.size(); ++i) { - if (!RemoveTab(tab_ids[i])) - return false; + if (!RemoveTab(tab_ids[i], &error)) + return RespondNow(Error(error)); } } else { EXTENSION_FUNCTION_VALIDATE(params->tab_ids.as_integer); - if (!RemoveTab(*params->tab_ids.as_integer.get())) - return false; + if (!RemoveTab(*params->tab_ids.as_integer, &error)) + return RespondNow(Error(error)); } - return true; + return RespondNow(NoArguments()); } -bool TabsRemoveFunction::RemoveTab(int tab_id) { +bool TabsRemoveFunction::RemoveTab(int tab_id, std::string* error) { Browser* browser = NULL; WebContents* contents = NULL; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - &browser, - NULL, - &contents, - NULL, - &error_)) { + if (!GetTabById(tab_id, browser_context(), include_incognito(), &browser, + nullptr, &contents, nullptr, error)) { return false; } // Don't let the extension remove a tab if the user is dragging tabs around. if (!browser->window()->IsTabStripEditable()) { - error_ = keys::kTabStripNotEditableError; + *error = keys::kTabStripNotEditableError; return false; } // There's a chance that the tab is being dragged, or we're in some other @@ -1687,7 +1623,7 @@ bool TabsCaptureVisibleTabFunction::ClientAllowsTransparency() { WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID(int window_id) { Browser* browser = NULL; - if (!GetBrowserFromWindowID(&chrome_details_, window_id, &browser)) + if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, &error_)) return NULL; WebContents* contents = browser->tab_strip_model()->GetActiveWebContents(); @@ -1773,14 +1709,8 @@ bool TabsDetectLanguageFunction::RunAsync() { // in the current window. if (params->tab_id.get()) { tab_id = *params->tab_id; - if (!GetTabById(tab_id, - GetProfile(), - include_incognito(), - &browser, - NULL, - &contents, - NULL, - &error_)) { + if (!GetTabById(tab_id, browser_context(), include_incognito(), &browser, + nullptr, &contents, nullptr, &error_)) { return false; } if (!browser || !contents) @@ -1910,14 +1840,8 @@ bool ExecuteCodeInTabFunction::CanExecuteScriptOnPage() { // If |tab_id| is specified, look for the tab. Otherwise default to selected // tab in the current window. CHECK_GE(execute_tab_id_, 0); - if (!GetTabById(execute_tab_id_, - chrome_details_.GetProfile(), - include_incognito(), - NULL, - NULL, - &contents, - NULL, - &error_)) { + if (!GetTabById(execute_tab_id_, browser_context(), include_incognito(), + nullptr, nullptr, &contents, nullptr, &error_)) { return false; } @@ -1972,15 +1896,10 @@ ScriptExecutor* ExecuteCodeInTabFunction::GetScriptExecutor() { Browser* browser = NULL; content::WebContents* contents = NULL; - bool success = GetTabById(execute_tab_id_, - chrome_details_.GetProfile(), - include_incognito(), - &browser, - NULL, - &contents, - NULL, - &error_) && - contents && browser; + bool success = + GetTabById(execute_tab_id_, browser_context(), include_incognito(), + &browser, nullptr, &contents, nullptr, &error_) && + contents && browser; if (!success) return NULL; @@ -2017,14 +1936,10 @@ content::WebContents* ZoomAPIFunction::GetWebContents(int tab_id) { content::WebContents* web_contents = NULL; if (tab_id != -1) { // We assume this call leaves web_contents unchanged if it is unsuccessful. - GetTabById(tab_id, - GetProfile(), - include_incognito(), - NULL /* ignore Browser* output */, - NULL /* ignore TabStripModel* output */, - &web_contents, - NULL /* ignore int tab_index output */, - &error_); + GetTabById(tab_id, browser_context(), include_incognito(), + nullptr /* ignore Browser* output */, + nullptr /* ignore TabStripModel* output */, &web_contents, + nullptr /* ignore int tab_index output */, &error_); } else { Browser* browser = GetCurrentBrowser(); if (!browser) @@ -2160,4 +2075,42 @@ bool TabsGetZoomSettingsFunction::RunAsync() { return true; } +ExtensionFunction::ResponseAction TabsDiscardFunction::Run() { + std::unique_ptr<tabs::Discard::Params> params( + tabs::Discard::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + + WebContents* contents = nullptr; + // If |tab_id| is given, find the web_contents respective to it. + // Otherwise invoke discard function in TabManager with null web_contents + // that will discard the least important tab. + if (params->tab_id) { + int tab_id = *params->tab_id; + std::string error; + if (!GetTabById(tab_id, browser_context(), include_incognito(), nullptr, + nullptr, &contents, nullptr, &error)) { + return RespondNow(Error(error)); + } + } + // Discard the tab. + contents = + g_browser_process->GetTabManager()->DiscardTabByExtension(contents); + + // Create the Tab object and return it in case of success. + if (contents) { + return RespondNow(ArgumentList(tabs::Discard::Results::Create( + *ExtensionTabUtil::CreateTabObject(contents)))); + } + + // Return appropriate error message otherwise. + return RespondNow(Error( + params->tab_id + ? ErrorUtils::FormatErrorMessage(keys::kCannotDiscardTab, + base::IntToString(*params->tab_id)) + : keys::kCannotFindTabToDiscard)); +} + +TabsDiscardFunction::TabsDiscardFunction() {} +TabsDiscardFunction::~TabsDiscardFunction() {} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h index 7457aad43d8..5e5299c1e9d 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h @@ -17,6 +17,7 @@ #include "content/public/browser/notification_registrar.h" #include "extensions/browser/api/execute_code_function.h" #include "extensions/browser/api/web_contents_capture_client.h" +#include "extensions/browser/extension_function.h" #include "extensions/common/extension_resource.h" #include "extensions/common/user_script.h" #include "url/gurl.h" @@ -48,29 +49,29 @@ void ZoomModeToZoomSettings(zoom::ZoomController::ZoomMode zoom_mode, api::tabs::ZoomSettings* zoom_settings); // Windows -class WindowsGetFunction : public ChromeSyncExtensionFunction { +class WindowsGetFunction : public UIThreadExtensionFunction { ~WindowsGetFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.get", WINDOWS_GET) }; -class WindowsGetCurrentFunction : public ChromeSyncExtensionFunction { +class WindowsGetCurrentFunction : public UIThreadExtensionFunction { ~WindowsGetCurrentFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getCurrent", WINDOWS_GETCURRENT) }; -class WindowsGetLastFocusedFunction : public ChromeSyncExtensionFunction { +class WindowsGetLastFocusedFunction : public UIThreadExtensionFunction { ~WindowsGetLastFocusedFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getLastFocused", WINDOWS_GETLASTFOCUSED) }; -class WindowsGetAllFunction : public ChromeSyncExtensionFunction { +class WindowsGetAllFunction : public UIThreadExtensionFunction { ~WindowsGetAllFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getAll", WINDOWS_GETALL) }; -class WindowsCreateFunction : public ChromeSyncExtensionFunction { +class WindowsCreateFunction : public UIThreadExtensionFunction { ~WindowsCreateFunction() override {} - bool RunSync() override; + ResponseAction Run() override; // Returns whether the window should be created in incognito mode. // |create_data| are the options passed by the extension. It may be NULL. // |urls| is the list of urls to open. If we are creating an incognito window, @@ -81,63 +82,64 @@ class WindowsCreateFunction : public ChromeSyncExtensionFunction { bool ShouldOpenIncognitoWindow( const api::windows::Create::Params::CreateData* create_data, std::vector<GURL>* urls, - bool* is_error); + std::string* error); DECLARE_EXTENSION_FUNCTION("windows.create", WINDOWS_CREATE) }; -class WindowsUpdateFunction : public ChromeSyncExtensionFunction { +class WindowsUpdateFunction : public UIThreadExtensionFunction { ~WindowsUpdateFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.update", WINDOWS_UPDATE) }; -class WindowsRemoveFunction : public ChromeSyncExtensionFunction { +class WindowsRemoveFunction : public UIThreadExtensionFunction { ~WindowsRemoveFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.remove", WINDOWS_REMOVE) }; // Tabs -class TabsGetFunction : public ChromeSyncExtensionFunction { +class TabsGetFunction : public UIThreadExtensionFunction { ~TabsGetFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.get", TABS_GET) }; -class TabsGetCurrentFunction : public ChromeSyncExtensionFunction { +class TabsGetCurrentFunction : public UIThreadExtensionFunction { ~TabsGetCurrentFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getCurrent", TABS_GETCURRENT) }; -class TabsGetSelectedFunction : public ChromeSyncExtensionFunction { +class TabsGetSelectedFunction : public UIThreadExtensionFunction { ~TabsGetSelectedFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getSelected", TABS_GETSELECTED) }; -class TabsGetAllInWindowFunction : public ChromeSyncExtensionFunction { +class TabsGetAllInWindowFunction : public UIThreadExtensionFunction { ~TabsGetAllInWindowFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getAllInWindow", TABS_GETALLINWINDOW) }; -class TabsQueryFunction : public ChromeSyncExtensionFunction { +class TabsQueryFunction : public UIThreadExtensionFunction { ~TabsQueryFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.query", TABS_QUERY) }; -class TabsCreateFunction : public ChromeSyncExtensionFunction { +class TabsCreateFunction : public UIThreadExtensionFunction { ~TabsCreateFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.create", TABS_CREATE) }; -class TabsDuplicateFunction : public ChromeSyncExtensionFunction { +class TabsDuplicateFunction : public UIThreadExtensionFunction { ~TabsDuplicateFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.duplicate", TABS_DUPLICATE) }; -class TabsHighlightFunction : public ChromeSyncExtensionFunction { +class TabsHighlightFunction : public UIThreadExtensionFunction { ~TabsHighlightFunction() override {} - bool RunSync() override; + ResponseAction Run() override; bool HighlightTab(TabStripModel* tabstrip, ui::ListSelectionModel* selection, - int *active_index, - int index); + int* active_index, + int index, + std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.highlight", TABS_HIGHLIGHT) }; class TabsUpdateFunction : public ChromeAsyncExtensionFunction { @@ -161,25 +163,26 @@ class TabsUpdateFunction : public ChromeAsyncExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.update", TABS_UPDATE) }; -class TabsMoveFunction : public ChromeSyncExtensionFunction { +class TabsMoveFunction : public UIThreadExtensionFunction { ~TabsMoveFunction() override {} - bool RunSync() override; + ResponseAction Run() override; bool MoveTab(int tab_id, int* new_index, int iteration, base::ListValue* tab_values, - int* window_id); + int* window_id, + std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.move", TABS_MOVE) }; -class TabsReloadFunction : public ChromeSyncExtensionFunction { +class TabsReloadFunction : public UIThreadExtensionFunction { ~TabsReloadFunction() override {} - bool RunSync() override; + ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.reload", TABS_RELOAD) }; -class TabsRemoveFunction : public ChromeSyncExtensionFunction { +class TabsRemoveFunction : public UIThreadExtensionFunction { ~TabsRemoveFunction() override {} - bool RunSync() override; - bool RemoveTab(int tab_id); + ResponseAction Run() override; + bool RemoveTab(int tab_id, std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.remove", TABS_REMOVE) }; class TabsDetectLanguageFunction : public ChromeAsyncExtensionFunction, @@ -322,6 +325,21 @@ class TabsGetZoomSettingsFunction : public ZoomAPIFunction { DECLARE_EXTENSION_FUNCTION("tabs.getZoomSettings", TABS_GETZOOMSETTINGS) }; +class TabsDiscardFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("tabs.discard", TABS_DISCARD) + + TabsDiscardFunction(); + + private: + ~TabsDiscardFunction() override; + + // ExtensionFunction: + ExtensionFunction::ResponseAction Run() override; + + DISALLOW_COPY_AND_ASSIGN(TabsDiscardFunction); +}; + } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_ 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 f8edf1b9371..506cc9455b7 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc @@ -2,16 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/test_browser_window.h" #include "content/public/browser/navigation_entry.h" +#include "content/public/common/browser_side_navigation_policy.h" +#include "content/public/test/browser_side_navigation_test_utils.h" #include "content/public/test/web_contents_tester.h" +#include "extensions/browser/api_test_utils.h" +#include "extensions/common/constants.h" #include "extensions/common/extension_builder.h" #include "extensions/common/test_util.h" @@ -57,6 +63,9 @@ void TabsApiUnitTest::SetUp() { ExtensionServiceTestBase::SetUp(); InitializeEmptyExtensionService(); + if (content::IsBrowserSideNavigationEnabled()) + content::BrowserSideNavigationSetUp(); + browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile()); params.type = Browser::TYPE_TABBED; @@ -67,6 +76,8 @@ void TabsApiUnitTest::SetUp() { void TabsApiUnitTest::TearDown() { browser_.reset(); browser_window_.reset(); + if (content::IsBrowserSideNavigationEnabled()) + content::BrowserSideNavigationTearDown(); ExtensionServiceTestBase::TearDown(); } @@ -201,12 +212,62 @@ TEST_F(TabsApiUnitTest, QueryWithHostPermission) { int first_tab_id = -1; ASSERT_TRUE(first_tab_info->GetInteger("id", &first_tab_id)); - EXPECT_TRUE(ContainsValue(expected_tabs_ids, first_tab_id)); + EXPECT_TRUE(base::ContainsValue(expected_tabs_ids, first_tab_id)); int third_tab_id = -1; ASSERT_TRUE(third_tab_info->GetInteger("id", &third_tab_id)); - EXPECT_TRUE(ContainsValue(expected_tabs_ids, third_tab_id)); + EXPECT_TRUE(base::ContainsValue(expected_tabs_ids, third_tab_id)); } } +// Test that using the PDF extension for tab updates is treated as a +// renderer-initiated navigation. crbug.com/660498 +TEST_F(TabsApiUnitTest, PDFExtensionNavigation) { + DictionaryBuilder manifest; + manifest.Set("name", "pdfext") + .Set("description", "desc") + .Set("version", "0.1") + .Set("manifest_version", 2) + .Set("permissions", ListBuilder().Append("tabs").Build()); + scoped_refptr<const Extension> extension = + ExtensionBuilder() + .SetManifest(manifest.Build()) + .SetID(extension_misc::kPdfExtensionId) + .Build(); + ASSERT_TRUE(extension); + + content::WebContents* web_contents = + content::WebContentsTester::CreateTestWebContents(profile(), nullptr); + ASSERT_TRUE(web_contents); + content::WebContentsTester* web_contents_tester = + content::WebContentsTester::For(web_contents); + const GURL kGoogle("http://www.google.com"); + web_contents_tester->NavigateAndCommit(kGoogle); + EXPECT_EQ(kGoogle, web_contents->GetLastCommittedURL()); + EXPECT_EQ(kGoogle, web_contents->GetVisibleURL()); + + SessionTabHelper::CreateForWebContents(web_contents); + int tab_id = SessionTabHelper::IdForTab(web_contents); + browser()->tab_strip_model()->AppendWebContents(web_contents, true); + + scoped_refptr<TabsUpdateFunction> function = new TabsUpdateFunction(); + function->set_extension(extension.get()); + function->set_browser_context(profile()); + std::unique_ptr<base::ListValue> args( + extension_function_test_utils::ParseList(base::StringPrintf( + "[%d, {\"url\":\"http://example.com\"}]", tab_id))); + function->SetArgs(args.get()); + api_test_utils::SendResponseHelper response_helper(function.get()); + function->RunWithValidation()->Execute(); + + EXPECT_EQ(kGoogle, web_contents->GetLastCommittedURL()); + EXPECT_EQ(kGoogle, web_contents->GetVisibleURL()); + + // Clean up. + response_helper.WaitForResponse(); + while (!browser()->tab_strip_model()->empty()) + browser()->tab_strip_model()->CloseWebContentsAt(0, 0); + base::RunLoop().RunUntilIdle(); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc index 2903ee9c5ad..8d4392b3f7a 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc @@ -31,6 +31,8 @@ const char kOldWindowIdKey[] = "oldWindowId"; const char kOpenerTabIdKey[] = "openerTabId"; const char kPinnedKey[] = "pinned"; const char kAudibleKey[] = "audible"; +const char kDiscardedKey[] = "discarded"; +const char kAutoDiscardableKey[] = "autoDiscardable"; const char kMutedKey[] = "muted"; const char kMutedInfoKey[] = "mutedInfo"; const char kQualityKey[] = "quality"; @@ -85,6 +87,8 @@ const char kPerOriginOnlyInAutomaticError[] = "Can only set scope to " const char kWindowNotFoundError[] = "No window with id: *."; const char kTabIndexNotFoundError[] = "No tab at index: *."; const char kTabNotFoundError[] = "No tab with id: *."; +const char kCannotDiscardTab[] = "Cannot discard tab with id: *."; +const char kCannotFindTabToDiscard[] = "Cannot find a tab to discard."; const char kTabStripNotEditableError[] = "Tabs cannot be edited right now (user may be dragging a tab)."; const char kNoSelectedTabError[] = "No selected tab"; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h index 628f5ae8f26..f9b633b326a 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h @@ -36,6 +36,8 @@ extern const char kOldWindowIdKey[]; extern const char kOpenerTabIdKey[]; extern const char kPinnedKey[]; extern const char kAudibleKey[]; +extern const char kDiscardedKey[]; +extern const char kAutoDiscardableKey[]; extern const char kMutedKey[]; extern const char kMutedInfoKey[]; extern const char kQualityKey[]; @@ -85,6 +87,8 @@ extern const char kPerOriginOnlyInAutomaticError[]; extern const char kWindowNotFoundError[]; extern const char kTabIndexNotFoundError[]; extern const char kTabNotFoundError[]; +extern const char kCannotDiscardTab[]; +extern const char kCannotFindTabToDiscard[]; extern const char kTabStripNotEditableError[]; extern const char kNoHighlightedTabError[]; extern const char kNoSelectedTabError[]; 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 80c495c9673..9fe585be6b0 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc @@ -11,10 +11,12 @@ #include "base/memory/ptr_util.h" #include "base/values.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h" #include "chrome/browser/extensions/api/tabs/windows_event_router.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/memory/tab_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -135,11 +137,14 @@ void TabsEventRouter::TabEntry::WebContentsDestroyed() { TabsEventRouter::TabsEventRouter(Profile* profile) : profile_(profile), favicon_scoped_observer_(this), - browser_tab_strip_tracker_(this, this, this) { + browser_tab_strip_tracker_(this, this, this), + tab_manager_scoped_observer_(this) { DCHECK(!profile->IsOffTheRecord()); browser_tab_strip_tracker_.Init( BrowserTabStripTracker::InitWith::ALL_BROWERS); + + tab_manager_scoped_observer_.Add(g_browser_process->GetTabManager()); } TabsEventRouter::~TabsEventRouter() { @@ -158,7 +163,7 @@ void TabsEventRouter::RegisterForTabNotifications(WebContents* contents) { int tab_id = ExtensionTabUtil::GetTabId(contents); DCHECK(tab_entries_.find(tab_id) == tab_entries_.end()); - tab_entries_[tab_id] = base::WrapUnique(new TabEntry(this, contents)); + tab_entries_[tab_id] = base::MakeUnique<TabEntry>(this, contents); } void TabsEventRouter::UnregisterForTabNotifications(WebContents* contents) { @@ -187,14 +192,12 @@ static bool WillDispatchTabCreatedEvent( const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { - base::DictionaryValue* tab_value = - ExtensionTabUtil::CreateTabObject(contents, extension) - ->ToValue() - .release(); event->event_args->Clear(); - event->event_args->Append(tab_value); + std::unique_ptr<base::DictionaryValue> tab_value = + ExtensionTabUtil::CreateTabObject(contents, extension)->ToValue(); tab_value->SetBoolean(tabs_constants::kSelectedKey, active); tab_value->SetBoolean(tabs_constants::kActiveKey, active); + event->event_args->Append(std::move(tab_value)); return true; } @@ -214,7 +217,8 @@ void TabsEventRouter::TabCreatedAt(WebContents* contents, RegisterForTabNotifications(contents); } -void TabsEventRouter::TabInsertedAt(WebContents* contents, +void TabsEventRouter::TabInsertedAt(TabStripModel* tab_strip_model, + WebContents* contents, int index, bool active) { if (!GetTabEntry(contents)) { @@ -295,15 +299,15 @@ void TabsEventRouter::ActiveTabChanged(WebContents* old_contents, WebContents* new_contents, int index, int reason) { - std::unique_ptr<base::ListValue> args(new base::ListValue); + auto args = base::MakeUnique<base::ListValue>(); int tab_id = ExtensionTabUtil::GetTabId(new_contents); args->AppendInteger(tab_id); - base::DictionaryValue* object_args = new base::DictionaryValue(); + auto object_args = base::MakeUnique<base::DictionaryValue>(); object_args->Set(tabs_constants::kWindowIdKey, new FundamentalValue( ExtensionTabUtil::GetWindowIdOfTab(new_contents))); - args->Append(object_args); + args->Append(object_args->CreateDeepCopy()); // The onActivated event replaced onActiveChanged and onSelectionChanged. The // deprecated events take two arguments: tabId, {windowId}. @@ -314,18 +318,19 @@ void TabsEventRouter::ActiveTabChanged(WebContents* old_contents, ? EventRouter::USER_GESTURE_ENABLED : EventRouter::USER_GESTURE_NOT_ENABLED; DispatchEvent(profile, events::TABS_ON_SELECTION_CHANGED, - tabs::OnSelectionChanged::kEventName, - std::unique_ptr<base::ListValue>(args->DeepCopy()), gesture); + tabs::OnSelectionChanged::kEventName, args->CreateDeepCopy(), + gesture); DispatchEvent(profile, events::TABS_ON_ACTIVE_CHANGED, - tabs::OnActiveChanged::kEventName, - std::unique_ptr<base::ListValue>(args->DeepCopy()), gesture); + tabs::OnActiveChanged::kEventName, std::move(args), gesture); // The onActivated event takes one argument: {windowId, tabId}. - args->Remove(0, NULL); + auto on_activated_args = base::MakeUnique<base::ListValue>(); object_args->Set(tabs_constants::kTabIdKey, new FundamentalValue(tab_id)); + on_activated_args->Append(std::move(object_args)); DispatchEvent(profile, events::TABS_ON_ACTIVATED, - tabs::OnActivated::kEventName, std::move(args), gesture); + tabs::OnActivated::kEventName, std::move(on_activated_args), + gesture); } void TabsEventRouter::TabSelectionChanged( @@ -502,15 +507,12 @@ void TabsEventRouter::TabReplacedAt(TabStripModel* tab_strip_model, RegisterForTabNotifications(new_contents); } -void TabsEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { - TabStripModel* tab_strip = NULL; - int tab_index; - - if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { - std::set<std::string> changed_property_names; - changed_property_names.insert(tabs_constants::kPinnedKey); - DispatchTabUpdatedEvent(contents, std::move(changed_property_names)); - } +void TabsEventRouter::TabPinnedStateChanged(TabStripModel* tab_strip_model, + WebContents* contents, + int index) { + std::set<std::string> changed_property_names; + changed_property_names.insert(tabs_constants::kPinnedKey); + DispatchTabUpdatedEvent(contents, std::move(changed_property_names)); } void TabsEventRouter::OnZoomChanged( @@ -552,4 +554,18 @@ void TabsEventRouter::OnFaviconUpdated( } } +void TabsEventRouter::OnDiscardedStateChange(WebContents* contents, + bool is_discarded) { + std::set<std::string> changed_property_names; + changed_property_names.insert(tabs_constants::kDiscardedKey); + DispatchTabUpdatedEvent(contents, std::move(changed_property_names)); +} + +void TabsEventRouter::OnAutoDiscardableStateChange(WebContents* contents, + bool is_auto_discardable) { + std::set<std::string> changed_property_names; + changed_property_names.insert(tabs_constants::kAutoDiscardableKey); + DispatchTabUpdatedEvent(contents, std::move(changed_property_names)); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h index 5468d913ec7..340498bd40a 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h @@ -12,6 +12,8 @@ #include "base/macros.h" #include "base/scoped_observer.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" +#include "chrome/browser/memory/tab_manager.h" +#include "chrome/browser/memory/tab_manager_observer.h" #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/browser_tab_strip_tracker.h" #include "chrome/browser/ui/browser_tab_strip_tracker_delegate.h" @@ -39,7 +41,8 @@ class TabsEventRouter : public TabStripModelObserver, public BrowserTabStripTrackerDelegate, public chrome::BrowserListObserver, public favicon::FaviconDriverObserver, - public zoom::ZoomObserver { + public zoom::ZoomObserver, + public memory::TabManagerObserver { public: explicit TabsEventRouter(Profile* profile); ~TabsEventRouter() override; @@ -51,7 +54,8 @@ class TabsEventRouter : public TabStripModelObserver, void OnBrowserSetLastActive(Browser* browser) override; // TabStripModelObserver: - void TabInsertedAt(content::WebContents* contents, + void TabInsertedAt(TabStripModel* tab_strip_model, + content::WebContents* contents, int index, bool active) override; void TabClosingAt(TabStripModel* tab_strip_model, @@ -74,7 +78,8 @@ class TabsEventRouter : public TabStripModelObserver, content::WebContents* old_contents, content::WebContents* new_contents, int index) override; - void TabPinnedStateChanged(content::WebContents* contents, + void TabPinnedStateChanged(TabStripModel* tab_strip_model, + content::WebContents* contents, int index) override; // ZoomObserver: @@ -88,6 +93,12 @@ class TabsEventRouter : public TabStripModelObserver, bool icon_url_changed, const gfx::Image& image) override; + // memory::TabManagerObserver: + void OnDiscardedStateChange(content::WebContents* contents, + bool is_discarded) override; + void OnAutoDiscardableStateChange(content::WebContents* contents, + bool is_auto_discardable) override; + private: // "Synthetic" event. Called from TabInsertedAt if new tab is detected. void TabCreatedAt(content::WebContents* contents, int index, bool active); @@ -196,6 +207,9 @@ class TabsEventRouter : public TabStripModelObserver, BrowserTabStripTracker browser_tab_strip_tracker_; + ScopedObserver<memory::TabManager, TabsEventRouter> + tab_manager_scoped_observer_; + DISALLOW_COPY_AND_ASSIGN(TabsEventRouter); }; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc index e49fdfb9ff1..1ca713ac39a 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -17,6 +17,7 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/apps/app_browsertest_util.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/devtools/devtools_window_testing.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" @@ -24,6 +25,7 @@ #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/window_controller.h" +#include "chrome/browser/memory/tab_manager.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -35,9 +37,11 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" +#include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/page_zoom.h" #include "content/public/common/url_constants.h" +#include "content/public/test/browser_test_utils.h" #include "extensions/browser/api_test_utils.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" @@ -47,6 +51,7 @@ #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "ui/base/window_open_disposition.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" @@ -151,7 +156,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetWindow) { EXPECT_EQ(window_id, GetWindowId(result.get())); // "populate" was enabled so tabs should be populated. base::ListValue* tabs = nullptr; - EXPECT_TRUE(result.get()->GetList(keys::kTabsKey, &tabs)); + EXPECT_TRUE(result->GetList(keys::kTabsKey, &tabs)); base::Value* tab0 = nullptr; EXPECT_TRUE(tabs->Get(0, &tab0)); @@ -238,7 +243,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetCurrentWindow) { // to RunFunctionAndReturnSingleResult. EXPECT_EQ(new_id, GetWindowId(result.get())); base::ListValue* tabs = nullptr; - EXPECT_FALSE(result.get()->GetList(keys::kTabsKey, &tabs)); + EXPECT_FALSE(result->GetList(keys::kTabsKey, &tabs)); // Get the current window using the old window and make the tabs populated. function = new WindowsGetCurrentFunction(); @@ -252,7 +257,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetCurrentWindow) { // to RunFunctionAndReturnSingleResult. EXPECT_EQ(window_id, GetWindowId(result.get())); // "populate" was enabled so tabs should be populated. - EXPECT_TRUE(result.get()->GetList(keys::kTabsKey, &tabs)); + EXPECT_TRUE(result->GetList(keys::kTabsKey, &tabs)); // The tab id should not be -1 as this is a browser window. base::Value* tab0 = nullptr; @@ -1068,7 +1073,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowCreateTest, AcceptState) { int window_id = GetWindowId(result.get()); std::string error; Browser* new_window = ExtensionTabUtil::GetBrowserFromWindowID( - function.get(), window_id, &error); + ChromeExtensionFunctionDetails(function.get()), window_id, &error); EXPECT_TRUE(error.empty()); #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // DesktopWindowTreeHostX11::IsMinimized() relies on an asynchronous update @@ -1082,8 +1087,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowCreateTest, AcceptState) { function.get(), "[{\"state\": \"fullscreen\"}]", browser(), utils::INCLUDE_INCOGNITO))); window_id = GetWindowId(result.get()); - new_window = ExtensionTabUtil::GetBrowserFromWindowID(function.get(), - window_id, &error); + new_window = ExtensionTabUtil::GetBrowserFromWindowID( + ChromeExtensionFunctionDetails(function.get()), window_id, &error); EXPECT_TRUE(error.empty()); EXPECT_TRUE(new_window->window()->IsFullscreen()); @@ -1131,11 +1136,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowCreateTest, ValidateCreateWindowState) { } IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTab) { - content::OpenURLParams params(GURL(url::kAboutBlankURL), - content::Referrer(), - NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_LINK, - false); + content::OpenURLParams params(GURL(url::kAboutBlankURL), content::Referrer(), + WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui::PAGE_TRANSITION_LINK, false); content::WebContents* web_contents = browser()->OpenURL(params); int tab_id = ExtensionTabUtil::GetTabId(web_contents); int window_id = ExtensionTabUtil::GetWindowIdOfTab(web_contents); @@ -1175,11 +1178,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTab) { } IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTabNoPermission) { - content::OpenURLParams params(GURL(url::kAboutBlankURL), - content::Referrer(), - NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_LINK, - false); + content::OpenURLParams params(GURL(url::kAboutBlankURL), content::Referrer(), + WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui::PAGE_TRANSITION_LINK, false); content::WebContents* web_contents = browser()->OpenURL(params); int tab_id = ExtensionTabUtil::GetTabId(web_contents); int window_id = ExtensionTabUtil::GetWindowIdOfTab(web_contents); @@ -1312,6 +1313,381 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, ExecuteScriptOnDevTools) { DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); } +// TODO(georgesak): change this browsertest to an unittest. +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { + ASSERT_TRUE(g_browser_process && g_browser_process->GetTabManager()); + memory::TabManager* tab_manager = g_browser_process->GetTabManager(); + + // Create two aditional tabs. + content::OpenURLParams params(GURL(url::kAboutBlankURL), content::Referrer(), + WindowOpenDisposition::NEW_BACKGROUND_TAB, + ui::PAGE_TRANSITION_LINK, false); + content::WebContents* web_contents_a = browser()->OpenURL(params); + content::WebContents* web_contents_b = browser()->OpenURL(params); + + // Set up query function with an extension. + scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension(); + auto RunQueryFunction = [this, &extension](const char* query_info) { + scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction(); + function->set_extension(extension.get()); + return utils::ToList(utils::RunFunctionAndReturnSingleResult( + function.get(), query_info, browser())); + }; + + // Get non-discarded tabs. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": false}]")); + + // The two created plus the default tab. + EXPECT_EQ(3u, result->GetSize()); + } + + // Get discarded tabs. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": true}]")); + EXPECT_EQ(0u, result->GetSize()); + } + + TabStripModel* tab_strip_model = browser()->tab_strip_model(); + + // Creates Tab object to ensure the property is correct for the extension. + std::unique_ptr<api::tabs::Tab> tab_object_a = + ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + EXPECT_FALSE(tab_object_a->discarded); + + // Discards one tab. + EXPECT_TRUE(tab_manager->DiscardTabByExtension(web_contents_a)); + web_contents_a = tab_strip_model->GetWebContentsAt(1); + + // Make sure the property is changed accordingly after discarding the tab. + tab_object_a = + ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + EXPECT_TRUE(tab_object_a->discarded); + + // Get non-discarded tabs after discarding one tab. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": false}]")); + EXPECT_EQ(2u, result->GetSize()); + } + + // Get discarded tabs after discarding one tab. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": true}]")); + EXPECT_EQ(1u, result->GetSize()); + + // Make sure the returned tab is the correct one. + int tab_id_a = ExtensionTabUtil::GetTabId(web_contents_a); + + int id = -1; + base::Value* tab = nullptr; + EXPECT_TRUE(result->Get(0, &tab)); + utils::ToDictionary(tab)->GetInteger(keys::kIdKey, &id); + + EXPECT_EQ(tab_id_a, id); + } + + // Discards another created tab. + EXPECT_TRUE(tab_manager->DiscardTabByExtension(web_contents_b)); + + // Get non-discarded tabs after discarding two created tabs. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": false}]")); + EXPECT_EQ(1u, result->GetSize()); + + // Make sure the returned tab is the correct one. + int tab_id_c = + ExtensionTabUtil::GetTabId(tab_strip_model->GetWebContentsAt(0)); + + int id = -1; + base::Value* tab = nullptr; + EXPECT_TRUE(result->Get(0, &tab)); + utils::ToDictionary(tab)->GetInteger(keys::kIdKey, &id); + + EXPECT_EQ(tab_id_c, id); + } + + // Get discarded tabs after discarding two created tabs. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": true}]")); + EXPECT_EQ(2u, result->GetSize()); + } + + // Activates the first created tab. + tab_strip_model->ActivateTabAt(1, false); + + // Get non-discarded tabs after activating a discarded tab. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": false}]")); + EXPECT_EQ(2u, result->GetSize()); + } + + // Get discarded tabs after activating a discarded tab. + { + std::unique_ptr<base::ListValue> result( + RunQueryFunction("[{\"discarded\": true}]")); + EXPECT_EQ(1u, result->GetSize()); + } +} + +// Tests chrome.tabs.discard(tabId). +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithId) { + // Create an additional tab. + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(url::kAboutBlankURL), + WindowOpenDisposition::NEW_BACKGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetWebContentsAt(1); + + // Set up the function with an extension. + scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension(); + scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction()); + discard->set_extension(extension.get()); + + // Run function passing the tab id as argument. + int tab_id = ExtensionTabUtil::GetTabId(web_contents); + std::unique_ptr<base::DictionaryValue> result( + utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( + discard.get(), base::StringPrintf("[%u]", tab_id), browser()))); + + // Confirms that TabManager sees the tab as discarded. + memory::TabManager* tab_manager = g_browser_process->GetTabManager(); + web_contents = browser()->tab_strip_model()->GetWebContentsAt(1); + EXPECT_TRUE(tab_manager->IsTabDiscarded(web_contents)); + + // Make sure the returned tab is the one discarded and its discarded state is + // correct. + tab_id = ExtensionTabUtil::GetTabId(web_contents); + EXPECT_EQ(tab_id, api_test_utils::GetInteger(result.get(), "id")); + EXPECT_TRUE(api_test_utils::GetBoolean(result.get(), "discarded")); + + // Tests chrome.tabs.discard(tabId) with an already discarded tab. It has to + // return the error stating that the tab couldn't be discarded. + scoped_refptr<TabsDiscardFunction> discarded(new TabsDiscardFunction()); + discarded->set_extension(extension.get()); + std::string error = utils::RunFunctionAndReturnError( + discarded.get(), base::StringPrintf("[%u]", tab_id), browser()); + EXPECT_TRUE(base::MatchPattern(error, keys::kCannotDiscardTab)); +} + +// Tests chrome.tabs.discard(invalidId). +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithInvalidId) { + // Create an additional tab. + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(url::kAboutBlankURL), + WindowOpenDisposition::NEW_BACKGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + + // Set up the function with an extension. + scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension(); + scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction()); + discard->set_extension(extension.get()); + + // Run function passing an invalid id as argument. + int tab_invalid_id = ExtensionTabUtil::GetTabId( + browser()->tab_strip_model()->GetWebContentsAt(0)); + tab_invalid_id = std::max( + tab_invalid_id, ExtensionTabUtil::GetTabId( + browser()->tab_strip_model()->GetWebContentsAt(1))); + tab_invalid_id++; + + std::string error = utils::RunFunctionAndReturnError( + discard.get(), base::StringPrintf("[%u]", tab_invalid_id), browser()); + + // Discarded state should still be false as no tab was discarded. + EXPECT_FALSE(g_browser_process->GetTabManager()->IsTabDiscarded( + browser()->tab_strip_model()->GetWebContentsAt(1))); + + // Check error message. + EXPECT_TRUE(base::MatchPattern(error, keys::kTabNotFoundError)); +} + +// Tests chrome.tabs.discard(). +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithoutId) { + // Create an additional tab. + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(url::kAboutBlankURL), + WindowOpenDisposition::NEW_BACKGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetWebContentsAt(1); + + // Set up the function with an extension. + scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension(); + scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction()); + discard->set_extension(extension.get()); + + // Disable protection time to discard the tab without passing id. + memory::TabManager* tab_manager = g_browser_process->GetTabManager(); + tab_manager->set_minimum_protection_time_for_tests( + base::TimeDelta::FromSeconds(0)); + + // Run without passing an id. + std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( + utils::RunFunctionAndReturnSingleResult(discard.get(), "[]", browser()))); + + // Confirms that TabManager sees the tab as discarded. + web_contents = browser()->tab_strip_model()->GetWebContentsAt(1); + EXPECT_TRUE(tab_manager->IsTabDiscarded(web_contents)); + + // Make sure the returned tab is the one discarded and its discarded state is + // correct. + EXPECT_EQ(ExtensionTabUtil::GetTabId(web_contents), + api_test_utils::GetInteger(result.get(), "id")); + EXPECT_TRUE(api_test_utils::GetBoolean(result.get(), "discarded")); +} + +// Tests chrome.tabs.discard() without disabling protection time. +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardNoTabProtection) { + // Create an additional tab. + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(url::kAboutBlankURL), + WindowOpenDisposition::NEW_BACKGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + + // Make sure protection time isn't disabled. + g_browser_process->GetTabManager()->set_minimum_protection_time_for_tests( + base::TimeDelta::FromMinutes(10)); + + // Set up the function with an extension. + scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension(); + scoped_refptr<TabsDiscardFunction> discard(new TabsDiscardFunction()); + discard->set_extension(extension.get()); + + // Run without passing an id. In this case the tab couldn't be discarded + // because of protection time. + std::string error = + utils::RunFunctionAndReturnError(discard.get(), "[]", browser()); + + // Discarded state should be false for both tabs as no tab was discarded. + EXPECT_FALSE(g_browser_process->GetTabManager()->IsTabDiscarded( + browser()->tab_strip_model()->GetWebContentsAt(1))); + EXPECT_FALSE(g_browser_process->GetTabManager()->IsTabDiscarded( + browser()->tab_strip_model()->GetWebContentsAt(0))); + + // Check error message. + EXPECT_TRUE(base::MatchPattern(error, keys::kCannotFindTabToDiscard)); +} + +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { + // Create two aditional tabs. + content::OpenURLParams params(GURL(url::kAboutBlankURL), content::Referrer(), + WindowOpenDisposition::NEW_BACKGROUND_TAB, + ui::PAGE_TRANSITION_LINK, false); + content::WebContents* web_contents_a = browser()->OpenURL(params); + content::WebContents* web_contents_b = browser()->OpenURL(params); + + // Creates Tab object to ensure the property is correct for the extension. + TabStripModel* tab_strip_model = browser()->tab_strip_model(); + std::unique_ptr<api::tabs::Tab> tab_object_a = + ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + EXPECT_TRUE(tab_object_a->auto_discardable); + + // Set up query and update functions with the extension. + scoped_refptr<const Extension> extension = test_util::CreateEmptyExtension(); + auto RunQueryFunction = [this, &extension](const char* query_info) { + scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction(); + function->set_extension(extension.get()); + return utils::ToList(utils::RunFunctionAndReturnSingleResult( + function.get(), query_info, browser())); + }; + auto RunUpdateFunction = [this, &extension](std::string update_info) { + scoped_refptr<TabsUpdateFunction> function = new TabsUpdateFunction(); + function->set_extension(extension.get()); + return utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( + function.get(), update_info, browser())); + }; + + // Queries and results used. + const char* kAutoDiscardableQueryInfo = "[{\"autoDiscardable\": true}]"; + const char* kNonAutoDiscardableQueryInfo = "[{\"autoDiscardable\": false}]"; + std::unique_ptr<base::ListValue> query_result; + std::unique_ptr<base::DictionaryValue> update_result; + + // Get auto-discardable tabs. Returns all since tabs are auto-discardable + // by default. + query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); + EXPECT_EQ(3u, query_result->GetSize()); + + // Get non auto-discardable tabs. + query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); + EXPECT_EQ(0u, query_result->GetSize()); + + // Update the auto-discardable state of web contents A. + int tab_id_a = ExtensionTabUtil::GetTabId(web_contents_a); + update_result.reset(RunUpdateFunction( + base::StringPrintf("[%u, {\"autoDiscardable\": false}]", tab_id_a))); + EXPECT_EQ(tab_id_a, api_test_utils::GetInteger(update_result.get(), "id")); + EXPECT_FALSE( + api_test_utils::GetBoolean(update_result.get(), "autoDiscardable")); + + // Make sure the property is changed accordingly after updating the tab. + tab_object_a = + ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + EXPECT_FALSE(tab_object_a->auto_discardable); + + // Get auto-discardable tabs after changing the status of web contents A. + query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); + EXPECT_EQ(2u, query_result->GetSize()); + + // Get non auto-discardable tabs after changing the status of web contents A. + query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); + EXPECT_EQ(1u, query_result->GetSize()); + + // Make sure the returned tab is the correct one. + int id = -1; + base::Value* tab = nullptr; + EXPECT_TRUE(query_result->Get(0, &tab)); + utils::ToDictionary(tab)->GetInteger(keys::kIdKey, &id); + EXPECT_EQ(tab_id_a, id); + + // Update the auto-discardable state of web contents B. + int tab_id_b = ExtensionTabUtil::GetTabId(web_contents_b); + update_result.reset(RunUpdateFunction( + base::StringPrintf("[%u, {\"autoDiscardable\": false}]", tab_id_b))); + EXPECT_EQ(tab_id_b, api_test_utils::GetInteger(update_result.get(), "id")); + EXPECT_FALSE( + api_test_utils::GetBoolean(update_result.get(), "autoDiscardable")); + + // Get auto-discardable tabs after changing the status of both created tabs. + query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); + EXPECT_EQ(1u, query_result->GetSize()); + + // Make sure the returned tab is the correct one. + id = -1; + tab = nullptr; + EXPECT_TRUE(query_result->Get(0, &tab)); + utils::ToDictionary(tab)->GetInteger(keys::kIdKey, &id); + EXPECT_EQ(ExtensionTabUtil::GetTabId(tab_strip_model->GetWebContentsAt(0)), + id); + + // Get auto-discardable tabs after changing the status of both created tabs. + query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); + EXPECT_EQ(2u, query_result->GetSize()); + + // Resets the first tab back to auto-discardable. + update_result.reset(RunUpdateFunction( + base::StringPrintf("[%u, {\"autoDiscardable\": true}]", tab_id_a))); + EXPECT_EQ(tab_id_a, api_test_utils::GetInteger(update_result.get(), "id")); + EXPECT_TRUE( + api_test_utils::GetBoolean(update_result.get(), "autoDiscardable")); + + // Get auto-discardable tabs after resetting the status of web contents A. + query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); + EXPECT_EQ(2u, query_result->GetSize()); + + // Get non auto-discardable tabs after resetting the status of web contents A. + query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); + EXPECT_EQ(1u, query_result->GetSize()); +} + // Tester class for the tabs.zoom* api functions. class ExtensionTabsZoomTest : public ExtensionTabsTest { public: @@ -1494,9 +1870,7 @@ std::string ExtensionTabsZoomTest::RunSetZoomSettingsExpectError( content::WebContents* ExtensionTabsZoomTest::OpenUrlAndWaitForLoad( const GURL& url) { ui_test_utils::NavigateToURLWithDisposition( - browser(), - url, - NEW_FOREGROUND_TAB, + browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); return browser()->tab_strip_model()->GetActiveWebContents(); } @@ -1508,11 +1882,9 @@ double GetZoomLevel(const content::WebContents* web_contents) { } content::OpenURLParams GetOpenParams(const char* url) { - return content::OpenURLParams(GURL(url), - content::Referrer(), - NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_LINK, - false); + return content::OpenURLParams(GURL(url), content::Referrer(), + WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui::PAGE_TRANSITION_LINK, false); } } // namespace 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 82697203cc4..6a85fc10464 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc @@ -159,7 +159,7 @@ WindowsEventRouter::WindowsEventRouter(Profile* profile) } WindowsEventRouter::~WindowsEventRouter() { -#if !defined(OS_MACOSX) +#if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX) views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this); #endif } @@ -214,7 +214,7 @@ void WindowsEventRouter::OnWindowControllerRemoved( window_controller, std::move(args)); } -#if !defined(OS_MACOSX) +#if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX) void WindowsEventRouter::OnNativeFocusChanged(gfx::NativeView focused_now) { if (!focused_now) OnActiveWindowChanged(nullptr); @@ -252,9 +252,9 @@ void WindowsEventRouter::OnActiveWindowChanged( if (!HasEventListener(windows::OnFocusChanged::kEventName)) return; - std::unique_ptr<Event> event(new Event( + std::unique_ptr<Event> event = base::MakeUnique<Event>( events::WINDOWS_ON_FOCUS_CHANGED, windows::OnFocusChanged::kEventName, - base::WrapUnique(new base::ListValue()))); + base::MakeUnique<base::ListValue>()); event->will_dispatch_callback = base::Bind(&WillDispatchWindowFocusedEvent, window_controller); EventRouter::Get(profile_)->BroadcastEvent(std::move(event)); @@ -264,8 +264,8 @@ void WindowsEventRouter::DispatchEvent(events::HistogramValue histogram_value, const std::string& event_name, WindowController* window_controller, std::unique_ptr<base::ListValue> args) { - std::unique_ptr<Event> event( - new Event(histogram_value, event_name, std::move(args))); + std::unique_ptr<Event> event = + base::MakeUnique<Event>(histogram_value, event_name, std::move(args)); event->restrict_to_browser_context = window_controller->profile(); event->will_dispatch_callback = base::Bind(&WillDispatchWindowEvent, window_controller); @@ -278,7 +278,7 @@ bool WindowsEventRouter::HasEventListener(const std::string& event_name) { void WindowsEventRouter::AddAppWindow(extensions::AppWindow* app_window) { std::unique_ptr<AppWindowController> controller(new AppWindowController( - app_window, base::WrapUnique(new AppBaseWindow(app_window)), profile_)); + app_window, base::MakeUnique<AppBaseWindow>(app_window), profile_)); app_windows_[app_window->session_id().id()] = std::move(controller); } diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h index 7c7041db3bf..0f9d46ff565 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h @@ -18,8 +18,8 @@ #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/extension_event_histogram_value.h" -#if !defined(OS_MACOSX) -#include "ui/views/focus/widget_focus_manager.h" +#if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX) +#include "ui/views/focus/widget_focus_manager.h" // nogncheck #endif class Profile; @@ -40,7 +40,7 @@ class WindowControllerList; // same profile. class WindowsEventRouter : public AppWindowRegistry::Observer, public WindowControllerListObserver, -#if !defined(OS_MACOSX) +#if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX) public views::WidgetFocusChangeListener, #endif public content::NotificationObserver { @@ -61,7 +61,7 @@ class WindowsEventRouter : public AppWindowRegistry::Observer, void OnWindowControllerAdded(WindowController* window_controller) override; void OnWindowControllerRemoved(WindowController* window) override; -#if !defined(OS_MACOSX) +#if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX) void OnNativeFocusChanged(gfx::NativeView focused_now) override; #endif diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc index 1c4e6495916..e7179e62225 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc @@ -26,7 +26,9 @@ namespace windows_util { bool GetWindowFromWindowID(UIThreadExtensionFunction* function, int window_id, extensions::WindowController::TypeFilter filter, - extensions::WindowController** controller) { + extensions::WindowController** controller, + std::string* error) { + DCHECK(error); if (window_id == extension_misc::kCurrentWindowId) { extensions::WindowController* extension_window_controller = function->dispatcher()->GetExtensionWindowController(); @@ -39,7 +41,7 @@ bool GetWindowFromWindowID(UIThreadExtensionFunction* function, ->CurrentWindowForFunctionWithFilter(function, filter); } if (!(*controller)) { - function->SetError(extensions::tabs_constants::kNoCurrentWindowError); + *error = extensions::tabs_constants::kNoCurrentWindowError; return false; } } else { @@ -47,9 +49,9 @@ bool GetWindowFromWindowID(UIThreadExtensionFunction* function, extensions::WindowControllerList::GetInstance() ->FindWindowForFunctionByIdWithFilter(function, window_id, filter); if (!(*controller)) { - function->SetError(extensions::ErrorUtils::FormatErrorMessage( + *error = extensions::ErrorUtils::FormatErrorMessage( extensions::tabs_constants::kWindowNotFoundError, - base::IntToString(window_id))); + base::IntToString(window_id)); return false; } } diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.h b/chromium/chrome/browser/extensions/api/tabs/windows_util.h index 940d380ebe4..b8b20c6f361 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.h @@ -21,11 +21,12 @@ class WindowController; namespace windows_util { // Populates |controller| for given |window_id|. If the window is not found, -// returns false and sets UIThreadExtensionFunction error_. +// returns false and sets |error|. bool GetWindowFromWindowID(UIThreadExtensionFunction* function, int window_id, extensions::WindowController::TypeFilter filter, - extensions::WindowController** controller); + extensions::WindowController** controller, + std::string* error); // Returns true if |function| (and the profile and extension that it was // invoked from) can operate on the window wrapped by |window_controller|. 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 a60623839ed..3e7db7188c3 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc @@ -69,10 +69,10 @@ void NotifyProcessOutput(content::BrowserContext* browser_context, } std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(new base::FundamentalValue(tab_id)); - args->Append(new base::FundamentalValue(terminal_id)); - args->Append(new base::StringValue(output_type)); - args->Append(new base::StringValue(output)); + args->AppendInteger(tab_id); + args->AppendInteger(terminal_id); + args->AppendString(output_type); + args->AppendString(output); extensions::EventRouter* event_router = extensions::EventRouter::Get(browser_context); @@ -166,12 +166,10 @@ TerminalPrivateSendInputFunction::~TerminalPrivateSendInputFunction() {} void TerminalPrivateOpenTerminalProcessFunction::RespondOnUIThread( int terminal_id) { if (terminal_id < 0) { - SetError("Failed to open process."); - SendResponse(false); + Respond(Error("Failed to open process.")); return; } - SetResult(base::MakeUnique<base::FundamentalValue>(terminal_id)); - SendResponse(true); + Respond(OneArgument(base::MakeUnique<base::FundamentalValue>(terminal_id))); } ExtensionFunction::ResponseAction TerminalPrivateSendInputFunction::Run() { @@ -198,8 +196,7 @@ void TerminalPrivateSendInputFunction::SendInputOnFileThread( } void TerminalPrivateSendInputFunction::RespondOnUIThread(bool success) { - SetResult(base::MakeUnique<base::FundamentalValue>(success)); - SendResponse(true); + Respond(OneArgument(base::MakeUnique<base::FundamentalValue>(success))); } TerminalPrivateCloseTerminalProcessFunction:: @@ -233,8 +230,7 @@ void TerminalPrivateCloseTerminalProcessFunction::CloseOnFileThread( void TerminalPrivateCloseTerminalProcessFunction::RespondOnUIThread( bool success) { - SetResult(base::MakeUnique<base::FundamentalValue>(success)); - SendResponse(true); + Respond(OneArgument(base::MakeUnique<base::FundamentalValue>(success))); } TerminalPrivateOnTerminalResizeFunction:: @@ -267,8 +263,7 @@ void TerminalPrivateOnTerminalResizeFunction::OnResizeOnFileThread( } void TerminalPrivateOnTerminalResizeFunction::RespondOnUIThread(bool success) { - SetResult(base::MakeUnique<base::FundamentalValue>(success)); - SendResponse(true); + Respond(OneArgument(base::MakeUnique<base::FundamentalValue>(success))); } TerminalPrivateAckOutputFunction::~TerminalPrivateAckOutputFunction() {} diff --git a/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc b/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc index bf4c7771309..ce4c05663bb 100644 --- a/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc +++ b/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc @@ -39,7 +39,8 @@ class TopSitesExtensionTest : public InProcessBrowserTest { // before we get to the conditional below. Otherwise, we'll run a nested // message loop until the async callback. top_sites->GetMostVisitedURLs( - base::Bind(&TopSitesExtensionTest::OnTopSitesAvailable, this), false); + base::Bind(&TopSitesExtensionTest::OnTopSitesAvailable, + base::Unretained(this)), false); if (!top_sites_inited_) { waiting_ = true; 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 27a14808755..3d27973cfae 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc @@ -9,7 +9,7 @@ #include "ash/shell.h" #include "base/command_line.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/string16.h" #include "chrome/browser/chromeos/login/lock/screen_locker.h" @@ -155,7 +155,7 @@ bool ChromeVirtualKeyboardDelegate::SendKeyEvent(const std::string& type, char_value, key_code, key_name, - modifiers, + modifiers | ui::EF_IS_SYNTHESIZED, window->GetHost()); } 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 9e72ecab1c2..165da220b19 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 @@ -160,8 +160,7 @@ void WebNavigationEventRouter::Retargeting(const RetargetingDetails* details) { tab_observer->frame_navigation_state(); content::RenderFrameHost* frame_host = content::RenderFrameHost::FromID( - details->source_web_contents->GetRenderProcessHost()->GetID(), - details->source_render_frame_id); + details->source_render_process_id, details->source_render_frame_id); if (!frame_navigation_state.CanSendEvents(frame_host)) return; @@ -374,12 +373,12 @@ void WebNavigationTabObserver::DidOpenRequestedURL( // We only send the onCreatedNavigationTarget if we end up creating a new // window. - if (disposition != SINGLETON_TAB && - disposition != NEW_FOREGROUND_TAB && - disposition != NEW_BACKGROUND_TAB && - disposition != NEW_POPUP && - disposition != NEW_WINDOW && - disposition != OFF_THE_RECORD) + if (disposition != WindowOpenDisposition::SINGLETON_TAB && + disposition != WindowOpenDisposition::NEW_FOREGROUND_TAB && + disposition != WindowOpenDisposition::NEW_BACKGROUND_TAB && + disposition != WindowOpenDisposition::NEW_POPUP && + disposition != WindowOpenDisposition::NEW_WINDOW && + disposition != WindowOpenDisposition::OFF_THE_RECORD) return; helpers::DispatchOnCreatedNavigationTarget(web_contents(), 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 6654a0e00d6..c542d111c49 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 @@ -24,14 +24,15 @@ #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/loader/chrome_resource_dispatcher_host_delegate.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" -#include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" @@ -50,6 +51,8 @@ #include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" #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 "third_party/WebKit/public/web/WebContextMenuData.h" #include "third_party/WebKit/public/web/WebInputEvent.h" @@ -186,7 +189,7 @@ class DelayLoadStartAndExecuteJavascript script_(script), has_user_gesture_(false), script_was_executed_(false), - rvh_(NULL) { + rfh_(nullptr) { registrar_.Add(this, chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); @@ -206,35 +209,34 @@ class DelayLoadStartAndExecuteJavascript registrar_.RemoveAll(); } - void DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) override { - if (validated_url != delay_url_ || !rvh_) + void DidStartNavigation( + content::NavigationHandle* navigation_handle) override { + if (navigation_handle->GetURL() != delay_url_ || !rfh_) return; if (has_user_gesture_) { - rvh_->GetMainFrame()->ExecuteJavaScriptWithUserGestureForTests( + rfh_->ExecuteJavaScriptWithUserGestureForTests( base::UTF8ToUTF16(script_)); } else { - rvh_->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script_)); + rfh_->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script_)); } script_was_executed_ = true; } - void DidCommitProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& url, - ui::PageTransition transition_type) override { + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override { + if (!navigation_handle->HasCommitted() || navigation_handle->IsErrorPage()) + return; + if (script_was_executed_ && - base::EndsWith(url.spec(), until_url_suffix_, + base::EndsWith(navigation_handle->GetURL().spec(), until_url_suffix_, base::CompareCase::SENSITIVE)) { content::WebContentsObserver::Observe(NULL); test_navigation_listener_->ResumeAll(); } - rvh_ = render_frame_host->GetRenderViewHost(); + + if (navigation_handle->IsInMainFrame()) + rfh_ = navigation_handle->GetRenderFrameHost(); } void set_has_user_gesture(bool has_user_gesture) { @@ -251,7 +253,7 @@ class DelayLoadStartAndExecuteJavascript std::string script_; bool has_user_gesture_; bool script_was_executed_; - content::RenderViewHost* rvh_; + content::RenderFrameHost* rfh_; DISALLOW_COPY_AND_ASSIGN(DelayLoadStartAndExecuteJavascript); }; @@ -330,11 +332,28 @@ class TestResourceDispatcherHostDelegate DISALLOW_COPY_AND_ASSIGN(TestResourceDispatcherHostDelegate); }; +// Handles requests for URLs with paths of "/test*" sent to the test server, so +// tests request a URL that receives a non-error response. +std::unique_ptr<net::test_server::HttpResponse> HandleTestRequest( + const net::test_server::HttpRequest& request) { + if (!base::StartsWith(request.relative_url, "/test", + base::CompareCase::SENSITIVE)) { + return nullptr; + } + std::unique_ptr<net::test_server::BasicHttpResponse> response( + new net::test_server::BasicHttpResponse()); + response->set_content("This space intentionally left blank."); + return std::move(response); +} + } // namespace class WebNavigationApiTest : public ExtensionApiTest { public: - WebNavigationApiTest() {} + WebNavigationApiTest() { + embedded_test_server()->RegisterRequestHandler( + base::Bind(&HandleTestRequest)); + } ~WebNavigationApiTest() override {} void SetUpInProcessBrowserTestFixture() override { @@ -397,7 +416,7 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Download) { ASSERT_TRUE(download_directory.CreateUniqueTempDir()); DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(browser()->profile()); - download_prefs->SetDownloadPath(download_directory.path()); + download_prefs->SetDownloadPath(download_directory.GetPath()); DownloadTestObserverNotInProgress download_observer( content::BrowserContext::GetDownloadManager(profile()), 1); @@ -423,17 +442,16 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ServerRedirectSingleProcess) { content::WaitForLoadStop(tab); ResultCatcher catcher; - GURL url(base::StringPrintf( - "http://www.a.com:%u/" - "extensions/api_test/webnavigation/serverRedirectSingleProcess/a.html", - embedded_test_server()->port())); + GURL url( + base::StringPrintf("http://www.a.com:%u/extensions/api_test/" + "webnavigation/serverRedirectSingleProcess/a.html", + embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); url = GURL(base::StringPrintf( - "http://www.b.com:%u/server-redirect?http://www.b.com:%u/", - embedded_test_server()->port(), - embedded_test_server()->port())); + "http://www.b.com:%u/server-redirect?http://www.b.com:%u/test", + embedded_test_server()->port(), embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); @@ -487,6 +505,7 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, FilteredTest) { } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, UserAction) { + content::IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. @@ -501,7 +520,8 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, UserAction) { browser()->profile())->extension_service(); const extensions::Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); - GURL url = extension->GetResourceURL("a.html"); + GURL url = extension->GetResourceURL( + "a.html?" + base::IntToString(embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); @@ -512,7 +532,13 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, UserAction) { params.page_url = url; params.link_url = extension->GetResourceURL("b.html"); - TestRenderViewContextMenu menu(tab->GetMainFrame(), params); + // Get the child frame, which will be the one associated with the context + // menu. + std::vector<content::RenderFrameHost*> frames = tab->GetAllFrames(); + EXPECT_EQ(2UL, frames.size()); + EXPECT_TRUE(frames[1]->GetParent()); + + TestRenderViewContextMenu menu(frames[1], params); menu.Init(); menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB, 0); @@ -542,7 +568,7 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { // There's a link on a.html. Middle-click on it to open it in a new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; - mouse_event.button = blink::WebMouseEvent::ButtonMiddle; + mouse_event.button = blink::WebMouseEvent::Button::Middle; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; @@ -574,7 +600,7 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlank) { // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; - mouse_event.button = blink::WebMouseEvent::ButtonLeft; + mouse_event.button = blink::WebMouseEvent::Button::Left; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; @@ -604,7 +630,7 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlankIncognito) { // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; - mouse_event.button = blink::WebMouseEvent::ButtonLeft; + mouse_event.button = blink::WebMouseEvent::Button::Left; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; 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 1e75bb5b488..c007c13476e 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 @@ -11,16 +11,15 @@ #include <tuple> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "base/files/file_path.h" #include "base/json/json_reader.h" #include "base/json/json_string_value_serializer.h" -#include "base/location.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" -#include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" @@ -54,6 +53,7 @@ #include "net/base/upload_bytes_element_reader.h" #include "net/base/upload_file_element_reader.h" #include "net/dns/mock_host_resolver.h" +#include "net/log/net_log_with_source.h" #include "net/log/test_net_log.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_test_util.h" @@ -92,6 +92,7 @@ using helpers::StringToCharList; namespace extensions { namespace { + static void EventHandledOnIOThread( void* profile, const std::string& extension_id, @@ -356,10 +357,14 @@ TEST_F(ExtensionWebRequestTest, BlockingEventPrecedenceRedirect) { EXPECT_EQ(0U, ipc_sender_.GetNumTasks()); } - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension1_id, kEventName + "/1", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id2( &profile_, extension2_id, kEventName + "/2", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2, + false); } // Test that a request is canceled if this is requested by any extension @@ -420,10 +425,14 @@ TEST_F(ExtensionWebRequestTest, BlockingEventPrecedenceCancel) { EXPECT_EQ(1U, request->url_chain().size()); EXPECT_EQ(0U, ipc_sender_.GetNumTasks()); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension1_id, kEventName + "/1", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id2( &profile_, extension2_id, kEventName + "/2", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2, + false); } TEST_F(ExtensionWebRequestTest, SimulateChancelWhileBlocked) { @@ -464,16 +473,18 @@ TEST_F(ExtensionWebRequestTest, SimulateChancelWhileBlocked) { &profile_, extension_id, kEventName, kEventName + "/1", request->identifier(), response)); + base::RunLoop run_loop; + // Extension response for OnErrorOccurred: Terminate the message loop. ipc_sender_.PushTask( - base::Bind(&base::MessageLoop::PostTask, - base::Unretained(base::MessageLoop::current()), FROM_HERE, - base::MessageLoop::QuitWhenIdleClosure())); + base::Bind(base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), + base::ThreadTaskRunnerHandle::Get(), FROM_HERE, + run_loop.QuitWhenIdleClosure())); request->Start(); // request->Start() will have submitted OnBeforeRequest by the time we cancel. request->Cancel(); - base::RunLoop().Run(); + run_loop.Run(); EXPECT_TRUE(!request->is_pending()); EXPECT_EQ(net::URLRequestStatus::CANCELED, request->status().status()); @@ -482,10 +493,14 @@ TEST_F(ExtensionWebRequestTest, SimulateChancelWhileBlocked) { EXPECT_EQ(1U, request->url_chain().size()); EXPECT_EQ(0U, ipc_sender_.GetNumTasks()); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension_id, kEventName + "/1", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id2( &profile_, extension_id, kEventName2 + "/1", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2, + false); } namespace { @@ -520,15 +535,15 @@ void ExtensionWebRequestTest::FireURLRequestWithData( true /* overwrite */); } std::vector<std::unique_ptr<net::UploadElementReader>> element_readers; - element_readers.push_back(base::WrapUnique( - new net::UploadBytesElementReader(&(bytes_1[0]), bytes_1.size()))); - element_readers.push_back(base::WrapUnique(new net::UploadFileElementReader( + element_readers.push_back(base::MakeUnique<net::UploadBytesElementReader>( + &(bytes_1[0]), bytes_1.size())); + element_readers.push_back(base::MakeUnique<net::UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), base::FilePath(), 0, 0, - base::Time()))); - element_readers.push_back(base::WrapUnique( - new net::UploadBytesElementReader(&(bytes_2[0]), bytes_2.size()))); - request->set_upload(base::WrapUnique( - new net::ElementsUploadDataStream(std::move(element_readers), 0))); + base::Time())); + element_readers.push_back(base::MakeUnique<net::UploadBytesElementReader>( + &(bytes_2[0]), bytes_2.size())); + request->set_upload(base::MakeUnique<net::ElementsUploadDataStream>( + std::move(element_readers), 0)); ipc_sender_.PushTask(base::Bind(&base::DoNothing)); request->Start(); } @@ -642,8 +657,10 @@ TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) { // We inspect the result in the message list of |ipc_sender_| later. base::RunLoop().RunUntilIdle(); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension_id, kEventName + "/1", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); // Part 2. // Now subscribe to OnBeforeRequest *without* the requestBody requirement. @@ -656,8 +673,8 @@ TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) { FireURLRequestWithData(kMethodPost, kMultipart, form_1, form_2); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( - &profile_, extension_id, kEventName + "/1", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); // Subscribe to OnBeforeRequest with requestBody requirement. ExtensionWebRequestEventRouter::GetInstance()->AddEventListener( @@ -676,8 +693,8 @@ TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) { base::RunLoop().RunUntilIdle(); // Clean-up. - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( - &profile_, extension_id, kEventName + "/1", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); IPC::Message* message = NULL; TestIPCSender::SentMessages::const_iterator i = ipc_sender_.sent_begin(); @@ -753,14 +770,22 @@ TEST_F(ExtensionWebRequestTest, MinimalAccessRequestBodyData) { base::RunLoop().RunUntilIdle(); // Clean-up - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( - &profile_, extension_id1, kEventName + "/1", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( - &profile_, extension_id2, kEventName + "/2", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension_id1, kEventName + "/1", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id2( + &profile_, extension_id1, kEventName + "/2", 0, 0); + ExtensionWebRequestEventRouter::EventListener::ID id3( + &profile_, extension_id2, kEventName + "/1", 0, 0); + ExtensionWebRequestEventRouter::EventListener::ID id4( &profile_, extension_id2, kEventName + "/2", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id3, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id4, + false); TestIPCSender::SentMessages::const_iterator i = ipc_sender_.sent_begin(); @@ -815,8 +840,10 @@ TEST_F(ExtensionWebRequestTest, NoAccessRequestBodyData) { // We inspect the result in the message list of |ipc_sender_| later. base::RunLoop().RunUntilIdle(); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension_id, kEventName + "/1", 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); TestIPCSender::SentMessages::const_iterator i = ipc_sender_.sent_begin(); for (size_t test = 0; test < arraysize(kMethods); ++test, ++i) { @@ -833,6 +860,112 @@ TEST_F(ExtensionWebRequestTest, NoAccessRequestBodyData) { EXPECT_EQ(i, ipc_sender_.sent_end()); } +// Tests that |embedder_process_id| is not relevant for adding and removing +// listeners with |web_view_instance_id| = 0. +TEST_F(ExtensionWebRequestTest, AddAndRemoveListeners) { + std::string ext_id("abcdefghijklmnopabcdefghijklmnop"); + ExtensionWebRequestEventRouter::RequestFilter filter; + const std::string kEventName(web_request::OnBeforeRequest::kEventName); + const std::string kSubEventName = kEventName + "/1"; + base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_); + EXPECT_EQ( + 0u, + ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting( + &profile_, kEventName)); + + // Add two non-webview listeners. + ExtensionWebRequestEventRouter::GetInstance()->AddEventListener( + &profile_, ext_id, ext_id, events::FOR_TEST, kEventName, kSubEventName, + filter, 0, 1 /* embedder_process_id */, 0, + ipc_sender_factory.GetWeakPtr()); + ExtensionWebRequestEventRouter::GetInstance()->AddEventListener( + &profile_, ext_id, ext_id, events::FOR_TEST, kEventName, kSubEventName, + filter, 0, 2 /* embedder_process_id */, 0, + ipc_sender_factory.GetWeakPtr()); + EXPECT_EQ( + 2u, + ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting( + &profile_, kEventName)); + + // Now remove the events without passing an explicit process ID. + ExtensionWebRequestEventRouter::EventListener::ID id1(&profile_, ext_id, + kSubEventName, 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + EXPECT_EQ( + 1u, + ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting( + &profile_, kEventName)); + + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + EXPECT_EQ( + 0u, + ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting( + &profile_, kEventName)); +} + +// The set of blocked requests should not grow unbounded. +TEST_F(ExtensionWebRequestTest, BlockedRequestsAreRemoved) { + std::string extension_id("1"); + ExtensionWebRequestEventRouter::RequestFilter filter; + + // Subscribe to OnBeforeRequest. + const std::string kEventName(web_request::OnBeforeRequest::kEventName); + base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_); + ExtensionWebRequestEventRouter::GetInstance()->AddEventListener( + &profile_, extension_id, extension_id, events::FOR_TEST, kEventName, + kEventName + "/1", filter, ExtraInfoSpec::BLOCKING, 0, 0, + ipc_sender_factory.GetWeakPtr()); + ExtensionWebRequestEventRouter::EventListener::ID id(&profile_, extension_id, + kEventName + "/1", 0, 0); + ExtensionWebRequestEventRouter::EventListener* listener = + ExtensionWebRequestEventRouter::GetInstance()->FindEventListener(id); + ASSERT_NE(nullptr, listener); + EXPECT_EQ(0u, listener->blocked_requests.size()); + + // Send a request. It should block. Wait for the run loop to become idle. + GURL request_url("about:blank"); + std::unique_ptr<net::URLRequest> request( + context_->CreateRequest(request_url, net::DEFAULT_PRIORITY, &delegate_)); + // Extension response for OnErrorOccurred: Terminate the message loop. + { + base::RunLoop run_loop; + ipc_sender_.PushTask( + base::Bind(base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), + base::ThreadTaskRunnerHandle::Get(), FROM_HERE, + run_loop.QuitWhenIdleClosure())); + request->Start(); + run_loop.Run(); + } + + // Confirm that there is a blocked request. + EXPECT_EQ(1u, listener->blocked_requests.size()); + + // Send a response through. + ExtensionWebRequestEventRouter::EventResponse* response = + new ExtensionWebRequestEventRouter::EventResponse( + extension_id, base::Time::FromDoubleT(1)); + response->cancel = true; + ExtensionWebRequestEventRouter::GetInstance()->OnEventHandled( + &profile_, extension_id, kEventName, kEventName + "/1", + request->identifier(), response); + { + base::RunLoop run_loop; + run_loop.RunUntilIdle(); + } + + // Now there should be no blocked requests. + EXPECT_EQ(0u, listener->blocked_requests.size()); + + EXPECT_TRUE(!request->is_pending()); + EXPECT_EQ(net::URLRequestStatus::FAILED, request->status().status()); + EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, request->status().error()); + EXPECT_EQ(0U, ipc_sender_.GetNumTasks()); + + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id, false); +} + struct HeaderModificationTest_Header { const char* name; const char* value; @@ -1045,13 +1178,19 @@ TEST_P(ExtensionWebRequestHeaderModificationTest, TestModifications) { ++num_headers_observed; } EXPECT_EQ(1, num_headers_observed); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id1( &profile_, extension1_id, kEventName + "/1", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( + ExtensionWebRequestEventRouter::EventListener::ID id2( &profile_, extension2_id, kEventName + "/2", 0, 0); - ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( - &profile_, extension3_id, - std::string(keys::kOnSendHeadersEvent) + "/3", 0, 0); + ExtensionWebRequestEventRouter::EventListener::ID id3( + &profile_, extension3_id, std::string(keys::kOnSendHeadersEvent) + "/3", + 0, 0); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2, + false); + ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id3, + false); }; namespace { @@ -1409,7 +1548,7 @@ TEST(ExtensionWebRequestHelpersTest, TestCalculateOnAuthRequiredDelta) { TEST(ExtensionWebRequestHelpersTest, TestMergeCancelOfResponses) { EventResponseDeltas deltas; net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); bool canceled = false; // Single event that does not cancel. @@ -1435,7 +1574,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeCancelOfResponses) { TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) { EventResponseDeltas deltas; net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; GURL effective_new_url; @@ -1516,7 +1655,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) { TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) { EventResponseDeltas deltas; net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; GURL effective_new_url; @@ -1585,7 +1724,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) { TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses3) { EventResponseDeltas deltas; net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; GURL effective_new_url; @@ -1618,10 +1757,10 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses3) { TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) { net::HttpRequestHeaders base_headers; - base_headers.AddHeaderFromString("key1: value 1"); - base_headers.AddHeaderFromString("key2: value 2"); + base_headers.SetHeader("key1", "value 1"); + base_headers.SetHeader("key2", "value 2"); net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; std::string header_value; EventResponseDeltas deltas; @@ -1644,8 +1783,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) { linked_ptr<EventResponseDelta> d1( new EventResponseDelta("extid1", base::Time::FromInternalValue(2000))); d1->deleted_request_headers.push_back("key1"); - d1->modified_request_headers.AddHeaderFromString("key2: value 3"); - d1->modified_request_headers.AddHeaderFromString("key3: value 3"); + d1->modified_request_headers.SetHeader("key2", "value 3"); + d1->modified_request_headers.SetHeader("key3", "value 3"); deltas.push_back(d1); deltas.sort(&InDecreasingExtensionInstallationTimeOrder); warning_set.clear(); @@ -1666,8 +1805,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) { linked_ptr<EventResponseDelta> d2( new EventResponseDelta("extid2", base::Time::FromInternalValue(1500))); // This one conflicts: - d2->modified_request_headers.AddHeaderFromString("key3: value 0"); - d2->modified_request_headers.AddHeaderFromString("key4: value 4"); + d2->modified_request_headers.SetHeader("key3", "value 0"); + d2->modified_request_headers.SetHeader("key4", "value 4"); deltas.push_back(d2); deltas.sort(&InDecreasingExtensionInstallationTimeOrder); warning_set.clear(); @@ -1690,8 +1829,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) { linked_ptr<EventResponseDelta> d3( new EventResponseDelta("extid3", base::Time::FromInternalValue(1000))); d3->deleted_request_headers.push_back("key1"); - d3->modified_request_headers.AddHeaderFromString("key2: value 3"); - d3->modified_request_headers.AddHeaderFromString("key5: value 5"); + d3->modified_request_headers.SetHeader("key2", "value 3"); + d3->modified_request_headers.SetHeader("key5", "value 5"); deltas.push_back(d3); deltas.sort(&InDecreasingExtensionInstallationTimeOrder); warning_set.clear(); @@ -1717,7 +1856,7 @@ TEST(ExtensionWebRequestHelpersTest, base_headers.AddHeaderFromString( "Cookie: name=value; name2=value2; name3=\"value3\""); net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; std::string header_value; EventResponseDeltas deltas; @@ -1801,7 +1940,7 @@ std::string GetCookieExpirationDate(int delta_secs) { TEST(ExtensionWebRequestHelpersTest, TestMergeCookiesInOnHeadersReceivedResponses) { net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; std::string header_value; EventResponseDeltas deltas; @@ -2036,7 +2175,7 @@ TEST(ExtensionWebRequestHelpersTest, TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) { net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; std::string header_value; EventResponseDeltas deltas; @@ -2136,7 +2275,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) { TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponsesDeletion) { net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; std::string header_value; EventResponseDeltas deltas; @@ -2190,7 +2329,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponsesRedirect) { EventResponseDeltas deltas; net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; char base_headers_string[] = @@ -2243,7 +2382,7 @@ TEST(ExtensionWebRequestHelpersTest, TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) { net::BoundTestNetLog capturing_net_log; - net::BoundNetLog net_log = capturing_net_log.bound(); + net::NetLogWithSource net_log = capturing_net_log.bound(); WarningSet warning_set; EventResponseDeltas deltas; base::string16 username = base::ASCIIToUTF16("foo"); 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 905f8cff3dc..a0ea8893dbb 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 @@ -14,11 +14,13 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/login/login_handler.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/extensions/extension_process_policy.h" +#include "chrome/test/base/search_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" @@ -159,6 +161,20 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestTypes) { ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_types.html")) << message_; } +// Test that a request to an OpenSearch description document (OSDD) generates +// an event with the expected details. +IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestTestOSDD) { + // An OSDD request is only generated when a main frame at is loaded at /, so + // serve osdd/index.html from the root of the test server: + embedded_test_server()->ServeFilesFromDirectory( + test_data_dir_.AppendASCII("webrequest/osdd")); + ASSERT_TRUE(StartEmbeddedTestServer()); + + search_test_utils::WaitForTemplateURLServiceToLoad( + TemplateURLServiceFactory::GetForProfile(profile())); + ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_osdd.html")) << message_; +} + // Test that the webRequest events are dispatched with the expected details when // a frame or tab is removed while a response is being received. // Flaky: https://crbug.com/617865 @@ -237,7 +253,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestNewTab) { // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; - mouse_event.button = blink::WebMouseEvent::ButtonLeft; + mouse_event.button = blink::WebMouseEvent::Button::Left; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; @@ -254,14 +270,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestDeclarative1) { << message_; } -// This test times out on XP. See http://crbug.com/178296 -#if defined(OS_WIN) -#define MAYBE_WebRequestDeclarative2 DISABLED_WebRequestDeclarative2 -#else -#define MAYBE_WebRequestDeclarative2 WebRequestDeclarative2 -#endif -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, - MAYBE_WebRequestDeclarative2) { +IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestDeclarative2) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_declarative2.html")) << message_; @@ -533,7 +542,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, const std::string kHost = "example.com"; GURL url = embedded_test_server()->GetURL(kHost, "/empty.html"); chrome::NavigateParams params(browser(), url, ui::PAGE_TRANSITION_LINK); - params.disposition = NEW_FOREGROUND_TAB; + params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; ui_test_utils::NavigateToURL(¶ms); content::WebContents* web_contents = diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc index 8c55a9c01c6..efdf7178daa 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc @@ -73,7 +73,7 @@ const char* WebrtcAudioPrivateEventService::service_name() { void WebrtcAudioPrivateEventService::OnDevicesChanged( base::SystemMonitor::DeviceType device_type) { switch (device_type) { - case base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE: + case base::SystemMonitor::DEVTYPE_AUDIO: case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE: SignalEvent(); break; @@ -96,9 +96,9 @@ void WebrtcAudioPrivateEventService::SignalEvent() { const std::string& extension_id = extension->id(); if (router->ExtensionHasEventListener(extension_id, kEventName) && extension->permissions_data()->HasAPIPermission("webrtcAudioPrivate")) { - std::unique_ptr<Event> event( - new Event(events::WEBRTC_AUDIO_PRIVATE_ON_SINKS_CHANGED, kEventName, - base::WrapUnique(new base::ListValue()))); + std::unique_ptr<Event> event = base::MakeUnique<Event>( + events::WEBRTC_AUDIO_PRIVATE_ON_SINKS_CHANGED, kEventName, + base::MakeUnique<base::ListValue>()); router->DispatchEventToExtension(extension_id, std::move(event)); } } @@ -140,9 +140,9 @@ bool WebrtcAudioPrivateFunction::GetControllerList(const RequestInfo& request) { // If |guest_process_id| is defined, directly use this id to find the // corresponding RenderProcessHost. if (request.guest_process_id.get()) { - rph = content::RenderProcessHost::FromID(*request.guest_process_id.get()); + rph = content::RenderProcessHost::FromID(*request.guest_process_id); } else if (request.tab_id.get()) { - int tab_id = *request.tab_id.get(); + int tab_id = *request.tab_id; content::WebContents* contents = NULL; if (!ExtensionTabUtil::GetTabById(tab_id, GetProfile(), true, NULL, NULL, &contents, NULL)) { @@ -244,7 +244,7 @@ void WebrtcAudioPrivateGetSinksFunction::OnOutputDeviceNames( // object run strictly in sequence; first RunAsync on the UI thread, // then DoQuery on the audio IO thread, then DoneOnUIThread on the // UI thread. - results_.reset(wap::GetSinks::Results::Create(results).release()); + results_ = wap::GetSinks::Results::Create(results); BrowserThread::PostTask( BrowserThread::UI, @@ -300,7 +300,7 @@ void WebrtcAudioPrivateGetActiveSinkFunction::OnHMACCalculated( DVLOG(2) << "Received empty ID, replacing with default ID."; result = media::AudioDeviceDescription::kDefaultDeviceId; } - results_.reset(wap::GetActiveSink::Results::Create(result).release()); + results_ = wap::GetActiveSink::Results::Create(result); SendResponse(true); } @@ -323,9 +323,9 @@ bool WebrtcAudioPrivateSetActiveSinkFunction::RunAsync() { if (params->request.guest_process_id.get()) { request_info_.guest_process_id.reset( - new int(*params->request.guest_process_id.get())); + new int(*params->request.guest_process_id)); } else if (params->request.tab_id.get()) { - request_info_.tab_id.reset(new int(*params->request.tab_id.get())); + request_info_.tab_id.reset(new int(*params->request.tab_id)); } else { return false; } @@ -343,10 +343,10 @@ void WebrtcAudioPrivateSetActiveSinkFunction::OnControllerList( int requested_process_id; if (request_info_.guest_process_id.get()) { requested_process_type = "guestProcessId"; - requested_process_id = *request_info_.guest_process_id.get(); + requested_process_id = *request_info_.guest_process_id; } else { requested_process_type = "tabId"; - requested_process_id = *request_info_.tab_id.get(); + requested_process_id = *request_info_.tab_id; } controllers_ = controllers; @@ -494,10 +494,9 @@ void WebrtcAudioPrivateGetAssociatedSinkFunction::OnHMACCalculated( if (associated_sink_id == media::AudioDeviceDescription::kDefaultDeviceId) { DVLOG(2) << "Got default ID, replacing with empty ID."; - results_.reset(wap::GetAssociatedSink::Results::Create("").release()); + results_ = wap::GetAssociatedSink::Results::Create(""); } else { - results_.reset( - wap::GetAssociatedSink::Results::Create(associated_sink_id).release()); + results_ = wap::GetAssociatedSink::Results::Create(associated_sink_id); } SendResponse(true); diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc index 3f7f1b1b251..8c3c475fc65 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc @@ -23,7 +23,7 @@ #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/media/webrtc_log_uploader.h" +#include "chrome/browser/media/webrtc/webrtc_log_uploader.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" @@ -138,7 +138,8 @@ class WebrtcAudioPrivateTest : public AudioWaitingExtensionTest { if (!audio_manager->GetTaskRunner()->BelongsToCurrentThread()) { audio_manager->GetTaskRunner()->PostTask( FROM_HERE, - base::Bind(&WebrtcAudioPrivateTest::GetAudioDeviceNames, this, + base::Bind(&WebrtcAudioPrivateTest::GetAudioDeviceNames, + base::Unretained(this), EnumerationFunc, device_names)); enumeration_event_.Wait(); } else { @@ -159,8 +160,8 @@ class WebrtcAudioPrivateTest : public AudioWaitingExtensionTest { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&WebrtcAudioPrivateTest::GetIDInOrigin, - this, resource_context, origin, raw_device_id, - id_in_origin)); + base::Unretained(this), + resource_context, origin, raw_device_id, id_in_origin)); enumeration_event_.Wait(); } else { *id_in_origin = content::GetHMACForMediaDeviceID( @@ -376,12 +377,12 @@ IN_PROC_BROWSER_TEST_F(WebrtcAudioPrivateTest, MAYBE_TriggerEvent) { WebrtcAudioPrivateEventService::GetFactoryInstance()->Get(profile()); // Just trigger, without any extension listening. - service->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE); + service->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO); // Now load our test extension and do it again. const extensions::Extension* extension = LoadExtension( test_data_dir_.AppendASCII("webrtc_audio_private_event_listener")); - service->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE); + service->OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO); // Check that the extension got the notification. std::string result = ExecuteScriptInBackgroundPage(extension->id(), diff --git a/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc index 32306a74b04..7db1679db25 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc @@ -5,8 +5,8 @@ #include "base/command_line.h" #include "base/macros.h" #include "chrome/browser/extensions/extension_apitest.h" +#include "chrome/browser/permissions/permission_request_manager.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/website_settings/permission_bubble_manager.h" #include "chrome/test/base/ui_test_utils.h" #include "extensions/test/result_catcher.h" #include "media/base/media_switches.h" @@ -18,28 +18,29 @@ namespace extensions { namespace { // Used to observe the creation of permission prompt without responding. -class PermissionRequestObserver : public PermissionBubbleManager::Observer { +class PermissionRequestObserver : public PermissionRequestManager::Observer { public: explicit PermissionRequestObserver(content::WebContents* web_contents) - : bubble_manager_(PermissionBubbleManager::FromWebContents(web_contents)), + : request_manager_( + PermissionRequestManager::FromWebContents(web_contents)), request_shown_(false) { - bubble_manager_->AddObserver(this); + request_manager_->AddObserver(this); } ~PermissionRequestObserver() override { // Safe to remove twice if it happens. - bubble_manager_->RemoveObserver(this); + request_manager_->RemoveObserver(this); } bool request_shown() const { return request_shown_; } private: - // PermissionBubbleManager::Observer + // PermissionRequestManager::Observer void OnBubbleAdded() override { request_shown_ = true; - bubble_manager_->RemoveObserver(this); + request_manager_->RemoveObserver(this); } - PermissionBubbleManager* bubble_manager_; + PermissionRequestManager* request_manager_; bool request_shown_; DISALLOW_COPY_AND_ASSIGN(PermissionRequestObserver); @@ -91,10 +92,10 @@ IN_PROC_BROWSER_TEST_F(WebRtcFromWebAccessibleResourceTest, GURL url = GetTestServerInsecureUrl("/extensions/test_file.html?succeed"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - PermissionBubbleManager* bubble_manager = - PermissionBubbleManager::FromWebContents(web_contents); - bubble_manager->set_auto_response_for_test( - PermissionBubbleManager::ACCEPT_ALL); + PermissionRequestManager* request_manager = + PermissionRequestManager::FromWebContents(web_contents); + request_manager->set_auto_response_for_test( + PermissionRequestManager::ACCEPT_ALL); PermissionRequestObserver permission_request_observer(web_contents); extensions::ResultCatcher catcher; ui_test_utils::NavigateToURL(browser(), url); @@ -104,7 +105,7 @@ IN_PROC_BROWSER_TEST_F(WebRtcFromWebAccessibleResourceTest, } // Verify that a chrome-extension:// web accessible URL will fail to access -// getUserMedia() if it is denied by the permission bubble, even if it is +// getUserMedia() if it is denied by the permission request, even if it is // embedded in an insecure context. IN_PROC_BROWSER_TEST_F(WebRtcFromWebAccessibleResourceTest, GetUserMediaInWebAccessibleResourceFail) { @@ -115,9 +116,10 @@ IN_PROC_BROWSER_TEST_F(WebRtcFromWebAccessibleResourceTest, GURL url = GetTestServerInsecureUrl("/extensions/test_file.html?fail"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - PermissionBubbleManager* bubble_manager = - PermissionBubbleManager::FromWebContents(web_contents); - bubble_manager->set_auto_response_for_test(PermissionBubbleManager::DENY_ALL); + PermissionRequestManager* request_manager = + PermissionRequestManager::FromWebContents(web_contents); + request_manager->set_auto_response_for_test( + PermissionRequestManager::DENY_ALL); PermissionRequestObserver permission_request_observer(web_contents); extensions::ResultCatcher catcher; ui_test_utils::NavigateToURL(browser(), url); diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc index 7b5a2bbfda8..17266643b89 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc @@ -6,7 +6,10 @@ #include <utility> #include "base/command_line.h" +#include "base/files/file_path_watcher.h" #include "base/json/json_writer.h" +#include "base/memory/ref_counted.h" +#include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" @@ -14,8 +17,8 @@ #include "chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/media/webrtc_browsertest_base.h" -#include "chrome/browser/media/webrtc_browsertest_common.h" +#include "chrome/browser/media/webrtc/webrtc_browsertest_base.h" +#include "chrome/browser/media/webrtc/webrtc_browsertest_common.h" #include "chrome/common/chrome_switches.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" @@ -38,15 +41,14 @@ namespace utils = extension_function_test_utils; namespace { // Get the expected EventLog file name. The name will be -// <temporary path>.<render process id>.event_log.<consumer id>, for example +// <temporary path>.<render process id>.<peer connection id>, for example // /tmp/.org.chromium.Chromium.vsygNQ/dnFW8ch/Default/WebRTC -// Logs/WebRtcEventLog.1.29113.event_log.1 +// Logs/WebRtcEventLog.1.6.1 base::FilePath GetExpectedEventLogFileName(const base::FilePath& base_file, int render_process_id) { - static const int kExpectedConsumerId = 1; + static const int kExpectedPeerConnectionId = 1; return base_file.AddExtension(IntToStringType(render_process_id)) - .AddExtension(FILE_PATH_LITERAL("event_log")) - .AddExtension(IntToStringType(kExpectedConsumerId)); + .AddExtension(IntToStringType(kExpectedPeerConnectionId)); } static const char kMainWebrtcTestHtmlPage[] = "/webrtc/webrtc_jsep01_test.html"; @@ -57,6 +59,47 @@ std::string ParamsToString(const base::ListValue& parameters) { return parameter_string; } +class FileWaiter : public base::RefCountedThreadSafe<FileWaiter> { + public: + explicit FileWaiter(const base::FilePath& path) + : found_(false), path_(path) {} + + bool Start() { + if (base::PathExists(path_)) { + found_ = true; + return true; + } else { + return watcher_.Watch(path_, false /* recursive */, + base::Bind(&FileWaiter::Callback, this)); + } + } + + // Returns true if |path_| became available. + bool WaitForFile() { + if (!found_) { + run_loop_.Run(); + } + return found_; + } + + // implements FilePathWatcher::Callback + void Callback(const base::FilePath& path, bool error) { + EXPECT_EQ(path, path_); + if (!error) + found_ = true; + run_loop_.Quit(); + } + + private: + friend class base::RefCountedThreadSafe<FileWaiter>; + ~FileWaiter() {} + base::RunLoop run_loop_; + bool found_; + base::FilePath path_; + base::FilePathWatcher watcher_; + DISALLOW_COPY_AND_ASSIGN(FileWaiter); +}; + class WebrtcEventLogApiTest : public WebRtcTestBase { protected: void SetUp() override { @@ -118,7 +161,9 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, TestStartStopWebRtcEventLogging) { SetupPeerconnectionWithLocalStream(left_tab); SetupPeerconnectionWithLocalStream(right_tab); - NegotiateCall(left_tab, right_tab, "VP8"); + SetDefaultVideoCodec(left_tab, "VP8"); + SetDefaultVideoCodec(right_tab, "VP8"); + NegotiateCall(left_tab, right_tab); StartDetectingVideo(left_tab, "remote-view"); StartDetectingVideo(right_tab, "remote-view"); @@ -140,7 +185,7 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, TestStartStopWebRtcEventLogging) { std::unique_ptr<extensions::api::webrtc_logging_private::RecordingInfo> recordings_info_start( extensions::api::webrtc_logging_private::RecordingInfo::FromValue( - *start_result.get())); + *start_result)); ASSERT_TRUE(recordings_info_start.get()); base::FilePath file_name_start( base::FilePath::FromUTF8Unsafe(recordings_info_start->prefix_path)); @@ -165,7 +210,7 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, TestStartStopWebRtcEventLogging) { std::unique_ptr<extensions::api::webrtc_logging_private::RecordingInfo> recordings_info_stop( extensions::api::webrtc_logging_private::RecordingInfo::FromValue( - *stop_result.get())); + *stop_result)); ASSERT_TRUE(recordings_info_stop.get()); base::FilePath file_name_stop( base::FilePath::FromUTF8Unsafe(recordings_info_stop->prefix_path)); @@ -176,20 +221,18 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, TestStartStopWebRtcEventLogging) { EXPECT_EQ(file_name_start, file_name_stop); // Check that the file exists and is non-empty. - base::ProcessId render_process_id = - base::GetProcId(left_tab->GetRenderProcessHost()->GetHandle()); - EXPECT_NE(render_process_id, base::kNullProcessId); + content::RenderProcessHost* render_process_host = + left_tab->GetRenderProcessHost(); + ASSERT_NE(render_process_host, nullptr); + int render_process_id = render_process_host->GetID(); base::FilePath full_file_name = GetExpectedEventLogFileName(file_name_stop, render_process_id); int64_t file_size = 0; - while (!(base::PathExists(full_file_name) && - base::GetFileSize(full_file_name, &file_size) && file_size > 0)) { - // This should normally not happen, but is here to prevent the test - // from becoming flaky on devices with weird timings or when the - // /webrtc/webrtc_jsep01_test.html changes. - VLOG(1) << "Waiting for logfile to become available..."; - base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); - } + scoped_refptr<FileWaiter> waiter = new FileWaiter(full_file_name); + + ASSERT_TRUE(waiter->Start()) << "ERROR watching for " + << full_file_name.value(); + ASSERT_TRUE(waiter->WaitForFile()); ASSERT_TRUE(base::PathExists(full_file_name)); EXPECT_TRUE(base::GetFileSize(full_file_name, &file_size)); EXPECT_GT(file_size, 0); @@ -210,7 +253,9 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, SetupPeerconnectionWithLocalStream(left_tab); SetupPeerconnectionWithLocalStream(right_tab); - NegotiateCall(left_tab, right_tab, "VP8"); + SetDefaultVideoCodec(left_tab, "VP8"); + SetDefaultVideoCodec(right_tab, "VP8"); + NegotiateCall(left_tab, right_tab); StartDetectingVideo(left_tab, "remote-view"); StartDetectingVideo(right_tab, "remote-view"); @@ -233,7 +278,7 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, std::unique_ptr<extensions::api::webrtc_logging_private::RecordingInfo> recordings_info_start( extensions::api::webrtc_logging_private::RecordingInfo::FromValue( - *start_result.get())); + *start_result)); ASSERT_TRUE(recordings_info_start.get()); base::FilePath file_name_start( base::FilePath::FromUTF8Unsafe(recordings_info_start->prefix_path)); @@ -249,20 +294,19 @@ IN_PROC_BROWSER_TEST_F(WebrtcEventLogApiTest, // The log has stopped automatically. Check that the file exists and is // non-empty. - base::ProcessId render_process_id = - base::GetProcId(left_tab->GetRenderProcessHost()->GetHandle()); - EXPECT_NE(render_process_id, base::kNullProcessId); + content::RenderProcessHost* render_process_host = + left_tab->GetRenderProcessHost(); + ASSERT_NE(render_process_host, nullptr); + int render_process_id = render_process_host->GetID(); base::FilePath full_file_name = GetExpectedEventLogFileName(file_name_start, render_process_id); int64_t file_size = 0; - while (!(base::PathExists(full_file_name) && - base::GetFileSize(full_file_name, &file_size) && file_size > 0)) { - // This should normally not happen, but is here to prevent the test - // from becoming flaky on devices with weird timings or when the - // /webrtc/webrtc_jsep01_test.html changes. - VLOG(1) << "Waiting for logfile to become available..."; - base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); - } + + scoped_refptr<FileWaiter> waiter = new FileWaiter(full_file_name); + + ASSERT_TRUE(waiter->Start()) << "ERROR watching for " + << full_file_name.value(); + ASSERT_TRUE(waiter->WaitForFile()); ASSERT_TRUE(base::PathExists(full_file_name)); EXPECT_TRUE(base::GetFileSize(full_file_name, &file_size)); EXPECT_GT(file_size, 0); 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 3c939662cb2..49ea727195a 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 @@ -4,6 +4,8 @@ #include "chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h" +#include <memory> + #include "base/command_line.h" #include "base/hash.h" #include "base/logging.h" @@ -59,14 +61,14 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest( // If |guest_process_id| is defined, directly use this id to find the // corresponding RenderProcessHost. if (request.guest_process_id.get()) - return content::RenderProcessHost::FromID(*request.guest_process_id.get()); + return content::RenderProcessHost::FromID(*request.guest_process_id); // Otherwise, use the |tab_id|. If there's no |tab_id| and no // |guest_process_id|, we can't look up the RenderProcessHost. if (!request.tab_id.get()) return NULL; - int tab_id = *request.tab_id.get(); + int tab_id = *request.tab_id; content::WebContents* contents = NULL; if (!ExtensionTabUtil::GetTabById( tab_id, GetProfile(), true, NULL, NULL, &contents, NULL)) { @@ -168,7 +170,7 @@ bool WebrtcLoggingPrivateSetMetaDataFunction::RunAsync() { std::unique_ptr<MetaDataMap> meta_data(new MetaDataMap()); for (const MetaDataEntry& entry : params->meta_data) - (*meta_data.get())[entry.key] = entry.value; + (*meta_data)[entry.key] = entry.value; BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &WebRtcLoggingHandlerHost::SetMetaData, webrtc_logging_handler_host, @@ -207,6 +209,14 @@ bool WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::RunAsync() { webrtc_logging_handler_host->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. + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind( + &WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::SendResponse, + this, true)); return true; } diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h index 4598a6e2ca7..8fdf3509234 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 @@ -10,8 +10,8 @@ #include "chrome/browser/extensions/chrome_extension_function.h" #if defined(ENABLE_WEBRTC) #include "chrome/browser/media/audio_debug_recordings_handler.h" -#include "chrome/browser/media/webrtc_event_log_handler.h" -#include "chrome/browser/media/webrtc_logging_handler_host.h" +#include "chrome/browser/media/webrtc/webrtc_event_log_handler.h" +#include "chrome/browser/media/webrtc/webrtc_logging_handler_host.h" #endif #include "chrome/common/extensions/api/webrtc_logging_private.h" diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc index 8c80134a088..d6b28a91bdf 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc @@ -15,7 +15,7 @@ #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/media/webrtc_log_uploader.h" +#include "chrome/browser/media/webrtc/webrtc_log_uploader.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/notification_service.h" @@ -100,11 +100,11 @@ class WebrtcLoggingPrivateApiTest : public ExtensionApiTest { function, ParamsToString(parameters), browser())); if (expect_results) { EXPECT_TRUE(result.get()); - return result.get() != nullptr; + return result != nullptr; } EXPECT_FALSE(result.get()); - return result.get() == nullptr; + return result == nullptr; } template<typename Function> @@ -301,8 +301,8 @@ IN_PROC_BROWSER_TEST_F(WebrtcLoggingPrivateApiTest, TestStartStopUpload) { EXPECT_NE(std::string::npos, log_part.find("Cpu brand:")); // Check the multipart contents. - std::vector<std::string> multipart_lines; - base::SplitStringUsingSubstr(multipart, "\r\n", &multipart_lines); + std::vector<std::string> multipart_lines = base::SplitStringUsingSubstr( + multipart, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(31, static_cast<int>(multipart_lines.size())); EXPECT_STREQ(&boundary[0], multipart_lines[0].c_str()); 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 6e66b28ddd3..e037c2ed376 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 @@ -10,8 +10,7 @@ #include "base/bind.h" #include "base/lazy_instance.h" #include "base/macros.h" -#include "base/memory/scoped_vector.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -21,6 +20,7 @@ #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_install_ui_util.h" #include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/install_tracker.h" #include "chrome/browser/gpu/gpu_feature_checker.h" #include "chrome/browser/profiles/profile.h" @@ -52,6 +52,8 @@ namespace GetEphemeralAppsEnabled = namespace GetIsLauncherEnabled = api::webstore_private::GetIsLauncherEnabled; namespace GetStoreLogin = api::webstore_private::GetStoreLogin; namespace GetWebGLStatus = api::webstore_private::GetWebGLStatus; +namespace IsPendingCustodianApproval = + api::webstore_private::IsPendingCustodianApproval; namespace IsInIncognitoMode = api::webstore_private::IsInIncognitoMode; namespace LaunchEphemeralApp = api::webstore_private::LaunchEphemeralApp; namespace SetStoreLogin = api::webstore_private::SetStoreLogin; @@ -70,7 +72,8 @@ class PendingApprovals { const std::string& id); private: - typedef ScopedVector<WebstoreInstaller::Approval> ApprovalList; + using ApprovalList = + std::vector<std::unique_ptr<WebstoreInstaller::Approval>>; ApprovalList approvals_; @@ -82,18 +85,19 @@ PendingApprovals::~PendingApprovals() {} void PendingApprovals::PushApproval( std::unique_ptr<WebstoreInstaller::Approval> approval) { - approvals_.push_back(approval.release()); + approvals_.push_back(std::move(approval)); } std::unique_ptr<WebstoreInstaller::Approval> PendingApprovals::PopApproval( Profile* profile, const std::string& id) { - for (size_t i = 0; i < approvals_.size(); ++i) { - WebstoreInstaller::Approval* approval = approvals_[i]; - if (approval->extension_id == id && - profile->IsSameProfile(approval->profile)) { - approvals_.weak_erase(approvals_.begin() + i); - return std::unique_ptr<WebstoreInstaller::Approval>(approval); + for (ApprovalList::iterator iter = approvals_.begin(); + iter != approvals_.end(); ++iter) { + if (iter->get()->extension_id == id && + profile->IsSameProfile(iter->get()->profile)) { + std::unique_ptr<WebstoreInstaller::Approval> approval = std::move(*iter); + approvals_.erase(iter); + return approval; } } return std::unique_ptr<WebstoreInstaller::Approval>(); @@ -586,4 +590,49 @@ WebstorePrivateGetEphemeralAppsEnabledFunction::Run() { false))); } +WebstorePrivateIsPendingCustodianApprovalFunction:: + WebstorePrivateIsPendingCustodianApprovalFunction() + : chrome_details_(this) {} + +WebstorePrivateIsPendingCustodianApprovalFunction:: + ~WebstorePrivateIsPendingCustodianApprovalFunction() {} + +ExtensionFunction::ResponseAction +WebstorePrivateIsPendingCustodianApprovalFunction::Run() { + std::unique_ptr<IsPendingCustodianApproval::Params> params( + IsPendingCustodianApproval::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + + Profile* profile = chrome_details_.GetProfile(); + + if (!profile->IsSupervised()) { + return RespondNow(BuildResponse(false)); + } + + ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); + + const Extension* extension = + registry->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); + if (!extension) { + return RespondNow(BuildResponse(false)); + } + + ExtensionPrefs* extensions_prefs = ExtensionPrefs::Get(browser_context()); + + if (extensions_prefs->HasDisableReason( + params->id, Extension::DISABLE_PERMISSIONS_INCREASE)) { + return RespondNow(BuildResponse(true)); + } + + bool is_pending_approval = extensions_prefs->HasDisableReason( + params->id, Extension::DISABLE_CUSTODIAN_APPROVAL_REQUIRED); + + return RespondNow(BuildResponse(is_pending_approval)); +} + +ExtensionFunction::ResponseValue +WebstorePrivateIsPendingCustodianApprovalFunction::BuildResponse(bool result) { + return OneArgument(base::MakeUnique<base::FundamentalValue>(result)); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h index 4e2c4b2dd70..6a7f2ef009e 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 @@ -288,6 +288,25 @@ class WebstorePrivateGetEphemeralAppsEnabledFunction ExtensionFunction::ResponseAction Run() override; }; +class WebstorePrivateIsPendingCustodianApprovalFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("webstorePrivate.isPendingCustodianApproval", + WEBSTOREPRIVATE_ISPENDINGCUSTODIANAPPROVAL) + + WebstorePrivateIsPendingCustodianApprovalFunction(); + + private: + ~WebstorePrivateIsPendingCustodianApprovalFunction() override; + + // ExtensionFunction: + ExtensionFunction::ResponseAction Run() override; + + ExtensionFunction::ResponseValue BuildResponse(bool result); + + ChromeExtensionFunctionDetails chrome_details_; +}; + } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_WEBSTORE_PRIVATE_WEBSTORE_PRIVATE_API_H_ 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 14a7f8218c8..44c766682bd 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 @@ -123,7 +123,7 @@ class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { new ScopedTestDialogAutoConfirm(ScopedTestDialogAutoConfirm::ACCEPT)); ASSERT_TRUE(webstore_install_dir_.CreateUniqueTempDir()); - webstore_install_dir_copy_ = webstore_install_dir_.path(); + webstore_install_dir_copy_ = webstore_install_dir_.GetPath(); WebstoreInstaller::SetDownloadDirectoryForTests( &webstore_install_dir_copy_); } diff --git a/chromium/chrome/browser/extensions/api/webstore_widget_private/webstore_widget_private_api.cc b/chromium/chrome/browser/extensions/api/webstore_widget_private/webstore_widget_private_api.cc index 00e0a6f2290..50ea3fc8820 100644 --- a/chromium/chrome/browser/extensions/api/webstore_widget_private/webstore_widget_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webstore_widget_private/webstore_widget_private_api.cc @@ -105,10 +105,7 @@ void WebstoreWidgetPrivateInstallWebstoreItemFunction::OnInstallComplete( bool success, const std::string& error, extensions::webstore_install::Result result) { - if (!success) - SetError(error); - - SendResponse(success); + Respond(success ? NoArguments() : Error(error)); } } // namespace api |